content_type stringclasses 8
values | main_lang stringclasses 7
values | message stringlengths 1 50 | sha stringlengths 40 40 | patch stringlengths 52 962k | file_count int64 1 300 |
|---|---|---|---|---|---|
PHP | PHP | fix input type inference when type=>checkbox | 30e139412de537160f34a51e4482482abd908e4a | <ide><path>lib/Cake/Test/Case/View/Helper/FormHelperTest.php
<ide> public function testInputOverridingMagicSelectType() {
<ide> $this->assertTags($result, $expected);
<ide> }
<ide>
<add>/**
<add> * Test that inferred types do not override developer input
<add> *
<add> * @return void
<add> */
<add> public function testInputMagicTypeDoesNotOverride() {
<add> $this->View->viewVars['users'] = array('value' => 'good', 'other' => 'bad');
<add> $result = $this->Form->input('Model.user', array('type' => 'checkbox'));
<add> $expected = array(
<add> 'div' => array('class' => 'input checkbox'),
<add> array('input' => array(
<add> 'type' => 'hidden',
<add> 'name' => 'data[Model][user]',
<add> 'id' => 'ModelUser_',
<add> 'value' => 0,
<add> )),
<add> array('input' => array(
<add> 'name' => 'data[Model][user]',
<add> 'type' => 'checkbox',
<add> 'id' => 'ModelUser',
<add> 'value' => 1
<add> )),
<add> 'label' => array('for' => 'ModelUser'), 'User', '/label',
<add> '/div'
<add> );
<add> $this->assertTags($result, $expected);
<add> }
<add>
<ide> /**
<ide> * Test that magic input() selects are created for type=number
<ide> *
<ide><path>lib/Cake/View/Helper/FormHelper.php
<ide> protected function _parseOptions($options) {
<ide> $options = $this->_magicOptions($options);
<ide> }
<ide>
<del> if (in_array($options['type'], array('checkbox', 'radio', 'select'))) {
<add> if (in_array($options['type'], array('radio', 'select'))) {
<ide> $options = $this->_optionsOptions($options);
<ide> }
<ide> | 2 |
Javascript | Javascript | move next-tick to misc/next-tick-breadth | 7e5cd08061dc17f38dec307ae8fc43e44b85a777 | <ide><path>benchmark/misc/next-tick-breadth.js
<add>
<add>var common = require('../common.js');
<add>var bench = common.createBenchmark(main, {
<add> millions: [2]
<add>});
<add>
<add>function main(conf) {
<add> var N = +conf.millions * 1e6;
<add> var n = 0;
<add>
<add> function cb() {
<add> n++;
<add> if (n === N)
<add> bench.end(n / 1e6);
<add> }
<add>
<add> bench.start();
<add> for (var i = 0; i < N; i++) {
<add> process.nextTick(cb);
<add> }
<add>}
<ide><path>benchmark/next-tick.js
<del>// run with `time node benchmark/next-tick.js`
<del>var assert = require('assert');
<del>
<del>var N = 1e7;
<del>var n = 0;
<del>
<del>process.on('exit', function() {
<del> assert.equal(n, N);
<del>});
<del>
<del>function cb() {
<del> n++;
<del>}
<del>
<del>for (var i = 0; i < N; ++i) {
<del> process.nextTick(cb);
<del>} | 2 |
Text | Text | suggest eager load in ci in the testing guide | e74012c7baf1e1efc4b48b5dc86989a9fe96c82b | <ide><path>guides/source/testing.md
<ide> class ChatRelayJobTest < ActiveJob::TestCase
<ide> end
<ide> ```
<ide>
<add>Testing Eager Loading
<add>---------------------
<add>
<add>Normally, applications do not eager load in the `development` or `test` environments to speed things up. But they do in the `production` environment.
<add>
<add>If some file in the project cannot be loaded for whatever reason, you better detect it before deploying to production, right?
<add>
<add>### Continuous Integration
<add>
<add>If your project has CI in place, eager loading in CI is an easy way to ensure the application eager loads.
<add>
<add>CIs typically set some environment variable to indicate the test suite is running there. For example, it could be `CI`:
<add>
<add>```ruby
<add># config/environments/test.rb
<add>config.eager_load = ENV["CI"].present?
<add>```
<add>
<add>Starting with Rails 7, newly generated applications are configured that way by default.
<add>
<add>### Bare Test Suites
<add>
<add>If your project does not have continuous integration, you can still eager load in the test suite by calling `Rails.application.eager_load!`:
<add>
<add>#### minitest
<add>
<add>```ruby
<add>require "test_helper"
<add>
<add>class ZeitwerkComplianceTest < ActiveSupport::TestCase
<add> test "eager loads all files without errors" do
<add> assert_nothing_raised { Rails.application.eager_load! }
<add> end
<add>end
<add>```
<add>
<add>#### RSpec
<add>
<add>```ruby
<add>require "rails_helper"
<add>
<add>RSpec.describe "Zeitwerk compliance" do
<add> it "eager loads all files without errors" do
<add> expect { Rails.application.eager_load! }.not_to raise_error
<add> end
<add>end
<add>```
<add>
<ide> Additional Testing Resources
<ide> ----------------------------
<ide> | 1 |
Ruby | Ruby | use ruby instead of mocha | a0ea528b612f9d8cdd14a5b76fdcf6719b7db56a | <ide><path>actioncable/test/channel/stream_test.rb
<ide> class StreamTest < ActionCable::TestCase
<ide> test "stream_for" do
<ide> run_in_eventmachine do
<ide> connection = TestConnection.new
<del> connection.pubsub.expects(:subscribe).with("action_cable:stream_tests:chat:Room#1-Campfire", kind_of(Proc), kind_of(Proc))
<ide>
<ide> channel = ChatChannel.new connection, ""
<ide> channel.subscribe_to_channel
<ide> channel.stream_for Room.new(1)
<add> wait_for_async
<add>
<add> pubsub_call = channel.pubsub.class.class_variable_get "@@subscribe_called"
<add>
<add> assert_equal "action_cable:stream_tests:chat:Room#1-Campfire", pubsub_call[:channel]
<add> assert_instance_of Proc, pubsub_call[:callback]
<add> assert_instance_of Proc, pubsub_call[:success_callback]
<ide> end
<ide> end
<ide>
<ide><path>actioncable/test/connection/identifier_test.rb
<ide> def connect
<ide> run_in_eventmachine do
<ide> server = TestServer.new
<ide>
<del> server.pubsub.expects(:subscribe)
<del> .with("action_cable/User#lifo", kind_of(Proc))
<del> server.pubsub.expects(:unsubscribe)
<del> .with("action_cable/User#lifo", kind_of(Proc))
<del>
<ide> open_connection(server)
<ide> close_connection
<add> wait_for_async
<add>
<add> %w[subscribe unsubscribe].each do |method|
<add> pubsub_call = server.pubsub.class.class_variable_get "@@#{method}_called"
<add>
<add> assert_equal "action_cable/User#lifo", pubsub_call[:channel]
<add> assert_instance_of Proc, pubsub_call[:callback]
<add> end
<ide> end
<ide> end
<ide>
<ide><path>actioncable/test/stubs/test_adapter.rb
<ide> # frozen_string_literal: true
<ide>
<ide> class SuccessAdapter < ActionCable::SubscriptionAdapter::Base
<add> class << self; attr_accessor :subscribe_called, :unsubscribe_called end
<add>
<ide> def broadcast(channel, payload)
<ide> end
<ide>
<ide> def subscribe(channel, callback, success_callback = nil)
<add> @@subscribe_called = { channel: channel, callback: callback, success_callback: success_callback }
<ide> end
<ide>
<ide> def unsubscribe(channel, callback)
<add> @@unsubscribe_called = { channel: channel, callback: callback }
<ide> end
<ide> end | 3 |
Mixed | Javascript | update viewconfig for scrollview | f6b8736b090185da936eb979621fac5d2a03e525 | <ide><path>Libraries/Components/ScrollView/ScrollViewViewConfig.js
<ide>
<ide> 'use strict';
<ide>
<del>import type {PartialViewConfig} from 'react-native/Libraries/Renderer/shims/ReactNativeTypes';
<add>import type {PartialViewConfig} from '../../Renderer/shims/ReactNativeTypes';
<ide>
<ide> const ScrollViewViewConfig = {
<ide> uiViewClassName: 'RCTScrollView',
<ide> const ScrollViewViewConfig = {
<ide> bouncesZoom: true,
<ide> canCancelContentTouches: true,
<ide> centerContent: true,
<del> contentInset: {diff: require('../../Utilities/differ/pointsDiffer')},
<del> contentOffset: {diff: require('../../Utilities/differ/pointsDiffer')},
<add> contentInset: {
<add> diff: require('../../Utilities/differ/pointsDiffer'),
<add> },
<add> contentOffset: {
<add> diff: require('../../Utilities/differ/pointsDiffer'),
<add> },
<ide> contentInsetAdjustmentBehavior: true,
<ide> decelerationRate: true,
<ide> directionalLockEnabled: true,
<ide> disableIntervalMomentum: true,
<del> endFillColor: {process: require('../../StyleSheet/processColor')},
<add> endFillColor: {
<add> process: require('../../StyleSheet/processColor'),
<add> },
<ide> fadingEdgeLength: true,
<ide> indicatorStyle: true,
<add> inverted: true,
<ide> keyboardDismissMode: true,
<ide> maintainVisibleContentPosition: true,
<ide> maximumZoomScale: true,
<ide><path>Libraries/ReactNative/getNativeComponentAttributes.js
<ide> function getDifferForType(
<ide> case 'UIEdgeInsets':
<ide> return insetsDiffer;
<ide> // Android Types
<del> // (not yet implemented)
<add> case 'Point':
<add> return pointsDiffer;
<ide> }
<ide> return null;
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollViewManager.java
<ide> public void setFadingEdgeLength(ReactScrollView view, int value) {
<ide> }
<ide> }
<ide>
<del> @ReactProp(name = "contentOffset")
<add> @ReactProp(name = "contentOffset", customType = "Point")
<ide> public void setContentOffset(ReactScrollView view, ReadableMap value) {
<ide> if (value != null) {
<ide> double x = value.hasKey("x") ? value.getDouble("x") : 0; | 3 |
Javascript | Javascript | make notifications.clear public and emit event | c629a1aac48252b319ce50348939312b098b066e | <ide><path>src/notification-manager.js
<ide> class NotificationManager {
<ide> /*
<ide> Section: Managing Notifications
<ide> */
<del>
<add>
<add> // Public: Clear all the notifications.
<ide> clear () {
<ide> this.notifications = []
<add> this.emitter.emit('did-clear-notifications')
<ide> }
<ide> } | 1 |
Go | Go | fix incorrect permissions (staticcheck) | fdc1b22030f2a04931fb0005f34020109b0562b8 | <ide><path>integration-cli/docker_api_containers_test.go
<ide> func (s *DockerSuite) TestContainerAPICreateMountsBindRead(c *testing.T) {
<ide> tmpDir, err := ioutil.TempDir("", "test-mounts-api-bind")
<ide> assert.NilError(c, err)
<ide> defer os.RemoveAll(tmpDir)
<del> err = ioutil.WriteFile(filepath.Join(tmpDir, "bar"), []byte("hello"), 666)
<add> err = ioutil.WriteFile(filepath.Join(tmpDir, "bar"), []byte("hello"), 0666)
<ide> assert.NilError(c, err)
<ide> config := containertypes.Config{
<ide> Image: "busybox",
<ide><path>integration-cli/fixtures_linux_daemon_test.go
<ide> func ensureSyscallTest(c *testing.T) {
<ide> FROM debian:jessie
<ide> COPY . /usr/bin/
<ide> `)
<del> err = ioutil.WriteFile(dockerFile, content, 600)
<add> err = ioutil.WriteFile(dockerFile, content, 0600)
<ide> assert.NilError(c, err)
<ide>
<ide> var buildArgs []string
<ide> func ensureNNPTest(c *testing.T) {
<ide> COPY . /usr/bin
<ide> RUN chmod +s /usr/bin/nnp-test
<ide> `
<del> err = ioutil.WriteFile(dockerfile, []byte(content), 600)
<add> err = ioutil.WriteFile(dockerfile, []byte(content), 0600)
<ide> assert.NilError(c, err, "could not write Dockerfile for nnp-test image")
<ide>
<ide> var buildArgs []string | 2 |
Text | Text | remove abi guide | fd6a7d4db185db6c0084b6a593d698568f0ffe9f | <ide><path>doc/guides/abi-stability.md
<del># ABI Stability
<del>
<del>## Introduction
<del>An Application Binary Interface (ABI) is a way for programs to call functions
<del>and use data structures from other compiled programs. It is the compiled version
<del>of an Application Programming Interface (API). In other words, the headers files
<del>describing the classes, functions, data structures, enumerations, and constants
<del>which enable an application to perform a desired task correspond by way of
<del>compilation to a set of addresses and expected parameter values and memory
<del>structure sizes and layouts with which the provider of the ABI was compiled.
<del>
<del>The application using the ABI must be compiled such that the available
<del>addresses, expected parameter values, and memory structure sizes and layouts
<del>agree with those with which the ABI provider was compiled. This is usually
<del>accomplished by compiling against the headers provided by the ABI provider.
<del>
<del>Since the provider of the ABI and the user of the ABI may be compiled at
<del>different times with different versions of the compiler, a portion of the
<del>responsibility for ensuring ABI compatibility lies with the compiler. Different
<del>versions of the compiler, perhaps provided by different vendors, must all
<del>produce the same ABI from a header file with a certain content, and must produce
<del>code for the application using the ABI that accesses the API described in a
<del>given header according to the conventions of the ABI resulting from the
<del>description in the header. Modern compilers have a fairly good track record of
<del>not breaking the ABI compatibility of the applications they compile.
<del>
<del>The remaining responsibility for ensuring ABI compatibility lies with the team
<del>maintaining the header files which provide the API that results, upon
<del>compilation, in the ABI that is to remain stable. Changes to the header files
<del>can be made, but the nature of the changes has to be closely tracked to ensure
<del>that, upon compilation, the ABI does not change in a way that will render
<del>existing users of the ABI incompatible with the new version.
<del>
<del>## ABI Stability in Node.js
<del>Node.js provides header files maintained by several independent teams. For
<del>example, header files such as `node.h` and `node_buffer.h` are maintained by
<del>the Node.js team. `v8.h` is maintained by the V8 team, which, although in close
<del>co-operation with the Node.js team, is independent, and with its own schedule
<del>and priorities. Thus, the Node.js team has only partial control over the
<del>changes that are introduced in the headers the project provides. As a result,
<del>the Node.js project has adopted [semantic versioning](https://semver.org/).
<del>This ensures that the APIs provided by the project will result in a stable ABI
<del>for all minor and patch versions of Node.js released within one major version.
<del>In practice, this means that the Node.js project has committed itself to
<del>ensuring that a Node.js native addon compiled against a given major version of
<del>Node.js will load successfully when loaded by any Node.js minor or patch version
<del>within the major version against which it was compiled.
<del>
<del>## N-API
<del>Demand has arisen for equipping Node.js with an API that results in an ABI that
<del>remains stable across multiple Node.js major versions. The motivation for
<del>creating such an API is as follows:
<del>* The JavaScript language has remained compatible with itself since its very
<del>early days, whereas the ABI of the engine executing the JavaScript code changes
<del>with every major version of Node.js. This means that applications consisting of
<del>Node.js packages written entirely in JavaScript need not be recompiled,
<del>reinstalled, or redeployed as a new major version of Node.js is dropped into
<del>the production environment in which such applications run. In contrast, if an
<del>application depends on a package that contains a native addon, the application
<del>has to be recompiled, reinstalled, and redeployed whenever a new major version
<del>of Node.js is introduced into the production environment. This disparity
<del>between Node.js packages containing native addons and those that are written
<del>entirely in JavaScript has added to the maintenance burden of production
<del>systems which rely on native addons.
<del>
<del>* Other projects have started to produce JavaScript interfaces that are
<del>essentially alternative implementations of Node.js. Since these projects are
<del>usually built on a different JavaScript engine than V8, their native addons
<del>necessarily take on a different structure and use a different API. Nevertheless,
<del>using a single API for a native addon across different implementations of the
<del>Node.js JavaScript API would allow these projects to take advantage of the
<del>ecosystem of JavaScript packages that has accrued around Node.js.
<del>
<del>* Node.js may contain a different JavaScript engine in the future. This means
<del>that, externally, all Node.js interfaces would remain the same, but the V8
<del>header file would be absent. Such a step would cause the disruption of the
<del>Node.js ecosystem in general, and that of the native addons in particular, if
<del>an API that is JavaScript engine agnostic is not first provided by Node.js and
<del>adopted by native addons.
<del>
<del>To these ends Node.js has introduced N-API in version 8.6.0 and marked it as a
<del>stable component of the project as of Node.js 8.12.0. The API is defined in the
<del>headers [`node_api.h`][] and [`node_api_types.h`][], and provides a forward-
<del>compatibility guarantee that crosses the Node.js major version boundary. The
<del>guarantee can be stated as follows:
<del>
<del>**A given version *n* of N-API will be available in the major version of
<del>Node.js in which it was published, and in all subsequent versions of Node.js,
<del>including subsequent major versions.**
<del>
<del>A native addon author can take advantage of the N-API forward compatibility
<del>guarantee by ensuring that the addon makes use only of APIs defined in
<del>`node_api.h` and data structures and constants defined in `node_api_types.h`.
<del>By doing so, the author facilitates adoption of their addon by indicating to
<del>production users that the maintenance burden for their application will increase
<del>no more by the addition of the native addon to their project than it would by
<del>the addition of a package written purely in JavaScript.
<del>
<del>N-API is versioned because new APIs are added from time to time. Unlike
<del>semantic versioning, N-API versioning is cumulative. That is, each version of
<del>N-API conveys the same meaning as a minor version in the semver system, meaning
<del>that all changes made to N-API will be backwards compatible. Additionally, new
<del>N-APIs are added under an experimental flag to give the community an opportunity
<del>to vet them in a production environment. Experimental status means that,
<del>although care has been taken to ensure that the new API will not have to be
<del>modified in an ABI-incompatible way in the future, it has not yet been
<del>sufficiently proven in production to be correct and useful as designed and, as
<del>such, may undergo ABI-incompatible changes before it is finally incorporated
<del>into a forthcoming version of N-API. That is, an experimental N-API is not yet
<del>covered by the forward compatibility guarantee.
<del>
<del>[`node_api.h`]: ../../src/node_api.h
<del>[`node_api_types.h`]: ../..src/node_api_types.h | 1 |
Ruby | Ruby | update tap readme template | 47fedf2951d9579ffc3245b577d1ce51b147169a | <ide><path>Library/Contributions/cmd/brew-tap-readme.rb
<ide> You can also install via URL:
<ide>
<ide> ```
<del>brew install https://raw.github.com/Homebrew/homebrew-#{name}/master/<formula>.rb
<add>brew install https://raw.githubusercontent.com/Homebrew/homebrew-#{name}/master/<formula>.rb
<ide> ```
<ide>
<ide> Docs | 1 |
Javascript | Javascript | remove unnecessary clearcontainer call | ceee524a8f45b97c5fa9861aec3f36161495d2e1 | <ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.new.js
<ide> import {
<ide> cancelTimeout,
<ide> noTimeout,
<ide> afterActiveInstanceBlur,
<del> clearContainer,
<ide> getCurrentEventPriority,
<ide> supportsMicrotasks,
<ide> errorHydratingContainer,
<ide> function recoverFromConcurrentError(root, errorRetryLanes) {
<ide> if (__DEV__) {
<ide> errorHydratingContainer(root.containerInfo);
<ide> }
<del> clearContainer(root.containerInfo);
<ide> }
<ide>
<ide> let exitStatus;
<ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.old.js
<ide> import {
<ide> cancelTimeout,
<ide> noTimeout,
<ide> afterActiveInstanceBlur,
<del> clearContainer,
<ide> getCurrentEventPriority,
<ide> supportsMicrotasks,
<ide> errorHydratingContainer,
<ide> function recoverFromConcurrentError(root, errorRetryLanes) {
<ide> if (__DEV__) {
<ide> errorHydratingContainer(root.containerInfo);
<ide> }
<del> clearContainer(root.containerInfo);
<ide> }
<ide>
<ide> let exitStatus; | 2 |
Text | Text | fix typo in dynamic import with multiple modules | 3a9c419160c33613cadf3e44b0aba82767c44d3a | <ide><path>readme.md
<ide> import dynamic from 'next/dynamic'
<ide>
<ide> const HelloBundle = dynamic({
<ide> modules: (props) => {
<del> const components {
<add> const components = {
<ide> Hello1: import('../components/hello1'),
<ide> Hello2: import('../components/hello2')
<ide> } | 1 |
Javascript | Javascript | fix path when copying resource | 80bf68edbc3e8f58ed9cc0c9d0b43c1556e15e24 | <ide><path>script/lib/package-application.js
<ide> function copyNonASARResources(packagedAppPath, bundledResourcesPath) {
<ide> 'folder.ico'
<ide> ].forEach(file =>
<ide> fs.copySync(
<del> path.join('resources', 'win', file),
<add> path.join(CONFIG.repositoryRootPath, 'resources', 'win', file),
<ide> path.join(bundledResourcesPath, 'cli', file)
<ide> )
<ide> ); | 1 |
Text | Text | fix image links and sizes | 0b36e28dd9a2aad94087707f7c34e23fbec93d91 | <ide><path>guide/english/tools/source-code-editors/index.md
<ide> title: Source Code Editors
<ide> ---
<ide>
<del>##Source Code Editors
<add>## Source Code Editors
<ide>
<ide> Source code editors are the programs that allow for code creation and
<ide> editing. Any text editor can be used to write code. But dedicated code
<ide> each have their own subtleties. Further research may help find the one that's
<ide> right for you. The following editors are all cross-platform and
<ide> free to use or evaluate.
<ide>
<del>## <a href='https://www.sublimetext.com/' target='_blank' rel='nofollow'>Sublime Text</a> 
<add>## <a href='https://www.sublimetext.com/' target='_blank' rel='nofollow'>Sublime Text</a><img src="https://i.imgur.com/3ALtws1.png" width="50px">
<ide>
<del>
<add>
<ide>
<ide> Sublime Text is a very popular editor that has been around <a href='https://www.sublimetext.com/blog/articles/one-point-oh' target='_blank' rel='nofollow'>since 2008</a>. There
<ide> are many options and <a href='https://packagecontrol.io/' target='_blank' rel='nofollow'>extensions</a> available,
<ide> online to help
<ide> (The license for continued use costs $70\. However, Sublime Text is free to
<ide> download and evaluate, with a nag-screen pop-up.)
<ide>
<del>## <a href='http://brackets.io/' target='_blank' rel='nofollow'>Brackets</a> 
<add>## <a href='http://brackets.io/' target='_blank' rel='nofollow'>Brackets</a><img src="https://i.imgur.com/fassWYs.png" width="50px">
<ide>
<del>
<add>
<ide>
<ide> Brackets is a relatively new open-source editor by Adobe. It is very user
<ide> friendly, especially for people who aren't used to command-line interfaces
<ide> or JSON-style settings/prefereces. Extensions and themes are quick and easy
<ide> to find and install through the Extension Manager.
<ide>
<del>## <a href='https://atom.io/' target='_blank' rel='nofollow'>Atom</a> 
<add>## <a href='https://atom.io/' target='_blank' rel='nofollow'>Atom</a><img src="https://i.imgur.com/woj5vPm.png" width="50px">
<ide>
<del>
<add>
<ide>
<ide> Atom is an <a href='https://github.com/atom/atom' target='_blank' rel='nofollow'>open source</a> editor, developed
<ide> by <a href='https://github.com/' target='_blank' rel='nofollow'>GitHub</a>. Like Sublime Text, Atom is quite popular.
<ide> be overwhelming to new users. There is also plenty of <a href='http://readwrite.
<ide> <a href='http://stackoverflow.com/search?q=atom' target='_blank' rel='nofollow'>availble</a> online.
<ide>
<ide>
<del>## <a href='https://code.visualstudio.com/' target='_blank' rel='nofollow'>Visual Studio Code</a> 
<add>## <a href='https://code.visualstudio.com/' target='_blank' rel='nofollow'>Visual Studio Code</a><img src="https://i.imgur.com/b4vFsKa.png" width="50px">
<ide>
<ide> 
<ide> | 1 |
Ruby | Ruby | move libgtextutils to homebrew-science | 5f58cd9e5370b59c5209988f3f4672226c47adec | <ide><path>Library/Homebrew/tap_migrations.rb
<ide> 'ipopt' => 'homebrew/science',
<ide> 'qfits' => 'homebrew/boneyard',
<ide> 'blackbox' => 'homebrew/boneyard',
<add> 'libgtextutils' -> 'homebrew/science',
<ide> } | 1 |
Mixed | Python | replace relu6 with relu layers | 468f080c98f06780c950e5a78c9eeeaf9fff002e | <ide><path>docs/templates/applications.md
<ide> MobileNet model, with weights pre-trained on ImageNet.
<ide>
<ide> Note that this model only supports the data format `'channels_last'` (height, width, channels).
<ide>
<del>To load a MobileNet model via `load_model`, import the custom object `relu6` and pass it to the `custom_objects` parameter.
<del>
<del>E.g.
<del>
<del>```python
<del>model = load_model('mobilenet.h5', custom_objects={
<del> 'relu6': mobilenet.relu6})
<del>```
<del>
<ide> The default input size for this model is 224x224.
<ide>
<ide> ### Arguments
<ide> MobileNetV2 model, with weights pre-trained on ImageNet.
<ide>
<ide> Note that this model only supports the data format `'channels_last'` (height, width, channels).
<ide>
<del>To load a MobileNetV2 model via `load_model`, import the custom object `relu6` and pass it to the `custom_objects` parameter.
<del>
<del>E.g.
<del>
<del>```python
<del>model = load_model('mobilenet_v2.h5', custom_objects={
<del> 'relu6': mobilenetv2.relu6})
<del>```
<del>
<ide> The default input size for this model is 224x224.
<ide>
<ide> ### Arguments
<ide><path>keras/applications/mobilenet.py
<ide>
<ide> from keras_applications import mobilenet
<ide>
<del>relu6 = mobilenet.relu6
<ide> MobileNet = mobilenet.MobileNet
<ide> decode_predictions = mobilenet.decode_predictions
<ide> preprocess_input = mobilenet.preprocess_input
<ide><path>keras/applications/mobilenetv2.py
<ide>
<ide> from keras_applications import mobilenet_v2
<ide>
<del>relu6 = mobilenet_v2.relu6
<ide> MobileNetV2 = mobilenet_v2.MobileNetV2
<ide> decode_predictions = mobilenet_v2.decode_predictions
<ide> preprocess_input = mobilenet_v2.preprocess_input | 3 |
PHP | PHP | add a test that the "blacklist" does something | ddcbcae7c06d0e779b910c9672c2b8ca45ec0c77 | <ide><path>tests/TestCase/View/Helper/FormHelperTest.php
<ide> public function testFormInputs() {
<ide> $this->assertTags($result, $expected);
<ide> }
<ide>
<add>/**
<add> * testFormInputsBlacklist
<add> *
<add> * @return void
<add> */
<add> public function testFormInputsBlacklist() {
<add> $this->Form->create($this->article);
<add> $result = $this->Form->inputs([
<add> 'id' => false
<add> ]);
<add> $expected = array(
<add> '<fieldset',
<add> '<legend', 'New Article', '/legend',
<add> array('div' => array('class' => 'input select required')),
<add> '*/div',
<add> array('div' => array('class' => 'input text required')),
<add> '*/div',
<add> array('div' => array('class' => 'input text')),
<add> '*/div',
<add> array('div' => array('class' => 'input text')),
<add> '*/div',
<add> '/fieldset',
<add> );
<add> $this->assertTags($result, $expected);
<add>
<add> $this->Form->create($this->article);
<add> $result = $this->Form->inputs([
<add> 'id' => []
<add> ]);
<add> $expected = array(
<add> '<fieldset',
<add> '<legend', 'New Article', '/legend',
<add> 'input' => array('type' => 'hidden', 'name' => 'id', 'id' => 'id'),
<add> array('div' => array('class' => 'input select required')),
<add> '*/div',
<add> array('div' => array('class' => 'input text required')),
<add> '*/div',
<add> array('div' => array('class' => 'input text')),
<add> '*/div',
<add> array('div' => array('class' => 'input text')),
<add> '*/div',
<add> '/fieldset',
<add> );
<add> $this->assertTags($result, $expected, 'A falsey value (array) should not remove the input');
<add> }
<add>
<ide> /**
<ide> * testSelectAsCheckbox method
<ide> * | 1 |
Javascript | Javascript | update @emails in react-displayname-test | 4dcc1161faaaa62201e51b60ca263ea51981a531 | <ide><path>vendor/fbtransform/transforms/__tests__/react-displayName-test.js
<ide> * LICENSE file in the root directory of this source tree. An additional grant
<ide> * of patent rights can be found in the PATENTS file in the same directory.
<ide> *
<del> * @emails jeffmo@fb.com
<add> * @emails react-core
<ide> */
<ide> "use strict";
<ide> | 1 |
Javascript | Javascript | improve the code in test-process-hrtime | 2685464e34731d9ea14e97616309f4e7b7292551 | <ide><path>test/parallel/test-process-hrtime.js
<ide> require('../common');
<ide> const assert = require('assert');
<ide>
<ide> // the default behavior, return an Array "tuple" of numbers
<del>var tuple = process.hrtime();
<add>const tuple = process.hrtime();
<ide>
<ide> // validate the default behavior
<ide> validateTuple(tuple);
<ide> validateTuple(tuple);
<ide> validateTuple(process.hrtime(tuple));
<ide>
<ide> // test that only an Array may be passed to process.hrtime()
<del>assert.throws(function() {
<add>assert.throws(() => {
<ide> process.hrtime(1);
<del>});
<add>}, /^TypeError: process.hrtime\(\) only accepts an Array tuple$/);
<ide>
<ide> function validateTuple(tuple) {
<ide> assert(Array.isArray(tuple));
<del> assert.equal(2, tuple.length);
<del> tuple.forEach(function(v) {
<del> assert.equal('number', typeof v);
<del> assert(isFinite(v));
<add> assert.strictEqual(tuple.length, 2);
<add> tuple.forEach((v) => {
<add> assert.strictEqual(typeof v, 'number');
<add> assert.strictEqual(isFinite(v), true);
<ide> });
<ide> }
<ide> | 1 |
Javascript | Javascript | reduce offset module. close gh-1139 | cbe0c2ef90669c4c145227a2ddf41993583f5437 | <ide><path>src/offset.js
<ide> jQuery.fn.offset = function( options ) {
<ide> }
<ide>
<ide> var docElem, win,
<del> box = { top: 0, left: 0 },
<ide> elem = this[ 0 ],
<add> box = { top: 0, left: 0 },
<ide> doc = elem && elem.ownerDocument;
<ide>
<ide> if ( !doc ) {
<ide> jQuery.fn.offset = function( options ) {
<ide> }
<ide> win = getWindow( doc );
<ide> return {
<del> top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ),
<del> left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 )
<add> top: box.top + win.pageYOffset - docElem.clientTop,
<add> left: box.left + win.pageXOffset - docElem.clientLeft
<ide> };
<ide> };
<ide>
<ide> jQuery.offset = {
<ide>
<ide> setOffset: function( elem, options, i ) {
<del> var position = jQuery.css( elem, "position" );
<add> var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition,
<add> position = jQuery.css( elem, "position" ),
<add> curElem = jQuery( elem ),
<add> props = {};
<ide>
<del> // set position first, in-case top/left are set even on static elem
<add> // Set position first, in-case top/left are set even on static elem
<ide> if ( position === "static" ) {
<ide> elem.style.position = "relative";
<ide> }
<ide>
<del> var curElem = jQuery( elem ),
<del> curOffset = curElem.offset(),
<del> curCSSTop = jQuery.css( elem, "top" ),
<del> curCSSLeft = jQuery.css( elem, "left" ),
<del> calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1,
<del> props = {}, curPosition = {}, curTop, curLeft;
<add> curOffset = curElem.offset();
<add> curCSSTop = jQuery.css( elem, "top" );
<add> curCSSLeft = jQuery.css( elem, "left" );
<add> calculatePosition = ( position === "absolute" || position === "fixed" ) && ( curCSSTop + curCSSLeft ).indexOf("auto") > -1;
<ide>
<del> // need to be able to calculate position if either top or left is auto and position is either absolute or fixed
<add> // Need to be able to calculate position if either top or left is auto and position is either absolute or fixed
<ide> if ( calculatePosition ) {
<ide> curPosition = curElem.position();
<ide> curTop = curPosition.top;
<ide> curLeft = curPosition.left;
<add>
<ide> } else {
<ide> curTop = parseFloat( curCSSTop ) || 0;
<ide> curLeft = parseFloat( curCSSLeft ) || 0;
<ide> jQuery.offset = {
<ide>
<ide> if ( "using" in options ) {
<ide> options.using.call( elem, props );
<add>
<ide> } else {
<ide> curElem.css( props );
<ide> }
<ide> jQuery.fn.extend({
<ide> }
<ide>
<ide> var offsetParent, offset,
<del> parentOffset = { top: 0, left: 0 },
<del> elem = this[ 0 ];
<add> elem = this[ 0 ],
<add> parentOffset = { top: 0, left: 0 };
<ide>
<del> // fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent
<add> // Fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent
<ide> if ( jQuery.css( elem, "position" ) === "fixed" ) {
<del> // we assume that getBoundingClientRect is available when computed position is fixed
<add> // We assume that getBoundingClientRect is available when computed position is fixed
<ide> offset = elem.getBoundingClientRect();
<add>
<ide> } else {
<ide> // Get *real* offsetParent
<ide> offsetParent = this.offsetParent();
<ide> jQuery.fn.extend({
<ide> }
<ide>
<ide> // Add offsetParent borders
<del> parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true );
<add> parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true );
<ide> parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true );
<ide> }
<ide>
<ide> // Subtract parent offsets and element margins
<del> // note: when an element has margin: auto the offsetLeft and marginLeft
<del> // are the same in Safari causing offset.left to incorrectly be 0
<ide> return {
<del> top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
<del> left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true)
<add> top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
<add> left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true )
<ide> };
<ide> },
<ide>
<ide> offsetParent: function() {
<ide> return this.map(function() {
<ide> var offsetParent = this.offsetParent || document.documentElement;
<add>
<ide> while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position") === "static" ) ) {
<ide> offsetParent = offsetParent.offsetParent;
<ide> }
<add>
<ide> return offsetParent || document.documentElement;
<ide> });
<ide> }
<ide> jQuery.fn.extend({
<ide>
<ide> // Create scrollLeft and scrollTop methods
<ide> jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) {
<del> var top = /Y/.test( prop );
<add> var top = "pageYOffset" === prop;
<ide>
<ide> jQuery.fn[ method ] = function( val ) {
<ide> return jQuery.access( this, function( elem, method, val ) {
<ide> var win = getWindow( elem );
<ide>
<ide> if ( val === undefined ) {
<del> return win ? (prop in win) ? win[ prop ] :
<del> win.document.documentElement[ method ] :
<del> elem[ method ];
<add> return win ? win[ prop ] : elem[ method ];
<ide> }
<ide>
<ide> if ( win ) {
<ide> win.scrollTo(
<del> !top ? val : jQuery( win ).scrollLeft(),
<del> top ? val : jQuery( win ).scrollTop()
<add> !top ? val : window.pageXOffset,
<add> top ? val : window.pageYOffset
<ide> );
<ide>
<ide> } else {
<ide> jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( me
<ide> });
<ide>
<ide> function getWindow( elem ) {
<del> return jQuery.isWindow( elem ) ?
<del> elem :
<del> elem.nodeType === 9 ?
<del> elem.defaultView || elem.parentWindow :
<del> false;
<add> return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView;
<ide> } | 1 |
Java | Java | remove variance on defer | 803f59bfa7a4c754dfd6b01287c0e00ad5e1f9b9 | <ide><path>rxjava-core/src/main/java/rx/Observable.java
<ide> public final static <T> Observable<T> concat(Observable<? extends T> t1, Observa
<ide> * @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#defer">RxJava wiki: defer</a>
<ide> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229160.aspx">MSDN: Observable.Defer</a>
<ide> */
<del> public final static <T> Observable<T> defer(Func0<? extends Observable<? extends T>> observableFactory) {
<add> public final static <T> Observable<T> defer(Func0<Observable<T>> observableFactory) {
<ide> return create(new OnSubscribeDefer<T>(observableFactory));
<ide> }
<ide> | 1 |
Javascript | Javascript | fill available params on deprecation notice | dcff8c833f7806c8dfdb1e79763646bfbb6702f5 | <ide><path>lib/optimize/CommonsChunkPlugin.js
<ide> function CommonsChunkPlugin(options) {
<ide> " names: string[]\n" +
<ide> " filename: string\n" +
<ide> " minChunks: number\n" +
<add> " chunks: string[]\n" +
<add> " children: boolean\n" +
<ide> " async: boolean\n" +
<ide> " minSize: number\n");
<ide> } | 1 |
Ruby | Ruby | convert activemodel to 1.9 hash syntax | eebb9ddf9ba559a510975c486fe59a4edc9da97d | <ide><path>activemodel/lib/active_model/attribute_methods.rb
<ide> def instance_method_already_implemented?(method_name) #:nodoc:
<ide> # significantly (in our case our test suite finishes 10% faster with
<ide> # this cache).
<ide> def attribute_method_matchers_cache #:nodoc:
<del> @attribute_method_matchers_cache ||= ThreadSafe::Cache.new(:initial_capacity => 4)
<add> @attribute_method_matchers_cache ||= ThreadSafe::Cache.new(initial_capacity: 4)
<ide> end
<ide>
<ide> def attribute_method_matcher(method_name) #:nodoc:
<ide><path>activemodel/lib/active_model/callbacks.rb
<ide> def self.extended(base) #:nodoc:
<ide> def define_model_callbacks(*callbacks)
<ide> options = callbacks.extract_options!
<ide> options = {
<del> :terminator => "result == false",
<del> :skip_after_callbacks_if_terminated => true,
<del> :scope => [:kind, :name],
<del> :only => [:before, :around, :after]
<add> terminator: "result == false",
<add> skip_after_callbacks_if_terminated: true,
<add> scope: [:kind, :name],
<add> only: [:before, :around, :after]
<ide> }.merge!(options)
<ide>
<ide> types = Array(options.delete(:only))
<ide><path>activemodel/lib/active_model/dirty.rb
<ide> module Dirty
<ide>
<ide> included do
<ide> attribute_method_suffix '_changed?', '_change', '_will_change!', '_was'
<del> attribute_method_affix :prefix => 'reset_', :suffix => '!'
<add> attribute_method_affix prefix: 'reset_', suffix: '!'
<ide> end
<ide>
<ide> # Returns +true+ if any attribute have unsaved changes, +false+ otherwise.
<ide><path>activemodel/lib/active_model/errors.rb
<ide> def empty?
<ide> # # <error>name must be specified</error>
<ide> # # </errors>
<ide> def to_xml(options={})
<del> to_a.to_xml({ :root => "errors", :skip_types => true }.merge!(options))
<add> to_a.to_xml({ root: "errors", skip_types: true }.merge!(options))
<ide> end
<ide>
<ide> # Returns a Hash that can be used as the JSON representation for this
<ide> def full_messages_for(attribute)
<ide> def full_message(attribute, message)
<ide> return message if attribute == :base
<ide> attr_name = attribute.to_s.tr('.', '_').humanize
<del> attr_name = @base.class.human_attribute_name(attribute, :default => attr_name)
<add> attr_name = @base.class.human_attribute_name(attribute, default: attr_name)
<ide> I18n.t(:"errors.format", {
<del> :default => "%{attribute} %{message}",
<del> :attribute => attr_name,
<del> :message => message
<add> default: "%{attribute} %{message}",
<add> attribute: attr_name,
<add> message: message
<ide> })
<ide> end
<ide>
<ide> def generate_message(attribute, type = :invalid, options = {})
<ide> value = (attribute != :base ? @base.send(:read_attribute_for_validation, attribute) : nil)
<ide>
<ide> options = {
<del> :default => defaults,
<del> :model => @base.class.model_name.human,
<del> :attribute => @base.class.human_attribute_name(attribute),
<del> :value => value
<add> default: defaults,
<add> model: @base.class.model_name.human,
<add> attribute: @base.class.human_attribute_name(attribute),
<add> value: value
<ide> }.merge!(options)
<ide>
<ide> I18n.translate(key, options)
<ide><path>activemodel/lib/active_model/naming.rb
<ide> class Name
<ide> #
<ide> # Equivalent to +to_s+.
<ide> delegate :==, :===, :<=>, :=~, :"!~", :eql?, :to_s,
<del> :to_str, :to => :name
<add> :to_str, to: :name
<ide>
<ide> # Returns a new ActiveModel::Name instance. By default, the +namespace+
<ide> # and +name+ option will take the namespace and name of the given class
<ide> def human(options={})
<ide> defaults << options[:default] if options[:default]
<ide> defaults << @human
<ide>
<del> options = { :scope => [@klass.i18n_scope, :models], :count => 1, :default => defaults }.merge!(options.except(:default))
<add> options = { scope: [@klass.i18n_scope, :models], count: 1, default: defaults }.merge!(options.except(:default))
<ide> I18n.translate(defaults.shift, options)
<ide> end
<ide>
<ide><path>activemodel/lib/active_model/secure_password.rb
<ide> def has_secure_password(options = {})
<ide>
<ide> if options.fetch(:validations, true)
<ide> validates_confirmation_of :password
<del> validates_presence_of :password, :on => :create
<add> validates_presence_of :password, on: :create
<ide>
<ide> before_create { raise "Password digest missing on new record" if password_digest.blank? }
<ide> end
<ide><path>activemodel/lib/active_model/serializers/xml.rb
<ide> def serialize
<ide> require 'builder' unless defined? ::Builder
<ide>
<ide> options[:indent] ||= 2
<del> options[:builder] ||= ::Builder::XmlMarkup.new(:indent => options[:indent])
<add> options[:builder] ||= ::Builder::XmlMarkup.new(indent: options[:indent])
<ide>
<ide> @builder = options[:builder]
<ide> @builder.instruct! unless options[:skip_instruct]
<ide> def serialize
<ide> root = ActiveSupport::XmlMini.rename_key(root, options)
<ide>
<ide> args = [root]
<del> args << {:xmlns => options[:namespace]} if options[:namespace]
<del> args << {:type => options[:type]} if options[:type] && !options[:skip_types]
<add> args << { xmlns: options[:namespace] } if options[:namespace]
<add> args << { type: options[:type] } if options[:type] && !options[:skip_types]
<ide>
<ide> @builder.tag!(*args) do
<ide> add_attributes_and_methods
<ide> def add_associations(association, records, opts)
<ide> records = records.to_ary
<ide>
<ide> tag = ActiveSupport::XmlMini.rename_key(association.to_s, options)
<del> type = options[:skip_types] ? { } : {:type => "array"}
<add> type = options[:skip_types] ? { } : { type: "array" }
<ide> association_name = association.to_s.singularize
<ide> merged_options[:root] = association_name
<ide>
<ide> def add_associations(association, records, opts)
<ide> record_type = {}
<ide> else
<ide> record_class = (record.class.to_s.underscore == association_name) ? nil : record.class.name
<del> record_type = {:type => record_class}
<add> record_type = { type: record_class }
<ide> end
<ide>
<ide> record.to_xml merged_options.merge(record_type)
<ide><path>activemodel/lib/active_model/translation.rb
<ide> def lookup_ancestors
<ide> #
<ide> # Specify +options+ with additional translating options.
<ide> def human_attribute_name(attribute, options = {})
<del> options = { :count => 1 }.merge!(options)
<add> options = { count: 1 }.merge!(options)
<ide> parts = attribute.to_s.split(".")
<ide> attribute = parts.pop
<ide> namespace = parts.join("/") unless parts.empty?
<ide><path>activemodel/lib/active_model/validations.rb
<ide> module Validations
<ide> include HelperMethods
<ide>
<ide> attr_accessor :validation_context
<del> define_callbacks :validate, :scope => :name
<add> define_callbacks :validate, scope: :name
<ide>
<ide> class_attribute :_validators
<ide> self._validators = Hash.new { |h,k| h[k] = [] }
<ide><path>activemodel/lib/active_model/validations/acceptance.rb
<ide> module ActiveModel
<ide> module Validations
<ide> class AcceptanceValidator < EachValidator # :nodoc:
<ide> def initialize(options)
<del> super({ :allow_nil => true, :accept => "1" }.merge!(options))
<add> super({ allow_nil: true, accept: "1" }.merge!(options))
<ide> end
<ide>
<ide> def validate_each(record, attribute, value)
<ide><path>activemodel/lib/active_model/validations/callbacks.rb
<ide> module Callbacks
<ide>
<ide> included do
<ide> include ActiveSupport::Callbacks
<del> define_callbacks :validation, :terminator => "result == false", :skip_after_callbacks_if_terminated => true, :scope => [:kind, :name]
<add> define_callbacks :validation, terminator: "result == false", skip_after_callbacks_if_terminated: true, scope: [:kind, :name]
<ide> end
<ide>
<ide> module ClassMethods
<ide><path>activemodel/lib/active_model/validations/confirmation.rb
<ide> class ConfirmationValidator < EachValidator # :nodoc:
<ide> def validate_each(record, attribute, value)
<ide> if (confirmed = record.send("#{attribute}_confirmation")) && (value != confirmed)
<ide> human_attribute_name = record.class.human_attribute_name(attribute)
<del> record.errors.add(:"#{attribute}_confirmation", :confirmation, options.merge(:attribute => human_attribute_name))
<add> record.errors.add(:"#{attribute}_confirmation", :confirmation, options.merge(attribute: human_attribute_name))
<ide> end
<ide> end
<ide>
<ide><path>activemodel/lib/active_model/validations/exclusion.rb
<ide> class ExclusionValidator < EachValidator # :nodoc:
<ide>
<ide> def validate_each(record, attribute, value)
<ide> if include?(record, value)
<del> record.errors.add(attribute, :exclusion, options.except(:in, :within).merge!(:value => value))
<add> record.errors.add(attribute, :exclusion, options.except(:in, :within).merge!(value: value))
<ide> end
<ide> end
<ide> end
<ide><path>activemodel/lib/active_model/validations/format.rb
<ide> def option_call(record, name)
<ide> end
<ide>
<ide> def record_error(record, attribute, name, value)
<del> record.errors.add(attribute, :invalid, options.except(name).merge!(:value => value))
<add> record.errors.add(attribute, :invalid, options.except(name).merge!(value: value))
<ide> end
<ide>
<ide> def regexp_using_multiline_anchors?(regexp)
<ide><path>activemodel/lib/active_model/validations/inclusion.rb
<ide> class InclusionValidator < EachValidator # :nodoc:
<ide>
<ide> def validate_each(record, attribute, value)
<ide> unless include?(record, value)
<del> record.errors.add(attribute, :inclusion, options.except(:in, :within).merge!(:value => value))
<add> record.errors.add(attribute, :inclusion, options.except(:in, :within).merge!(value: value))
<ide> end
<ide> end
<ide> end
<ide><path>activemodel/lib/active_model/validations/length.rb
<ide> module ActiveModel
<ide> # == Active \Model Length \Validator
<ide> module Validations
<ide> class LengthValidator < EachValidator # :nodoc:
<del> MESSAGES = { :is => :wrong_length, :minimum => :too_short, :maximum => :too_long }.freeze
<del> CHECKS = { :is => :==, :minimum => :>=, :maximum => :<= }.freeze
<add> MESSAGES = { is: :wrong_length, minimum: :too_short, maximum: :too_long }.freeze
<add> CHECKS = { is: :==, minimum: :>=, maximum: :<= }.freeze
<ide>
<ide> RESERVED_OPTIONS = [:minimum, :maximum, :within, :is, :tokenizer, :too_short, :too_long]
<ide>
<ide><path>activemodel/lib/active_model/validations/numericality.rb
<ide> module ActiveModel
<ide>
<ide> module Validations
<ide> class NumericalityValidator < EachValidator # :nodoc:
<del> CHECKS = { :greater_than => :>, :greater_than_or_equal_to => :>=,
<del> :equal_to => :==, :less_than => :<, :less_than_or_equal_to => :<=,
<del> :odd => :odd?, :even => :even?, :other_than => :!= }.freeze
<add> CHECKS = { greater_than: :>, greater_than_or_equal_to: :>=,
<add> equal_to: :==, less_than: :<, less_than_or_equal_to: :<=,
<add> odd: :odd?, even: :even?, other_than: :!= }.freeze
<ide>
<ide> RESERVED_OPTIONS = CHECKS.keys + [:only_integer]
<ide>
<ide> def validate_each(record, attr_name, value)
<ide> option_value = record.send(option_value) if option_value.is_a?(Symbol)
<ide>
<ide> unless value.send(CHECKS[option], option_value)
<del> record.errors.add(attr_name, option, filtered_options(value).merge(:count => option_value))
<add> record.errors.add(attr_name, option, filtered_options(value).merge(count: option_value))
<ide> end
<ide> end
<ide> end
<ide> def parse_raw_value_as_an_integer(raw_value)
<ide> end
<ide>
<ide> def filtered_options(value)
<del> options.except(*RESERVED_OPTIONS).merge!(:value => value)
<add> options.except(*RESERVED_OPTIONS).merge!(value: value)
<ide> end
<ide> end
<ide>
<ide><path>activemodel/lib/active_model/validations/validates.rb
<ide> def _parse_validates_options(options) # :nodoc:
<ide> when Hash
<ide> options
<ide> when Range, Array
<del> { :in => options }
<add> { in: options }
<ide> else
<del> { :with => options }
<add> { with: options }
<ide> end
<ide> end
<ide> end
<ide><path>activemodel/test/cases/attribute_methods_test.rb
<ide> class << self
<ide> end
<ide>
<ide> def attributes
<del> { :foo => 'value of foo', :baz => 'value of baz' }
<add> { foo: 'value of foo', baz: 'value of baz' }
<ide> end
<ide>
<ide> private
<ide> class ModelWithRubyKeywordNamedAttributes
<ide> include ActiveModel::AttributeMethods
<ide>
<ide> def attributes
<del> { :begin => 'value of begin', :end => 'value of end' }
<add> { begin: 'value of begin', end: 'value of end' }
<ide> end
<ide>
<ide> private
<ide><path>activemodel/test/cases/callbacks_test.rb
<ide> class ModelCallbacks
<ide> extend ActiveModel::Callbacks
<ide>
<ide> define_model_callbacks :create
<del> define_model_callbacks :initialize, :only => :after
<del> define_model_callbacks :multiple, :only => [:before, :around]
<del> define_model_callbacks :empty, :only => []
<add> define_model_callbacks :initialize, only: :after
<add> define_model_callbacks :multiple, only: [:before, :around]
<add> define_model_callbacks :empty, only: []
<ide>
<ide> before_create :before_create
<ide> around_create CallbackValidator.new
<ide><path>activemodel/test/cases/conversion_test.rb
<ide> class ConversionTest < ActiveModel::TestCase
<ide> end
<ide>
<ide> test "to_key default implementation returns the id in an array for persisted records" do
<del> assert_equal [1], Contact.new(:id => 1).to_key
<add> assert_equal [1], Contact.new(id: 1).to_key
<ide> end
<ide>
<ide> test "to_param default implementation returns nil for new records" do
<ide> assert_nil Contact.new.to_param
<ide> end
<ide>
<ide> test "to_param default implementation returns a string of ids for persisted records" do
<del> assert_equal "1", Contact.new(:id => 1).to_param
<add> assert_equal "1", Contact.new(id: 1).to_param
<ide> end
<ide>
<ide> test "to_partial_path default implementation returns a string giving a relative path" do
<ide><path>activemodel/test/cases/errors_test.rb
<ide> def test_has_key?
<ide>
<ide> test "add_on_empty generates message with custom default message" do
<ide> person = Person.new
<del> person.errors.expects(:generate_message).with(:name, :empty, {:message => 'custom'})
<del> person.errors.add_on_empty :name, :message => 'custom'
<add> person.errors.expects(:generate_message).with(:name, :empty, { message: 'custom' })
<add> person.errors.add_on_empty :name, message: 'custom'
<ide> end
<ide>
<ide> test "add_on_empty generates message with empty string value" do
<ide> def test_has_key?
<ide>
<ide> test "add_on_blank generates message with custom default message" do
<ide> person = Person.new
<del> person.errors.expects(:generate_message).with(:name, :blank, {:message => 'custom'})
<del> person.errors.add_on_blank :name, :message => 'custom'
<add> person.errors.expects(:generate_message).with(:name, :blank, { message: 'custom' })
<add> person.errors.add_on_blank :name, message: 'custom'
<ide> end
<ide> end
<ide><path>activemodel/test/cases/model_test.rb
<ide> def setup
<ide> end
<ide>
<ide> def test_initialize_with_params
<del> object = BasicModel.new(:attr => "value")
<add> object = BasicModel.new(attr: "value")
<ide> assert_equal object.attr, "value"
<ide> end
<ide>
<ide> def test_initialize_with_nil_or_empty_hash_params_does_not_explode
<ide> end
<ide>
<ide> def test_persisted_is_always_false
<del> object = BasicModel.new(:attr => "value")
<add> object = BasicModel.new(attr: "value")
<ide> assert object.persisted? == false
<ide> end
<ide> end
<ide><path>activemodel/test/cases/serialization_test.rb
<ide> def test_method_serializable_hash_should_work
<ide>
<ide> def test_method_serializable_hash_should_work_with_only_option
<ide> expected = {"name"=>"David"}
<del> assert_equal expected, @user.serializable_hash(:only => [:name])
<add> assert_equal expected, @user.serializable_hash(only: [:name])
<ide> end
<ide>
<ide> def test_method_serializable_hash_should_work_with_except_option
<ide> expected = {"gender"=>"male", "email"=>"david@example.com"}
<del> assert_equal expected, @user.serializable_hash(:except => [:name])
<add> assert_equal expected, @user.serializable_hash(except: [:name])
<ide> end
<ide>
<ide> def test_method_serializable_hash_should_work_with_methods_option
<ide> expected = {"name"=>"David", "gender"=>"male", "foo"=>"i_am_foo", "email"=>"david@example.com"}
<del> assert_equal expected, @user.serializable_hash(:methods => [:foo])
<add> assert_equal expected, @user.serializable_hash(methods: [:foo])
<ide> end
<ide>
<ide> def test_method_serializable_hash_should_work_with_only_and_methods
<ide> expected = {"foo"=>"i_am_foo"}
<del> assert_equal expected, @user.serializable_hash(:only => [], :methods => [:foo])
<add> assert_equal expected, @user.serializable_hash(only: [], methods: [:foo])
<ide> end
<ide>
<ide> def test_method_serializable_hash_should_work_with_except_and_methods
<ide> expected = {"gender"=>"male", "foo"=>"i_am_foo"}
<del> assert_equal expected, @user.serializable_hash(:except => [:name, :email], :methods => [:foo])
<add> assert_equal expected, @user.serializable_hash(except: [:name, :email], methods: [:foo])
<ide> end
<ide>
<ide> def test_should_not_call_methods_that_dont_respond
<ide> expected = {"name"=>"David", "gender"=>"male", "email"=>"david@example.com"}
<del> assert_equal expected, @user.serializable_hash(:methods => [:bar])
<add> assert_equal expected, @user.serializable_hash(methods: [:bar])
<ide> end
<ide>
<ide> def test_should_use_read_attribute_for_serialization
<ide> def @user.read_attribute_for_serialization(n)
<ide> end
<ide>
<ide> expected = { "name" => "Jon" }
<del> assert_equal expected, @user.serializable_hash(:only => :name)
<add> assert_equal expected, @user.serializable_hash(only: :name)
<ide> end
<ide>
<ide> def test_include_option_with_singular_association
<ide> expected = {"name"=>"David", "gender"=>"male", "email"=>"david@example.com",
<ide> "address"=>{"street"=>"123 Lane", "city"=>"Springfield", "state"=>"CA", "zip"=>11111}}
<del> assert_equal expected, @user.serializable_hash(:include => :address)
<add> assert_equal expected, @user.serializable_hash(include: :address)
<ide> end
<ide>
<ide> def test_include_option_with_plural_association
<ide> expected = {"email"=>"david@example.com", "gender"=>"male", "name"=>"David",
<ide> "friends"=>[{"name"=>'Joe', "email"=>'joe@example.com', "gender"=>'male'},
<ide> {"name"=>'Sue', "email"=>'sue@example.com', "gender"=>'female'}]}
<del> assert_equal expected, @user.serializable_hash(:include => :friends)
<add> assert_equal expected, @user.serializable_hash(include: :friends)
<ide> end
<ide>
<ide> def test_include_option_with_empty_association
<ide> @user.friends = []
<ide> expected = {"email"=>"david@example.com", "gender"=>"male", "name"=>"David", "friends"=>[]}
<del> assert_equal expected, @user.serializable_hash(:include => :friends)
<add> assert_equal expected, @user.serializable_hash(include: :friends)
<ide> end
<ide>
<ide> class FriendList
<ide> def test_include_option_with_ary
<ide> expected = {"email"=>"david@example.com", "gender"=>"male", "name"=>"David",
<ide> "friends"=>[{"name"=>'Joe', "email"=>'joe@example.com', "gender"=>'male'},
<ide> {"name"=>'Sue', "email"=>'sue@example.com', "gender"=>'female'}]}
<del> assert_equal expected, @user.serializable_hash(:include => :friends)
<add> assert_equal expected, @user.serializable_hash(include: :friends)
<ide> end
<ide>
<ide> def test_multiple_includes
<ide> expected = {"email"=>"david@example.com", "gender"=>"male", "name"=>"David",
<ide> "address"=>{"street"=>"123 Lane", "city"=>"Springfield", "state"=>"CA", "zip"=>11111},
<ide> "friends"=>[{"name"=>'Joe', "email"=>'joe@example.com', "gender"=>'male'},
<ide> {"name"=>'Sue', "email"=>'sue@example.com', "gender"=>'female'}]}
<del> assert_equal expected, @user.serializable_hash(:include => [:address, :friends])
<add> assert_equal expected, @user.serializable_hash(include: [:address, :friends])
<ide> end
<ide>
<ide> def test_include_with_options
<ide> expected = {"email"=>"david@example.com", "gender"=>"male", "name"=>"David",
<ide> "address"=>{"street"=>"123 Lane"}}
<del> assert_equal expected, @user.serializable_hash(:include => {:address => {:only => "street"}})
<add> assert_equal expected, @user.serializable_hash(include: { address: { only: "street" } })
<ide> end
<ide>
<ide> def test_nested_include
<ide> def test_nested_include
<ide> "friends"=>[{"name"=>'Joe', "email"=>'joe@example.com', "gender"=>'male',
<ide> "friends"=> [{"email"=>"david@example.com", "gender"=>"male", "name"=>"David"}]},
<ide> {"name"=>'Sue', "email"=>'sue@example.com', "gender"=>'female', "friends"=> []}]}
<del> assert_equal expected, @user.serializable_hash(:include => {:friends => {:include => :friends}})
<add> assert_equal expected, @user.serializable_hash(include: { friends: { include: :friends } })
<ide> end
<ide>
<ide> def test_only_include
<ide> expected = {"name"=>"David", "friends" => [{"name" => "Joe"}, {"name" => "Sue"}]}
<del> assert_equal expected, @user.serializable_hash(:only => :name, :include => {:friends => {:only => :name}})
<add> assert_equal expected, @user.serializable_hash(only: :name, include: { friends: { only: :name } })
<ide> end
<ide>
<ide> def test_except_include
<ide> expected = {"name"=>"David", "email"=>"david@example.com",
<ide> "friends"=> [{"name" => 'Joe', "email" => 'joe@example.com'},
<ide> {"name" => "Sue", "email" => 'sue@example.com'}]}
<del> assert_equal expected, @user.serializable_hash(:except => :gender, :include => {:friends => {:except => :gender}})
<add> assert_equal expected, @user.serializable_hash(except: :gender, include: { friends: { except: :gender } })
<ide> end
<ide>
<ide> def test_multiple_includes_with_options
<ide> expected = {"email"=>"david@example.com", "gender"=>"male", "name"=>"David",
<ide> "address"=>{"street"=>"123 Lane"},
<ide> "friends"=>[{"name"=>'Joe', "email"=>'joe@example.com', "gender"=>'male'},
<ide> {"name"=>'Sue', "email"=>'sue@example.com', "gender"=>'female'}]}
<del> assert_equal expected, @user.serializable_hash(:include => [{:address => {:only => "street"}}, :friends])
<add> assert_equal expected, @user.serializable_hash(include: [{ address: {only: "street" } }, :friends])
<ide> end
<ide> end
<ide><path>activemodel/test/cases/serializers/json_serialization_test.rb
<ide> def teardown
<ide> end
<ide>
<ide> test "should allow attribute filtering with only" do
<del> json = @contact.to_json(:only => [:name, :age])
<add> json = @contact.to_json(only: [:name, :age])
<ide>
<ide> assert_match %r{"name":"Konata Izumi"}, json
<ide> assert_match %r{"age":16}, json
<ide><path>activemodel/test/cases/serializers/xml_serialization_test.rb
<ide> def attributes
<ide>
<ide> class SerializableContact < Contact
<ide> def serializable_hash(options={})
<del> super(options.merge(:only => [:name, :age]))
<add> super(options.merge(only: [:name, :age]))
<ide> end
<ide> end
<ide>
<ide> def setup
<ide> end
<ide>
<ide> test "should serialize default root with namespace" do
<del> @xml = @contact.to_xml :namespace => "http://xml.rubyonrails.org/contact"
<add> @xml = @contact.to_xml namespace: "http://xml.rubyonrails.org/contact"
<ide> assert_match %r{^<contact xmlns="http://xml.rubyonrails.org/contact">}, @xml
<ide> assert_match %r{</contact>$}, @xml
<ide> end
<ide>
<ide> test "should serialize custom root" do
<del> @xml = @contact.to_xml :root => 'xml_contact'
<add> @xml = @contact.to_xml root: 'xml_contact'
<ide> assert_match %r{^<xml-contact>}, @xml
<ide> assert_match %r{</xml-contact>$}, @xml
<ide> end
<ide>
<ide> test "should allow undasherized tags" do
<del> @xml = @contact.to_xml :root => 'xml_contact', :dasherize => false
<add> @xml = @contact.to_xml root: 'xml_contact', dasherize: false
<ide> assert_match %r{^<xml_contact>}, @xml
<ide> assert_match %r{</xml_contact>$}, @xml
<ide> assert_match %r{<created_at}, @xml
<ide> end
<ide>
<ide> test "should allow camelized tags" do
<del> @xml = @contact.to_xml :root => 'xml_contact', :camelize => true
<add> @xml = @contact.to_xml root: 'xml_contact', camelize: true
<ide> assert_match %r{^<XmlContact>}, @xml
<ide> assert_match %r{</XmlContact>$}, @xml
<ide> assert_match %r{<CreatedAt}, @xml
<ide> end
<ide>
<ide> test "should allow lower-camelized tags" do
<del> @xml = @contact.to_xml :root => 'xml_contact', :camelize => :lower
<add> @xml = @contact.to_xml root: 'xml_contact', camelize: :lower
<ide> assert_match %r{^<xmlContact>}, @xml
<ide> assert_match %r{</xmlContact>$}, @xml
<ide> assert_match %r{<createdAt}, @xml
<ide> def setup
<ide> end
<ide>
<ide> test "should allow skipped types" do
<del> @xml = @contact.to_xml :skip_types => true
<add> @xml = @contact.to_xml skip_types: true
<ide> assert_match %r{<age>25</age>}, @xml
<ide> end
<ide>
<ide> def setup
<ide> end
<ide>
<ide> test "should serialize nil" do
<del> assert_match %r{<pseudonyms nil=\"true\"/>}, @contact.to_xml(:methods => :pseudonyms)
<add> assert_match %r{<pseudonyms nil=\"true\"/>}, @contact.to_xml(methods: :pseudonyms)
<ide> end
<ide>
<ide> test "should serialize integer" do
<ide> def setup
<ide> end
<ide>
<ide> test "should serialize array" do
<del> assert_match %r{<social type=\"array\">\s*<social>twitter</social>\s*<social>github</social>\s*</social>}, @contact.to_xml(:methods => :social)
<add> assert_match %r{<social type=\"array\">\s*<social>twitter</social>\s*<social>github</social>\s*</social>}, @contact.to_xml(methods: :social)
<ide> end
<ide>
<ide> test "should serialize hash" do
<del> assert_match %r{<network>\s*<git type=\"symbol\">github</git>\s*</network>}, @contact.to_xml(:methods => :network)
<add> assert_match %r{<network>\s*<git type=\"symbol\">github</git>\s*</network>}, @contact.to_xml(methods: :network)
<ide> end
<ide>
<ide> test "should serialize yaml" do
<ide> def setup
<ide>
<ide> test "should call proc on object" do
<ide> proc = Proc.new { |options| options[:builder].tag!('nationality', 'unknown') }
<del> xml = @contact.to_xml(:procs => [ proc ])
<add> xml = @contact.to_xml(procs: [ proc ])
<ide> assert_match %r{<nationality>unknown</nationality>}, xml
<ide> end
<ide>
<ide> test 'should supply serializable to second proc argument' do
<ide> proc = Proc.new { |options, record| options[:builder].tag!('name-reverse', record.name.reverse) }
<del> xml = @contact.to_xml(:procs => [ proc ])
<add> xml = @contact.to_xml(procs: [ proc ])
<ide> assert_match %r{<name-reverse>kcats noraa</name-reverse>}, xml
<ide> end
<ide>
<ide> test "should serialize string correctly when type passed" do
<del> xml = @contact.to_xml :type => 'Contact'
<add> xml = @contact.to_xml type: 'Contact'
<ide> assert_match %r{<contact type="Contact">}, xml
<ide> assert_match %r{<name>aaron stack</name>}, xml
<ide> end
<ide>
<ide> test "include option with singular association" do
<del> xml = @contact.to_xml :include => :address, :indent => 0
<del> assert xml.include?(@contact.address.to_xml(:indent => 0, :skip_instruct => true))
<add> xml = @contact.to_xml include: :address, indent: 0
<add> assert xml.include?(@contact.address.to_xml(indent: 0, skip_instruct: true))
<ide> end
<ide>
<ide> test "include option with plural association" do
<del> xml = @contact.to_xml :include => :friends, :indent => 0
<add> xml = @contact.to_xml include: :friends, indent: 0
<ide> assert_match %r{<friends type="array">}, xml
<ide> assert_match %r{<friend type="Contact">}, xml
<ide> end
<ide> def to_ary
<ide>
<ide> test "include option with ary" do
<ide> @contact.friends = FriendList.new(@contact.friends)
<del> xml = @contact.to_xml :include => :friends, :indent => 0
<add> xml = @contact.to_xml include: :friends, indent: 0
<ide> assert_match %r{<friends type="array">}, xml
<ide> assert_match %r{<friend type="Contact">}, xml
<ide> end
<ide>
<ide> test "multiple includes" do
<del> xml = @contact.to_xml :indent => 0, :skip_instruct => true, :include => [ :address, :friends ]
<del> assert xml.include?(@contact.address.to_xml(:indent => 0, :skip_instruct => true))
<add> xml = @contact.to_xml indent: 0, skip_instruct: true, include: [ :address, :friends ]
<add> assert xml.include?(@contact.address.to_xml(indent: 0, skip_instruct: true))
<ide> assert_match %r{<friends type="array">}, xml
<ide> assert_match %r{<friend type="Contact">}, xml
<ide> end
<ide>
<ide> test "include with options" do
<del> xml = @contact.to_xml :indent => 0, :skip_instruct => true, :include => { :address => { :only => :city } }
<add> xml = @contact.to_xml indent: 0, skip_instruct: true, include: { address: { only: :city } }
<ide> assert xml.include?(%(><address><city>Springfield</city></address>))
<ide> end
<ide>
<ide> test "propagates skip_types option to included associations" do
<del> xml = @contact.to_xml :include => :friends, :indent => 0, :skip_types => true
<add> xml = @contact.to_xml include: :friends, indent: 0, skip_types: true
<ide> assert_match %r{<friends>}, xml
<ide> assert_match %r{<friend>}, xml
<ide> end
<ide>
<ide> test "propagates skip-types option to included associations and attributes" do
<del> xml = @contact.to_xml :skip_types => true, :include => :address, :indent => 0
<add> xml = @contact.to_xml skip_types: true, include: :address, indent: 0
<ide> assert_match %r{<address>}, xml
<ide> assert_match %r{<apt-number>}, xml
<ide> end
<ide>
<ide> test "propagates camelize option to included associations and attributes" do
<del> xml = @contact.to_xml :camelize => true, :include => :address, :indent => 0
<add> xml = @contact.to_xml camelize: true, include: :address, indent: 0
<ide> assert_match %r{<Address>}, xml
<ide> assert_match %r{<AptNumber type="integer">}, xml
<ide> end
<ide>
<ide> test "propagates dasherize option to included associations and attributes" do
<del> xml = @contact.to_xml :dasherize => false, :include => :address, :indent => 0
<add> xml = @contact.to_xml dasherize: false, include: :address, indent: 0
<ide> assert_match %r{<apt_number type="integer">}, xml
<ide> end
<ide>
<ide> test "don't propagate skip_types if skip_types is defined at the included association level" do
<del> xml = @contact.to_xml :skip_types => true, :include => { :address => { :skip_types => false } }, :indent => 0
<add> xml = @contact.to_xml skip_types: true, include: { address: { skip_types: false } }, indent: 0
<ide> assert_match %r{<address>}, xml
<ide> assert_match %r{<apt-number type="integer">}, xml
<ide> end
<ide>
<ide> test "don't propagate camelize if camelize is defined at the included association level" do
<del> xml = @contact.to_xml :camelize => true, :include => { :address => { :camelize => false } }, :indent => 0
<add> xml = @contact.to_xml camelize: true, include: { address: { camelize: false } }, indent: 0
<ide> assert_match %r{<address>}, xml
<ide> assert_match %r{<apt-number type="integer">}, xml
<ide> end
<ide>
<ide> test "don't propagate dasherize if dasherize is defined at the included association level" do
<del> xml = @contact.to_xml :dasherize => false, :include => { :address => { :dasherize => true } }, :indent => 0
<add> xml = @contact.to_xml dasherize: false, include: { address: { dasherize: true } }, indent: 0
<ide> assert_match %r{<address>}, xml
<ide> assert_match %r{<apt-number type="integer">}, xml
<ide> end
<ide><path>activemodel/test/cases/translation_test.rb
<ide> def setup
<ide> end
<ide>
<ide> def test_translated_model_attributes
<del> I18n.backend.store_translations 'en', :activemodel => {:attributes => {:person => {:name => 'person name attribute'} } }
<add> I18n.backend.store_translations 'en', activemodel: { attributes: { person: { name: 'person name attribute' } } }
<ide> assert_equal 'person name attribute', Person.human_attribute_name('name')
<ide> end
<ide>
<ide> def test_translated_model_attributes_with_default
<del> I18n.backend.store_translations 'en', :attributes => { :name => 'name default attribute' }
<add> I18n.backend.store_translations 'en', attributes: { name: 'name default attribute' }
<ide> assert_equal 'name default attribute', Person.human_attribute_name('name')
<ide> end
<ide>
<ide> def test_translated_model_attributes_using_default_option
<del> assert_equal 'name default attribute', Person.human_attribute_name('name', :default => "name default attribute")
<add> assert_equal 'name default attribute', Person.human_attribute_name('name', default: "name default attribute")
<ide> end
<ide>
<ide> def test_translated_model_attributes_using_default_option_as_symbol
<del> I18n.backend.store_translations 'en', :default_name => 'name default attribute'
<del> assert_equal 'name default attribute', Person.human_attribute_name('name', :default => :default_name)
<add> I18n.backend.store_translations 'en', default_name: 'name default attribute'
<add> assert_equal 'name default attribute', Person.human_attribute_name('name', default: :default_name)
<ide> end
<ide>
<ide> def test_translated_model_attributes_falling_back_to_default
<ide> assert_equal 'Name', Person.human_attribute_name('name')
<ide> end
<ide>
<ide> def test_translated_model_attributes_using_default_option_as_symbol_and_falling_back_to_default
<del> assert_equal 'Name', Person.human_attribute_name('name', :default => :default_name)
<add> assert_equal 'Name', Person.human_attribute_name('name', default: :default_name)
<ide> end
<ide>
<ide> def test_translated_model_attributes_with_symbols
<del> I18n.backend.store_translations 'en', :activemodel => {:attributes => {:person => {:name => 'person name attribute'} } }
<add> I18n.backend.store_translations 'en', activemodel: { attributes: { person: { name: 'person name attribute'} } }
<ide> assert_equal 'person name attribute', Person.human_attribute_name(:name)
<ide> end
<ide>
<ide> def test_translated_model_attributes_with_ancestor
<del> I18n.backend.store_translations 'en', :activemodel => {:attributes => {:child => {:name => 'child name attribute'} } }
<add> I18n.backend.store_translations 'en', activemodel: { attributes: { child: { name: 'child name attribute'} } }
<ide> assert_equal 'child name attribute', Child.human_attribute_name('name')
<ide> end
<ide>
<ide> def test_translated_model_attributes_with_ancestors_fallback
<del> I18n.backend.store_translations 'en', :activemodel => {:attributes => {:person => {:name => 'person name attribute'} } }
<add> I18n.backend.store_translations 'en', activemodel: { attributes: { person: { name: 'person name attribute'} } }
<ide> assert_equal 'person name attribute', Child.human_attribute_name('name')
<ide> end
<ide>
<ide> def test_translated_model_attributes_with_attribute_matching_namespaced_model_name
<del> I18n.backend.store_translations 'en', :activemodel => {:attributes => {:person => {:gender => 'person gender'}, :"person/gender" => {:attribute => 'person gender attribute'}}}
<add> I18n.backend.store_translations 'en', activemodel: { attributes: {
<add> person: { gender: 'person gender'},
<add> :"person/gender" => { attribute: 'person gender attribute' }
<add> } }
<ide>
<ide> assert_equal 'person gender', Person.human_attribute_name('gender')
<ide> assert_equal 'person gender attribute', Person::Gender.human_attribute_name('attribute')
<ide> end
<ide>
<ide> def test_translated_deeply_nested_model_attributes
<del> I18n.backend.store_translations 'en', :activemodel => {:attributes => {:"person/contacts/addresses" => {:street => 'Deeply Nested Address Street'}}}
<add> I18n.backend.store_translations 'en', activemodel: { attributes: { :"person/contacts/addresses" => { street: 'Deeply Nested Address Street' } } }
<ide> assert_equal 'Deeply Nested Address Street', Person.human_attribute_name('contacts.addresses.street')
<ide> end
<ide>
<ide> def test_translated_nested_model_attributes
<del> I18n.backend.store_translations 'en', :activemodel => {:attributes => {:"person/addresses" => {:street => 'Person Address Street'}}}
<add> I18n.backend.store_translations 'en', activemodel: { attributes: { :"person/addresses" => { street: 'Person Address Street' } } }
<ide> assert_equal 'Person Address Street', Person.human_attribute_name('addresses.street')
<ide> end
<ide>
<ide> def test_translated_nested_model_attributes_with_namespace_fallback
<del> I18n.backend.store_translations 'en', :activemodel => {:attributes => {:addresses => {:street => 'Cool Address Street'}}}
<add> I18n.backend.store_translations 'en', activemodel: { attributes: { addresses: { street: 'Cool Address Street' } } }
<ide> assert_equal 'Cool Address Street', Person.human_attribute_name('addresses.street')
<ide> end
<ide>
<ide> def test_translated_model_names
<del> I18n.backend.store_translations 'en', :activemodel => {:models => {:person => 'person model'} }
<add> I18n.backend.store_translations 'en', activemodel: { models: { person: 'person model' } }
<ide> assert_equal 'person model', Person.model_name.human
<ide> end
<ide>
<ide> def test_translated_model_names_with_sti
<del> I18n.backend.store_translations 'en', :activemodel => {:models => {:child => 'child model'} }
<add> I18n.backend.store_translations 'en', activemodel: { models: { child: 'child model' } }
<ide> assert_equal 'child model', Child.model_name.human
<ide> end
<ide>
<ide> def test_translated_model_names_with_ancestors_fallback
<del> I18n.backend.store_translations 'en', :activemodel => {:models => {:person => 'person model'} }
<add> I18n.backend.store_translations 'en', activemodel: { models: { person: 'person model' } }
<ide> assert_equal 'person model', Child.model_name.human
<ide> end
<ide>
<ide> def test_human_does_not_modify_options
<del> options = { :default => 'person model' }
<add> options = { default: 'person model' }
<ide> Person.model_name.human(options)
<del> assert_equal({ :default => 'person model' }, options)
<add> assert_equal({ default: 'person model' }, options)
<ide> end
<ide>
<ide> def test_human_attribute_name_does_not_modify_options
<del> options = { :default => 'Cool gender' }
<add> options = { default: 'Cool gender' }
<ide> Person.human_attribute_name('gender', options)
<del> assert_equal({ :default => 'Cool gender' }, options)
<add> assert_equal({ default: 'Cool gender' }, options)
<ide> end
<ide> end
<ide>
<ide><path>activemodel/test/cases/validations/acceptance_validation_test.rb
<ide> def test_terms_of_service_agreement
<ide> end
<ide>
<ide> def test_eula
<del> Topic.validates_acceptance_of(:eula, :message => "must be abided")
<add> Topic.validates_acceptance_of(:eula, message: "must be abided")
<ide>
<ide> t = Topic.new("title" => "We should be confirmed","eula" => "")
<ide> assert t.invalid?
<ide> def test_eula
<ide> end
<ide>
<ide> def test_terms_of_service_agreement_with_accept_value
<del> Topic.validates_acceptance_of(:terms_of_service, :accept => "I agree.")
<add> Topic.validates_acceptance_of(:terms_of_service, accept: "I agree.")
<ide>
<ide> t = Topic.new("title" => "We should be confirmed", "terms_of_service" => "")
<ide> assert t.invalid?
<ide><path>activemodel/test/cases/validations/conditional_validation_test.rb
<ide> def teardown
<ide>
<ide> def test_if_validation_using_method_true
<ide> # When the method returns true
<del> Topic.validates_length_of( :title, :maximum => 5, :too_long => "hoo %{count}", :if => :condition_is_true )
<add> Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}", if: :condition_is_true)
<ide> t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
<ide> assert t.invalid?
<ide> assert t.errors[:title].any?
<ide> def test_if_validation_using_method_true
<ide>
<ide> def test_unless_validation_using_method_true
<ide> # When the method returns true
<del> Topic.validates_length_of( :title, :maximum => 5, :too_long => "hoo %{count}", :unless => :condition_is_true )
<add> Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}", unless: :condition_is_true)
<ide> t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
<ide> assert t.valid?
<ide> assert t.errors[:title].empty?
<ide> end
<ide>
<ide> def test_if_validation_using_method_false
<ide> # When the method returns false
<del> Topic.validates_length_of( :title, :maximum => 5, :too_long => "hoo %{count}", :if => :condition_is_true_but_its_not )
<add> Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}", if: :condition_is_true_but_its_not)
<ide> t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
<ide> assert t.valid?
<ide> assert t.errors[:title].empty?
<ide> end
<ide>
<ide> def test_unless_validation_using_method_false
<ide> # When the method returns false
<del> Topic.validates_length_of( :title, :maximum => 5, :too_long => "hoo %{count}", :unless => :condition_is_true_but_its_not )
<add> Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}", unless: :condition_is_true_but_its_not)
<ide> t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
<ide> assert t.invalid?
<ide> assert t.errors[:title].any?
<ide> def test_unless_validation_using_method_false
<ide>
<ide> def test_if_validation_using_string_true
<ide> # When the evaluated string returns true
<del> Topic.validates_length_of( :title, :maximum => 5, :too_long => "hoo %{count}", :if => "a = 1; a == 1" )
<add> Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}", if: "a = 1; a == 1")
<ide> t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
<ide> assert t.invalid?
<ide> assert t.errors[:title].any?
<ide> def test_if_validation_using_string_true
<ide>
<ide> def test_unless_validation_using_string_true
<ide> # When the evaluated string returns true
<del> Topic.validates_length_of( :title, :maximum => 5, :too_long => "hoo %{count}", :unless => "a = 1; a == 1" )
<add> Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}", unless: "a = 1; a == 1")
<ide> t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
<ide> assert t.valid?
<ide> assert t.errors[:title].empty?
<ide> end
<ide>
<ide> def test_if_validation_using_string_false
<ide> # When the evaluated string returns false
<del> Topic.validates_length_of( :title, :maximum => 5, :too_long => "hoo %{count}", :if => "false")
<add> Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}", if: "false")
<ide> t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
<ide> assert t.valid?
<ide> assert t.errors[:title].empty?
<ide> end
<ide>
<ide> def test_unless_validation_using_string_false
<ide> # When the evaluated string returns false
<del> Topic.validates_length_of( :title, :maximum => 5, :too_long => "hoo %{count}", :unless => "false")
<add> Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}", unless: "false")
<ide> t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
<ide> assert t.invalid?
<ide> assert t.errors[:title].any?
<ide> def test_unless_validation_using_string_false
<ide>
<ide> def test_if_validation_using_block_true
<ide> # When the block returns true
<del> Topic.validates_length_of( :title, :maximum => 5, :too_long => "hoo %{count}",
<del> :if => Proc.new { |r| r.content.size > 4 } )
<add> Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}",
<add> if: Proc.new { |r| r.content.size > 4 })
<ide> t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
<ide> assert t.invalid?
<ide> assert t.errors[:title].any?
<ide> def test_if_validation_using_block_true
<ide>
<ide> def test_unless_validation_using_block_true
<ide> # When the block returns true
<del> Topic.validates_length_of( :title, :maximum => 5, :too_long => "hoo %{count}",
<del> :unless => Proc.new { |r| r.content.size > 4 } )
<add> Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}",
<add> unless: Proc.new { |r| r.content.size > 4 })
<ide> t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
<ide> assert t.valid?
<ide> assert t.errors[:title].empty?
<ide> end
<ide>
<ide> def test_if_validation_using_block_false
<ide> # When the block returns false
<del> Topic.validates_length_of( :title, :maximum => 5, :too_long => "hoo %{count}",
<del> :if => Proc.new { |r| r.title != "uhohuhoh"} )
<add> Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}",
<add> if: Proc.new { |r| r.title != "uhohuhoh"})
<ide> t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
<ide> assert t.valid?
<ide> assert t.errors[:title].empty?
<ide> end
<ide>
<ide> def test_unless_validation_using_block_false
<ide> # When the block returns false
<del> Topic.validates_length_of( :title, :maximum => 5, :too_long => "hoo %{count}",
<del> :unless => Proc.new { |r| r.title != "uhohuhoh"} )
<add> Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}",
<add> unless: Proc.new { |r| r.title != "uhohuhoh"} )
<ide> t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
<ide> assert t.invalid?
<ide> assert t.errors[:title].any?
<ide> def test_unless_validation_using_block_false
<ide> # ensure that it works correctly
<ide> def test_validation_with_if_as_string
<ide> Topic.validates_presence_of(:title)
<del> Topic.validates_presence_of(:author_name, :if => "title.to_s.match('important')")
<add> Topic.validates_presence_of(:author_name, if: "title.to_s.match('important')")
<ide>
<ide> t = Topic.new
<ide> assert t.invalid?, "A topic without a title should not be valid"
<ide><path>activemodel/test/cases/validations/confirmation_validation_test.rb
<ide> def teardown
<ide> def test_no_title_confirmation
<ide> Topic.validates_confirmation_of(:title)
<ide>
<del> t = Topic.new(:author_name => "Plutarch")
<add> t = Topic.new(author_name: "Plutarch")
<ide> assert t.valid?
<ide>
<ide> t.title_confirmation = "Parallel Lives"
<ide> def test_title_confirmation_with_i18n_attribute
<ide> I18n.load_path.clear
<ide> I18n.backend = I18n::Backend::Simple.new
<ide> I18n.backend.store_translations('en', {
<del> :errors => {:messages => {:confirmation => "doesn't match %{attribute}"}},
<del> :activemodel => {:attributes => {:topic => {:title => 'Test Title'}}}
<add> errors: { messages: { confirmation: "doesn't match %{attribute}" } },
<add> activemodel: { attributes: { topic: { title: 'Test Title'} } }
<ide> })
<ide>
<ide> Topic.validates_confirmation_of(:title)
<ide><path>activemodel/test/cases/validations/exclusion_validation_test.rb
<ide> def teardown
<ide> end
<ide>
<ide> def test_validates_exclusion_of
<del> Topic.validates_exclusion_of( :title, :in => %w( abe monkey ) )
<add> Topic.validates_exclusion_of(:title, in: %w( abe monkey ))
<ide>
<ide> assert Topic.new("title" => "something", "content" => "abc").valid?
<ide> assert Topic.new("title" => "monkey", "content" => "abc").invalid?
<ide> end
<ide>
<ide> def test_validates_exclusion_of_with_formatted_message
<del> Topic.validates_exclusion_of( :title, :in => %w( abe monkey ), :message => "option %{value} is restricted" )
<add> Topic.validates_exclusion_of(:title, in: %w( abe monkey ), message: "option %{value} is restricted")
<ide>
<ide> assert Topic.new("title" => "something", "content" => "abc")
<ide>
<ide> def test_validates_exclusion_of_with_formatted_message
<ide> end
<ide>
<ide> def test_validates_exclusion_of_with_within_option
<del> Topic.validates_exclusion_of( :title, :within => %w( abe monkey ) )
<add> Topic.validates_exclusion_of(:title, within: %w( abe monkey ))
<ide>
<ide> assert Topic.new("title" => "something", "content" => "abc")
<ide>
<ide> def test_validates_exclusion_of_with_within_option
<ide> end
<ide>
<ide> def test_validates_exclusion_of_for_ruby_class
<del> Person.validates_exclusion_of :karma, :in => %w( abe monkey )
<add> Person.validates_exclusion_of :karma, in: %w( abe monkey )
<ide>
<ide> p = Person.new
<ide> p.karma = "abe"
<ide> def test_validates_exclusion_of_for_ruby_class
<ide> end
<ide>
<ide> def test_validates_exclusion_of_with_lambda
<del> Topic.validates_exclusion_of :title, :in => lambda{ |topic| topic.author_name == "sikachu" ? %w( monkey elephant ) : %w( abe wasabi ) }
<add> Topic.validates_exclusion_of :title, in: lambda { |topic| topic.author_name == "sikachu" ? %w( monkey elephant ) : %w( abe wasabi ) }
<ide>
<ide> t = Topic.new
<ide> t.title = "elephant"
<ide> def test_validates_exclusion_of_with_lambda
<ide> end
<ide>
<ide> def test_validates_inclusion_of_with_symbol
<del> Person.validates_exclusion_of :karma, :in => :reserved_karmas
<add> Person.validates_exclusion_of :karma, in: :reserved_karmas
<ide>
<ide> p = Person.new
<ide> p.karma = "abe"
<ide><path>activemodel/test/cases/validations/format_validation_test.rb
<ide> def teardown
<ide> end
<ide>
<ide> def test_validate_format
<del> Topic.validates_format_of(:title, :content, :with => /\AValidation\smacros \w+!\z/, :message => "is bad data")
<add> Topic.validates_format_of(:title, :content, with: /\AValidation\smacros \w+!\z/, message: "is bad data")
<ide>
<ide> t = Topic.new("title" => "i'm incorrect", "content" => "Validation macros rule!")
<ide> assert t.invalid?, "Shouldn't be valid"
<ide> def test_validate_format
<ide> end
<ide>
<ide> def test_validate_format_with_allow_blank
<del> Topic.validates_format_of(:title, :with => /\AValidation\smacros \w+!\z/, :allow_blank => true)
<add> Topic.validates_format_of(:title, with: /\AValidation\smacros \w+!\z/, allow_blank: true)
<ide> assert Topic.new("title" => "Shouldn't be valid").invalid?
<ide> assert Topic.new("title" => "").valid?
<ide> assert Topic.new("title" => nil).valid?
<ide> def test_validate_format_with_allow_blank
<ide>
<ide> # testing ticket #3142
<ide> def test_validate_format_numeric
<del> Topic.validates_format_of(:title, :content, :with => /\A[1-9][0-9]*\z/, :message => "is bad data")
<add> Topic.validates_format_of(:title, :content, with: /\A[1-9][0-9]*\z/, message: "is bad data")
<ide>
<ide> t = Topic.new("title" => "72x", "content" => "6789")
<ide> assert t.invalid?, "Shouldn't be valid"
<ide> def test_validate_format_numeric
<ide> end
<ide>
<ide> def test_validate_format_with_formatted_message
<del> Topic.validates_format_of(:title, :with => /\AValid Title\z/, :message => "can't be %{value}")
<del> t = Topic.new(:title => 'Invalid title')
<add> Topic.validates_format_of(:title, with: /\AValid Title\z/, message: "can't be %{value}")
<add> t = Topic.new(title: 'Invalid title')
<ide> assert t.invalid?
<ide> assert_equal ["can't be Invalid title"], t.errors[:title]
<ide> end
<ide>
<ide> def test_validate_format_of_with_multiline_regexp_should_raise_error
<del> assert_raise(ArgumentError) { Topic.validates_format_of(:title, :with => /^Valid Title$/) }
<add> assert_raise(ArgumentError) { Topic.validates_format_of(:title, with: /^Valid Title$/) }
<ide> end
<ide>
<ide> def test_validate_format_of_with_multiline_regexp_and_option
<ide> assert_nothing_raised(ArgumentError) do
<del> Topic.validates_format_of(:title, :with => /^Valid Title$/, :multiline => true)
<add> Topic.validates_format_of(:title, with: /^Valid Title$/, multiline: true)
<ide> end
<ide> end
<ide>
<ide> def test_validate_format_with_not_option
<del> Topic.validates_format_of(:title, :without => /foo/, :message => "should not contain foo")
<add> Topic.validates_format_of(:title, without: /foo/, message: "should not contain foo")
<ide> t = Topic.new
<ide>
<ide> t.title = "foobar"
<ide> def test_validate_format_of_without_any_regexp_should_raise_error
<ide> end
<ide>
<ide> def test_validates_format_of_with_both_regexps_should_raise_error
<del> assert_raise(ArgumentError) { Topic.validates_format_of(:title, :with => /this/, :without => /that/) }
<add> assert_raise(ArgumentError) { Topic.validates_format_of(:title, with: /this/, without: /that/) }
<ide> end
<ide>
<ide> def test_validates_format_of_when_with_isnt_a_regexp_should_raise_error
<del> assert_raise(ArgumentError) { Topic.validates_format_of(:title, :with => "clearly not a regexp") }
<add> assert_raise(ArgumentError) { Topic.validates_format_of(:title, with: "clearly not a regexp") }
<ide> end
<ide>
<ide> def test_validates_format_of_when_not_isnt_a_regexp_should_raise_error
<del> assert_raise(ArgumentError) { Topic.validates_format_of(:title, :without => "clearly not a regexp") }
<add> assert_raise(ArgumentError) { Topic.validates_format_of(:title, without: "clearly not a regexp") }
<ide> end
<ide>
<ide> def test_validates_format_of_with_lambda
<del> Topic.validates_format_of :content, :with => lambda{ |topic| topic.title == "digit" ? /\A\d+\Z/ : /\A\S+\Z/ }
<add> Topic.validates_format_of :content, with: lambda { |topic| topic.title == "digit" ? /\A\d+\Z/ : /\A\S+\Z/ }
<ide>
<ide> t = Topic.new
<ide> t.title = "digit"
<ide> def test_validates_format_of_with_lambda
<ide> end
<ide>
<ide> def test_validates_format_of_without_lambda
<del> Topic.validates_format_of :content, :without => lambda{ |topic| topic.title == "characters" ? /\A\d+\Z/ : /\A\S+\Z/ }
<add> Topic.validates_format_of :content, without: lambda { |topic| topic.title == "characters" ? /\A\d+\Z/ : /\A\S+\Z/ }
<ide>
<ide> t = Topic.new
<ide> t.title = "characters"
<ide> def test_validates_format_of_without_lambda
<ide> end
<ide>
<ide> def test_validates_format_of_for_ruby_class
<del> Person.validates_format_of :karma, :with => /\A\d+\Z/
<add> Person.validates_format_of :karma, with: /\A\d+\Z/
<ide>
<ide> p = Person.new
<ide> p.karma = "Pixies"
<ide><path>activemodel/test/cases/validations/i18n_generate_message_validation_test.rb
<ide> def setup
<ide>
<ide> # validates_inclusion_of: generate_message(attr_name, :inclusion, message: custom_message, value: value)
<ide> def test_generate_message_inclusion_with_default_message
<del> assert_equal 'is not included in the list', @person.errors.generate_message(:title, :inclusion, :value => 'title')
<add> assert_equal 'is not included in the list', @person.errors.generate_message(:title, :inclusion, value: 'title')
<ide> end
<ide>
<ide> def test_generate_message_inclusion_with_custom_message
<del> assert_equal 'custom message title', @person.errors.generate_message(:title, :inclusion, :message => 'custom message %{value}', :value => 'title')
<add> assert_equal 'custom message title', @person.errors.generate_message(:title, :inclusion, message: 'custom message %{value}', value: 'title')
<ide> end
<ide>
<ide> # validates_exclusion_of: generate_message(attr_name, :exclusion, message: custom_message, value: value)
<ide> def test_generate_message_exclusion_with_default_message
<del> assert_equal 'is reserved', @person.errors.generate_message(:title, :exclusion, :value => 'title')
<add> assert_equal 'is reserved', @person.errors.generate_message(:title, :exclusion, value: 'title')
<ide> end
<ide>
<ide> def test_generate_message_exclusion_with_custom_message
<del> assert_equal 'custom message title', @person.errors.generate_message(:title, :exclusion, :message => 'custom message %{value}', :value => 'title')
<add> assert_equal 'custom message title', @person.errors.generate_message(:title, :exclusion, message: 'custom message %{value}', value: 'title')
<ide> end
<ide>
<ide> # validates_format_of: generate_message(attr_name, :invalid, message: custom_message, value: value)
<ide> def test_generate_message_invalid_with_default_message
<del> assert_equal 'is invalid', @person.errors.generate_message(:title, :invalid, :value => 'title')
<add> assert_equal 'is invalid', @person.errors.generate_message(:title, :invalid, value: 'title')
<ide> end
<ide>
<ide> def test_generate_message_invalid_with_custom_message
<del> assert_equal 'custom message title', @person.errors.generate_message(:title, :invalid, :message => 'custom message %{value}', :value => 'title')
<add> assert_equal 'custom message title', @person.errors.generate_message(:title, :invalid, message: 'custom message %{value}', value: 'title')
<ide> end
<ide>
<ide> # validates_confirmation_of: generate_message(attr_name, :confirmation, message: custom_message)
<ide> def test_generate_message_confirmation_with_default_message
<ide> end
<ide>
<ide> def test_generate_message_confirmation_with_custom_message
<del> assert_equal 'custom message', @person.errors.generate_message(:title, :confirmation, :message => 'custom message')
<add> assert_equal 'custom message', @person.errors.generate_message(:title, :confirmation, message: 'custom message')
<ide> end
<ide>
<ide> # validates_acceptance_of: generate_message(attr_name, :accepted, message: custom_message)
<ide> def test_generate_message_accepted_with_default_message
<ide> end
<ide>
<ide> def test_generate_message_accepted_with_custom_message
<del> assert_equal 'custom message', @person.errors.generate_message(:title, :accepted, :message => 'custom message')
<add> assert_equal 'custom message', @person.errors.generate_message(:title, :accepted, message: 'custom message')
<ide> end
<ide>
<ide> # add_on_empty: generate_message(attr, :empty, message: custom_message)
<ide> def test_generate_message_empty_with_default_message
<ide> end
<ide>
<ide> def test_generate_message_empty_with_custom_message
<del> assert_equal 'custom message', @person.errors.generate_message(:title, :empty, :message => 'custom message')
<add> assert_equal 'custom message', @person.errors.generate_message(:title, :empty, message: 'custom message')
<ide> end
<ide>
<ide> # add_on_blank: generate_message(attr, :blank, message: custom_message)
<ide> def test_generate_message_blank_with_default_message
<ide> end
<ide>
<ide> def test_generate_message_blank_with_custom_message
<del> assert_equal 'custom message', @person.errors.generate_message(:title, :blank, :message => 'custom message')
<add> assert_equal 'custom message', @person.errors.generate_message(:title, :blank, message: 'custom message')
<ide> end
<ide>
<ide> # validates_length_of: generate_message(attr, :too_long, message: custom_message, count: option_value.end)
<ide> def test_generate_message_too_long_with_default_message
<del> assert_equal "is too long (maximum is 10 characters)", @person.errors.generate_message(:title, :too_long, :count => 10)
<add> assert_equal "is too long (maximum is 10 characters)", @person.errors.generate_message(:title, :too_long, count: 10)
<ide> end
<ide>
<ide> def test_generate_message_too_long_with_custom_message
<del> assert_equal 'custom message 10', @person.errors.generate_message(:title, :too_long, :message => 'custom message %{count}', :count => 10)
<add> assert_equal 'custom message 10', @person.errors.generate_message(:title, :too_long, message: 'custom message %{count}', count: 10)
<ide> end
<ide>
<ide> # validates_length_of: generate_message(attr, :too_short, default: custom_message, count: option_value.begin)
<ide> def test_generate_message_too_short_with_default_message
<del> assert_equal "is too short (minimum is 10 characters)", @person.errors.generate_message(:title, :too_short, :count => 10)
<add> assert_equal "is too short (minimum is 10 characters)", @person.errors.generate_message(:title, :too_short, count: 10)
<ide> end
<ide>
<ide> def test_generate_message_too_short_with_custom_message
<del> assert_equal 'custom message 10', @person.errors.generate_message(:title, :too_short, :message => 'custom message %{count}', :count => 10)
<add> assert_equal 'custom message 10', @person.errors.generate_message(:title, :too_short, message: 'custom message %{count}', count: 10)
<ide> end
<ide>
<ide> # validates_length_of: generate_message(attr, :wrong_length, message: custom_message, count: option_value)
<ide> def test_generate_message_wrong_length_with_default_message
<del> assert_equal "is the wrong length (should be 10 characters)", @person.errors.generate_message(:title, :wrong_length, :count => 10)
<add> assert_equal "is the wrong length (should be 10 characters)", @person.errors.generate_message(:title, :wrong_length, count: 10)
<ide> end
<ide>
<ide> def test_generate_message_wrong_length_with_custom_message
<del> assert_equal 'custom message 10', @person.errors.generate_message(:title, :wrong_length, :message => 'custom message %{count}', :count => 10)
<add> assert_equal 'custom message 10', @person.errors.generate_message(:title, :wrong_length, message: 'custom message %{count}', count: 10)
<ide> end
<ide>
<ide> # validates_numericality_of: generate_message(attr_name, :not_a_number, value: raw_value, message: custom_message)
<ide> def test_generate_message_not_a_number_with_default_message
<del> assert_equal "is not a number", @person.errors.generate_message(:title, :not_a_number, :value => 'title')
<add> assert_equal "is not a number", @person.errors.generate_message(:title, :not_a_number, value: 'title')
<ide> end
<ide>
<ide> def test_generate_message_not_a_number_with_custom_message
<del> assert_equal 'custom message title', @person.errors.generate_message(:title, :not_a_number, :message => 'custom message %{value}', :value => 'title')
<add> assert_equal 'custom message title', @person.errors.generate_message(:title, :not_a_number, message: 'custom message %{value}', value: 'title')
<ide> end
<ide>
<ide> # validates_numericality_of: generate_message(attr_name, option, value: raw_value, default: custom_message)
<ide> def test_generate_message_greater_than_with_default_message
<del> assert_equal "must be greater than 10", @person.errors.generate_message(:title, :greater_than, :value => 'title', :count => 10)
<add> assert_equal "must be greater than 10", @person.errors.generate_message(:title, :greater_than, value: 'title', count: 10)
<ide> end
<ide>
<ide> def test_generate_message_greater_than_or_equal_to_with_default_message
<del> assert_equal "must be greater than or equal to 10", @person.errors.generate_message(:title, :greater_than_or_equal_to, :value => 'title', :count => 10)
<add> assert_equal "must be greater than or equal to 10", @person.errors.generate_message(:title, :greater_than_or_equal_to, value: 'title', count: 10)
<ide> end
<ide>
<ide> def test_generate_message_equal_to_with_default_message
<del> assert_equal "must be equal to 10", @person.errors.generate_message(:title, :equal_to, :value => 'title', :count => 10)
<add> assert_equal "must be equal to 10", @person.errors.generate_message(:title, :equal_to, value: 'title', count: 10)
<ide> end
<ide>
<ide> def test_generate_message_less_than_with_default_message
<del> assert_equal "must be less than 10", @person.errors.generate_message(:title, :less_than, :value => 'title', :count => 10)
<add> assert_equal "must be less than 10", @person.errors.generate_message(:title, :less_than, value: 'title', count: 10)
<ide> end
<ide>
<ide> def test_generate_message_less_than_or_equal_to_with_default_message
<del> assert_equal "must be less than or equal to 10", @person.errors.generate_message(:title, :less_than_or_equal_to, :value => 'title', :count => 10)
<add> assert_equal "must be less than or equal to 10", @person.errors.generate_message(:title, :less_than_or_equal_to, value: 'title', count: 10)
<ide> end
<ide>
<ide> def test_generate_message_odd_with_default_message
<del> assert_equal "must be odd", @person.errors.generate_message(:title, :odd, :value => 'title', :count => 10)
<add> assert_equal "must be odd", @person.errors.generate_message(:title, :odd, value: 'title', count: 10)
<ide> end
<ide>
<ide> def test_generate_message_even_with_default_message
<del> assert_equal "must be even", @person.errors.generate_message(:title, :even, :value => 'title', :count => 10)
<add> assert_equal "must be even", @person.errors.generate_message(:title, :even, value: 'title', count: 10)
<ide> end
<ide> end
<ide><path>activemodel/test/cases/validations/i18n_validation_test.rb
<ide> def setup
<ide> @old_load_path, @old_backend = I18n.load_path.dup, I18n.backend
<ide> I18n.load_path.clear
<ide> I18n.backend = I18n::Backend::Simple.new
<del> I18n.backend.store_translations('en', :errors => {:messages => {:custom => nil}})
<add> I18n.backend.store_translations('en', errors: { messages: { custom: nil } })
<ide> end
<ide>
<ide> def teardown
<ide> def teardown
<ide> end
<ide>
<ide> def test_full_message_encoding
<del> I18n.backend.store_translations('en', :errors => {
<del> :messages => { :too_short => '猫舌' }})
<del> Person.validates_length_of :title, :within => 3..5
<add> I18n.backend.store_translations('en', errors: {
<add> messages: { too_short: '猫舌' } })
<add> Person.validates_length_of :title, within: 3..5
<ide> @person.valid?
<ide> assert_equal ['Title 猫舌'], @person.errors.full_messages
<ide> end
<ide>
<ide> def test_errors_full_messages_translates_human_attribute_name_for_model_attributes
<ide> @person.errors.add(:name, 'not found')
<del> Person.expects(:human_attribute_name).with(:name, :default => 'Name').returns("Person's name")
<add> Person.expects(:human_attribute_name).with(:name, default: 'Name').returns("Person's name")
<ide> assert_equal ["Person's name not found"], @person.errors.full_messages
<ide> end
<ide>
<ide> def test_errors_full_messages_uses_format
<del> I18n.backend.store_translations('en', :errors => {:format => "Field %{attribute} %{message}"})
<add> I18n.backend.store_translations('en', errors: { format: "Field %{attribute} %{message}" })
<ide> @person.errors.add('name', 'empty')
<ide> assert_equal ["Field Name empty"], @person.errors.full_messages
<ide> end
<ide> def test_errors_full_messages_uses_format
<ide> COMMON_CASES = [
<ide> # [ case, validation_options, generate_message_options]
<ide> [ "given no options", {}, {}],
<del> [ "given custom message", {:message => "custom"}, {:message => "custom"}],
<del> [ "given if condition", {:if => lambda { true }}, {}],
<del> [ "given unless condition", {:unless => lambda { false }}, {}],
<del> [ "given option that is not reserved", {:format => "jpg"}, {:format => "jpg" }]
<add> [ "given custom message", { message: "custom" }, { message: "custom" }],
<add> [ "given if condition", { if: lambda { true }}, {}],
<add> [ "given unless condition", { unless: lambda { false }}, {}],
<add> [ "given option that is not reserved", { format: "jpg" }, { format: "jpg" }]
<ide> ]
<ide>
<ide> # validates_confirmation_of w/ mocha
<ide> def test_errors_full_messages_uses_format
<ide> test "validates_confirmation_of on generated message #{name}" do
<ide> Person.validates_confirmation_of :title, validation_options
<ide> @person.title_confirmation = 'foo'
<del> @person.errors.expects(:generate_message).with(:title_confirmation, :confirmation, generate_message_options.merge(:attribute => 'Title'))
<add> @person.errors.expects(:generate_message).with(:title_confirmation, :confirmation, generate_message_options.merge(attribute: 'Title'))
<ide> @person.valid?
<ide> end
<ide> end
<ide> def test_errors_full_messages_uses_format
<ide>
<ide> COMMON_CASES.each do |name, validation_options, generate_message_options|
<ide> test "validates_acceptance_of on generated message #{name}" do
<del> Person.validates_acceptance_of :title, validation_options.merge(:allow_nil => false)
<add> Person.validates_acceptance_of :title, validation_options.merge(allow_nil: false)
<ide> @person.errors.expects(:generate_message).with(:title, :accepted, generate_message_options)
<ide> @person.valid?
<ide> end
<ide> def test_errors_full_messages_uses_format
<ide>
<ide> COMMON_CASES.each do |name, validation_options, generate_message_options|
<ide> test "validates_length_of for :withing on generated message when too short #{name}" do
<del> Person.validates_length_of :title, validation_options.merge(:within => 3..5)
<del> @person.errors.expects(:generate_message).with(:title, :too_short, generate_message_options.merge(:count => 3))
<add> Person.validates_length_of :title, validation_options.merge(within: 3..5)
<add> @person.errors.expects(:generate_message).with(:title, :too_short, generate_message_options.merge(count: 3))
<ide> @person.valid?
<ide> end
<ide> end
<ide> def test_errors_full_messages_uses_format
<ide>
<ide> COMMON_CASES.each do |name, validation_options, generate_message_options|
<ide> test "validates_length_of for :too_long generated message #{name}" do
<del> Person.validates_length_of :title, validation_options.merge(:within => 3..5)
<add> Person.validates_length_of :title, validation_options.merge(within: 3..5)
<ide> @person.title = 'this title is too long'
<del> @person.errors.expects(:generate_message).with(:title, :too_long, generate_message_options.merge(:count => 5))
<add> @person.errors.expects(:generate_message).with(:title, :too_long, generate_message_options.merge(count: 5))
<ide> @person.valid?
<ide> end
<ide> end
<ide> def test_errors_full_messages_uses_format
<ide>
<ide> COMMON_CASES.each do |name, validation_options, generate_message_options|
<ide> test "validates_length_of for :is on generated message #{name}" do
<del> Person.validates_length_of :title, validation_options.merge(:is => 5)
<del> @person.errors.expects(:generate_message).with(:title, :wrong_length, generate_message_options.merge(:count => 5))
<add> Person.validates_length_of :title, validation_options.merge(is: 5)
<add> @person.errors.expects(:generate_message).with(:title, :wrong_length, generate_message_options.merge(count: 5))
<ide> @person.valid?
<ide> end
<ide> end
<ide> def test_errors_full_messages_uses_format
<ide>
<ide> COMMON_CASES.each do |name, validation_options, generate_message_options|
<ide> test "validates_format_of on generated message #{name}" do
<del> Person.validates_format_of :title, validation_options.merge(:with => /\A[1-9][0-9]*\z/)
<add> Person.validates_format_of :title, validation_options.merge(with: /\A[1-9][0-9]*\z/)
<ide> @person.title = '72x'
<del> @person.errors.expects(:generate_message).with(:title, :invalid, generate_message_options.merge(:value => '72x'))
<add> @person.errors.expects(:generate_message).with(:title, :invalid, generate_message_options.merge(value: '72x'))
<ide> @person.valid?
<ide> end
<ide> end
<ide> def test_errors_full_messages_uses_format
<ide>
<ide> COMMON_CASES.each do |name, validation_options, generate_message_options|
<ide> test "validates_inclusion_of on generated message #{name}" do
<del> Person.validates_inclusion_of :title, validation_options.merge(:in => %w(a b c))
<add> Person.validates_inclusion_of :title, validation_options.merge(in: %w(a b c))
<ide> @person.title = 'z'
<del> @person.errors.expects(:generate_message).with(:title, :inclusion, generate_message_options.merge(:value => 'z'))
<add> @person.errors.expects(:generate_message).with(:title, :inclusion, generate_message_options.merge(value: 'z'))
<ide> @person.valid?
<ide> end
<ide> end
<ide> def test_errors_full_messages_uses_format
<ide>
<ide> COMMON_CASES.each do |name, validation_options, generate_message_options|
<ide> test "validates_inclusion_of using :within on generated message #{name}" do
<del> Person.validates_inclusion_of :title, validation_options.merge(:within => %w(a b c))
<add> Person.validates_inclusion_of :title, validation_options.merge(within: %w(a b c))
<ide> @person.title = 'z'
<del> @person.errors.expects(:generate_message).with(:title, :inclusion, generate_message_options.merge(:value => 'z'))
<add> @person.errors.expects(:generate_message).with(:title, :inclusion, generate_message_options.merge(value: 'z'))
<ide> @person.valid?
<ide> end
<ide> end
<ide> def test_errors_full_messages_uses_format
<ide>
<ide> COMMON_CASES.each do |name, validation_options, generate_message_options|
<ide> test "validates_exclusion_of generated message #{name}" do
<del> Person.validates_exclusion_of :title, validation_options.merge(:in => %w(a b c))
<add> Person.validates_exclusion_of :title, validation_options.merge(in: %w(a b c))
<ide> @person.title = 'a'
<del> @person.errors.expects(:generate_message).with(:title, :exclusion, generate_message_options.merge(:value => 'a'))
<add> @person.errors.expects(:generate_message).with(:title, :exclusion, generate_message_options.merge(value: 'a'))
<ide> @person.valid?
<ide> end
<ide> end
<ide> def test_errors_full_messages_uses_format
<ide>
<ide> COMMON_CASES.each do |name, validation_options, generate_message_options|
<ide> test "validates_exclusion_of using :within generated message #{name}" do
<del> Person.validates_exclusion_of :title, validation_options.merge(:within => %w(a b c))
<add> Person.validates_exclusion_of :title, validation_options.merge(within: %w(a b c))
<ide> @person.title = 'a'
<del> @person.errors.expects(:generate_message).with(:title, :exclusion, generate_message_options.merge(:value => 'a'))
<add> @person.errors.expects(:generate_message).with(:title, :exclusion, generate_message_options.merge(value: 'a'))
<ide> @person.valid?
<ide> end
<ide> end
<ide> def test_errors_full_messages_uses_format
<ide> test "validates_numericality_of generated message #{name}" do
<ide> Person.validates_numericality_of :title, validation_options
<ide> @person.title = 'a'
<del> @person.errors.expects(:generate_message).with(:title, :not_a_number, generate_message_options.merge(:value => 'a'))
<add> @person.errors.expects(:generate_message).with(:title, :not_a_number, generate_message_options.merge(value: 'a'))
<ide> @person.valid?
<ide> end
<ide> end
<ide> def test_errors_full_messages_uses_format
<ide>
<ide> COMMON_CASES.each do |name, validation_options, generate_message_options|
<ide> test "validates_numericality_of for :only_integer on generated message #{name}" do
<del> Person.validates_numericality_of :title, validation_options.merge(:only_integer => true)
<add> Person.validates_numericality_of :title, validation_options.merge(only_integer: true)
<ide> @person.title = '0.0'
<del> @person.errors.expects(:generate_message).with(:title, :not_an_integer, generate_message_options.merge(:value => '0.0'))
<add> @person.errors.expects(:generate_message).with(:title, :not_an_integer, generate_message_options.merge(value: '0.0'))
<ide> @person.valid?
<ide> end
<ide> end
<ide> def test_errors_full_messages_uses_format
<ide>
<ide> COMMON_CASES.each do |name, validation_options, generate_message_options|
<ide> test "validates_numericality_of for :odd on generated message #{name}" do
<del> Person.validates_numericality_of :title, validation_options.merge(:only_integer => true, :odd => true)
<add> Person.validates_numericality_of :title, validation_options.merge(only_integer: true, odd: true)
<ide> @person.title = 0
<del> @person.errors.expects(:generate_message).with(:title, :odd, generate_message_options.merge(:value => 0))
<add> @person.errors.expects(:generate_message).with(:title, :odd, generate_message_options.merge(value: 0))
<ide> @person.valid?
<ide> end
<ide> end
<ide> def test_errors_full_messages_uses_format
<ide>
<ide> COMMON_CASES.each do |name, validation_options, generate_message_options|
<ide> test "validates_numericality_of for :less_than on generated message #{name}" do
<del> Person.validates_numericality_of :title, validation_options.merge(:only_integer => true, :less_than => 0)
<add> Person.validates_numericality_of :title, validation_options.merge(only_integer: true, less_than: 0)
<ide> @person.title = 1
<del> @person.errors.expects(:generate_message).with(:title, :less_than, generate_message_options.merge(:value => 1, :count => 0))
<add> @person.errors.expects(:generate_message).with(:title, :less_than, generate_message_options.merge(value: 1, count: 0))
<ide> @person.valid?
<ide> end
<ide> end
<ide> def self.set_expectations_for_validation(validation, error_type, &block_that_set
<ide> end
<ide> # test "validates_confirmation_of finds custom model key translation when blank"
<ide> test "#{validation} finds custom model key translation when #{error_type}" do
<del> I18n.backend.store_translations 'en', :activemodel => {:errors => {:models => {:person => {:attributes => {attribute => {error_type => 'custom message'}}}}}}
<del> I18n.backend.store_translations 'en', :errors => {:messages => {error_type => 'global message'}}
<add> I18n.backend.store_translations 'en', activemodel: { errors: { models: { person: { attributes: { attribute => { error_type => 'custom message' } } } } } }
<add> I18n.backend.store_translations 'en', errors: { messages: { error_type => 'global message'}}
<ide>
<ide> yield(@person, {})
<ide> @person.valid?
<ide> def self.set_expectations_for_validation(validation, error_type, &block_that_set
<ide>
<ide> # test "validates_confirmation_of finds custom model key translation with interpolation when blank"
<ide> test "#{validation} finds custom model key translation with interpolation when #{error_type}" do
<del> I18n.backend.store_translations 'en', :activemodel => {:errors => {:models => {:person => {:attributes => {attribute => {error_type => 'custom message with %{extra}'}}}}}}
<del> I18n.backend.store_translations 'en', :errors => {:messages => {error_type => 'global message'}}
<add> I18n.backend.store_translations 'en', activemodel: { errors: { models: { person: { attributes: { attribute => { error_type => 'custom message with %{extra}' } } } } } }
<add> I18n.backend.store_translations 'en', errors: { messages: {error_type => 'global message'} }
<ide>
<del> yield(@person, {:extra => "extra information"})
<add> yield(@person, { extra: "extra information" })
<ide> @person.valid?
<ide> assert_equal ['custom message with extra information'], @person.errors[attribute]
<ide> end
<ide>
<ide> # test "validates_confirmation_of finds global default key translation when blank"
<ide> test "#{validation} finds global default key translation when #{error_type}" do
<del> I18n.backend.store_translations 'en', :errors => {:messages => {error_type => 'global message'}}
<add> I18n.backend.store_translations 'en', errors: { messages: {error_type => 'global message'} }
<ide>
<ide> yield(@person, {})
<ide> @person.valid?
<ide> def self.set_expectations_for_validation(validation, error_type, &block_that_set
<ide> # validates_acceptance_of w/o mocha
<ide>
<ide> set_expectations_for_validation "validates_acceptance_of", :accepted do |person, options_to_merge|
<del> Person.validates_acceptance_of :title, options_to_merge.merge(:allow_nil => false)
<add> Person.validates_acceptance_of :title, options_to_merge.merge(allow_nil: false)
<ide> end
<ide>
<ide> # validates_presence_of w/o mocha
<ide> def self.set_expectations_for_validation(validation, error_type, &block_that_set
<ide> # validates_length_of :within w/o mocha
<ide>
<ide> set_expectations_for_validation "validates_length_of", :too_short do |person, options_to_merge|
<del> Person.validates_length_of :title, options_to_merge.merge(:within => 3..5)
<add> Person.validates_length_of :title, options_to_merge.merge(within: 3..5)
<ide> end
<ide>
<ide> set_expectations_for_validation "validates_length_of", :too_long do |person, options_to_merge|
<del> Person.validates_length_of :title, options_to_merge.merge(:within => 3..5)
<add> Person.validates_length_of :title, options_to_merge.merge(within: 3..5)
<ide> person.title = "too long"
<ide> end
<ide>
<ide> # validates_length_of :is w/o mocha
<ide>
<ide> set_expectations_for_validation "validates_length_of", :wrong_length do |person, options_to_merge|
<del> Person.validates_length_of :title, options_to_merge.merge(:is => 5)
<add> Person.validates_length_of :title, options_to_merge.merge(is: 5)
<ide> end
<ide>
<ide> # validates_format_of w/o mocha
<ide>
<ide> set_expectations_for_validation "validates_format_of", :invalid do |person, options_to_merge|
<del> Person.validates_format_of :title, options_to_merge.merge(:with => /\A[1-9][0-9]*\z/)
<add> Person.validates_format_of :title, options_to_merge.merge(with: /\A[1-9][0-9]*\z/)
<ide> end
<ide>
<ide> # validates_inclusion_of w/o mocha
<ide>
<ide> set_expectations_for_validation "validates_inclusion_of", :inclusion do |person, options_to_merge|
<del> Person.validates_inclusion_of :title, options_to_merge.merge(:in => %w(a b c))
<add> Person.validates_inclusion_of :title, options_to_merge.merge(in: %w(a b c))
<ide> end
<ide>
<ide> # validates_exclusion_of w/o mocha
<ide>
<ide> set_expectations_for_validation "validates_exclusion_of", :exclusion do |person, options_to_merge|
<del> Person.validates_exclusion_of :title, options_to_merge.merge(:in => %w(a b c))
<add> Person.validates_exclusion_of :title, options_to_merge.merge(in: %w(a b c))
<ide> person.title = 'a'
<ide> end
<ide>
<ide> def self.set_expectations_for_validation(validation, error_type, &block_that_set
<ide> # validates_numericality_of with :only_integer w/o mocha
<ide>
<ide> set_expectations_for_validation "validates_numericality_of", :not_an_integer do |person, options_to_merge|
<del> Person.validates_numericality_of :title, options_to_merge.merge(:only_integer => true)
<add> Person.validates_numericality_of :title, options_to_merge.merge(only_integer: true)
<ide> person.title = '1.0'
<ide> end
<ide>
<ide> # validates_numericality_of :odd w/o mocha
<ide>
<ide> set_expectations_for_validation "validates_numericality_of", :odd do |person, options_to_merge|
<del> Person.validates_numericality_of :title, options_to_merge.merge(:only_integer => true, :odd => true)
<add> Person.validates_numericality_of :title, options_to_merge.merge(only_integer: true, odd: true)
<ide> person.title = 0
<ide> end
<ide>
<ide> # validates_numericality_of :less_than w/o mocha
<ide>
<ide> set_expectations_for_validation "validates_numericality_of", :less_than do |person, options_to_merge|
<del> Person.validates_numericality_of :title, options_to_merge.merge(:only_integer => true, :less_than => 0)
<add> Person.validates_numericality_of :title, options_to_merge.merge(only_integer: true, less_than: 0)
<ide> person.title = 1
<ide> end
<ide>
<ide> # test with validates_with
<ide>
<ide> def test_validations_with_message_symbol_must_translate
<del> I18n.backend.store_translations 'en', :errors => {:messages => {:custom_error => "I am a custom error"}}
<del> Person.validates_presence_of :title, :message => :custom_error
<add> I18n.backend.store_translations 'en', errors: { messages: { custom_error: "I am a custom error" } }
<add> Person.validates_presence_of :title, message: :custom_error
<ide> @person.title = nil
<ide> @person.valid?
<ide> assert_equal ["I am a custom error"], @person.errors[:title]
<ide> end
<ide>
<ide> def test_validates_with_message_symbol_must_translate_per_attribute
<del> I18n.backend.store_translations 'en', :activemodel => {:errors => {:models => {:person => {:attributes => {:title => {:custom_error => "I am a custom error"}}}}}}
<del> Person.validates_presence_of :title, :message => :custom_error
<add> I18n.backend.store_translations 'en', activemodel: { errors: { models: { person: { attributes: { title: { custom_error: "I am a custom error" } } } } } }
<add> Person.validates_presence_of :title, message: :custom_error
<ide> @person.title = nil
<ide> @person.valid?
<ide> assert_equal ["I am a custom error"], @person.errors[:title]
<ide> end
<ide>
<ide> def test_validates_with_message_symbol_must_translate_per_model
<del> I18n.backend.store_translations 'en', :activemodel => {:errors => {:models => {:person => {:custom_error => "I am a custom error"}}}}
<del> Person.validates_presence_of :title, :message => :custom_error
<add> I18n.backend.store_translations 'en', activemodel: { errors: { models: { person: { custom_error: "I am a custom error" } } } }
<add> Person.validates_presence_of :title, message: :custom_error
<ide> @person.title = nil
<ide> @person.valid?
<ide> assert_equal ["I am a custom error"], @person.errors[:title]
<ide> end
<ide>
<ide> def test_validates_with_message_string
<del> Person.validates_presence_of :title, :message => "I am a custom error"
<add> Person.validates_presence_of :title, message: "I am a custom error"
<ide> @person.title = nil
<ide> @person.valid?
<ide> assert_equal ["I am a custom error"], @person.errors[:title]
<ide> end
<del>
<ide> end
<ide><path>activemodel/test/cases/validations/inclusion_validation_test.rb
<ide> def teardown
<ide> end
<ide>
<ide> def test_validates_inclusion_of_range
<del> Topic.validates_inclusion_of( :title, :in => 'aaa'..'bbb' )
<add> Topic.validates_inclusion_of(:title, in: 'aaa'..'bbb')
<ide> assert Topic.new("title" => "bbc", "content" => "abc").invalid?
<ide> assert Topic.new("title" => "aa", "content" => "abc").invalid?
<ide> assert Topic.new("title" => "aaa", "content" => "abc").valid?
<ide> def test_validates_inclusion_of_range
<ide> end
<ide>
<ide> def test_validates_inclusion_of
<del> Topic.validates_inclusion_of( :title, :in => %w( a b c d e f g ) )
<add> Topic.validates_inclusion_of(:title, in: %w( a b c d e f g ))
<ide>
<ide> assert Topic.new("title" => "a!", "content" => "abc").invalid?
<ide> assert Topic.new("title" => "a b", "content" => "abc").invalid?
<ide> def test_validates_inclusion_of
<ide> assert t.errors[:title].any?
<ide> assert_equal ["is not included in the list"], t.errors[:title]
<ide>
<del> assert_raise(ArgumentError) { Topic.validates_inclusion_of( :title, :in => nil ) }
<del> assert_raise(ArgumentError) { Topic.validates_inclusion_of( :title, :in => 0) }
<add> assert_raise(ArgumentError) { Topic.validates_inclusion_of(:title, in: nil) }
<add> assert_raise(ArgumentError) { Topic.validates_inclusion_of(:title, in: 0) }
<ide>
<del> assert_nothing_raised(ArgumentError) { Topic.validates_inclusion_of( :title, :in => "hi!" ) }
<del> assert_nothing_raised(ArgumentError) { Topic.validates_inclusion_of( :title, :in => {} ) }
<del> assert_nothing_raised(ArgumentError) { Topic.validates_inclusion_of( :title, :in => [] ) }
<add> assert_nothing_raised(ArgumentError) { Topic.validates_inclusion_of(:title, in: "hi!") }
<add> assert_nothing_raised(ArgumentError) { Topic.validates_inclusion_of(:title, in: {}) }
<add> assert_nothing_raised(ArgumentError) { Topic.validates_inclusion_of(:title, in: []) }
<ide> end
<ide>
<ide> def test_validates_inclusion_of_with_allow_nil
<del> Topic.validates_inclusion_of( :title, :in => %w( a b c d e f g ), :allow_nil => true )
<add> Topic.validates_inclusion_of(:title, in: %w( a b c d e f g ), allow_nil: true)
<ide>
<ide> assert Topic.new("title" => "a!", "content" => "abc").invalid?
<ide> assert Topic.new("title" => "", "content" => "abc").invalid?
<ide> assert Topic.new("title" => nil, "content" => "abc").valid?
<ide> end
<ide>
<ide> def test_validates_inclusion_of_with_formatted_message
<del> Topic.validates_inclusion_of( :title, :in => %w( a b c d e f g ), :message => "option %{value} is not in the list" )
<add> Topic.validates_inclusion_of(:title, in: %w( a b c d e f g ), message: "option %{value} is not in the list")
<ide>
<ide> assert Topic.new("title" => "a", "content" => "abc").valid?
<ide>
<ide> def test_validates_inclusion_of_with_formatted_message
<ide> end
<ide>
<ide> def test_validates_inclusion_of_with_within_option
<del> Topic.validates_inclusion_of( :title, :within => %w( a b c d e f g ) )
<add> Topic.validates_inclusion_of(:title, within: %w( a b c d e f g ))
<ide>
<ide> assert Topic.new("title" => "a", "content" => "abc").valid?
<ide>
<ide> def test_validates_inclusion_of_with_within_option
<ide> end
<ide>
<ide> def test_validates_inclusion_of_for_ruby_class
<del> Person.validates_inclusion_of :karma, :in => %w( abe monkey )
<add> Person.validates_inclusion_of :karma, in: %w( abe monkey )
<ide>
<ide> p = Person.new
<ide> p.karma = "Lifo"
<ide> def test_validates_inclusion_of_for_ruby_class
<ide> end
<ide>
<ide> def test_validates_inclusion_of_with_lambda
<del> Topic.validates_inclusion_of :title, :in => lambda{ |topic| topic.author_name == "sikachu" ? %w( monkey elephant ) : %w( abe wasabi ) }
<add> Topic.validates_inclusion_of :title, in: lambda{ |topic| topic.author_name == "sikachu" ? %w( monkey elephant ) : %w( abe wasabi ) }
<ide>
<ide> t = Topic.new
<ide> t.title = "wasabi"
<ide> def test_validates_inclusion_of_with_lambda
<ide> end
<ide>
<ide> def test_validates_inclusion_of_with_symbol
<del> Person.validates_inclusion_of :karma, :in => :available_karmas
<add> Person.validates_inclusion_of :karma, in: :available_karmas
<ide>
<ide> p = Person.new
<ide> p.karma = "Lifo"
<ide><path>activemodel/test/cases/validations/numericality_validation_test.rb
<ide> def test_default_validates_numericality_of
<ide> end
<ide>
<ide> def test_validates_numericality_of_with_nil_allowed
<del> Topic.validates_numericality_of :approved, :allow_nil => true
<add> Topic.validates_numericality_of :approved, allow_nil: true
<ide>
<ide> invalid!(JUNK + BLANK)
<ide> valid!(NIL + FLOATS + INTEGERS + BIGDECIMAL + INFINITY)
<ide> end
<ide>
<ide> def test_validates_numericality_of_with_integer_only
<del> Topic.validates_numericality_of :approved, :only_integer => true
<add> Topic.validates_numericality_of :approved, only_integer: true
<ide>
<ide> invalid!(NIL + BLANK + JUNK + FLOATS + BIGDECIMAL + INFINITY)
<ide> valid!(INTEGERS)
<ide> end
<ide>
<ide> def test_validates_numericality_of_with_integer_only_and_nil_allowed
<del> Topic.validates_numericality_of :approved, :only_integer => true, :allow_nil => true
<add> Topic.validates_numericality_of :approved, only_integer: true, allow_nil: true
<ide>
<ide> invalid!(JUNK + BLANK + FLOATS + BIGDECIMAL + INFINITY)
<ide> valid!(NIL + INTEGERS)
<ide> end
<ide>
<ide> def test_validates_numericality_with_greater_than
<del> Topic.validates_numericality_of :approved, :greater_than => 10
<add> Topic.validates_numericality_of :approved, greater_than: 10
<ide>
<ide> invalid!([-10, 10], 'must be greater than 10')
<ide> valid!([11])
<ide> end
<ide>
<ide> def test_validates_numericality_with_greater_than_or_equal
<del> Topic.validates_numericality_of :approved, :greater_than_or_equal_to => 10
<add> Topic.validates_numericality_of :approved, greater_than_or_equal_to: 10
<ide>
<ide> invalid!([-9, 9], 'must be greater than or equal to 10')
<ide> valid!([10])
<ide> end
<ide>
<ide> def test_validates_numericality_with_equal_to
<del> Topic.validates_numericality_of :approved, :equal_to => 10
<add> Topic.validates_numericality_of :approved, equal_to: 10
<ide>
<ide> invalid!([-10, 11] + INFINITY, 'must be equal to 10')
<ide> valid!([10])
<ide> end
<ide>
<ide> def test_validates_numericality_with_less_than
<del> Topic.validates_numericality_of :approved, :less_than => 10
<add> Topic.validates_numericality_of :approved, less_than: 10
<ide>
<ide> invalid!([10], 'must be less than 10')
<ide> valid!([-9, 9])
<ide> end
<ide>
<ide> def test_validates_numericality_with_less_than_or_equal_to
<del> Topic.validates_numericality_of :approved, :less_than_or_equal_to => 10
<add> Topic.validates_numericality_of :approved, less_than_or_equal_to: 10
<ide>
<ide> invalid!([11], 'must be less than or equal to 10')
<ide> valid!([-10, 10])
<ide> end
<ide>
<ide> def test_validates_numericality_with_odd
<del> Topic.validates_numericality_of :approved, :odd => true
<add> Topic.validates_numericality_of :approved, odd: true
<ide>
<ide> invalid!([-2, 2], 'must be odd')
<ide> valid!([-1, 1])
<ide> end
<ide>
<ide> def test_validates_numericality_with_even
<del> Topic.validates_numericality_of :approved, :even => true
<add> Topic.validates_numericality_of :approved, even: true
<ide>
<ide> invalid!([-1, 1], 'must be even')
<ide> valid!([-2, 2])
<ide> end
<ide>
<ide> def test_validates_numericality_with_greater_than_less_than_and_even
<del> Topic.validates_numericality_of :approved, :greater_than => 1, :less_than => 4, :even => true
<add> Topic.validates_numericality_of :approved, greater_than: 1, less_than: 4, even: true
<ide>
<ide> invalid!([1, 3, 4])
<ide> valid!([2])
<ide> end
<ide>
<ide> def test_validates_numericality_with_other_than
<del> Topic.validates_numericality_of :approved, :other_than => 0
<add> Topic.validates_numericality_of :approved, other_than: 0
<ide>
<ide> invalid!([0, 0.0])
<ide> valid!([-1, 42])
<ide> end
<ide>
<ide> def test_validates_numericality_with_proc
<ide> Topic.send(:define_method, :min_approved, lambda { 5 })
<del> Topic.validates_numericality_of :approved, :greater_than_or_equal_to => Proc.new {|topic| topic.min_approved }
<add> Topic.validates_numericality_of :approved, greater_than_or_equal_to: Proc.new {|topic| topic.min_approved }
<ide>
<ide> invalid!([3, 4])
<ide> valid!([5, 6])
<ide> def test_validates_numericality_with_proc
<ide>
<ide> def test_validates_numericality_with_symbol
<ide> Topic.send(:define_method, :max_approved, lambda { 5 })
<del> Topic.validates_numericality_of :approved, :less_than_or_equal_to => :max_approved
<add> Topic.validates_numericality_of :approved, less_than_or_equal_to: :max_approved
<ide>
<ide> invalid!([6])
<ide> valid!([4, 5])
<ide> Topic.send(:remove_method, :max_approved)
<ide> end
<ide>
<ide> def test_validates_numericality_with_numeric_message
<del> Topic.validates_numericality_of :approved, :less_than => 4, :message => "smaller than %{count}"
<add> Topic.validates_numericality_of :approved, less_than: 4, message: "smaller than %{count}"
<ide> topic = Topic.new("title" => "numeric test", "approved" => 10)
<ide>
<ide> assert !topic.valid?
<ide> assert_equal ["smaller than 4"], topic.errors[:approved]
<ide>
<del> Topic.validates_numericality_of :approved, :greater_than => 4, :message => "greater than %{count}"
<add> Topic.validates_numericality_of :approved, greater_than: 4, message: "greater than %{count}"
<ide> topic = Topic.new("title" => "numeric test", "approved" => 1)
<ide>
<ide> assert !topic.valid?
<ide> assert_equal ["greater than 4"], topic.errors[:approved]
<ide> end
<ide>
<ide> def test_validates_numericality_of_for_ruby_class
<del> Person.validates_numericality_of :karma, :allow_nil => false
<add> Person.validates_numericality_of :karma, allow_nil: false
<ide>
<ide> p = Person.new
<ide> p.karma = "Pix"
<ide> def test_validates_numericality_of_for_ruby_class
<ide> end
<ide>
<ide> def test_validates_numericality_with_invalid_args
<del> assert_raise(ArgumentError){ Topic.validates_numericality_of :approved, :greater_than_or_equal_to => "foo" }
<del> assert_raise(ArgumentError){ Topic.validates_numericality_of :approved, :less_than_or_equal_to => "foo" }
<del> assert_raise(ArgumentError){ Topic.validates_numericality_of :approved, :greater_than => "foo" }
<del> assert_raise(ArgumentError){ Topic.validates_numericality_of :approved, :less_than => "foo" }
<del> assert_raise(ArgumentError){ Topic.validates_numericality_of :approved, :equal_to => "foo" }
<add> assert_raise(ArgumentError){ Topic.validates_numericality_of :approved, greater_than_or_equal_to: "foo" }
<add> assert_raise(ArgumentError){ Topic.validates_numericality_of :approved, less_than_or_equal_to: "foo" }
<add> assert_raise(ArgumentError){ Topic.validates_numericality_of :approved, greater_than: "foo" }
<add> assert_raise(ArgumentError){ Topic.validates_numericality_of :approved, less_than: "foo" }
<add> assert_raise(ArgumentError){ Topic.validates_numericality_of :approved, equal_to: "foo" }
<ide> end
<ide>
<ide> private
<ide> def valid!(values)
<ide> end
<ide>
<ide> def with_each_topic_approved_value(values)
<del> topic = Topic.new(:title => "numeric test", :content => "whatever")
<add> topic = Topic.new(title: "numeric test", content: "whatever")
<ide> values.each do |value|
<ide> topic.approved = value
<ide> yield topic, value
<ide><path>activemodel/test/cases/validations/validates_test.rb
<ide> def reset_callbacks
<ide> end
<ide>
<ide> def test_validates_with_messages_empty
<del> Person.validates :title, :presence => {:message => "" }
<add> Person.validates :title, presence: { message: "" }
<ide> person = Person.new
<ide> assert !person.valid?, 'person should not be valid.'
<ide> end
<ide>
<ide> def test_validates_with_built_in_validation
<del> Person.validates :title, :numericality => true
<add> Person.validates :title, numericality: true
<ide> person = Person.new
<ide> person.valid?
<ide> assert_equal ['is not a number'], person.errors[:title]
<ide> end
<ide>
<ide> def test_validates_with_attribute_specified_as_string
<del> Person.validates "title", :numericality => true
<add> Person.validates "title", numericality: true
<ide> person = Person.new
<ide> person.valid?
<ide> assert_equal ['is not a number'], person.errors[:title]
<ide> def test_validates_with_attribute_specified_as_string
<ide> end
<ide>
<ide> def test_validates_with_built_in_validation_and_options
<del> Person.validates :salary, :numericality => { :message => 'my custom message' }
<add> Person.validates :salary, numericality: { message: 'my custom message' }
<ide> person = Person.new
<ide> person.valid?
<ide> assert_equal ['my custom message'], person.errors[:salary]
<ide> end
<ide>
<ide> def test_validates_with_validator_class
<del> Person.validates :karma, :email => true
<add> Person.validates :karma, email: true
<ide> person = Person.new
<ide> person.valid?
<ide> assert_equal ['is not an email'], person.errors[:karma]
<ide> def test_validates_with_namespaced_validator_class
<ide> end
<ide>
<ide> def test_validates_with_if_as_local_conditions
<del> Person.validates :karma, :presence => true, :email => { :unless => :condition_is_true }
<add> Person.validates :karma, presence: true, email: { unless: :condition_is_true }
<ide> person = Person.new
<ide> person.valid?
<ide> assert_equal ["can't be blank"], person.errors[:karma]
<ide> end
<ide>
<ide> def test_validates_with_if_as_shared_conditions
<del> Person.validates :karma, :presence => true, :email => true, :if => :condition_is_true
<add> Person.validates :karma, presence: true, email: true, if: :condition_is_true
<ide> person = Person.new
<ide> person.valid?
<ide> assert_equal ["can't be blank", "is not an email"], person.errors[:karma].sort
<ide> end
<ide>
<ide> def test_validates_with_unless_shared_conditions
<del> Person.validates :karma, :presence => true, :email => true, :unless => :condition_is_true
<add> Person.validates :karma, presence: true, email: true, unless: :condition_is_true
<ide> person = Person.new
<ide> assert person.valid?
<ide> end
<ide>
<ide> def test_validates_with_allow_nil_shared_conditions
<del> Person.validates :karma, :length => { :minimum => 20 }, :email => true, :allow_nil => true
<add> Person.validates :karma, length: { minimum: 20 }, email: true, allow_nil: true
<ide> person = Person.new
<ide> assert person.valid?
<ide> end
<ide>
<ide> def test_validates_with_regexp
<del> Person.validates :karma, :format => /positive|negative/
<add> Person.validates :karma, format: /positive|negative/
<ide> person = Person.new
<ide> assert person.invalid?
<ide> assert_equal ['is invalid'], person.errors[:karma]
<ide> def test_validates_with_regexp
<ide> end
<ide>
<ide> def test_validates_with_array
<del> Person.validates :gender, :inclusion => %w(m f)
<add> Person.validates :gender, inclusion: %w(m f)
<ide> person = Person.new
<ide> assert person.invalid?
<ide> assert_equal ['is not included in the list'], person.errors[:gender]
<ide> def test_validates_with_array
<ide> end
<ide>
<ide> def test_validates_with_range
<del> Person.validates :karma, :length => 6..20
<add> Person.validates :karma, length: 6..20
<ide> person = Person.new
<ide> assert person.invalid?
<ide> assert_equal ['is too short (minimum is 6 characters)'], person.errors[:karma]
<ide> def test_validates_with_range
<ide> end
<ide>
<ide> def test_validates_with_validator_class_and_options
<del> Person.validates :karma, :email => { :message => 'my custom message' }
<add> Person.validates :karma, email: { message: 'my custom message' }
<ide> person = Person.new
<ide> person.valid?
<ide> assert_equal ['my custom message'], person.errors[:karma]
<ide> end
<ide>
<ide> def test_validates_with_unknown_validator
<del> assert_raise(ArgumentError) { Person.validates :karma, :unknown => true }
<add> assert_raise(ArgumentError) { Person.validates :karma, unknown: true }
<ide> end
<ide>
<ide> def test_validates_with_included_validator
<del> PersonWithValidator.validates :title, :presence => true
<add> PersonWithValidator.validates :title, presence: true
<ide> person = PersonWithValidator.new
<ide> person.valid?
<ide> assert_equal ['Local validator'], person.errors[:title]
<ide> end
<ide>
<ide> def test_validates_with_included_validator_and_options
<del> PersonWithValidator.validates :title, :presence => { :custom => ' please' }
<add> PersonWithValidator.validates :title, presence: { custom: ' please' }
<ide> person = PersonWithValidator.new
<ide> person.valid?
<ide> assert_equal ['Local validator please'], person.errors[:title]
<ide> end
<ide>
<ide> def test_validates_with_included_validator_and_wildcard_shortcut
<ide> # Shortcut for PersonWithValidator.validates :title, like: { with: "Mr." }
<del> PersonWithValidator.validates :title, :like => "Mr."
<add> PersonWithValidator.validates :title, like: "Mr."
<ide> person = PersonWithValidator.new
<ide> person.title = "Ms. Pacman"
<ide> person.valid?
<ide> assert_equal ['does not appear to be like Mr.'], person.errors[:title]
<ide> end
<ide>
<ide> def test_defining_extra_default_keys_for_validates
<del> Topic.validates :title, :confirmation => true, :message => 'Y U NO CONFIRM'
<add> Topic.validates :title, confirmation: true, message: 'Y U NO CONFIRM'
<ide> topic = Topic.new
<ide> topic.title = "What's happening"
<ide> topic.title_confirmation = "Not this"
<ide><path>activemodel/test/cases/validations/validations_context_test.rb
<ide> def validate(record)
<ide> end
<ide>
<ide> test "with a class that adds errors on create and validating a new model with no arguments" do
<del> Topic.validates_with(ValidatorThatAddsErrors, :on => :create)
<add> Topic.validates_with(ValidatorThatAddsErrors, on: :create)
<ide> topic = Topic.new
<ide> assert topic.valid?, "Validation doesn't run on valid? if 'on' is set to create"
<ide> end
<ide>
<ide> test "with a class that adds errors on update and validating a new model" do
<del> Topic.validates_with(ValidatorThatAddsErrors, :on => :update)
<add> Topic.validates_with(ValidatorThatAddsErrors, on: :update)
<ide> topic = Topic.new
<ide> assert topic.valid?(:create), "Validation doesn't run on create if 'on' is set to update"
<ide> end
<ide>
<ide> test "with a class that adds errors on create and validating a new model" do
<del> Topic.validates_with(ValidatorThatAddsErrors, :on => :create)
<add> Topic.validates_with(ValidatorThatAddsErrors, on: :create)
<ide> topic = Topic.new
<ide> assert topic.invalid?(:create), "Validation does run on create if 'on' is set to create"
<ide> assert topic.errors[:base].include?(ERROR_MESSAGE)
<ide> end
<del>end
<ide>\ No newline at end of file
<add>end
<ide><path>activemodel/test/cases/validations/with_validation_test.rb
<ide> def check_validity!
<ide> end
<ide>
<ide> test "with if statements that return false" do
<del> Topic.validates_with(ValidatorThatAddsErrors, :if => "1 == 2")
<add> Topic.validates_with(ValidatorThatAddsErrors, if: "1 == 2")
<ide> topic = Topic.new
<ide> assert topic.valid?
<ide> end
<ide>
<ide> test "with if statements that return true" do
<del> Topic.validates_with(ValidatorThatAddsErrors, :if => "1 == 1")
<add> Topic.validates_with(ValidatorThatAddsErrors, if: "1 == 1")
<ide> topic = Topic.new
<ide> assert topic.invalid?
<ide> assert topic.errors[:base].include?(ERROR_MESSAGE)
<ide> end
<ide>
<ide> test "with unless statements that return true" do
<del> Topic.validates_with(ValidatorThatAddsErrors, :unless => "1 == 1")
<add> Topic.validates_with(ValidatorThatAddsErrors, unless: "1 == 1")
<ide> topic = Topic.new
<ide> assert topic.valid?
<ide> end
<ide>
<ide> test "with unless statements that returns false" do
<del> Topic.validates_with(ValidatorThatAddsErrors, :unless => "1 == 2")
<add> Topic.validates_with(ValidatorThatAddsErrors, unless: "1 == 2")
<ide> topic = Topic.new
<ide> assert topic.invalid?
<ide> assert topic.errors[:base].include?(ERROR_MESSAGE)
<ide> def check_validity!
<ide> test "passes all configuration options to the validator class" do
<ide> topic = Topic.new
<ide> validator = mock()
<del> validator.expects(:new).with(:foo => :bar, :if => "1 == 1").returns(validator)
<add> validator.expects(:new).with(foo: :bar, if: "1 == 1").returns(validator)
<ide> validator.expects(:validate).with(topic)
<ide>
<del> Topic.validates_with(validator, :if => "1 == 1", :foo => :bar)
<add> Topic.validates_with(validator, if: "1 == 1", foo: :bar)
<ide> assert topic.valid?
<ide> end
<ide>
<ide> def check_validity!
<ide> end
<ide>
<ide> test "validates_with with options" do
<del> Topic.validates_with(ValidatorThatValidatesOptions, :field => :first_name)
<add> Topic.validates_with(ValidatorThatValidatesOptions, field: :first_name)
<ide> topic = Topic.new
<ide> assert topic.invalid?
<ide> assert topic.errors[:base].include?(ERROR_MESSAGE)
<ide> end
<ide>
<ide> test "validates_with each validator" do
<del> Topic.validates_with(ValidatorPerEachAttribute, :attributes => [:title, :content])
<del> topic = Topic.new :title => "Title", :content => "Content"
<add> Topic.validates_with(ValidatorPerEachAttribute, attributes: [:title, :content])
<add> topic = Topic.new title: "Title", content: "Content"
<ide> assert topic.invalid?
<ide> assert_equal ["Value is Title"], topic.errors[:title]
<ide> assert_equal ["Value is Content"], topic.errors[:content]
<ide> end
<ide>
<ide> test "each validator checks validity" do
<ide> assert_raise RuntimeError do
<del> Topic.validates_with(ValidatorCheckValidity, :attributes => [:title])
<add> Topic.validates_with(ValidatorCheckValidity, attributes: [:title])
<ide> end
<ide> end
<ide>
<ide> def check_validity!
<ide> end
<ide>
<ide> test "each validator skip nil values if :allow_nil is set to true" do
<del> Topic.validates_with(ValidatorPerEachAttribute, :attributes => [:title, :content], :allow_nil => true)
<del> topic = Topic.new :content => ""
<add> Topic.validates_with(ValidatorPerEachAttribute, attributes: [:title, :content], allow_nil: true)
<add> topic = Topic.new content: ""
<ide> assert topic.invalid?
<ide> assert topic.errors[:title].empty?
<ide> assert_equal ["Value is "], topic.errors[:content]
<ide> end
<ide>
<ide> test "each validator skip blank values if :allow_blank is set to true" do
<del> Topic.validates_with(ValidatorPerEachAttribute, :attributes => [:title, :content], :allow_blank => true)
<del> topic = Topic.new :content => ""
<add> Topic.validates_with(ValidatorPerEachAttribute, attributes: [:title, :content], allow_blank: true)
<add> topic = Topic.new content: ""
<ide> assert topic.valid?
<ide> assert topic.errors[:title].empty?
<ide> assert topic.errors[:content].empty?
<ide> end
<ide>
<ide> test "validates_with can validate with an instance method" do
<del> Topic.validates :title, :with => :my_validation
<add> Topic.validates :title, with: :my_validation
<ide>
<del> topic = Topic.new :title => "foo"
<add> topic = Topic.new title: "foo"
<ide> assert topic.valid?
<ide> assert topic.errors[:title].empty?
<ide>
<ide> def check_validity!
<ide> end
<ide>
<ide> test "optionally pass in the attribute being validated when validating with an instance method" do
<del> Topic.validates :title, :content, :with => :my_validation_with_arg
<add> Topic.validates :title, :content, with: :my_validation_with_arg
<ide>
<del> topic = Topic.new :title => "foo"
<add> topic = Topic.new title: "foo"
<ide> assert !topic.valid?
<ide> assert topic.errors[:title].empty?
<ide> assert_equal ['is missing'], topic.errors[:content]
<ide><path>activemodel/test/cases/validations_test.rb
<ide> def test_errors_conversions
<ide>
<ide> def test_validation_order
<ide> Topic.validates_presence_of :title
<del> Topic.validates_length_of :title, :minimum => 2
<add> Topic.validates_length_of :title, minimum: 2
<ide>
<ide> t = Topic.new("title" => "")
<ide> assert t.invalid?
<ide> assert_equal "can't be blank", t.errors["title"].first
<ide> Topic.validates_presence_of :title, :author_name
<ide> Topic.validate {errors.add('author_email_address', 'will never be valid')}
<del> Topic.validates_length_of :title, :content, :minimum => 2
<add> Topic.validates_length_of :title, :content, minimum: 2
<ide>
<del> t = Topic.new :title => ''
<add> t = Topic.new title: ''
<ide> assert t.invalid?
<ide>
<ide> assert_equal :title, key = t.errors.keys[0]
<ide> def test_validation_order
<ide> end
<ide>
<ide> def test_validation_with_if_and_on
<del> Topic.validates_presence_of :title, :if => Proc.new{|x| x.author_name = "bad"; true }, :on => :update
<add> Topic.validates_presence_of :title, if: Proc.new{|x| x.author_name = "bad"; true }, on: :update
<ide>
<del> t = Topic.new(:title => "")
<add> t = Topic.new(title: "")
<ide>
<ide> # If block should not fire
<ide> assert t.valid?
<ide> def test_invalid_should_be_the_opposite_of_valid
<ide> end
<ide>
<ide> def test_validation_with_message_as_proc
<del> Topic.validates_presence_of(:title, :message => proc { "no blanks here".upcase })
<add> Topic.validates_presence_of(:title, message: proc { "no blanks here".upcase })
<ide>
<ide> t = Topic.new
<ide> assert t.invalid?
<ide> def test_validation_with_message_as_proc
<ide>
<ide> def test_list_of_validators_for_model
<ide> Topic.validates_presence_of :title
<del> Topic.validates_length_of :title, :minimum => 2
<add> Topic.validates_length_of :title, minimum: 2
<ide>
<ide> assert_equal 2, Topic.validators.count
<ide> assert_equal [:presence, :length], Topic.validators.map(&:kind)
<ide> end
<ide>
<ide> def test_list_of_validators_on_an_attribute
<ide> Topic.validates_presence_of :title, :content
<del> Topic.validates_length_of :title, :minimum => 2
<add> Topic.validates_length_of :title, minimum: 2
<ide>
<ide> assert_equal 2, Topic.validators_on(:title).count
<ide> assert_equal [:presence, :length], Topic.validators_on(:title).map(&:kind)
<ide> def test_list_of_validators_on_an_attribute
<ide> end
<ide>
<ide> def test_accessing_instance_of_validator_on_an_attribute
<del> Topic.validates_length_of :title, :minimum => 10
<add> Topic.validates_length_of :title, minimum: 10
<ide> assert_equal 10, Topic.validators_on(:title).first.options[:minimum]
<ide> end
<ide>
<ide> def test_list_of_validators_on_multiple_attributes
<del> Topic.validates :title, :length => { :minimum => 10 }
<del> Topic.validates :author_name, :presence => true, :format => /a/
<add> Topic.validates :title, length: { minimum: 10 }
<add> Topic.validates :author_name, presence: true, format: /a/
<ide>
<ide> validators = Topic.validators_on(:title, :author_name)
<ide>
<ide> def test_list_of_validators_on_multiple_attributes
<ide> end
<ide>
<ide> def test_list_of_validators_will_be_empty_when_empty
<del> Topic.validates :title, :length => { :minimum => 10 }
<add> Topic.validates :title, length: { minimum: 10 }
<ide> assert_equal [], Topic.validators_on(:author_name)
<ide> end
<ide>
<ide> def test_validations_on_the_instance_level
<ide> end
<ide>
<ide> def test_strict_validation_in_validates
<del> Topic.validates :title, :strict => true, :presence => true
<add> Topic.validates :title, strict: true, presence: true
<ide> assert_raises ActiveModel::StrictValidationFailed do
<ide> Topic.new.valid?
<ide> end
<ide> end
<ide>
<ide> def test_strict_validation_not_fails
<del> Topic.validates :title, :strict => true, :presence => true
<del> assert Topic.new(:title => "hello").valid?
<add> Topic.validates :title, strict: true, presence: true
<add> assert Topic.new(title: "hello").valid?
<ide> end
<ide>
<ide> def test_strict_validation_particular_validator
<del> Topic.validates :title, :presence => { :strict => true }
<add> Topic.validates :title, presence: { strict: true }
<ide> assert_raises ActiveModel::StrictValidationFailed do
<ide> Topic.new.valid?
<ide> end
<ide> end
<ide>
<ide> def test_strict_validation_in_custom_validator_helper
<del> Topic.validates_presence_of :title, :strict => true
<add> Topic.validates_presence_of :title, strict: true
<ide> assert_raises ActiveModel::StrictValidationFailed do
<ide> Topic.new.valid?
<ide> end
<ide> end
<ide>
<ide> def test_strict_validation_custom_exception
<del> Topic.validates_presence_of :title, :strict => CustomStrictValidationException
<add> Topic.validates_presence_of :title, strict: CustomStrictValidationException
<ide> assert_raises CustomStrictValidationException do
<ide> Topic.new.valid?
<ide> end
<ide> end
<ide>
<ide> def test_validates_with_bang
<del> Topic.validates! :title, :presence => true
<add> Topic.validates! :title, presence: true
<ide> assert_raises ActiveModel::StrictValidationFailed do
<ide> Topic.new.valid?
<ide> end
<ide> end
<ide>
<ide> def test_validates_with_false_hash_value
<del> Topic.validates :title, :presence => false
<add> Topic.validates :title, presence: false
<ide> assert Topic.new.valid?
<ide> end
<ide>
<ide> def test_strict_validation_error_message
<del> Topic.validates :title, :strict => true, :presence => true
<add> Topic.validates :title, strict: true, presence: true
<ide>
<ide> exception = assert_raises(ActiveModel::StrictValidationFailed) do
<ide> Topic.new.valid?
<ide> def test_strict_validation_error_message
<ide> end
<ide>
<ide> def test_does_not_modify_options_argument
<del> options = { :presence => true }
<add> options = { presence: true }
<ide> Topic.validates :title, options
<del> assert_equal({ :presence => true }, options)
<add> assert_equal({ presence: true }, options)
<ide> end
<ide>
<ide> def test_dup_validity_is_independent
<ide><path>activemodel/test/models/automobile.rb
<ide> class Automobile
<ide>
<ide> def validations
<ide> validates_presence_of :make
<del> validates_length_of :model, :within => 2..10
<add> validates_length_of :model, within: 2..10
<ide> end
<del>end
<ide>\ No newline at end of file
<add>end
<ide><path>activemodel/test/models/contact.rb
<ide> def social
<ide> end
<ide>
<ide> def network
<del> {:git => :github}
<add> { git: :github }
<ide> end
<ide>
<ide> def initialize(options = {})
<ide><path>activemodel/test/models/reply.rb
<ide>
<ide> class Reply < Topic
<ide> validate :errors_on_empty_content
<del> validate :title_is_wrong_create, :on => :create
<add> validate :title_is_wrong_create, on: :create
<ide>
<ide> validate :check_empty_title
<del> validate :check_content_mismatch, :on => :create
<del> validate :check_wrong_update, :on => :update
<add> validate :check_content_mismatch, on: :create
<add> validate :check_wrong_update, on: :update
<ide>
<ide> def check_empty_title
<ide> errors[:title] << "is Empty" unless title && title.size > 0 | 43 |
Ruby | Ruby | remove useless code | 446b6855dc88715315ce1ea15c25d1e821f8e598 | <ide><path>actionpack/lib/abstract_controller/rendering.rb
<ide> module Rendering
<ide> def render(*args, &block)
<ide> options = _normalize_render(*args, &block)
<ide> self.response_body = render_to_body(options)
<del> _process_format(rendered_format) if rendered_format
<ide> if options[:plain]
<ide> _set_content_type Mime::TEXT.to_s
<ide> else | 1 |
PHP | PHP | implement implementedevents on all core components | da143545fd6d0a82536753442dff918c76dc629c | <ide><path>src/Controller/Component/AuthComponent.php
<ide> public function startup(Event $event) {
<ide> return $this->_unauthorized($controller);
<ide> }
<ide>
<add>/**
<add> * Events supported by this component.
<add> *
<add> * @return array
<add> */
<add> public function implementedEvents() {
<add> return [
<add> 'Controller.initialize' => 'initialize',
<add> 'Controller.startup' => 'startup',
<add> ];
<add> }
<add>
<ide> /**
<ide> * Checks whether current action is accessible without authentication.
<ide> *
<ide><path>src/Controller/Component/CookieComponent.php
<ide> public function startup(Event $event) {
<ide> $this->_values[$this->_config['name']] = array();
<ide> }
<ide>
<add>/**
<add> * Events supported by this component.
<add> *
<add> * @return array
<add> */
<add> public function implementedEvents() {
<add> return [
<add> 'Controller.startup' => 'startup',
<add> ];
<add> }
<add>
<ide> /**
<ide> * Write a value to the $_COOKIE[$key];
<ide> *
<ide><path>src/Controller/Component/CsrfComponent.php
<ide> public function startup(Event $event) {
<ide> }
<ide> }
<ide>
<add>/**
<add> * Events supported by this component.
<add> *
<add> * @return array
<add> */
<add> public function implementedEvents() {
<add> return [
<add> 'Controller.startup' => 'startup',
<add> ];
<add> }
<add>
<ide> /**
<ide> * Set the cookie in the response.
<ide> *
<ide><path>src/Controller/Component/PaginatorComponent.php
<ide> class PaginatorComponent extends Component {
<ide> 'whitelist' => ['limit', 'sort', 'page', 'direction']
<ide> );
<ide>
<add>/**
<add> * Events supported by this component.
<add> *
<add> * @return array
<add> */
<add> public function implementedEvents() {
<add> return [];
<add> }
<add>
<ide> /**
<ide> * Handles automatic pagination of model records.
<ide> *
<ide> class PaginatorComponent extends Component {
<ide> *
<ide> * {{{
<ide> * $query = $this->Articles->find('popular')->matching('Tags', function($q) {
<del> * return $q->where(['name' => 'CakePHP'])
<add> * return $q->where(['name' => 'CakePHP'])
<ide> * });
<ide> * $results = $paginator->paginate($query);
<ide> * }}}
<ide><path>src/Controller/Component/RequestHandlerComponent.php
<ide> public function __construct(ComponentRegistry $collection, array $config = array
<ide> $this->response = $Controller->response;
<ide> }
<ide>
<add>/**
<add> * Events supported by this component.
<add> *
<add> * @return array
<add> */
<add> public function implementedEvents() {
<add> return [
<add> 'Controller.initialize' => 'initialize',
<add> 'Controller.startup' => 'startup',
<add> 'Controller.beforeRender' => 'beforeRender',
<add> 'Controller.beforeRedirect' => 'beforeRedirect',
<add> ];
<add> }
<add>
<ide> /**
<ide> * Checks to see if a specific content type has been requested and sets RequestHandler::$ext
<ide> * accordingly. Checks the following in order: 1. The '_ext' value parsed by the Router. 2. A specific
<ide><path>src/Controller/Component/SecurityComponent.php
<ide> public function startup(Event $event) {
<ide> }
<ide> }
<ide>
<add>/**
<add> * Events supported by this component.
<add> *
<add> * @return array
<add> */
<add> public function implementedEvents() {
<add> return [
<add> 'Controller.startup' => 'startup',
<add> ];
<add> }
<add>
<ide> /**
<ide> * Sets the actions that require a request that is SSL-secured, or empty for all actions
<ide> *
<ide><path>src/Controller/Component/SessionComponent.php
<ide> public function started() {
<ide> return Session::started();
<ide> }
<ide>
<add>/**
<add> * Events supported by this component.
<add> *
<add> * @return array
<add> */
<add> public function implementedEvents() {
<add> return [];
<add> }
<add>
<ide> } | 7 |
Text | Text | update license fix for github | 98d8967b0239602ca94c36973f0d6231141c84a0 | <ide><path>LICENSE.md
<add>Attribution-ShareAlike 4.0 International
<add>
<add>=======================================================================
<add>
<add>Creative Commons Corporation ("Creative Commons") is not a law firm and
<add>does not provide legal services or legal advice. Distribution of
<add>Creative Commons public licenses does not create a lawyer-client or
<add>other relationship. Creative Commons makes its licenses and related
<add>information available on an "as-is" basis. Creative Commons gives no
<add>warranties regarding its licenses, any material licensed under their
<add>terms and conditions, or any related information. Creative Commons
<add>disclaims all liability for damages resulting from their use to the
<add>fullest extent possible.
<add>
<add>Using Creative Commons Public Licenses
<add>
<add>Creative Commons public licenses provide a standard set of terms and
<add>conditions that creators and other rights holders may use to share
<add>original works of authorship and other material subject to copyright
<add>and certain other rights specified in the public license below. The
<add>following considerations are for informational purposes only, are not
<add>exhaustive, and do not form part of our licenses.
<add>
<add> Considerations for licensors: Our public licenses are
<add> intended for use by those authorized to give the public
<add> permission to use material in ways otherwise restricted by
<add> copyright and certain other rights. Our licenses are
<add> irrevocable. Licensors should read and understand the terms
<add> and conditions of the license they choose before applying it.
<add> Licensors should also secure all rights necessary before
<add> applying our licenses so that the public can reuse the
<add> material as expected. Licensors should clearly mark any
<add> material not subject to the license. This includes other CC-
<add> licensed material, or material used under an exception or
<add> limitation to copyright. More considerations for licensors:
<add> wiki.creativecommons.org/Considerations_for_licensors
<add>
<add> Considerations for the public: By using one of our public
<add> licenses, a licensor grants the public permission to use the
<add> licensed material under specified terms and conditions. If
<add> the licensor's permission is not necessary for any reason--for
<add> example, because of any applicable exception or limitation to
<add> copyright--then that use is not regulated by the license. Our
<add> licenses grant only permissions under copyright and certain
<add> other rights that a licensor has authority to grant. Use of
<add> the licensed material may still be restricted for other
<add> reasons, including because others have copyright or other
<add> rights in the material. A licensor may make special requests,
<add> such as asking that all changes be marked or described.
<add> Although not required by our licenses, you are encouraged to
<add> respect those requests where reasonable. More_considerations
<add> for the public:
<add> wiki.creativecommons.org/Considerations_for_licensees
<add>
<add>=======================================================================
<add>
<add>Creative Commons Attribution-ShareAlike 4.0 International Public
<add>License
<add>
<add>By exercising the Licensed Rights (defined below), You accept and agree
<add>to be bound by the terms and conditions of this Creative Commons
<add>Attribution-ShareAlike 4.0 International Public License ("Public
<add>License"). To the extent this Public License may be interpreted as a
<add>contract, You are granted the Licensed Rights in consideration of Your
<add>acceptance of these terms and conditions, and the Licensor grants You
<add>such rights in consideration of benefits the Licensor receives from
<add>making the Licensed Material available under these terms and
<add>conditions.
<add>
<add>
<add>Section 1 -- Definitions.
<add>
<add> a. Adapted Material means material subject to Copyright and Similar
<add> Rights that is derived from or based upon the Licensed Material
<add> and in which the Licensed Material is translated, altered,
<add> arranged, transformed, or otherwise modified in a manner requiring
<add> permission under the Copyright and Similar Rights held by the
<add> Licensor. For purposes of this Public License, where the Licensed
<add> Material is a musical work, performance, or sound recording,
<add> Adapted Material is always produced where the Licensed Material is
<add> synched in timed relation with a moving image.
<add>
<add> b. Adapter's License means the license You apply to Your Copyright
<add> and Similar Rights in Your contributions to Adapted Material in
<add> accordance with the terms and conditions of this Public License.
<add>
<add> c. BY-SA Compatible License means a license listed at
<add> creativecommons.org/compatiblelicenses, approved by Creative
<add> Commons as essentially the equivalent of this Public License.
<add>
<add> d. Copyright and Similar Rights means copyright and/or similar rights
<add> closely related to copyright including, without limitation,
<add> performance, broadcast, sound recording, and Sui Generis Database
<add> Rights, without regard to how the rights are labeled or
<add> categorized. For purposes of this Public License, the rights
<add> specified in Section 2(b)(1)-(2) are not Copyright and Similar
<add> Rights.
<add>
<add> e. Effective Technological Measures means those measures that, in the
<add> absence of proper authority, may not be circumvented under laws
<add> fulfilling obligations under Article 11 of the WIPO Copyright
<add> Treaty adopted on December 20, 1996, and/or similar international
<add> agreements.
<add>
<add> f. Exceptions and Limitations means fair use, fair dealing, and/or
<add> any other exception or limitation to Copyright and Similar Rights
<add> that applies to Your use of the Licensed Material.
<add>
<add> g. License Elements means the license attributes listed in the name
<add> of a Creative Commons Public License. The License Elements of this
<add> Public License are Attribution and ShareAlike.
<add>
<add> h. Licensed Material means the artistic or literary work, database,
<add> or other material to which the Licensor applied this Public
<add> License.
<add>
<add> i. Licensed Rights means the rights granted to You subject to the
<add> terms and conditions of this Public License, which are limited to
<add> all Copyright and Similar Rights that apply to Your use of the
<add> Licensed Material and that the Licensor has authority to license.
<add>
<add> j. Licensor means the individual(s) or entity(ies) granting rights
<add> under this Public License.
<add>
<add> k. Share means to provide material to the public by any means or
<add> process that requires permission under the Licensed Rights, such
<add> as reproduction, public display, public performance, distribution,
<add> dissemination, communication, or importation, and to make material
<add> available to the public including in ways that members of the
<add> public may access the material from a place and at a time
<add> individually chosen by them.
<add>
<add> l. Sui Generis Database Rights means rights other than copyright
<add> resulting from Directive 96/9/EC of the European Parliament and of
<add> the Council of 11 March 1996 on the legal protection of databases,
<add> as amended and/or succeeded, as well as other essentially
<add> equivalent rights anywhere in the world.
<add>
<add> m. You means the individual or entity exercising the Licensed Rights
<add> under this Public License. Your has a corresponding meaning.
<add>
<add>
<add>Section 2 -- Scope.
<add>
<add> a. License grant.
<add>
<add> 1. Subject to the terms and conditions of this Public License,
<add> the Licensor hereby grants You a worldwide, royalty-free,
<add> non-sublicensable, non-exclusive, irrevocable license to
<add> exercise the Licensed Rights in the Licensed Material to:
<add>
<add> a. reproduce and Share the Licensed Material, in whole or
<add> in part; and
<add>
<add> b. produce, reproduce, and Share Adapted Material.
<add>
<add> 2. Exceptions and Limitations. For the avoidance of doubt, where
<add> Exceptions and Limitations apply to Your use, this Public
<add> License does not apply, and You do not need to comply with
<add> its terms and conditions.
<add>
<add> 3. Term. The term of this Public License is specified in Section
<add> 6(a).
<add>
<add> 4. Media and formats; technical modifications allowed. The
<add> Licensor authorizes You to exercise the Licensed Rights in
<add> all media and formats whether now known or hereafter created,
<add> and to make technical modifications necessary to do so. The
<add> Licensor waives and/or agrees not to assert any right or
<add> authority to forbid You from making technical modifications
<add> necessary to exercise the Licensed Rights, including
<add> technical modifications necessary to circumvent Effective
<add> Technological Measures. For purposes of this Public License,
<add> simply making modifications authorized by this Section 2(a)
<add> (4) never produces Adapted Material.
<add>
<add> 5. Downstream recipients.
<add>
<add> a. Offer from the Licensor -- Licensed Material. Every
<add> recipient of the Licensed Material automatically
<add> receives an offer from the Licensor to exercise the
<add> Licensed Rights under the terms and conditions of this
<add> Public License.
<add>
<add> b. Additional offer from the Licensor -- Adapted Material.
<add> Every recipient of Adapted Material from You
<add> automatically receives an offer from the Licensor to
<add> exercise the Licensed Rights in the Adapted Material
<add> under the conditions of the Adapter's License You apply.
<add>
<add> c. No downstream restrictions. You may not offer or impose
<add> any additional or different terms or conditions on, or
<add> apply any Effective Technological Measures to, the
<add> Licensed Material if doing so restricts exercise of the
<add> Licensed Rights by any recipient of the Licensed
<add> Material.
<add>
<add> 6. No endorsement. Nothing in this Public License constitutes or
<add> may be construed as permission to assert or imply that You
<add> are, or that Your use of the Licensed Material is, connected
<add> with, or sponsored, endorsed, or granted official status by,
<add> the Licensor or others designated to receive attribution as
<add> provided in Section 3(a)(1)(A)(i).
<add>
<add> b. Other rights.
<add>
<add> 1. Moral rights, such as the right of integrity, are not
<add> licensed under this Public License, nor are publicity,
<add> privacy, and/or other similar personality rights; however, to
<add> the extent possible, the Licensor waives and/or agrees not to
<add> assert any such rights held by the Licensor to the limited
<add> extent necessary to allow You to exercise the Licensed
<add> Rights, but not otherwise.
<add>
<add> 2. Patent and trademark rights are not licensed under this
<add> Public License.
<add>
<add> 3. To the extent possible, the Licensor waives any right to
<add> collect royalties from You for the exercise of the Licensed
<add> Rights, whether directly or through a collecting society
<add> under any voluntary or waivable statutory or compulsory
<add> licensing scheme. In all other cases the Licensor expressly
<add> reserves any right to collect such royalties.
<add>
<add>
<add>Section 3 -- License Conditions.
<add>
<add>Your exercise of the Licensed Rights is expressly made subject to the
<add>following conditions.
<add>
<add> a. Attribution.
<add>
<add> 1. If You Share the Licensed Material (including in modified
<add> form), You must:
<add>
<add> a. retain the following if it is supplied by the Licensor
<add> with the Licensed Material:
<add>
<add> i. identification of the creator(s) of the Licensed
<add> Material and any others designated to receive
<add> attribution, in any reasonable manner requested by
<add> the Licensor (including by pseudonym if
<add> designated);
<add>
<add> ii. a copyright notice;
<add>
<add> iii. a notice that refers to this Public License;
<add>
<add> iv. a notice that refers to the disclaimer of
<add> warranties;
<add>
<add> v. a URI or hyperlink to the Licensed Material to the
<add> extent reasonably practicable;
<add>
<add> b. indicate if You modified the Licensed Material and
<add> retain an indication of any previous modifications; and
<add>
<add> c. indicate the Licensed Material is licensed under this
<add> Public License, and include the text of, or the URI or
<add> hyperlink to, this Public License.
<add>
<add> 2. You may satisfy the conditions in Section 3(a)(1) in any
<add> reasonable manner based on the medium, means, and context in
<add> which You Share the Licensed Material. For example, it may be
<add> reasonable to satisfy the conditions by providing a URI or
<add> hyperlink to a resource that includes the required
<add> information.
<add>
<add> 3. If requested by the Licensor, You must remove any of the
<add> information required by Section 3(a)(1)(A) to the extent
<add> reasonably practicable.
<add>
<add> b. ShareAlike.
<add>
<add> In addition to the conditions in Section 3(a), if You Share
<add> Adapted Material You produce, the following conditions also apply.
<add>
<add> 1. The Adapter's License You apply must be a Creative Commons
<add> license with the same License Elements, this version or
<add> later, or a BY-SA Compatible License.
<add>
<add> 2. You must include the text of, or the URI or hyperlink to, the
<add> Adapter's License You apply. You may satisfy this condition
<add> in any reasonable manner based on the medium, means, and
<add> context in which You Share Adapted Material.
<add>
<add> 3. You may not offer or impose any additional or different terms
<add> or conditions on, or apply any Effective Technological
<add> Measures to, Adapted Material that restrict exercise of the
<add> rights granted under the Adapter's License You apply.
<add>
<add>
<add>Section 4 -- Sui Generis Database Rights.
<add>
<add>Where the Licensed Rights include Sui Generis Database Rights that
<add>apply to Your use of the Licensed Material:
<add>
<add> a. for the avoidance of doubt, Section 2(a)(1) grants You the right
<add> to extract, reuse, reproduce, and Share all or a substantial
<add> portion of the contents of the database;
<add>
<add> b. if You include all or a substantial portion of the database
<add> contents in a database in which You have Sui Generis Database
<add> Rights, then the database in which You have Sui Generis Database
<add> Rights (but not its individual contents) is Adapted Material,
<add>
<add> including for purposes of Section 3(b); and
<add> c. You must comply with the conditions in Section 3(a) if You Share
<add> all or a substantial portion of the contents of the database.
<add>
<add>For the avoidance of doubt, this Section 4 supplements and does not
<add>replace Your obligations under this Public License where the Licensed
<add>Rights include other Copyright and Similar Rights.
<add>
<add>
<add>Section 5 -- Disclaimer of Warranties and Limitation of Liability.
<add>
<add> a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
<add> EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
<add> AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
<add> ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
<add> IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
<add> WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
<add> PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
<add> ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
<add> KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
<add> ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
<add>
<add> b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
<add> TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
<add> NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
<add> INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
<add> COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
<add> USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
<add> ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
<add> DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
<add> IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
<add>
<add> c. The disclaimer of warranties and limitation of liability provided
<add> above shall be interpreted in a manner that, to the extent
<add> possible, most closely approximates an absolute disclaimer and
<add> waiver of all liability.
<add>
<add>
<add>Section 6 -- Term and Termination.
<add>
<add> a. This Public License applies for the term of the Copyright and
<add> Similar Rights licensed here. However, if You fail to comply with
<add> this Public License, then Your rights under this Public License
<add> terminate automatically.
<add>
<add> b. Where Your right to use the Licensed Material has terminated under
<add> Section 6(a), it reinstates:
<add>
<add> 1. automatically as of the date the violation is cured, provided
<add> it is cured within 30 days of Your discovery of the
<add> violation; or
<add>
<add> 2. upon express reinstatement by the Licensor.
<add>
<add> For the avoidance of doubt, this Section 6(b) does not affect any
<add> right the Licensor may have to seek remedies for Your violations
<add> of this Public License.
<add>
<add> c. For the avoidance of doubt, the Licensor may also offer the
<add> Licensed Material under separate terms or conditions or stop
<add> distributing the Licensed Material at any time; however, doing so
<add> will not terminate this Public License.
<add>
<add> d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
<add> License.
<add>
<add>
<add>Section 7 -- Other Terms and Conditions.
<add>
<add> a. The Licensor shall not be bound by any additional or different
<add> terms or conditions communicated by You unless expressly agreed.
<add>
<add> b. Any arrangements, understandings, or agreements regarding the
<add> Licensed Material not stated herein are separate from and
<add> independent of the terms and conditions of this Public License.
<add>
<add>
<add>Section 8 -- Interpretation.
<add>
<add> a. For the avoidance of doubt, this Public License does not, and
<add> shall not be interpreted to, reduce, limit, restrict, or impose
<add> conditions on any use of the Licensed Material that could lawfully
<add> be made without permission under this Public License.
<add>
<add> b. To the extent possible, if any provision of this Public License is
<add> deemed unenforceable, it shall be automatically reformed to the
<add> minimum extent necessary to make it enforceable. If the provision
<add> cannot be reformed, it shall be severed from this Public License
<add> without affecting the enforceability of the remaining terms and
<add> conditions.
<add>
<add> c. No term or condition of this Public License will be waived and no
<add> failure to comply consented to unless expressly agreed to by the
<add> Licensor.
<add>
<add> d. Nothing in this Public License constitutes or may be interpreted
<add> as a limitation upon, or waiver of, any privileges and immunities
<add> that apply to the Licensor or You, including from the legal
<add> processes of any jurisdiction or authority.
<add>
<add>
<add>=======================================================================
<add>
<add>Creative Commons is not a party to its public
<add>licenses. Notwithstanding, Creative Commons may elect to apply one of
<add>its public licenses to material it publishes and in those instances
<add>will be considered the “Licensor.” The text of the Creative Commons
<add>public licenses is dedicated to the public domain under the CC0 Public
<add>Domain Dedication. Except for the limited purpose of indicating that
<add>material is shared under a Creative Commons public license or as
<add>otherwise permitted by the Creative Commons policies published at
<add>creativecommons.org/policies, Creative Commons does not authorize the
<add>use of the trademark "Creative Commons" or any other trademark or logo
<add>of Creative Commons without its prior written consent including,
<add>without limitation, in connection with any unauthorized modifications
<add>to any of its public licenses or any other arrangements,
<add>understandings, or agreements concerning use of licensed material. For
<add>the avoidance of doubt, this paragraph does not form part of the
<add>public licenses.
<add>
<add>Creative Commons may be contacted at creativecommons.org. | 1 |
Ruby | Ruby | fix bug in configs_for | 2791b7c280ac65b3de5976141d79d2c1328b798e | <ide><path>activerecord/lib/active_record/database_configurations.rb
<ide> def initialize(configurations = {})
<ide> # * <tt>env_name:</tt> The environment name. Defaults to +nil+ which will collect
<ide> # configs for all environments.
<ide> # * <tt>spec_name:</tt> The specification name (i.e. primary, animals, etc.). Defaults
<del> # to +nil+.
<add> # to +nil+. If no +env_name+ is specified the config for the default env and the
<add> # passed +spec_name+ will be returned.
<ide> # * <tt>include_replicas:</tt> Determines whether to include replicas in
<ide> # the returned list. Most of the time we're only iterating over the write
<ide> # connection (i.e. migrations don't need to run for the write and read connection).
<ide> # Defaults to +false+.
<ide> def configs_for(env_name: nil, spec_name: nil, include_replicas: false)
<add> env_name ||= default_env if spec_name
<ide> configs = env_with_configs(env_name)
<ide>
<ide> unless include_replicas
<ide> def configs_for(env_name: nil, spec_name: nil, include_replicas: false)
<ide> # return the first config hash for the environment.
<ide> #
<ide> # { database: "my_db", adapter: "mysql2" }
<del> def default_hash(env = ActiveRecord::ConnectionHandling::DEFAULT_ENV.call.to_s)
<add> def default_hash(env = default_env)
<ide> default = find_db_config(env)
<ide> default.configuration_hash if default
<ide> end
<ide> def resolve(config, pool_name = nil) # :nodoc:
<ide> when Symbol
<ide> resolve_symbol_connection(config, pool_name)
<ide> when Hash, String
<del> env = ActiveRecord::ConnectionHandling::DEFAULT_ENV.call.to_s
<del> build_db_config_from_raw_config(env, "primary", config)
<add> build_db_config_from_raw_config(default_env, "primary", config)
<ide> else
<ide> raise TypeError, "Invalid type for configuration. Expected Symbol, String, or Hash. Got #{config.inspect}"
<ide> end
<ide> end
<ide>
<ide> private
<add> def default_env
<add> ActiveRecord::ConnectionHandling::DEFAULT_ENV.call.to_s
<add> end
<add>
<ide> def env_with_configs(env = nil)
<ide> if env
<ide> configurations.select { |db_config| db_config.env_name == env }
<ide> def build_configs(configs)
<ide> end
<ide> end
<ide>
<del> current_env = ActiveRecord::ConnectionHandling::DEFAULT_ENV.call.to_s
<del>
<ide> unless db_configs.find(&:for_current_env?)
<del> db_configs << environment_url_config(current_env, "primary", {})
<add> db_configs << environment_url_config(default_env, "primary", {})
<ide> end
<ide>
<del> merge_db_environment_variables(current_env, db_configs.compact)
<add> merge_db_environment_variables(default_env, db_configs.compact)
<ide> end
<ide>
<ide> def walk_configs(env_name, config)
<ide> def resolve_symbol_connection(env_name, pool_name)
<ide> DatabaseConfigurations::HashConfig.new(db_config.env_name, db_config.spec_name, config)
<ide> else
<ide> raise AdapterNotSpecified, <<~MSG
<del> The `#{env_name}` database is not configured for the `#{ActiveRecord::ConnectionHandling::DEFAULT_ENV.call}` environment.
<add> The `#{env_name}` database is not configured for the `#{default_env}` environment.
<ide>
<ide> Available databases configurations are:
<ide>
<ide><path>activerecord/test/cases/database_configurations_test.rb
<ide> def test_configs_for_getter_with_env_name
<ide> assert_equal ["arunit"], configs.map(&:env_name)
<ide> end
<ide>
<add> def test_configs_for_getter_with_spec_name
<add> previous_env, ENV["RAILS_ENV"] = ENV["RAILS_ENV"], "arunit2"
<add>
<add> config = ActiveRecord::Base.configurations.configs_for(spec_name: "primary")
<add>
<add> assert_equal "arunit2", config.env_name
<add> assert_equal "primary", config.spec_name
<add> ensure
<add> ENV["RAILS_ENV"] = previous_env
<add> end
<add>
<ide> def test_configs_for_getter_with_env_and_spec_name
<ide> config = ActiveRecord::Base.configurations.configs_for(env_name: "arunit", spec_name: "primary")
<ide> | 2 |
Javascript | Javascript | avoid duplicate jqlite wrappers | 2e3c6404f27bf41b8874078d751ec1987992c0e5 | <ide><path>src/ng/directive/ngRepeat.js
<ide> var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
<ide>
<ide> if (getBlockStart(block) != nextNode) {
<ide> // existing item which got moved
<del> $animate.move(getBlockNodes(block.clone), null, jqLite(previousNode));
<add> $animate.move(getBlockNodes(block.clone), null, previousNode);
<ide> }
<ide> previousNode = getBlockEnd(block);
<ide> updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
<ide> var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
<ide> var endNode = ngRepeatEndComment.cloneNode(false);
<ide> clone[clone.length++] = endNode;
<ide>
<del> // TODO(perf): support naked previousNode in `enter` to avoid creation of jqLite wrapper?
<del> $animate.enter(clone, null, jqLite(previousNode));
<add> $animate.enter(clone, null, previousNode);
<ide> previousNode = endNode;
<ide> // Note: We only need the first/last node of the cloned nodes.
<ide> // However, we need to keep the reference to the jqlite wrapper as it might be changed later | 1 |
Ruby | Ruby | hide gcc warnings in `config` output | a59c1ae6cb90644869862e6432ed8e82ac361ebe | <ide><path>Library/Homebrew/os/mac.rb
<ide> def default_compiler
<ide> def gcc_40_build_version
<ide> @gcc_40_build_version ||=
<ide> if (path = locate("gcc-4.0"))
<del> `#{path} --version`[/build (\d{4,})/, 1].to_i
<add> `#{path} --version 2>/dev/null`[/build (\d{4,})/, 1].to_i
<ide> end
<ide> end
<ide> alias_method :gcc_4_0_build_version, :gcc_40_build_version
<ide> def gcc_42_build_version
<ide> begin
<ide> gcc = MacOS.locate("gcc-4.2") || HOMEBREW_PREFIX.join("opt/apple-gcc42/bin/gcc-4.2")
<ide> if gcc.exist? && !gcc.realpath.basename.to_s.start_with?("llvm")
<del> `#{gcc} --version`[/build (\d{4,})/, 1].to_i
<add> `#{gcc} --version 2>/dev/null`[/build (\d{4,})/, 1].to_i
<ide> end
<ide> end
<ide> end | 1 |
Text | Text | fix the desc for image_alt change [ci skip] | 1ba8412607ae7190dc1c59718099e2f04372905d | <ide><path>guides/source/5_2_release_notes.md
<ide> Please refer to the [Changelog][action-view] for detailed changes.
<ide> ### Deprecations
<ide>
<ide> * Deprecated `image_alt` helper which used to add default alt text to
<del> the image text.
<add> the images generated by `image_tag`.
<ide> ([Pull Request](https://github.com/rails/rails/pull/30213))
<ide>
<ide> ### Notable changes | 1 |
PHP | PHP | add original parameters to route | 14b1b506d3cb14bf7aa70e8134f32416c9ef0f0f | <ide><path>src/Illuminate/Routing/Route.php
<ide> class Route
<ide> */
<ide> public $compiled;
<ide>
<add> /**
<add> * The matched parameters' original state.
<add> *
<add> * @var array
<add> */
<add> protected $originalParameters;
<add>
<ide> /**
<ide> * The router instance used by the route.
<ide> *
<ide> public function bind(Request $request)
<ide> $this->parameters = (new RouteParameterBinder($this))
<ide> ->parameters($request);
<ide>
<add> $this->originalParameters = $this->parameters;
<add>
<ide> return $this;
<ide> }
<ide>
<ide> public function parameter($name, $default = null)
<ide> return Arr::get($this->parameters(), $name, $default);
<ide> }
<ide>
<add> /**
<add> * Get original value of a given parameter from the route.
<add> *
<add> * @param string $name
<add> * @param mixed $default
<add> * @return string|object
<add> */
<add> public function originalParameter($name, $default = null)
<add> {
<add> return Arr::get($this->originalParameters(), $name, $default);
<add> }
<add>
<ide> /**
<ide> * Set a parameter to the given value.
<ide> *
<ide> public function parameters()
<ide> throw new LogicException('Route is not bound.');
<ide> }
<ide>
<add> /**
<add> * Get the key / value list of original parameters for the route.
<add> *
<add> * @return array
<add> *
<add> * @throws \LogicException
<add> */
<add> public function originalParameters()
<add> {
<add> if (isset($this->originalParameters)) {
<add> return $this->originalParameters;
<add> }
<add>
<add> throw new LogicException('Route is not bound.');
<add> }
<add>
<ide> /**
<ide> * Get the key / value list of parameters without null values.
<ide> * | 1 |
PHP | PHP | fix failing test | 9089bba84b519ca312b9100bb048c96fab59fb2b | <ide><path>lib/Cake/Test/Case/View/Helper/HtmlHelperTest.php
<ide> public function testLink() {
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<del> Configure::write('Asset.timestamp', 'force');
<del>
<ide> $result = $this->Html->link($this->Html->image('../favicon.ico'), '#', array('escape' => false));
<ide> $expected = array(
<ide> 'a' => array('href' => '#'),
<ide> public function testLink() {
<ide> $this->assertTags($result, $expected);
<ide>
<ide> $result = $this->Html->image('../favicon.ico', array('url' => '#'));
<del>
<ide> $expected = array(
<ide> 'a' => array('href' => '#'),
<ide> 'img' => array('src' => 'img/../favicon.ico', 'alt' => ''), | 1 |
Javascript | Javascript | remove unused frustumboundingbox file | 74d0bca4fa8c78ea00b1132f3c5f03b89d3d1887 | <ide><path>examples/jsm/csm/FrustumBoundingBox.js
<del>/**
<del> * @author vHawk / https://github.com/vHawk/
<del> */
<del>
<del>export default class FrustumBoundingBox {
<del>
<del> constructor() {
<del>
<del> this.min = {
<del> x: 0,
<del> y: 0,
<del> z: 0
<del> };
<del> this.max = {
<del> x: 0,
<del> y: 0,
<del> z: 0
<del> };
<del>
<del> }
<del>
<del> fromFrustum( frustum ) {
<del>
<del> const vertices = [];
<del>
<del> for ( let i = 0; i < 4; i ++ ) {
<del>
<del> vertices.push( frustum.vertices.near[ i ] );
<del> vertices.push( frustum.vertices.far[ i ] );
<del>
<del> }
<del>
<del> this.min = {
<del> x: vertices[ 0 ].x,
<del> y: vertices[ 0 ].y,
<del> z: vertices[ 0 ].z
<del> };
<del> this.max = {
<del> x: vertices[ 0 ].x,
<del> y: vertices[ 0 ].y,
<del> z: vertices[ 0 ].z
<del> };
<del>
<del> for ( let i = 1; i < 8; i ++ ) {
<del>
<del> this.min.x = Math.min( this.min.x, vertices[ i ].x );
<del> this.min.y = Math.min( this.min.y, vertices[ i ].y );
<del> this.min.z = Math.min( this.min.z, vertices[ i ].z );
<del> this.max.x = Math.max( this.max.x, vertices[ i ].x );
<del> this.max.y = Math.max( this.max.y, vertices[ i ].y );
<del> this.max.z = Math.max( this.max.z, vertices[ i ].z );
<del>
<del> }
<del>
<del> return this;
<del>
<del> }
<del>
<del> getSize() {
<del>
<del> this.size = {
<del> x: this.max.x - this.min.x,
<del> y: this.max.y - this.min.y,
<del> z: this.max.z - this.min.z
<del> };
<del>
<del> return this.size;
<del>
<del> }
<del>
<del> getCenter( margin ) {
<del>
<del> this.center = {
<del> x: ( this.max.x + this.min.x ) / 2,
<del> y: ( this.max.y + this.min.y ) / 2,
<del> z: this.max.z + margin
<del> };
<del>
<del> return this.center;
<del>
<del> }
<del>
<del>} | 1 |
Ruby | Ruby | allow deprecated options on new @ formulae | 1980af52deb5629c9f605017c6261a94f9e2b3e7 | <ide><path>Library/Homebrew/dev-cmd/audit.rb
<ide> def audit_options
<ide>
<ide> return unless @new_formula
<ide> return if formula.deprecated_options.empty?
<add> return if formula.name.include?("@")
<ide> problem "New formulae should not use `deprecated_option`."
<ide> end
<ide> | 1 |
Python | Python | add max_results param | da56ad5f684ebf99b892030c89748edbf5aada60 | <ide><path>libcloud/compute/drivers/gce.py
<ide> def paginated_request(self, *args, **kwargs):
<ide> """
<ide> more_results = True
<ide> items = []
<del> params = {"maxResults": 500}
<add> max_results = kwargs["max_results"] if "max_results" in kwargs else 500
<add> params = {"maxResults": max_results}
<ide> while more_results:
<ide> self.gce_params = params
<ide> response = self.request(*args, **kwargs) | 1 |
Javascript | Javascript | fix typo in animationclip | a7a9edc24048078843e35b1d069a77961924a1f8 | <ide><path>src/animation/AnimationClip.js
<ide> AnimationClip.prototype = {
<ide>
<ide> var track = this.tracks[ i ];
<ide>
<del> duration = Math.max(
<del> duration, track.times[ track.times.length - 1 ] );
<add> duration = Math.max( duration, track.times[ track.times.length - 1 ] );
<ide>
<ide> }
<ide> | 1 |
Javascript | Javascript | add moment.isdate method | 9b68dacfbb61633de96fe34054cd3c4d4974c413 | <ide><path>moment.js
<ide> return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
<ide> };
<ide>
<add> moment.isDate = isDate;
<add>
<ide> /************************************
<ide> Moment Prototype
<ide> ************************************/
<ide><path>test/moment/is_date.js
<add>var moment = require('../../moment');
<add>
<add>exports.add = {
<add> setUp : function (done) {
<add> moment.createFromInputFallback = function () {
<add> throw new Error('input not handled by moment');
<add> };
<add> done();
<add> },
<add>
<add> 'isDate recognizes Date objects' : function (test) {
<add> test.ok(moment.isDate(new Date()), 'no args (now)');
<add> test.ok(moment.isDate(new Date([2014, 02, 15])), 'array args');
<add> test.ok(moment.isDate(new Date('2014-03-15')), 'string args');
<add> test.ok(moment.isDate(new Date('does NOT look like a date')), 'invalid date');
<add> test.done();
<add> },
<add>
<add> 'isDate rejects non-Date objects' : function (test) {
<add> test.ok(!moment.isDate(), 'nothing');
<add> test.ok(!moment.isDate(undefined), 'undefined');
<add> test.ok(!moment.isDate(null), 'string args');
<add> test.ok(!moment.isDate(42), 'number');
<add> test.ok(!moment.isDate('2014-03-15'), 'string');
<add> test.ok(!moment.isDate([2014, 2, 15]), 'array');
<add> test.ok(!moment.isDate({year: 2014, month: 2, day: 15}), 'object');
<add> test.ok(!moment.isDate({toString: function () {
<add> return '[object Date]';
<add> }}), 'lying object');
<add> test.done();
<add> }
<add>}; | 2 |
PHP | PHP | add test case | c2df1fb71aa06e0daa484561d21f5f34f80d670e | <ide><path>tests/TestCase/Datasource/PaginatorTest.php
<ide> public function testDefaultPaginateParams()
<ide> $this->Paginator->paginate($table, [], $settings);
<ide> }
<ide>
<add> /**
<add> * Tests that flat default pagination parameters work for multi order.
<add> *
<add> * @return void
<add> */
<add> public function testDefaultPaginateParamsMultiOrder()
<add> {
<add> $settings = [
<add> 'order' => ['PaginatorPosts.id' => 'DESC', 'PaginatorPosts.title' => 'ASC'],
<add> ];
<add>
<add> $table = $this->_getMockPosts(['query']);
<add> $query = $this->_getMockFindQuery();
<add>
<add> $table->expects($this->once())
<add> ->method('query')
<add> ->will($this->returnValue($query));
<add>
<add> $query->expects($this->once())
<add> ->method('applyOptions')
<add> ->with([
<add> 'limit' => 20,
<add> 'page' => 1,
<add> 'order' => $settings['order'],
<add> 'whitelist' => ['limit', 'sort', 'page', 'direction'],
<add> 'scope' => null,
<add> 'sort' => null,
<add> ]);
<add>
<add> $this->Paginator->paginate($table, [], $settings);
<add>
<add> $pagingParams = $this->Paginator->getPagingParams();
<add> $this->assertNull($pagingParams['PaginatorPosts']['direction']);
<add> $this->assertFalse($pagingParams['PaginatorPosts']['sortDefault']);
<add> $this->assertFalse($pagingParams['PaginatorPosts']['directionDefault']);
<add> }
<add>
<ide> /**
<ide> * test that default sort and default direction are injected into request
<ide> * | 1 |
Python | Python | handle odd scipy installations | d04bb02f393f0122e52b804bf548e0e18a0a2ecc | <ide><path>numpy/dual.py
<ide> have_scipy = 0
<ide> try:
<ide> import scipy
<del> if scipy.__version__ >= '0.4.4':
<add> if getattr(scipy, '__version__', None) >= '0.4.4':
<ide> have_scipy = 1
<ide> except ImportError:
<ide> pass | 1 |
Javascript | Javascript | replace frustumboundingbox use with box3 | f54797b4c33aaa51896ba57d9927370feb0eb84f | <ide><path>examples/jsm/csm/CSM.js
<ide> import {
<ide> BufferGeometry,
<ide> BufferAttribute,
<ide> Line,
<del> Matrix4
<add> Matrix4,
<add> Box3
<ide> } from '../../../build/three.module.js';
<ide> import Frustum from './Frustum.js';
<del>import FrustumBoundingBox from './FrustumBoundingBox.js';
<ide> import Shader from './Shader.js';
<ide>
<ide> const _cameraToLightMatrix = new Matrix4();
<ide> const _lightSpaceFrustum = new Frustum();
<ide> const _frustum = new Frustum();
<ide> const _center = new Vector3();
<del>const _bbox = new FrustumBoundingBox();
<add>const _size = new Vector3();
<add>const _bbox = new Box3();
<ide> const _uniformArray = [];
<ide> const _logArray = [];
<ide>
<ide> export default class CSM {
<ide> for ( let i = 0; i < this.frustums.length; i ++ ) {
<ide>
<ide> const light = this.lights[ i ];
<add> light.shadow.camera.updateMatrixWorld( true );
<ide> _cameraToLightMatrix.multiplyMatrices( light.shadow.camera.matrixWorldInverse, cameraMatrix );
<ide> this.frustums[ i ].toSpace( _cameraToLightMatrix, _lightSpaceFrustum );
<ide>
<del> light.shadow.camera.updateMatrixWorld( true );
<add> _bbox.makeEmpty();
<add> for ( let j = 0; j < 4; j ++ ) {
<ide>
<del> _bbox.fromFrustum( _lightSpaceFrustum );
<del> _bbox.getSize();
<del> _bbox.getCenter( this.lightMargin );
<add> _bbox.expandByPoint( _lightSpaceFrustum.vertices.near[ j ] );
<add> _bbox.expandByPoint( _lightSpaceFrustum.vertices.far[ j ] );
<ide>
<del> const squaredBBWidth = Math.max( _bbox.size.x, _bbox.size.y );
<add> }
<ide>
<del> _center.copy( _bbox.center );
<add> _bbox.getSize( _size );
<add> _bbox.getCenter( _center );
<add> _center.z = _bbox.max.z + this.lightMargin;
<ide> _center.applyMatrix4( light.shadow.camera.matrixWorld );
<ide>
<add> const squaredBBWidth = Math.max( _size.x, _size.y );
<ide> light.shadow.camera.left = - squaredBBWidth / 2;
<ide> light.shadow.camera.right = squaredBBWidth / 2;
<ide> light.shadow.camera.top = squaredBBWidth / 2; | 1 |
Javascript | Javascript | simplify d8-runner and add simple app | 9d31a6d0aca41f0c0cd901ee01948394078e90c8 | <ide><path>d8-app.js
<add>var Router = Ember.Router.extend({
<add> location: 'none',
<add> rootURL: '/'
<add>});
<add>Router.map(function() {
<add> this.route('my-route', { path: '/my-route' }, function () {
<add> });
<add>});
<add>Ember.TEMPLATES['index'] = Ember.HTMLBars.template({"id":null,"block":"{\"statements\":[[\"text\",\"index\"]],\"locals\":[],\"named\":[],\"yields\":[],\"blocks\":[],\"hasPartials\":false}","meta":{}});
<add>Ember.TEMPLATES['my-route/index'] = Ember.HTMLBars.template({"id":null,"block":"{\"statements\":[[\"text\",\"my-route\"]],\"locals\":[],\"named\":[],\"yields\":[],\"blocks\":[],\"hasPartials\":false}","meta":{}});
<add>var App = Ember.Application.extend({
<add> Router: Router,
<add> autoboot: false
<add>});
<add>var app = new App();
<add>var serializer = new SimpleDOM.HTMLSerializer(SimpleDOM.voidMap);
<add>var doc = new SimpleDOM.Document();
<add>var options = {
<add> isBrowser: false,
<add> document: doc,
<add> rootElement: doc.body,
<add> shouldRender: true
<add>};
<add>app.visit('/', options).then(function (instance) {
<add> print(serializer.serialize(doc.body));
<add> var router = instance.lookup('router:main');
<add> return router.transitionTo('/my-route');
<add>}).then(function () {
<add> return new Ember.RSVP.Promise(function (resolve) {
<add> Ember.run.schedule('afterRender', resolve)
<add> });
<add>}).then(function () {
<add> print(serializer.serialize(doc.body));
<add>}).catch(function (err) {
<add> print(err.stack);
<add>});
<ide><path>d8-runner.js
<ide> // begin MISC setup;
<ide> const global = new Function('return this;')();
<ide> global.self = global;
<del>global.window = {};
<ide> function loadFile(file) {
<ide> print('load: ' + file);
<ide> load(file);
<ide> global.setTimeout = function(callback) {
<ide> Promise.resolve().then(callback).catch(e => print('error' + e));
<ide> };
<ide> loadFile('./node_modules/simple-dom/dist/simple-dom.js');
<del>const document = new SimpleDOM.Document();
<del>document.createElementNS = document.createElement; // TODO:wat
<del>global.document = document;
<del>SimpleDOM.Node.prototype.insertAdjacentHTML = function( ) {};
<add>
<add>// url protocol
<add>global.URL = {};
<ide>
<ide> // end MISC setup
<ide>
<ide> // Load the ember you want
<del>loadFile('./dist/ember.js'); // prod build === no asserts and dev related code
<add>loadFile('./dist/ember.prod.js'); // prod build === no asserts and dev related code
<ide> // loadFile('/dist/ember.min.js'); // prod build + minified
<ide> // loadFile('/dist/ember.debug.js'); // debug build === asserts and stuff, has perf issues
<ide>
<add>
<ide> // do what you want
<del>console.log(Ember);
<add>
<add>// try running `d8 d8-runner.js d8-app.js` | 2 |
Python | Python | add tests for non-iterable input.. | 4aac3ae8dd02d070b8641113e0c486e7213a5c9a | <ide><path>numpy/core/tests/test_shape_base.py
<ide> def test_3D_array(self):
<ide>
<ide>
<ide> class TestHstack(TestCase):
<add> def test_non_iterable(self):
<add> assert_raises(TypeError, hstack, 1)
<add>
<ide> def test_0D_array(self):
<ide> a = array(1)
<ide> b = array(2)
<ide> def test_2D_array(self):
<ide>
<ide>
<ide> class TestVstack(TestCase):
<add> def test_non_iterable(self):
<add> assert_raises(TypeError, vstack, 1)
<add>
<ide> def test_0D_array(self):
<ide> a = array(1)
<ide> b = array(2)
<ide> def test_concatenate(self):
<ide>
<ide>
<ide> def test_stack():
<add> # non-iterable input
<add> assert_raises(TypeError, stack, 1)
<add>
<ide> # 0d input
<ide> for input_ in [(1, 2, 3),
<ide> [np.int32(1), np.int32(2), np.int32(3)],
<ide><path>numpy/lib/tests/test_shape_base.py
<ide> import numpy as np
<ide> from numpy.lib.shape_base import (
<ide> apply_along_axis, apply_over_axes, array_split, split, hsplit, dsplit,
<del> vsplit, dstack, kron, tile
<add> vsplit, dstack, column_stack, kron, tile
<ide> )
<ide> from numpy.testing import (
<ide> run_module_suite, TestCase, assert_, assert_equal, assert_array_equal,
<ide> def test_unequal_split(self):
<ide> a = np.arange(10)
<ide> assert_raises(ValueError, split, a, 3)
<ide>
<add>class TestColumnStack(TestCase):
<add> def test_non_iterable(self):
<add> assert_raises(TypeError, column_stack, 1)
<add>
<ide>
<ide> class TestDstack(TestCase):
<add> def test_non_iterable(self):
<add> assert_raises(TypeError, dstack, 1)
<add>
<ide> def test_0D_array(self):
<ide> a = np.array(1)
<ide> b = np.array(2)
<ide> class TestHsplit(TestCase):
<ide> """Only testing for integer splits.
<ide>
<ide> """
<add> def test_non_iterable(self):
<add> assert_raises(ValueError, hsplit, 1, 1)
<add>
<ide> def test_0D_array(self):
<ide> a = np.array(1)
<ide> try:
<ide> class TestVsplit(TestCase):
<ide> """Only testing for integer splits.
<ide>
<ide> """
<add> def test_non_iterable(self):
<add> assert_raises(ValueError, vsplit, 1, 1)
<add>
<add> def test_0D_array(self):
<add> a = np.array(1)
<add> assert_raises(ValueError, vsplit, a, 2)
<add>
<ide> def test_1D_array(self):
<ide> a = np.array([1, 2, 3, 4])
<ide> try:
<ide> def test_2D_array(self):
<ide>
<ide> class TestDsplit(TestCase):
<ide> # Only testing for integer splits.
<add> def test_non_iterable(self):
<add> assert_raises(ValueError, dsplit, 1, 1)
<add>
<add> def test_0D_array(self):
<add> a = np.array(1)
<add> assert_raises(ValueError, dsplit, a, 2)
<add>
<add> def test_1D_array(self):
<add> a = np.array([1, 2, 3, 4])
<add> assert_raises(ValueError, dsplit, a, 2)
<ide>
<ide> def test_2D_array(self):
<ide> a = np.array([[1, 2, 3, 4], | 2 |
Text | Text | add v3.24.5 to changelog.md | c166010bac915977bda513d389e80d37074e0da2 | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<del>## v3.28.0 (August 9, 2021)
<add>### v3.28.0 (August 9, 2021)
<ide>
<ide> - [#19697](https://github.com/emberjs/ember.js/pull/19697) [BUGFIX] Ensure `deserializeQueryParam` is called for lazy routes
<ide> - [#19681](https://github.com/emberjs/ember.js/pull/19681) [BUGFIX] Restore previous hash behavior
<ide> - [#19491](https://github.com/emberjs/ember.js/pull/19491) [BUGFIX] Fix `owner.lookup` `owner.register` behavior with `singleton: true` option
<ide> - [#19472](https://github.com/emberjs/ember.js/pull/19472) [BUGFIX] Prevent transformation of block params called `attrs`
<ide>
<add>### v3.24.5 (August 9, 2021)
<add>
<add>- [#19685](https://github.com/emberjs/ember.js/pull/19685) Fix memory leak with `RouterService` under Chrome
<add>- [#19683](https://github.com/emberjs/ember.js/pull/19683) Ensure `super.willDestroy` is called correctly in `Router`'s `willDestroy`
<add>
<ide> ### v3.27.5 (June 10, 2021)
<ide>
<ide> - [#19597](https://github.com/emberjs/ember.js/pull/19597) [BIGFIX] Fix `<LinkTo>` with nested children | 1 |
Javascript | Javascript | allow missing callback for socket.connect | c6cbbf92630069f7f7c29e4dff2f622d48d741d5 | <ide><path>lib/net.js
<ide> function connect(self, address, port, addressType, localAddress, localPort) {
<ide> }
<ide>
<ide>
<del>Socket.prototype.connect = function(options, cb) {
<add>Socket.prototype.connect = function() {
<add> const args = new Array(arguments.length);
<add> for (var i = 0; i < arguments.length; i++)
<add> args[i] = arguments[i];
<add> // TODO(joyeecheung): use destructuring when V8 is fast enough
<add> const normalized = normalizeArgs(args);
<add> const options = normalized[0];
<add> const cb = normalized[1];
<add>
<ide> if (this.write !== Socket.prototype.write)
<ide> this.write = Socket.prototype.write;
<ide>
<del> if (options === null || typeof options !== 'object') {
<del> // Old API:
<del> // connect(port[, host][, cb])
<del> // connect(path[, cb]);
<del> const args = new Array(arguments.length);
<del> for (var i = 0; i < arguments.length; i++)
<del> args[i] = arguments[i];
<del> const normalized = normalizeArgs(args);
<del> const normalizedOptions = normalized[0];
<del> const normalizedCb = normalized[1];
<del> return Socket.prototype.connect.call(this,
<del> normalizedOptions, normalizedCb);
<del> }
<del>
<ide> if (this.destroyed) {
<ide> this._readableState.reading = false;
<ide> this._readableState.ended = false;
<ide><path>test/parallel/test-net-socket-connect-without-cb.js
<add>'use strict';
<add>const common = require('../common');
<add>
<add>// This test ensures that socket.connect can be called without callback
<add>// which is optional.
<add>
<add>const net = require('net');
<add>
<add>const server = net.createServer(common.mustCall(function(conn) {
<add> conn.end();
<add> server.close();
<add>})).listen(0, common.mustCall(function() {
<add> const client = new net.Socket();
<add>
<add> client.on('connect', common.mustCall(function() {
<add> client.end();
<add> }));
<add>
<add> client.connect(server.address());
<add>})); | 2 |
Python | Python | azure key vault optional lookup | 3ff7e0743a1156efe1d6aaf7b8f82136d0bba08f | <ide><path>airflow/providers/microsoft/azure/secrets/azure_key_vault.py
<ide> class AzureKeyVaultBackend(BaseSecretsBackend, LoggingMixin):
<ide> if you provide ``{"variables_prefix": "airflow-variables"}`` and request variable key ``hello``.
<ide>
<ide> :param connections_prefix: Specifies the prefix of the secret to read to get Connections
<add> If set to None (null), requests for connections will not be sent to Azure Key Vault
<ide> :type connections_prefix: str
<ide> :param variables_prefix: Specifies the prefix of the secret to read to get Variables
<add> If set to None (null), requests for variables will not be sent to Azure Key Vault
<ide> :type variables_prefix: str
<ide> :param config_prefix: Specifies the prefix of the secret to read to get Variables.
<add> If set to None (null), requests for configurations will not be sent to Azure Key Vault
<ide> :type config_prefix: str
<ide> :param vault_url: The URL of an Azure Key Vault to use
<ide> :type vault_url: str
<ide> def __init__(
<ide> ) -> None:
<ide> super().__init__()
<ide> self.vault_url = vault_url
<del> self.connections_prefix = connections_prefix.rstrip(sep)
<del> self.variables_prefix = variables_prefix.rstrip(sep)
<del> self.config_prefix = config_prefix.rstrip(sep)
<add> if connections_prefix is not None:
<add> self.connections_prefix = connections_prefix.rstrip(sep)
<add> else:
<add> self.connections_prefix = connections_prefix
<add> if variables_prefix is not None:
<add> self.variables_prefix = variables_prefix.rstrip(sep)
<add> else:
<add> self.variables_prefix = variables_prefix
<add> if config_prefix is not None:
<add> self.config_prefix = config_prefix.rstrip(sep)
<add> else:
<add> self.config_prefix = config_prefix
<ide> self.sep = sep
<ide> self.kwargs = kwargs
<ide>
<ide> def get_conn_uri(self, conn_id: str) -> Optional[str]:
<ide> :param conn_id: The Airflow connection id to retrieve
<ide> :type conn_id: str
<ide> """
<add> if self.connections_prefix is None:
<add> return None
<add>
<ide> return self._get_secret(self.connections_prefix, conn_id)
<ide>
<ide> def get_variable(self, key: str) -> Optional[str]:
<ide> def get_variable(self, key: str) -> Optional[str]:
<ide> :type key: str
<ide> :return: Variable Value
<ide> """
<add> if self.variables_prefix is None:
<add> return None
<add>
<ide> return self._get_secret(self.variables_prefix, key)
<ide>
<ide> def get_config(self, key: str) -> Optional[str]:
<ide> def get_config(self, key: str) -> Optional[str]:
<ide> :param key: Configuration Option Key
<ide> :return: Configuration Option Value
<ide> """
<add> if self.config_prefix is None:
<add> return None
<add>
<ide> return self._get_secret(self.config_prefix, key)
<ide>
<ide> @staticmethod
<ide><path>tests/providers/microsoft/azure/secrets/test_azure_key_vault.py
<ide> def test_get_secret_value(self, mock_client):
<ide> secret_val = backend._get_secret('af-secrets', 'test_mysql_password')
<ide> mock_client.get_secret.assert_called_with(name='af-secrets-test-mysql-password')
<ide> self.assertEqual(secret_val, 'super-secret')
<add>
<add> @mock.patch('airflow.providers.microsoft.azure.secrets.azure_key_vault.AzureKeyVaultBackend._get_secret')
<add> def test_connection_prefix_none_value(self, mock_get_secret):
<add> """
<add> Test that if Connections prefix is None,
<add> AzureKeyVaultBackend.get_connections should return None
<add> AzureKeyVaultBackend._get_secret should not be called
<add> """
<add> kwargs = {'connections_prefix': None}
<add>
<add> backend = AzureKeyVaultBackend(**kwargs)
<add> self.assertIsNone(backend.get_conn_uri('test_mysql'))
<add> mock_get_secret._get_secret.assert_not_called()
<add>
<add> @mock.patch('airflow.providers.microsoft.azure.secrets.azure_key_vault.AzureKeyVaultBackend._get_secret')
<add> def test_variable_prefix_none_value(self, mock_get_secret):
<add> """
<add> Test that if Variables prefix is None,
<add> AzureKeyVaultBackend.get_variables should return None
<add> AzureKeyVaultBackend._get_secret should not be called
<add> """
<add> kwargs = {'variables_prefix': None}
<add>
<add> backend = AzureKeyVaultBackend(**kwargs)
<add> self.assertIsNone(backend.get_variable('hello'))
<add> mock_get_secret._get_secret.assert_not_called()
<add>
<add> @mock.patch('airflow.providers.microsoft.azure.secrets.azure_key_vault.AzureKeyVaultBackend._get_secret')
<add> def test_config_prefix_none_value(self, mock_get_secret):
<add> """
<add> Test that if Config prefix is None,
<add> AzureKeyVaultBackend.get_config should return None
<add> AzureKeyVaultBackend._get_secret should not be called
<add> """
<add> kwargs = {'config_prefix': None}
<add>
<add> backend = AzureKeyVaultBackend(**kwargs)
<add> self.assertIsNone(backend.get_config('test_mysql'))
<add> mock_get_secret._get_secret.assert_not_called() | 2 |
Go | Go | return devmapper errors with additional text | 69640123826cf73d3d83182cb81e5de4ad0cc3a7 | <ide><path>daemon/graphdriver/devmapper/devmapper.go
<ide> func createPool(poolName string, dataFile, metadataFile *os.File) error {
<ide>
<ide> size, err := GetBlockDeviceSize(dataFile)
<ide> if err != nil {
<del> return fmt.Errorf("Can't get data size")
<add> return fmt.Errorf("Can't get data size %s", err)
<ide> }
<ide>
<ide> params := metadataFile.Name() + " " + dataFile.Name() + " 128 32768 1 skip_block_zeroing"
<ide> if err := task.AddTarget(0, size/512, "thin-pool", params); err != nil {
<del> return fmt.Errorf("Can't add target")
<add> return fmt.Errorf("Can't add target %s", err)
<ide> }
<ide>
<ide> var cookie uint = 0
<ide> if err := task.SetCookie(&cookie, 0); err != nil {
<del> return fmt.Errorf("Can't set cookie")
<add> return fmt.Errorf("Can't set cookie %s", err)
<ide> }
<ide>
<ide> if err := task.Run(); err != nil {
<del> return fmt.Errorf("Error running DeviceCreate (createPool)")
<add> return fmt.Errorf("Error running DeviceCreate (createPool) %s", err)
<ide> }
<ide>
<ide> UdevWait(cookie)
<ide> func reloadPool(poolName string, dataFile, metadataFile *os.File) error {
<ide>
<ide> size, err := GetBlockDeviceSize(dataFile)
<ide> if err != nil {
<del> return fmt.Errorf("Can't get data size")
<add> return fmt.Errorf("Can't get data size %s", err)
<ide> }
<ide>
<ide> params := metadataFile.Name() + " " + dataFile.Name() + " 128 32768"
<ide> if err := task.AddTarget(0, size/512, "thin-pool", params); err != nil {
<del> return fmt.Errorf("Can't add target")
<add> return fmt.Errorf("Can't add target %s", err)
<ide> }
<ide>
<ide> if err := task.Run(); err != nil {
<del> return fmt.Errorf("Error running DeviceCreate")
<add> return fmt.Errorf("Error running DeviceCreate %s", err)
<ide> }
<ide>
<ide> return nil
<ide> func setTransactionId(poolName string, oldId uint64, newId uint64) error {
<ide> }
<ide>
<ide> if err := task.SetSector(0); err != nil {
<del> return fmt.Errorf("Can't set sector")
<add> return fmt.Errorf("Can't set sector %s", err)
<ide> }
<ide>
<ide> if err := task.SetMessage(fmt.Sprintf("set_transaction_id %d %d", oldId, newId)); err != nil {
<del> return fmt.Errorf("Can't set message")
<add> return fmt.Errorf("Can't set message %s", err)
<ide> }
<ide>
<ide> if err := task.Run(); err != nil {
<del> return fmt.Errorf("Error running setTransactionId")
<add> return fmt.Errorf("Error running setTransactionId %s", err)
<ide> }
<ide> return nil
<ide> }
<ide> func suspendDevice(name string) error {
<ide> return err
<ide> }
<ide> if err := task.Run(); err != nil {
<del> return fmt.Errorf("Error running DeviceSuspend: %s", err)
<add> return fmt.Errorf("Error running DeviceSuspend %s", err)
<ide> }
<ide> return nil
<ide> }
<ide> func resumeDevice(name string) error {
<ide>
<ide> var cookie uint = 0
<ide> if err := task.SetCookie(&cookie, 0); err != nil {
<del> return fmt.Errorf("Can't set cookie")
<add> return fmt.Errorf("Can't set cookie %s", err)
<ide> }
<ide>
<ide> if err := task.Run(); err != nil {
<del> return fmt.Errorf("Error running DeviceResume")
<add> return fmt.Errorf("Error running DeviceResume %s", err)
<ide> }
<ide>
<ide> UdevWait(cookie)
<ide> func createDevice(poolName string, deviceId *int) error {
<ide> }
<ide>
<ide> if err := task.SetSector(0); err != nil {
<del> return fmt.Errorf("Can't set sector")
<add> return fmt.Errorf("Can't set sector %s", err)
<ide> }
<ide>
<ide> if err := task.SetMessage(fmt.Sprintf("create_thin %d", *deviceId)); err != nil {
<del> return fmt.Errorf("Can't set message")
<add> return fmt.Errorf("Can't set message %s", err)
<ide> }
<ide>
<ide> dmSawExist = false
<ide> func createDevice(poolName string, deviceId *int) error {
<ide> *deviceId++
<ide> continue
<ide> }
<del> return fmt.Errorf("Error running createDevice")
<add> return fmt.Errorf("Error running createDevice %s", err)
<ide> }
<ide> break
<ide> }
<ide> func deleteDevice(poolName string, deviceId int) error {
<ide> }
<ide>
<ide> if err := task.SetSector(0); err != nil {
<del> return fmt.Errorf("Can't set sector")
<add> return fmt.Errorf("Can't set sector %s", err)
<ide> }
<ide>
<ide> if err := task.SetMessage(fmt.Sprintf("delete %d", deviceId)); err != nil {
<del> return fmt.Errorf("Can't set message")
<add> return fmt.Errorf("Can't set message %s", err)
<ide> }
<ide>
<ide> if err := task.Run(); err != nil {
<del> return fmt.Errorf("Error running deleteDevice")
<add> return fmt.Errorf("Error running deleteDevice %s", err)
<ide> }
<ide> return nil
<ide> }
<ide> func removeDevice(name string) error {
<ide> if dmSawBusy {
<ide> return ErrBusy
<ide> }
<del> return fmt.Errorf("Error running removeDevice")
<add> return fmt.Errorf("Error running removeDevice %s", err)
<ide> }
<ide> return nil
<ide> }
<ide> func activateDevice(poolName string, name string, deviceId int, size uint64) err
<ide>
<ide> params := fmt.Sprintf("%s %d", poolName, deviceId)
<ide> if err := task.AddTarget(0, size/512, "thin", params); err != nil {
<del> return fmt.Errorf("Can't add target")
<add> return fmt.Errorf("Can't add target %s", err)
<ide> }
<ide> if err := task.SetAddNode(AddNodeOnCreate); err != nil {
<del> return fmt.Errorf("Can't add node")
<add> return fmt.Errorf("Can't add node %s", err)
<ide> }
<ide>
<ide> var cookie uint = 0
<ide> if err := task.SetCookie(&cookie, 0); err != nil {
<del> return fmt.Errorf("Can't set cookie")
<add> return fmt.Errorf("Can't set cookie %s", err)
<ide> }
<ide>
<ide> if err := task.Run(); err != nil {
<del> return fmt.Errorf("Error running DeviceCreate (activateDevice)")
<add> return fmt.Errorf("Error running DeviceCreate (activateDevice) %s", err)
<ide> }
<ide>
<ide> UdevWait(cookie)
<ide> func createSnapDevice(poolName string, deviceId *int, baseName string, baseDevic
<ide> if doSuspend {
<ide> resumeDevice(baseName)
<ide> }
<del> return fmt.Errorf("Can't set sector")
<add> return fmt.Errorf("Can't set sector %s", err)
<ide> }
<ide>
<ide> if err := task.SetMessage(fmt.Sprintf("create_snap %d %d", *deviceId, baseDeviceId)); err != nil {
<ide> if doSuspend {
<ide> resumeDevice(baseName)
<ide> }
<del> return fmt.Errorf("Can't set message")
<add> return fmt.Errorf("Can't set message %s", err)
<ide> }
<ide>
<ide> dmSawExist = false
<ide> func createSnapDevice(poolName string, deviceId *int, baseName string, baseDevic
<ide> if doSuspend {
<ide> resumeDevice(baseName)
<ide> }
<del> return fmt.Errorf("Error running DeviceCreate (createSnapDevice)")
<add> return fmt.Errorf("Error running DeviceCreate (createSnapDevice) %s", err)
<ide> }
<ide>
<ide> break | 1 |
Text | Text | fix broken link for childprocess | 760a6c80e5cd7c1b47f8788efd5f26902e5822a4 | <ide><path>doc/api/child_process.md
<ide> or [`child_process.fork()`][].
<ide> [`'error'`]: #child_process_event_error
<ide> [`'exit'`]: #child_process_event_exit
<ide> [`'message'`]: process.md#process_event_message
<del>[`ChildProcess`]: #child_process_child_process
<add>[`ChildProcess`]: #child_process_class_childprocess
<ide> [`Error`]: errors.md#errors_class_error
<ide> [`EventEmitter`]: events.md#events_class_eventemitter
<ide> [`child_process.exec()`]: #child_process_child_process_exec_command_options_callback | 1 |
Text | Text | add link to abi guide | 157d507d64d471cfcd77ce0e10d80fb102ca065c | <ide><path>doc/api/n-api.md
<ide> the underlying JavaScript runtime (ex V8) and is maintained as part of
<ide> Node.js itself. This API will be Application Binary Interface (ABI) stable
<ide> across versions of Node.js. It is intended to insulate Addons from
<ide> changes in the underlying JavaScript engine and allow modules
<del>compiled for one version to run on later versions of Node.js without
<del>recompilation.
<add>compiled for one major version to run on later major versions of Node.js without
<add>recompilation. The [ABI Stability][] guide provides a more in-depth explanation.
<ide>
<ide> Addons are built/packaged with the same approach/tools
<ide> outlined in the section titled [C++ Addons](addons.html).
<ide> idempotent.
<ide>
<ide> This API may only be called from the main thread.
<ide>
<add>[ABI Stability]: https://nodejs.org/en/docs/guides/abi-stability/
<ide> [ECMAScript Language Specification]: https://tc39.github.io/ecma262/
<ide> [Error Handling]: #n_api_error_handling
<ide> [Native Abstractions for Node.js]: https://github.com/nodejs/nan | 1 |
Python | Python | fix typos and update docs | 89132a6986781ae6519e3ee912336b50caa11a31 | <ide><path>examples/neural_turing_machine_copy.py
<ide> from keras.layers.core import TimeDistributedDense, Activation
<ide> from keras.layers.recurrent import LSTM
<ide> from keras.optimizers import Adam
<add>from keras.utils import generic_utils
<ide>
<ide> from keras.layers.ntm import NeuralTuringMachine as NTM
<ide>
<ide> """
<ide> Copy Problem defined in Graves et. al [0]
<del>After 3000 gradients updates, the accuracy becomes >92%.
<add>After about 3500 updates, the accuracy becomes jumps from around 50% to >90%.
<add>
<add>Estimated compile time: 12 min
<add>Estimated time to train Neural Turing Machine and 3 layer LSTM on an NVidia GTX 680: 2h
<ide>
<ide>
<ide> [0]: http://arxiv.org/pdf/1410.5401v2.pdf
<ide> batch_size = 100
<ide>
<ide> h_dim = 128
<del>n_slots = 121
<add>n_slots = 128
<ide> m_length = 20
<ide> input_dim = 8
<ide> lr = 1e-3
<del>clipnorm = 10
<add>clipvalue = 10
<ide>
<ide> ##### Neural Turing Machine ######
<ide>
<ide> model.add(TimeDistributedDense(input_dim))
<ide> model.add(Activation('sigmoid'))
<ide>
<del>sgd = Adam(lr=lr, clipnorm=clipnorm)
<add>sgd = Adam(lr=lr, clipvalue=clipvalue)
<ide> model.compile(loss='binary_crossentropy', optimizer=sgd)
<ide>
<ide> # LSTM - Run this for comparison
<ide>
<del>sgd = Adam(lr=lr, clipnorm=clipnorm)
<add>sgd2 = Adam(lr=lr, clipvalue=clipvalue)
<ide> lstm = Sequential()
<ide> lstm.add(LSTM(input_dim=input_dim, output_dim=h_dim*2, return_sequences=True))
<ide> lstm.add(LSTM(output_dim=h_dim*2, return_sequences=True))
<ide> def test_model(model, file_name, min_size=100):
<ide> if e % 500 == 0:
<ide> print("")
<ide> acc1 = test_model(model, 'ntm.png')
<del> acc2 = test_model(model, 'lstm.png')
<del> print("NTM test acc: {}".format(a))
<del> print("LSTM test acc: {}".format(a))
<add> acc2 = test_model(lstm, 'lstm.png')
<add> print("NTM test acc: {}".format(acc1))
<add> print("LSTM test acc: {}".format(acc2))
<ide>
<ide> ##### VISUALIZATION #####
<ide> X = model.get_input()
<del>Y = ntm.get_full_output()[0:3] # (memory over time, read_vectors, write_vectors)
<add>Y = ntm.get_full_output()[0:3] # (memory over time, read_vectors, write_vectors)
<ide> F = function([X], Y, allow_input_downcast=True)
<ide>
<ide> inp, out, sw = get_sample(1, 8, 21, 20) | 1 |
Javascript | Javascript | fix json for grouped optional params | 6222e5b76d0f37fe8b5049bd23ca0271cab1821e | <ide><path>tools/doc/json.js
<ide> function parseSignature(text, sig) {
<ide> var params = text.match(paramExpr);
<ide> if (!params) return;
<ide> params = params[1];
<del> // the [ is irrelevant. ] indicates optionalness.
<del> params = params.replace(/\[/g, '');
<ide> params = params.split(/,/);
<add> var optionalLevel = 0;
<add> var optionalCharDict = {'[': 1, ' ': 0, ']': -1};
<ide> params.forEach(function(p, i, _) {
<ide> p = p.trim();
<ide> if (!p) return;
<ide> var param = sig.params[i];
<ide> var optional = false;
<ide> var def;
<del> // [foo] -> optional
<del> if (p.charAt(p.length - 1) === ']') {
<del> optional = true;
<del> p = p.replace(/\]/g, '');
<del> p = p.trim();
<add>
<add> // for grouped optional params such as someMethod(a[, b[, c]])
<add> var pos;
<add> for (pos = 0; pos < p.length; pos++) {
<add> if (optionalCharDict[p[pos]] === undefined) { break; }
<add> optionalLevel += optionalCharDict[p[pos]];
<add> }
<add> p = p.substring(pos);
<add> optional = (optionalLevel > 0);
<add> for (pos = p.length - 1; pos >= 0; pos--) {
<add> if (optionalCharDict[p[pos]] === undefined) { break; }
<add> optionalLevel += optionalCharDict[p[pos]];
<ide> }
<add> p = p.substring(0, pos + 1);
<add>
<ide> var eq = p.indexOf('=');
<ide> if (eq !== -1) {
<ide> def = p.substr(eq + 1); | 1 |
Python | Python | fix qa sample | ab229663b580e5e14a8a292d5a2ed372ca3b661c | <ide><path>src/transformers/utils/doc.py
<ide> def _prepare_output_docstrings(output_type, config_class, min_indent=None):
<ide>
<ide> ```python
<ide> >>> # target is "nice puppet"
<del> >>> target_start_index, target_end_index = torch.tensor([14]), torch.tensor([15])
<add> >>> target_start_index = torch.tensor([{qa_target_start_index}])
<add> >>> target_end_index = torch.tensor([{qa_target_end_index}])
<ide>
<ide> >>> outputs = model(**inputs, start_positions=target_start_index, end_positions=target_end_index)
<ide> >>> loss = outputs.loss
<ide> def _prepare_output_docstrings(output_type, config_class, min_indent=None):
<ide>
<ide> ```python
<ide> >>> # target is "nice puppet"
<del> >>> target_start_index, target_end_index = tf.constant([14]), tf.constant([15])
<add> >>> target_start_index = tf.constant([{qa_target_start_index}])
<add> >>> target_end_index = tf.constant([{qa_target_end_index}])
<ide>
<ide> >>> outputs = model(**inputs, start_positions=target_start_index, end_positions=target_end_index)
<ide> >>> loss = tf.math.reduce_mean(outputs.loss)
<ide> def add_code_sample_docstrings(
<ide> output_type=None,
<ide> config_class=None,
<ide> mask="[MASK]",
<add> qa_target_start_index=14,
<add> qa_target_end_index=15,
<ide> model_cls=None,
<ide> modality=None,
<ide> expected_output="",
<ide> def docstring_decorator(fn):
<ide> processor_class=processor_class,
<ide> checkpoint=checkpoint,
<ide> mask=mask,
<add> qa_target_start_index=qa_target_start_index,
<add> qa_target_end_index=qa_target_end_index,
<ide> expected_output=expected_output,
<ide> expected_loss=expected_loss,
<ide> ) | 1 |
Python | Python | use name instead of city for location | 79cf4402834423e411778973639978acf120d4be | <ide><path>libcloud/compute/drivers/maxihost.py
<ide> def list_locations(self, available=True):
<ide> return locations
<ide>
<ide> def _to_location(self, data):
<del> name = data.get('location').get('city', '')
<add> name = data.get('name')
<ide> country = data.get('location').get('country', '')
<ide> return NodeLocation(id=data['slug'], name=name, country=None,
<ide> driver=self) | 1 |
Ruby | Ruby | fix clear_all_connections! nomethoderror | 6e9675c6bf885c17c154bbcc697a8c9d49277e5b | <ide><path>actioncable/test/subscription_adapter/postgresql_test.rb
<ide> def setup
<ide> def teardown
<ide> super
<ide>
<del> ActiveRecord::Base.connection.clear_all_connections!
<add> ActiveRecord::Base.connection_handler.clear_all_connections!
<ide> end
<ide>
<ide> def cable_config | 1 |
Python | Python | add versionadded 1.4.0 for deprecated decorator | 759e989edf36a77648c2fdb970ba469e37ebc53a | <ide><path>numpy/testing/decorators.py
<ide> def deprecated(conditional=True):
<ide> Decorator, which, when applied to a function, causes SkipTest
<ide> to be raised when the skip_condition was True, and the function
<ide> to be called normally otherwise.
<add>
<add> Notes
<add> -----
<add>
<add> .. versionadded:: 1.4.0
<ide> """
<ide> def deprecate_decorator(f):
<ide> # Local import to avoid a hard nose dependency and only incur the | 1 |
Ruby | Ruby | use present tense on examples | db4f0ac025a53017b35337f81e1096a58fdce1fb | <ide><path>actionpack/lib/abstract_controller/layouts.rb
<ide> module AbstractController
<ide> # layout nil
<ide> #
<ide> # In these examples:
<del> # * The InformationController will use the "bank_standard" layout, which is inherited from BankController
<del> # * The TellerController will follow convention and use +app/views/layouts/teller.html.erb+
<del> # * The TillController will inherit the layout from TellerController and use +teller.html.erb+ as well
<del> # * The VaultController will pick a layout dynamically by calling the <tt>access_level_layout</tt> method
<del> # * The EmployeeController will not use a layout
<add> # * The InformationController uses the "bank_standard" layout, inherited from BankController.
<add> # * The TellerController follows convention and uses +app/views/layouts/teller.html.erb+.
<add> # * The TillController inherits the layout from TellerController and uses +teller.html.erb+ as well.
<add> # * The VaultController chooses a layout dynamically by calling the <tt>access_level_layout</tt> method.
<add> # * The EmployeeController does not use a layout at all.
<ide> #
<ide> # == Types of layouts
<ide> # | 1 |
PHP | PHP | upgrade shell - option to specify extensions | a7d69701ba7bdcaa67799b170c52a15132e64168 | <ide><path>cake/console/shells/upgrade.php
<ide> protected function _filesRegexpUpdate($patterns) {
<ide> $this->_paths = array(App::pluginPath($this->params['plugin']));
<ide> }
<ide>
<del> $this->_findFiles();
<add> $extensions = 'php|ctp|thtml|inc|tpl';
<add> if (!empty($this->params['ext'])) {
<add> $extensions = $this->params['ext'];
<add> }
<add>
<add> $this->_findFiles($extensions);
<ide> foreach ($this->_files as $file) {
<ide> $this->out('Updating ' . $file . '...', 1, Shell::VERBOSE);
<ide> $this->_updateFile($file, $patterns);
<ide> }
<ide> }
<ide>
<del> protected function _findFiles($pattern = '') {
<add> protected function _findFiles($extensions = '', $pattern = '') {
<ide> foreach ($this->_paths as $path) {
<ide> $Folder = new Folder($path);
<del> $files = $Folder->findRecursive('.*\.(php|ctp|thtml|inc|tpl)', true);
<add> $files = $Folder->findRecursive(".*\.($extensions)", true);
<ide> if (!empty($pattern)) {
<ide> foreach ($files as $i => $file) {
<ide> if (preg_match($pattern, $file)) {
<ide> protected function _updateFile($file, $patterns) {
<ide> * @return void
<ide> */
<ide> function getOptionParser() {
<add> $subcommandParser = array(
<add> 'options' => array(
<add> 'plugin' => array('short' => 'p', 'help' => __('The plugin to update.')),
<add> 'ext' => array('short' => 'e', 'help' => __('The extension(s) to search.')),
<add> )
<add> );
<add>
<ide> return parent::getOptionParser()
<ide> ->addSubcommand('i18n', array(
<ide> 'help' => 'Update the i18n translation method calls.',
<del> 'parser' => array(
<del> 'options' => array(
<del> 'plugin' => array('short' => 'p', 'help' => __('The plugin to update.'))
<del> )
<del> )
<add> 'parser' => $subcommandParser
<ide> ))
<ide> ->addSubcommand('helpers', array(
<ide> 'help' => 'Update calls to helpers.',
<del> 'parser' => array(
<del> 'options' => array(
<del> 'plugin' => array('short' => 'p', 'help' => __('The plugin to update.'))
<del> )
<del> )
<add> 'parser' => $subcommandParser
<ide> ));
<ide> }
<ide> }
<ide>\ No newline at end of file | 1 |
PHP | PHP | add missing docblock | 0064e25ddb006b0a287a6535679ce09d06e3f822 | <ide><path>src/Routing/Router.php
<ide> class Router
<ide> */
<ide> const UUID = '[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}';
<ide>
<add> /**
<add> * The route collection routes would be added to.
<add> *
<add> * @var \Cake\Routing\RouteCollection
<add> */
<ide> protected static $_collection;
<ide>
<ide> /** | 1 |
Python | Python | fix pickle dump in run_squad example | 257a35134a1bd378b16aa985ee76675289ff439c | <ide><path>examples/run_squad.py
<ide> def main():
<ide> if args.local_rank == -1 or torch.distributed.get_rank() == 0:
<ide> logger.info(" Saving train features into cached file %s", cached_train_features_file)
<ide> with open(cached_train_features_file, "wb") as writer:
<del> train_features = pickle.dump(train_features, writer)
<add> pickle.dump(train_features, writer)
<ide> logger.info("***** Running training *****")
<ide> logger.info(" Num orig examples = %d", len(train_examples))
<ide> logger.info(" Num split examples = %d", len(train_features)) | 1 |
Python | Python | fix typo in docstrings | b04fc0d0b392368fcc4819fd38a6a09e9feb0da4 | <ide><path>keras/layers/multi_head_attention.py
<ide> class MultiHeadAttention(Layer):
<ide> indicates no attention. Broadcasting can happen for the missing batch
<ide> dimensions and the head dimension.
<ide> return_attention_scores: A boolean to indicate whether the output should
<del> be attention output if True, or (attention_output, attention_scores) if
<del> False. Defaults to False.
<add> be `(attention_output, attention_scores)` if `True`, or `attention_output`
<add> if `False`. Defaults to `False`.
<ide> training: Python boolean indicating whether the layer should behave in
<ide> training mode (adding dropout) or in inference mode (no dropout).
<ide> Defaults to either using the training mode of the parent layer/model, | 1 |
Java | Java | fix checkstyle nohttp violation | 1607f1db0bccce2d1a12102cc4a190356e8962e1 | <ide><path>spring-web/src/test/java/org/springframework/http/converter/feed/RssChannelHttpMessageConverterTests.java
<ide>
<ide> import com.rometools.rome.feed.rss.Channel;
<ide> import com.rometools.rome.feed.rss.Item;
<del>import org.junit.jupiter.api.BeforeEach;
<ide> import org.junit.jupiter.api.Test;
<ide>
<ide> import org.springframework.http.MediaType;
<ide> */
<ide> public class RssChannelHttpMessageConverterTests {
<ide>
<del> private static final MediaType RSS_XML_UTF8 =
<del> new MediaType(MediaType.APPLICATION_RSS_XML, StandardCharsets.UTF_8);
<add> private static final MediaType RSS_XML_UTF8 = new MediaType(MediaType.APPLICATION_RSS_XML, StandardCharsets.UTF_8);
<ide>
<del>
<del> private RssChannelHttpMessageConverter converter;
<del>
<del>
<del> @BeforeEach
<del> public void setUp() {
<del> converter = new RssChannelHttpMessageConverter();
<del> }
<add> private final RssChannelHttpMessageConverter converter = new RssChannelHttpMessageConverter();
<ide>
<ide>
<ide> @Test
<ide> public void writeOtherCharset() throws IOException {
<ide> public void writeOtherContentTypeParameters() throws IOException {
<ide> Channel channel = new Channel("rss_2.0");
<ide> channel.setTitle("title");
<del> channel.setLink("http://example.com");
<add> channel.setLink("https://example.com");
<ide> channel.setDescription("description");
<ide>
<ide> MockHttpOutputMessage message = new MockHttpOutputMessage(); | 1 |
PHP | PHP | add declare statements | 166e6ec4362a7793572d9ebd4ede713afb25769a | <ide><path>src/Form/Form.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>src/Form/Schema.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>tests/TestCase/Form/FormTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>tests/TestCase/Form/SchemaTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) | 4 |
Ruby | Ruby | improve associated no reflection error | a4c4a0dc1382483303f1cb06236e8a71f12215a5 | <ide><path>activerecord/lib/active_record/relation/query_methods.rb
<ide> def not(opts, *rest)
<ide> # # WHERE "authors"."id" IS NOT NULL AND "comments"."id" IS NOT NULL
<ide> def associated(*associations)
<ide> associations.each do |association|
<del> reflection = @scope.klass._reflect_on_association(association)
<add> reflection = scope_association_reflection(association)
<ide> @scope.joins!(association)
<ide> self.not(reflection.table_name => { reflection.association_primary_key => nil })
<ide> end
<ide> def associated(*associations)
<ide> # # WHERE "authors"."id" IS NULL AND "comments"."id" IS NULL
<ide> def missing(*associations)
<ide> associations.each do |association|
<del> reflection = @scope.klass._reflect_on_association(association)
<del> unless reflection
<del> raise ArgumentError.new("An association named `:#{association}` does not exist on the model `#{@scope.name}`.")
<del> end
<add> reflection = scope_association_reflection(association)
<ide> @scope.left_outer_joins!(association)
<ide> @scope.where!(reflection.table_name => { reflection.association_primary_key => nil })
<ide> end
<ide>
<ide> @scope
<ide> end
<add>
<add> private
<add> def scope_association_reflection(association)
<add> reflection = @scope.klass._reflect_on_association(association)
<add> unless reflection
<add> raise ArgumentError.new("An association named `:#{association}` does not exist on the model `#{@scope.name}`.")
<add> end
<add> reflection
<add> end
<ide> end
<ide>
<ide> FROZEN_EMPTY_ARRAY = [].freeze
<ide><path>activerecord/test/cases/relation/where_chain_test.rb
<ide> def test_associated_with_multiple_associations
<ide> end
<ide> end
<ide>
<add> def test_associated__with_invalid_association_name
<add> e = assert_raises(ArgumentError) do
<add> Post.where.associated(:cars).to_a
<add> end
<add>
<add> assert_match(/An association named `:cars` does not exist on the model `Post`\./, e.message)
<add> end
<add>
<ide> def test_missing_with_association
<ide> assert posts(:authorless).author.blank?
<ide> assert_equal [posts(:authorless)], Post.where.missing(:author).to_a | 2 |
Python | Python | change default value verbose=1 to verbose=0 | 21b80642d0d050bf40c66c2841955ffb48506b66 | <ide><path>keras/models.py
<ide> def test_on_batch(self, x, y,
<ide> return self.model.test_on_batch(x, y,
<ide> sample_weight=sample_weight)
<ide>
<del> def predict_proba(self, x, batch_size=32, verbose=1):
<add> def predict_proba(self, x, batch_size=32, verbose=0):
<ide> """Generates class probability predictions for the input samples.
<ide>
<ide> The input samples are processed batch by batch.
<ide> def predict_proba(self, x, batch_size=32, verbose=1):
<ide> '(like softmax or sigmoid would).')
<ide> return preds
<ide>
<del> def predict_classes(self, x, batch_size=32, verbose=1):
<add> def predict_classes(self, x, batch_size=32, verbose=0):
<ide> """Generate class predictions for the input samples.
<ide>
<ide> The input samples are processed batch by batch. | 1 |
Python | Python | add more information about using googleadshook | ef98edf4da2d9b74d5cf5b21e81577b3151edb79 | <ide><path>airflow/providers/google/ads/hooks/ads.py
<ide>
<ide> class GoogleAdsHook(BaseHook):
<ide> """
<del> Hook for the Google Ads API
<add> Hook for the Google Ads API.
<add>
<add> This hook requires two connections:
<add>
<add> - gcp_conn_id - provides service account details (like any other GCP connection)
<add> - google_ads_conn_id - which contains information from Google Ads config.yaml file
<add> in the ``extras``. Example of the ``extras``:
<add>
<add> .. code-block:: json
<add>
<add> {
<add> "google_ads_client": {
<add> "developer_token": "{{ INSERT_TOKEN }}",
<add> "path_to_private_key_file": null,
<add> "delegated_account": "{{ INSERT_DELEGATED_ACCOUNT }}"
<add> }
<add> }
<add>
<add> The ``path_to_private_key_file`` is resolved by the hook using credentials from gcp_conn_id.
<add> https://developers.google.com/google-ads/api/docs/client-libs/python/oauth-service
<add>
<add> .. seealso::
<add> For more information on how Google Ads authentication flow works take a look at:
<add> https://developers.google.com/google-ads/api/docs/client-libs/python/oauth-service
<ide>
<ide> .. seealso::
<ide> For more information on the Google Ads API, take a look at the API docs: | 1 |
PHP | PHP | add typehints to console classes | 2e3c5c441c3a280a679ec592c7037e636305ca50 | <ide><path>src/Command/HelpCommand.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> class HelpCommand extends Command implements CommandCollectionAwareInterface
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> public function setCommandCollection(CommandCollection $commands)
<add> public function setCommandCollection(CommandCollection $commands): void
<ide> {
<ide> $this->commands = $commands;
<ide> }
<ide> public function setCommandCollection(CommandCollection $commands)
<ide> * @param \Cake\Console\ConsoleIo $io The console io
<ide> * @return int
<ide> */
<del> public function execute(Arguments $args, ConsoleIo $io)
<add> public function execute(Arguments $args, ConsoleIo $io): int
<ide> {
<ide> if (!$args->getOption('xml')) {
<ide> $io->out('<info>Current Paths:</info>', 2);
<ide> public function execute(Arguments $args, ConsoleIo $io)
<ide> * @param \ArrayIterator $commands The command collection to output.
<ide> * @return void
<ide> */
<del> protected function asText($io, $commands)
<add> protected function asText($io, $commands): void
<ide> {
<ide> $invert = [];
<ide> foreach ($commands as $name => $class) {
<ide> protected function asText($io, $commands)
<ide> * @param \ArrayIterator $commands The command collection to output
<ide> * @return void
<ide> */
<del> protected function asXml($io, $commands)
<add> protected function asXml($io, $commands): void
<ide> {
<ide> $shells = new SimpleXMLElement('<shells></shells>');
<ide> foreach ($commands as $name => $class) {
<ide> protected function asXml($io, $commands)
<ide> * @param \Cake\Console\ConsoleOptionParser $parser The parser to build
<ide> * @return \Cake\Console\ConsoleOptionParser
<ide> */
<del> protected function buildOptionParser(ConsoleOptionParser $parser)
<add> protected function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionParser
<ide> {
<ide> $parser->setDescription(
<ide> 'Get the list of available shells for this application.'
<ide><path>src/Command/VersionCommand.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> class VersionCommand extends Command
<ide> * @param \Cake\Console\ConsoleIo $io The console io
<ide> * @return int
<ide> */
<del> public function execute(Arguments $args, ConsoleIo $io)
<add> public function execute(Arguments $args, ConsoleIo $io): int
<ide> {
<ide> $io->out(Configure::version());
<ide>
<ide><path>src/Console/Arguments.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> public function __construct(array $args, array $options, array $argNames)
<ide> *
<ide> * @return string[]
<ide> */
<del> public function getArguments()
<add> public function getArguments(): array
<ide> {
<ide> return $this->args;
<ide> }
<ide> public function getArguments()
<ide> * @param int $index The argument index to access.
<ide> * @return string|null The argument value or null
<ide> */
<del> public function getArgumentAt($index)
<add> public function getArgumentAt(int $index)
<ide> {
<ide> if ($this->hasArgumentAt($index)) {
<ide> return $this->args[$index];
<ide> public function getArgumentAt($index)
<ide> * @param int $index The argument index to check.
<ide> * @return bool
<ide> */
<del> public function hasArgumentAt($index)
<add> public function hasArgumentAt(int $index): bool
<ide> {
<ide> return isset($this->args[$index]);
<ide> }
<ide> public function hasArgumentAt($index)
<ide> * @param string $name The argument name to check.
<ide> * @return bool
<ide> */
<del> public function hasArgument($name)
<add> public function hasArgument(string $name): bool
<ide> {
<ide> $offset = array_search($name, $this->argNames, true);
<ide> if ($offset === false) {
<ide> public function hasArgument($name)
<ide> * @param string $name The argument name to check.
<ide> * @return string|null
<ide> */
<del> public function getArgument($name)
<add> public function getArgument(string $name)
<ide> {
<ide> $offset = array_search($name, $this->argNames, true);
<ide> if ($offset === false) {
<ide> public function getArgument($name)
<ide> *
<ide> * @return array
<ide> */
<del> public function getOptions()
<add> public function getOptions(): array
<ide> {
<ide> return $this->options;
<ide> }
<ide> public function getOptions()
<ide> * @param string $name The name of the option to check.
<ide> * @return string|int|bool|null The option value or null.
<ide> */
<del> public function getOption($name)
<add> public function getOption(string $name)
<ide> {
<ide> if (isset($this->options[$name])) {
<ide> return $this->options[$name];
<ide> public function getOption($name)
<ide> * @param string $name The name of the option to check.
<ide> * @return bool
<ide> */
<del> public function hasOption($name)
<add> public function hasOption(string $name): bool
<ide> {
<ide> return isset($this->options[$name]);
<ide> }
<ide><path>src/Console/Command.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> public function __construct()
<ide> * @return $this
<ide> * @throws \InvalidArgumentException
<ide> */
<del> public function setName($name)
<add> public function setName(string $name): self
<ide> {
<ide> if (strpos($name, ' ') < 1) {
<ide> throw new InvalidArgumentException(
<ide> public function setName($name)
<ide> *
<ide> * @return string
<ide> */
<del> public function getName()
<add> public function getName(): string
<ide> {
<ide> return $this->name;
<ide> }
<ide> public function getName()
<ide> * @return \Cake\Console\ConsoleOptionParser
<ide> * @throws \RuntimeException When the parser is invalid
<ide> */
<del> public function getOptionParser()
<add> public function getOptionParser(): ConsoleOptionParser
<ide> {
<ide> list($root, $name) = explode(' ', $this->name, 2);
<ide> $parser = new ConsoleOptionParser($name);
<ide> protected function buildOptionParser(ConsoleOptionParser $parser)
<ide> *
<ide> * @return void
<ide> */
<del> public function initialize()
<add> public function initialize(): void
<ide> {
<ide> }
<ide>
<ide> public function initialize()
<ide> * @param \Cake\Console\ConsoleIo $io The console io
<ide> * @return int|null Exit code or null for success.
<ide> */
<del> public function run(array $argv, ConsoleIo $io)
<add> public function run(array $argv, ConsoleIo $io): ?int
<ide> {
<ide> $this->initialize();
<ide>
<ide> public function run(array $argv, ConsoleIo $io)
<ide> * @param \Cake\Console\ConsoleIo $io The console io
<ide> * @return void
<ide> */
<del> protected function displayHelp(ConsoleOptionParser $parser, Arguments $args, ConsoleIo $io)
<add> protected function displayHelp(ConsoleOptionParser $parser, Arguments $args, ConsoleIo $io): void
<ide> {
<ide> $format = 'text';
<ide> if ($args->getArgumentAt(0) === 'xml') {
<ide> protected function displayHelp(ConsoleOptionParser $parser, Arguments $args, Con
<ide> * @param \Cake\Console\ConsoleIo $io The console io
<ide> * @return void
<ide> */
<del> protected function setOutputLevel(Arguments $args, ConsoleIo $io)
<add> protected function setOutputLevel(Arguments $args, ConsoleIo $io): void
<ide> {
<ide> $io->setLoggers(ConsoleIo::NORMAL);
<ide> if ($args->getOption('quiet')) {
<ide> public function execute(Arguments $args, ConsoleIo $io)
<ide> * @throws \Cake\Console\Exception\StopException
<ide> * @return void
<ide> */
<del> public function abort($code = self::CODE_ERROR)
<add> public function abort($code = self::CODE_ERROR): void
<ide> {
<ide> throw new StopException('Command aborted', $code);
<ide> }
<ide><path>src/Console/CommandCollection.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide> public function __construct(array $commands = [])
<ide> * @param string|\Cake\Console\Shell|\Cake\Console\Command $command The command to map.
<ide> * @return $this
<ide> */
<del> public function add($name, $command)
<add> public function add(string $name, $command): self
<ide> {
<ide> // Once we have a new Command class this should check
<ide> // against that interface.
<ide> public function add($name, $command)
<ide> * @return $this
<ide> * @see \Cake\Console\CommandCollection::add()
<ide> */
<del> public function addMany(array $commands)
<add> public function addMany(array $commands): self
<ide> {
<ide> foreach ($commands as $name => $class) {
<ide> $this->add($name, $class);
<ide> public function addMany(array $commands)
<ide> * @param string $name The named shell.
<ide> * @return $this
<ide> */
<del> public function remove($name)
<add> public function remove(string $name): self
<ide> {
<ide> unset($this->commands[$name]);
<ide>
<ide> public function remove($name)
<ide> * @param string $name The named shell.
<ide> * @return bool
<ide> */
<del> public function has($name)
<add> public function has(string $name): bool
<ide> {
<ide> return isset($this->commands[$name]);
<ide> }
<ide> public function has($name)
<ide> * Get the target for a command.
<ide> *
<ide> * @param string $name The named shell.
<del> * @return string|\Cake\Console\Shell Either the shell class or an instance.
<add> * @return string|\Cake\Console\Command Either the command class or an instance.
<ide> * @throws \InvalidArgumentException when unknown commands are fetched.
<ide> */
<del> public function get($name)
<add> public function get(string $name)
<ide> {
<ide> if (!$this->has($name)) {
<ide> throw new InvalidArgumentException("The $name is not a known command name.");
<ide> public function getIterator()
<ide> *
<ide> * @return int
<ide> */
<del> public function count()
<add> public function count(): int
<ide> {
<ide> return count($this->commands);
<ide> }
<ide> public function count()
<ide> * @param string $plugin The plugin to scan.
<ide> * @return array Discovered plugin commands.
<ide> */
<del> public function discoverPlugin($plugin)
<add> public function discoverPlugin($plugin): array
<ide> {
<ide> $scanner = new CommandScanner();
<ide> $shells = $scanner->scanPlugin($plugin);
<ide> public function discoverPlugin($plugin)
<ide> * @param array $input The results of a CommandScanner operation.
<ide> * @return array A flat map of command names => class names.
<ide> */
<del> protected function resolveNames(array $input)
<add> protected function resolveNames(array $input): array
<ide> {
<ide> $out = [];
<ide> foreach ($input as $info) {
<ide> protected function resolveNames(array $input)
<ide> *
<ide> * @return array An array of command names and their classes.
<ide> */
<del> public function autoDiscover()
<add> public function autoDiscover(): array
<ide> {
<ide> $scanner = new CommandScanner();
<ide>
<ide><path>src/Console/CommandCollectionAwareInterface.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide> interface CommandCollectionAwareInterface
<ide> * @param \Cake\Console\CommandCollection $commands The commands to use.
<ide> * @return void
<ide> */
<del> public function setCommandCollection(CommandCollection $commands);
<add> public function setCommandCollection(CommandCollection $commands): void;
<ide> }
<ide><path>src/Console/CommandFactory.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide><path>src/Console/CommandFactoryInterface.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide><path>src/Console/CommandRunner.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide> public function __construct(ConsoleApplicationInterface $app, $root = 'cake', Co
<ide> * @param array $aliases The map of aliases to replace.
<ide> * @return $this
<ide> */
<del> public function setAliases(array $aliases)
<add> public function setAliases(array $aliases): self
<ide> {
<ide> $this->aliases = $aliases;
<ide>
<ide> public function setAliases(array $aliases)
<ide> * @return int The exit code of the command.
<ide> * @throws \RuntimeException
<ide> */
<del> public function run(array $argv, ConsoleIo $io = null)
<add> public function run(array $argv, ConsoleIo $io = null): int
<ide> {
<ide> $this->bootstrap();
<ide>
<ide> public function run(array $argv, ConsoleIo $io = null)
<ide> *
<ide> * @return void
<ide> */
<del> protected function bootstrap()
<add> protected function bootstrap(): void
<ide> {
<ide> $this->app->bootstrap();
<ide> if ($this->app instanceof PluginApplicationInterface) {
<ide> protected function checkCollection($commands, $method)
<ide> *
<ide> * @return \Cake\Event\EventManagerInterface
<ide> */
<del> public function getEventManager()
<add> public function getEventManager(): EventManagerInterface
<ide> {
<ide> if ($this->app instanceof PluginApplicationInterface) {
<ide> return $this->app->getEventManager();
<ide> protected function getShell(ConsoleIo $io, CommandCollection $commands, $name)
<ide> *
<ide> * @param \Cake\Console\CommandCollection $commands The command collection to check.
<ide> * @param \Cake\Console\ConsoleIo $io ConsoleIo object for errors.
<del> * @param string $name The name from the CLI args.
<add> * @param string|null $name The name from the CLI args.
<ide> * @return string The resolved name.
<ide> */
<del> protected function resolveName($commands, $io, $name)
<add> protected function resolveName(CommandCollection $commands, ConsoleIo $io, ?string $name): string
<ide> {
<ide> if (!$name) {
<ide> $io->err('<error>No command provided. Choose one of the available commands.</error>', 2);
<ide> protected function resolveName($commands, $io, $name)
<ide> *
<ide> * @param \Cake\Console\Shell $shell The shell to run.
<ide> * @param array $argv The CLI arguments to invoke.
<del> * @return int Exit code
<add> * @return int|bool|null Exit code
<ide> */
<ide> protected function runShell(Shell $shell, array $argv)
<ide> {
<ide> protected function createShell($className, ConsoleIo $io)
<ide> *
<ide> * @return void
<ide> */
<del> protected function loadRoutes()
<add> protected function loadRoutes(): void
<ide> {
<ide> $builder = Router::createRouteBuilder('/');
<ide>
<ide><path>src/Console/CommandScanner.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide> class CommandScanner
<ide> *
<ide> * @return array A list of command metadata.
<ide> */
<del> public function scanCore()
<add> public function scanCore(): array
<ide> {
<ide> $coreShells = $this->scanDir(
<ide> dirname(__DIR__) . DIRECTORY_SEPARATOR . 'Shell' . DIRECTORY_SEPARATOR,
<ide> public function scanCore()
<ide> *
<ide> * @return array A list of command metadata.
<ide> */
<del> public function scanApp()
<add> public function scanApp(): array
<ide> {
<ide> $appNamespace = Configure::read('App.namespace');
<ide> $appShells = $this->scanDir(
<ide> public function scanApp()
<ide> * @param string $plugin The named plugin.
<ide> * @return array A list of command metadata.
<ide> */
<del> public function scanPlugin($plugin)
<add> public function scanPlugin(string $plugin): array
<ide> {
<ide> if (!Plugin::loaded($plugin)) {
<ide> return [];
<ide> public function scanPlugin($plugin)
<ide> * @param array $hide A list of command names to hide as they are internal commands.
<ide> * @return array The list of shell info arrays based on scanning the filesystem and inflection.
<ide> */
<del> protected function scanDir($path, $namespace, $prefix, array $hide)
<add> protected function scanDir(string $path, string $namespace, string $prefix, array $hide): array
<ide> {
<ide> $dir = new Folder($path);
<ide> $contents = $dir->read(true, true);
<ide><path>src/Console/ConsoleErrorHandler.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> public function __construct($options = [])
<ide> * @throws \Exception When renderer class not found
<ide> * @see https://secure.php.net/manual/en/function.set-exception-handler.php
<ide> */
<del> public function handleException(Exception $exception)
<add> public function handleException(Exception $exception): void
<ide> {
<ide> $this->_displayException($exception);
<ide> $this->_logException($exception);
<ide> public function handleException(Exception $exception)
<ide> * @param \Exception $exception The exception to handle
<ide> * @return void
<ide> */
<del> protected function _displayException($exception)
<add> protected function _displayException($exception): void
<ide> {
<ide> $errorName = 'Exception:';
<ide> if ($exception instanceof FatalErrorException) {
<ide> protected function _displayError($error, $debug)
<ide> * @param int $code The exit code.
<ide> * @return void
<ide> */
<del> protected function _stop($code)
<add> protected function _stop($code): void
<ide> {
<ide> exit($code);
<ide> }
<ide><path>src/Console/ConsoleInput.php
<ide> class ConsoleInput
<ide> *
<ide> * @param string $handle The location of the stream to use as input.
<ide> */
<del> public function __construct($handle = 'php://stdin')
<add> public function __construct(string $handle = 'php://stdin')
<ide> {
<ide> $this->_canReadline = (extension_loaded('readline') && $handle === 'php://stdin');
<ide> $this->_input = fopen($handle, 'rb');
<ide> public function __construct($handle = 'php://stdin')
<ide> /**
<ide> * Read a value from the stream
<ide> *
<del> * @return mixed The value of the stream
<add> * @return string The value of the stream
<ide> */
<del> public function read()
<add> public function read(): string
<ide> {
<ide> if ($this->_canReadline) {
<ide> $line = readline('');
<ide> public function read()
<ide> * @param int $timeout An optional time to wait for data
<ide> * @return bool True for data available, false otherwise
<ide> */
<del> public function dataAvailable($timeout = 0)
<add> public function dataAvailable(int $timeout = 0): bool
<ide> {
<ide> $readFds = [$this->_input];
<ide> $readyFds = stream_select($readFds, $writeFds, $errorFds, $timeout);
<ide><path>src/Console/ConsoleInputArgument.php
<ide> public function __construct($name, $help = '', $required = false, $choices = [])
<ide> *
<ide> * @return string Value of this->_name.
<ide> */
<del> public function name()
<add> public function name(): string
<ide> {
<ide> return $this->_name;
<ide> }
<ide> public function name()
<ide> * @param \Cake\Console\ConsoleInputArgument $argument ConsoleInputArgument to compare to.
<ide> * @return bool
<ide> */
<del> public function isEqualTo(ConsoleInputArgument $argument)
<add> public function isEqualTo(ConsoleInputArgument $argument): bool
<ide> {
<ide> return $this->usage() === $argument->usage();
<ide> }
<ide> public function isEqualTo(ConsoleInputArgument $argument)
<ide> * @param int $width The width to make the name of the option.
<ide> * @return string
<ide> */
<del> public function help($width = 0)
<add> public function help(int $width = 0): string
<ide> {
<ide> $name = $this->_name;
<ide> if (strlen($name) < $width) {
<ide> public function help($width = 0)
<ide> *
<ide> * @return string
<ide> */
<del> public function usage()
<add> public function usage(): string
<ide> {
<ide> $name = $this->_name;
<ide> if ($this->_choices) {
<ide> public function usage()
<ide> *
<ide> * @return bool
<ide> */
<del> public function isRequired()
<add> public function isRequired(): bool
<ide> {
<ide> return (bool)$this->_required;
<ide> }
<ide> public function isRequired()
<ide> * @return bool
<ide> * @throws \Cake\Console\Exception\ConsoleException
<ide> */
<del> public function validChoice($value)
<add> public function validChoice(string $value): bool
<ide> {
<ide> if (empty($this->_choices)) {
<ide> return true;
<ide> public function validChoice($value)
<ide> * @param \SimpleXMLElement $parent The parent element.
<ide> * @return \SimpleXMLElement The parent with this argument appended.
<ide> */
<del> public function xml(SimpleXMLElement $parent)
<add> public function xml(SimpleXMLElement $parent): SimpleXmlElement
<ide> {
<ide> $option = $parent->addChild('argument');
<ide> $option->addAttribute('name', $this->_name);
<ide><path>src/Console/ConsoleInputOption.php
<ide> public function __construct(
<ide> *
<ide> * @return string Value of this->_name.
<ide> */
<del> public function name()
<add> public function name(): string
<ide> {
<ide> return $this->_name;
<ide> }
<ide> public function name()
<ide> *
<ide> * @return string Value of this->_short.
<ide> */
<del> public function short()
<add> public function short(): string
<ide> {
<del> return $this->_short;
<add> return (string)$this->_short;
<ide> }
<ide>
<ide> /**
<ide> public function short()
<ide> * @param int $width The width to make the name of the option.
<ide> * @return string
<ide> */
<del> public function help($width = 0)
<add> public function help(int $width = 0): string
<ide> {
<ide> $default = $short = '';
<ide> if ($this->_default && $this->_default !== true) {
<ide> public function help($width = 0)
<ide> *
<ide> * @return string
<ide> */
<del> public function usage()
<add> public function usage(): string
<ide> {
<ide> $name = (strlen($this->_short) > 0) ? ('-' . $this->_short) : ('--' . $this->_name);
<ide> $default = '';
<ide> public function defaultValue()
<ide> *
<ide> * @return bool
<ide> */
<del> public function isBoolean()
<add> public function isBoolean(): bool
<ide> {
<ide> return (bool)$this->_boolean;
<ide> }
<ide> public function isBoolean()
<ide> *
<ide> * @return bool
<ide> */
<del> public function acceptsMultiple()
<add> public function acceptsMultiple(): bool
<ide> {
<ide> return (bool)$this->_multiple;
<ide> }
<ide> public function acceptsMultiple()
<ide> * @return bool
<ide> * @throws \Cake\Console\Exception\ConsoleException
<ide> */
<del> public function validChoice($value)
<add> public function validChoice($value): bool
<ide> {
<ide> if (empty($this->_choices)) {
<ide> return true;
<ide> public function validChoice($value)
<ide> * @param \SimpleXMLElement $parent The parent element.
<ide> * @return \SimpleXMLElement The parent with this option appended.
<ide> */
<del> public function xml(SimpleXMLElement $parent)
<add> public function xml(SimpleXMLElement $parent): SimpleXmlElement
<ide> {
<ide> $option = $parent->addChild('option');
<ide> $option->addAttribute('name', '--' . $this->_name);
<ide><path>src/Console/ConsoleInputSubcommand.php
<ide> public function __construct($name, $help = '', $parser = null)
<ide> *
<ide> * @return string Value of this->_name.
<ide> */
<del> public function name()
<add> public function name(): string
<ide> {
<ide> return $this->_name;
<ide> }
<ide> public function name()
<ide> *
<ide> * @return string
<ide> */
<del> public function getRawHelp()
<add> public function getRawHelp(): string
<ide> {
<ide> return $this->_help;
<ide> }
<ide> public function getRawHelp()
<ide> * @param int $width The width to make the name of the subcommand.
<ide> * @return string
<ide> */
<del> public function help($width = 0)
<add> public function help(int $width = 0): string
<ide> {
<ide> $name = $this->_name;
<ide> if (strlen($name) < $width) {
<ide> public function parser()
<ide> * @param \SimpleXMLElement $parent The parent element.
<ide> * @return \SimpleXMLElement The parent with this subcommand appended.
<ide> */
<del> public function xml(SimpleXMLElement $parent)
<add> public function xml(SimpleXMLElement $parent): SimpleXmlElement
<ide> {
<ide> $command = $parent->addChild('command');
<ide> $command->addAttribute('name', $this->_name);
<ide><path>src/Console/ConsoleIo.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> public function __construct(ConsoleOutput $out = null, ConsoleOutput $err = null
<ide> * @param null|int $level The current output level.
<ide> * @return int The current output level.
<ide> */
<del> public function level($level = null)
<add> public function level(?int $level = null): int
<ide> {
<ide> if ($level !== null) {
<ide> $this->_level = $level;
<ide> public function level($level = null)
<ide> * @param int $newlines Number of newlines to append
<ide> * @return int|bool The number of bytes returned from writing to stdout.
<ide> */
<del> public function verbose($message, $newlines = 1)
<add> public function verbose($message, int $newlines = 1)
<ide> {
<ide> return $this->out($message, $newlines, self::VERBOSE);
<ide> }
<ide> public function verbose($message, $newlines = 1)
<ide> * @param int $newlines Number of newlines to append
<ide> * @return int|bool The number of bytes returned from writing to stdout.
<ide> */
<del> public function quiet($message, $newlines = 1)
<add> public function quiet($message, int $newlines = 1)
<ide> {
<ide> return $this->out($message, $newlines, self::QUIET);
<ide> }
<ide> public function quiet($message, $newlines = 1)
<ide> * @param int $level The message's output level, see above.
<ide> * @return int|bool The number of bytes returned from writing to stdout.
<ide> */
<del> public function out($message = '', $newlines = 1, $level = ConsoleIo::NORMAL)
<add> public function out($message = '', int $newlines = 1, int $level = ConsoleIo::NORMAL)
<ide> {
<ide> if ($level <= $this->_level) {
<ide> $this->_lastWritten = (int)$this->_out->write($message, $newlines);
<ide> public function out($message = '', $newlines = 1, $level = ConsoleIo::NORMAL)
<ide> * @return int|bool The number of bytes returned from writing to stdout.
<ide> * @see https://book.cakephp.org/3.0/en/console-and-shells.html#Shell::out
<ide> */
<del> public function info($message = null, $newlines = 1, $level = Shell::NORMAL)
<add> public function info($message = null, int $newlines = 1, int $level = Shell::NORMAL)
<ide> {
<ide> $messageType = 'info';
<ide> $message = $this->wrapMessageWithType($messageType, $message);
<ide> public function info($message = null, $newlines = 1, $level = Shell::NORMAL)
<ide> * @return int|bool The number of bytes returned from writing to stderr.
<ide> * @see https://book.cakephp.org/3.0/en/console-and-shells.html#Shell::err
<ide> */
<del> public function warning($message = null, $newlines = 1)
<add> public function warning($message = null, int $newlines = 1)
<ide> {
<ide> $messageType = 'warning';
<ide> $message = $this->wrapMessageWithType($messageType, $message);
<ide> public function warning($message = null, $newlines = 1)
<ide> * @return int|bool The number of bytes returned from writing to stderr.
<ide> * @see https://book.cakephp.org/3.0/en/console-and-shells.html#Shell::err
<ide> */
<del> public function error($message = null, $newlines = 1)
<add> public function error($message = null, int $newlines = 1)
<ide> {
<ide> $messageType = 'error';
<ide> $message = $this->wrapMessageWithType($messageType, $message);
<ide> public function error($message = null, $newlines = 1)
<ide> * @return int|bool The number of bytes returned from writing to stdout.
<ide> * @see https://book.cakephp.org/3.0/en/console-and-shells.html#Shell::out
<ide> */
<del> public function success($message = null, $newlines = 1, $level = Shell::NORMAL)
<add> public function success($message = null, int $newlines = 1, int $level = Shell::NORMAL)
<ide> {
<ide> $messageType = 'success';
<ide> $message = $this->wrapMessageWithType($messageType, $message);
<ide> public function success($message = null, $newlines = 1, $level = Shell::NORMAL)
<ide> * @param string|array $message The message to wrap.
<ide> * @return array|string The message wrapped with the given message type.
<ide> */
<del> protected function wrapMessageWithType($messageType, $message)
<add> protected function wrapMessageWithType(string $messageType, $message)
<ide> {
<ide> if (is_array($message)) {
<ide> foreach ($message as $k => $v) {
<ide> protected function wrapMessageWithType($messageType, $message)
<ide> * length of the last message output.
<ide> * @return void
<ide> */
<del> public function overwrite($message, $newlines = 1, $size = null)
<add> public function overwrite($message, int $newlines = 1, ?int $size = null)
<ide> {
<ide> $size = $size ?: $this->_lastWritten;
<ide>
<ide> public function overwrite($message, $newlines = 1, $size = null)
<ide> * @param int $newlines Number of newlines to append
<ide> * @return int|bool The number of bytes returned from writing to stderr.
<ide> */
<del> public function err($message = '', $newlines = 1)
<add> public function err($message = '', int $newlines = 1)
<ide> {
<ide> return $this->_err->write($message, $newlines);
<ide> }
<ide> public function err($message = '', $newlines = 1)
<ide> * @param int $multiplier Number of times the linefeed sequence should be repeated
<ide> * @return string
<ide> */
<del> public function nl($multiplier = 1)
<add> public function nl(int $multiplier = 1): string
<ide> {
<ide> return str_repeat(ConsoleOutput::LF, $multiplier);
<ide> }
<ide> public function nl($multiplier = 1)
<ide> * @param int $width Width of the line, defaults to 79
<ide> * @return void
<ide> */
<del> public function hr($newlines = 0, $width = 79)
<add> public function hr(int $newlines = 0, int $width = 79): void
<ide> {
<ide> $this->out(null, $newlines);
<ide> $this->out(str_repeat('-', $width));
<ide> public function ask($prompt, $default = null)
<ide> * @return void
<ide> * @see \Cake\Console\ConsoleOutput::setOutputAs()
<ide> */
<del> public function setOutputAs($mode)
<add> public function setOutputAs(int $mode): void
<ide> {
<ide> $this->_out->setOutputAs($mode);
<ide> }
<ide> public function styles($style = null, $definition = null)
<ide> * @param string|null $default Default input value.
<ide> * @return mixed Either the default value, or the user-provided input.
<ide> */
<del> public function askChoice($prompt, $options, $default = null)
<add> public function askChoice(string $prompt, $options, $default = null)
<ide> {
<ide> if ($options && is_string($options)) {
<ide> if (strpos($options, ',')) {
<ide> public function askChoice($prompt, $options, $default = null)
<ide> * @param string|null $default Default input value. Pass null to omit.
<ide> * @return string Either the default value, or the user-provided input.
<ide> */
<del> protected function _getInput($prompt, $options, $default)
<add> protected function _getInput(string $prompt, $options, $default): string
<ide> {
<ide> $optionsText = '';
<ide> if (isset($options)) {
<ide> protected function _getInput($prompt, $options, $default)
<ide> * QUIET disables notice, info and debug logs.
<ide> * @return void
<ide> */
<del> public function setLoggers($enable)
<add> public function setLoggers($enable): void
<ide> {
<ide> Log::drop('stdout');
<ide> Log::drop('stderr');
<ide> public function setLoggers($enable)
<ide> * @param array $settings Configuration data for the helper.
<ide> * @return \Cake\Console\Helper The created helper instance.
<ide> */
<del> public function helper($name, array $settings = [])
<add> public function helper(string $name, array $settings = [])
<ide> {
<ide> $name = ucfirst($name);
<ide>
<ide> public function helper($name, array $settings = [])
<ide> * @throws \Cake\Console\Exception\StopException When `q` is given as an answer
<ide> * to whether or not a file should be overwritten.
<ide> */
<del> public function createFile($path, $contents, $forceOverwrite = false)
<add> public function createFile(string $path, string $contents, bool $forceOverwrite = false): bool
<ide> {
<ide> $path = str_replace(
<ide> DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR,
<ide><path>src/Console/ConsoleOptionParser.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> class ConsoleOptionParser
<ide> * @see \Cake\Console\ConsoleOptionParser::description()
<ide> * @var string
<ide> */
<del> protected $_description;
<add> protected $_description = '';
<ide>
<ide> /**
<ide> * Epilog text - displays after options when help is generated
<ide> *
<ide> * @see \Cake\Console\ConsoleOptionParser::epilog()
<ide> * @var string
<ide> */
<del> protected $_epilog;
<add> protected $_epilog = '';
<ide>
<ide> /**
<ide> * Option definitions.
<ide> public static function create($command, $defaultOptions = true)
<ide> * @param bool $defaultOptions Whether you want the verbose and quiet options set.
<ide> * @return static
<ide> */
<del> public static function buildFromArray($spec, $defaultOptions = true)
<add> public static function buildFromArray(array $spec, bool $defaultOptions = true)
<ide> {
<ide> $parser = new static($spec['command'], $defaultOptions);
<ide> if (!empty($spec['arguments'])) {
<ide> public static function buildFromArray($spec, $defaultOptions = true)
<ide> *
<ide> * @return array
<ide> */
<del> public function toArray()
<add> public function toArray(): array
<ide> {
<ide> $result = [
<ide> 'command' => $this->_command,
<ide> public function merge($spec)
<ide> * @param string $text The text to set.
<ide> * @return $this
<ide> */
<del> public function setCommand($text)
<add> public function setCommand(string $text): self
<ide> {
<ide> $this->_command = Inflector::underscore($text);
<ide>
<ide> public function setCommand($text)
<ide> *
<ide> * @return string The value of the command.
<ide> */
<del> public function getCommand()
<add> public function getCommand(): string
<ide> {
<ide> return $this->_command;
<ide> }
<ide> public function getCommand()
<ide> * text will be imploded with "\n".
<ide> * @return $this
<ide> */
<del> public function setDescription($text)
<add> public function setDescription($text): self
<ide> {
<ide> if (is_array($text)) {
<ide> $text = implode("\n", $text);
<ide> public function setDescription($text)
<ide> *
<ide> * @return string The value of the description
<ide> */
<del> public function getDescription()
<add> public function getDescription(): string
<ide> {
<ide> return $this->_description;
<ide> }
<ide> public function getDescription()
<ide> * be imploded with "\n".
<ide> * @return $this
<ide> */
<del> public function setEpilog($text)
<add> public function setEpilog($text): self
<ide> {
<ide> if (is_array($text)) {
<ide> $text = implode("\n", $text);
<ide> public function setEpilog($text)
<ide> *
<ide> * @return string The value of the epilog.
<ide> */
<del> public function getEpilog()
<add> public function getEpilog(): string
<ide> {
<ide> return $this->_epilog;
<ide> }
<ide> public function getEpilog()
<ide> * @param bool $value Whether or not to sort subcommands
<ide> * @return $this
<ide> */
<del> public function enableSubcommandSort($value = true)
<add> public function enableSubcommandSort(bool $value = true): self
<ide> {
<ide> $this->_subcommandSort = (bool)$value;
<ide>
<ide> public function enableSubcommandSort($value = true)
<ide> *
<ide> * @return bool
<ide> */
<del> public function isSubcommandSortEnabled()
<add> public function isSubcommandSortEnabled(): bool
<ide> {
<ide> return $this->_subcommandSort;
<ide> }
<ide> public function isSubcommandSortEnabled()
<ide> * @param array $options An array of parameters that define the behavior of the option
<ide> * @return $this
<ide> */
<del> public function addOption($name, array $options = [])
<add> public function addOption($name, array $options = []): self
<ide> {
<ide> if ($name instanceof ConsoleInputOption) {
<ide> $option = $name;
<ide> public function addOption($name, array $options = [])
<ide> * @param string $name The option name to remove.
<ide> * @return $this
<ide> */
<del> public function removeOption($name)
<add> public function removeOption(string $name): self
<ide> {
<ide> unset($this->_options[$name]);
<ide>
<ide> public function subcommands()
<ide> * @return array [$params, $args]
<ide> * @throws \Cake\Console\Exception\ConsoleException When an invalid parameter is encountered.
<ide> */
<del> public function parse($argv)
<add> public function parse(array $argv): array
<ide> {
<ide> $command = isset($argv[0]) ? Inflector::underscore($argv[0]) : null;
<ide> if (isset($this->_subcommands[$command])) {
<ide> public function parse($argv)
<ide> $params = $args = [];
<ide> $this->_tokens = $argv;
<ide> while (($token = array_shift($this->_tokens)) !== null) {
<add> $token = (string)$token;
<ide> if (isset($this->_subcommands[$token])) {
<ide> continue;
<ide> }
<ide> public function parse($argv)
<ide> * @param int $width The width to format user content to. Defaults to 72
<ide> * @return string Generated help.
<ide> */
<del> public function help($subcommand = null, $format = 'text', $width = 72)
<add> public function help(?string $subcommand = null, string $format = 'text', int $width = 72): string
<ide> {
<ide> if ($subcommand === null) {
<ide> $formatter = new HelpFormatter($this);
<ide> public function help($subcommand = null, $format = 'text', $width = 72)
<ide> * @param string $name The root command name
<ide> * @return $this
<ide> */
<del> public function setRootName($name)
<add> public function setRootName(string $name): self
<ide> {
<ide> $this->rootName = (string)$name;
<ide>
<ide> public function setRootName($name)
<ide> * @param string $command Unknown command name trying to be dispatched.
<ide> * @return string The message to be displayed in the console.
<ide> */
<del> protected function getCommandError($command)
<add> protected function getCommandError(string $command): string
<ide> {
<ide> $rootCommand = $this->getCommand();
<ide> $subcommands = array_keys((array)$this->subcommands());
<ide> protected function getCommandError($command)
<ide> * @param string $option Unknown option name trying to be used.
<ide> * @return string The message to be displayed in the console.
<ide> */
<del> protected function getOptionError($option)
<add> protected function getOptionError(string $option): string
<ide> {
<ide> $availableOptions = array_keys($this->_options);
<ide> $bestGuess = $this->findClosestItem($option, $availableOptions);
<ide> protected function getOptionError($option)
<ide> * @param string $option Unknown short option name trying to be used.
<ide> * @return string The message to be displayed in the console.
<ide> */
<del> protected function getShortOptionError($option)
<add> protected function getShortOptionError(string $option): string
<ide> {
<ide> $out = [sprintf('Unknown short option `%s`', $option)];
<ide> $out[] = '';
<ide> protected function getShortOptionError($option)
<ide> * @param array $haystack List of items available for the type $needle belongs to.
<ide> * @return string|null The closest name to the item submitted by the user.
<ide> */
<del> protected function findClosestItem($needle, $haystack)
<add> protected function findClosestItem(string $needle, array $haystack): ?string
<ide> {
<ide> $bestGuess = null;
<ide> foreach ($haystack as $item) {
<ide> protected function findClosestItem($needle, $haystack)
<ide> * @param array $params The params to append the parsed value into
<ide> * @return array Params with $option added in.
<ide> */
<del> protected function _parseLongOption($option, $params)
<add> protected function _parseLongOption(string $option, array $params): array
<ide> {
<ide> $name = substr($option, 2);
<ide> if (strpos($name, '=') !== false) {
<ide> protected function _parseLongOption($option, $params)
<ide> * @return array Params with $option added in.
<ide> * @throws \Cake\Console\Exception\ConsoleException When unknown short options are encountered.
<ide> */
<del> protected function _parseShortOption($option, $params)
<add> protected function _parseShortOption(string $option, array $params): array
<ide> {
<ide> $key = substr($option, 1);
<ide> if (strlen($key) > 1) {
<ide> protected function _parseShortOption($option, $params)
<ide> * @return array Params with $option added in.
<ide> * @throws \Cake\Console\Exception\ConsoleException
<ide> */
<del> protected function _parseOption($name, $params)
<add> protected function _parseOption(string $name, array $params): array
<ide> {
<ide> if (!isset($this->_options[$name])) {
<ide> throw new ConsoleException($this->getOptionError($name));
<ide> protected function _parseOption($name, $params)
<ide> * @param string $name The name of the option.
<ide> * @return bool
<ide> */
<del> protected function _optionExists($name)
<add> protected function _optionExists(string $name): bool
<ide> {
<ide> if (substr($name, 0, 2) === '--') {
<ide> return isset($this->_options[substr($name, 2)]);
<ide> protected function _optionExists($name)
<ide> * @return array Args
<ide> * @throws \Cake\Console\Exception\ConsoleException
<ide> */
<del> protected function _parseArg($argument, $args)
<add> protected function _parseArg(string $argument, array $args): array
<ide> {
<ide> if (empty($this->_args)) {
<ide> $args[] = $argument;
<ide> protected function _parseArg($argument, $args)
<ide> *
<ide> * @return string next token or ''
<ide> */
<del> protected function _nextToken()
<add> protected function _nextToken(): string
<ide> {
<ide> return isset($this->_tokens[0]) ? $this->_tokens[0] : '';
<ide> }
<ide><path>src/Console/ConsoleOutput.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> class ConsoleOutput
<ide> *
<ide> * @param string $stream The identifier of the stream to write output to.
<ide> */
<del> public function __construct($stream = 'php://stdout')
<add> public function __construct(string $stream = 'php://stdout')
<ide> {
<ide> $this->_output = fopen($stream, 'wb');
<ide>
<ide> public function __construct($stream = 'php://stdout')
<ide> * @param int $newlines Number of newlines to append
<ide> * @return int|bool The number of bytes returned from writing to output.
<ide> */
<del> public function write($message, $newlines = 1)
<add> public function write($message, int $newlines = 1)
<ide> {
<ide> if (is_array($message)) {
<ide> $message = implode(static::LF, $message);
<ide> public function write($message, $newlines = 1)
<ide> * @param string $text Text with styling tags.
<ide> * @return string String with color codes added.
<ide> */
<del> public function styleText($text)
<add> public function styleText(string $text): string
<ide> {
<ide> if ($this->_outputAs == static::RAW) {
<ide> return $text;
<ide> public function styleText($text)
<ide> * @param array $matches An array of matches to replace.
<ide> * @return string
<ide> */
<del> protected function _replaceTags($matches)
<add> protected function _replaceTags(array $matches): string
<ide> {
<ide> $style = $this->styles($matches['tag']);
<ide> if (empty($style)) {
<ide> protected function _replaceTags($matches)
<ide> * @param string $message Message to write.
<ide> * @return int|bool The number of bytes returned from writing to output.
<ide> */
<del> protected function _write($message)
<add> protected function _write(string $message)
<ide> {
<ide> return fwrite($this->_output, $message);
<ide> }
<ide> public function styles($style = null, $definition = null)
<ide> *
<ide> * @return int
<ide> */
<del> public function getOutputAs()
<add> public function getOutputAs(): int
<ide> {
<ide> return $this->_outputAs;
<ide> }
<ide> public function getOutputAs()
<ide> * @return void
<ide> * @throws \InvalidArgumentException in case of a not supported output type.
<ide> */
<del> public function setOutputAs($type)
<add> public function setOutputAs(int $type): void
<ide> {
<ide> if (!in_array($type, [self::RAW, self::PLAIN, self::COLOR], true)) {
<ide> throw new InvalidArgumentException(sprintf('Invalid output type "%s".', $type));
<ide><path>src/Console/Exception/ConsoleException.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>src/Console/Exception/MissingHelperException.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>src/Console/Exception/MissingShellException.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>src/Console/Exception/MissingShellMethodException.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>src/Console/Exception/MissingTaskException.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>src/Console/Exception/StopException.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>src/Console/HelpFormatter.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> public function __construct(ConsoleOptionParser $parser)
<ide> *
<ide> * @param string $alias The alias
<ide> * @return void
<del> * @throws \Cake\Console\Exception\ConsoleException When alias is not a string.
<ide> */
<del> public function setAlias($alias)
<add> public function setAlias(string $alias): void
<ide> {
<del> if (is_string($alias)) {
<del> $this->_alias = $alias;
<del> } else {
<del> throw new ConsoleException('Alias must be of type string.');
<del> }
<add> $this->_alias = $alias;
<ide> }
<ide>
<ide> /**
<ide> public function text($width = 72)
<ide> *
<ide> * @return string
<ide> */
<del> protected function _generateUsage()
<add> protected function _generateUsage(): string
<ide> {
<ide> $usage = [$this->_alias . ' ' . $this->_parser->getCommand()];
<ide> $subcommands = $this->_parser->subcommands();
<ide> protected function _generateUsage()
<ide> * @param array $collection The collection to find a max length of.
<ide> * @return int
<ide> */
<del> protected function _getMaxLength($collection)
<add> protected function _getMaxLength(array $collection): int
<ide> {
<ide> $max = 0;
<ide> foreach ($collection as $item) {
<ide> protected function _getMaxLength($collection)
<ide> * @param bool $string Return the SimpleXml object or a string. Defaults to true.
<ide> * @return string|\SimpleXMLElement See $string
<ide> */
<del> public function xml($string = true)
<add> public function xml(bool $string = true)
<ide> {
<ide> $parser = $this->_parser;
<ide> $xml = new SimpleXMLElement('<shell></shell>');
<ide><path>src/Console/Helper.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>src/Console/HelperRegistry.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> class HelperRegistry extends ObjectRegistry
<ide> * @param \Cake\Console\ConsoleIo $io An io instance.
<ide> * @return void
<ide> */
<del> public function setIo(ConsoleIo $io)
<add> public function setIo(ConsoleIo $io): void
<ide> {
<ide> $this->_io = $io;
<ide> }
<ide><path>src/Console/Shell.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> public function __construct(ConsoleIo $io = null, LocatorInterface $locator = nu
<ide> * @param string $name The name of the root command.
<ide> * @return $this
<ide> */
<del> public function setRootName($name)
<add> public function setRootName(string $name): self
<ide> {
<del> $this->rootName = (string)$name;
<add> $this->rootName = $name;
<ide>
<ide> return $this;
<ide> }
<ide> public function setRootName($name)
<ide> *
<ide> * @return \Cake\Console\ConsoleIo The current ConsoleIo object.
<ide> */
<del> public function getIo()
<add> public function getIo(): ConsoleIo
<ide> {
<ide> return $this->_io;
<ide> }
<ide> public function getIo()
<ide> * @param \Cake\Console\ConsoleIo $io The ConsoleIo object to use.
<ide> * @return void
<ide> */
<del> public function setIo(ConsoleIo $io)
<add> public function setIo(ConsoleIo $io): void
<ide> {
<ide> $this->_io = $io;
<ide> }
<ide> protected function _welcome()
<ide> *
<ide> * @return bool
<ide> */
<del> public function loadTasks()
<add> public function loadTasks(): bool
<ide> {
<ide> if ($this->tasks === true || empty($this->tasks) || empty($this->Tasks)) {
<ide> return true;
<ide> public function loadTasks()
<ide> * @throws \RuntimeException
<ide> * @return void
<ide> */
<del> protected function _validateTasks()
<add> protected function _validateTasks(): void
<ide> {
<ide> foreach ($this->_taskMap as $taskName => $task) {
<ide> $class = App::className($task['class'], 'Shell/Task', 'Task');
<del> if (!class_exists($class)) {
<add> if ($class === false || !class_exists($class)) {
<ide> throw new RuntimeException(sprintf(
<ide> 'Task `%s` not found. Maybe you made a typo or a plugin is missing or not loaded?',
<ide> $taskName
<ide> protected function _validateTasks()
<ide> * @return bool Success
<ide> * @link https://book.cakephp.org/3.0/en/console-and-shells.html#shell-tasks
<ide> */
<del> public function hasTask($task)
<add> public function hasTask(string $task): bool
<ide> {
<ide> return isset($this->_taskMap[Inflector::camelize($task)]);
<ide> }
<ide> public function hasTask($task)
<ide> * @return bool
<ide> * @link https://book.cakephp.org/3.0/en/console-and-shells.html#shell-tasks
<ide> */
<del> public function hasMethod($name)
<add> public function hasMethod(string $name): bool
<ide> {
<ide> try {
<ide> $method = new ReflectionMethod($this, $name);
<ide> public function hasMethod($name)
<ide> * @return int The cli command exit code. 0 is success.
<ide> * @link https://book.cakephp.org/3.0/en/console-and-shells.html#invoking-other-shells-from-your-shell
<ide> */
<del> public function dispatchShell()
<add> public function dispatchShell(): int
<ide> {
<ide> list($args, $extra) = $this->parseDispatchArguments(func_get_args());
<ide>
<ide> public function dispatchShell()
<ide> * @return array First value has to be an array of the command arguments.
<ide> * Second value has to be an array of extra parameter to pass on to the dispatcher
<ide> */
<del> public function parseDispatchArguments($args)
<add> public function parseDispatchArguments(array $args): array
<ide> {
<ide> $extra = [];
<ide>
<ide> public function parseDispatchArguments($args)
<ide> * @return int|bool|null
<ide> * @link https://book.cakephp.org/3.0/en/console-and-shells.html#the-cakephp-console
<ide> */
<del> public function runCommand($argv, $autoMethod = false, $extra = [])
<add> public function runCommand(array $argv, bool $autoMethod = false, array $extra = [])
<ide> {
<ide> $command = isset($argv[0]) ? Inflector::underscore($argv[0]) : null;
<ide> $this->OptionParser = $this->getOptionParser();
<ide> public function runCommand($argv, $autoMethod = false, $extra = [])
<ide> return $this->$method(...$this->args);
<ide> }
<ide>
<del> if ($this->hasTask($command) && isset($subcommands[$command])) {
<add> if ($command && $this->hasTask($command) && isset($subcommands[$command])) {
<ide> $this->startup();
<ide> array_shift($argv);
<ide>
<ide> public function runCommand($argv, $autoMethod = false, $extra = [])
<ide> *
<ide> * @return void
<ide> */
<del> protected function _setOutputLevel()
<add> protected function _setOutputLevel(): void
<ide> {
<ide> $this->_io->setLoggers(ConsoleIo::NORMAL);
<ide> if (!empty($this->params['quiet'])) {
<ide> protected function _setOutputLevel()
<ide> * @param string $command The command to get help for.
<ide> * @return int|bool The number of bytes returned from writing to stdout.
<ide> */
<del> protected function _displayHelp($command)
<add> protected function _displayHelp(string $command)
<ide> {
<ide> $format = 'text';
<ide> if (!empty($this->args[0]) && $this->args[0] === 'xml') {
<ide> public function getOptionParser()
<ide> * @param string $name The task to get.
<ide> * @return \Cake\Console\Shell Object of Task
<ide> */
<del> public function __get($name)
<add> public function __get(string $name)
<ide> {
<ide> if (empty($this->{$name}) && in_array($name, $this->taskNames)) {
<ide> $properties = $this->_taskMap[$name];
<ide> public function __get($name)
<ide> * @param string $name The name of the parameter to get.
<ide> * @return string|bool|null Value. Will return null if it doesn't exist.
<ide> */
<del> public function param($name)
<add> public function param(string $name)
<ide> {
<ide> if (!isset($this->params[$name])) {
<ide> return null;
<ide> public function param($name)
<ide> * @return mixed Either the default value, or the user-provided input.
<ide> * @link https://book.cakephp.org/3.0/en/console-and-shells.html#Shell::in
<ide> */
<del> public function in($prompt, $options = null, $default = null)
<add> public function in(string $prompt, $options = null, $default = null)
<ide> {
<ide> if (!$this->interactive) {
<ide> return $default;
<ide> public function in($prompt, $options = null, $default = null)
<ide> * @see \Cake\Utility\Text::wrap()
<ide> * @link https://book.cakephp.org/3.0/en/console-and-shells.html#Shell::wrapText
<ide> */
<del> public function wrapText($text, $options = [])
<add> public function wrapText(string $text, array $options = [])
<ide> {
<ide> return Text::wrap($text, $options);
<ide> }
<ide> public function wrapText($text, $options = [])
<ide> * @param int $newlines Number of newlines to append
<ide> * @return int|bool The number of bytes returned from writing to stdout.
<ide> */
<del> public function verbose($message, $newlines = 1)
<add> public function verbose($message, int $newlines = 1)
<ide> {
<ide> return $this->_io->verbose($message, $newlines);
<ide> }
<ide> public function verbose($message, $newlines = 1)
<ide> * @param int $newlines Number of newlines to append
<ide> * @return int|bool The number of bytes returned from writing to stdout.
<ide> */
<del> public function quiet($message, $newlines = 1)
<add> public function quiet($message, int $newlines = 1)
<ide> {
<ide> return $this->_io->quiet($message, $newlines);
<ide> }
<ide> public function quiet($message, $newlines = 1)
<ide> * @return int|bool The number of bytes returned from writing to stdout.
<ide> * @link https://book.cakephp.org/3.0/en/console-and-shells.html#Shell::out
<ide> */
<del> public function out($message = null, $newlines = 1, $level = Shell::NORMAL)
<add> public function out($message = null, int $newlines = 1, int $level = Shell::NORMAL)
<ide> {
<ide> return $this->_io->out($message, $newlines, $level);
<ide> }
<ide> public function out($message = null, $newlines = 1, $level = Shell::NORMAL)
<ide> * @param int $newlines Number of newlines to append
<ide> * @return int|bool The number of bytes returned from writing to stderr.
<ide> */
<del> public function err($message = null, $newlines = 1)
<add> public function err($message = null, int $newlines = 1)
<ide> {
<ide> return $this->_io->error($message, $newlines);
<ide> }
<ide> public function err($message = null, $newlines = 1)
<ide> * @return int|bool The number of bytes returned from writing to stdout.
<ide> * @see https://book.cakephp.org/3.0/en/console-and-shells.html#Shell::out
<ide> */
<del> public function info($message = null, $newlines = 1, $level = Shell::NORMAL)
<add> public function info($message = null, int $newlines = 1, int $level = Shell::NORMAL)
<ide> {
<ide> return $this->_io->info($message, $newlines, $level);
<ide> }
<ide> public function info($message = null, $newlines = 1, $level = Shell::NORMAL)
<ide> * @return int|bool The number of bytes returned from writing to stderr.
<ide> * @see https://book.cakephp.org/3.0/en/console-and-shells.html#Shell::err
<ide> */
<del> public function warn($message = null, $newlines = 1)
<add> public function warn($message = null, int $newlines = 1)
<ide> {
<ide> return $this->_io->warning($message, $newlines);
<ide> }
<ide> public function warn($message = null, $newlines = 1)
<ide> * @return int|bool The number of bytes returned from writing to stdout.
<ide> * @see https://book.cakephp.org/3.0/en/console-and-shells.html#Shell::out
<ide> */
<del> public function success($message = null, $newlines = 1, $level = Shell::NORMAL)
<add> public function success($message = null, int $newlines = 1, int $level = Shell::NORMAL)
<ide> {
<ide> return $this->_io->success($message, $newlines, $level);
<ide> }
<ide> public function success($message = null, $newlines = 1, $level = Shell::NORMAL)
<ide> * @return string
<ide> * @link https://book.cakephp.org/3.0/en/console-and-shells.html#Shell::nl
<ide> */
<del> public function nl($multiplier = 1)
<add> public function nl(int $multiplier = 1)
<ide> {
<ide> return $this->_io->nl($multiplier);
<ide> }
<ide> public function nl($multiplier = 1)
<ide> * @return void
<ide> * @link https://book.cakephp.org/3.0/en/console-and-shells.html#Shell::hr
<ide> */
<del> public function hr($newlines = 0, $width = 63)
<add> public function hr(int $newlines = 0, int $width = 63)
<ide> {
<ide> $this->_io->hr($newlines, $width);
<ide> }
<ide> public function hr($newlines = 0, $width = 63)
<ide> * @return void
<ide> * @link https://book.cakephp.org/3.0/en/console-and-shells.html#styling-output
<ide> */
<del> public function abort($message, $exitCode = self::CODE_ERROR)
<add> public function abort(string $message, int $exitCode = self::CODE_ERROR): void
<ide> {
<ide> $this->_io->err('<error>' . $message . '</error>');
<ide> throw new StopException($message, $exitCode);
<ide> public function clear()
<ide> * @return bool Success
<ide> * @link https://book.cakephp.org/3.0/en/console-and-shells.html#creating-files
<ide> */
<del> public function createFile($path, $contents)
<add> public function createFile(string $path, string $contents): bool
<ide> {
<ide> $path = str_replace(DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, $path);
<ide>
<ide> public function createFile($path, $contents)
<ide> * @return string short path
<ide> * @link https://book.cakephp.org/3.0/en/console-and-shells.html#Shell::shortPath
<ide> */
<del> public function shortPath($file)
<add> public function shortPath(string $file): string
<ide> {
<ide> $shortPath = str_replace(ROOT, null, $file);
<ide> $shortPath = str_replace('..' . DIRECTORY_SEPARATOR, '', $shortPath);
<ide> public function shortPath($file)
<ide> * @param array $settings Configuration data for the helper.
<ide> * @return \Cake\Console\Helper The created helper instance.
<ide> */
<del> public function helper($name, array $settings = [])
<add> public function helper(string $name, array $settings = [])
<ide> {
<ide> return $this->_io->helper($name, $settings);
<ide> }
<ide> public function helper($name, array $settings = [])
<ide> * @throws \Cake\Console\Exception\StopException
<ide> * @return void
<ide> */
<del> protected function _stop($status = self::CODE_SUCCESS)
<add> protected function _stop(int $status = self::CODE_SUCCESS): void
<ide> {
<ide> throw new StopException('Halting error reached', $status);
<ide> }
<ide><path>src/Console/ShellDispatcher.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> public function __construct($args = [], $bootstrap = true)
<ide> * @param string|null $original The original full name for the shell.
<ide> * @return string|false The aliased class name, or false if the alias does not exist
<ide> */
<del> public static function alias($short, $original = null)
<add> public static function alias(string $short, ?string $original = null)
<ide> {
<ide> $short = Inflector::camelize($short);
<ide> if ($original) {
<ide> public static function alias($short, $original = null)
<ide> *
<ide> * @return void
<ide> */
<del> public static function resetAliases()
<add> public static function resetAliases(): void
<ide> {
<ide> static::$_aliases = [];
<ide> }
<ide> public static function resetAliases()
<ide> * @param array $extra Extra parameters
<ide> * @return int The exit code of the shell process.
<ide> */
<del> public static function run($argv, $extra = [])
<add> public static function run(array $argv, array $extra = []): int
<ide> {
<ide> $dispatcher = new ShellDispatcher($argv);
<ide>
<ide> public static function run($argv, $extra = [])
<ide> * @return void
<ide> * @throws \Cake\Core\Exception\Exception
<ide> */
<del> protected function _initEnvironment()
<add> protected function _initEnvironment(): void
<ide> {
<ide> if (!$this->_bootstrap()) {
<ide> $message = "Unable to load CakePHP core.\nMake sure Cake exists in " . CAKE_CORE_INCLUDE_PATH;
<ide> protected function _initEnvironment()
<ide> *
<ide> * @return bool Success.
<ide> */
<del> protected function _bootstrap()
<add> protected function _bootstrap(): bool
<ide> {
<ide> if (!Configure::read('App.fullBaseUrl')) {
<ide> Configure::write('App.fullBaseUrl', 'http://localhost');
<ide> protected function _bootstrap()
<ide> * - `requested` : if used, will prevent the Shell welcome message to be displayed
<ide> * @return int The cli command exit code. 0 is success.
<ide> */
<del> public function dispatch($extra = [])
<add> public function dispatch(array $extra = []): int
<ide> {
<ide> try {
<ide> $result = $this->_dispatch($extra);
<ide> public function dispatch($extra = [])
<ide> * @return bool|int|null
<ide> * @throws \Cake\Console\Exception\MissingShellMethodException
<ide> */
<del> protected function _dispatch($extra = [])
<add> protected function _dispatch(array $extra = [])
<ide> {
<ide> $shell = $this->shiftArgs();
<ide>
<ide> protected function _dispatch($extra = [])
<ide> *
<ide> * @return array the resultant list of aliases
<ide> */
<del> public function addShortPluginAliases()
<add> public function addShortPluginAliases(): array
<ide> {
<ide> $plugins = Plugin::loaded();
<ide>
<ide> public function addShortPluginAliases()
<ide> * @return \Cake\Console\Shell A shell instance.
<ide> * @throws \Cake\Console\Exception\MissingShellException when errors are encountered.
<ide> */
<del> public function findShell($shell)
<add> public function findShell(string $shell)
<ide> {
<ide> $className = $this->_shellExists($shell);
<ide> if (!$className) {
<ide> public function findShell($shell)
<ide> * @param string $shell Optionally the name of a plugin or alias
<ide> * @return string Shell name with plugin prefix
<ide> */
<del> protected function _handleAlias($shell)
<add> protected function _handleAlias(string $shell): string
<ide> {
<ide> $aliased = static::alias($shell);
<ide> if ($aliased) {
<ide> protected function _handleAlias($shell)
<ide> * @param string $shell The shell name to look for.
<ide> * @return string|bool Either the classname or false.
<ide> */
<del> protected function _shellExists($shell)
<add> protected function _shellExists(string $shell)
<ide> {
<ide> $class = App::className($shell, 'Shell', 'Shell');
<del> if (class_exists($class)) {
<add> if ($class && class_exists($class)) {
<ide> return $class;
<ide> }
<ide>
<ide> protected function _createShell($className, $shortName)
<ide> {
<ide> list($plugin) = pluginSplit($shortName);
<ide> $instance = new $className();
<del> $instance->plugin = trim($plugin, '.');
<add> $instance->plugin = trim((string)$plugin, '.');
<ide>
<ide> return $instance;
<ide> }
<ide> public function shiftArgs()
<ide> *
<ide> * @return void
<ide> */
<del> public function help()
<add> public function help(): void
<ide> {
<ide> trigger_error(
<ide> 'Console help cannot be generated from Shell classes anymore. ' .
<ide> public function help()
<ide> *
<ide> * @return void
<ide> */
<del> public function version()
<add> public function version(): void
<ide> {
<ide> trigger_error(
<ide> 'Version information cannot be generated from Shell classes anymore. ' .
<ide><path>src/Console/TaskRegistry.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>tests/TestCase/Console/ArgumentsTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>tests/TestCase/Console/CommandCollectionTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide><path>tests/TestCase/Console/CommandFactoryTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide><path>tests/TestCase/Console/CommandRunnerTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide><path>tests/TestCase/Console/CommandTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> public function testGetOptionParser()
<ide> $this->assertSame('routes show', $parser->getCommand());
<ide> }
<ide>
<del> /**
<del> * Test option parser fetching
<del> *
<del> * @expectedException RuntimeException
<del> * @return void
<del> */
<del> public function testGetOptionParserInvalid()
<del> {
<del> $command = $this->getMockBuilder(Command::class)
<del> ->setMethods(['buildOptionParser'])
<del> ->getMock();
<del> $command->expects($this->once())
<del> ->method('buildOptionParser')
<del> ->will($this->returnValue(null));
<del> $command->getOptionParser();
<del> }
<del>
<ide> /**
<ide> * Test that initialize is called.
<ide> *
<ide><path>tests/TestCase/Console/ConsoleErrorHandlerTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>tests/TestCase/Console/ConsoleIoTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> public function testNl()
<ide> $newLine = "\r\n";
<ide> }
<ide> $this->assertEquals($this->io->nl(), $newLine);
<del> $this->assertEquals($this->io->nl(true), $newLine);
<del> $this->assertEquals('', $this->io->nl(false));
<ide> $this->assertEquals($this->io->nl(2), $newLine . $newLine);
<ide> $this->assertEquals($this->io->nl(1), $newLine);
<ide> }
<ide> public function testHr()
<ide> $this->out->expects($this->at(4))->method('write')->with($bar, 1);
<ide> $this->out->expects($this->at(5))->method('write')->with('', true);
<ide>
<del> $this->out->expects($this->at(6))->method('write')->with('', 2);
<del> $this->out->expects($this->at(7))->method('write')->with($bar, 1);
<del> $this->out->expects($this->at(8))->method('write')->with('', 2);
<del>
<ide> $this->io->hr();
<del> $this->io->hr(true);
<ide> $this->io->hr(2);
<ide> }
<ide>
<ide><path>tests/TestCase/Console/ConsoleOptionParserTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>tests/TestCase/Console/ConsoleOutputTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * ConsoleOutputTest file
<ide> *
<ide> public function testWriteNoNewLine()
<ide> $this->output->expects($this->once())->method('_write')
<ide> ->with('Some output');
<ide>
<del> $this->output->write('Some output', false);
<add> $this->output->write('Some output', 0);
<ide> }
<ide>
<ide> /**
<ide> public function testFormattingSimple()
<ide> $this->output->expects($this->once())->method('_write')
<ide> ->with("\033[31mError:\033[0m Something bad");
<ide>
<del> $this->output->write('<error>Error:</error> Something bad', false);
<add> $this->output->write('<error>Error:</error> Something bad', 0);
<ide> }
<ide>
<ide> /**
<ide> public function testFormattingNotEatingTags()
<ide> $this->output->expects($this->once())->method('_write')
<ide> ->with('<red> Something bad');
<ide>
<del> $this->output->write('<red> Something bad', false);
<add> $this->output->write('<red> Something bad', 0);
<ide> }
<ide>
<ide> /**
<ide> public function testFormattingCustom()
<ide> $this->output->expects($this->once())->method('_write')
<ide> ->with("\033[35;46;5;4mAnnoy:\033[0m Something bad");
<ide>
<del> $this->output->write('<annoying>Annoy:</annoying> Something bad', false);
<add> $this->output->write('<annoying>Annoy:</annoying> Something bad', 0);
<ide> }
<ide>
<ide> /**
<ide> public function testFormattingMissingStyleName()
<ide> $this->output->expects($this->once())->method('_write')
<ide> ->with('<not_there>Error:</not_there> Something bad');
<ide>
<del> $this->output->write('<not_there>Error:</not_there> Something bad', false);
<add> $this->output->write('<not_there>Error:</not_there> Something bad', 0);
<ide> }
<ide>
<ide> /**
<ide> public function testFormattingMultipleStylesName()
<ide> $this->output->expects($this->once())->method('_write')
<ide> ->with("\033[31mBad\033[0m \033[33mWarning\033[0m Regular");
<ide>
<del> $this->output->write('<error>Bad</error> <warning>Warning</warning> Regular', false);
<add> $this->output->write('<error>Bad</error> <warning>Warning</warning> Regular', 0);
<ide> }
<ide>
<ide> /**
<ide> public function testFormattingMultipleSameTags()
<ide> $this->output->expects($this->once())->method('_write')
<ide> ->with("\033[31mBad\033[0m \033[31mWarning\033[0m Regular");
<ide>
<del> $this->output->write('<error>Bad</error> <error>Warning</error> Regular', false);
<add> $this->output->write('<error>Bad</error> <error>Warning</error> Regular', 0);
<ide> }
<ide>
<ide> /**
<ide> public function testSetOutputAsRaw()
<ide> $this->output->expects($this->once())->method('_write')
<ide> ->with('<error>Bad</error> Regular');
<ide>
<del> $this->output->write('<error>Bad</error> Regular', false);
<add> $this->output->write('<error>Bad</error> Regular', 0);
<ide> }
<ide>
<ide> /**
<ide> public function testSetOutputAsPlain()
<ide> $this->output->expects($this->once())->method('_write')
<ide> ->with('Bad Regular');
<ide>
<del> $this->output->write('<error>Bad</error> Regular', false);
<del> }
<del>
<del> /**
<del> * test set wrong type.
<del> *
<del> */
<del> public function testSetOutputWrongType()
<del> {
<del> $this->expectException(\InvalidArgumentException::class);
<del> $this->expectExceptionMessage('Invalid output type "Foo".');
<del> $this->output->setOutputAs('Foo');
<add> $this->output->write('<error>Bad</error> Regular', 0);
<ide> }
<ide>
<ide> /**
<ide> public function testSetOutputWrongType()
<ide> public function testSetOutputAsPlainSelectiveTagRemoval()
<ide> {
<ide> $this->output->setOutputAs(ConsoleOutput::PLAIN);
<del> $this->output->expects($this->once())->method('_write')
<add> $this->output->expects($this->once())
<add> ->method('_write')
<ide> ->with('Bad Regular <b>Left</b> <i>behind</i> <name>');
<ide>
<del> $this->output->write('<error>Bad</error> Regular <b>Left</b> <i>behind</i> <name>', false);
<add> $this->output->write('<error>Bad</error> Regular <b>Left</b> <i>behind</i> <name>', 0);
<ide> }
<ide> }
<ide><path>tests/TestCase/Console/HelpFormatterTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * HelpFormatterTest file
<ide> *
<ide> public function testWithHelpAlias()
<ide> $this->assertContains($expected, $result);
<ide> }
<ide>
<del> /**
<del> * Tests that setting a none string help alias triggers an exception
<del> *
<del> * @return void
<del> */
<del> public function testWithNoneStringHelpAlias()
<del> {
<del> $this->expectException(\Cake\Console\Exception\ConsoleException::class);
<del> $this->expectExceptionMessage('Alias must be of type string.');
<del> $parser = new ConsoleOptionParser('mycommand', false);
<del> $formatter = new HelpFormatter($parser);
<del> $formatter->setAlias(['foo']);
<del> }
<del>
<ide> /**
<ide> * test help() with options and arguments that have choices.
<ide> *
<ide><path>tests/TestCase/Console/HelperRegistryTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>tests/TestCase/Console/ShellDispatcherTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>tests/TestCase/Console/ShellTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> public function testRunCommandBaseClassMethod()
<ide> $parser = $this->getMockBuilder('Cake\Console\ConsoleOptionParser')
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<del>
<ide> $parser->expects($this->once())->method('help');
<add> $parser->method('parse')
<add> ->will($this->returnValue([[], []]));
<add>
<ide> $shell->expects($this->once())->method('getOptionParser')
<ide> ->will($this->returnValue($parser));
<ide> $shell->expects($this->never())->method('hr');
<ide> public function testRunCommandMissingMethod()
<ide> $parser = $this->getMockBuilder('Cake\Console\ConsoleOptionParser')
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<del>
<ide> $parser->expects($this->once())->method('help');
<add> $parser->method('parse')
<add> ->will($this->returnValue([[], []]));
<add>
<ide> $shell->expects($this->once())->method('getOptionParser')
<ide> ->will($this->returnValue($parser));
<ide> $shell->_io->expects($this->exactly(2))->method('err');
<ide><path>tests/TestCase/Console/TaskRegistryTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>tests/test_app/TestApp/Shell/ShellTestShell.php
<ide> class ShellTestShell extends Shell
<ide> * @param int $status
<ide> * @return void
<ide> */
<del> protected function _stop($status = Shell::CODE_SUCCESS)
<add> protected function _stop($status = Shell::CODE_SUCCESS): void
<ide> {
<ide> $this->stopped = $status;
<ide> } | 45 |
Text | Text | fix minor doc grammar issues | f50d0d7fdb11ce36715adfbf857e4668c0fd8f75 | <ide><path>docs/userguide/networking/default_network/container-communication.md
<ide> automatically when you install Docker.
<ide>
<ide> Whether a container can talk to the world is governed by two factors. The first
<ide> factor is whether the host machine is forwarding its IP packets. The second is
<del>whether the hosts `iptables` allow this particular connections
<add>whether the host's `iptables` allow this particular connection.
<ide>
<ide> IP packet forwarding is governed by the `ip_forward` system parameter. Packets
<ide> can only pass between containers if this parameter is `1`. Usually you will | 1 |
Javascript | Javascript | log all parameters in ie 9, not just the first two | b277e3ead7296ae27106fe7ac37696635c6bfda1 | <ide><path>src/ng/log.js
<ide> function $LogProvider() {
<ide>
<ide> function consoleLog(type) {
<ide> var console = $window.console || {},
<del> logFn = console[type] || console.log || noop,
<del> hasApply = false;
<add> logFn = console[type] || console.log || noop;
<ide>
<del> // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
<del> // The reason behind this is that console.log has type "object" in IE8...
<del> try {
<del> hasApply = !!logFn.apply;
<del> } catch (e) { /* empty */ }
<del>
<del> if (hasApply) {
<del> return function() {
<del> var args = [];
<del> forEach(arguments, function(arg) {
<del> args.push(formatError(arg));
<del> });
<del> return logFn.apply(console, args);
<del> };
<del> }
<del>
<del> // we are IE which either doesn't have window.console => this is noop and we do nothing,
<del> // or we are IE where console.log doesn't have apply so we log at least first 2 args
<del> return function(arg1, arg2) {
<del> logFn(arg1, arg2 == null ? '' : arg2);
<add> return function() {
<add> var args = [];
<add> forEach(arguments, function(arg) {
<add> args.push(formatError(arg));
<add> });
<add> // Support: IE 9 only
<add> // console methods don't inherit from Function.prototype in IE 9 so we can't
<add> // call `logFn.apply(console, args)` directly.
<add> return Function.prototype.apply.call(logFn, console, args);
<ide> };
<ide> }
<ide> }];
<ide><path>test/ng/logSpec.js
<ide> describe('$log', function() {
<ide> })
<ide> );
<ide>
<del> it('should not attempt to log the second argument in IE if it is not specified', inject(
<del> function() {
<del> log = function(arg1, arg2) { logger += 'log;' + arg2; };
<del> warn = function(arg1, arg2) { logger += 'warn;' + arg2; };
<del> info = function(arg1, arg2) { logger += 'info;' + arg2; };
<del> error = function(arg1, arg2) { logger += 'error;' + arg2; };
<del> debug = function(arg1, arg2) { logger += 'debug;' + arg2; };
<del> },
<del> removeApplyFunctionForIE,
<del> function($log) {
<del> $log.log();
<del> $log.warn();
<del> $log.info();
<del> $log.error();
<del> $log.debug();
<del> expect(logger).toEqual('log;warn;info;error;debug;');
<del> })
<del> );
<add> // Support: Safari 9.1 only, iOS 9.3 only
<add> // For some reason Safari thinks there is always 1 parameter passed here.
<add> if (!/\b9\.\d(\.\d+)* safari/i.test(window.navigator.userAgent) &&
<add> !/\biphone os 9_/i.test(window.navigator.userAgent)) {
<add> it('should not attempt to log the second argument in IE if it is not specified', inject(
<add> function() {
<add> log = function(arg1, arg2) { logger += 'log,' + arguments.length + ';'; };
<add> warn = function(arg1, arg2) { logger += 'warn,' + arguments.length + ';'; };
<add> info = function(arg1, arg2) { logger += 'info,' + arguments.length + ';'; };
<add> error = function(arg1, arg2) { logger += 'error,' + arguments.length + ';'; };
<add> debug = function(arg1, arg2) { logger += 'debug,' + arguments.length + ';'; };
<add> },
<add> removeApplyFunctionForIE,
<add> function($log) {
<add> $log.log();
<add> $log.warn();
<add> $log.info();
<add> $log.error();
<add> $log.debug();
<add> expect(logger).toEqual('log,0;warn,0;info,0;error,0;debug,0;');
<add> })
<add> );
<add> }
<ide> });
<ide>
<ide> describe('$log.debug', function() { | 2 |
Mixed | Javascript | support abortsignal in constructor | 040a27ae5f586305ee52d188e3654563f28e99ce | <ide><path>doc/api/stream.md
<ide> method.
<ide> #### `new stream.Writable([options])`
<ide> <!-- YAML
<ide> changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/36431
<add> description: support passing in an AbortSignal.
<ide> - version: v14.0.0
<ide> pr-url: https://github.com/nodejs/node/pull/30623
<ide> description: Change `autoDestroy` option default to `true`.
<ide> changes:
<ide> [`stream._construct()`][writable-_construct] method.
<ide> * `autoDestroy` {boolean} Whether this stream should automatically call
<ide> `.destroy()` on itself after ending. **Default:** `true`.
<add> * `signal` {AbortSignal} A signal representing possible cancellation.
<ide>
<ide> <!-- eslint-disable no-useless-constructor -->
<ide> ```js
<ide> const myWritable = new Writable({
<ide> });
<ide> ```
<ide>
<add>Calling `abort` on the `AbortController` corresponding to the passed
<add>`AbortSignal` will behave the same way as calling `.destroy(new AbortError())`
<add>on the writeable stream.
<add>
<add>```js
<add>const { Writable } = require('stream');
<add>
<add>const controller = new AbortController();
<add>const myWritable = new Writable({
<add> write(chunk, encoding, callback) {
<add> // ...
<add> },
<add> writev(chunks, callback) {
<add> // ...
<add> },
<add> signal: controller.signal
<add>});
<add>// Later, abort the operation closing the stream
<add>controller.abort();
<add>
<add>```
<ide> #### `writable._construct(callback)`
<ide> <!-- YAML
<ide> added: v15.0.0
<ide> constructor and implement the [`readable._read()`][] method.
<ide> #### `new stream.Readable([options])`
<ide> <!-- YAML
<ide> changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/36431
<add> description: support passing in an AbortSignal.
<ide> - version: v14.0.0
<ide> pr-url: https://github.com/nodejs/node/pull/30623
<ide> description: Change `autoDestroy` option default to `true`.
<ide> changes:
<ide> [`stream._construct()`][readable-_construct] method.
<ide> * `autoDestroy` {boolean} Whether this stream should automatically call
<ide> `.destroy()` on itself after ending. **Default:** `true`.
<add> * `signal` {AbortSignal} A signal representing possible cancellation.
<ide>
<ide> <!-- eslint-disable no-useless-constructor -->
<ide> ```js
<ide> const myReadable = new Readable({
<ide> });
<ide> ```
<ide>
<add>Calling `abort` on the `AbortController` corresponding to the passed
<add>`AbortSignal` will behave the same way as calling `.destroy(new AbortError())`
<add>on the readable created.
<add>
<add>```js
<add>const fs = require('fs');
<add>const controller = new AbortController();
<add>const read = new Readable({
<add> read(size) {
<add> // ...
<add> },
<add> signal: controller.signal
<add>});
<add>// Later, abort the operation closing the stream
<add>controller.abort();
<add>```
<add>
<ide> #### `readable._construct(callback)`
<ide> <!-- YAML
<ide> added: v15.0.0
<ide><path>lib/internal/streams/add-abort-signal.js
<ide> const eos = require('internal/streams/end-of-stream');
<ide> const { ERR_INVALID_ARG_TYPE } = codes;
<ide>
<ide> // This method is inlined here for readable-stream
<add>// It also does not allow for signal to not exist on the steam
<ide> // https://github.com/nodejs/node/pull/36061#discussion_r533718029
<ide> const validateAbortSignal = (signal, name) => {
<del> if (signal !== undefined &&
<del> (signal === null ||
<del> typeof signal !== 'object' ||
<del> !('aborted' in signal))) {
<add> if (typeof signal !== 'object' ||
<add> !('aborted' in signal)) {
<ide> throw new ERR_INVALID_ARG_TYPE(name, 'AbortSignal', signal);
<ide> }
<ide> };
<ide> function isStream(obj) {
<ide> return !!(obj && typeof obj.pipe === 'function');
<ide> }
<ide>
<del>module.exports = function addAbortSignal(signal, stream) {
<add>module.exports.addAbortSignal = function addAbortSignal(signal, stream) {
<ide> validateAbortSignal(signal, 'signal');
<ide> if (!isStream(stream)) {
<ide> throw new ERR_INVALID_ARG_TYPE('stream', 'stream.Stream', stream);
<ide> }
<add> return module.exports.addAbortSignalNoValidate(signal, stream);
<add>};
<add>module.exports.addAbortSignalNoValidate = function(signal, stream) {
<add> if (typeof signal !== 'object' || !('aborted' in signal)) {
<add> return stream;
<add> }
<ide> const onAbort = () => {
<ide> stream.destroy(new AbortError());
<ide> };
<ide><path>lib/internal/streams/readable.js
<ide> const EE = require('events');
<ide> const { Stream, prependListener } = require('internal/streams/legacy');
<ide> const { Buffer } = require('buffer');
<ide>
<add>const {
<add> addAbortSignalNoValidate,
<add>} = require('internal/streams/add-abort-signal');
<add>
<ide> let debug = require('internal/util/debuglog').debuglog('stream', (fn) => {
<ide> debug = fn;
<ide> });
<ide> function Readable(options) {
<ide>
<ide> if (typeof options.construct === 'function')
<ide> this._construct = options.construct;
<add> if (options.signal && !isDuplex)
<add> addAbortSignalNoValidate(options.signal, this);
<ide> }
<ide>
<ide> Stream.call(this, options);
<ide><path>lib/internal/streams/writable.js
<ide> const EE = require('events');
<ide> const Stream = require('internal/streams/legacy').Stream;
<ide> const { Buffer } = require('buffer');
<ide> const destroyImpl = require('internal/streams/destroy');
<add>
<add>const {
<add> addAbortSignalNoValidate,
<add>} = require('internal/streams/add-abort-signal');
<add>
<ide> const {
<ide> getHighWaterMark,
<ide> getDefaultHighWaterMark
<ide> function Writable(options) {
<ide>
<ide> if (typeof options.construct === 'function')
<ide> this._construct = options.construct;
<add> if (options.signal)
<add> addAbortSignalNoValidate(options.signal, this);
<ide> }
<ide>
<ide> Stream.call(this, options);
<ide><path>lib/stream.js
<ide> Stream.Duplex = require('internal/streams/duplex');
<ide> Stream.Transform = require('internal/streams/transform');
<ide> Stream.PassThrough = require('internal/streams/passthrough');
<ide> Stream.pipeline = pipeline;
<del>Stream.addAbortSignal = require('internal/streams/add-abort-signal');
<add>const { addAbortSignal } = require('internal/streams/add-abort-signal');
<add>Stream.addAbortSignal = addAbortSignal;
<ide> Stream.finished = eos;
<ide>
<ide> function lazyLoadPromises() {
<ide><path>test/parallel/test-stream-duplex-destroy.js
<ide> const assert = require('assert');
<ide> });
<ide> duplex.on('close', common.mustCall());
<ide> }
<add>{
<add> // Check abort signal
<add> const controller = new AbortController();
<add> const { signal } = controller;
<add> const duplex = new Duplex({
<add> write(chunk, enc, cb) { cb(); },
<add> read() {},
<add> signal,
<add> });
<add> let count = 0;
<add> duplex.on('error', common.mustCall((e) => {
<add> assert.strictEqual(count++, 0); // Ensure not called twice
<add> assert.strictEqual(e.name, 'AbortError');
<add> }));
<add> duplex.on('close', common.mustCall());
<add> controller.abort();
<add>}
<ide><path>test/parallel/test-stream-readable-destroy.js
<ide> const assert = require('assert');
<ide> read.on('data', common.mustNotCall());
<ide> }
<ide>
<add>{
<add> const controller = new AbortController();
<add> const read = new Readable({
<add> signal: controller.signal,
<add> read() {
<add> this.push('asd');
<add> },
<add> });
<add>
<add> read.on('error', common.mustCall((e) => {
<add> assert.strictEqual(e.name, 'AbortError');
<add> }));
<add> controller.abort();
<add> read.on('data', common.mustNotCall());
<add>}
<add>
<ide> {
<ide> const controller = new AbortController();
<ide> const read = addAbortSignal(controller.signal, new Readable({
<ide><path>test/parallel/test-stream-writable-destroy.js
<ide> const assert = require('assert');
<ide> write.write('asd');
<ide> ac.abort();
<ide> }
<add>
<add>{
<add> const ac = new AbortController();
<add> const write = new Writable({
<add> signal: ac.signal,
<add> write(chunk, enc, cb) { cb(); }
<add> });
<add>
<add> write.on('error', common.mustCall((e) => {
<add> assert.strictEqual(e.name, 'AbortError');
<add> assert.strictEqual(write.destroyed, true);
<add> }));
<add> write.write('asd');
<add> ac.abort();
<add>} | 8 |
Javascript | Javascript | transform empty responses into empty blobs | 9a8c06b502c774f7a0bff1bdc064fbfe16ca75be | <ide><path>Libraries/Blob/FileReader.js
<ide> class FileReader extends (EventTarget(...READER_EVENTS): any) {
<ide> throw new Error('FileReader.readAsArrayBuffer is not implemented');
<ide> }
<ide>
<del> readAsDataURL(blob: Blob) {
<add> readAsDataURL(blob: ?Blob) {
<ide> this._aborted = false;
<ide>
<add> if (blob == null) {
<add> throw new TypeError(
<add> "Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'",
<add> );
<add> }
<add>
<ide> NativeFileReaderModule.readAsDataURL(blob.data).then(
<ide> (text: string) => {
<ide> if (this._aborted) {
<ide> class FileReader extends (EventTarget(...READER_EVENTS): any) {
<ide> );
<ide> }
<ide>
<del> readAsText(blob: Blob, encoding: string = 'UTF-8') {
<add> readAsText(blob: ?Blob, encoding: string = 'UTF-8') {
<ide> this._aborted = false;
<ide>
<add> if (blob == null) {
<add> throw new TypeError(
<add> "Failed to execute 'readAsText' on 'FileReader': parameter 1 is not of type 'Blob'",
<add> );
<add> }
<add>
<ide> NativeFileReaderModule.readAsText(blob.data, encoding).then(
<ide> (text: string) => {
<ide> if (this._aborted) {
<ide><path>Libraries/Network/XMLHttpRequest.js
<ide> class XMLHttpRequest extends (EventTarget(...XHR_EVENTS): any) {
<ide> if (typeof this._response === 'object' && this._response) {
<ide> this._cachedResponse = BlobManager.createFromOptions(this._response);
<ide> } else if (this._response === '') {
<del> this._cachedResponse = null;
<add> this._cachedResponse = BlobManager.createFromParts([]);
<ide> } else {
<ide> throw new Error(`Invalid response for blob: ${this._response}`);
<ide> } | 2 |
Python | Python | add missing license headers | 81852763cf7f6304ff05493bf861040ccfc406db | <ide><path>libcloud/test/common/test_aliyun.py
<add># Licensed to the Apache Software Foundation (ASF) under one or more
<add># contributor license agreements. See the NOTICE file distributed with
<add># this work for additional information regarding copyright ownership.
<add># The ASF licenses this file to You under the Apache License, Version 2.0
<add># (the "License"); you may not use this file except in compliance with
<add># the License. You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing, software
<add># distributed under the License is distributed on an "AS IS" BASIS,
<add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add># See the License for the specific language governing permissions and
<add># limitations under the License.
<add>
<ide> import sys
<ide> import unittest
<ide>
<ide><path>libcloud/test/common/test_aws.py
<add># Licensed to the Apache Software Foundation (ASF) under one or more
<add># contributor license agreements. See the NOTICE file distributed with
<add># this work for additional information regarding copyright ownership.
<add># The ASF licenses this file to You under the Apache License, Version 2.0
<add># (the "License"); you may not use this file except in compliance with
<add># the License. You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing, software
<add># distributed under the License is distributed on an "AS IS" BASIS,
<add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add># See the License for the specific language governing permissions and
<add># limitations under the License.
<add>
<ide> import sys
<ide> import unittest
<ide> from datetime import datetime
<ide><path>libcloud/test/common/test_base.py
<add># Licensed to the Apache Software Foundation (ASF) under one or more
<add># contributor license agreements. See the NOTICE file distributed with
<add># this work for additional information regarding copyright ownership.
<add># The ASF licenses this file to You under the Apache License, Version 2.0
<add># (the "License"); you may not use this file except in compliance with
<add># the License. You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing, software
<add># distributed under the License is distributed on an "AS IS" BASIS,
<add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add># See the License for the specific language governing permissions and
<add># limitations under the License.
<add>
<ide> import unittest
<ide> import sys
<ide>
<ide><path>libcloud/test/common/test_nfsn.py
<del>from mock import Mock, patch
<add># Licensed to the Apache Software Foundation (ASF) under one or more
<add># contributor license agreements. See the NOTICE file distributed with
<add># this work for additional information regarding copyright ownership.
<add># The ASF licenses this file to You under the Apache License, Version 2.0
<add># (the "License"); you may not use this file except in compliance with
<add># the License. You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing, software
<add># distributed under the License is distributed on an "AS IS" BASIS,
<add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add># See the License for the specific language governing permissions and
<add># limitations under the License.
<add>
<ide> import string
<ide> import sys
<ide> import unittest
<ide>
<add>from mock import Mock, patch
<add>
<ide> from libcloud.common.nfsn import NFSNConnection
<ide> from libcloud.test import LibcloudTestCase, MockHttp
<ide> from libcloud.utils.py3 import httplib | 4 |
Javascript | Javascript | name all anonymous watch functions in angular | ca30fce28ca13284bfa1c926e810ed75cdcde499 | <ide><path>docs/src/templates/js/docs.js
<ide> docsApp.controller.DocsController = function($scope, $location, $window, $cookie
<ide> tutorial: 'Tutorial',
<ide> cookbook: 'Examples'
<ide> };
<del> $scope.$watch(function() {return $location.path(); }, function(path) {
<add> $scope.$watch(function docsPathWatch() {return $location.path(); }, function docsPathWatchAction(path) {
<ide> // ignore non-doc links which are used in examples
<ide> if (DOCS_PATH.test(path)) {
<ide> var parts = path.split('/'),
<ide><path>src/bootstrap/bootstrap-prettify.js
<ide> directive.ngEmbedApp = ['$templateCache', '$browser', '$rootScope', '$location',
<ide> }, $delegate);
<ide> }]);
<ide> $provide.decorator('$rootScope', ['$delegate', function(embedRootScope) {
<del> docsRootScope.$watch(function() {
<add> docsRootScope.$watch(function embedRootScopeDigestWatch() {
<ide> embedRootScope.$digest();
<ide> });
<ide> return embedRootScope;
<ide><path>src/bootstrap/bootstrap.js
<ide> directive.dropdownToggle =
<ide> return {
<ide> restrict: 'C',
<ide> link: function(scope, element, attrs) {
<del> scope.$watch(function(){return $location.path();}, function() {
<add> scope.$watch(function dropdownTogglePathWatch(){return $location.path();}, function dropdownTogglePathWatchAction() {
<ide> close && close();
<ide> });
<ide>
<ide><path>src/ng/anchorScroll.js
<ide> function $AnchorScrollProvider() {
<ide> // does not scroll when user clicks on anchor link that is currently on
<ide> // (no url change, no $locaiton.hash() change), browser native does scroll
<ide> if (autoScrollingEnabled) {
<del> $rootScope.$watch(function() {return $location.hash();}, function() {
<del> $rootScope.$evalAsync(scroll);
<del> });
<add> $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
<add> function autoScrollWatchAction() {
<add> $rootScope.$evalAsync(scroll);
<add> });
<ide> }
<ide>
<ide> return scroll;
<ide><path>src/ng/compile.js
<ide> function $CompileProvider($provide) {
<ide> ' (directive: ' + newScopeDirective.name + ')');
<ide> };
<ide> lastValue = scope[scopeName] = parentGet(parentScope);
<del> scope.$watch(function() {
<add> scope.$watch(function parentValueWatch() {
<ide> var parentValue = parentGet(parentScope);
<ide>
<ide> if (parentValue !== scope[scopeName]) {
<ide> function $CompileProvider($provide) {
<ide> bindings = parent.data('$binding') || [];
<ide> bindings.push(interpolateFn);
<ide> safeAddClass(parent.data('$binding', bindings), 'ng-binding');
<del> scope.$watch(interpolateFn, function(value) {
<add> scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
<ide> node[0].nodeValue = value;
<ide> });
<ide> })
<ide> function $CompileProvider($provide) {
<ide> attr[name] = undefined;
<ide> ($$observers[name] || ($$observers[name] = [])).$$inter = true;
<ide> (attr.$$observers && attr.$$observers[name].$$scope || scope).
<del> $watch(interpolateFn, function(value) {
<add> $watch(interpolateFn, function interpolateFnWatchAction(value) {
<ide> attr.$set(name, value);
<ide> });
<ide> })
<ide><path>src/ng/directive/booleanAttrs.js
<ide> forEach(BOOLEAN_ATTR, function(propName, attrName) {
<ide> priority: 100,
<ide> compile: function() {
<ide> return function(scope, element, attr) {
<del> scope.$watch(attr[normalized], function(value) {
<add> scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
<ide> attr.$set(attrName, !!value);
<ide> });
<ide> };
<ide><path>src/ng/directive/input.js
<ide> var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$
<ide>
<ide> // model -> value
<ide> var ctrl = this;
<del> $scope.$watch(ngModelGet, function(value) {
<add> $scope.$watch(ngModelGet, function ngModelWatchAction(value) {
<ide>
<ide> // ignore change from view
<ide> if (ctrl.$modelValue === value) return;
<ide> var ngValueDirective = function() {
<ide> };
<ide> } else {
<ide> return function(scope, elm, attr) {
<del> scope.$watch(attr.ngValue, function(value) {
<add> scope.$watch(attr.ngValue, function valueWatchAction(value) {
<ide> attr.$set('value', value, false);
<ide> });
<ide> };
<ide><path>src/ng/directive/ngBind.js
<ide> */
<ide> var ngBindDirective = ngDirective(function(scope, element, attr) {
<ide> element.addClass('ng-binding').data('$binding', attr.ngBind);
<del> scope.$watch(attr.ngBind, function(value) {
<add> scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
<ide> element.text(value == undefined ? '' : value);
<ide> });
<ide> });
<ide> var ngBindTemplateDirective = ['$interpolate', function($interpolate) {
<ide> var ngBindHtmlUnsafeDirective = [function() {
<ide> return function(scope, element, attr) {
<ide> element.addClass('ng-binding').data('$binding', attr.ngBindHtmlUnsafe);
<del> scope.$watch(attr.ngBindHtmlUnsafe, function(value) {
<add> scope.$watch(attr.ngBindHtmlUnsafe, function ngBindHtmlUnsafeWatchAction(value) {
<ide> element.html(value || '');
<ide> });
<ide> };
<ide><path>src/ng/directive/ngClass.js
<ide> function classDirective(name, selector) {
<ide> name = 'ngClass' + name;
<ide> return ngDirective(function(scope, element, attr) {
<ide> // Reusable function for re-applying the ngClass
<del> function reapply(newVal, oldVal) {
<add> function ngClassWatchAction(newVal, oldVal) {
<ide> if (selector === true || scope.$index % 2 === selector) {
<ide> if (oldVal && (newVal !== oldVal)) {
<ide> if (isObject(oldVal) && !isArray(oldVal))
<ide> function classDirective(name, selector) {
<ide> if (newVal) element.addClass(isArray(newVal) ? newVal.join(' ') : newVal);
<ide> }
<ide> };
<del> scope.$watch(attr[name], reapply, true);
<add> scope.$watch(attr[name], ngClassWatchAction, true);
<ide>
<ide> attr.$observe('class', function(value) {
<ide> var ngClass = scope.$eval(attr[name]);
<del> reapply(ngClass, ngClass);
<add> ngClassWatchAction(ngClass, ngClass);
<ide> });
<ide> });
<ide> }
<ide><path>src/ng/directive/ngInclude.js
<ide> var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$compile'
<ide> element.html('');
<ide> };
<ide>
<del> scope.$watch(srcExp, function(src) {
<add> scope.$watch(srcExp, function ngIncludeWatchAction(src) {
<ide> var thisChangeId = ++changeCounter;
<ide>
<ide> if (src) {
<ide><path>src/ng/directive/ngPluralize.js
<ide> var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interp
<ide> offset + endSymbol));
<ide> });
<ide>
<del> scope.$watch(function() {
<add> scope.$watch(function ngPluralizeWatch() {
<ide> var value = parseFloat(scope.$eval(numberExp));
<ide>
<ide> if (!isNaN(value)) {
<ide> var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interp
<ide> } else {
<ide> return '';
<ide> }
<del> }, function(newVal) {
<add> }, function ngPluralizeWatchAction(newVal) {
<ide> element.text(newVal);
<ide> });
<ide> }
<ide><path>src/ng/directive/ngRepeat.js
<ide> var ngRepeatDirective = ngDirective({
<ide> // We expect this to be a rare case.
<ide> var lastOrder = new HashQueueMap();
<ide> var indexValues = [];
<del> scope.$watch(function(scope){
<add> scope.$watch(function ngRepeatWatch(scope){
<ide> var index, length,
<ide> collection = scope.$eval(rhs),
<ide> collectionLength = size(collection, true),
<ide> var ngRepeatDirective = ngDirective({
<ide> } else {
<ide> last = undefined;
<ide> }
<del>
<add>
<ide> if (last) {
<ide> // if we have already seen this object, then we need to reuse the
<ide> // associated scope/element
<ide> var ngRepeatDirective = ngDirective({
<ide> for (i = 0, l = indexValues.length - length; i < l; i++) {
<ide> indexValues.pop();
<ide> }
<del>
<add>
<ide> //shrink children
<ide> for (key in lastOrder) {
<ide> if (lastOrder.hasOwnProperty(key)) {
<ide><path>src/ng/directive/ngShowHide.js
<ide> */
<ide> //TODO(misko): refactor to remove element from the DOM
<ide> var ngShowDirective = ngDirective(function(scope, element, attr){
<del> scope.$watch(attr.ngShow, function(value){
<add> scope.$watch(attr.ngShow, function ngShowWatchAction(value){
<ide> element.css('display', toBoolean(value) ? '' : 'none');
<ide> });
<ide> });
<ide> var ngShowDirective = ngDirective(function(scope, element, attr){
<ide> */
<ide> //TODO(misko): refactor to remove element from the DOM
<ide> var ngHideDirective = ngDirective(function(scope, element, attr){
<del> scope.$watch(attr.ngHide, function(value){
<add> scope.$watch(attr.ngHide, function ngHideWatchAction(value){
<ide> element.css('display', toBoolean(value) ? 'none' : '');
<ide> });
<ide> });
<ide><path>src/ng/directive/ngStyle.js
<ide> </example>
<ide> */
<ide> var ngStyleDirective = ngDirective(function(scope, element, attr) {
<del> scope.$watch(attr.ngStyle, function(newStyles, oldStyles) {
<add> scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
<ide> if (oldStyles && (newStyles !== oldStyles)) {
<ide> forEach(oldStyles, function(val, style) { element.css(style, '');});
<ide> }
<ide><path>src/ng/directive/ngSwitch.js
<ide> var ngSwitchDirective = valueFn({
<ide> selectedElement,
<ide> selectedScope;
<ide>
<del> scope.$watch(watchExpr, function(value) {
<add> scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
<ide> if (selectedElement) {
<ide> selectedScope.$destroy();
<ide> selectedElement.remove();
<ide><path>src/ng/directive/select.js
<ide> var selectDirective = ['$compile', '$parse', function($compile, $parse) {
<ide>
<ide> // we have to do it on each watch since ngModel watches reference, but
<ide> // we need to work of an array, so we need to see if anything was inserted/removed
<del> scope.$watch(function() {
<add> scope.$watch(function selectMultipleWatch() {
<ide> if (!equals(lastView, ctrl.$viewValue)) {
<ide> lastView = copy(ctrl.$viewValue);
<ide> ctrl.$render();
<ide> var optionDirective = ['$interpolate', function($interpolate) {
<ide> }
<ide>
<ide> if (interpolateFn) {
<del> scope.$watch(interpolateFn, function(newVal, oldVal) {
<add> scope.$watch(interpolateFn, function interpolateWatchAction(newVal, oldVal) {
<ide> attr.$set('value', newVal);
<ide> if (newVal !== oldVal) selectCtrl.removeOption(oldVal);
<ide> selectCtrl.addOption(newVal);
<ide><path>src/ngSanitize/directive/ngBindHtml.js
<ide> angular.module('ngSanitize').directive('ngBindHtml', ['$sanitize', function($sanitize) {
<ide> return function(scope, element, attr) {
<ide> element.addClass('ng-binding').data('$binding', attr.ngBindHtml);
<del> scope.$watch(attr.ngBindHtml, function(value) {
<add> scope.$watch(attr.ngBindHtml, function ngBindHtmlWatchAction(value) {
<ide> value = $sanitize(value);
<ide> element.html(value || '');
<ide> }); | 17 |
Python | Python | add aliases for commonly used `arraylike` objects | 864848ebc58d4eb3a5e79ce1ce3c0f07bf77e8f3 | <ide><path>numpy/typing/__init__.py
<ide> class _8Bit(_16Bit): ... # type: ignore[misc]
<ide> _ScalarLike,
<ide> _VoidLike,
<ide> )
<del>from ._array_like import _SupportsArray, ArrayLike
<ide> from ._shape import _Shape, _ShapeLike
<ide> from ._dtype_like import _SupportsDType, _VoidDTypeLike, DTypeLike
<add>from ._array_like import (
<add> ArrayLike,
<add> _ArrayLike,
<add> _NestedSequence,
<add> _SupportsArray,
<add> _ArrayLikeBool,
<add> _ArrayLikeUInt,
<add> _ArrayLikeInt,
<add> _ArrayLikeFloat,
<add> _ArrayLikeComplex,
<add> _ArrayLikeTD64,
<add> _ArrayLikeDT64,
<add> _ArrayLikeObject,
<add> _ArrayLikeVoid,
<add> _ArrayLikeStr,
<add> _ArrayLikeBytes,
<add>)
<ide>
<ide> if __doc__ is not None:
<ide> from ._add_docstring import _docstrings
<ide><path>numpy/typing/_array_like.py
<ide> import sys
<ide> from typing import Any, overload, Sequence, TYPE_CHECKING, Union, TypeVar
<ide>
<del>from numpy import ndarray, dtype
<del>from ._scalars import _ScalarLike
<add>from numpy import (
<add> ndarray,
<add> dtype,
<add> generic,
<add> bool_,
<add> unsignedinteger,
<add> integer,
<add> floating,
<add> complexfloating,
<add> timedelta64,
<add> datetime64,
<add> object_,
<add> void,
<add> str_,
<add> bytes_,
<add>)
<ide> from ._dtype_like import DTypeLike
<ide>
<ide> if sys.version_info >= (3, 8):
<ide> else:
<ide> HAVE_PROTOCOL = True
<ide>
<add>_T = TypeVar("_T")
<ide> _DType = TypeVar("_DType", bound="dtype[Any]")
<ide>
<ide> if TYPE_CHECKING or HAVE_PROTOCOL:
<ide> def __array__(self, dtype: None = ...) -> ndarray[Any, _DType]: ...
<ide> else:
<ide> _SupportsArray = Any
<ide>
<add># TODO: Wait for support for recursive types
<add>_NestedSequence = Union[
<add> _T,
<add> Sequence[_T],
<add> Sequence[Sequence[_T]],
<add> Sequence[Sequence[Sequence[_T]]],
<add> Sequence[Sequence[Sequence[Sequence[_T]]]],
<add>]
<add>_RecursiveSequence = Sequence[Sequence[Sequence[Sequence[Sequence[Any]]]]]
<add>
<add># A union representing array-like objects; consists of two typevars:
<add># One representing types that can be parametrized w.r.t. `np.dtype`
<add># and another one for the rest
<add>_ArrayLike = Union[
<add> _NestedSequence[_SupportsArray[_DType]],
<add> _NestedSequence[_T],
<add>]
<add>
<ide> # TODO: support buffer protocols once
<ide> #
<ide> # https://bugs.python.org/issue27501
<ide> def __array__(self, dtype: None = ...) -> ndarray[Any, _DType]: ...
<ide> #
<ide> # https://github.com/python/typing/issues/593
<ide> ArrayLike = Union[
<del> _ScalarLike,
<del> Sequence[_ScalarLike],
<del> Sequence[Sequence[Any]], # TODO: Wait for support for recursive types
<del> "_SupportsArray[Any]",
<add> _RecursiveSequence,
<add> _ArrayLike[
<add> "dtype[Any]",
<add> Union[bool, int, float, complex, str, bytes]
<add> ],
<add>]
<add>
<add># `ArrayLike<X>`: array-like objects that can be coerced into `X`
<add># given the casting rules `same_kind`
<add>_ArrayLikeBool = _ArrayLike[
<add> "dtype[bool_]",
<add> bool,
<add>]
<add>_ArrayLikeUInt = _ArrayLike[
<add> "dtype[Union[bool_, unsignedinteger[Any]]]",
<add> bool,
<add>]
<add>_ArrayLikeInt = _ArrayLike[
<add> "dtype[Union[bool_, integer[Any]]]",
<add> Union[bool, int],
<add>]
<add>_ArrayLikeFloat = _ArrayLike[
<add> "dtype[Union[bool_, integer[Any], floating[Any]]]",
<add> Union[bool, int, float],
<add>]
<add>_ArrayLikeComplex = _ArrayLike[
<add> "dtype[Union[bool_, integer[Any], floating[Any], complexfloating[Any, Any]]]",
<add> Union[bool, int, float, complex],
<add>]
<add>_ArrayLikeTD64 = _ArrayLike[
<add> "dtype[Union[bool_, integer[Any], timedelta64]]",
<add> Union[bool, int],
<add>]
<add>_ArrayLikeDT64 = _NestedSequence[_SupportsArray["dtype[datetime64]"]]
<add>_ArrayLikeObject = _NestedSequence[_SupportsArray["dtype[object_]"]]
<add>
<add>_ArrayLikeVoid = _NestedSequence[_SupportsArray["dtype[void]"]]
<add>_ArrayLikeStr = _ArrayLike[
<add> "dtype[str_]",
<add> str,
<add>]
<add>_ArrayLikeBytes = _ArrayLike[
<add> "dtype[bytes_]",
<add> bytes,
<ide> ] | 2 |
Text | Text | fix minor typos in the changelog | 4eeeca405ecff7fc26f27f43aa37bc3a31da0942 | <ide><path>CHANGELOG.md
<ide> languages:
<ide> * [2097](https://github.com/moment/moment/issues/2097) add ar-tn locale
<ide>
<ide> deprecations:
<del>* [2074](https://github.com/moment/moment/issues/2074) Implement `moment.fn.utcOffset`, deprecate `momen.fn.zone`
<add>* [2074](https://github.com/moment/moment/issues/2074) Implement `moment.fn.utcOffset`, deprecate `moment.fn.zone`
<ide>
<ide> features:
<ide> * [2088](https://github.com/moment/moment/issues/2088) add moment.fn.isBetween
<ide> Bugfix: Fixed parsing of first century dates
<ide>
<ide> Bugfix: Parsing 10Sep2001 should work as expected
<ide>
<del>Bugfix: Fixed wierdness with `moment.utc()` parsing.
<add>Bugfix: Fixed weirdness with `moment.utc()` parsing.
<ide>
<ide> Changed language ordinal method to return the number + ordinal instead of just the ordinal.
<ide> | 1 |
Python | Python | fix deprecation for configuration.getsection | f7fe363255801f7342b8a92e119b7e75e26ab5cb | <ide><path>airflow/configuration.py
<ide> def getsection(*args, **kwargs): # noqa: D103
<ide> DeprecationWarning,
<ide> stacklevel=2,
<ide> )
<del> return conf.getint(*args, **kwargs)
<add> return conf.getsection(*args, **kwargs)
<ide>
<ide>
<ide> def has_option(*args, **kwargs): # noqa: D103 | 1 |
Javascript | Javascript | use comment nodes for empty components | 358140679cbda686f8c3a7d04887342188572cb0 | <ide><path>src/renderers/dom/client/ReactDOMComponentTree.js
<ide> function precacheChildNodes(inst, node) {
<ide> // We assume the child nodes are in the same order as the child instances.
<ide> for (; childNode !== null; childNode = childNode.nextSibling) {
<ide> if (childNode.nodeType === 1 &&
<del> childNode.getAttribute(ATTR_NAME) === String(childID)) {
<add> childNode.getAttribute(ATTR_NAME) === String(childID) ||
<add> childNode.nodeType === 8 &&
<add> childNode.nodeValue === ' react-empty: ' + childID + ' ') {
<ide> precacheNode(childInst, childNode);
<ide> continue outer;
<ide> }
<ide><path>src/renderers/dom/shared/Danger.js
<ide> var Danger = {
<ide> );
<ide> invariant(markup, 'dangerouslyReplaceNodeWithMarkup(...): Missing markup.');
<ide> invariant(
<del> oldChild.tagName.toLowerCase() !== 'html',
<add> oldChild.nodeName !== 'HTML',
<ide> 'dangerouslyReplaceNodeWithMarkup(...): Cannot replace markup of the ' +
<ide> '<html> node. This is because browser quirks make this unreliable ' +
<ide> 'and/or slow. If you want to render to the root you must use ' +
<ide><path>src/renderers/dom/shared/ReactDOMEmptyComponent.js
<add>/**
<add> * Copyright 2014-2015, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> *
<add> * @providesModule ReactDOMEmptyComponent
<add> */
<add>
<add>'use strict';
<add>
<add>var DOMLazyTree = require('DOMLazyTree');
<add>var ReactDOMComponentTree = require('ReactDOMComponentTree');
<add>
<add>var assign = require('Object.assign');
<add>
<add>var ReactDOMEmptyComponent = function(instantiate) {
<add> // ReactCompositeComponent uses this:
<add> this._currentElement = null;
<add> // ReactDOMComponentTree uses these:
<add> this._nativeNode = null;
<add> this._nativeParent = null;
<add> this._nativeContainerInfo = null;
<add> this._domID = null;
<add>};
<add>assign(ReactDOMEmptyComponent.prototype, {
<add> construct: function(element) {
<add> },
<add> mountComponent: function(
<add> transaction,
<add> nativeParent,
<add> nativeContainerInfo,
<add> context
<add> ) {
<add> var domID = nativeContainerInfo._idCounter++;
<add> this._domID = domID;
<add> this._nativeParent = nativeParent;
<add> this._nativeContainerInfo = nativeContainerInfo;
<add>
<add> var nodeValue = ' react-empty: ' + this._domID + ' ';
<add> if (transaction.useCreateElement) {
<add> var ownerDocument = nativeContainerInfo._ownerDocument;
<add> var node = ownerDocument.createComment(nodeValue);
<add> ReactDOMComponentTree.precacheNode(this, node);
<add> return DOMLazyTree(node);
<add> } else {
<add> if (transaction.renderToStaticMarkup) {
<add> // Normally we'd insert a comment node, but since this is a situation
<add> // where React won't take over (static pages), we can simply return
<add> // nothing.
<add> return '';
<add> }
<add> return '<!--' + nodeValue + '-->';
<add> }
<add> },
<add> receiveComponent: function() {
<add> },
<add> getNativeNode: function() {
<add> return ReactDOMComponentTree.getNodeFromInstance(this);
<add> },
<add> unmountComponent: function() {
<add> ReactDOMComponentTree.uncacheNode(this);
<add> },
<add>});
<add>
<add>module.exports = ReactDOMEmptyComponent;
<ide><path>src/renderers/dom/shared/ReactDOMTextComponent.js
<ide> assign(ReactDOMTextComponent.prototype, {
<ide> // TODO: This is really a ReactText (ReactNode), not a ReactElement
<ide> this._currentElement = text;
<ide> this._stringText = '' + text;
<add> // ReactDOMComponentTree uses these:
<ide> this._nativeNode = null;
<del> // ReactDOMComponentTree uses this:
<ide> this._nativeParent = null;
<ide>
<ide> // Properties
<ide><path>src/renderers/dom/shared/ReactDefaultInjection.js
<ide> var ReactComponentBrowserEnvironment =
<ide> require('ReactComponentBrowserEnvironment');
<ide> var ReactDOMComponent = require('ReactDOMComponent');
<ide> var ReactDOMComponentTree = require('ReactDOMComponentTree');
<add>var ReactDOMEmptyComponent = require('ReactDOMEmptyComponent');
<ide> var ReactDOMTreeTraversal = require('ReactDOMTreeTraversal');
<ide> var ReactDOMTextComponent = require('ReactDOMTextComponent');
<ide> var ReactDefaultBatchingStrategy = require('ReactDefaultBatchingStrategy');
<ide> function inject() {
<ide> ReactInjection.DOMProperty.injectDOMPropertyConfig(HTMLDOMPropertyConfig);
<ide> ReactInjection.DOMProperty.injectDOMPropertyConfig(SVGDOMPropertyConfig);
<ide>
<del> ReactInjection.EmptyComponent.injectEmptyComponent('noscript');
<add> ReactInjection.EmptyComponent.injectEmptyComponentFactory(
<add> function(instantiate) {
<add> return new ReactDOMEmptyComponent(instantiate);
<add> }
<add> );
<ide>
<ide> ReactInjection.Updates.injectReconcileTransaction(
<ide> ReactReconcileTransaction
<ide><path>src/renderers/shared/reconciler/ReactEmptyComponent.js
<ide>
<ide> 'use strict';
<ide>
<del>var ReactElement = require('ReactElement');
<del>var ReactReconciler = require('ReactReconciler');
<del>
<del>var assign = require('Object.assign');
<del>
<del>var placeholderElement;
<add>var emptyComponentFactory;
<ide>
<ide> var ReactEmptyComponentInjection = {
<del> injectEmptyComponent: function(component) {
<del> placeholderElement = ReactElement.createElement(component);
<add> injectEmptyComponentFactory: function(factory) {
<add> emptyComponentFactory = factory;
<ide> },
<ide> };
<ide>
<del>var ReactEmptyComponent = function(instantiate) {
<del> this._currentElement = null;
<del> this._renderedComponent = instantiate(placeholderElement);
<del>};
<del>assign(ReactEmptyComponent.prototype, {
<del> construct: function(element) {
<del> },
<del> mountComponent: function(
<del> transaction,
<del> nativeParent,
<del> nativeContainerInfo,
<del> context
<del> ) {
<del> return ReactReconciler.mountComponent(
<del> this._renderedComponent,
<del> transaction,
<del> nativeParent,
<del> nativeContainerInfo,
<del> context
<del> );
<add>var ReactEmptyComponent = {
<add> create: function(instantiate) {
<add> return emptyComponentFactory(instantiate);
<ide> },
<del> receiveComponent: function() {
<del> },
<del> getNativeNode: function() {
<del> return ReactReconciler.getNativeNode(this._renderedComponent);
<del> },
<del> unmountComponent: function() {
<del> ReactReconciler.unmountComponent(this._renderedComponent);
<del> this._renderedComponent = null;
<del> },
<del>});
<add>};
<ide>
<ide> ReactEmptyComponent.injection = ReactEmptyComponentInjection;
<ide>
<ide><path>src/renderers/shared/reconciler/ReactSimpleEmptyComponent.js
<add>/**
<add> * Copyright 2014-2015, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> *
<add> * @providesModule ReactSimpleEmptyComponent
<add> */
<add>
<add>'use strict';
<add>
<add>var ReactReconciler = require('ReactReconciler');
<add>
<add>var assign = require('Object.assign');
<add>
<add>var ReactSimpleEmptyComponent = function(placeholderElement, instantiate) {
<add> this._currentElement = null;
<add> this._renderedComponent = instantiate(placeholderElement);
<add>};
<add>assign(ReactSimpleEmptyComponent.prototype, {
<add> construct: function(element) {
<add> },
<add> mountComponent: function(
<add> transaction,
<add> nativeParent,
<add> nativeContainerInfo,
<add> context
<add> ) {
<add> return ReactReconciler.mountComponent(
<add> this._renderedComponent,
<add> transaction,
<add> nativeParent,
<add> nativeContainerInfo,
<add> context
<add> );
<add> },
<add> receiveComponent: function() {
<add> },
<add> getNativeNode: function() {
<add> return ReactReconciler.getNativeNode(this._renderedComponent);
<add> },
<add> unmountComponent: function() {
<add> ReactReconciler.unmountComponent(this._renderedComponent);
<add> this._renderedComponent = null;
<add> },
<add>});
<add>
<add>module.exports = ReactSimpleEmptyComponent;
<ide><path>src/renderers/shared/reconciler/__tests__/ReactEmptyComponent-test.js
<ide> describe('ReactEmptyComponent', function() {
<ide> expect(log.argsForCall[3][0]).toBe(null);
<ide> });
<ide>
<add> it('should be able to switch in a list of children', () => {
<add> var instance1 =
<add> <TogglingComponent
<add> firstComponent={null}
<add> secondComponent={'div'}
<add> />;
<add>
<add> ReactTestUtils.renderIntoDocument(
<add> <div>
<add> {instance1}
<add> {instance1}
<add> {instance1}
<add> </div>
<add> );
<add>
<add> expect(log.argsForCall.length).toBe(6);
<add> expect(log.argsForCall[0][0]).toBe(null);
<add> expect(log.argsForCall[1][0]).toBe(null);
<add> expect(log.argsForCall[2][0]).toBe(null);
<add> expect(log.argsForCall[3][0].tagName).toBe('DIV');
<add> expect(log.argsForCall[4][0].tagName).toBe('DIV');
<add> expect(log.argsForCall[5][0].tagName).toBe('DIV');
<add> });
<add>
<ide> it('should distinguish between a script placeholder and an actual script tag',
<ide> () => {
<ide> var instance1 =
<ide> describe('ReactEmptyComponent', function() {
<ide>
<ide> ReactDOM.render(<Empty />, container);
<ide> var noscript1 = container.firstChild;
<del> expect(noscript1.tagName).toBe('NOSCRIPT');
<add> expect(noscript1.nodeName).toBe('#comment');
<ide>
<ide> // This update shouldn't create a DOM node
<ide> ReactDOM.render(<Empty />, container);
<ide> var noscript2 = container.firstChild;
<del> expect(noscript2.tagName).toBe('NOSCRIPT');
<add> expect(noscript2.nodeName).toBe('#comment');
<ide>
<ide> expect(noscript1).toBe(noscript2);
<ide> });
<ide><path>src/renderers/shared/reconciler/instantiateReactComponent.js
<ide> function instantiateReactComponent(node) {
<ide> var instance;
<ide>
<ide> if (node === null || node === false) {
<del> instance = new ReactEmptyComponent(instantiateReactComponent);
<add> instance = ReactEmptyComponent.create(instantiateReactComponent);
<ide> } else if (typeof node === 'object') {
<ide> var element = node;
<ide> invariant( | 9 |
PHP | PHP | fix typo causing notice errors | 4b3d8612e9928701b0be5808cdbc504cc0b3588b | <ide><path>lib/Cake/Core/App.php
<ide> protected static function _mapped($name, $plugin = null) {
<ide> if ($plugin) {
<ide> $key = 'plugin.' . $name;
<ide> }
<del> return isset(self::$_map[$key]) ? self::$_map[$name] : false;
<add> return isset(self::$_map[$key]) ? self::$_map[$key] : false;
<ide> }
<ide>
<ide> /** | 1 |
Python | Python | fix cache for gpt-neo-x | fdb120805c93d101efc03ec716e9153562054db7 | <ide><path>src/transformers/modeling_utils.py
<ide> def _find_mismatched_keys(
<ide>
<ide> if offload_state_dict:
<ide> # Load back temporarily offloaded state dict
<del> load_offloaded_weights(model, state_dict_index, state_dict_folder)
<add> load_offloaded_weights(model_to_load, state_dict_index, state_dict_folder)
<ide> shutil.rmtree(state_dict_folder)
<ide>
<ide> if len(error_msgs) > 0:
<ide><path>src/transformers/models/gpt_neox/modeling_gpt_neox.py
<ide> def forward(
<ide> past_value = layer_past[1]
<ide> key = torch.cat((past_key, key), dim=-2)
<ide> value = torch.cat((past_value, value), dim=-2)
<del> present = None if use_cache else (key, value)
<add> present = (key, value) if use_cache else None
<ide>
<ide> # Compute attention
<ide> attn_output, attn_weights = self._attn(query, key, value, attention_mask, head_mask)
<ide><path>tests/models/gpt_neox/test_modeling_gpt_neox.py
<ide> def test_model_as_decoder_with_default_input_mask(self):
<ide>
<ide> self.model_tester.create_and_check_model_as_decoder(config, input_ids, input_mask)
<ide>
<add> def test_decoder_model_past_large_inputs(self):
<add> config, input_ids, input_mask, token_labels = self.model_tester.prepare_config_and_inputs()
<add> self.model_tester.create_and_check_decoder_model_past_large_inputs(config, input_ids, input_mask)
<add>
<add> def test_model_for_causal_lm(self):
<add> config_and_inputs = self.model_tester.prepare_config_and_inputs()
<add> self.model_tester.create_and_check_for_causal_lm(*config_and_inputs)
<add>
<ide> @slow
<ide> def test_model_from_pretrained(self):
<ide> for model_name in GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: | 3 |
Text | Text | capitalize "effect" in the title | e30deb67e1428e1d8c754cb927fca4a1a746f394 | <ide><path>guide/english/3d/blender/iceberg-scene/index.md
<del>---
<del>title: Blender Water Shader effect
<del>---
<del>
<del># This is a simple scene to render polar waters.
<del>
<del>**_To make the cube look like water, mix the following shaders:_**
<del>
<del>1. Glass BSDF Shader : Roughness = 0.850
<del> , IOR = 1.010 ~ 1.333
<del> and Color = Blue
<del>2. Mix Shader : Factor = 0.500
<del>3. Translucent BSDF Shader : Color ~= 2B9489 (a bit dark greenish blue)
<del>4. Transparent BSDF Shader : Color ~= 3173C0 (bluish)
<del>
<del>
<del>
<del><a href="http://www.youtube.com/watch?feature=player_embedded&v=4m2ldp-2fJc" target="_blank"><img src="http://img.youtube.com/vi/4m2ldp-2fJc/0.jpg"
<del>alt="IMAGE ALT TEXT HERE" width="240" height="180" border="10" /></a>
<del>you can watch this to learn how to blender water.
<add>---
<add>title: Blender Water Shader Effect
<add>---
<add>
<add># This is a simple scene to render polar waters.
<add>
<add>**_To make the cube look like water, mix the following shaders:_**
<add>
<add>1. Glass BSDF Shader : Roughness = 0.850
<add> , IOR = 1.010 ~ 1.333
<add> and Color = Blue
<add>2. Mix Shader : Factor = 0.500
<add>3. Translucent BSDF Shader : Color ~= 2B9489 (a bit dark greenish blue)
<add>4. Transparent BSDF Shader : Color ~= 3173C0 (bluish)
<add>
<add><a href="http://www.youtube.com/watch?feature=player_embedded&v=4m2ldp-2fJc" target="_blank"><img src="http://img.youtube.com/vi/4m2ldp-2fJc/0.jpg"
<add>alt="IMAGE ALT TEXT HERE" width="240" height="180" border="10" /></a>
<add>you can watch this to learn how to blender water. | 1 |
Text | Text | fix apache directives [ci skip] | 02ef0313419f50ac09ec782cf042ed7f43d129c7 | <ide><path>guides/source/asset_pipeline.md
<ide> For Apache:
<ide> # `mod_expires` to be enabled.
<ide> <Location /assets/>
<ide> # Use of ETag is discouraged when Last-Modified is present
<del> Header unset ETag FileETag None
<add> Header unset ETag
<add> FileETag None
<ide> # RFC says only cache for 1 year
<del> ExpiresActive On ExpiresDefault "access plus 1 year"
<add> ExpiresActive On
<add> ExpiresDefault "access plus 1 year"
<ide> </Location>
<ide> ```
<ide> | 1 |
PHP | PHP | use symfonystyle in command | fde58c362d2f736040d3601920c711a9ae1555a7 | <ide><path>src/Illuminate/Console/Command.php
<ide> use Symfony\Component\Console\Input\ArrayInput;
<ide> use Symfony\Component\Console\Output\NullOutput;
<ide> use Symfony\Component\Console\Question\Question;
<add>use Symfony\Component\Console\Style\SymfonyStyle;
<ide> use Symfony\Component\Console\Input\InputInterface;
<ide> use Symfony\Component\Console\Output\OutputInterface;
<ide> use Symfony\Component\Console\Question\ChoiceQuestion;
<ide> class Command extends \Symfony\Component\Console\Command\Command {
<ide> /**
<ide> * The output interface implementation.
<ide> *
<del> * @var \Symfony\Component\Console\Output\OutputInterface
<add> * @var \Symfony\Component\Console\Style\SymfonyStyle
<ide> */
<ide> protected $output;
<ide>
<ide> public function run(InputInterface $input, OutputInterface $output)
<ide> {
<ide> $this->input = $input;
<ide>
<del> $this->output = $output;
<add> $this->output = new SymfonyStyle($input, $output);
<ide>
<ide> return parent::run($input, $output);
<ide> }
<ide> public function option($key = null)
<ide> */
<ide> public function confirm($question, $default = false)
<ide> {
<del> $helper = $this->getHelperSet()->get('question');
<del>
<del> $question = new ConfirmationQuestion("<question>{$question}</question> ", $default);
<del>
<del> return $helper->ask($this->input, $this->output, $question);
<add> return $this->output->confirm($question, $default);
<ide> }
<ide>
<ide> /**
<ide> public function confirm($question, $default = false)
<ide> */
<ide> public function ask($question, $default = null)
<ide> {
<del> $helper = $this->getHelperSet()->get('question');
<del>
<del> $question = new Question("<question>$question</question> ", $default);
<del>
<del> return $helper->ask($this->input, $this->output, $question);
<add> return $this->output->ask($question, $default);
<ide> }
<ide>
<ide> /**
<ide> public function ask($question, $default = null)
<ide> */
<ide> public function askWithCompletion($question, array $choices, $default = null)
<ide> {
<del> $helper = $this->getHelperSet()->get('question');
<del>
<del> $question = new Question("<question>$question</question> ", $default);
<add> $question = new Question($question, $default);
<ide>
<ide> $question->setAutocompleterValues($choices);
<ide>
<del> return $helper->ask($this->input, $this->output, $question);
<add> return $this->output->askQuestion($question);
<ide> }
<ide>
<ide> /**
<ide> public function askWithCompletion($question, array $choices, $default = null)
<ide> */
<ide> public function secret($question, $fallback = true)
<ide> {
<del> $helper = $this->getHelperSet()->get('question');
<del>
<del> $question = new Question("<question>$question</question> ");
<add> $question = new Question($question);
<ide>
<ide> $question->setHidden(true)->setHiddenFallback($fallback);
<ide>
<del> return $helper->ask($this->input, $this->output, $question);
<add> return $this->output->askQuestion($question);
<ide> }
<ide>
<ide> /**
<ide> public function secret($question, $fallback = true)
<ide> */
<ide> public function choice($question, array $choices, $default = null, $attempts = null, $multiple = null)
<ide> {
<del> $helper = $this->getHelperSet()->get('question');
<del>
<del> $question = new ChoiceQuestion("<question>$question</question> ", $choices, $default);
<add> $question = new ChoiceQuestion($question, $choices, $default);
<ide>
<ide> $question->setMaxAttempts($attempts)->setMultiselect($multiple);
<ide>
<del> return $helper->ask($this->input, $this->output, $question);
<add> return $this->output->askQuestion($question);
<ide> }
<ide>
<ide> /** | 1 |
Ruby | Ruby | add tasks to automatize changelog headers | d52baa851480ca79d60333187cd0dab9338b7c5f | <ide><path>tasks/release.rb
<ide> end
<ide>
<ide> namespace :changelog do
<add> task :header do
<add> (FRAMEWORKS + ['guides']).each do |fw|
<add> require 'date'
<add> fname = File.join fw, 'CHANGELOG.md'
<add>
<add> header = "## Rails #{version} (#{Date.today.strftime('%B %d, %Y')}) ##\n\n* No changes.\n\n\n"
<add> contents = header + File.read(fname)
<add> File.open(fname, 'wb') { |f| f.write contents }
<add> end
<add> end
<add>
<ide> task :release_date do
<ide> (FRAMEWORKS + ['guides']).each do |fw|
<ide> require 'date'
<del> replace = '\1(' + Date.today.strftime('%B %d, %Y') + ')'
<add> replace = "## Rails #{version} (#{Date.today.strftime('%B %d, %Y')}) ##\n"
<ide> fname = File.join fw, 'CHANGELOG.md'
<ide>
<del> contents = File.read(fname).sub(/^([^(]*)\(unreleased\)/, replace)
<add> contents = File.read(fname).sub(/^(## Rails .*)\n/, replace)
<ide> File.open(fname, 'wb') { |f| f.write contents }
<ide> end
<ide> end | 1 |
Javascript | Javascript | remove last uses of {' '} in docs and tests | 09333a3819a8e1e6606536f9b572d9042a9426cb | <ide><path>src/browser/ui/dom/components/__tests__/ReactDOMInput-test.js
<ide> describe('ReactDOMInput', function() {
<ide> render: function() {
<ide> return (
<ide> <div>
<del> <input ref="a" type="radio" name="fruit" checked={true} />A{' '}
<del> <input ref="b" type="radio" name="fruit" />B{' '}
<add> <input ref="a" type="radio" name="fruit" checked={true} />A
<add> <input ref="b" type="radio" name="fruit" />B
<ide>
<ide> <form>
<ide> <input ref="c" type="radio" name="fruit" defaultChecked={true} />
<ide><path>src/core/__tests__/refs-destruction-test.js
<ide> var TestComponent = React.createClass({
<ide> return (
<ide> <div>
<ide> <div ref="theInnerDiv">
<del> {' '}Lets try to destroy this.{' '}
<add> Lets try to destroy this.
<ide> </div>
<ide> </div>
<ide> ); | 2 |
Text | Text | add changelog entry for on master too | f8ca941f4a0a5a6115a05d06646a6411ebe5aa44 | <ide><path>actionpack/CHANGELOG.md
<ide> ## Rails 4.0.0 (unreleased) ##
<ide>
<add>* Fix input name when `:multiple => true` and `:index` are set.
<add>
<add> Before:
<add>
<add> check_box("post", "comment_ids", { :multiple => true, :index => "foo" }, 1)
<add> #=> <input name=\"post[foo][comment_ids]\" type=\"hidden\" value=\"0\" /><input id=\"post_foo_comment_ids_1\" name=\"post[foo][comment_ids]\" type=\"checkbox\" value=\"1\" />
<add>
<add> After:
<add>
<add> check_box("post", "comment_ids", { :multiple => true, :index => "foo" }, 1)
<add> #=> <input name=\"post[foo][comment_ids][]\" type=\"hidden\" value=\"0\" /><input id=\"post_foo_comment_ids_1\" name=\"post[foo][comment_ids][]\" type=\"checkbox\" value=\"1\" />
<add>
<add> Fix #8108
<add>
<add> *Daniel Fox, Grant Hutchins & Trace Wax*
<add>
<ide> * Clear url helpers when reloading routes.
<ide>
<ide> *Santiago Pastorino* | 1 |
PHP | PHP | unify database chunk methods, and add each methods | 55259e5178a61dc3393df33a6dd4d8bcbf2c3e59 | <ide><path>src/Illuminate/Database/Eloquent/Builder.php
<ide> public function value($column)
<ide> *
<ide> * @param int $count
<ide> * @param callable $callback
<del> * @return void
<add> * @return bool
<ide> */
<ide> public function chunk($count, callable $callback)
<ide> {
<ide> public function chunk($count, callable $callback)
<ide> // developer take care of everything within the callback, which allows us to
<ide> // keep the memory low for spinning through large result sets for working.
<ide> if (call_user_func($callback, $results) === false) {
<del> break;
<add> return false;
<ide> }
<ide>
<ide> $page++;
<ide>
<ide> $results = $this->forPage($page, $count)->get();
<ide> }
<add>
<add> return true;
<add> }
<add>
<add> /**
<add> * Execute a callback over each item.
<add> *
<add> * We're also saving memory by chunking the results into memory.
<add> *
<add> * @param callable $callback
<add> * @param int $count
<add> * @return bool
<add> */
<add> public function each(callable $callback, $count = 1000)
<add> {
<add> return $this->chunk($count, function ($results) use ($callback) {
<add> foreach ($results as $key => $value) {
<add> if ($callback($item, $key) === false) {
<add> return false;
<add> }
<add> }
<add> });
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php
<ide> public function simplePaginate($perPage = null, $columns = ['*'])
<ide> *
<ide> * @param int $count
<ide> * @param callable $callback
<del> * @return void
<add> * @return bool
<ide> */
<ide> public function chunk($count, callable $callback)
<ide> {
<ide> $this->query->addSelect($this->getSelectColumns());
<ide>
<del> $this->query->chunk($count, function ($results) use ($callback) {
<add> return $this->query->chunk($count, function ($results) use ($callback) {
<ide> $this->hydratePivotRelation($results->all());
<ide>
<del> call_user_func($callback, $results);
<add> return $callback($results);
<ide> });
<ide> }
<ide>
<ide><path>src/Illuminate/Database/Query/Builder.php
<ide> public function chunk($count, callable $callback)
<ide> return true;
<ide> }
<ide>
<add> /**
<add> * Execute a callback over each item.
<add> *
<add> * We're also saving memory by chunking the results into memory.
<add> *
<add> * @param callable $callback
<add> * @param int $count
<add> * @return bool
<add> */
<add> public function each(callable $callback, $count = 1000)
<add> {
<add> return $this->chunk($count, function ($results) use ($callback) {
<add> foreach ($results as $key => $value) {
<add> if ($callback($item, $key) === false) {
<add> return false;
<add> }
<add> }
<add> });
<add> }
<add>
<ide> /**
<ide> * Get an array with the values of a given column.
<ide> * | 3 |
Text | Text | correct 404 link for object detection tutorial | acbd8837870e0ed87d015a76096d30a6e69135e4 | <ide><path>research/object_detection/g3doc/running_notebook.md
<ide> jupyter notebook
<ide> ```
<ide>
<ide> The notebook should open in your favorite web browser. Click the
<del>[`object_detection_tutorial.ipynb`](../object_detection_tutorial.ipynb) link to
<add>[`object_detection_tutorial.ipynb`](../colab_tutorials/object_detection_tutorial.ipynb) link to
<ide> open the demo. | 1 |
Python | Python | add default name and lang to meta | 74c2c6a58cabdb31b77df3b24f6068355d9738bb | <ide><path>spacy/cli/train.py
<ide> def train(cmd, lang, output_dir, train_data, dev_data, n_iter=10, n_sents=0,
<ide> if not isinstance(meta, dict):
<ide> prints("Expected dict but got: {}".format(type(meta)),
<ide> title="Not a valid meta.json format", exits=1)
<add> meta.setdefault('lang', lang)
<add> meta.setdefault('name', 'unnamed')
<ide>
<ide> pipeline = ['tagger', 'parser', 'ner']
<ide> if no_tagger and 'tagger' in pipeline: pipeline.remove('tagger') | 1 |
PHP | PHP | increase coverage by covering another failure case | 15638b1a2aa3e8d6ea1fdebac60baef6b63fa20b | <ide><path>tests/TestCase/ORM/Association/BelongsToManyTest.php
<ide> public function emptyProvider()
<ide> ];
<ide> }
<ide>
<add> /**
<add> * Test that saveAssociated() fails on non-empty, non-iterable value
<add> *
<add> * @expectedException InvalidArgumentException
<add> * @expectedExceptionMessage Could not save tags, it cannot be traversed
<add> * @return void
<add> */
<add> public function testSaveAssociatedNotEmptyNotIterable()
<add> {
<add> $articles = TableRegistry::get('Articles');
<add> $assoc = $articles->belongsToMany('Tags', [
<add> 'saveStrategy' => BelongsToMany::SAVE_APPEND,
<add> 'joinTable' => 'articles_tags',
<add> ]);
<add> $entity = new Entity([
<add> 'id' => 1,
<add> 'tags' => 'oh noes',
<add> ], ['markNew' => true]);
<add>
<add> $assoc->saveAssociated($entity);
<add> }
<add>
<ide> /**
<ide> * Test that saving an empty set on create works.
<ide> * | 1 |
Python | Python | persist tags params in pagination | f878ec6c599a089a6d7516b7a66eed693f0c9037 | <ide><path>airflow/www/utils.py
<ide> def should_hide_value_for_key(key_name):
<ide>
<ide> def get_params(**kwargs):
<ide> """Return URL-encoded params"""
<del> return urlencode({d: v for d, v in kwargs.items() if v is not None})
<add> return urlencode({d: v for d, v in kwargs.items() if v is not None}, True)
<ide>
<ide>
<del>def generate_pages(current_page, num_of_pages, search=None, status=None, window=7):
<add>def generate_pages(current_page, num_of_pages, search=None, status=None, tags=None, window=7):
<ide> """
<ide> Generates the HTML for a paging component using a similar logic to the paging
<ide> auto-generated by Flask managed views. The paging component defines a number of
<ide> def generate_pages(current_page, num_of_pages, search=None, status=None, window=
<ide> current one in the middle of the pager component. When in the last pages,
<ide> the pages won't scroll and just keep moving until the last page. Pager also contains
<ide> <first, previous, ..., next, last> pages.
<del> This component takes into account custom parameters such as search and status,
<add> This component takes into account custom parameters such as search, status, and tags
<ide> which could be added to the pages link in order to maintain the state between
<ide> client and server. It also allows to make a bookmark on a specific paging state.
<ide>
<ide> :param current_page: the current page number, 0-indexed
<ide> :param num_of_pages: the total number of pages
<ide> :param search: the search query string, if any
<ide> :param status: 'all', 'active', or 'paused'
<add> :param tags: array of strings of the current filtered tags
<ide> :param window: the number of pages to be shown in the paging component (7 default)
<ide> :return: the HTML string of the paging component
<ide> """
<ide> def generate_pages(current_page, num_of_pages, search=None, status=None, window=
<ide>
<ide> is_disabled = 'disabled' if current_page <= 0 else ''
<ide>
<del> first_node_link = void_link if is_disabled else f'?{get_params(page=0, search=search, status=status)}'
<add> first_node_link = (
<add> void_link if is_disabled else f'?{get_params(page=0, search=search, status=status, tags=tags)}'
<add> )
<ide> output.append(
<ide> first_node.format(
<ide> href_link=first_node_link,
<ide> def generate_pages(current_page, num_of_pages, search=None, status=None, window=
<ide>
<ide> page_link = void_link
<ide> if current_page > 0:
<del> page_link = f'?{get_params(page=current_page - 1, search=search, status=status)}'
<add> page_link = f'?{get_params(page=current_page - 1, search=search, status=status, tags=tags)}'
<ide>
<ide> output.append(previous_node.format(href_link=page_link, disabled=is_disabled)) # noqa
<ide>
<ide> def is_current(current, page): # noqa
<ide> 'is_active': 'active' if is_current(current_page, page) else '',
<ide> 'href_link': void_link
<ide> if is_current(current_page, page)
<del> else f'?{get_params(page=page, search=search, status=status)}',
<add> else f'?{get_params(page=page, search=search, status=status, tags=tags)}',
<ide> 'page_num': page + 1,
<ide> }
<ide> output.append(page_node.format(**vals)) # noqa
<ide> def is_current(current, page): # noqa
<ide> page_link = (
<ide> void_link
<ide> if current_page >= num_of_pages - 1
<del> else f'?{get_params(page=current_page + 1, search=search, status=status)}'
<add> else f'?{get_params(page=current_page + 1, search=search, status=status, tags=tags)}'
<ide> )
<ide>
<ide> output.append(next_node.format(href_link=page_link, disabled=is_disabled)) # noqa
<ide>
<ide> last_node_link = (
<del> void_link if is_disabled else f'?{get_params(page=last_page, search=search, status=status)}'
<add> void_link
<add> if is_disabled
<add> else f'?{get_params(page=last_page, search=search, status=status, tags=tags)}'
<ide> )
<ide> output.append(
<ide> last_node.format(
<ide><path>airflow/www/views.py
<ide> def index(self):
<ide> num_of_pages,
<ide> search=escape(arg_search_query) if arg_search_query else None,
<ide> status=arg_status_filter if arg_status_filter else None,
<add> tags=arg_tags_filter if arg_tags_filter else None,
<ide> ),
<ide> num_runs=num_runs,
<ide> tags=tags,
<ide><path>tests/www/test_utils.py
<ide> def test_params_none_and_zero(self):
<ide> assert ['a=0', 'c=true'] == pairs
<ide>
<ide> def test_params_all(self):
<del> query = utils.get_params(status='active', page=3, search='bash_')
<del> assert {'page': ['3'], 'search': ['bash_'], 'status': ['active']} == parse_qs(query)
<add> query = utils.get_params(tags=['tag1', 'tag2'], status='active', page=3, search='bash_')
<add> assert {
<add> 'tags': ['tag1', 'tag2'],
<add> 'page': ['3'],
<add> 'search': ['bash_'],
<add> 'status': ['active'],
<add> } == parse_qs(query)
<ide>
<ide> def test_params_escape(self):
<ide> assert 'search=%27%3E%22%2F%3E%3Cimg+src%3Dx+onerror%3Dalert%281%29%3E' == utils.get_params( | 3 |
Text | Text | add inspiration & thanks | df17224af6859c34515e47993b897d4f9d41062f | <ide><path>README.md
<ide> function (state, action) {
<ide> ```
<ide>
<ide> [Read more](https://github.com/sebmarkbage/ecmascript-rest-spread) about the spread properties ES7 proposal.
<add>
<add>## Inspiration and Thanks
<add>
<add>* [Webpack Hot Module Replacement](https://github.com/webpack/docs/wiki/hot-module-replacement-with-webpack)
<add>* [The Elm Architecture](https://github.com/evancz/elm-architecture-tutorial)
<add>* [Turning the database inside-out](http://blog.confluent.io/2015/03/04/turning-the-database-inside-out-with-apache-samza/)
<add>* [Developing ClojureScript with Figwheel](http://www.youtube.com/watch?v=j-kj2qwJa_E)
<add>* [Flummox](https://github.com/acdlite/flummox)
<add>* [disto](https://github.com/threepointone/disto)
<add>
<add>Special thanks to [Jamie Paton](http://jdpaton.github.io/) for handing over the `redux` NPM package name. | 1 |
Javascript | Javascript | add rfc232 variants | 81568674fdbfdf26221708b94c08340f97279c9a | <ide><path>blueprints/instance-initializer-test/qunit-rfc-232-files/tests/unit/instance-initializers/__name__-test.js
<add>import Application from '@ember/application';
<add>import { run } from '@ember/runloop';
<add>
<add>import { initialize } from '<%= dasherizedModulePrefix %>/initializers/<%= dasherizedModuleName %>';
<add>import { module, test } from 'qunit';
<add>import { setupTest } from 'ember-qunit';
<add>import destroyApp from '../../helpers/destroy-app';
<add>
<add>module('<%= friendlyTestName %>', function(hooks) {
<add> setupTest(hooks);
<add>
<add> hooks.beforeEach(function() {
<add> run(() => {
<add> this.application = Application.create();
<add> this.application.deferReadiness();
<add> });
<add> });
<add> hooks.afterEach(function() {
<add> destroyApp(this.application);
<add> });
<add>
<add> // Replace this with your real tests.
<add> test('it works', function(assert) {
<add> initialize(this.application);
<add>
<add> // you would normally confirm the results of the initializer here
<add> assert.ok(true);
<add> });
<add>});
<ide><path>node-tests/blueprints/instance-initializer-test-test.js
<ide> const modifyPackages = blueprintHelpers.modifyPackages;
<ide> const chai = require('ember-cli-blueprint-test-helpers/chai');
<ide> const expect = chai.expect;
<ide>
<add>const generateFakePackageManifest = require('../helpers/generate-fake-package-manifest');
<ide> const fixture = require('../helpers/fixture');
<ide>
<ide> describe('Blueprint: instance-initializer-test', function() {
<ide> describe('Blueprint: instance-initializer-test', function() {
<ide> });
<ide> });
<ide>
<add> describe('with ember-cli-qunit@4.1.1', function() {
<add> beforeEach(function() {
<add> generateFakePackageManifest('ember-cli-qunit', '4.1.1');
<add> });
<add>
<add> it('instance-initializer-test foo', function() {
<add> return emberGenerateDestroy(['instance-initializer-test', 'foo'], _file => {
<add> expect(_file('tests/unit/instance-initializers/foo-test.js'))
<add> .to.equal(fixture('instance-initializer-test/rfc232.js'));
<add> });
<add> });
<add> });
<add>
<ide> describe('with ember-cli-mocha', function() {
<ide> beforeEach(function() {
<ide> modifyPackages([
<ide><path>node-tests/fixtures/instance-initializer-test/rfc232.js
<add>import Application from '@ember/application';
<add>import { run } from '@ember/runloop';
<add>
<add>import { initialize } from 'my-app/initializers/foo';
<add>import { module, test } from 'qunit';
<add>import { setupTest } from 'ember-qunit';
<add>import destroyApp from '../../helpers/destroy-app';
<add>
<add>module('Unit | Instance Initializer | foo', function(hooks) {
<add> setupTest(hooks);
<add>
<add> hooks.beforeEach(function() {
<add> run(() => {
<add> this.application = Application.create();
<add> this.application.deferReadiness();
<add> });
<add> });
<add> hooks.afterEach(function() {
<add> destroyApp(this.application);
<add> });
<add>
<add> // Replace this with your real tests.
<add> test('it works', function(assert) {
<add> initialize(this.application);
<add>
<add> // you would normally confirm the results of the initializer here
<add> assert.ok(true);
<add> });
<add>}); | 3 |
Mixed | Ruby | take hash with options inside array in #url_for | d04c4fac3bb6f75ba15704dd03faeb5f2d7033f7 | <ide><path>actionpack/CHANGELOG.md
<add>* Take a hash with options inside array in #url_for
<add>
<add> Example:
<add>
<add> url_for [:new, :admin, :post, { param: 'value' }]
<add> # => http://example.com/admin/posts/new?params=value
<add>
<add> *Andrey Ognevsky*
<add>
<ide> * Add `session#fetch` method
<ide>
<ide> fetch behaves similarly to [Hash#fetch](http://www.ruby-doc.org/core-1.9.3/Hash.html#method-i-fetch),
<ide><path>actionpack/lib/action_dispatch/routing/url_for.rb
<ide> def url_for(options = nil)
<ide> _routes.url_for(options.symbolize_keys.reverse_merge!(url_options))
<ide> when String
<ide> options
<add> when Array
<add> polymorphic_url(options, options.extract_options!)
<ide> else
<ide> polymorphic_url(options)
<ide> end
<ide><path>actionpack/test/controller/url_for_test.rb
<ide> def test_false_url_params_are_included_in_query
<ide> assert_equal("/c/a?show=false", W.new.url_for(:only_path => true, :controller => 'c', :action => 'a', :show => false))
<ide> end
<ide>
<add> def test_url_generation_with_array_and_hash
<add> with_routing do |set|
<add> set.draw do
<add> namespace :admin do
<add> resources :posts
<add> end
<add> end
<add>
<add> kls = Class.new { include set.url_helpers }
<add> kls.default_url_options[:host] = 'www.basecamphq.com'
<add>
<add> controller = kls.new
<add> assert_equal("http://www.basecamphq.com/admin/posts/new?param=value",
<add> controller.send(:url_for, [:new, :admin, :post, { param: 'value' }])
<add> )
<add> end
<add> end
<add>
<ide> private
<ide> def extract_params(url)
<ide> url.split('?', 2).last.split('&').sort
<ide><path>actionview/lib/action_view/routing_url_for.rb
<ide> def url_for(options = nil)
<ide> super
<ide> when :back
<ide> _back_url
<add> when Array
<add> polymorphic_path(options, options.extract_options!)
<ide> else
<ide> polymorphic_path(options)
<ide> end | 4 |
Python | Python | fix index error, to support non-square kernels | d4a6670ade6ebd007b7974f85d70c4c879ba99d6 | <ide><path>research/slim/nets/mobilenet_v1.py
<ide> def _fixed_padding(inputs, kernel_size, rate=1):
<ide> input, either intact (if kernel_size == 1) or padded (if kernel_size > 1).
<ide> """
<ide> kernel_size_effective = [kernel_size[0] + (kernel_size[0] - 1) * (rate - 1),
<del> kernel_size[0] + (kernel_size[0] - 1) * (rate - 1)]
<add> kernel_size[1] + (kernel_size[1] - 1) * (rate - 1)]
<ide> pad_total = [kernel_size_effective[0] - 1, kernel_size_effective[1] - 1]
<ide> pad_beg = [pad_total[0] // 2, pad_total[1] // 2]
<ide> pad_end = [pad_total[0] - pad_beg[0], pad_total[1] - pad_beg[1]] | 1 |
Python | Python | fix some fatal pyflakes issues | f6ae27e631e6f2408441f92164b2f0be66dd1a6e | <ide><path>libcloud/common/base.py
<ide> def makefile(self, *args, **kwargs):
<ide>
<ide> return cls(b(self.s))
<ide> rr = r
<del> original_data = body
<ide> headers = lowercase_keys(dict(r.getheaders()))
<ide>
<ide> encoding = headers.get('content-encoding', None)
<ide><path>libcloud/common/gandi.py
<ide>
<ide> import time
<ide> import hashlib
<add>import sys
<ide>
<ide> from libcloud.utils.py3 import xmlrpclib
<ide> from libcloud.utils.py3 import b
<ide><path>libcloud/compute/drivers/softlayer.py
<ide> Softlayer driver
<ide> """
<ide>
<add>import sys
<ide> import time
<ide>
<ide> import libcloud
<ide><path>libcloud/loadbalancer/drivers/gogrid.py
<ide> # See the License for the specific language governing permissions and
<ide> # limitations under the License.
<ide>
<add>import sys
<ide> import time
<add>
<ide> from libcloud.utils.py3 import httplib
<ide>
<ide> try:
<ide> def _update_balancer(self, params):
<ide> if "Update already pending" in str(e):
<ide> raise LibcloudLBImmutableError("Balancer is immutable", GoGridLBDriver)
<ide>
<del> raise LibcloudError(value='Exception: %s' % str(err), driver=self)
<add> raise LibcloudError(value='Exception: %s' % str(e), driver=self)
<ide>
<ide> def _members_to_params(self, members):
<ide> """ | 4 |
Javascript | Javascript | fix language type | 816350374b203f24d47b87b98285a243c810a603 | <ide><path>packages/ember-handlebars/lib/controls/checkbox.js
<ide> var set = Ember.set, get = Ember.get;
<ide> You can add a `label` tag yourself in the template where the `Ember.Checkbox`
<ide> is being used.
<ide>
<del> ```html
<add> ```handlebars
<ide> <label>
<ide> {{view Ember.Checkbox classNames="applicaton-specific-checkbox"}}
<ide> Some Title | 1 |
Python | Python | remove is_base_form from french lemmatizer | 923affd091dac4c1a7e11168f7c8f1f05dcc224e | <ide><path>spacy/lang/fr/lemmatizer.py
<ide> def __call__(self, string, univ_pos, morphology=None):
<ide> univ_pos = "sconj"
<ide> else:
<ide> return [self.lookup(string)]
<del> # See Issue #435 for example of where this logic is requied.
<del> if self.is_base_form(univ_pos, morphology):
<del> return list(set([string.lower()]))
<ide> index_table = self.lookups.get_table("lemma_index", {})
<ide> exc_table = self.lookups.get_table("lemma_exc", {})
<ide> rules_table = self.lookups.get_table("lemma_rules", {})
<ide> def __call__(self, string, univ_pos, morphology=None):
<ide> )
<ide> return lemmas
<ide>
<del> def is_base_form(self, univ_pos, morphology=None):
<del> """
<del> Check whether we're dealing with an uninflected paradigm, so we can
<del> avoid lemmatization entirely.
<del> """
<del> morphology = {} if morphology is None else morphology
<del> others = [
<del> key
<del> for key in morphology
<del> if key not in (POS, "Number", "POS", "VerbForm", "Tense")
<del> ]
<del> if univ_pos == "noun" and morphology.get("Number") == "sing":
<del> return True
<del> elif univ_pos == "verb" and morphology.get("VerbForm") == "inf":
<del> return True
<del> # This maps 'VBP' to base form -- probably just need 'IS_BASE'
<del> # morphology
<del> elif univ_pos == "verb" and (
<del> morphology.get("VerbForm") == "fin"
<del> and morphology.get("Tense") == "pres"
<del> and morphology.get("Number") is None
<del> and not others
<del> ):
<del> return True
<del> elif univ_pos == "adj" and morphology.get("Degree") == "pos":
<del> return True
<del> elif VerbForm_inf in morphology:
<del> return True
<del> elif VerbForm_none in morphology:
<del> return True
<del> elif Number_sing in morphology:
<del> return True
<del> elif Degree_pos in morphology:
<del> return True
<del> else:
<del> return False
<del>
<ide> def noun(self, string, morphology=None):
<ide> return self(string, "noun", morphology)
<ide> | 1 |
Text | Text | correct the file name to preprocessor | ade9645ae8d18e335cf7221b79d830acd7b6768a | <ide><path>docs/Testing.md
<ide> Note: In order to run your own tests, you will have to first follow the Getting
<ide> },
<ide> ...
<ide> "jest": {
<del> "scriptPreprocessor": "node_modules/react-native/jestSupport/scriptPreprocess.js",
<add> "scriptPreprocessor": "node_modules/react-native/jestSupport/preprocessor.js",
<ide> "setupEnvScriptFile": "node_modules/react-native/jestSupport/env.js",
<ide> "testPathIgnorePatterns": [
<ide> "/node_modules/", | 1 |
Text | Text | remove repl.it links spanish challenge articles | b5e5f116745d6a018c6882a4f8ea92d02ede4e72 | <ide><path>guide/spanish/certifications/coding-interview-prep/algorithms/find-the-symmetric-difference/index.md
<ide> A = {1, 2, 3}
<ide>
<ide> ```](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce)
<ide>
<del> [](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) [Ejecutar código](https://repl.it/C4II/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> A = {1, 2, 3}
<ide> sym([1, 2, 3], [5, 2, 1, 4]);
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLoc/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> A = {1, 2, 3}
<ide> sym([1, 2, 3], [5, 2, 1, 4]);
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/@ashenm/Symmetric-Difference)
<ide>
<ide> ### Explicación del código:
<ide>
<ide><path>guide/spanish/certifications/coding-interview-prep/algorithms/implement-bubble-sort/index.md
<ide> function swap(a, b, arr){
<ide>
<ide> `js function bubbleSort(array) { for (let i = 0; i < array.length; i++){ for (let j = 0; j < array.length-1-i; j++){ if (array[j] > array[j+1]) [array[j], array[j+1]] = [array[j+1], array[j]]; // Using ES6 array destructuring to swap } } return array; }`
<ide>
<del>* [Ejecutar código](https://repl.it/@ezioda004/Bubble-Sort)
<ide>
<ide> ### Referencias:
<ide>
<ide><path>guide/spanish/certifications/coding-interview-prep/algorithms/implement-insertion-sort/index.md
<ide> function insertionSort(array) {
<ide> }
<ide> ```
<ide>
<del>* [Ejecutar código](https://repl.it/@ezioda004/Insertion-Sort)
<ide>
<ide> ### Referencias:
<ide>
<ide><path>guide/spanish/certifications/coding-interview-prep/algorithms/implement-merge-sort/index.md
<ide> localeTitle: Implementar Merge Sort
<ide> }
<ide> ```
<ide>
<del>* [Ejecutar código](https://repl.it/@ezioda004/Merge-Sort)
<ide>
<ide> ### Referencias:
<ide>
<ide><path>guide/spanish/certifications/coding-interview-prep/algorithms/implement-quick-sort/index.md
<ide> localeTitle: Implementar ordenación rápida
<ide> }
<ide> ```
<ide>
<del>* [Ejecutar código](https://repl.it/@ezioda004/Quick-Sort)
<ide>
<ide> ### Referencia:
<ide>
<ide><path>guide/spanish/certifications/coding-interview-prep/algorithms/inventory-update/index.md
<ide> Devuelve el inventario completado en orden alfabético.
<ide> updateInventory(curInv, newInv);
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLok/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> Devuelve el inventario completado en orden alfabético.
<ide> updateInventory(curInv, newInv);
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLol/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> Devuelve el inventario completado en orden alfabético.
<ide> updateInventory(curInv, newInv);
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/MQvv/latest)
<ide>
<ide> ### Explicación del código:
<ide>
<ide><path>guide/spanish/certifications/coding-interview-prep/algorithms/no-repeats-please/index.md
<ide> function permAlone(str) {
<ide> permAlone('aab');
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLop/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide><path>guide/spanish/certifications/coding-interview-prep/project-euler/problem-1-multiples-of-3-and-5/index.md
<ide> function multiplesOf3and5(number) {
<ide> }
<ide> ```
<ide>
<del>* [Ejecutar código](https://repl.it/@ezioda004/Project-Euler-Problem-1-Multiples-of-3-and-5)
<ide>
<ide> ### Referencia:
<ide>
<ide><path>guide/spanish/certifications/coding-interview-prep/project-euler/problem-2-even-fibonacci-numbers/index.md
<ide> function fiboEvenSum(n) {
<ide> }
<ide> ```
<ide>
<del>* [Ejecutar código](https://repl.it/@ezioda004/Project-Euler-Problem-2-Even-Fibonacci-Numbers)
<ide>
<ide> ### Referencias:
<ide>
<ide><path>guide/spanish/certifications/coding-interview-prep/project-euler/problem-3-largest-prime-factor/index.md
<ide> function largestPrimeFactor(number) {
<ide> }
<ide> ```
<ide>
<del>* [Ejecutar código](https://repl.it/@ezioda004/Problem-3-Largest-prime-factor)
<ide>
<ide> ### Recursos:
<ide>
<ide><path>guide/spanish/certifications/coding-interview-prep/project-euler/problem-4-largest-palindrome-product/index.md
<ide> function largestPalindromeProduct(n) {
<ide> }
<ide> ```
<ide>
<del>* [Ejecutar código](https://repl.it/@ezioda004/Problem-4-Largest-palindrome-product)
<ide>
<ide> ### Referencias:
<ide>
<ide><path>guide/spanish/certifications/coding-interview-prep/project-euler/problem-5-smallest-multiple/index.md
<ide> localeTitle: Múltiplo más pequeño
<ide> }
<ide> ```
<ide>
<del>* [Ejecutar código](https://repl.it/@ezioda004/Problem-5-Smallest-multiple)
<ide>
<ide> ### Referencias:
<ide>
<ide><path>guide/spanish/certifications/coding-interview-prep/project-euler/problem-6-sum-square-difference/index.md
<ide> function sumSquareDifference(n) {
<ide> }
<ide> ```
<ide>
<del>* [Ejecutar código](https://repl.it/@ezioda004/Problem-6-Sum-square-difference)
<ide>
<ide> ### Referencias:
<ide>
<ide><path>guide/spanish/certifications/coding-interview-prep/project-euler/problem-7-10001st-prime/index.md
<ide> function nthPrime(n) {
<ide> }
<ide> ```
<ide>
<del>\- [Ejecutar código](https://repl.it/@ezioda004/Project-Euler-Problem-7-10001st-prime)
<ide>
<ide> ### Referencias:
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/basic-algorithm-scripting/boo-who/index.md
<ide> Este programa es muy simple, el truco es entender qué es un primitivo booleano.
<ide> booWho(null);
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLnK/0)
<ide>
<ide> # Explicación del código:
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/basic-algorithm-scripting/chunky-monkey/index.md
<ide> Finalmente, necesitamos un método para hacer la división real y podemos usar `
<ide> }
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLjU/24)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> Finalmente, necesitamos un método para hacer la división real y podemos usar `
<ide> }
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/Cj9x/3)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> Finalmente, necesitamos un método para hacer la división real y podemos usar `
<ide> chunkArrayInGroups(["a", "b", "c", "d"], 2);
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLjU/26)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> Finalmente, necesitamos un método para hacer la división real y podemos usar `
<ide> }
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLjU/579)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> Finalmente, necesitamos un método para hacer la división real y podemos usar `
<ide> }
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLjU/579)
<ide>
<ide> ### Explicación del código:
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/basic-algorithm-scripting/confirm-the-ending/index.md
<ide> function confirmEnding(str, target) {
<ide> confirmEnding("He has to give me a new name", "name");
<ide> ```
<ide>
<del>#### 🚀 [Ejecutar Código](https://repl.it/repls/SardonicRoundAfkgaming)
<ide>
<ide> # Explicación del código:
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/basic-algorithm-scripting/factorialize-a-number/index.md
<ide> function factorialize(num) {
<ide> factorialize(5);
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLjU/1)
<ide>
<ide> ## Explicación del código:
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/basic-algorithm-scripting/falsy-bouncer/index.md
<ide> function bouncer(arr) {
<ide> }
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLjU/32)
<ide>
<ide> ### Explicación del código:
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/basic-algorithm-scripting/find-the-longest-word-in-a-string/index.md
<ide> function findLongestWordLength(str) {
<ide> }
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLjU/5)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> function findLongestWordLength(s) {
<ide> }
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLjU/6)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> function findLongestWordLength(str) {
<ide> }
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLjU/7)
<ide>
<ide> ### Explicación del código:
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/basic-algorithm-scripting/mutations/index.md
<ide> function mutation(arr) {
<ide> }
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLjU/30)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> function mutation(arr) {
<ide> }
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLjU/31)
<ide>
<ide> ### Explicación del código:
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/basic-algorithm-scripting/repeat-a-string-repeat-a-string/index.md
<ide> function repeatStringNumTimes(str, num) {
<ide> }
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLjU/19)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> function repeatStringNumTimes(str, num) {
<ide> }
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLjU/21)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> function repeatStringNumTimes(str, num) {
<ide> repeatStringNumTimes("abc", 3);
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLjU/85)
<ide>
<ide> ### Explicación del código:
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/basic-algorithm-scripting/return-largest-numbers-in-arrays/index.md
<ide> function largestOfFour(arr) {
<ide> }
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLjU/734)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> function largestOfFour(arr) {
<ide> }
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLjU/733)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> function largestOfFour(arr) {
<ide> }
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLjU/17)
<ide>
<ide> ### Explicación del código:
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/basic-algorithm-scripting/reverse-a-string/index.md
<ide> function reverseString(str) {
<ide> }
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLjU)
<ide>
<ide> ### Explicación del código:
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/basic-algorithm-scripting/slice-and-splice/index.md
<ide> function frankenSplice(arr1, arr2, n) {
<ide> }
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLjU)
<ide>
<ide> ### Explicación del código:
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/basic-algorithm-scripting/title-case-a-sentence/index.md
<ide> String.prototype.replaceAt = function(index, character) {
<ide> }
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLjU/8)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> function titleCase(str) {
<ide> titleCase("I'm a little tea pot");
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLjU/9)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> function titleCase(str) {
<ide> }
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLjU/14)
<ide>
<ide> ### Explicación del código:
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/basic-algorithm-scripting/truncate-a-string/index.md
<ide> function truncateString(str, num) {
<ide> }
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLjU/55)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> function truncateString(str, num) {
<ide> }
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLjU/54)
<ide>
<ide> ### Explicación del código:
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/basic-algorithm-scripting/where-do-i-belong/index.md
<ide> function getIndexToIns(arr, num) {
<ide> }
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLjU/36)
<ide>
<ide> ## Explicación del código:
<ide>
<ide> function getIndexToIns(arr, num) {
<ide> getIndexToIns([40, 60], 50);
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLjU/2547)
<ide>
<ide> ## Explicación del código:
<ide>
<ide> function getIndexToIns(arr, num) {
<ide> getIndexToIns([40, 60], 50);
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLjU/4135)
<ide>
<ide> ## Explicación del código:
<ide>
<ide> function getIndexToIns(arr, num) {
<ide> }
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/EB10/1)
<ide>
<ide> ## Explicación del código:
<ide>
<ide> function getIndexToIns(arr, num) {
<ide> getIndexToIns([40, 60], 500);
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLjU/63)
<ide>
<ide> ## Explicación del código:
<ide>
<ide> function getIndexToIns(arr, num) {
<ide> getIndexToIns([1,3,4],2);
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/IUJE/0)
<ide>
<ide> ## Explicación del código:
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/basic-javascript/chaining-if-else-statements/index.md
<ide> function testSize(num) {
<ide> }
<ide> ```
<ide>
<del>· Ejecutar código en [repl.it](https://repl.it/@AdrianSkar/Basic-JS-Chaining-ifelse-statements)
<ide>
<ide> ### Explicación del código
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-equality-operator/index.md
<ide> function testEqual(val) {
<ide> testEqual(10);
<ide> ```
<ide>
<del>· [Ejecutar código en repl.it](https://repl.it/@AdrianSkar/Basic-JS-Equality-operator)
<ide>
<ide> ### Explicación del código
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/basic-javascript/comparisons-with-the-logical-and-operator/index.md
<ide> function testLogicalAnd(val) {
<ide> testLogicalAnd(10);
<ide> ```
<ide>
<del>· [Ejecutar código en repl.it](https://repl.it/@AdrianSkar/Basic-JS-Comparison-with-the-and-operator)
<del>
<ide> ### Explicación del código
<ide>
<ide> La función primero evalúa `if` la condición `val <= 50` evalúa como `true` conversión de `val` en un número si es necesario, luego hace lo mismo con `val >=25` debido al operador lógico AND ( `&&` ); Si ambos devuelven verdadero, se ejecuta la instrucción de `return "Yes"` .
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/basic-javascript/counting-cards/index.md
<ide> function cc(card) {
<ide> }
<ide> ```
<ide>
<del>· Ejecutar código en [repl.it.](https://repl.it/@AdrianSkar/Basic-JS-Counting-cards)
<ide>
<ide> ### Explicación del código
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/basic-javascript/golf-code/index.md
<ide> var names = ["Hole-in-one!", "Eagle", "Birdie", "Par", "Bogey", "Double Bogey",
<ide> golfScore(5, 4);
<ide> ```
<ide>
<del>· Ejecutar en [repl.it](https://repl.it/@AdrianSkar/Basic-JS-Golf-code)
<ide>
<ide> \## explicación del código Como ya tenemos una matriz definida en los `names` las variables, podemos aprovecharla y utilizarla para nuestras declaraciones de devolución usando índices (por ejemplo: `names[0] is the first one` ). De esa manera, si alguna vez necesita cambiar un resultado específico, no tendría que buscarlo dentro de la función, estaría al principio, en su matriz.
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/basic-javascript/introducing-else-if-statements/index.md
<ide> function testElseIf(val) {
<ide> testElseIf(7);
<ide> ```
<ide>
<del>: cohete: [Ejecutar código](https://repl.it/@RyanPisuena/GoldenWorriedRuntime) ## explicación del código La estructura de un **flujo lógico else-if** es una declaración inicial `if` , una instrucción `if-else` y una instrucción `else` final.
<add>## explicación del código La estructura de un **flujo lógico else-if** es una declaración inicial `if` , una instrucción `if-else` y una instrucción `else` final.
<ide>
<ide> ### Recursos
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/basic-javascript/introducing-else-statements/index.md
<ide> function testElse(val) {
<ide> testElse(4);
<ide> ```
<ide>
<del>· [Ejecutar código en repl.it](https://repl.it/@AdrianSkar/Introducing-else-statements)
<ide>
<ide> ### Explicación del código
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/basic-javascript/multiple-identical-options-in-switch-statements/index.md
<ide> function sequentialSizes(val) {
<ide> sequentialSizes(1);
<ide> ```
<ide>
<del>· Ejecutar código en [repl.it.](https://repl.it/@AdrianSkar/Basic-JS-Multiple-opts-in-switch)
<ide>
<ide> ### Explicación del código
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/basic-javascript/record-collection/index.md
<ide> function updateRecords(id, prop, value) {
<ide> }
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/C2AZ/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/basic-javascript/returning-boolean-values-from-functions/index.md
<ide> function isLess(a, b) {
<ide> isLess(10, 15);
<ide> ```
<ide>
<del>Ejecute el código en [repl.it.](https://repl.it/@AdrianSkar/Basic-Js-Returning-boolean-from-function)
<del>
<ide> ### Recursos
<ide>
<ide> * ["Operador menor o igual (<=)" - _MDN Referencia de Javascript_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Less_than_or_equal_operator_(%3C))
<ide>\ No newline at end of file
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/basic-javascript/selecting-from-many-options-with-switch-statements/index.md
<ide> function caseInSwitch(val) {
<ide> caseInSwitch(1);
<ide> ```
<ide>
<del>· Ejecutar código en [repl.it.](https://repl.it/@AdrianSkar/Basic-JS-Switch-statements)
<ide>
<ide> ### Explicación del código
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/basic-javascript/using-objects-for-lookups/index.md
<ide> function phoneticLookup(val) {
<ide>
<ide> javascript resultado = búsqueda \[val\]; \`\` \`
<ide>
<del>· Ejecutar código en [repl.it.](https://repl.it/@AdrianSkar/Using-objects-for-lookups)
<ide>
<ide> ### Recursos
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/es6/set-default-parameters-for-your-functions/index.md
<ide> const increment = (function() {
<ide> console.log(increment(5)); // returns NaN
<ide> ```
<ide>
<del>: cohete: [Ejecutar código](https://repl.it/@RyanPisuena/PleasingFumblingThings)
<ide>
<ide> ## Explicación del Código
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/arguments-optional/index.md
<ide> En el caso de que solo se haya pasado un argumento, no se preocupe acerca de có
<ide> addTogether(2,3);
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLnz/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> En el caso de que solo se haya pasado un argumento, no se preocupe acerca de có
<ide> addTogether(2,3);
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLoA/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> En el caso de que solo se haya pasado un argumento, no se preocupe acerca de có
<ide> addTogether(2,3);
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLoB/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/binary-agents/index.md
<ide> Asegúrate de que cada vez que transcodifiques un carácter de binario a decimal
<ide> binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111");
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLnm/0)
<ide>
<ide> # Explicación del código:
<ide>
<ide> Asegúrate de que cada vez que transcodifiques un carácter de binario a decimal
<ide> binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111");
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLno/0)
<ide>
<ide> # Explicación del Código
<ide>
<ide> Asegúrate de que cada vez que transcodifiques un carácter de binario a decimal
<ide> binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111");
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLnp/0)
<ide>
<ide> # Explicación del Código
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/convert-html-entities/index.md
<ide> Explica la solución aquí y agrega cualquier enlace relevante.
<ide> * [arr.join ()](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/join)
<ide> * [declaración de cambio](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/switch)
<ide>
<del> [Ejecutar código](https://repl.it/CLnP/0)
<ide>
<ide> ##  Solución de código intermedio:
<ide> ```
<ide> function convertHTML(str) {
<ide> convertHTML("Dolce & Gabbana");
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLnQ/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> Explica la solución aquí y agrega cualquier enlace relevante.
<ide> convertHTML("Dolce & Gabbana");
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLnR/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/diff-two-arrays/index.md
<ide> La mejor manera de realizar la función de devolución de llamada es verificar s
<ide> diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLme/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> Lee los comentarios en el código.
<ide> diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CNYb/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> function diffArray(arr1, arr2) {
<ide> diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CNYU/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/dna-pairing/index.md
<ide> Este problema no implica reorganizar la entrada en diferentes combinaciones o pe
<ide> pairElement("GCG");
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLmz/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> Este problema no implica reorganizar la entrada en diferentes combinaciones o pe
<ide> pairElement("GCG");
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/repls/ThoroughSphericalComputeranimation)
<ide>
<ide> ## Explicación del código:
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/drop-it/index.md
<ide> function dropElements(arr, func) {
<ide> dropElements([1, 2, 3, 4], function(n) {return n >= 3;})
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLna/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> function dropElements(arr, func) {
<ide> dropElements([1, 2, 3, 4], function(n) {return n >= 3;});
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLnc/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> function dropElements(arr, func) {
<ide> dropElements([1, 2, 3, 4], function(n) {return n >= 3;});
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLnf/0)
<ide>
<ide> ### Explicación del Código
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/everything-be-true/index.md
<ide> function truthCheck(collection, pre) {
<ide> truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex");
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLnw/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> function truthCheck(collection, pre) {
<ide> truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex");
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLny/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> function truthCheck(collection, pre) {
<ide> truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex");
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/E2u6/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/make-a-person/index.md
<ide> var Person = function(firstAndLast) {
<ide> bob.getFullName();
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLov/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/map-the-debris/index.md
<ide> function orbitalPeriod(arr) {
<ide> orbitalPeriod([{name : "sputnik", avgAlt : 35873.5553}]);
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLow/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> function orbitalPeriod(arr) {
<ide> orbitalPeriod([{name : "sputnik", avgAlt : 35873.5553}]);
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLoy/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> function orbitalPeriod(arr) {
<ide> orbitalPeriod([{name : "sputnik", avgAlt : 35873.5553}]);
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLoz/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/missing-letters/index.md
<ide> function fearNotLetter(str) {
<ide> fearNotLetter("abce");
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLnD/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> function fearNotLetter(str) {
<ide> fearNotLetter("abce");
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLnE/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> function fearNotLetter(str) {
<ide> fearNotLetter("abce");
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLnG/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/pig-latin/index.md
<ide> function translatePigLatin(str) {
<ide> translatePigLatin("consonant");
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLmt/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> function translatePigLatin(str) {
<ide> translatePigLatin("consonant");
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLmw/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> function translatePigLatin(str) {
<ide> translatePigLatin("consonant");
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLmv/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/search-and-replace/index.md
<ide> function myReplace(str, before, after) {
<ide> myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLmo/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> function myReplace(str, before, after) {
<ide> myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLmp/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> function myReplace(str, before, after) {
<ide> myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLmq/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> function myReplace(str, before, after) {
<ide> }
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/@kr3at0/SearchAndReplace)
<ide>
<ide> ##  Solución alternativa de código avanzado 2:
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/seek-and-destroy/index.md
<ide> function destroyer(arr) {
<ide> }
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLjU/95)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> function destroyer(arr) {
<ide> }
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/Ck2m/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/smallest-common-multiple/index.md
<ide> function smallestCommons(arr) {
<ide> smallestCommons([1,5]);
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLn2/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> function smallestCommons(arr) {
<ide> smallestCommons([1,5]);
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLn4/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> function smallestCommons(arr) {
<ide> smallestCommons([1,5]);
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/MR9P/latest)
<ide>
<ide> ### Explicación del código:
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sorted-union/index.md
<ide> function uniteUnique(arr1, arr2, arr3) {
<ide> uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLnM/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> function uniteUnique(arr1, arr2, arr3) {
<ide> uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLnO/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> function uniteUnique() {
<ide> uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLnN/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> function uniteUnique() {
<ide> uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CcWk/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/spinal-tap-case/index.md
<ide> function spinalCase(str) {
<ide> spinalCase('This Is Spinal Tap');
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLnS/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> function spinalCase(str) {
<ide> spinalCase('This Is Spinal Tap');
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLnT/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> function spinalCase(str) {
<ide> }
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/EUZV)
<ide>
<ide> ### Explicación del código:
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/steamroller/index.md
<ide> function steamrollArray(arr) {
<ide> steamrollArray([1, [2], [3, [[4]]]]);
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLnh/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> function steamrollArray(arr) {
<ide> flattenArray([1, [2], [3, [[4]]]]);
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLni/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> function steamrollArray(arr) {
<ide> }
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CpDy/4)
<ide>
<ide> ### Explicación del código:
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-numbers-in-a-range/index.md
<ide> function sumAll(arr) {
<ide> sumAll([1, 4]);
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLm6/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> function sumAll(arr) {
<ide> }
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLm7/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> function sumAll(arr) {
<ide> sumAll([1, 4]);
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLm8/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-odd-fibonacci-numbers/index.md
<ide> function sumFibs(num) {
<ide> sumFibs(4);
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLnV/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> function sumFibs(num) {
<ide> sumFibs(4);
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/repls/ImpassionedFineConnection)
<ide>
<ide> ### Explicación del código:
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-primes/index.md
<ide> function sumPrimes(num) {
<ide> sumPrimes(10);
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLnZ/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> function sumPrimes(num) {
<ide> sumPrimes(10);
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLn0/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> function sumPrimes(num) {
<ide> sumPrimes(977);
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/DoOo/3)
<ide>
<ide> ### Explicación del código:
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/wherefore-art-thou/index.md
<ide> function whatIsInAName(collection, source) {
<ide> whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLmh/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> function whatIsInAName(collection, source) {
<ide> whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLmi/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> function whatIsInAName(collection, source) {
<ide> whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLmj/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/caesars-cipher/index.md
<ide> Deja cualquier cosa que no se interponga entre AZ como es.
<ide> }
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLjU/38)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> ALPHA KEY BASE ROTATED ROT13
<ide> * [Regex](https://forum.freecodecamp.com/t/regular-expressions-resources/15931)
<ide> * [Regex.test](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test)
<ide>
<del> [Ejecutar código](https://repl.it/CLjU/39)
<ide>
<ide> ##  Solución avanzada de código:
<ide> ```
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/cash-register/index.md
<ide> localeTitle: Caja registradora
<ide> checkCashRegister(19.50, 20.00, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.10], ["QUARTER", 4.25], ["ONE", 90.00], ["FIVE", 55.00], ["TEN", 20.00], ["TWENTY", 60.00], ["ONE HUNDRED", 100.00]]);
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/@scissorsneedfoo/cash-register-example)
<ide>
<ide> ### Explicación del código:
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/palindrome-checker/index.md
<ide> Los métodos `Array.prototype.split` y `Array.prototype.join` pueden ser de util
<ide> }
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLjU/2)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> Los métodos `Array.prototype.split` y `Array.prototype.join` pueden ser de util
<ide> }
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLjU/3)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> Los métodos `Array.prototype.split` y `Array.prototype.join` pueden ser de util
<ide> }
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLjU/4)
<ide>
<ide> ### Explicación del código:
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/roman-numeral-converter/index.md
<ide> var convertToRoman = function(num) {
<ide> convertToRoman(36);
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLmf/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> function convertToRoman(num) {
<ide> convertToRoman(97);
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/C1YV)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> function convertToRoman(num) {
<ide> convertToRoman(36);
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/C1YV)
<ide>
<ide> ### Explicación del código:
<ide>
<ide><path>guide/spanish/certifications/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/telephone-number-validator/index.md
<ide> function telephoneCheck(str) {
<ide> telephoneCheck("555-555-5555");
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLo9/0)
<ide>
<ide> ### Explicación del código:
<ide>
<ide> function telephoneCheck(str) {
<ide> telephoneCheck("555-555-5555");
<ide> ```
<ide>
<del> [Ejecutar código](https://repl.it/CLoa/0)
<ide>
<ide> ### Explicación del código:
<ide> | 67 |
Text | Text | add redial to ecosystem | 0063fb28ff546126cfd1b3c18e4faccaa98b4380 | <ide><path>docs/introduction/Ecosystem.md
<ide> On this page we will only feature a few of them that the Redux maintainers have
<ide> ### Routing
<ide>
<ide> * [react-router-redux](https://github.com/reactjs/react-router-redux) — Ruthlessly simple bindings to keep React Router and Redux in sync
<add>* [redial](https://github.com/markdalgleish/redial) — Universal data fetching and route lifecycle management for React that works great with Redux
<ide>
<ide> ### Components
<ide> | 1 |
PHP | PHP | add support for assoc keys in cli table helper | dc7ebfd1151689186098fe00ef169eab1950152b | <ide><path>src/Shell/Helper/TableHelper.php
<ide> protected function _calculateWidths($rows)
<ide> {
<ide> $widths = [];
<ide> foreach ($rows as $line) {
<del> for ($i = 0, $len = count($line); $i < $len; $i++) {
<del> $columnLength = mb_strlen($line[$i]);
<del> if ($columnLength > (isset($widths[$i]) ? $widths[$i] : 0)) {
<del> $widths[$i] = $columnLength;
<add> foreach ($line as $k => $v) {
<add> $columnLength = mb_strlen($line[$k]);
<add> if ($columnLength > (isset($widths[$k]) ? $widths[$k] : 0)) {
<add> $widths[$k] = $columnLength;
<ide> }
<ide> }
<ide> } | 1 |
PHP | PHP | allow only classname strings for type map | 913a6d0a47a0bdd43b940ee2fb5f49da629f09f1 | <ide><path>src/Database/Type.php
<ide> class Type
<ide> * identifier is used as key and a complete namespaced class name as value
<ide> * representing the class that will do actual type conversions.
<ide> *
<del> * @var string[]|\Cake\Database\TypeInterface[]
<add> * @var string[]
<ide> */
<ide> protected static $_types = [
<ide> 'tinyinteger' => 'Cake\Database\Type\IntegerType',
<ide> public static function build($name)
<ide> if (!isset(static::$_types[$name])) {
<ide> throw new InvalidArgumentException(sprintf('Unknown type "%s"', $name));
<ide> }
<del> if (is_string(static::$_types[$name])) {
<del> return static::$_builtTypes[$name] = new static::$_types[$name]($name);
<del> }
<ide>
<del> return static::$_builtTypes[$name] = static::$_types[$name];
<add> return static::$_builtTypes[$name] = new static::$_types[$name]($name);
<ide> }
<ide>
<ide> /**
<ide> public static function set($name, TypeInterface $instance)
<ide> * Registers a new type identifier and maps it to a fully namespaced classname.
<ide> *
<ide> * @param string $type Name of type to map.
<del> * @param string|\Cake\Database\TypeInterface $className The classname or object instance of it to register.
<add> * @param string $className The classname to register.
<ide> * @return void
<ide> */
<ide> public static function map(string $type, $className)
<ide> public static function setMap(array $map)
<ide> }
<ide>
<ide> /**
<del> * Get mapped class name or instance for type(s).
<add> * Get mapped class name for given type or map array.
<ide> *
<ide> * @param string|null $type Type name to get mapped class for or null to get map array.
<del> * @return array|string|\Cake\Database\TypeInterface|null Configured class name or instance for give $type or map array.
<add> * @return array|string|null Configured class name for given $type or map array.
<ide> */
<ide> public static function getMap(string $type = null)
<ide> {
<ide><path>tests/TestCase/Database/TypeTest.php
<ide> public function testReMapAndBuild()
<ide> $this->assertInstanceOf($barType, $type);
<ide> }
<ide>
<del> /**
<del> * Tests new types can be registered and built as objects
<del> *
<del> * @return void
<del> */
<del> public function testMapAndBuildWithObjects()
<del> {
<del> $map = Type::getMap();
<del> Type::clear();
<del>
<del> $uuidType = new UuidType('uuid');
<del> Type::map('uuid', $uuidType);
<del>
<del> $this->assertSame($uuidType, Type::build('uuid'));
<del> Type::setMap($map);
<del> }
<del>
<ide> /**
<ide> * Tests clear function in conjunction with map
<ide> * | 2 |
Javascript | Javascript | use existing handlers instead of duplicated code | a892d9a0c1facba70753398a41d9dbd74ba83396 | <ide><path>lib/internal/url.js
<ide> function onParseProtocolComplete(flags, protocol, username, password,
<ide> ctx.port = port;
<ide> }
<ide>
<del>function onParseHostComplete(flags, protocol, username, password,
<del> host, port, path, query, fragment) {
<del> const ctx = this[context];
<del> if ((flags & URL_FLAGS_HAS_HOST) !== 0) {
<del> ctx.host = host;
<del> ctx.flags |= URL_FLAGS_HAS_HOST;
<del> } else {
<del> ctx.host = null;
<del> ctx.flags &= ~URL_FLAGS_HAS_HOST;
<del> }
<del> if (port !== null)
<del> ctx.port = port;
<del>}
<del>
<ide> function onParseHostnameComplete(flags, protocol, username, password,
<ide> host, port, path, query, fragment) {
<ide> const ctx = this[context];
<ide> function onParsePortComplete(flags, protocol, username, password,
<ide> this[context].port = port;
<ide> }
<ide>
<add>function onParseHostComplete(flags, protocol, username, password,
<add> host, port, path, query, fragment) {
<add> onParseHostnameComplete.apply(this, arguments);
<add> if (port !== null)
<add> onParsePortComplete.apply(this, arguments);
<add>}
<add>
<ide> function onParsePathComplete(flags, protocol, username, password,
<ide> host, port, path, query, fragment) {
<ide> const ctx = this[context]; | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.