content_type stringclasses 8 values | main_lang stringclasses 7 values | message stringlengths 1 50 | sha stringlengths 40 40 | patch stringlengths 52 962k | file_count int64 1 300 |
|---|---|---|---|---|---|
Javascript | Javascript | add setnumviews() to webglmultiview | 16c4b71837b24cd207225d2f76d9f16f2b558dec | <ide><path>src/renderers/WebGLMultiviewRenderTarget.js
<ide> WebGLMultiviewRenderTarget.prototype = Object.assign( Object.create( WebGLRender
<ide>
<ide> return this;
<ide>
<add> },
<add>
<add> setNumViews: function ( numViews ) {
<add>
<add> if ( this.numViews !== numViews ) {
<add>
<add> this.numViews = numViews;
<add> this.dispose();
<add>
<add> }
<add>
<add> return this;
<add>
<ide> }
<ide>
<ide> } );
<ide><path>src/renderers/WebGLRenderer.js
<ide> function WebGLRenderer( parameters ) {
<ide>
<ide> state.setPolygonOffset( false );
<ide>
<del> if ( this.multiview.isEnabled() ) {
<add> if ( multiview.isEnabled() ) {
<ide>
<del> this.multiview.detachRenderTarget( camera );
<add> multiview.detachRenderTarget( camera );
<ide>
<ide> }
<ide>
<ide><path>src/renderers/webgl/WebGLMultiview.js
<ide> function WebGLMultiview( renderer, requested, options ) {
<ide>
<ide> options = Object.assign( {}, { debug: false }, options );
<ide>
<add> var DEFAULT_NUMVIEWS = 2;
<ide> var gl = renderer.context;
<ide> var canvas = renderer.domElement;
<ide> var capabilities = renderer.capabilities;
<ide> var properties = renderer.properties;
<ide>
<del> var numViews = 2;
<ide> var renderTarget, currentRenderTarget;
<ide>
<del> // Auxiliary matrices to be used when updating arrays of uniforms
<del> var aux = {
<del> mat4: [],
<del> mat3: []
<del> };
<add> this.getMaxViews = function () {
<ide>
<del> for ( var i = 0; i < numViews; i ++ ) {
<add> return capabilities.maxMultiviewViews;
<ide>
<del> aux.mat4[ i ] = new Matrix4();
<del> aux.mat3[ i ] = new Matrix3();
<add> };
<ide>
<del> }
<add> this.getNumViews = function () {
<ide>
<del> //
<add> return renderTarget ? renderTarget.numViews : 1;
<ide>
<del> this.isAvailable = function () {
<add> };
<ide>
<del> return capabilities.multiview;
<add> // Auxiliary matrices to be used when updating arrays of uniforms
<add> var mat4 = [];
<add> var mat3 = [];
<ide>
<del> };
<add> for ( var i = 0; i < this.getMaxViews(); i ++ ) {
<ide>
<del> this.getNumViews = function () {
<add> mat4[ i ] = new Matrix4();
<add> mat3[ i ] = new Matrix3();
<ide>
<del> return numViews;
<add> }
<ide>
<del> };
<add> //
<ide>
<del> this.getMaxViews = function () {
<add> this.isAvailable = function () {
<ide>
<del> return capabilities.maxMultiviewViews;
<add> return capabilities.multiview;
<ide>
<ide> };
<ide>
<ide> function WebGLMultiview( renderer, requested, options ) {
<ide>
<ide> }
<ide>
<del> this.updateCameraProjectionMatrices = function ( camera, p_uniforms ) {
<add> this.updateCameraProjectionMatrices = function ( camera, uniforms ) {
<add>
<add> var numViews = this.getNumViews();
<ide>
<ide> if ( camera.isArrayCamera ) {
<ide>
<ide> for ( var i = 0; i < numViews; i ++ ) {
<ide>
<del> aux.mat4[ i ].copy( camera.cameras[ i ].projectionMatrix );
<add> mat4[ i ].copy( camera.cameras[ i ].projectionMatrix );
<ide>
<ide> }
<ide>
<ide> } else {
<ide>
<ide> for ( var i = 0; i < numViews; i ++ ) {
<ide>
<del> aux.mat4[ i ].copy( camera.projectionMatrix );
<add> mat4[ i ].copy( camera.projectionMatrix );
<ide>
<ide> }
<ide>
<ide> }
<ide>
<del> p_uniforms.setValue( gl, 'projectionMatrices', aux.mat4 );
<add> uniforms.setValue( gl, 'projectionMatrices', mat4 );
<ide>
<ide> };
<ide>
<del> this.updateCameraViewMatrices = function ( camera, p_uniforms ) {
<add> this.updateCameraViewMatrices = function ( camera, uniforms ) {
<add>
<add> var numViews = this.getNumViews();
<ide>
<ide> if ( camera.isArrayCamera ) {
<ide>
<ide> for ( var i = 0; i < numViews; i ++ ) {
<ide>
<del> aux.mat4[ i ].copy( camera.cameras[ i ].matrixWorldInverse );
<add> mat4[ i ].copy( camera.cameras[ i ].matrixWorldInverse );
<ide>
<ide> }
<ide>
<ide> } else {
<ide>
<ide> for ( var i = 0; i < numViews; i ++ ) {
<ide>
<del> aux.mat4[ i ].copy( camera.matrixWorldInverse );
<add> mat4[ i ].copy( camera.matrixWorldInverse );
<ide>
<ide> }
<ide>
<ide> }
<ide>
<del> p_uniforms.setValue( gl, 'viewMatrices', aux.mat4 );
<add> uniforms.setValue( gl, 'viewMatrices', mat4 );
<ide>
<ide> };
<ide>
<del> this.updateObjectMatrices = function ( object, camera, p_uniforms ) {
<add> this.updateObjectMatrices = function ( object, camera, uniforms ) {
<add>
<add> var numViews = this.getNumViews();
<ide>
<ide> if ( camera.isArrayCamera ) {
<ide>
<ide> for ( var i = 0; i < numViews; i ++ ) {
<ide>
<del> aux.mat4[ i ].multiplyMatrices( camera.cameras[ i ].matrixWorldInverse, object.matrixWorld );
<del> aux.mat3[ i ].getNormalMatrix( aux.mat4[ i ] );
<add> mat4[ i ].multiplyMatrices( camera.cameras[ i ].matrixWorldInverse, object.matrixWorld );
<add> mat3[ i ].getNormalMatrix( mat4[ i ] );
<ide>
<ide> }
<ide>
<ide> } else {
<ide>
<ide> // In this case we still need to provide an array of matrices but just the first one will be used
<del> aux.mat4[ 0 ].multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
<del> aux.mat3[ 0 ].getNormalMatrix( aux.mat4[ 0 ] );
<add> mat4[ 0 ].multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
<add> mat3[ 0 ].getNormalMatrix( mat4[ 0 ] );
<ide>
<ide> for ( var i = 1; i < numViews; i ++ ) {
<ide>
<del> aux.mat4[ i ].copy( aux.mat4[ 0 ] );
<del> aux.mat3[ i ].copy( aux.mat3[ 0 ] );
<add> mat4[ i ].copy( mat4[ 0 ] );
<add> mat3[ i ].copy( mat3[ 0 ] );
<ide>
<ide> }
<ide>
<ide> }
<ide>
<del> p_uniforms.setValue( gl, 'modelViewMatrices', aux.mat4 );
<del> p_uniforms.setValue( gl, 'normalMatrices', aux.mat3 );
<add> uniforms.setValue( gl, 'modelViewMatrices', mat4 );
<add> uniforms.setValue( gl, 'normalMatrices', mat3 );
<ide>
<ide> };
<ide>
<ide> function WebGLMultiview( renderer, requested, options ) {
<ide> width *= bounds.z;
<ide> height *= bounds.w;
<ide>
<add> renderTarget.setNumViews( camera.cameras.length );
<add>
<add> } else {
<add>
<add> renderTarget.setNumViews( DEFAULT_NUMVIEWS );
<add>
<ide> }
<ide>
<ide> renderTarget.setSize( width, height );
<ide> function WebGLMultiview( renderer, requested, options ) {
<ide>
<ide> if ( this.isEnabled() ) {
<ide>
<del> renderTarget = new WebGLMultiviewRenderTarget( canvas.width, canvas.height, numViews );
<add> renderTarget = new WebGLMultiviewRenderTarget( canvas.width, canvas.height, this.numViews );
<ide>
<ide> }
<ide>
<ide><path>src/renderers/webgl/WebGLTextures.js
<ide> function WebGLTextures( _gl, extensions, state, properties, capabilities, utils,
<ide> ext.framebufferTextureMultiviewOVR( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, depthStencilTexture, 0, 0, numViews );
<ide>
<ide> var viewFramebuffers = new Array( numViews );
<del> for ( var viewIndex = 0; viewIndex < numViews; ++ viewIndex ) {
<add> for ( var i = 0; i < numViews; ++ i ) {
<ide>
<del> viewFramebuffers[ viewIndex ] = _gl.createFramebuffer();
<del> _gl.bindFramebuffer( _gl.FRAMEBUFFER, viewFramebuffers[ viewIndex ] );
<del> _gl.framebufferTextureLayer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, colorTexture, 0, viewIndex );
<add> viewFramebuffers[ i ] = _gl.createFramebuffer();
<add> _gl.bindFramebuffer( _gl.FRAMEBUFFER, viewFramebuffers[ i ] );
<add> _gl.framebufferTextureLayer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, colorTexture, 0, i );
<ide>
<ide> }
<ide> | 4 |
Ruby | Ruby | move debugger into middleware | c80fe1093deeb57eee8df11d3c4120158634cb81 | <ide><path>railties/lib/commands/server.rb
<ide> app = Rack::Builder.new {
<ide> use Rails::Rack::Logger
<ide> use Rails::Rack::Static
<add> use Rails::Rack::Debugger if options[:debugger]
<ide> run ActionController::Dispatcher.new
<ide> }.to_app
<ide> end
<ide>
<del>if options[:debugger]
<del> begin
<del> require_library_or_gem 'ruby-debug'
<del> Debugger.start
<del> Debugger.settings[:autoeval] = true if Debugger.respond_to?(:settings)
<del> puts "=> Debugger enabled"
<del> rescue Exception
<del> puts "You need to install ruby-debug to run the server in debugging mode. With gems, use 'gem install ruby-debug'"
<del> exit
<del> end
<del>end
<del>
<ide> puts "=> Call with -d to detach"
<ide>
<ide> trap(:INT) { exit }
<ide><path>railties/lib/rails/rack.rb
<ide> module Rails
<ide> module Rack
<add> autoload :Debugger, "rails/rack/debugger"
<ide> autoload :Logger, "rails/rack/logger"
<ide> autoload :Static, "rails/rack/static"
<ide> end
<ide><path>railties/lib/rails/rack/debugger.rb
<add>module Rails
<add> module Rack
<add> class Debugger
<add> def initialize(app)
<add> @app = app
<add>
<add> require_library_or_gem 'ruby-debug'
<add> ::Debugger.start
<add> ::Debugger.settings[:autoeval] = true if ::Debugger.respond_to?(:settings)
<add> puts "=> Debugger enabled"
<add> rescue Exception
<add> puts "You need to install ruby-debug to run the server in debugging mode. With gems, use 'gem install ruby-debug'"
<add> exit
<add> end
<add>
<add> def call(env)
<add> @app.call(env)
<add> end
<add> end
<add> end
<add>end | 3 |
Javascript | Javascript | fix abc order of docs nav | fab8e38759f620f242557e1219c2e6c8c5766f1f | <ide><path>website/server/extractDocs.js
<ide> var components = [
<ide> '../Libraries/Image/Image.ios.js',
<ide> '../Libraries/CustomComponents/ListView/ListView.js',
<ide> '../Libraries/Components/MapView/MapView.js',
<del> '../Libraries/CustomComponents/Navigator/Navigator.js',
<ide> '../Libraries/Modal/Modal.js',
<add> '../Libraries/CustomComponents/Navigator/Navigator.js',
<ide> '../Libraries/Components/Navigation/NavigatorIOS.ios.js',
<ide> '../Libraries/Picker/PickerIOS.ios.js',
<ide> '../Libraries/Components/ProgressBarAndroid/ProgressBarAndroid.android.js', | 1 |
Javascript | Javascript | add mocha rfc 232 test blueprints for helpers | e8b58eed1b58edd902ba5b6782cc18ccdb3b7c34 | <ide><path>blueprints/helper-test/mocha-rfc-232-files/tests/__testType__/__path__/__name__-test.js
<add>import { expect } from 'chai';
<add><% if (testType == 'integration') { %>import { describe, it } from 'mocha';
<add>import { setupRenderingTest } from 'ember-mocha';
<add>import { render } from '@ember/test-helpers';
<add>import hbs from 'htmlbars-inline-precompile';
<add>
<add>describe('<%= friendlyTestName %>', function() {
<add> setupRenderingTest();
<add>
<add> // Replace this with your real tests.
<add> it('renders', async function() {
<add> this.set('inputValue', '1234');
<add>
<add> await render(hbs`{{<%= dasherizedModuleName %> inputValue}}`);
<add>
<add> expect(this.element.textContent.trim()).to.equal('1234');
<add> });
<add>});<% } else if (testType == 'unit') { %>import { describe, it } from 'mocha';
<add>import { <%= camelizedModuleName %> } from '<%= dasherizedPackageName %>/helpers/<%= dasherizedModuleName %>';
<add>
<add>describe('<%= friendlyTestName %>', function() {
<add>
<add> // Replace this with your real tests.
<add> it('works', function() {
<add> let result = <%= camelizedModuleName %>(42);
<add> expect(result).to.be.ok;
<add> });
<add>});<% } %>
<ide><path>node-tests/blueprints/helper-test-test.js
<ide> describe('Blueprint: helper-test', function() {
<ide> });
<ide> });
<ide> });
<add>
<add> describe('with ember-mocha@0.14.0', function() {
<add> beforeEach(function() {
<add> modifyPackages([
<add> { name: 'ember-cli-qunit', delete: true },
<add> { name: 'ember-mocha', dev: true },
<add> ]);
<add> generateFakePackageManifest('ember-mocha', '0.14.0');
<add> });
<add>
<add> it('helper-test foo/bar-baz for mocha', function() {
<add> return emberGenerateDestroy(['helper-test', 'foo/bar-baz'], _file => {
<add> expect(_file('tests/integration/helpers/foo/bar-baz-test.js')).to.equal(
<add> fixture('helper-test/mocha-rfc232.js')
<add> );
<add> });
<add> });
<add>
<add> it('helper-test foo/bar-baz for mocha --unit', function() {
<add> return emberGenerateDestroy(['helper-test', 'foo/bar-baz', '--unit'], _file => {
<add> expect(_file('tests/unit/helpers/foo/bar-baz-test.js')).to.equal(
<add> fixture('helper-test/mocha-rfc232-unit.js')
<add> );
<add> });
<add> });
<add> });
<ide> });
<ide>
<ide> describe('in addon', function() {
<ide><path>node-tests/fixtures/helper-test/mocha-rfc232-unit.js
<add>import { expect } from 'chai';
<add>import { describe, it } from 'mocha';
<add>import { fooBarBaz } from 'my-app/helpers/foo/bar-baz';
<add>
<add>describe('Unit | Helper | foo/bar-baz', function() {
<add>
<add> // Replace this with your real tests.
<add> it('works', function() {
<add> let result = fooBarBaz(42);
<add> expect(result).to.be.ok;
<add> });
<add>});
<ide><path>node-tests/fixtures/helper-test/mocha-rfc232.js
<add>import { expect } from 'chai';
<add>import { describe, it } from 'mocha';
<add>import { setupRenderingTest } from 'ember-mocha';
<add>import { render } from '@ember/test-helpers';
<add>import hbs from 'htmlbars-inline-precompile';
<add>
<add>describe('Integration | Helper | foo/bar-baz', function() {
<add> setupRenderingTest();
<add>
<add> // Replace this with your real tests.
<add> it('renders', async function() {
<add> this.set('inputValue', '1234');
<add>
<add> await render(hbs`{{foo/bar-baz inputValue}}`);
<add>
<add> expect(this.element.textContent.trim()).to.equal('1234');
<add> });
<add>}); | 4 |
Text | Text | update the style guide | de716df2e512e50d31c6ddec4c14508a8bd2ddaf | <ide><path>docs/style-guide-for-guide-articles.md
<ide> Use Markdown style links in your articles to link to other websites.
<ide> > becomes
<ide> > `https://example.com/a-long/url/to-a-webpage/`
<ide>
<add>## List
<add>
<add>You can make an unordered list by preceding one or more lines of text with - or *
<add>To order your list, precede each line with a number.
<add>
<add>```markdown
<add> - Hello user!
<add> * Hey there!
<add>
<add>```
<add>
<ide> ## Images
<ide>
<ide> For including images, if they aren't already hosted somewhere else on the web, you will need to put them online yourself using a platform like [Imgur](https://imgur.com/) or [Flickr](https://www.flickr.com). You can also host images by committing them to a git repository and pushing it to GitHub. Then you can right-click the image and copy its URL. | 1 |
Ruby | Ruby | fix hash#slice code example [ci skip] | 255cefbff44d0bf0faeec43a5112e88b7c4424c2 | <ide><path>actionmailer/lib/action_mailer/base.rb
<ide> require 'active_support/core_ext/module/anonymous'
<ide> require 'action_mailer/log_subscriber'
<ide>
<del>module ActionMailer # :nodoc:
<add>module ActionMailer # :notdoc:
<ide> # = Action Mailer
<ide> #
<ide> # Action Mailer allows you to send email from your application using a mailer
<ide><path>activesupport/lib/active_support/core_ext/hash/slice.rb
<ide> class Hash
<ide> # limiting an options hash to valid keys before passing to a method:
<ide> #
<ide> # def search(criteria = {})
<del> # assert_valid_keys(:mass, :velocity, :time)
<add> # criteria.assert_valid_keys(:mass, :velocity, :time)
<ide> # end
<ide> #
<ide> # search(options.slice(:mass, :velocity, :time)) | 2 |
Ruby | Ruby | remove unused method / fix documentation | 082130d1d43620ca29c2f2f169a5059fa0065a8c | <ide><path>actionview/lib/action_view/template/resolver.rb
<ide> def find_all_with_query(query) # :nodoc:
<ide> # because Resolver guarantees that the arguments are present and
<ide> # normalized.
<ide> def find_templates(name, prefix, partial, details, outside_app_allowed = false, locals = [])
<del> raise NotImplementedError, "Subclasses must implement a find_templates(name, prefix, partial, details, outside_app_allowed = false) method"
<del> end
<del>
<del> # Helpers that builds a path. Useful for building virtual paths.
<del> def build_path(name, prefix, partial)
<del> Path.build(name, prefix, partial)
<add> raise NotImplementedError, "Subclasses must implement a find_templates(name, prefix, partial, details, outside_app_allowed = false, locals = []) method"
<ide> end
<ide>
<ide> # Handles templates caching. If a key is given and caching is on | 1 |
Text | Text | add note for windows build path | 43029da762fafabf1d5594b83ee4fbab91dc35d0 | <ide><path>BUILDING.md
<ide> More Developer Tools...`. This step will install `clang`, `clang++`, and
<ide> * You may want to setup [firewall rules](tools/macosx-firewall.sh)
<ide> to avoid popups asking to accept incoming network connections when running tests:
<ide>
<add>If the path to your build directory contains a space, the build will likely fail.
<add>
<ide> ```console
<ide> $ sudo ./tools/macosx-firewall.sh
<ide> ```
<ide> Prerequisites:
<ide> [Git for Windows](http://git-scm.com/download/win) includes Git Bash
<ide> and tools which can be included in the global `PATH`.
<ide>
<add>If the path to your build directory contains a space, the build will likely fail.
<add>
<ide> ```console
<ide> > .\vcbuild
<ide> ``` | 1 |
Text | Text | fix new nits in links | 3070d53e31a09be5f8b121dc13d844d04a5541ee | <ide><path>doc/api/http.md
<ide> const req = http.request(options, (res) => {
<ide> [`agent.createConnection()`]: #http_agent_createconnection_options_callback
<ide> [`agent.getName()`]: #http_agent_getname_options
<ide> [`destroy()`]: #http_agent_destroy
<del>[`getHeader(name)`]: #requestgetheadername
<add>[`getHeader(name)`]: #http_request_getheader_name
<ide> [`http.Agent`]: #http_class_http_agent
<ide> [`http.ClientRequest`]: #http_class_http_clientrequest
<ide> [`http.IncomingMessage`]: #http_class_http_incomingmessage
<ide> const req = http.request(options, (res) => {
<ide> [`net.Server`]: net.html#net_class_net_server
<ide> [`net.Socket`]: net.html#net_class_net_socket
<ide> [`net.createConnection()`]: net.html#net_net_createconnection_options_connectlistener
<del>[`removeHeader(name)`]: #requestremoveheadername
<add>[`removeHeader(name)`]: #http_request_removeheader_name
<ide> [`request.end()`]: #http_request_end_data_encoding_callback
<ide> [`request.setTimeout()`]: #http_request_settimeout_timeout_callback
<ide> [`request.socket`]: #http_request_socket
<ide> const req = http.request(options, (res) => {
<ide> [`response.writeContinue()`]: #http_response_writecontinue
<ide> [`response.writeHead()`]: #http_response_writehead_statuscode_statusmessage_headers
<ide> [`server.timeout`]: #http_server_timeout
<del>[`setHeader(name, value)`]: #requestsetheadername-value
<add>[`setHeader(name, value)`]: #http_request_setheader_name_value
<ide> [`socket.setKeepAlive()`]: net.html#net_socket_setkeepalive_enable_initialdelay
<ide> [`socket.setNoDelay()`]: net.html#net_socket_setnodelay_nodelay
<ide> [`socket.setTimeout()`]: net.html#net_socket_settimeout_timeout_callback
<ide><path>doc/api/n-api.md
<ide> NAPI_EXTERN napi_status napi_run_script(napi_env env,
<ide> - `[out] result`: The value resulting from having executed the script.
<ide>
<ide> [Promises]: #n_api_promises
<del>[Simple Asynchronous Operations]: #n_api_asynchronous_operations
<add>[Simple Asynchronous Operations]: #n_api_simple_asynchronous_operations
<ide> [Custom Asynchronous Operations]: #n_api_custom_asynchronous_operations
<ide> [Basic N-API Data Types]: #n_api_basic_n_api_data_types
<ide> [ECMAScript Language Specification]: https://tc39.github.io/ecma262/
<ide><path>doc/api/process.md
<ide> cases:
<ide> [`promise.catch()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch
<ide> [`require()`]: globals.html#globals_require
<ide> [`require.main`]: modules.html#modules_accessing_the_main_module
<del>[`require.resolve()`]: globals.html#globals_require_resolve
<add>[`require.resolve()`]: modules.html#modules_require_resolve
<ide> [`setTimeout(fn, 0)`]: timers.html#timers_settimeout_callback_delay_args
<ide> [Child Process]: child_process.html
<ide> [Cluster]: cluster.html | 3 |
Text | Text | add info on post-publishing arm6 builds | 4e65f9d504a8cb6490a1eebbdc827f801f70fca9 | <ide><path>doc/releases.md
<ide> If you have an error on Windows and need to start again, be aware that you'll ge
<ide>
<ide> ARMv7 takes the longest to compile. Unfortunately ccache isn't as effective on release builds, I think it's because of the additional macro settings that go in to a release build that nullify previous builds. Also most of the release build machines are separate to the test build machines so they don't get any benefit from ongoing compiles between releases. You can expect 1.5 hours for the ARMv7 builder to complete and you should normally wait for this to finish. It is possible to rush a release out if you want and add additional builds later but we normally provide ARMv7 from initial promotion.
<ide>
<del>You do not have to wait for the ARMv6 / Raspberry PI builds if they take longer than the others. It is only necessary to have the main Linux (x64 and x86), macOS .pkg and .tar.gz, Windows (x64 and x86) .msi and .exe, source, headers, and docs (both produced currently by an macOS worker). **If you promote builds _before_ ARM builds have finished, you must repeat the promotion step for the ARM builds when they are ready**.
<add>You do not have to wait for the ARMv6 / Raspberry PI builds if they take longer than the others. It is only necessary to have the main Linux (x64 and x86), macOS .pkg and .tar.gz, Windows (x64 and x86) .msi and .exe, source, headers, and docs (both produced currently by an macOS worker). **If you promote builds _before_ ARM builds have finished, you must repeat the promotion step for the ARM builds when they are ready**. If the ARMv6 build failed for some reason you can use the [`iojs-release-arm6-only`](https://ci-release.nodejs.org/job/iojs+release-arm6-only/) build in the release CI to re-run the build only for ARMv6. When launching the build make sure to use the same commit hash as for the original release.
<ide>
<ide> ### 9. Test the Build
<ide> | 1 |
Text | Text | add more immutability links | c54704355b35ccb76970a8633ea82dfe38557754 | <ide><path>docs/usage/structuring-reducers/ImmutableUpdatePatterns.md
<ide> your reducers are using Redux Toolkit and Immer.
<ide>
<ide> In addition, Redux Toolkit's [`createSlice` utility](https://redux-toolkit.js.org/api/createSlice) will auto-generate action creators
<ide> and action types based on the reducer functions you provide, with the same Immer-powered update capabilities inside.
<add>
<add>## Further Information
<add>
<add>- [Dave Ceddia: The Complete Guide to Immutability in React and Redux](https://daveceddia.com/react-redux-immutability-guide/)
<add>- [React docs: Updating Objects in State](https://beta.reactjs.org/learn/updating-objects-in-state)
<add>- [React docs: Updating Arrays in State](https://beta.reactjs.org/learn/updating-arrays-in-state) | 1 |
Python | Python | correct an subsampling issue on python 3 | 982054becd85e443b0f6e69e1157f9299fabcd83 | <ide><path>glances/compat.py
<ide> def subsample(data, sampling):
<ide> if len(data) <= sampling:
<ide> return data
<ide> sampling_length = int(round(len(data) / float(sampling)))
<del> return [mean(data[s * sampling_length:(s + 1) * sampling_length]) for s in xrange(0, sampling)]
<add> return [mean(data[s * sampling_length:(s + 1) * sampling_length]) for s in range(0, sampling)]
<ide>
<ide>
<ide> def time_serie_subsample(data, sampling):
<ide> def time_serie_subsample(data, sampling):
<ide> t = [t[0] for t in data]
<ide> v = [t[1] for t in data]
<ide> sampling_length = int(round(len(data) / float(sampling)))
<del> t_subsampled = [t[s * sampling_length:(s + 1) * sampling_length][0] for s in xrange(0, sampling)]
<del> v_subsampled = [mean(v[s * sampling_length:(s + 1) * sampling_length]) for s in xrange(0, sampling)]
<add> t_subsampled = [t[s * sampling_length:(s + 1) * sampling_length][0] for s in range(0, sampling)]
<add> v_subsampled = [mean(v[s * sampling_length:(s + 1) * sampling_length]) for s in range(0, sampling)]
<ide> return list(zip(t_subsampled, v_subsampled))
<ide><path>unitest.py
<ide> from glances.thresholds import GlancesThresholdCritical
<ide> from glances.thresholds import GlancesThresholds
<ide> from glances.plugins.glances_plugin import GlancesPlugin
<del>from glances.compat import subsample
<add>from glances.compat import subsample, range
<ide>
<ide> # Global variables
<ide> # =================
<ide> def test_015_subsample(self):
<ide> ([1, 2, 3, 4], 4),
<ide> ([1, 2, 3, 4, 5, 6, 7], 4),
<ide> ([1, 2, 3, 4, 5, 6, 7, 8], 4),
<del> (list(xrange(1, 800)), 4),
<del> (list(xrange(1, 8000)), 800)]:
<add> (list(range(1, 800)), 4),
<add> (list(range(1, 8000)), 800)]:
<ide> l_subsample = subsample(l[0], l[1])
<ide> self.assertLessEqual(len(l_subsample), l[1])
<ide> | 2 |
Python | Python | add basic tests for np.array | 16c55bad4aa4c49116d963eee85550258c83b934 | <ide><path>numpy/core/tests/test_api.py
<ide> from numpy.compat import sixu
<ide>
<ide> # Switch between new behaviour when NPY_RELAXED_STRIDES_CHECKING is set.
<del>NPY_RELAXED_STRIDES_CHECKING = np.ones((10,1), order='C').flags.f_contiguous
<add>NPY_RELAXED_STRIDES_CHECKING = np.ones((10, 1), order='C').flags.f_contiguous
<add>
<add>
<add>def test_array_array():
<add> obj = object()
<add> tobj = type(object)
<add> ones11 = np.ones((1, 1), np.float64)
<add> tndarray = type(ones11)
<add> # Test is_ndarary
<add> assert_equal(np.array(ones11, dtype=np.float64), ones11)
<add> old_refcount = sys.getrefcount(tndarray)
<add> np.array(ones11)
<add> assert_equal(old_refcount, sys.getrefcount(tndarray))
<add>
<add> # test None
<add> assert_equal(np.array(None, dtype=np.float64),
<add> np.array(np.nan, dtype=np.float64))
<add> old_refcount = sys.getrefcount(tobj)
<add> np.array(None, dtype=np.float64)
<add> assert_equal(old_refcount, sys.getrefcount(tobj))
<add>
<add> # test scalar
<add> assert_equal(np.array(1.0, dtype=np.float64),
<add> np.ones((), dtype=np.float64))
<add> old_refcount = sys.getrefcount(np.float64)
<add> np.array(np.array(1.0, dtype=np.float64), dtype=np.float64)
<add> assert_equal(old_refcount, sys.getrefcount(np.float64))
<add>
<add> # test string
<add> S2 = np.dtype((str, 2))
<add> S3 = np.dtype((str, 3))
<add> S5 = np.dtype((str, 5))
<add> assert_equal(np.array("1.0", dtype=np.float64),
<add> np.ones((), dtype=np.float64))
<add> assert_equal(np.array("1.0").dtype, S3)
<add> assert_equal(np.array("1.0", dtype=str).dtype, S3)
<add> assert_equal(np.array("1.0", dtype=S2), np.array("1."))
<add> assert_equal(np.array("1", dtype=S5), np.ones((), dtype=S5))
<add>
<add> # test unicode
<add> _unicode = globals().get("unicode")
<add> if _unicode:
<add> U2 = np.dtype((_unicode, 2))
<add> U3 = np.dtype((_unicode, 3))
<add> U5 = np.dtype((_unicode, 5))
<add> assert_equal(np.array(_unicode("1.0"), dtype=np.float64),
<add> np.ones((), dtype=np.float64))
<add> assert_equal(np.array(_unicode("1.0")).dtype, U3)
<add> assert_equal(np.array(_unicode("1.0"), dtype=_unicode).dtype, U3)
<add> assert_equal(np.array(_unicode("1.0"), dtype=U2),
<add> np.array(_unicode("1.")))
<add> assert_equal(np.array(_unicode("1"), dtype=U5),
<add> np.ones((), dtype=U5))
<add>
<add> builtins = getattr(__builtins__, '__dict__', __builtins__)
<add> assert_(isinstance(builtins, dict))
<add>
<add> # test buffer
<add> _buffer = builtins.get("buffer")
<add> if _buffer:
<add> assert_equal(np.array(_buffer("1.0"), dtype=np.float64),
<add> np.array(1.0, dtype=np.float64))
<add> assert_equal(np.array(_buffer("1.0"), dtype=np.float64).dtype,
<add> np.dtype("float64"))
<add> assert_equal(np.array([_buffer("1.0")], dtype=np.float64),
<add> np.array([1.0], dtype=np.float64))
<add>
<add> # test memoryview, new version of buffer
<add> _memoryview = builtins.get("memoryview")
<add> if _memoryview:
<add> assert_equal(np.array(_memoryview(bytearray(b'1.0')),
<add> dtype=np.float64),
<add> np.array([49.0, 46.0, 48.0],
<add> dtype=np.float64))
<add> assert_equal(np.array(_memoryview(bytearray(b'1.0')),
<add> dtype=np.float64).dtype,
<add> np.dtype("float64"))
<add> assert_equal(np.array(_memoryview(bytearray(b'1.0'))).dtype,
<add> np.dtype('uint8'))
<add>
<add> # test array interface
<add> a = np.array(100.0, dtype=np.float64)
<add> o = type("o", (object,),
<add> dict(__array_interface__=a.__array_interface__))
<add> assert_equal(np.array(o, dtype=np.float64), a)
<add>
<add> # test array_struct interface
<add> a = np.array([(1, 4.0, 'Hello'), (2, 6.0, 'World')],
<add> dtype=[('f0', int), ('f1', float), ('f2', str)])
<add> o = type("o", (object,),
<add> dict(__array_struct__=a.__array_struct__))
<add> ## wasn't what I expected... is np.array(o) supposed to equal a ?
<add> ## instead we get a array([...], dtype=">V18")
<add> assert_equal(str(np.array(o).data), str(a.data))
<add>
<add> # test array
<add> o = type("o", (object,),
<add> dict(__array__=lambda *x: np.array(100.0, dtype=np.float64)))()
<add> assert_equal(np.array(o, dtype=np.float64), np.array(100.0, np.float64))
<add>
<add> # test recursion
<add> nested = 1.5
<add> for i in range(np.MAXDIMS):
<add> nested = [nested]
<add>
<add> # no error
<add> np.array(nested)
<add>
<add> # Exceeds recursion limit
<add> assert_raises(ValueError, np.array, [nested], dtype=np.float64)
<add>
<add> # Try with lists...
<add> assert_equal(np.array([None] * 10, dtype=np.float64),
<add> np.empty((10,), dtype=np.float64) + np.nan)
<add> assert_equal(np.array([[None]] * 10, dtype=np.float64),
<add> np.empty((10, 1), dtype=np.float64) + np.nan)
<add> assert_equal(np.array([[None] * 10], dtype=np.float64),
<add> np.empty((1, 10), dtype=np.float64) + np.nan)
<add> assert_equal(np.array([[None] * 10] * 10, dtype=np.float64),
<add> np.empty((10, 10), dtype=np.float64) + np.nan)
<add>
<add> assert_equal(np.array([1.0] * 10, dtype=np.float64),
<add> np.ones((10,), dtype=np.float64))
<add> assert_equal(np.array([[1.0]] * 10, dtype=np.float64),
<add> np.ones((10, 1), dtype=np.float64))
<add> assert_equal(np.array([[1.0] * 10], dtype=np.float64),
<add> np.ones((1, 10), dtype=np.float64))
<add> assert_equal(np.array([[1.0] * 10] * 10, dtype=np.float64),
<add> np.ones((10, 10), dtype=np.float64))
<add>
<add> # Try with tuples
<add> assert_equal(np.array((None,) * 10, dtype=np.float64),
<add> np.empty((10,), dtype=np.float64) + np.nan)
<add> assert_equal(np.array([(None,)] * 10, dtype=np.float64),
<add> np.empty((10, 1), dtype=np.float64) + np.nan)
<add> assert_equal(np.array([(None,) * 10], dtype=np.float64),
<add> np.empty((1, 10), dtype=np.float64) + np.nan)
<add> assert_equal(np.array([(None,) * 10] * 10, dtype=np.float64),
<add> np.empty((10, 10), dtype=np.float64) + np.nan)
<add>
<add> assert_equal(np.array((1.0,) * 10, dtype=np.float64),
<add> np.ones((10,), dtype=np.float64))
<add> assert_equal(np.array([(1.0,)] * 10, dtype=np.float64),
<add> np.ones((10, 1), dtype=np.float64))
<add> assert_equal(np.array([(1.0,) * 10], dtype=np.float64),
<add> np.ones((1, 10), dtype=np.float64))
<add> assert_equal(np.array([(1.0,) * 10] * 10, dtype=np.float64),
<add> np.ones((10, 10), dtype=np.float64))
<add>
<ide>
<ide> def test_fastCopyAndTranspose():
<ide> # 0D array | 1 |
Python | Python | remove unnecessary imports and assignments | 89ede72fca942e7ceffd414e795e3d2c5e09ed0a | <ide><path>test/message/testcfg.py
<ide>
<ide> import test
<ide> import os
<del>from os.path import join, dirname, exists, basename, isdir
<add>from os.path import join, exists, basename, isdir
<ide> import re
<ide>
<ide> FLAGS_PATTERN = re.compile(r"//\s+Flags:(.*)")
<ide><path>test/testpy/__init__.py
<ide>
<ide> import test
<ide> import os
<del>import shutil
<del>from os import mkdir
<del>from glob import glob
<ide> from os.path import join, dirname, exists
<ide> import re
<ide>
<ide><path>test/timers/testcfg.py
<ide>
<ide> import test
<ide> import os
<del>import shutil
<del>from shutil import rmtree
<del>from os import mkdir
<del>from glob import glob
<del>from os.path import join, dirname, exists
<add>from os.path import join, exists
<ide> import re
<ide> import shlex
<ide>
<ide><path>tools/configure.d/nodedownload.py
<ide> def retrievefile(url, targetfile):
<ide> try:
<ide> sys.stdout.write(' <%s>\nConnecting...\r' % url)
<ide> sys.stdout.flush()
<del> msg = ConfigOpener().retrieve(url, targetfile, reporthook=reporthook)
<add> ConfigOpener().retrieve(url, targetfile, reporthook=reporthook)
<ide> print '' # clear the line
<ide> return targetfile
<ide> except:
<ide><path>tools/icu/shrink-icu-src.py
<ide> #!/usr/bin/env python
<ide> import optparse
<ide> import os
<del>import pprint
<ide> import re
<del>import shlex
<del>import subprocess
<ide> import sys
<ide> import shutil
<del>import string
<ide>
<ide> parser = optparse.OptionParser()
<ide>
<ide><path>tools/specialize_node_d.py
<ide> #
<ide>
<ide> import re
<del>import subprocess
<ide> import sys
<del>import errno
<ide>
<ide> if len(sys.argv) != 5:
<ide> print "usage: specialize_node_d.py outfile src/node.d flavor arch"
<ide><path>tools/test.py
<ide> import logging
<ide> import optparse
<ide> import os
<del>import platform
<ide> import re
<ide> import signal
<ide> import subprocess | 7 |
PHP | PHP | use undeprecated method | f74e4de295f564c6bba5b6d67966289426aaf259 | <ide><path>tests/TestCase/Error/ExceptionRendererTest.php
<ide> public function testMissingLayoutPathRenderSafe()
<ide> 'Controller.beforeRender',
<ide> function (Event $event) {
<ide> $this->called = true;
<del> $event->subject()->viewBuilder()->layoutPath('boom');
<add> $event->subject()->viewBuilder()->setLayoutPath('boom');
<ide> }
<ide> );
<ide> $ExceptionRenderer->controller->request = new Request; | 1 |
Python | Python | fix special tokens mask in encode | fe92755b992eb61239ad361abae3b71f86bbbba1 | <ide><path>transformers/tokenization_utils.py
<ide> def prepare_for_model(self, ids, pair_ids=None, max_length=None, add_special_tok
<ide> token_type_ids = [0] * len(ids) + ([1] * len(pair_ids) if pair else [])
<ide>
<ide> if return_special_tokens_mask:
<del> encoded_inputs["special_tokens_mask"] = special_tokens_mask
<add> encoded_inputs["special_tokens_mask"] = self.get_special_tokens_mask(ids, pair_ids)
<ide>
<ide> encoded_inputs["input_ids"] = sequence
<ide> if return_token_type_ids: | 1 |
Ruby | Ruby | spell existence properly (closes ) | b6e7cc63de744c08f7b310ab879ff20af17572e8 | <ide><path>actionpack/lib/action_controller/base.rb
<ide> def render_action(action_name, status = nil, with_layout = true)
<ide>
<ide> def render_file(template_path, status = nil, use_full_path = false, locals = {})
<ide> add_variables_to_assigns
<del> assert_existance_of_template_file(template_path) if use_full_path
<add> assert_existence_of_template_file(template_path) if use_full_path
<ide> logger.info("Rendering #{template_path}" + (status ? " (#{status})" : '')) if logger
<ide> render_text(@template.render_file(template_path, use_full_path, locals), status)
<ide> end
<ide> def template_exempt_from_layout?(template_name = default_template_name)
<ide> template_name =~ /\.rjs$/ || (@template.pick_template_extension(template_name) == :rjs rescue false)
<ide> end
<ide>
<del> def assert_existance_of_template_file(template_name)
<add> def assert_existence_of_template_file(template_name)
<ide> unless template_exists?(template_name) || ignore_missing_templates
<ide> full_template_path = @template.send(:full_template_path, template_name, 'rhtml')
<ide> template_type = (template_name =~ /layouts/i) ? 'layout' : 'template' | 1 |
Text | Text | remove extraneous files from contributor tools | e5763e9bb431fd999e460adc316a60a57780b288 | <ide><path>tools/contributor/CODE_OF_CONDUCT.md
<del>> Our Code of Conduct is available here: <https://code-of-conduct.freecodecamp.org/>
<ide><path>tools/contributor/LICENSE.md
<del>BSD 3-Clause License
<del>
<del>Copyright (c) 2018, freeCodeCamp.org
<del>All rights reserved.
<del>
<del>Redistribution and use in source and binary forms, with or without
<del>modification, are permitted provided that the following conditions are met:
<del>
<del>* Redistributions of source code must retain the above copyright notice, this
<del> list of conditions and the following disclaimer.
<del>
<del>* Redistributions in binary form must reproduce the above copyright notice,
<del> this list of conditions and the following disclaimer in the documentation
<del> and/or other materials provided with the distribution.
<del>
<del>* Neither the name of the copyright holder nor the names of its
<del> contributors may be used to endorse or promote products derived from
<del> this software without specific prior written permission.
<del>
<del>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
<del>AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
<del>IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
<del>DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
<del>FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
<del>DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
<del>SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
<del>CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
<del>OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
<del>OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
<ide><path>tools/contributor/README.md
<del>
<del>
<del># Contribute
<del>
<del>Tools to help maintain [freeCodeCamp.org](https://www.freecodecamp.org)'s Open Source Codebase on GitHub. We are currently working on creating a tools dashboard for helping you review PRs and translations. Hangout with us in the [contributor's chat room](https://chat.freecodecamp.org/channel/contributors) to learn more. | 3 |
Javascript | Javascript | use __webpack_require__.i to escape brakets | 3b6ef1a7abfef15f6ab5bbef30245297f6555be1 | <ide><path>lib/DefinePlugin.js
<ide> class DefinePlugin {
<ide> }(definitions, ""));
<ide>
<ide> function stringifyObj(obj) {
<del> return "({" + Object.keys(obj).map((key) => {
<add> return "__webpack_require__.i({" + Object.keys(obj).map((key) => {
<ide> let code = obj[key];
<ide> return JSON.stringify(key) + ":" + toCode(code);
<ide> }).join(",") + "})"; | 1 |
Text | Text | remove node-report from support tiers | 819ff24aa1b7d883aaa4600c69fbb4969b352596 | <ide><path>doc/contributing/diagnostic-tooling-support-tiers.md
<ide> The tools are currently assigned to Tiers as follows:
<ide>
<ide> | Tool Type | Tool/API Name | Regular Testing in Node.js CI | Integrated with Node.js | Target Tier |
<ide> | --------- | ------------------------- | ----------------------------- | ----------------------- | ----------- |
<del>| FFDC | node-report | No | No | 1 |
<ide> | Memory | V8 heap profiler | No | Yes | 1 |
<ide> | Memory | V8 sampling heap profiler | No | Yes | 1 |
<ide> | AsyncFlow | Async Hooks (API) | ? | Yes | 1 | | 1 |
Ruby | Ruby | add test case for joined pluck | 6cb956592cc5deb5496729f1e09ca9a4cc22868c | <ide><path>activerecord/test/cases/calculations_test.rb
<ide> def test_calculation_with_polymorphic_relation
<ide> assert_equal part.id, ShipPart.joins(:trinkets).sum(:id)
<ide> end
<ide>
<add> def test_pluck_joined_with_polymorphic_relation
<add> part = ShipPart.create!(name: "has trinket")
<add> part.trinkets.create!
<add>
<add> assert_equal [part.id], ShipPart.joins(:trinkets).pluck(:id)
<add> end
<add>
<ide> def test_grouped_calculation_with_polymorphic_relation
<ide> part = ShipPart.create!(name: "has trinket")
<ide> part.trinkets.create! | 1 |
Javascript | Javascript | adjust layout to show youtube controls | c80bc0086e9cef1c2f843bead3160ad4c7aaed85 | <ide><path>news/routes/Show/Show.js
<ide> import Youtube from 'react-youtube';
<ide> import { Image } from 'react-bootstrap';
<ide>
<ide> import Author from './components/Author';
<del>import { Loader } from '../../../common/app/helperComponents';
<add>import { Loader, Spacer } from '../../../common/app/helperComponents';
<ide> import { getArticleById, postPopularityEvent } from '../../utils/ajax';
<ide>
<ide> const propTypes = {
<ide> const styles = `
<ide> position: absolute;
<ide> left: 0;
<ide> width: 100%;
<del> height: 100%;
<add> height: 95%;
<ide> }
<ide> `;
<ide>
<ide> class ShowArticle extends Component {
<ide> />
<ide> ) : null}
<ide> </div>
<add> <Spacer />
<ide> </article>
<ide> );
<ide> } | 1 |
Python | Python | fix flake8 error | 70280db22e87f669c9b142bd0dd1852261cbe94b | <ide><path>libcloud/compute/drivers/packet.py
<ide> def ex_delete_bgp_session(self, session_uuid):
<ide> res = self.connection.request(path, method='DELETE')
<ide> return res.status == httplib.OK # or res.status == httplib.NO_CONTENT
<ide>
<del> def ex_list_events_for_node(self, node, include=None, page=1, per_page=10):
<add> def ex_list_events_for_node(self, node, include=None,
<add> page=1, per_page=10):
<ide> path = '/devices/%s/events' % node.id
<ide> params = {
<ide> 'include': include,
<ide> def ex_list_events_for_project(self, project, include=None, page=1, per_page=10)
<ide> }
<ide> return self.connection.request(path, params=params).object
<ide>
<add>
<ide> class Project(object):
<ide> def __init__(self, project):
<ide> self.id = project.get('id') | 1 |
Ruby | Ruby | request no byte code python when bottling." | f155b0570e97c51a88392b91062f4a74a85b1f1b | <ide><path>Library/Homebrew/extend/ENV/std.rb
<ide> def setup_build_environment(formula=nil)
<ide> self['CMAKE_FRAMEWORK_PATH'] = HOMEBREW_PREFIX/"Frameworks"
<ide> end
<ide>
<del> self['PYTHONDONTWRITEBYTECODE'] = "1" if ARGV.build_bottle?
<del>
<ide> # Os is the default Apple uses for all its stuff so let's trust them
<ide> set_cflags "-Os #{SAFE_CFLAGS_FLAGS}"
<ide>
<ide><path>Library/Homebrew/extend/ENV/super.rb
<ide> def setup_build_environment(formula=nil)
<ide> self['CMAKE_LIBRARY_PATH'] = determine_cmake_library_path
<ide> self['ACLOCAL_PATH'] = determine_aclocal_path
<ide> self['M4'] = MacOS.locate("m4") if deps.include? "autoconf"
<del> self['PYTHONDONTWRITEBYTECODE'] = "1" if ARGV.build_bottle?
<ide>
<ide> # The HOMEBREW_CCCFG ENV variable is used by the ENV/cc tool to control
<ide> # compiler flag stripping. It consists of a string of characters which act | 2 |
Java | Java | implement release of fabricuimanager resources | 8529b1ee913229ba0696399a3132c2bd4034eead | <ide><path>ReactAndroid/src/androidTest/java/com/facebook/react/testing/idledetection/ReactBridgeIdleSignaler.java
<ide> public void onTransitionToBridgeIdle() {
<ide> mBridgeIdleSemaphore.release();
<ide> }
<ide>
<add> @Override
<add> public void onBridgeDestroyed() {
<add> // Do nothing
<add> }
<add>
<ide> @Override
<ide> public void onTransitionToBridgeBusy() {
<ide> mIsBridgeIdle = false;
<ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/CatalystInstanceImpl.java
<ide> public void destroy() {
<ide> @Override
<ide> public void run() {
<ide> mNativeModuleRegistry.notifyJSInstanceDestroy();
<add> mJSIModuleRegistry.notifyJSInstanceDestroy();
<ide> boolean wasIdle = (mPendingJSCalls.getAndSet(0) == 0);
<del> if (!wasIdle && !mBridgeIdleListeners.isEmpty()) {
<add> if (!mBridgeIdleListeners.isEmpty()) {
<ide> for (NotThreadSafeBridgeIdleDebugListener listener : mBridgeIdleListeners) {
<del> listener.onTransitionToBridgeIdle();
<add> if (!wasIdle) {
<add> listener.onTransitionToBridgeIdle();
<add> }
<add> listener.onBridgeDestroyed();
<ide> }
<ide> }
<ide> AsyncTask.execute(
<ide> public void run() {
<ide> // Kill non-UI threads from neutral third party
<ide> // potentially expensive, so don't run on UI thread
<ide>
<del> // contextHolder is used as a lock to guard against other users of the JS VM having
<add> // contextHolder is used as a lock to guard against other users of the JS VM
<add> // having
<ide> // the VM destroyed underneath them, so notify them before we resetNative
<ide> mJavaScriptContextHolder.clear();
<ide>
<ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/JSIModule.java
<ide> * Marker interface used to represent a JSI Module.
<ide> */
<ide> public interface JSIModule {
<add>
<add> /**
<add> * This is called at the end of {@link CatalystApplicationFragment#createCatalystInstance()}
<add> * after the CatalystInstance has been created, in order to initialize NativeModules that require
<add> * the CatalystInstance or JS modules.
<add> */
<add> void initialize();
<add>
<add> /**
<add> * Called before {CatalystInstance#onHostDestroy}
<add> */
<add> void onCatalystInstanceDestroy();
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/JSIModuleHolder.java
<ide> public JSIModule getJSIModule() {
<ide> return mModule;
<ide> }
<ide> mModule = mSpec.getJSIModuleProvider().get();
<add> mModule.initialize();
<ide> }
<ide> }
<ide> return mModule;
<ide> }
<add>
<add> public void notifyJSInstanceDestroy() {
<add> if (mModule != null) {
<add> mModule.onCatalystInstanceDestroy();
<add> }
<add> }
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/JSIModuleRegistry.java
<ide> public void registerModules(List<JSIModuleSpec> jsiModules) {
<ide> }
<ide> }
<ide>
<add> public void notifyJSInstanceDestroy() {
<add> for (JSIModuleHolder moduleHolder : mModules.values()) {
<add> moduleHolder.notifyJSInstanceDestroy();
<add> }
<add> }
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/NotThreadSafeBridgeIdleDebugListener.java
<ide> public interface NotThreadSafeBridgeIdleDebugListener {
<ide> * Called when the bridge was in an idle state and executes a JS call or callback.
<ide> */
<ide> void onTransitionToBridgeBusy();
<add>
<add> /**
<add> * Called when the bridge is destroyed
<add> */
<add> void onBridgeDestroyed();
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManager.java
<ide> import com.facebook.react.modules.i18nmanager.I18nUtil;
<ide> import com.facebook.react.uimanager.DisplayMetricsHolder;
<ide> import com.facebook.react.uimanager.NativeViewHierarchyManager;
<del>import com.facebook.react.uimanager.OnLayoutEvent;
<ide> import com.facebook.react.uimanager.ReactRootViewTagGenerator;
<ide> import com.facebook.react.uimanager.ReactShadowNode;
<ide> import com.facebook.react.uimanager.ReactShadowNodeImpl;
<ide> public FabricUIManager(
<ide> mFabricReconciler = new FabricReconciler(mUIViewOperationQueue);
<ide> mEventDispatcher = eventDispatcher;
<ide> mJSContext = jsContext;
<del>
<del> FabricEventEmitter eventEmitter =
<del> new FabricEventEmitter(reactContext, this);
<del> eventDispatcher.registerEventEmitter(FABRIC, eventEmitter);
<ide> }
<ide>
<ide> public void setBinding(FabricBinding binding) {
<ide> public void invoke(long eventTarget, String name, WritableMap params) {
<ide> mBinding.dispatchEventToTarget(mJSContext.get(), mEventHandlerPointer, eventTarget, name, (WritableNativeMap) params);
<ide> }
<ide>
<add> @Override
<add> public void initialize() {
<add> FabricEventEmitter eventEmitter =
<add> new FabricEventEmitter(mReactApplicationContext, this);
<add> mEventDispatcher.registerEventEmitter(FABRIC, eventEmitter);
<add> }
<add>
<add> @Override
<add> public void onCatalystInstanceDestroy() {
<add> mBinding.releaseEventHandler(mJSContext.get(), mEventHandlerPointer);
<add> }
<add>
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/modules/debug/DidJSUpdateUiDuringFrameDetector.java
<ide> public synchronized void onTransitionToBridgeBusy() {
<ide> mTransitionToBusyEvents.add(System.nanoTime());
<ide> }
<ide>
<add> @Override
<add> public synchronized void onBridgeDestroyed() {
<add> // do nothing
<add> }
<add>
<ide> @Override
<ide> public synchronized void onViewHierarchyUpdateEnqueued() {
<ide> mViewHierarchyUpdateEnqueuedEvents.add(System.nanoTime()); | 8 |
Ruby | Ruby | add ordinalize to fixnum and bignum instances | dba6b8b46f93ed0116755bea17cfbce7ca6d7c72 | <ide><path>activesupport/lib/active_support/core_ext/fixnum.rb
<ide> require File.dirname(__FILE__) + '/fixnum/even_odd'
<add>require File.dirname(__FILE__) + '/fixnum/inflections'
<ide>
<ide> class Fixnum #:nodoc:
<ide> include ActiveSupport::CoreExtensions::Fixnum::EvenOdd
<add> include ActiveSupport::CoreExtensions::Fixnum::Inflections
<ide> end
<ide>
<ide> class Bignum #:nodoc:
<ide> include ActiveSupport::CoreExtensions::Fixnum::EvenOdd
<add> include ActiveSupport::CoreExtensions::Fixnum::Inflections
<ide> end
<ide>\ No newline at end of file
<ide><path>activesupport/test/core_ext/fixnum_ext_test.rb
<ide> def test_multiple_of
<ide> assert !22953686867719691230002707821868552601124472329079.multiple_of?(5)
<ide> assert !22953686867719691230002707821868552601124472329079.multiple_of?(7)
<ide> end
<add>
<add> def test_ordinalize
<add> # These tests are mostly just to ensure that the ordinalize method exists
<add> # It's results are tested comprehensively in the inflector test cases.
<add> assert_equal '1st', 1.ordinalize
<add> assert_equal '8th', 8.ordinalize
<add> end
<ide> end | 2 |
Javascript | Javascript | improve coverage for readline.interface | f51c44d32560439f214c4594bb2f8242ca1789a2 | <ide><path>test/parallel/test-readline-interface.js
<ide> function isWarned(emitter) {
<ide> rli.close();
<ide> }
<ide>
<add> {
<add> // Back and Forward one character
<add> const fi = new FakeInput();
<add> const rli = new readline.Interface({
<add> input: fi,
<add> output: fi,
<add> prompt: '',
<add> terminal: terminal
<add> });
<add> fi.emit('data', 'the quick brown fox');
<add> let cursorPos = rli._getCursorPos();
<add> assert.strictEqual(cursorPos.rows, 0);
<add> assert.strictEqual(cursorPos.cols, 19);
<add>
<add> // Back one character
<add> fi.emit('keypress', '.', { ctrl: true, name: 'b' });
<add> cursorPos = rli._getCursorPos();
<add> assert.strictEqual(cursorPos.rows, 0);
<add> assert.strictEqual(cursorPos.cols, 18);
<add> // Back one character
<add> fi.emit('keypress', '.', { ctrl: true, name: 'b' });
<add> cursorPos = rli._getCursorPos();
<add> assert.strictEqual(cursorPos.rows, 0);
<add> assert.strictEqual(cursorPos.cols, 17);
<add> // Forward one character
<add> fi.emit('keypress', '.', { ctrl: true, name: 'f' });
<add> cursorPos = rli._getCursorPos();
<add> assert.strictEqual(cursorPos.rows, 0);
<add> assert.strictEqual(cursorPos.cols, 18);
<add> // Forward one character
<add> fi.emit('keypress', '.', { ctrl: true, name: 'f' });
<add> cursorPos = rli._getCursorPos();
<add> assert.strictEqual(cursorPos.rows, 0);
<add> assert.strictEqual(cursorPos.cols, 19);
<add> rli.close();
<add> }
<add>
<ide> {
<ide> // `wordLeft` and `wordRight`
<ide> const fi = new FakeInput();
<ide> function isWarned(emitter) {
<ide> });
<ide> }
<ide>
<add> // deleteLeft
<add> {
<add> const fi = new FakeInput();
<add> const rli = new readline.Interface({
<add> input: fi,
<add> output: fi,
<add> prompt: '',
<add> terminal: terminal
<add> });
<add> fi.emit('data', 'the quick brown fox');
<add> let cursorPos = rli._getCursorPos();
<add> assert.strictEqual(cursorPos.rows, 0);
<add> assert.strictEqual(cursorPos.cols, 19);
<add>
<add> // Delete left character
<add> fi.emit('keypress', '.', { ctrl: true, name: 'h' });
<add> cursorPos = rli._getCursorPos();
<add> assert.strictEqual(cursorPos.rows, 0);
<add> assert.strictEqual(cursorPos.cols, 18);
<add> rli.on('line', common.mustCall((line) => {
<add> assert.strictEqual(line, 'the quick brown fo');
<add> }));
<add> fi.emit('data', '\n');
<add> rli.close();
<add> }
<add>
<add> // deleteRight
<add> {
<add> const fi = new FakeInput();
<add> const rli = new readline.Interface({
<add> input: fi,
<add> output: fi,
<add> prompt: '',
<add> terminal: terminal
<add> });
<add> fi.emit('data', 'the quick brown fox');
<add>
<add> // Go to the start of the line
<add> fi.emit('keypress', '.', { ctrl: true, name: 'a' });
<add> let cursorPos = rli._getCursorPos();
<add> assert.strictEqual(cursorPos.rows, 0);
<add> assert.strictEqual(cursorPos.cols, 0);
<add>
<add> // Delete right character
<add> fi.emit('keypress', '.', { ctrl: true, name: 'd' });
<add> cursorPos = rli._getCursorPos();
<add> assert.strictEqual(cursorPos.rows, 0);
<add> assert.strictEqual(cursorPos.cols, 0);
<add> rli.on('line', common.mustCall((line) => {
<add> assert.strictEqual(line, 'he quick brown fox');
<add> }));
<add> fi.emit('data', '\n');
<add> rli.close();
<add> }
<add>
<add>
<add> // deleteLineLeft
<add> {
<add> const fi = new FakeInput();
<add> const rli = new readline.Interface({
<add> input: fi,
<add> output: fi,
<add> prompt: '',
<add> terminal: terminal
<add> });
<add> fi.emit('data', 'the quick brown fox');
<add> let cursorPos = rli._getCursorPos();
<add> assert.strictEqual(cursorPos.rows, 0);
<add> assert.strictEqual(cursorPos.cols, 19);
<add>
<add> // Delete from current to start of line
<add> fi.emit('keypress', '.', { ctrl: true, shift: true, name: 'backspace' });
<add> cursorPos = rli._getCursorPos();
<add> assert.strictEqual(cursorPos.rows, 0);
<add> assert.strictEqual(cursorPos.cols, 0);
<add> rli.on('line', common.mustCall((line) => {
<add> assert.strictEqual(line, '');
<add> }));
<add> fi.emit('data', '\n');
<add> rli.close();
<add> }
<add>
<add> // deleteLineRight
<add> {
<add> const fi = new FakeInput();
<add> const rli = new readline.Interface({
<add> input: fi,
<add> output: fi,
<add> prompt: '',
<add> terminal: terminal
<add> });
<add> fi.emit('data', 'the quick brown fox');
<add>
<add> // Go to the start of the line
<add> fi.emit('keypress', '.', { ctrl: true, name: 'a' });
<add> let cursorPos = rli._getCursorPos();
<add> assert.strictEqual(cursorPos.rows, 0);
<add> assert.strictEqual(cursorPos.cols, 0);
<add>
<add> // Delete from current to end of line
<add> fi.emit('keypress', '.', { ctrl: true, shift: true, name: 'delete' });
<add> cursorPos = rli._getCursorPos();
<add> assert.strictEqual(cursorPos.rows, 0);
<add> assert.strictEqual(cursorPos.cols, 0);
<add> rli.on('line', common.mustCall((line) => {
<add> assert.strictEqual(line, '');
<add> }));
<add> fi.emit('data', '\n');
<add> rli.close();
<add> }
<add>
<ide> // multi-line cursor position
<ide> {
<ide> const fi = new FakeInput();
<ide> function isWarned(emitter) {
<ide> const cursorPos = rli._getCursorPos();
<ide> assert.strictEqual(cursorPos.rows, 1);
<ide> assert.strictEqual(cursorPos.cols, 5);
<add> rli.close();
<add> }
<add>
<add> // Clear the whole screen
<add> {
<add> const fi = new FakeInput();
<add> const rli = new readline.Interface({
<add> input: fi,
<add> output: fi,
<add> prompt: '',
<add> terminal: terminal
<add> });
<add> const lines = ['line 1', 'line 2', 'line 3'];
<add> fi.emit('data', lines.join('\n'));
<add> fi.emit('keypress', '.', { ctrl: true, name: 'l' });
<add> const cursorPos = rli._getCursorPos();
<add> assert.strictEqual(cursorPos.rows, 0);
<add> assert.strictEqual(cursorPos.cols, 6);
<add> rli.on('line', common.mustCall((line) => {
<add> assert.strictEqual(line, 'line 3');
<add> }));
<add> fi.emit('data', '\n');
<add> rli.close();
<ide> }
<ide> }
<ide> | 1 |
Go | Go | fix bug in engine.sender | 9236e088eb5a9a6d662b08ef7983dbecf01e6ef0 | <ide><path>engine/remote.go
<ide> func (s *Sender) Handle(job *Job) Status {
<ide> var status int
<ide> r.NewRoute().KeyStartsWith("cmd", "status").Handler(func(p []byte, f *os.File) error {
<ide> cmd := data.Message(p).Get("cmd")
<del> if len(cmd) != 3 {
<add> if len(cmd) != 2 {
<ide> return fmt.Errorf("usage: %s <0-127>", cmd[0])
<ide> }
<del> s, err := strconv.ParseUint(cmd[2], 10, 8)
<add> s, err := strconv.ParseUint(cmd[1], 10, 8)
<ide> if err != nil {
<ide> return fmt.Errorf("usage: %s <0-127>", cmd[0])
<ide> } | 1 |
PHP | PHP | add throttlesexceptionswithredis job middleware | 35071ab6ec3c906c0f26d153e743770e8df86079 | <ide><path>src/Illuminate/Queue/Middleware/ThrottlesExceptionsWithRedis.php
<add><?php
<add>
<add>namespace Illuminate\Queue\Middleware;
<add>
<add>use Illuminate\Container\Container;
<add>use Illuminate\Contracts\Redis\Factory as Redis;
<add>use Illuminate\Redis\Limiters\DurationLimiter;
<add>use Illuminate\Support\InteractsWithTime;
<add>use Throwable;
<add>
<add>class ThrottlesExceptionsWithRedis extends ThrottlesExceptions
<add>{
<add> use InteractsWithTime;
<add>
<add> /**
<add> * The Redis factory implementation.
<add> *
<add> * @var \Illuminate\Contracts\Redis\Factory
<add> */
<add> protected $redis;
<add>
<add> /**
<add> * The rate limiter instance.
<add> *
<add> * @var \Illuminate\Redis\Limiters\DurationLimiter
<add> */
<add> protected $limiter;
<add>
<add> /**
<add> * Process the job.
<add> *
<add> * @param mixed $job
<add> * @param callable $next
<add> * @return mixed
<add> */
<add> public function handle($job, $next)
<add> {
<add> $this->redis = Container::getInstance()->make(Redis::class);
<add>
<add> $this->limiter = new DurationLimiter(
<add> $this->redis, $this->getKey($job), $this->maxAttempts, $this->decayMinutes * 60
<add> );
<add>
<add> if ($this->limiter->tooManyAttempts()) {
<add> return $job->release($this->limiter->decaysAt - $this->currentTime());
<add> }
<add>
<add> try {
<add> $next($job);
<add>
<add> $this->limiter->clear();
<add> } catch (Throwable $throwable) {
<add> if ($this->whenCallback && ! call_user_func($this->whenCallback, $throwable)) {
<add> throw $throwable;
<add> }
<add>
<add> $this->limiter->acquire();
<add>
<add> return $job->release($this->retryAfterMinutes * 60);
<add> }
<add> }
<add>}
<ide><path>src/Illuminate/Redis/Limiters/DurationLimiter.php
<ide> public function acquire()
<ide> return (bool) $results[0];
<ide> }
<ide>
<add> /**
<add> * Determine if the key has been "accessed" too many times.
<add> *
<add> * @return bool
<add> */
<add> public function tooManyAttempts()
<add> {
<add> [$this->decaysAt, $this->remaining] = $this->redis->eval(
<add> $this->tooManyAttemptsScript(), 1, $this->name, microtime(true), time(), $this->decay, $this->maxLocks
<add> );
<add>
<add> return $this->remaining <= 0;
<add> }
<add>
<add> /**
<add> * Clear the limiter.
<add> *
<add> * @return void
<add> */
<add> public function clear()
<add> {
<add> $this->redis->del($this->name);
<add> }
<add>
<ide> /**
<ide> * Get the Lua script for acquiring a lock.
<ide> *
<ide> protected function luaScript()
<ide> end
<ide>
<ide> return {reset(), ARGV[2] + ARGV[3], ARGV[4] - 1}
<add>LUA;
<add> }
<add>
<add> /**
<add> * Get the Lua script to determine if the key has been "accessed" too many times.
<add> *
<add> * KEYS[1] - The limiter name
<add> * ARGV[1] - Current time in microseconds
<add> * ARGV[2] - Current time in seconds
<add> * ARGV[3] - Duration of the bucket
<add> * ARGV[4] - Allowed number of tasks
<add> *
<add> * @return string
<add> */
<add> protected function tooManyAttemptsScript()
<add> {
<add> return <<<'LUA'
<add>
<add>if redis.call('EXISTS', KEYS[1]) == 0 then
<add> return {0, ARGV[2] + ARGV[3]}
<add>end
<add>
<add>if ARGV[1] >= redis.call('HGET', KEYS[1], 'start') and ARGV[1] <= redis.call('HGET', KEYS[1], 'end') then
<add> return {
<add> redis.call('HGET', KEYS[1], 'end'),
<add> ARGV[4] - redis.call('HGET', KEYS[1], 'count')
<add> }
<add>end
<add>
<add>return {0, ARGV[2] + ARGV[3]}
<ide> LUA;
<ide> }
<ide> }
<ide><path>tests/Integration/Queue/ThrottlesExceptionsWithRedisTest.php
<add><?php
<add>
<add>namespace Illuminate\Tests\Integration\Queue;
<add>
<add>use Exception;
<add>use Illuminate\Bus\Dispatcher;
<add>use Illuminate\Bus\Queueable;
<add>use Illuminate\Contracts\Queue\Job;
<add>use Illuminate\Foundation\Testing\Concerns\InteractsWithRedis;
<add>use Illuminate\Queue\CallQueuedHandler;
<add>use Illuminate\Queue\InteractsWithQueue;
<add>use Illuminate\Queue\Middleware\ThrottlesExceptionsWithRedis;
<add>use Illuminate\Support\Str;
<add>use Mockery as m;
<add>use Orchestra\Testbench\TestCase;
<add>
<add>/**
<add> * @group integration
<add> */
<add>class ThrottlesExceptionsWithRedisTest extends TestCase
<add>{
<add> use InteractsWithRedis;
<add>
<add> protected function setUp(): void
<add> {
<add> parent::setUp();
<add>
<add> $this->setUpRedis();
<add> }
<add>
<add> protected function tearDown(): void
<add> {
<add> parent::tearDown();
<add>
<add> $this->tearDownRedis();
<add>
<add> m::close();
<add> }
<add>
<add> public function testCircuitIsOpenedForJobErrors()
<add> {
<add> $this->assertJobWasReleasedImmediately(CircuitBreakerWithRedisTestJob::class, $key = Str::random());
<add> $this->assertJobWasReleasedImmediately(CircuitBreakerWithRedisTestJob::class, $key);
<add> $this->assertJobWasReleasedWithDelay(CircuitBreakerWithRedisTestJob::class, $key);
<add> }
<add>
<add> public function testCircuitStaysClosedForSuccessfulJobs()
<add> {
<add> $this->assertJobRanSuccessfully(CircuitBreakerWithRedisSuccessfulJob::class, $key = Str::random());
<add> $this->assertJobRanSuccessfully(CircuitBreakerWithRedisSuccessfulJob::class, $key);
<add> $this->assertJobRanSuccessfully(CircuitBreakerWithRedisSuccessfulJob::class, $key);
<add> }
<add>
<add> public function testCircuitResetsAfterSuccess()
<add> {
<add> $this->assertJobWasReleasedImmediately(CircuitBreakerWithRedisTestJob::class, $key = Str::random());
<add> $this->assertJobRanSuccessfully(CircuitBreakerWithRedisSuccessfulJob::class, $key);
<add> $this->assertJobWasReleasedImmediately(CircuitBreakerWithRedisTestJob::class, $key);
<add> $this->assertJobWasReleasedImmediately(CircuitBreakerWithRedisTestJob::class, $key);
<add> $this->assertJobWasReleasedWithDelay(CircuitBreakerWithRedisTestJob::class, $key);
<add> }
<add>
<add> protected function assertJobWasReleasedImmediately($class, $key)
<add> {
<add> $class::$handled = false;
<add> $instance = new CallQueuedHandler(new Dispatcher($this->app), $this->app);
<add>
<add> $job = m::mock(Job::class);
<add>
<add> $job->shouldReceive('hasFailed')->once()->andReturn(false);
<add> $job->shouldReceive('release')->with(0)->once();
<add> $job->shouldReceive('isReleased')->andReturn(true);
<add> $job->shouldReceive('isDeletedOrReleased')->once()->andReturn(true);
<add>
<add> $instance->call($job, [
<add> 'command' => serialize($command = new $class($key)),
<add> ]);
<add>
<add> $this->assertTrue($class::$handled);
<add> }
<add>
<add> protected function assertJobWasReleasedWithDelay($class, $key)
<add> {
<add> $class::$handled = false;
<add> $instance = new CallQueuedHandler(new Dispatcher($this->app), $this->app);
<add>
<add> $job = m::mock(Job::class);
<add>
<add> $job->shouldReceive('hasFailed')->once()->andReturn(false);
<add> $job->shouldReceive('release')->withArgs(function ($delay) {
<add> return $delay >= 600;
<add> })->once();
<add> $job->shouldReceive('isReleased')->andReturn(true);
<add> $job->shouldReceive('isDeletedOrReleased')->once()->andReturn(true);
<add>
<add> $instance->call($job, [
<add> 'command' => serialize($command = new $class($key)),
<add> ]);
<add>
<add> $this->assertFalse($class::$handled);
<add> }
<add>
<add> protected function assertJobRanSuccessfully($class, $key)
<add> {
<add> $class::$handled = false;
<add> $instance = new CallQueuedHandler(new Dispatcher($this->app), $this->app);
<add>
<add> $job = m::mock(Job::class);
<add>
<add> $job->shouldReceive('hasFailed')->once()->andReturn(false);
<add> $job->shouldReceive('isReleased')->andReturn(false);
<add> $job->shouldReceive('isDeletedOrReleased')->once()->andReturn(false);
<add> $job->shouldReceive('delete')->once();
<add>
<add> $instance->call($job, [
<add> 'command' => serialize($command = new $class($key)),
<add> ]);
<add>
<add> $this->assertTrue($class::$handled);
<add> }
<add>}
<add>
<add>class CircuitBreakerWithRedisTestJob
<add>{
<add> use InteractsWithQueue, Queueable;
<add>
<add> public static $handled = false;
<add>
<add> public function __construct($key)
<add> {
<add> $this->key = $key;
<add> }
<add>
<add> public function handle()
<add> {
<add> static::$handled = true;
<add>
<add> throw new Exception;
<add> }
<add>
<add> public function middleware()
<add> {
<add> return [new ThrottlesExceptionsWithRedis(2, 10, 0, $this->key)];
<add> }
<add>}
<add>
<add>class CircuitBreakerWithRedisSuccessfulJob
<add>{
<add> use InteractsWithQueue, Queueable;
<add>
<add> public static $handled = false;
<add>
<add> public function __construct($key)
<add> {
<add> $this->key = $key;
<add> }
<add>
<add> public function handle()
<add> {
<add> static::$handled = true;
<add> }
<add>
<add> public function middleware()
<add> {
<add> return [new ThrottlesExceptionsWithRedis(2, 10, 0, $this->key)];
<add> }
<add>} | 3 |
Ruby | Ruby | handle redirects in get_content_details | 5e9057500419d1a2b41efe784e9f12ae232e7f6e | <ide><path>Library/Homebrew/dev-cmd/audit.rb
<ide> def problem(text)
<ide> def get_content_details(url)
<ide> out = {}
<ide> output, = curl_output "--connect-timeout", "15", "--include", url
<del> split = output.partition("\r\n\r\n")
<del> headers = split.first
<del> out[:status] = headers[%r{HTTP\/.* (\d+)}, 1]
<add> status_code = :unknown
<add> while status_code == :unknown || status_code.to_s.start_with?("3")
<add> headers, _, output = output.partition("\r\n\r\n")
<add> status_code = headers[%r{HTTP\/.* (\d+)}, 1]
<add> end
<add>
<add> out[:status] = status_code
<ide> out[:etag] = headers[%r{ETag: ([wW]\/)?"(([^"]|\\")*)"}, 2]
<ide> out[:content_length] = headers[/Content-Length: (\d+)/, 1]
<del> out[:file_hash] = Digest::SHA256.digest split.last
<add> out[:file_hash] = Digest::SHA256.digest output
<ide> out
<ide> end
<ide> end | 1 |
Ruby | Ruby | require clt headers on 10.14 | e5212d74a6166b1c84bcc32910705da89cc1a95b | <ide><path>Library/Homebrew/extend/os/mac/diagnostic.rb
<ide> def fatal_development_tools_checks
<ide> check_xcode_minimum_version
<ide> check_clt_minimum_version
<ide> check_if_xcode_needs_clt_installed
<add> check_if_clt_needs_headers_installed
<ide> ].freeze
<ide> end
<ide>
<ide> def check_if_xcode_needs_clt_installed
<ide> EOS
<ide> end
<ide>
<add> def check_if_clt_needs_headers_installed
<add> return unless MacOS::CLT.separate_header_package?
<add> return if MacOS::CLT.headers_installed?
<add>
<add> <<~EOS
<add> The Command Line Tools header package must be installed on #{MacOS.version.pretty_name}.
<add> The installer is located at:
<add> #{MacOS::CLT::HEADER_PKG_PATH.sub(":macos_version", MacOS.version)}
<add> EOS
<add> end
<add>
<ide> def check_for_other_package_managers
<ide> ponk = MacOS.macports_or_fink
<ide> return if ponk.empty?
<ide><path>Library/Homebrew/test/os/mac/diagnostic_spec.rb
<ide> .to match("Xcode alone is not sufficient on El Capitan")
<ide> end
<ide>
<add> specify "#check_if_clt_needs_headers_installed" do
<add> allow(MacOS).to receive(:version).and_return(OS::Mac::Version.new("10.14"))
<add> allow(MacOS::CLT).to receive(:installed?).and_return(true)
<add> allow(MacOS::CLT).to receive(:headers_installed?).and_return(false)
<add>
<add> expect(subject.check_if_clt_needs_headers_installed)
<add> .to match("The Command Line Tools header package must be installed on Mojave.")
<add>
<add> allow(MacOS).to receive(:version).and_return(OS::Mac::Version.new("10.13"))
<add> expect(subject.check_if_clt_needs_headers_installed)
<add> .to be_nil
<add> end
<add>
<ide> specify "#check_homebrew_prefix" do
<ide> # the integration tests are run in a special prefix
<ide> expect(subject.check_homebrew_prefix) | 2 |
Java | Java | fix concat breaks with double oncompleted | cade58c419cc3877ad55d2aaa2241723531a26ce | <ide><path>src/main/java/rx/internal/operators/OperatorConcat.java
<ide> void subscribeNext() {
<ide>
<ide> private final Subscriber<T> child;
<ide> private final ConcatSubscriber<T> parent;
<add> @SuppressWarnings("unused")
<add> private volatile int once = 0;
<add> @SuppressWarnings("rawtypes")
<add> private final static AtomicIntegerFieldUpdater<ConcatInnerSubscriber> ONCE_UPDATER = AtomicIntegerFieldUpdater.newUpdater(ConcatInnerSubscriber.class, "once");
<ide>
<ide> public ConcatInnerSubscriber(ConcatSubscriber<T> parent, Subscriber<T> child, long initialRequest) {
<ide> this.parent = parent;
<ide> public void onNext(T t) {
<ide>
<ide> @Override
<ide> public void onError(Throwable e) {
<del> // terminal error through parent so everything gets cleaned up, including this inner
<del> parent.onError(e);
<add> if (ONCE_UPDATER.compareAndSet(this, 0, 1)) {
<add> // terminal error through parent so everything gets cleaned up, including this inner
<add> parent.onError(e);
<add> }
<ide> }
<ide>
<ide> @Override
<ide> public void onCompleted() {
<del> // terminal completion to parent so it continues to the next
<del> parent.completeInner();
<add> if (ONCE_UPDATER.compareAndSet(this, 0, 1)) {
<add> // terminal completion to parent so it continues to the next
<add> parent.completeInner();
<add> }
<ide> }
<ide>
<ide> };
<ide><path>src/test/java/rx/internal/operators/OperatorConcatTest.java
<ide> public void testInnerBackpressureWithoutAlignedBoundaries() {
<ide> ts.assertNoErrors();
<ide> assertEquals((RxRingBuffer.SIZE * 4) + 20, ts.getOnNextEvents().size());
<ide> }
<add>
<add> // https://github.com/ReactiveX/RxJava/issues/1818
<add> @Test
<add> public void testConcatWithNonCompliantSourceDoubleOnComplete() {
<add> Observable<String> o = Observable.create(new OnSubscribe<String>() {
<add>
<add> @Override
<add> public void call(Subscriber<? super String> s) {
<add> s.onNext("hello");
<add> s.onCompleted();
<add> s.onCompleted();
<add> }
<add>
<add> });
<add>
<add> TestSubscriber<String> ts = new TestSubscriber<String>();
<add> Observable.concat(o, o).subscribe(ts);
<add> ts.awaitTerminalEvent(500, TimeUnit.MILLISECONDS);
<add> ts.assertTerminalEvent();
<add> ts.assertNoErrors();
<add> ts.assertReceivedOnNext(Arrays.asList("hello", "hello"));
<add> }
<ide>
<ide> } | 2 |
Text | Text | add 2.18.0-beta.4 to the changelog | 27a8df9c5916795c869e985fafcab69bb67af01e | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### 2.18.0-beta.4 (December 19, 2017)
<add>- [#15982](https://github.com/emberjs/ember.js/pull/15982) [BUGFIX] Fix issue with unchaining ChainNodes (again)
<add>
<ide> ### 2.18.0-beta.3 (December 12, 2017)
<ide>
<ide> - [#15924](https://github.com/emberjs/ember.js/pull/15924) / [#15940](https://github.com/emberjs/ember.js/pull/15940) [BUGFIX] Assert that `classNameBinding` items are non-empty strings | 1 |
PHP | PHP | fix code style | 96d9ac521de59de99c83c56b8a64067cdbf3b038 | <ide><path>src/Illuminate/Database/Eloquent/Collection.php
<ide> public function getQueueableConnection()
<ide> }
<ide>
<ide> /**
<del> * Get the Eloquent query builder from the collection
<add> * Get the Eloquent query builder from the collection.
<ide> *
<ide> * @return Illuminate\Database\Eloquen\Builder
<ide> * | 1 |
Python | Python | add ex_clone_node method to vsphere driver | 106846bf67ce8ccb04befdeaf90408b425852c18 | <ide><path>libcloud/compute/drivers/vsphere.py
<ide> def list_nodes(self):
<ide>
<ide> return nodes
<ide>
<add> @wrap_non_libcloud_exceptions
<add> def ex_clone_node(self, node, name, power_on=True, template=False):
<add> """
<add> Clone the provided node.
<add>
<add> :param node: Node to clone.
<add> :type node: :class:`Node`
<add>
<add> :param name: Name of the new node.
<add> :type name: ``str``
<add>
<add> :param power_on: Power the new node on after being created.
<add> :type power_on: ``bool``
<add>
<add> :param template: Specifies whether or not the new virtual machine
<add> should be marked as a template.
<add> :type template: ``bool``
<add>
<add> :return: New node.
<add> :rtype: :class:`Node`
<add> """
<add> vm = self._get_vm_for_node(node=node)
<add> new_vm = vm.clone(name=name, power_on=power_on, template=template)
<add> new_node = self._to_node(vm=new_vm)
<add>
<add> return new_node
<add>
<ide> @wrap_non_libcloud_exceptions
<ide> def reboot_node(self, node):
<ide> vm = self._get_vm_for_node(node=node) | 1 |
Python | Python | replace main_session with @provide_session | 8af779ac9d5baa8164152d9dd27d4e4194e7f3ce | <ide><path>airflow/models.py
<ide> def mark_success_url(self):
<ide> "&downstream=false"
<ide> ).format(**locals())
<ide>
<del> def current_state(self, main_session=None):
<add> @provide_session
<add> def current_state(self, session=None):
<ide> """
<ide> Get the very latest state from the database, if a session is passed,
<ide> we use and looking up the state becomes part of the session, otherwise
<ide> a new session is used.
<ide> """
<del> session = main_session or settings.Session()
<ide> TI = TaskInstance
<ide> ti = session.query(TI).filter(
<ide> TI.dag_id == self.dag_id,
<ide> def current_state(self, main_session=None):
<ide> state = ti[0].state
<ide> else:
<ide> state = None
<del> if not main_session:
<del> session.commit()
<del> session.close()
<ide> return state
<ide>
<del> def error(self, main_session=None):
<add> @provide_session
<add> def error(self, session=None):
<ide> """
<ide> Forces the task instance's state to FAILED in the database.
<ide> """
<del> session = settings.Session()
<ide> logging.error("Recording the task instance as FAILED")
<ide> self.state = State.FAILED
<ide> session.merge(self)
<ide> session.commit()
<del> session.close()
<ide>
<del> def refresh_from_db(self, main_session=None):
<add> @provide_session
<add> def refresh_from_db(self, session=None):
<ide> """
<ide> Refreshes the task instance from the database based on the primary key
<ide> """
<del> session = main_session or settings.Session()
<ide> TI = TaskInstance
<ide> ti = session.query(TI).filter(
<ide> TI.dag_id == self.dag_id,
<ide> def refresh_from_db(self, main_session=None):
<ide> else:
<ide> self.state = None
<ide>
<del> if not main_session:
<del> session.commit()
<del> session.close()
<del>
<ide> @property
<ide> def key(self):
<ide> """
<ide> def is_runnable(self, flag_upstream_failed=False):
<ide> """
<ide> return self.is_queueable(flag_upstream_failed) and not self.pool_full()
<ide>
<del> def are_dependents_done(self, main_session=None):
<add> @provide_session
<add> def are_dependents_done(self, session=None):
<ide> """
<ide> Checks whether the dependents of this task instance have all succeeded.
<ide> This is meant to be used by wait_for_downstream.
<ide> def are_dependents_done(self, main_session=None):
<ide> schedule of a task until the dependents are done. For instance,
<ide> if the task DROPs and recreates a table.
<ide> """
<del> session = main_session or settings.Session()
<ide> task = self.task
<ide>
<ide> if not task._downstream_list:
<ide> def are_dependents_done(self, main_session=None):
<ide> TaskInstance.state == State.SUCCESS,
<ide> )
<ide> count = ti[0][0]
<del> if not main_session:
<del> session.commit()
<del> session.close()
<ide> return count == len(task._downstream_list)
<ide>
<add> @provide_session
<ide> def are_dependencies_met(
<del> self, main_session=None, flag_upstream_failed=False,
<add> self, session=None, flag_upstream_failed=False,
<ide> verbose=False):
<ide> """
<ide> Returns a boolean on whether the upstream tasks are in a SUCCESS state
<ide> def are_dependencies_met(
<ide> TI = TaskInstance
<ide> TR = TriggerRule
<ide>
<del> # Using the session if passed as param
<del> session = main_session or settings.Session()
<ide> task = self.task
<ide>
<ide> # Checking that the depends_on_past is fulfilled
<ide> def are_dependencies_met(
<ide> # Applying wait_for_downstream
<ide> previous_ti.task = self.task
<ide> if task.wait_for_downstream and not \
<del> previous_ti.are_dependents_done(session):
<add> previous_ti.are_dependents_done(session=session):
<ide> if verbose:
<ide> logging.warning("wait_for_downstream not satisfied")
<ide> return False
<ide> def are_dependencies_met(
<ide> ):
<ide> return True
<ide>
<del> if not main_session:
<del> session.commit()
<del> session.close()
<add> session.commit()
<ide> if verbose:
<ide> logging.warning("Trigger rule `{}` not satisfied".format(tr))
<ide> return False | 1 |
Ruby | Ruby | maintain original encoding from path | 8607c25ba7810573733d9b37d0015154ba059f5e | <ide><path>actionpack/lib/action_dispatch/journey/router/utils.rb
<ide> class Utils # :nodoc:
<ide> # normalize_path("") # => "/"
<ide> # normalize_path("/%ab") # => "/%AB"
<ide> def self.normalize_path(path)
<add> encoding = path.encoding
<ide> path = "/#{path}"
<ide> path.squeeze!("/".freeze)
<ide> path.sub!(%r{/+\Z}, "".freeze)
<ide> path.gsub!(/(%[a-f0-9]{2})/) { $1.upcase }
<ide> path = "/" if path == "".freeze
<add> path.force_encoding(encoding)
<ide> path
<ide> end
<ide>
<ide><path>actionpack/test/journey/router/utils_test.rb
<ide> def test_normalize_path_not_greedy
<ide> def test_normalize_path_uppercase
<ide> assert_equal "/foo%AAbar%AAbaz", Utils.normalize_path("/foo%aabar%aabaz")
<ide> end
<add>
<add> def test_normalize_path_maintains_string_encoding
<add> path = "/foo%AAbar%AAbaz".b
<add> assert_equal Encoding::ASCII_8BIT, Utils.normalize_path(path).encoding
<add> end
<ide> end
<ide> end
<ide> end | 2 |
Text | Text | clarify fallback behavior of module require | 594dd4242b99824d44b2b0f17421fa86c10f1d12 | <ide><path>doc/api/modules.md
<ide> If this was in a folder at `./some-library`, then
<ide>
<ide> This is the extent of Node.js's awareness of `package.json` files.
<ide>
<del>If the file specified by the `'main'` entry of `package.json` is missing and
<del>can not be resolved, Node.js will report the entire module as missing with the
<del>default error:
<del>
<del>```txt
<del>Error: Cannot find module 'some-library'
<del>```
<del>
<del>If there is no `package.json` file present in the directory, then Node.js
<add>If there is no `package.json` file present in the directory, or if the
<add>`'main'` entry is missing or cannot be resolved, then Node.js
<ide> will attempt to load an `index.js` or `index.node` file out of that
<ide> directory. For example, if there was no `package.json` file in the above
<ide> example, then `require('./some-library')` would attempt to load:
<ide>
<ide> * `./some-library/index.js`
<ide> * `./some-library/index.node`
<ide>
<add>If these attempts fail, then Node.js will report the entire module as missing
<add>with the default error:
<add>
<add>```txt
<add>Error: Cannot find module 'some-library'
<add>```
<add>
<ide> ## Loading from `node_modules` Folders
<ide>
<ide> <!--type=misc--> | 1 |
Mixed | Javascript | add support for <dialog> tag's open attribute | ffa0447177987398c4089eab85b44c59cfc4b25d | <ide><path>docs/docs/ref-04-tags-and-attributes.md
<ide> className cols colSpan content contentEditable contextMenu controls coords
<ide> crossOrigin data dateTime defer dir disabled download draggable encType form
<ide> formNoValidate frameBorder height hidden href hrefLang htmlFor httpEquiv icon
<ide> id label lang list loop max maxLength mediaGroup method min multiple muted
<del>name noValidate pattern placeholder poster preload radioGroup readOnly rel
<add>name noValidate open pattern placeholder poster preload radioGroup readOnly rel
<ide> required role rows rowSpan sandbox scope scrollLeft scrolling scrollTop
<ide> seamless selected shape size span spellCheck src srcDoc srcSet start step
<ide> style tabIndex target title type useMap value width wmode
<ide><path>src/browser/ui/dom/HTMLDOMPropertyConfig.js
<ide> var HTMLDOMPropertyConfig = {
<ide> muted: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
<ide> name: null,
<ide> noValidate: HAS_BOOLEAN_VALUE,
<add> open: null,
<ide> pattern: null,
<ide> placeholder: null,
<ide> poster: null, | 2 |
PHP | PHP | adjust initialization of $fixtures | c08505a40bbdcfbe062c81dfbac3ffc190a9ec9e | <ide><path>src/TestSuite/TestCase.php
<ide> abstract class TestCase extends BaseTestCase
<ide> /**
<ide> * Fixtures used by this test case.
<ide> *
<del> * @var array|string
<add> * @var array|string|null
<ide> */
<del> public $fixtures = null;
<add> public $fixtures;
<ide>
<ide> /**
<ide> * By default, all fixtures attached to this class will be truncated and reloaded after each test. | 1 |
PHP | PHP | use an expression object | 21d5d07d0babe550ea52a17f49c53ee45bc79fc1 | <ide><path>tests/TestCase/ORM/Association/BelongsToManyTest.php
<ide> public function testEagerLoadingBelongsToManyLimitedFieldsWithAutoFields()
<ide> $result = $table
<ide> ->find()
<ide> ->contain(['Tags' => function ($q) {
<del> return $q->select(['two' => '1 + 1'])->autoFields(true);
<add> return $q->select(['two' => $q->newExpr('1 + 1')])->autoFields(true);
<ide> }])
<ide> ->first();
<ide> | 1 |
Javascript | Javascript | fix stderr matching for fatal error | b82d72c199e70a0c9fbeb6c06715ef8120b3de2f | <ide><path>test/report/test-report-fatal-error.js
<ide> const ARGS = [
<ide> assert.strictEqual(reports.length, 0);
<ide>
<ide> const lines = child.stderr.split('\n');
<del> // Skip over unavoidable free-form output from V8.
<del> const report = lines[1];
<add> // Skip over unavoidable free-form output and gc log from V8.
<add> const report = lines.find((i) => i.startsWith('{'));
<ide> const json = JSON.parse(report);
<ide>
<ide> assert.strictEqual(json.header.threadId, null); | 1 |
Python | Python | implement all tf interpolation upscaling methods | 25e53c1654b0aeeb8bf4ea00dcc2f9743420a9d9 | <ide><path>keras/backend.py
<ide> def resize_images(x, height_factor, width_factor, data_format,
<ide> height_factor: Positive integer.
<ide> width_factor: Positive integer.
<ide> data_format: One of `"channels_first"`, `"channels_last"`.
<del> interpolation: A string, one of `nearest` or `bilinear`.
<add> interpolation: A string any of `tf.image.ResizeMethod`.
<ide>
<ide> Returns:
<ide> A tensor.
<ide> def resize_images(x, height_factor, width_factor, data_format,
<ide>
<ide> if data_format == 'channels_first':
<ide> x = permute_dimensions(x, [0, 2, 3, 1])
<del> if interpolation == 'nearest':
<del> x = tf.image.resize(
<del> x, new_shape, method=tf.image.ResizeMethod.NEAREST_NEIGHBOR)
<del> elif interpolation == 'bilinear':
<del> x = tf.image.resize(x, new_shape,
<del> method=tf.image.ResizeMethod.BILINEAR)
<add> interpolations = {
<add> 'area': tf.image.ResizeMethod.AREA,
<add> 'bicubic': tf.image.ResizeMethod.BICUBIC,
<add> 'bilinear': tf.image.ResizeMethod.BILINEAR,
<add> 'gaussian': tf.image.ResizeMethod.GAUSSIAN,
<add> 'lanczos3': tf.image.ResizeMethod.LANCZOS3,
<add> 'lanczos5': tf.image.ResizeMethod.LANCZOS5,
<add> 'mitchellcubic': tf.image.ResizeMethod.MITCHELLCUBIC,
<add> 'nearest': tf.image.ResizeMethod.NEAREST_NEIGHBOR,
<add> }
<add> if interpolation in interpolations:
<add> x = tf.image.resize(x, new_shape, method=interpolations[interpolation])
<ide> else:
<del> raise ValueError('interpolation should be one '
<del> 'of "nearest" or "bilinear".')
<add> raise ValueError('interpolation should be '
<add> 'from `tf.image.ResizeMethod`.')
<ide> if data_format == 'channels_first':
<ide> x = permute_dimensions(x, [0, 3, 1, 2])
<ide>
<ide><path>keras/layers/reshaping/up_sampling2d.py
<ide> class UpSampling2D(Layer):
<ide> It defaults to the `image_data_format` value found in your
<ide> Keras config file at `~/.keras/keras.json`.
<ide> If you never set it, then it will be "channels_last".
<del> interpolation: A string, one of `nearest` or `bilinear`.
<add> interpolation: A string any of `tf.image.ResizeMethod`.
<ide>
<ide> Input shape:
<ide> 4D tensor with shape:
<ide> def __init__(self,
<ide> super(UpSampling2D, self).__init__(**kwargs)
<ide> self.data_format = conv_utils.normalize_data_format(data_format)
<ide> self.size = conv_utils.normalize_tuple(size, 2, 'size')
<del> if interpolation not in {'nearest', 'bilinear'}:
<del> raise ValueError('`interpolation` argument should be one of `"nearest"` '
<del> f'or `"bilinear"`. Received: "{interpolation}".')
<add> interpolations = {
<add> 'area': tf.image.ResizeMethod.AREA,
<add> 'bicubic': tf.image.ResizeMethod.BICUBIC,
<add> 'bilinear': tf.image.ResizeMethod.BILINEAR,
<add> 'gaussian': tf.image.ResizeMethod.GAUSSIAN,
<add> 'lanczos3': tf.image.ResizeMethod.LANCZOS3,
<add> 'lanczos5': tf.image.ResizeMethod.LANCZOS5,
<add> 'mitchellcubic': tf.image.ResizeMethod.MITCHELLCUBIC,
<add> 'nearest': tf.image.ResizeMethod.NEAREST_NEIGHBOR,
<add> }
<add> if interpolation not in interpolations:
<add> raise ValueError('`interpolation` argument should be from `tf.image.ResizeMethod`. '
<add> f'Received: "{interpolation}".')
<ide> self.interpolation = interpolation
<ide> self.input_spec = InputSpec(ndim=4)
<ide> | 2 |
Python | Python | put smaller albert model | 1bf38611a4183f9fd0e0928703ed2264e0305647 | <ide><path>tests/test_onnx_v2.py
<ide> def test_values_override(self):
<ide> )
<ide>
<ide> PYTORCH_EXPORT_DEFAULT_MODELS = {
<del> ("ALBERT", "albert-base-v2", AlbertModel, AlbertConfig, AlbertOnnxConfig),
<add> ("ALBERT", "hf-internal-testing/tiny-albert", AlbertModel, AlbertConfig, AlbertOnnxConfig),
<ide> ("BART", "facebook/bart-base", BartModel, BartConfig, BartOnnxConfig),
<ide> ("BERT", "bert-base-cased", BertModel, BertConfig, BertOnnxConfig),
<ide> ("DistilBERT", "distilbert-base-cased", DistilBertModel, DistilBertConfig, DistilBertOnnxConfig),
<ide> def test_pytorch_export_default(self):
<ide> self.assertTrue(hasattr(onnx_config_class, "default"))
<ide>
<ide> tokenizer = AutoTokenizer.from_pretrained(model)
<del> model = model_class(config_class())
<add> model = model_class(config_class.from_pretrained(model))
<ide> onnx_config = onnx_config_class.default(model.config)
<ide>
<ide> with NamedTemporaryFile("w") as output: | 1 |
Javascript | Javascript | add android support for modal | 998d68d36d08a7daaf8c80dbe5a0fdc4a8652c3e | <ide><path>Libraries/Modal/Modal.js
<ide> class Modal extends React.Component {
<ide> <RCTModalHostView
<ide> animated={this.props.animated}
<ide> transparent={this.props.transparent}
<del> onDismiss={this.props.onDismiss}
<add> onRequestClose={this.props.onRequestClose}
<ide> onShow={this.props.onShow}
<ide> style={styles.modal}>
<ide> <View style={[styles.container, containerBackgroundColor]}>
<ide> Modal.propTypes = {
<ide> animated: PropTypes.bool,
<ide> transparent: PropTypes.bool,
<ide> visible: PropTypes.bool,
<del> onDismiss: PropTypes.func,
<add> onRequestClose: PropTypes.func,
<ide> onShow: PropTypes.func,
<ide> };
<ide>
<ide> var styles = StyleSheet.create({
<ide> position: 'absolute',
<ide> },
<ide> container: {
<del> left: 0,
<ide> position: 'absolute',
<add> bottom: 0,
<add> left: 0,
<add> right: 0,
<ide> top: 0,
<ide> }
<ide> }); | 1 |
PHP | PHP | remove timestamp from index file | adc2e21e7ffe00cb660934f9b798b53479f1b5a7 | <ide><path>public/index.php
<ide> // --------------------------------------------------------------
<ide> // Launch Laravel.
<ide> // --------------------------------------------------------------
<del>require $laravel.'/laravel.php';
<del>
<del>echo (microtime(true) - LARAVEL_START) * 1000;
<ide>\ No newline at end of file
<add>require $laravel.'/laravel.php';
<ide>\ No newline at end of file | 1 |
Java | Java | ignore failing test for now | 6206e5f11f4395b62c1fb296f2aab3d7299fc889 | <ide><path>org.springframework.expression/src/test/java/org/springframework/expression/spel/ConstructorInvocationTests.java
<ide>
<ide> package org.springframework.expression.spel;
<ide>
<add>import org.junit.Ignore;
<ide> import org.junit.Test;
<ide>
<ide> /**
<ide> public void testWidening01() {
<ide> }
<ide>
<ide> @Test
<add> @Ignore
<ide> public void testArgumentConversion01() {
<ide> // Closest ctor will be new String(String) and converter supports Double>String
<add> // TODO currently failing as with new ObjectToArray converter closest constructor matched becomes String(byte[]) which fails...
<ide> evaluate("new String(3.0d)", "3.0", String.class);
<ide> }
<ide> | 1 |
PHP | PHP | fix side-effect in destructor | 1a74e798309192a9895c9cedabd714ceee345f4e | <ide><path>src/Mailer/Transport/SmtpTransport.php
<ide> public function __destruct()
<ide> }
<ide> }
<ide>
<add> /**
<add> * Unserialize handler.
<add> *
<add> * Ensure that the socket property isn't reinitialized in a broken state.
<add> *
<add> * @return void
<add> */
<add> public function __wakeup()
<add> {
<add> $this->_socket = null;
<add> }
<add>
<ide> /**
<ide> * Connect to the SMTP server.
<ide> *
<ide><path>tests/TestCase/Mailer/Transport/SmtpTransportTest.php
<ide> public function testSendDefaults()
<ide>
<ide> $this->SmtpTransport->send($email);
<ide> }
<add>
<add> /**
<add> * Ensure that unserialized transports have no connection.
<add> *
<add> * @return void
<add> */
<add> public function testSerializeCleanupSocket()
<add> {
<add> $this->socket->expects($this->at(0))->method('connect')->will($this->returnValue(true));
<add> $this->socket->expects($this->at(1))->method('read')->will($this->returnValue("220 Welcome message\r\n"));
<add> $this->socket->expects($this->at(2))->method('write')->with("EHLO localhost\r\n");
<add> $this->socket->expects($this->at(3))->method('read')->will($this->returnValue("250 OK\r\n"));
<add>
<add> $smtpTransport = new SmtpTestTransport();
<add> $smtpTransport->setSocket($this->socket);
<add> $smtpTransport->connect();
<add>
<add> $result = unserialize(serialize($smtpTransport));
<add> $this->assertAttributeEquals(null, '_socket', $result);
<add> $this->assertFalse($result->connected());
<add> }
<ide> } | 2 |
Python | Python | fix warning when collating list of numpy arrays | ecf29db0e5471205cf89527235d8b1002013c3fd | <ide><path>src/transformers/data/data_collator.py
<ide> import warnings
<ide> from collections.abc import Mapping
<ide> from dataclasses import dataclass
<add>from random import randint
<ide> from typing import Any, Callable, Dict, List, NewType, Optional, Tuple, Union
<ide>
<add>import numpy as np
<add>
<ide> from ..models.bert import BertTokenizer, BertTokenizerFast
<ide> from ..tokenization_utils_base import PreTrainedTokenizerBase
<ide> from ..utils import PaddingStrategy
<ide> def torch_default_data_collator(features: List[InputDataClass]) -> Dict[str, Any
<ide> if k not in ("label", "label_ids") and v is not None and not isinstance(v, str):
<ide> if isinstance(v, torch.Tensor):
<ide> batch[k] = torch.stack([f[k] for f in features])
<add> elif isinstance(v, np.ndarray):
<add> batch[k] = torch.tensor(np.stack([f[k] for f in features]))
<ide> else:
<ide> batch[k] = torch.tensor([f[k] for f in features])
<ide>
<ide> return batch
<ide>
<ide>
<ide> def tf_default_data_collator(features: List[InputDataClass]) -> Dict[str, Any]:
<del> import numpy as np
<ide> import tensorflow as tf
<ide>
<ide> if not isinstance(features[0], Mapping):
<ide> def tf_default_data_collator(features: List[InputDataClass]) -> Dict[str, Any]:
<ide>
<ide>
<ide> def numpy_default_data_collator(features: List[InputDataClass]) -> Dict[str, Any]:
<del> import numpy as np
<del>
<ide> if not isinstance(features[0], Mapping):
<ide> features = [vars(f) for f in features]
<ide> first = features[0]
<ide> def tf_call(self, features):
<ide> return batch
<ide>
<ide> def numpy_call(self, features):
<del> import numpy as np
<del>
<ide> label_name = "label" if "label" in features[0].keys() else "labels"
<ide> labels = [feature[label_name] for feature in features] if label_name in features[0].keys() else None
<ide> batch = self.tokenizer.pad(
<ide> def numpy_call(self, features):
<ide>
<ide> def _torch_collate_batch(examples, tokenizer, pad_to_multiple_of: Optional[int] = None):
<ide> """Collate `examples` into a batch, using the information in `tokenizer` for padding if necessary."""
<del> import numpy as np
<ide> import torch
<ide>
<ide> # Tensorize if necessary.
<ide> def _torch_collate_batch(examples, tokenizer, pad_to_multiple_of: Optional[int]
<ide>
<ide>
<ide> def _tf_collate_batch(examples, tokenizer, pad_to_multiple_of: Optional[int] = None):
<del> import numpy as np
<ide> import tensorflow as tf
<ide>
<ide> """Collate `examples` into a batch, using the information in `tokenizer` for padding if necessary."""
<ide> def _tf_collate_batch(examples, tokenizer, pad_to_multiple_of: Optional[int] = N
<ide>
<ide>
<ide> def _numpy_collate_batch(examples, tokenizer, pad_to_multiple_of: Optional[int] = None):
<del> import numpy as np
<del>
<ide> """Collate `examples` into a batch, using the information in `tokenizer` for padding if necessary."""
<ide> # Tensorize if necessary.
<ide> if isinstance(examples[0], (list, tuple)):
<ide> class DataCollatorForSeq2Seq:
<ide> return_tensors: str = "pt"
<ide>
<ide> def __call__(self, features, return_tensors=None):
<del> import numpy as np
<del>
<ide> if return_tensors is None:
<ide> return_tensors = self.return_tensors
<ide> labels = [feature["labels"] for feature in features] if "labels" in features[0].keys() else None
<ide> def torch_mask_tokens(self, inputs: Any, special_tokens_mask: Optional[Any] = No
<ide> return inputs, labels
<ide>
<ide> def numpy_call(self, examples: List[Union[List[int], Any, Dict[str, Any]]]) -> Dict[str, Any]:
<del> import numpy as np
<del>
<ide> # Handle dict or lists with proper padding and conversion to tensor.
<ide> if isinstance(examples[0], Mapping):
<ide> batch = self.tokenizer.pad(examples, return_tensors="np", pad_to_multiple_of=self.pad_to_multiple_of)
<ide> def numpy_mask_tokens(self, inputs: Any, special_tokens_mask: Optional[Any] = No
<ide> """
<ide> Prepare masked tokens inputs/labels for masked language modeling: 80% MASK, 10% random, 10% original.
<ide> """
<del> import numpy as np
<del>
<ide> labels = np.copy(inputs)
<ide> # We sample a few tokens in each sequence for MLM training (with probability `self.mlm_probability`)
<ide> probability_matrix = np.full(labels.shape, self.mlm_probability)
<ide> def numpy_mask_tokens(self, inputs: Any, mask_labels: Any) -> Tuple[Any, Any]:
<ide> Prepare masked tokens inputs/labels for masked language modeling: 80% MASK, 10% random, 10% original. Set
<ide> 'mask_labels' means we use whole word mask (wwm), we directly mask idxs according to it's ref.
<ide> """
<del> import numpy as np
<del>
<ide> if self.tokenizer.mask_token is None:
<ide> raise ValueError(
<ide> "This tokenizer does not have a mask token which is necessary for masked language modeling. Remove the"
<ide> def tf_mask_tokens(self, inputs: Any) -> Tuple[Any, Any, Any, Any]:
<ide> 4. Set `cur_len = cur_len + context_length`. If `cur_len < max_len` (i.e. there are tokens remaining in the
<ide> sequence to be processed), repeat from Step 1.
<ide> """
<del> from random import randint
<del>
<del> import numpy as np
<ide> import tensorflow as tf
<ide>
<ide> if self.tokenizer.mask_token is None:
<ide> def numpy_mask_tokens(self, inputs: Any) -> Tuple[Any, Any, Any, Any]:
<ide> 4. Set `cur_len = cur_len + context_length`. If `cur_len < max_len` (i.e. there are tokens remaining in the
<ide> sequence to be processed), repeat from Step 1.
<ide> """
<del> from random import randint
<del>
<del> import numpy as np
<del>
<ide> if self.tokenizer.mask_token is None:
<ide> raise ValueError(
<ide> "This tokenizer does not have a mask token which is necessary for permutation language modeling." | 1 |
PHP | PHP | allow silent deletion on failed model retrieval | bceded6fef79760b9907dbe105829f7d2d62f899 | <ide><path>src/Illuminate/Queue/CallQueuedHandler.php
<ide>
<ide> namespace Illuminate\Queue;
<ide>
<add>use Exception;
<add>use ReflectionClass;
<ide> use Illuminate\Contracts\Queue\Job;
<ide> use Illuminate\Contracts\Bus\Dispatcher;
<ide> use Illuminate\Database\Eloquent\ModelNotFoundException;
<ide> public function call(Job $job, array $data)
<ide> $job, unserialize($data['command'])
<ide> );
<ide> } catch (ModelNotFoundException $e) {
<del> return FailingJob::handle(
<del> $job->getConnectionName(), $job, $e
<del> );
<add> return $this->handleModelNotFound($job, $e);
<ide> }
<ide>
<ide> $this->dispatcher->dispatchNow(
<ide> protected function ensureNextJobInChainIsDispatched($command)
<ide> }
<ide> }
<ide>
<add> /**
<add> * Handle a model not found exception.
<add> *
<add> * @param \Illuminate\Contracts\Queue\Job $job
<add> * @param \Exception $e
<add> * @return void
<add> */
<add> protected function handleModelNotFound(Job $job, $e)
<add> {
<add> $class = $job->resolveName();
<add>
<add> try {
<add> $shouldDelete = (new ReflectionClass($class))
<add> ->getDefaultProperties()['deleteWhenMissingModels'] ?? false;
<add> } catch (Exception $e) {
<add> $shouldDelete = false;
<add> }
<add>
<add> if ($shouldDelete) {
<add> return $job->delete();
<add> }
<add>
<add> return FailingJob::handle(
<add> $job->getConnectionName(), $job, $e
<add> );
<add> }
<add>
<ide> /**
<ide> * Call the failed method on the job instance.
<ide> *
<ide><path>tests/Integration/Queue/CallQueuedHandlerTest.php
<ide> public function test_job_is_marked_as_failed_if_model_not_found_exception_is_thr
<ide>
<ide> $job = Mockery::mock('Illuminate\Contracts\Queue\Job');
<ide> $job->shouldReceive('getConnectionName')->andReturn('connection');
<add> $job->shouldReceive('resolveName')->andReturn(__CLASS__);
<ide> $job->shouldReceive('markAsFailed')->once();
<ide> $job->shouldReceive('isDeleted')->andReturn(false);
<ide> $job->shouldReceive('delete')->once();
<ide> public function test_job_is_marked_as_failed_if_model_not_found_exception_is_thr
<ide>
<ide> Event::assertDispatched(JobFailed::class);
<ide> }
<add>
<add> public function test_job_is_deleted_if_has_delete_property()
<add> {
<add> Event::fake();
<add>
<add> $instance = new Illuminate\Queue\CallQueuedHandler(new Illuminate\Bus\Dispatcher(app()));
<add>
<add> $job = Mockery::mock('Illuminate\Contracts\Queue\Job');
<add> $job->shouldReceive('getConnectionName')->andReturn('connection');
<add> $job->shouldReceive('resolveName')->andReturn(CallQueuedHandlerExceptionThrower::class);
<add> $job->shouldReceive('markAsFailed')->never();
<add> $job->shouldReceive('isDeleted')->andReturn(false);
<add> $job->shouldReceive('delete')->once();
<add> $job->shouldReceive('failed')->never();
<add>
<add> $instance->call($job, [
<add> 'command' => serialize(new CallQueuedHandlerExceptionThrower),
<add> ]);
<add>
<add> Event::assertNotDispatched(JobFailed::class);
<add> }
<ide> }
<ide>
<ide> class CallQueuedHandlerTestJob
<ide> public function handle()
<ide>
<ide> class CallQueuedHandlerExceptionThrower
<ide> {
<add> public $deleteWhenMissingModels = true;
<add>
<ide> public function handle()
<ide> {
<ide> // | 2 |
Javascript | Javascript | fix appendtext after api changes | e48530d3913132ed0d369cf50639820060640201 | <ide><path>src/canvas.js
<ide> var CanvasGraphics = (function CanvasGraphicsClosure() {
<ide> if (textSelection) {
<ide> geom.canvasWidth = canvasWidth;
<ide> this.textLayer.appendText(font.fallbackName, fontSize, geom);
<del> }`
<add> }
<ide>
<ide> return canvasWidth;
<ide> },
<ide><path>test/driver.js
<ide> SimpleTextLayerBuilder.prototype = {
<ide> endLayout: function SimpleTextLayerBuilder_EndLayout() {
<ide> this.ctx.restore();
<ide> },
<del> appendText: function SimpleTextLayerBuilder_AppendText(text, fontName,
<del> fontSize) {
<add> appendText: function SimpleTextLayerBuilder_AppendText(fontName, fontSize,
<add> geom) {
<ide> var ctx = this.ctx, viewport = this.viewport;
<ide> // vScale and hScale already contain the scaling to pixel units
<del> var fontHeight = fontSize * text.geom.vScale;
<add> var fontHeight = fontSize * geom.vScale;
<ide> ctx.beginPath();
<ide> ctx.strokeStyle = 'red';
<ide> ctx.fillStyle = 'yellow';
<del> ctx.rect(text.geom.x, text.geom.y - fontHeight,
<del> text.canvasWidth * text.geom.hScale, fontHeight);
<add> ctx.rect(geom.x, geom.y - fontHeight,
<add> geom.canvasWidth * geom.hScale, fontHeight);
<ide> ctx.stroke();
<ide> ctx.fill();
<ide>
<ide> var textContent = this.textContent.text[this.textCounter];
<ide> ctx.font = fontHeight + 'px ' + fontName;
<ide> ctx.fillStyle = 'black';
<del> ctx.fillText(textContent, text.geom.x, text.geom.y);
<add> ctx.fillText(textContent, geom.x, geom.y);
<ide>
<ide> this.textCounter++;
<ide> }, | 2 |
Text | Text | fix a link in dgram.md | 83fcb9f07591ceb89cfe0b6347ffb622aa26cdf4 | <ide><path>doc/api/dgram.md
<ide> and `udp6` sockets). The bound address and port can be retrieved using
<ide> [`socket.address().address`]: #dgram_socket_address
<ide> [`socket.address().port`]: #dgram_socket_address
<ide> [`socket.bind()`]: #dgram_socket_bind_port_address_callback
<del>[`System Error`]: errors.html#errors_class_system_error
<add>[`System Error`]: errors.html#errors_class_systemerror
<ide> [byte length]: buffer.html#buffer_class_method_buffer_bytelength_string_encoding
<ide> [IPv6 Zone Indices]: https://en.wikipedia.org/wiki/IPv6_address#Link-local_addresses_and_zone_indices
<ide> [RFC 4007]: https://tools.ietf.org/html/rfc4007 | 1 |
Javascript | Javascript | update the current branch as well | c76d0f04382865f922096dae0272ffa2da8b8c18 | <ide><path>src/git-repository-async.js
<ide> module.exports = class GitRepositoryAsync {
<ide> }).then((statuses) => {
<ide> let cachedStatus = this.pathStatusCache[relativePath] || 0
<ide> let status = statuses[0] ? statuses[0].statusBit() : Git.Status.STATUS.CURRENT
<del> if (status !== cachedStatus) {
<add> if (status !== cachedStatus && this.emitter != null) {
<ide> this.emitter.emit('did-change-status', {path: _path, pathStatus: status})
<ide> }
<ide> this.pathStatusCache[relativePath] = status
<ide> module.exports = class GitRepositoryAsync {
<ide> })
<ide> }
<ide>
<add> // Get the current branch and update this.branch.
<add> //
<add> // Returns :: Promise<String>
<add> // The branch name.
<add> _refreshBranch () {
<add> return this.repoPromise
<add> .then(repo => repo.getCurrentBranch())
<add> .then(ref => ref.name())
<add> .then(branchRef => this.branch = branchRef)
<add> }
<add>
<ide> // Refreshes the git status. Note: the sync GitRepository class does this with
<ide> // a separate process, let's see if we can avoid that.
<ide> refreshStatus () {
<ide> // TODO add upstream, branch, and submodule tracking
<del> return this.repoPromise.then((repo) => {
<del> return repo.getStatus()
<del> }).then((statuses) => {
<del> // update the status cache
<del> return Promise.all(statuses.map((status) => {
<del> return [status.path(), status.statusBit()]
<del> })).then((statusesByPath) => {
<del> return _.object(statusesByPath)
<add> const status = this.repoPromise
<add> .then(repo => repo.getStatus())
<add> .then(statuses => {
<add> // update the status cache
<add> return Promise.all(statuses.map(status => [status.path(), status.statusBit()]))
<add> .then(statusesByPath => _.object(statusesByPath))
<ide> })
<del> }).then((newPathStatusCache) => {
<del> if (!_.isEqual(this.pathStatusCache, newPathStatusCache)) {
<del> this.emitter.emit('did-change-statuses')
<del> }
<del> this.pathStatusCache = newPathStatusCache
<del> return newPathStatusCache
<del> })
<add> .then(newPathStatusCache => {
<add> if (!_.isEqual(this.pathStatusCache, newPathStatusCache) && this.emitter != null) {
<add> this.emitter.emit('did-change-statuses')
<add> }
<add> this.pathStatusCache = newPathStatusCache
<add> return newPathStatusCache
<add> })
<add>
<add> const branch = this._refreshBranch()
<add>
<add> return Promise.all([status, branch])
<ide> }
<ide>
<ide> // Section: Private | 1 |
PHP | PHP | mark unused method and property as deprecated | 3ab0ad1c5c83476c03755329ca0d2c32bf891c48 | <ide><path>src/ORM/ResultSet.php
<ide> class ResultSet implements ResultSetInterface
<ide> * Converters are indexed by alias and column name.
<ide> *
<ide> * @var array
<add> * @deprecated 3.2.0 Not used anymore. Type casting is done at the statement level
<ide> */
<ide> protected $_types = [];
<ide>
<ide> protected function _calculateTypeMap()
<ide> * @param \Cake\ORM\Table $table The table from which to get the schema
<ide> * @param array $fields The fields whitelist to use for fields in the schema.
<ide> * @return array
<add> * @deprecated 3.2.0 Not used anymore. Type casting is done at the statement level
<ide> */
<ide> protected function _getTypes($table, $fields)
<ide> { | 1 |
Javascript | Javascript | add usvstring conversion benchmark | 6123ed5b25bfedc3054dbaf9f3039e2585b799f8 | <ide><path>benchmark/url/usvstring.js
<add>'use strict';
<add>const common = require('../common.js');
<add>
<add>const inputs = {
<add> valid: 'adsfadsfadsf',
<add> validsurr: '\uda23\ude23\uda1f\udfaa\ud800\udfff\uda23\ude23\uda1f\udfaa' +
<add> '\ud800\udfff',
<add> someinvalid: 'asasfdfasd\uda23',
<add> allinvalid: '\udc45\uda23 \udf00\udc00 \udfaa\uda12 \udc00\udfaa',
<add> nonstring: { toString() { return 'asdf'; } }
<add>};
<add>const bench = common.createBenchmark(main, {
<add> input: Object.keys(inputs),
<add> n: [5e7]
<add>}, {
<add> flags: ['--expose-internals']
<add>});
<add>
<add>function main(conf) {
<add> const { toUSVString } = require('internal/url');
<add> const str = inputs[conf.input];
<add> const n = conf.n | 0;
<add>
<add> bench.start();
<add> for (var i = 0; i < n; i++)
<add> toUSVString(str);
<add> bench.end(n);
<add>} | 1 |
Javascript | Javascript | fix mod function | 0c52b0c1887b21b2ad8af5f0bb6bda99bc455d90 | <ide><path>examples/js/nodes/math/Math2Node.js
<ide> THREE.Math2Node.prototype.generate = function( builder, output ) {
<ide>
<ide> case THREE.Math2Node.MIN:
<ide> case THREE.Math2Node.MAX:
<del> case THREE.Math2Node.MODULO:
<add> case THREE.Math2Node.MOD:
<ide> a = this.a.build( builder, type );
<ide> b = this.b.build( builder, bl == 1 ? 'fv1' : type );
<ide> break; | 1 |
PHP | PHP | add tests for data_get with arrayaccess object | 73eddfa09c4a7d238e29d2e74692b8455fc1ceb7 | <ide><path>tests/Support/SupportHelpersTest.php
<ide> public function testDataGetWithNestedArrays()
<ide> $this->assertEquals(['taylor', 'abigail', 'dayle'], data_get($array, '*.name'));
<ide> $this->assertEquals(['taylorotwell@gmail.com', null, null], data_get($array, '*.email', 'irrelevant'));
<ide>
<add> $arrayAccess = new SupportTestArrayAccess($array);
<add> $this->assertEquals([], data_get($arrayAccess, '*.name'));
<add>
<ide> $array = [
<ide> 'users' => [
<ide> ['first' => 'taylor', 'last' => 'otwell', 'email' => 'taylorotwell@gmail.com'],
<ide> public function testDataGetWithNestedArrays()
<ide> $this->assertEquals(['taylorotwell@gmail.com', null, null], data_get($array, 'users.*.email', 'irrelevant'));
<ide> $this->assertEquals('not found', data_get($array, 'posts.*.date', 'not found'));
<ide> $this->assertNull(data_get($array, 'posts.*.date'));
<add>
<add> $arrayAccess = new SupportTestArrayAccess($array);
<add> $this->assertEquals(['taylor', 'abigail', 'dayle'], data_get($arrayAccess, 'users.*.first'));
<ide> }
<ide>
<ide> public function testDataGetWithDoubleNestedArraysCollapsesResult() | 1 |
Javascript | Javascript | add challenge order to individual challenge | 22c416c7dbd88887929267928a924fca168ce2c1 | <ide><path>index.js
<ide> Challenge.destroyAll(function(err, info) {
<ide> }
<ide> challenges.forEach(function(file) {
<ide> var challengeSpec = require('./challenges/' + file);
<add> var order = challengeSpec.order;
<ide> var challenges = challengeSpec.challenges
<del> .map(function(challenge) {
<add> .map(function(challenge, index) {
<ide> // NOTE(berks): add title for displaying in views
<ide> challenge.name =
<ide> _.capitalize(challenge.type) +
<ide> ': ' +
<ide> challenge.title.replace(/[^a-zA-Z0-9\s]/g, '');
<del> challenge.dashedName = challenge.name.toLowerCase().replace(/\s/g, '-');
<add> challenge.dashedName = challenge.name
<add> .toLowerCase()
<add> .replace(/\:/g, '')
<add> .replace(/\s/g, '-');
<add> challenge.order = +('' + order + (index + 1));
<ide> return challenge;
<ide> });
<ide> | 1 |
Javascript | Javascript | fix linting issues | 685292bb8d64ac2604cecf3de9d8fa977d85fe50 | <ide><path>spec/project-spec.js
<ide> describe('Project', () => {
<ide> projectPath2 = temp.mkdirSync('project-path2')
<ide> projectSpecification = {
<ide> paths: [projectPath1, projectPath2],
<del> originPath: "originPath",
<add> originPath: 'originPath',
<ide> config: {
<del> "baz": "buzz"
<add> 'baz': 'buzz'
<ide> }
<ide> }
<ide> })
<ide> describe('Project', () => {
<ide> it('clears a project through replace with no params', () => {
<ide> expect(atom.config.get('baz')).toBeUndefined()
<ide> atom.project.replace(projectSpecification)
<del> expect(atom.config.get('baz')).toBe("buzz")
<add> expect(atom.config.get('baz')).toBe('buzz')
<ide> expect(atom.project.getPaths()).toEqual([projectPath1, projectPath2])
<ide> atom.project.replace()
<ide> expect(atom.config.get('baz')).toBeUndefined() | 1 |
PHP | PHP | simplify app helper. remove recursive call | 033801f0ba200a4f7c5e8bb54cbd6c7524e91038 | <ide><path>src/Illuminate/Foundation/helpers.php
<ide> <?php
<ide>
<ide> use Illuminate\Support\Str;
<add>use Illuminate\Container\Container;
<ide>
<ide> if ( ! function_exists('abort'))
<ide> {
<ide> function action($name, $parameters = array())
<ide> * @param array $parameters
<ide> * @return mixed|\Illuminate\Foundation\Application
<ide> */
<del> function app($make = null, $parameters = array())
<add> function app($make = null, $parameters = [])
<ide> {
<del> if ( ! is_null($make))
<del> {
<del> return app()->make($make, $parameters);
<del> }
<add> if (is_null($make)) return Container::getInstance();
<ide>
<del> return Illuminate\Container\Container::getInstance();
<add> return Container::getInstance()->make($make, $parameters);
<ide> }
<ide> }
<ide>
<ide> function env($key, $default = null)
<ide> case '(empty)':
<ide> return '';
<ide> }
<del>
<add>
<ide> if (Str::startsWith($value, '"') && Str::endsWith($value, '"'))
<ide> {
<ide> return substr($value, 1, -1); | 1 |
Ruby | Ruby | update pr number with unexpired artifacts | d55cbeac789d00c0ce319ee8cb8e67e3d71aac79 | <ide><path>Library/Homebrew/test/utils/github_spec.rb
<ide> it "fails to find artifacts that don't exist" do
<ide> expect {
<ide> described_class.get_artifact_url(
<del> described_class.get_workflow_run("Homebrew", "homebrew-core", 51971, artifact_name: "false_bottles"),
<add> described_class.get_workflow_run("Homebrew", "homebrew-core", 79751, artifact_name: "false_bottles"),
<ide> )
<ide> }.to raise_error(/No artifact .+ was found/)
<ide> end
<ide>
<ide> it "gets an artifact link" do
<ide> url = described_class.get_artifact_url(
<del> described_class.get_workflow_run("Homebrew", "homebrew-core", 51971, artifact_name: "bottles"),
<add> described_class.get_workflow_run("Homebrew", "homebrew-core", 79751, artifact_name: "bottles"),
<ide> )
<del> expect(url).to eq("https://api.github.com/repos/Homebrew/homebrew-core/actions/artifacts/3557392/zip")
<add> expect(url).to eq("https://api.github.com/repos/Homebrew/homebrew-core/actions/artifacts/69422207/zip")
<ide> end
<ide> end
<ide> | 1 |
Javascript | Javascript | remove unneccessary argument | 1f2b11a169f9f536ed62424bf9a1ae66b812d175 | <ide><path>src/geometries/ExtrudeGeometry.js
<ide> function ExtrudeBufferGeometry( shapes, options ) {
<ide> for ( var i = 0, l = shapes.length; i < l; i ++ ) {
<ide>
<ide> var shape = shapes[ i ];
<del> addShape( shape, options );
<add> addShape( shape );
<ide>
<ide> }
<ide> | 1 |
Text | Text | update broken link for apollo-boost | 067a43c1ca4a3b276e1d9204577f96b0365ad07f | <ide><path>docs/redux-toolkit/overview.md
<ide> This is good in some cases, because it gives you flexibility, but that flexibili
<ide> - "I have to add a lot of packages to get Redux to do anything useful"
<ide> - "Redux requires too much boilerplate code"
<ide>
<del>We can't solve every use case, but in the spirit of [`create-react-app`](https://github.com/facebook/create-react-app) and [`apollo-boost`](https://dev-blog.apollodata.com/zero-config-graphql-state-management-27b1f1b3c2c3), we can provide an official recommended set of tools that handle the most common use cases and reduce the need to make extra decisions.
<add>We can't solve every use case, but in the spirit of [`create-react-app`](https://github.com/facebook/create-react-app) and [`apollo-boost`](https://www.apollographql.com/blog/announcement/frontend/zero-config-graphql-state-management/), we can provide an official recommended set of tools that handle the most common use cases and reduce the need to make extra decisions.
<ide>
<ide> ## Why You Should Use Redux Toolkit
<ide> | 1 |
Text | Text | create strings using template literals | 8d593a1256a876773fbe3199139fee6bfe670212 | <ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/es6/create-strings-using-template-literals.english.md
<ide> This new way of creating strings gives you more flexibility to create robust str
<ide> ## Instructions
<ide> <section id='instructions'>
<ide> Use template literal syntax with backticks to display each entry of the <code>result</code> object's <code>failure</code> array. Each entry should be wrapped inside an <code>li</code> element with the class attribute <code>text-warning</code>, and listed within the <code>resultDisplayArray</code>.
<add>Use an iterator method (any kind of loop) to get the desired output.
<ide> </section>
<ide>
<ide> ## Tests
<ide> tests:
<ide> testString: assert(typeof makeList(result.failure) === 'object' && resultDisplayArray.length === 3, '<code>resultDisplayArray</code> is a list containing <code>result failure</code> messages.');
<ide> - text: <code>resultDisplayArray</code> is the desired output.
<ide> testString: assert(makeList(result.failure).every((v, i) => v === `<li class="text-warning">${result.failure[i]}</li>` || v === `<li class='text-warning'>${result.failure[i]}</li>`), '<code>resultDisplayArray</code> is the desired output.');
<del> - text: Template strings were used
<del> testString: getUserInput => assert(getUserInput('index').match(/`.*`/g), 'Template strings were not used');
<del>
<add> - text: Template strings and expression interpolation should be used
<add> testString: getUserInput => assert(getUserInput('index').match(/(`.*\${.*}.*`)/), 'Template strings and expression interpolation should be used');
<add> - text: An iterator should be used
<add> testString: getUserInput => assert(getUserInput('index').match(/for|map|reduce|forEach|while/), 'An iterator should be used');
<ide> ```
<ide>
<ide> </section>
<ide> const resultDisplayArray = makeList(result.failure);
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>const result = {
<add> success: ["max-length", "no-amd", "prefer-arrow-functions"],
<add> failure: ["no-var", "var-on-top", "linebreak"],
<add> skipped: ["id-blacklist", "no-dup-keys"]
<add>};
<add>function makeList(arr) {
<add> "use strict";
<add>
<add> const resultDisplayArray = arr.map(val => `<li class="text-warning">${val}</li>`);
<add>
<add> return resultDisplayArray;
<add>}
<add>/**
<add> * makeList(result.failure) should return:
<add> * [ `<li class="text-warning">no-var</li>`,
<add> * `<li class="text-warning">var-on-top</li>`,
<add> * `<li class="text-warning">linebreak</li>` ]
<add> **/
<add>const resultDisplayArray = makeList(result.failure);
<ide> ```
<ide> </section> | 1 |
Javascript | Javascript | remove crufty variable | 1c70462de5b0aced98cc20602d5a53d63fe1ac9b | <ide><path>src/core/timer.js
<ide> function d3_timer(callback, delay) {
<ide> function d3_timer_step() {
<ide> var elapsed,
<ide> now = Date.now(),
<del> t0 = null,
<ide> t1 = d3_timer_queue;
<ide>
<ide> while (t1) {
<ide> elapsed = now - t1.then;
<ide> if (elapsed > t1.delay) t1.flush = t1.callback(elapsed);
<del> t1 = (t0 = t1).next;
<add> t1 = t1.next;
<ide> }
<ide>
<ide> var delay = d3_timer_flush() - now; | 1 |
Java | Java | add propagatequeryparams property to redirectview | 0bbb7704b517f0721ee1ac810b854fbc3f30697f | <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/view/RedirectView.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import org.springframework.web.util.WebUtils;
<ide>
<ide> /**
<del> * <p>View that redirects to an absolute, context relative, or current request
<add> * View that redirects to an absolute, context relative, or current request
<ide> * relative URL. The URL may be a URI template in which case the URI template
<ide> * variables will be replaced with values available in the model. By default
<ide> * all primitive model attributes (or collections thereof) are exposed as HTTP
<ide> public class RedirectView extends AbstractUrlBasedView implements SmartView {
<ide>
<ide> private boolean expandUriTemplateVariables = true;
<ide>
<add> private boolean propagateQueryParams = false;
<add>
<ide>
<ide> /**
<ide> * Constructor for use as a bean.
<ide> public void setExpandUriTemplateVariables(boolean expandUriTemplateVariables) {
<ide> this.expandUriTemplateVariables = expandUriTemplateVariables;
<ide> }
<ide>
<add> /**
<add> * When set to {@code true} the query string of the current URL is appended
<add> * and thus propagated through to the redirected URL.
<add> * <p>Defaults to {@code false}.
<add> * @since 4.1
<add> */
<add> public void setPropagateQueryParams(boolean propagateQueryParams) {
<add> this.propagateQueryParams = propagateQueryParams;
<add> }
<add>
<add> /**
<add> * Whether to propagate the query params of the current URL.
<add> * @since 4.1
<add> */
<add> public boolean isPropagateQueryProperties() {
<add> return this.propagateQueryParams;
<add> }
<add>
<ide> /**
<ide> * Returns "true" indicating this view performs a redirect.
<ide> */
<ide> protected final String createTargetUrl(Map<String, Object> model, HttpServletReq
<ide> Map<String, String> variables = getCurrentRequestUriVariables(request);
<ide> targetUrl = replaceUriTemplateVariables(targetUrl.toString(), model, variables, enc);
<ide> }
<add> if (isPropagateQueryProperties()) {
<add> appendCurrentQueryParams(targetUrl, request);
<add> }
<ide> if (this.exposeModelAttributes) {
<ide> appendQueryProperties(targetUrl, model, enc);
<ide> }
<ide> protected StringBuilder replaceUriTemplateVariables(
<ide>
<ide> @SuppressWarnings("unchecked")
<ide> private Map<String, String> getCurrentRequestUriVariables(HttpServletRequest request) {
<del> Map<String, String> uriVars =
<del> (Map<String, String>) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
<add> String name = HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE;
<add> Map<String, String> uriVars = (Map<String, String>) request.getAttribute(name);
<ide> return (uriVars != null) ? uriVars : Collections.<String, String> emptyMap();
<ide> }
<ide>
<add> /**
<add> * Append the query string of the current request to the target redirect URL.
<add> * @param targetUrl the StringBuilder to append the properties to
<add> * @param request the current request
<add> * @since 4.1
<add> */
<add> protected void appendCurrentQueryParams(StringBuilder targetUrl, HttpServletRequest request) {
<add>
<add> String query = request.getQueryString();
<add> if (StringUtils.hasText(query)) {
<add>
<add> // Extract anchor fragment, if any.
<add> String fragment = null;
<add> int anchorIndex = targetUrl.indexOf("#");
<add> if (anchorIndex > -1) {
<add> fragment = targetUrl.substring(anchorIndex);
<add> targetUrl.delete(anchorIndex, targetUrl.length());
<add> }
<add>
<add> if (targetUrl.toString().indexOf('?') < 0) {
<add> targetUrl.append('?').append(query);
<add> }
<add> else {
<add> targetUrl.append('&').append(query);
<add> }
<add>
<add> // Append anchor fragment, if any, to end of URL.
<add> if (fragment != null) {
<add> targetUrl.append(fragment);
<add> }
<add> }
<add> }
<add>
<ide> /**
<ide> * Append query properties to the redirect URL.
<ide> * Stringifies, URL-encodes and formats model attributes as query properties.
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/view/RedirectViewTests.java
<ide> public void objectConversion() throws Exception {
<ide> doTest(model, url, false, expectedUrlForEncoding);
<ide> }
<ide>
<add> @Test
<add> public void propagateQueryParams() throws Exception {
<add> RedirectView rv = new RedirectView();
<add> rv.setPropagateQueryParams(true);
<add> rv.setUrl("http://url.somewhere.com?foo=bar#bazz");
<add> MockHttpServletRequest request = createRequest();
<add> MockHttpServletResponse response = new MockHttpServletResponse();
<add> request.setQueryString("a=b&c=d");
<add> rv.render(new HashMap<String, Object>(), request, response);
<add> assertEquals(302, response.getStatus());
<add> assertEquals("http://url.somewhere.com?foo=bar&a=b&c=d#bazz", response.getHeader("Location"));
<add> }
<add>
<ide> private void doTest(Map<String, ?> map, String url, boolean contextRelative, String expectedUrlForEncoding)
<ide> throws Exception {
<ide> doTest(map, url, contextRelative, true, expectedUrlForEncoding); | 2 |
Javascript | Javascript | fix parentview and nearestchildof documentation | 4fba5a1e6c8016c74649224280318d43074d8983 | <ide><path>packages/ember-views/lib/views/view.js
<ide> Ember.View = Ember.Object.extend(Ember.Evented,
<ide> @type Ember.View
<ide> @default null
<ide> */
<del> _parentView: null,
<del>
<ide> parentView: Ember.computed(function() {
<ide> var parent = get(this, '_parentView');
<ide>
<ide> Ember.View = Ember.Object.extend(Ember.Evented,
<ide> }
<ide> }).property('_parentView').volatile(),
<ide>
<add> _parentView: null,
<add>
<ide> // return the current view, not including virtual views
<ide> concreteView: Ember.computed(function() {
<ide> if (!this.isVirtual) { return this; }
<ide> Ember.View = Ember.Object.extend(Ember.Evented,
<ide> },
<ide>
<ide> /**
<del> Return the nearest ancestor that is a direct child of a
<del> view of.
<add> Return the nearest ancestor whose parent is an instance of
<add> `klass`.
<ide>
<ide> @param {Class} klass Subclass of Ember.View (or Ember.View itself)
<ide> @returns Ember.View | 1 |
Javascript | Javascript | replace fixturesdir with fixtures method | 1c28dfa09a443bab9f72fd1d89a4f645de8c5a42 | <ide><path>test/parallel/test-https-byteswritten.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<add>const fixtures = require('../common/fixtures');
<ide> if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<ide>
<ide> const assert = require('assert');
<del>const fs = require('fs');
<ide> const https = require('https');
<ide>
<ide> const options = {
<del> key: fs.readFileSync(`${common.fixturesDir}/keys/agent1-key.pem`),
<del> cert: fs.readFileSync(`${common.fixturesDir}/keys/agent1-cert.pem`)
<add> key: fixtures.readKey('agent1-key.pem'),
<add> cert: fixtures.readKey('agent1-cert.pem')
<ide> };
<ide>
<ide> const body = 'hello world\n'; | 1 |
Javascript | Javascript | get profile data in getvenmo controller | 81d4712ba9345afa5bf9ea25374edc541a47223d | <ide><path>app.js
<ide> app.get('/auth/tumblr', passport.authorize('tumblr'));
<ide> app.get('/auth/tumblr/callback', passport.authorize('tumblr', { failureRedirect: '/api' }), function(req, res) {
<ide> res.redirect('/api/tumblr');
<ide> });
<del>app.get('/auth/venmo', passport.authorize('venmo', { scope: 'access_profile make_payments' }));
<add>app.get('/auth/venmo', passport.authorize('venmo', { scope: 'make_payments access_profile access_balance access_email access_phone' }));
<ide> app.get('/auth/venmo/callback', passport.authorize('venmo', { failureRedirect: '/api' }), function(req, res) {
<ide> console.log('Success');
<ide> res.redirect('/api/venmo');
<ide><path>controllers/api.js
<ide> exports.postTwilio = function(req, res, next) {
<ide> };
<ide>
<ide> exports.getVenmo = function(req, res, next) {
<del> res.render('api/venmo', {
<del> title: 'Venmo API'
<add> var token = _.findWhere(req.user.tokens, { kind: 'venmo' });
<add> var query = querystring.stringify({ access_token: token.accessToken });
<add> request.get({ url: 'https://api.venmo.com/v1/me?' + query, json: true }, function(err, request, body) {
<add> if (err) return next(err);
<add> res.render('api/venmo', {
<add> title: 'Venmo API',
<add> profile: body.data
<add> });
<add>
<ide> });
<add>
<ide> };
<ide>\ No newline at end of file | 2 |
Go | Go | calculate pid file after root | 7453d028daaba786b7eaa55ce739e24becd09a33 | <ide><path>cmd/dockerd/docker.go
<ide> package main
<ide> import (
<ide> "fmt"
<ide> "os"
<add> "path/filepath"
<add> "runtime"
<ide>
<ide> "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/cli"
<ide> func runDaemon(opts daemonOptions) error {
<ide>
<ide> daemonCli := NewDaemonCli()
<ide>
<add> // On Windows, if there's no explicit pidfile set, set to under the daemon root
<add> if runtime.GOOS == "windows" && opts.daemonConfig.Pidfile == "" {
<add> opts.daemonConfig.Pidfile = filepath.Join(opts.daemonConfig.Root, "docker.pid")
<add> }
<add>
<ide> // On Windows, this may be launching as a service or with an option to
<ide> // register the service.
<ide> stop, err := initService(daemonCli)
<ide><path>daemon/config_windows.go
<ide> package daemon
<ide>
<ide> import (
<ide> "os"
<add> "path/filepath"
<ide>
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/spf13/pflag"
<ide> )
<ide>
<ide> var (
<del> defaultPidFile = os.Getenv("programdata") + string(os.PathSeparator) + "docker.pid"
<del> defaultGraph = os.Getenv("programdata") + string(os.PathSeparator) + "docker"
<add> defaultPidFile string
<add> defaultGraph = filepath.Join(os.Getenv("programdata"), "docker")
<ide> )
<ide>
<ide> // bridgeConfig stores all the bridge driver specific | 2 |
Go | Go | fix more goimports | 562880b276edb9130eab6adaab27d8aeb41ec388 | <ide><path>daemon/logger/splunk/splunk_test.go
<ide> func TestValidateLogOpt(t *testing.T) {
<ide> splunkVerifyConnectionKey: "true",
<ide> splunkGzipCompressionKey: "true",
<ide> splunkGzipCompressionLevelKey: "1",
<del> envKey: "a",
<del> envRegexKey: "^foo",
<del> labelsKey: "b",
<del> tagKey: "c",
<add> envKey: "a",
<add> envRegexKey: "^foo",
<add> labelsKey: "b",
<add> tagKey: "c",
<ide> })
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> func TestInlineFormatWithNonDefaultOptions(t *testing.T) {
<ide> splunkIndexKey: "myindex",
<ide> splunkFormatKey: splunkFormatInline,
<ide> splunkGzipCompressionKey: "true",
<del> tagKey: "{{.ImageName}}/{{.Name}}",
<del> labelsKey: "a",
<del> envRegexKey: "^foo",
<add> tagKey: "{{.ImageName}}/{{.Name}}",
<add> labelsKey: "a",
<add> envRegexKey: "^foo",
<ide> },
<ide> ContainerID: "containeriid",
<ide> ContainerName: "/container_name",
<ide><path>integration-cli/docker_cli_build_test.go
<ide> func (s *DockerSuite) TestBuildCopyWildcard(c *testing.T) {
<ide> "file2.txt": "test2",
<ide> "dir/nested_file": "nested file",
<ide> "dir/nested_dir/nest_nest_file": "2 times nested",
<del> "dirt": "dirty",
<add> "dirt": "dirty",
<ide> }))
<ide> defer ctx.Close()
<ide>
<ide><path>integration/build/build_test.go
<ide> func TestBuildWithRemoveAndForceRemove(t *testing.T) {
<ide> RUN exit 0
<ide> RUN exit 0`,
<ide> numberOfIntermediateContainers: 2,
<del> rm: false,
<del> forceRm: false,
<add> rm: false,
<add> forceRm: false,
<ide> },
<ide> {
<ide> name: "successful build with remove",
<ide> dockerfile: `FROM busybox
<ide> RUN exit 0
<ide> RUN exit 0`,
<ide> numberOfIntermediateContainers: 0,
<del> rm: true,
<del> forceRm: false,
<add> rm: true,
<add> forceRm: false,
<ide> },
<ide> {
<ide> name: "successful build with remove and force remove",
<ide> dockerfile: `FROM busybox
<ide> RUN exit 0
<ide> RUN exit 0`,
<ide> numberOfIntermediateContainers: 0,
<del> rm: true,
<del> forceRm: true,
<add> rm: true,
<add> forceRm: true,
<ide> },
<ide> {
<ide> name: "failed build with no removal",
<ide> dockerfile: `FROM busybox
<ide> RUN exit 0
<ide> RUN exit 1`,
<ide> numberOfIntermediateContainers: 2,
<del> rm: false,
<del> forceRm: false,
<add> rm: false,
<add> forceRm: false,
<ide> },
<ide> {
<ide> name: "failed build with remove",
<ide> dockerfile: `FROM busybox
<ide> RUN exit 0
<ide> RUN exit 1`,
<ide> numberOfIntermediateContainers: 1,
<del> rm: true,
<del> forceRm: false,
<add> rm: true,
<add> forceRm: false,
<ide> },
<ide> {
<ide> name: "failed build with remove and force remove",
<ide> dockerfile: `FROM busybox
<ide> RUN exit 0
<ide> RUN exit 1`,
<ide> numberOfIntermediateContainers: 0,
<del> rm: true,
<del> forceRm: true,
<add> rm: true,
<add> forceRm: true,
<ide> },
<ide> }
<ide>
<ide><path>integration/image/remove_unix_test.go
<ide> func TestRemoveImageGarbageCollector(t *testing.T) {
<ide>
<ide> layerStores := make(map[string]layer.Store)
<ide> layerStores[runtime.GOOS], _ = layer.NewStoreFromOptions(layer.StoreOptions{
<del> Root: d.Root,
<add> Root: d.Root,
<ide> MetadataStorePathTemplate: filepath.Join(d.RootDir(), "image", "%s", "layerdb"),
<ide> GraphDriver: d.StorageDriver(),
<ide> GraphDriverOptions: nil,
<ide><path>integration/service/jobs_test.go
<ide> func TestUpdateReplicatedJob(t *testing.T) {
<ide> id := swarm.CreateService(t, d,
<ide> swarm.ServiceWithMode(swarmtypes.ServiceMode{
<ide> ReplicatedJob: &swarmtypes.ReplicatedJob{
<del> // use the default, empty values.
<add> // use the default, empty values.
<ide> },
<ide> }),
<ide> // run "true" so the task exits with 0 | 5 |
Text | Text | fix typos in action cable guide [ci skip] | 2ff63580fe5636b384b2de9ce67b6f8d0ad8f622 | <ide><path>guides/source/action_cable_overview.md
<ide> client-server connection instance established per WebSocket connection.
<ide> ## Server-Side Components
<ide>
<ide> ### Connections
<del>Connections form the foundaton of the client-server relationship. For every WebSocket
<add>Connections form the foundation of the client-server relationship. For every WebSocket
<ide> the cable server is accepting, a Connection object will be instantiated. This instance
<del>becomes the parent of all the channel subscriptions that are created from there on.
<add>becomes the parent of all the channel subscriptions that are created from there on.
<ide> The Connection itself does not deal with any specific application logic beyond authentication
<del>and authorization. The client of a WebSocket connection is called the consumer.
<add>and authorization. The client of a WebSocket connection is called the consumer.
<ide> A single consumer may have multiple WebSockets open to your application if they
<del>use multiple browser tabs or devices.
<add>use multiple browser tabs or devices.
<ide>
<ide> Connections are instantiated via the `ApplicationCable::Connection` class in Ruby.
<ide> In this class, you authorize the incoming connection, and proceed to establish it
<ide> Note that anything marked as an identifier will automatically create a delegate
<ide> by the same name on any channel instances created off the connection.
<ide>
<ide> This relies on the fact that you will already have handled authentication of the user,
<del>and that a successful authentication sets a signed cookie with the `user_id`.
<add>and that a successful authentication sets a signed cookie with the `user_id`.
<ide> This cookie is then automatically sent to the connection instance when a new connection
<ide> is attempted, and you use that to set the `current_user`. By identifying the connection
<ide> by this same current_user, you're also ensuring that you can later retrieve all open
<ide> or deauthorized).
<ide>
<ide> ### Channels
<ide> A channel encapsulates a logical unit of work, similar to what a controller does in a
<del>regular MVC setup.
<add>regular MVC setup.
<ide> By default, Rails creates a parent `ApplicationCable::Channel` class for encapsulating
<del>shared logic between your channels.
<add>shared logic between your channels.
<ide>
<ide> #### Parent Channel Setup
<ide> ```ruby
<ide> This ensures that the signed cookie will be correctly sent.
<ide>
<ide> #### Subscriber
<ide> When a consumer is subscribed to a channel, they act as a subscriber. A
<del>consumer can act as a subscriber to a given channel any number of times.
<del>For example, a consumer could subscribe to multiple chat rooms at the same time.
<add>consumer can act as a subscriber to a given channel any number of times.
<add>For example, a consumer could subscribe to multiple chat rooms at the same time.
<ide> (remember that a physical user may have multiple consumers, one per tab/device open to your connection).
<ide>
<del>A consumer becomes a subscriber, by creating a subscribtion to a given channel:
<add>A consumer becomes a subscriber, by creating a subscription to a given channel:
<ide> ```coffeescript
<ide> # app/assets/javascripts/cable/subscriptions/chat.coffee
<ide> # Assumes you've already requested the right to send web notifications
<ide> end
<ide>
<ide> A broadcasting is a pub/sub link where anything transmitted by a publisher
<ide> is routed directly to the channel subscribers who are streaming that named
<del>broadcasting. Each channel can be streaming zero or more broadcastings.
<del>Broadcastings are purely an online queue and time dependent;
<add>broadcasting. Each channel can be streaming zero or more broadcastings.
<add>Broadcastings are purely an online queue and time dependent;
<ide> If a consumer is not streaming (subscribed to a given channel), they'll not
<ide> get the broadcast should they connect later.
<ide>
<ide> callback.
<ide>
<ide> ### Subscriptions
<ide>
<del>When a consumer is subscribed to a channel, they act as a subscriber;
<add>When a consumer is subscribed to a channel, they act as a subscriber;
<ide> This connection is called a subscription. Incoming messages are then routed
<del>to these channel subscriptions based on an identifier sent by the cable consumer.
<add>to these channel subscriptions based on an identifier sent by the cable consumer.
<ide>
<ide> ```coffeescript
<ide> # app/assets/javascripts/cable/subscriptions/chat.coffee
<ide> App.cable.subscriptions.create "AppearanceChannel",
<ide> The appearance example was all about exposing server functionality to
<ide> client-side invocation over the WebSocket connection. But the great thing
<ide> about WebSockets is that it's a two-way street. So now let's show an example
<del>where the server invokesan action on the client.
<add>where the server invokes an action on the client.
<ide>
<ide> This is a web notification channel that allows you to trigger client-side
<ide> web notifications when you broadcast to the right streams:
<ide>
<ide> #### Create the server-side Web Notifications Channel:
<del>
<add>
<ide> ```ruby
<ide> # app/channels/web_notifications_channel.rb
<ide> class WebNotificationsChannel < ApplicationCable::Channel
<ide> this would be something like: `App.cable = ActionCable.createConsumer("ws://exam
<ide> and for an in-app server, something like: `App.cable = ActionCable.createConsumer("/cable")`.
<ide>
<ide> The second option is to pass the server url through the `action_cable_meta_tag` in your layout.
<del>This uses a url or path typically set via `config.action_cable.url`
<add>This uses a url or path typically set via `config.action_cable.url`
<ide> in the environment configuration files, or defaults to "/cable".
<ide>
<ide> This method is especially useful if your WebSocket url might change
<ide> between environments. If you host your production server via https,
<del>you will need to use the wss scheme for your ActionCable server, but
<add>you will need to use the wss scheme for your ActionCable server, but
<ide> development might remain http and use the ws scheme. You might use localhost
<ide> in development and your domain in production.
<ide>
<ide> end
<ide>
<ide> You can use `App.cable = ActionCable.createConsumer()` to connect to the
<ide> cable server if `action_cable_meta_tag` is included in the layout. A custom
<del>path is specified as first argument to `createConsumer`
<add>path is specified as first argument to `createConsumer`
<ide> (e.g. `App.cable = ActionCable.createConsumer("/websocket")`).
<ide>
<ide> For every instance of your server you create and for every worker
<ide> your server spawns, you will also have a new instance of ActionCable,
<del>but the use of Redis keeps messages synced across connections.
<add>but the use of Redis keeps messages synced across connections.
<ide>
<ide> ### Standalone
<del>The cable server(s) can be separated from your normal application server.
<add>The cable server(s) can be separated from your normal application server.
<ide> It's still a Rack application, but it is its own Rack application.
<ide> The recommended basic setup is as follows:
<ide>
<ide> The above will start a cable server on port 28080.
<ide> Beware that currently the cable server will _not_ auto-reload any
<ide> changes in the framework. As we've discussed, long-running cable
<ide> connections mean long-running objects. We don't yet have a way of
<del>reloading the classes of those objects in a safe manner. So when
<add>reloading the classes of those objects in a safe manner. So when
<ide> you change your channels, or the model your channels use, you must
<ide> restart the cable server.
<ide>
<ide> The Ruby side of things is built on top of [websocket-driver](https://github.com
<ide> ## Deployment
<ide>
<ide> Action Cable is powered by a combination of WebSockets and threads. Both the
<del>framework plumbing and user-specified channel work are handled internally by
<del>utilizing Ruby's native thread support. This means you can use all your regular
<add>framework plumbing and user-specified channel work are handled internally by
<add>utilizing Ruby's native thread support. This means you can use all your regular
<ide> Rails models with no problem, as long as you haven't committed any thread-safety sins.
<ide>
<del>The Action Cable server implements the Rack socket hijacking API,
<add>The Action Cable server implements the Rack socket hijacking API,
<ide> thereby allowing the use of a multithreaded pattern for managing connections
<ide> internally, irrespective of whether the application server is multi-threaded or not.
<ide> | 1 |
Python | Python | set version to v2.1.0a8.dev1 | f75be6e7be0f5fac33a43d8ac3075e48784285ac | <ide><path>spacy/about.py
<ide> # fmt: off
<ide>
<ide> __title__ = "spacy-nightly"
<del>__version__ = "2.1.0a8.dev0"
<add>__version__ = "2.1.0a8.dev1"
<ide> __summary__ = "Industrial-strength Natural Language Processing (NLP) with Python and Cython"
<ide> __uri__ = "https://spacy.io"
<ide> __author__ = "Explosion AI" | 1 |
Text | Text | update description of nonprofit projects | 039854361e7aa374d30ec7821ca2e314d37ae282 | <ide><path>guide/english/miscellaneous/how-free-code-camps-nonprofits-projects-work/index.md
<ide> ---
<ide> title: How Free Code Camps Nonprofits Projects Work
<ide> ---
<del>Building nonprofit projects is the main way that our campers learn full stack JavaScript and agile software development. You'll begin this process once you've earned your Front End Development, Data Visualization, and Back End Development certifications.
<ide>
<del>## Starting with the end in mind
<add>In the past, freeCodeCamp.org built one-off projects for individual nonprofits.
<ide>
<del>Our goal at Free Code Camp is to help you land a job as a software developer or get promoted in your current company to a more technical role.
<add>This was a very hands-on, time-consuming process, and only a few people were able to participate in each project.
<ide>
<del>You'll continue to work on nonprofit projects until you've built a sufficiently impressive portfolio and references to start your job search. Your portfolio will ultimately have four nonprofit projects. We estimate that the 800 hours of nonprofit projects and 80 hours of interview prep you're going to complete, in addition to the 1,200 hours of challenges you've already completed by this point, will be more than enough to qualify you for your first coding job.
<add>We've instead switched to building more general open source projects that many nonprofits can make use of.
<ide>
<del>## Your first Nonprofit Project
<add>For example, we built and maintain [Mail for Good](https://github.com/freecodecamp/mail-for-good), which nonprofits (including freeCodeCamp.org itself) can use to send emails at a mere fraction of traditional email services (it only costs $1 to send 10,000 emails).
<ide>
<del>We generally scope Nonprofit Projects to 200 hours, or about 10 weeks at 20 hours per week of development per camper. These are only rough estimates. You'll only work on one project at a time.
<add>We have a ton of additional projects we plan to build in the near future, too.
<ide>
<del>You will choose another camper to partner with on this projects. You should choose your them based on:
<add>You can contribute to these open source projects whenever you feel ready.
<ide>
<del>* Your estimated time commitment (10, 20 or 40 hours per week)
<del>* Your time zones (Will you be able to pair program together?)
<del>* Prior coding experience (we'd like both campers to be able to contribute equally)
<del>
<del>We won't take age or gender into account. This will provide you with valuable experience in meshing with diverse teams, which is a reality of the contemporary workplace.
<del>
<del>Then, you'll email team@freecodecamp.com with:
<del>
<del>* Names
<del>* Contact information
<del>* Links to each of your Free Code Camp code portfolios
<del>* Timezones
<del>* Hours pledged per week
<del>
<del>We'll send you a list of 3 nonprofit projects that need your help, and together you will choose one to begin work on. While you do this, our team will code review each of your code portfolios to ensure that all user stories have been completed, and that there are no signs of academic dishonesty.
<del>
<del>### Beginning the Project
<del>
<del>We'll set an initial meeting with representatives from Free Code Camp, the two campers, and the stakeholder. If the stakeholder and both campers show up promptly, and seem enthusiastic and professional, we'll start the project. This lengthy process serves an important purpose: it reduces the likelihood that any of our campers or stakeholders will waste their precious time.
<del>
<del>### Nonprofit Stakeholders
<del>
<del>Each nonprofit project was submitted by a nonprofit. A representative from this nonprofit has agreed to serve as a "stakeholder" - an authorative person who understands the organization and its needs for this particular project.
<del>
<del>Stakeholders have a deep understanding of their organizations' needs. Campers will work with them to figure out the best solutions to these needs.
<del>
<del>When you and your pair partner first speak with your nonprofit stakeholder, you'll:
<del>
<del>* talk at length to better understand their needs.
<del>* create a new Trello board and use it to prioritize what needs to be built.
<del>* and establish deadlines based on your weekly time commitment, and how long you think each task will take.
<del>
<del>Ideally, we'll scope each project to be completed in 10 sprints. It's notoriously difficult to estimate how long building software projects will take, so feel free to ask our volunteer team for help.
<del>
<del>You'll continue to meet with your stakeholder weekly using the conference software GoToMeeting. You will also correspond with the team on the project's Trello board.
<del>
<del>Getting "blocked" on a task can take away your sense of forward momentum, so be sure to proactively seek answers to any ambiguities you encounter.
<del>
<del>Ultimately, the project will be considered complete once the stakeholder's needs have been met, and you and your partner are happy with the project. Then you can add it to your portfolio!
<del>
<del>### Working with your Pair
<del>
<del>You and your pair will pair program (code together on the same computer virtually) about half of the time, and work independently the other half of the time.
<del>
<del>Here are our recommended ways of collaborating:
<del>
<del>* Gitter has robust private messaging functionality. It's the main way our team communicates, and we recommend it over email.
<del>* Trello is great for managing projects. Work with your stakeholder to create Trello cards, and update these cards regularly as you make progress on them.
<del>* Screen Hero or Team Viewer - These are the ideal way to pair program. Tools like TMUX are good, but difficult to use. We discourage you from using screen sharing tools where only one person has control of the keyboard and mouse - that isn't real pair programming.
<del>* Write clear and readable code, commit messages, branch names, and pull request messages.
<del>
<del>### Hosting Apps
<del>
<del>Unless your stakeholder has an existing modern host (AWS, Digital Ocean), you'll need to transition them over to a new platform. We believe Heroku is the best choice for a vast majority of web projects. It's free, easy to use, and has both browser and command line interfaces. It's owned by Salesforce and used by a ton of companies, so it's accountable and unlikely to go away.
<del>
<del>If you need help convincing your stakeholder that Heroku is the ideal platform, we'll be happy to talk with them.
<del>
<del>### Maintaining Apps
<del>
<del>Once you complete a nonprofit project, your obligation to its stakeholder is finished. Your goal is to leave behind a well documented solution that can be easily maintained by a contract JavaScript developer (or even a less-technical "super user").
<del>
<del>While you will no longer need to help with feature development, we encourage you to consider helping your stakeholder with occasional patches down the road. After all, this project will be an important piece of your portfolio, and you'll want it to remain in good shape for curious future employers.
<del>
<del>### Pledging to finish the project
<del>
<del>Your nonprofit stakeholder, your pair partner, and our volunteer team are all counting on you to finish your nonprofit project. If you walk away from an unfinished nonprofit project, you'll become ineligible to ever be assigned another one.
<del>
<del>To confirm that you understand the seriousness of this commitment, we require that all campers <a href='http://goo.gl/forms/ZMn96z2QqY' target='_blank' rel='nofollow'>sign this pledge</a> before starting on their nonprofit projects.
<del>
<del>There will likely be times of confusion or frustration. This is normal in software development. The most important thing is that you do not give up and instead persevere through these setbacks. As Steve Jobs famously said, "Real artists ship." And you are going to ship one successful nonprofit project after another until you feel ready to take the next step in your promising career.
<ide>\ No newline at end of file
<add>Clone one of these repositories, get it running locally on your computer, then start browsing the repo's open issues for an issue to work on. If you have questions, you can ask any time in the [Contributors section of our forum](https://www.freecodecamp.org/forum/c/contributors) | 1 |
Mixed | Javascript | pass the hover event to the onhover event handler | 152ce9c9f83e3678aee663ee250d7cda06bb3b99 | <ide><path>docs/01-Chart-Configuration.md
<ide> responsive | Boolean | true | Resizes the chart canvas when its container does.
<ide> responsiveAnimationDuration | Number | 0 | Duration in milliseconds it takes to animate to new size after a resize event.
<ide> maintainAspectRatio | Boolean | true | Maintain the original canvas aspect ratio `(width / height)` when resizing
<ide> events | Array[String] | `["mousemove", "mouseout", "click", "touchstart", "touchmove", "touchend"]` | Events that the chart should listen to for tooltips and hovering
<del>onClick | Function | null | Called if the event is of type 'mouseup' or 'click'. Called in the context of the chart and passed an array of active elements
<add>onClick | Function | null | Called if the event is of type 'mouseup' or 'click'. Called in the context of the chart and passed the event and an array of active elements
<ide> legendCallback | Function | ` function (chart) { }` | Function to generate a legend. Receives the chart object to generate a legend from. Default implementation returns an HTML string.
<ide> onResize | Function | null | Called when a resize occurs. Gets passed two arguments: the chart instance and the new size.
<ide>
<ide> Name | Type | Default | Description
<ide> mode | String | 'nearest' | Sets which elements appear in the tooltip. See [Interaction Modes](#interaction-modes) for details
<ide> intersect | Boolean | true | if true, the hover mode only applies when the mouse position intersects an item on the chart
<ide> animationDuration | Number | 400 | Duration in milliseconds it takes to animate hover style changes
<del>onHover | Function | null | Called when any of the events fire. Called in the context of the chart and passed an array of active elements (bars, points, etc)
<add>onHover | Function | null | Called when any of the events fire. Called in the context of the chart and passed the event and an array of active elements (bars, points, etc)
<ide>
<ide> ### Interaction Modes
<ide> When configuring interaction with the graph via hover or tooltips, a number of different modes are available.
<ide><path>src/core/core.controller.js
<ide> module.exports = function(Chart) {
<ide>
<ide> // On Hover hook
<ide> if (hoverOptions.onHover) {
<del> hoverOptions.onHover.call(me, me.active);
<add> hoverOptions.onHover.call(me, e, me.active);
<ide> }
<ide>
<ide> if (e.type === 'mouseup' || e.type === 'click') { | 2 |
Ruby | Ruby | emulate dylinker behavior | 27d6cfb12e0a5cac753ab1b1157ebfb9d371f4f3 | <ide><path>Library/Homebrew/extend/os/mac/keg_relocate.rb
<ide> def fix_dynamic_linkage
<ide> generic_fix_dynamic_linkage
<ide> end
<ide>
<add> def expand_rpath(file, bad_name)
<add> suffix = bad_name.sub(/^@rpath/, "")
<add>
<add> # short circuit: we expect lib to be usually correct, so we try it first
<add> return (lib + suffix) if (lib + suffix).exist?
<add>
<add> file.rpaths.each do |rpath|
<add> return (rpath + suffix) if (rpath + suffix).exist?
<add> end
<add>
<add> opoo "Could not expand an RPATH in #{file}"
<add> bad_name
<add> end
<add>
<ide> # If file is a dylib or bundle itself, look for the dylib named by
<ide> # bad_name relative to the lib directory, so that we can skip the more
<ide> # expensive recursive search if possible.
<ide> def fixed_name(file, bad_name)
<ide> elsif file.mach_o_executable? && (lib + bad_name).exist?
<ide> "#{lib}/#{bad_name}"
<ide> elsif bad_name.start_with? "@rpath"
<del> bad_name.sub("@rpath", lib)
<add> expand_rpath bad_name
<ide> elsif (abs_name = find_dylib(bad_name)) && abs_name.exist?
<ide> abs_name.to_s
<ide> else | 1 |
Java | Java | fix checkstyle violation (plus related polishing) | e485abbe5628e1817c66e96d7703d523cec8a2cb | <ide><path>spring-web/src/main/java/org/springframework/http/HttpHeaders.java
<ide> public ZonedDateTime getFirstZonedDateTime(String headerName) {
<ide> * {@link IllegalArgumentException} ({@code true}) or rather return {@code null}
<ide> * in that case ({@code false})
<ide> * @return the parsed date header, or {@code null} if none (or invalid)
<del> */
<add> */
<ide> @Nullable
<ide> private ZonedDateTime getFirstZonedDateTime(String headerName, boolean rejectInvalid) {
<ide> String headerValue = getFirst(headerName);
<ide> public static HttpHeaders readOnlyHttpHeaders(HttpHeaders headers) {
<ide> }
<ide>
<ide> /**
<del> * Returns a {@code HttpHeaders} consumer that adds Basic Authentication.
<add> * Return a {@code HttpHeaders} consumer that adds Basic Authentication.
<ide> * More specifically: a consumer that adds an {@linkplain #AUTHORIZATION
<del> * Authorization} header based on the given username and password. Meant
<del> * to be used in combination with
<add> * Authorization} header based on the given username and password.
<add> * Meant to be used in combination with
<ide> * {@link org.springframework.web.reactive.function.client.WebClient.RequestHeadersSpec#headers(java.util.function.Consumer)}.
<ide> * <p>Note that Basic Authentication only supports characters in the
<ide> * {@linkplain StandardCharsets#ISO_8859_1 ISO-8859-1} character set.
<del> *
<ide> * @param username the username
<ide> * @param password the password
<ide> * @return a consumer that adds a Basic Authentication header
<add> * @since 5.1
<ide> */
<del> public static Consumer<HttpHeaders> basicAuthenticationConsumer(String username,String password) {
<add> public static Consumer<HttpHeaders> basicAuthenticationConsumer(String username, String password) {
<ide> return basicAuthenticationConsumer(() -> username, () -> password);
<ide>
<ide> }
<ide>
<ide> /**
<del> * Returns a {@code HttpHeaders} consumer that adds Basic Authentication.
<add> * Return a {@code HttpHeaders} consumer that adds Basic Authentication.
<ide> * More specifically: a consumer that adds an {@linkplain #AUTHORIZATION
<ide> * Authorization} header based on the given username and password
<ide> * suppliers. Meant to be used in combination with
<ide> * {@link org.springframework.web.reactive.function.client.WebClient.RequestHeadersSpec#headers(java.util.function.Consumer)}.
<ide> * <p>Note that Basic Authentication only supports characters in the
<ide> * {@linkplain StandardCharsets#ISO_8859_1 ISO-8859-1} character set.
<del> *
<ide> * @param usernameSupplier supplier for the username
<ide> * @param passwordSupplier supplier for the password
<ide> * @return a consumer that adds a Basic Authentication header
<add> * @since 5.1
<ide> */
<del> public static Consumer<HttpHeaders> basicAuthenticationConsumer(Supplier<String> usernameSupplier,
<del> Supplier<String> passwordSupplier) {
<add> public static Consumer<HttpHeaders> basicAuthenticationConsumer(
<add> Supplier<String> usernameSupplier, Supplier<String> passwordSupplier) {
<ide>
<ide> Assert.notNull(usernameSupplier, "Username Supplier must not be null");
<ide> Assert.notNull(passwordSupplier, "Password Supplier must not be null");
<del>
<ide> return new BasicAuthenticationConsumer(usernameSupplier, passwordSupplier);
<ide> }
<ide>
<ide>
<del> /**
<del> * @see #basicAuthenticationConsumer
<del> */
<ide> private static class BasicAuthenticationConsumer implements Consumer<HttpHeaders> {
<ide>
<ide> private final Supplier<String> usernameSupplier;
<ide>
<ide> private final Supplier<String> passwordSupplier;
<ide>
<del> public BasicAuthenticationConsumer(Supplier<String> usernameSupplier,
<del> Supplier<String> passwordSupplier) {
<add> public BasicAuthenticationConsumer(Supplier<String> usernameSupplier, Supplier<String> passwordSupplier) {
<ide> this.usernameSupplier = usernameSupplier;
<ide> this.passwordSupplier = passwordSupplier;
<ide> }
<ide> public BasicAuthenticationConsumer(Supplier<String> usernameSupplier,
<ide> public void accept(HttpHeaders httpHeaders) {
<ide> String username = this.usernameSupplier.get();
<ide> String password = this.passwordSupplier.get();
<del>
<ide> Assert.state(username != null, "Supplied username is null");
<ide> Assert.state(password != null, "Supplied password is null");
<del>
<ide> checkIllegalCharacters(username, password);
<ide>
<ide> String credentialsString = username + ":" + password;
<ide> byte[] credentialBytes = credentialsString.getBytes(StandardCharsets.ISO_8859_1);
<ide> byte[] encodedBytes = Base64.getEncoder().encode(credentialBytes);
<ide> String encodedCredentials = new String(encodedBytes, StandardCharsets.ISO_8859_1);
<del>
<ide> httpHeaders.set(HttpHeaders.AUTHORIZATION, "Basic " + encodedCredentials);
<ide> }
<ide>
<ide> private static void checkIllegalCharacters(String username, String password) {
<ide> "Username or password contains characters that cannot be encoded to ISO-8859-1");
<ide> }
<ide> }
<del>
<ide> }
<add>
<ide> } | 1 |
Python | Python | handle non-int port arguments gracefully | 503147f17e51c986ea4059f7f74f2f48582693a5 | <ide><path>glances/glances.py
<ide> def main():
<ide> sys.exit(2)
<ide> server_ip = arg
<ide> elif opt in ("-p", "--port"):
<add> try:
<add> port_number = int(arg)
<add> except:
<add> print("invalid port number argument: %s" % arg)
<add> sys.exit(2)
<ide> server_port = arg
<ide> elif opt in ("-o", "--output"):
<ide> if arg.lower() == "html": | 1 |
Javascript | Javascript | remove blank lines at end of files | 5b2a8053cbe9d2a76477c3e49cc40f0d4953f3ac | <ide><path>test/debugger/test-debugger-repl-utf8.js
<ide> var script = common.fixturesDir + '/breakpoints_utf8.js';
<ide> process.env.NODE_DEBUGGER_TEST_SCRIPT = script;
<ide>
<ide> require('./test-debugger-repl.js');
<del>
<ide><path>test/gc/test-http-client-onerror.js
<ide> function status() {
<ide> process.exit(0);
<ide> }
<ide> }
<del>
<ide><path>test/known_issues/test-stdout-buffer-flush-on-exit.js
<ide> if (process.argv[2] === 'child') {
<ide>
<ide> assert.strictEqual(stdout, longLine, `failed with exponent ${exponent}`);
<ide> });
<del>
<del>
<ide><path>test/message/2100bytes.js
<ide> console.log([
<ide> '_____________________________________________2050',
<ide> '_____________________________________________2100'
<ide> ].join('\n'));
<del>
<ide><path>test/parallel/test-domain-stack-empty-in-process-uncaughtexception.js
<ide> process.on('beforeExit', common.mustCall(function onBeforeExit() {
<ide> d.run(function() {
<ide> throw new Error('boom');
<ide> });
<del>
<ide><path>test/parallel/test-eval-require.js
<ide> var child = spawn(process.execPath, ['-e', 'require("foo")'], options);
<ide> child.on('exit', function(code) {
<ide> assert.equal(code, 0);
<ide> });
<del>
<ide><path>test/parallel/test-event-emitter-special-event-names.js
<ide> process.on('__proto__', common.mustCall(function(val) {
<ide> assert.strictEqual(val, 1);
<ide> }));
<ide> process.emit('__proto__', 1);
<del>
<ide><path>test/parallel/test-fs-chmod.js
<ide> process.on('exit', function() {
<ide> assert.equal(0, openCount);
<ide> assert.equal(false, got_error);
<ide> });
<del>
<ide><path>test/parallel/test-http-client-abort2.js
<ide> server.listen(0, function() {
<ide> });
<ide> });
<ide> });
<del>
<ide><path>test/parallel/test-http-client-race-2.js
<ide> process.on('exit', function() {
<ide> assert.equal(body2_s, body2);
<ide> assert.equal(body3_s, body3);
<ide> });
<del>
<ide><path>test/parallel/test-http-exceptions.js
<ide> process.on('uncaughtException', function(err) {
<ide> if (err.name === 'AssertionError') throw err;
<ide> if (++exception_count === 4) process.exit(0);
<ide> });
<del>
<ide><path>test/parallel/test-http-keepalive-maxsockets.js
<ide> server.listen(0, function() {
<ide> }, 0);
<ide> }
<ide> });
<del>
<ide><path>test/parallel/test-http-mutable-headers.js
<ide> function nextTest() {
<ide> process.on('exit', function() {
<ide> assert.equal(4, testsComplete);
<ide> });
<del>
<ide><path>test/parallel/test-http-request-dont-override-options.js
<ide> http.createServer(function(req, res) {
<ide> assert.strictEqual(options.method, undefined);
<ide> });
<ide> }).unref();
<del>
<ide><path>test/parallel/test-http-request-end-twice.js
<ide> server.listen(0, function() {
<ide> res.resume();
<ide> });
<ide> });
<del>
<ide><path>test/parallel/test-http-response-readable.js
<ide> testServer.listen(0, function() {
<ide> res.resume();
<ide> });
<ide> });
<del>
<ide><path>test/parallel/test-http-response-statuscode.js
<ide> server.on('listening', function makeRequest() {
<ide> res.resume();
<ide> });
<ide> });
<del>
<ide><path>test/parallel/test-http-status-code.js
<ide> function nextTest() {
<ide> process.on('exit', function() {
<ide> assert.equal(5, testsComplete);
<ide> });
<del>
<ide><path>test/parallel/test-listen-fd-detached-inherit.js
<ide> function child() {
<ide> console.error('child listening on fd=3');
<ide> });
<ide> }
<del>
<ide><path>test/parallel/test-listen-fd-detached.js
<ide> function child() {
<ide> console.error('child listening on fd=3');
<ide> });
<ide> }
<del>
<ide><path>test/parallel/test-net-reconnect.js
<ide> process.on('exit', function() {
<ide> assert.equal(N + 1, client_recv_count);
<ide> assert.equal(N + 1, client_end_count);
<ide> });
<del>
<ide><path>test/parallel/test-next-tick-errors.js
<ide> process.on('uncaughtException', function() {
<ide> process.on('exit', function() {
<ide> assert.deepStrictEqual(['A', 'B', 'C'], order);
<ide> });
<del>
<ide><path>test/parallel/test-pipe-return-val.js
<ide> var destStream = new Stream();
<ide> var result = sourceStream.pipe(destStream);
<ide>
<ide> assert.strictEqual(result, destStream);
<del>
<ide><path>test/parallel/test-pipe-stream.js
<ide> function test(clazz, cb) {
<ide> test(net.Stream, function() {
<ide> test(net.Socket);
<ide> });
<del>
<ide><path>test/parallel/test-regress-GH-1899.js
<ide> child.on('exit', function(code, signal) {
<ide> assert.equal(code, 0);
<ide> assert.equal(output, 'hello, world!\n');
<ide> });
<del>
<ide><path>test/parallel/test-stdin-pipe-resume.js
<ide> if (process.argv[2] === 'child') {
<ide> child.stdin.end();
<ide> }, 10);
<ide> }
<del>
<ide><path>test/parallel/test-stream2-pipe-error-once-listener.js
<ide> process.on('exit', function(c) {
<ide> });
<ide>
<ide> read.pipe(write);
<del>
<ide><path>test/parallel/test-utf8-scripts.js
<ide> var assert = require('assert');
<ide> console.log('Σὲ γνωρίζω ἀπὸ τὴν κόψη');
<ide>
<ide> assert.equal(true, /Hellö Wörld/.test('Hellö Wörld'));
<del>
<ide><path>test/parallel/test-vm-create-context-circular-reference.js
<ide> sbx = vm.createContext(sbx);
<ide> sbx.test = 123;
<ide>
<ide> assert.equal(sbx.window.window.window.window.window.test, 123);
<del> | 29 |
Javascript | Javascript | add moduleid to stats | 5f856ec3b3c4fc2b68b6d2574ed154bbb70c2158 | <ide><path>lib/Stats.js
<ide> Stats.prototype.toJson = function toJson(options, forToString) {
<ide> if(showChunkOrigins) {
<ide> obj.origins = chunk.origins.map(function(origin) {
<ide> return {
<add> moduleId: origin.module ? origin.module.id : undefined,
<ide> module: origin.module ? origin.module.identifier() : "",
<ide> loc: origin.loc ? obj.loc = origin.loc.start.line + ":" + origin.loc.start.column + "-" +
<ide> (origin.loc.start.line != origin.loc.end.line ? origin.loc.end.line + ":" : "") + origin.loc.end.column : "", | 1 |
Text | Text | clarify change to process helpers [ci skip] | 885348f360640d144bfd881ddb9141ff7cc048f1 | <ide><path>guides/source/4_2_release_notes.md
<ide> Please refer to the [Changelog][action-view] for detailed changes.
<ide> * Placeholder I18n follows the same convention as `label` I18n.
<ide> ([Pull Request](https://github.com/rails/rails/pull/16438))
<ide>
<add>* When calling the `process` helpers in an integration test the path needs to
<add> a leading slash. Previously you could omit it but that was a byproduct of t
<add> implementation and not an intentional feature, e.g.:
<add>
<add> ```ruby
<add> test "list all posts" do
<add> get "/posts"
<add> assert_response :success
<add> end
<add> ```
<add>
<ide>
<ide> Action Mailer
<ide> ------------- | 1 |
Javascript | Javascript | create a base time display class, and use it | fa6f88440934f661db0fa6bb4128e3c916ef37b6 | <ide><path>src/js/control-bar/time-controls/current-time-display.js
<ide> /**
<ide> * @file current-time-display.js
<ide> */
<del>import document from 'global/document';
<add>import TimeDisplay from './time-display';
<ide> import Component from '../../component.js';
<del>import * as Dom from '../../utils/dom.js';
<del>import {bind, throttle} from '../../utils/fn.js';
<del>import formatTime from '../../utils/format-time.js';
<ide>
<ide> /**
<ide> * Displays the current time
<ide> *
<ide> * @extends Component
<ide> */
<del>class CurrentTimeDisplay extends Component {
<add>class CurrentTimeDisplay extends TimeDisplay {
<ide>
<ide> /**
<del> * Creates an instance of this class.
<add> * Builds the default DOM `className`.
<ide> *
<del> * @param {Player} player
<del> * The `Player` that this class should be attached to.
<del> *
<del> * @param {Object} [options]
<del> * The key/value store of player options.
<add> * @return {string}
<add> * The DOM `className` for this object.
<ide> */
<del> constructor(player, options) {
<del> super(player, options);
<del> this.throttledUpdateContent = throttle(bind(this, this.updateContent), 25);
<del> this.on(player, 'timeupdate', this.throttledUpdateContent);
<del> }
<del>
<del> /**
<del> * Create the `Component`'s DOM element
<del> *
<del> * @return {Element}
<del> * The element that was created.
<del> */
<del> createEl() {
<del> const el = super.createEl('div', {
<del> className: 'vjs-current-time vjs-time-control vjs-control'
<del> });
<del>
<del> this.contentEl_ = Dom.createEl('div', {
<del> className: 'vjs-current-time-display'
<del> }, {
<del> // tell screen readers not to automatically read the time as it changes
<del> 'aria-live': 'off'
<del> }, Dom.createEl('span', {
<del> className: 'vjs-control-text',
<del> textContent: this.localize('Current Time')
<del> }));
<del>
<del> this.updateTextNode_();
<del> el.appendChild(this.contentEl_);
<del> return el;
<del> }
<del>
<del> /**
<del> * Updates the "current time" text node with new content using the
<del> * contents of the `formattedTime_` property.
<del> *
<del> * @private
<del> */
<del> updateTextNode_() {
<del> if (this.textNode_) {
<del> this.contentEl_.removeChild(this.textNode_);
<del> }
<del> this.textNode_ = document.createTextNode(` ${this.formattedTime_ || '0:00'}`);
<del> this.contentEl_.appendChild(this.textNode_);
<add> buildCSSClass() {
<add> return 'vjs-current-time';
<ide> }
<ide>
<ide> /**
<ide> class CurrentTimeDisplay extends Component {
<ide> updateContent(event) {
<ide> // Allows for smooth scrubbing, when player can't keep up.
<ide> const time = (this.player_.scrubbing()) ? this.player_.getCache().currentTime : this.player_.currentTime();
<del> const formattedTime = formatTime(time, this.player_.duration());
<ide>
<del> if (formattedTime !== this.formattedTime_) {
<del> this.formattedTime_ = formattedTime;
<del> this.requestAnimationFrame(this.updateTextNode_);
<del> }
<add> this.updateFormattedTime_(time);
<ide> }
<ide>
<ide> }
<ide>
<add>/**
<add> * The text that should display over the `CurrentTimeDisplay`s controls. Added to for localization.
<add> *
<add> * @type {string}
<add> * @private
<add> */
<add>CurrentTimeDisplay.prototype.controlText_ = 'Current Time';
<add>
<ide> Component.registerComponent('CurrentTimeDisplay', CurrentTimeDisplay);
<ide> export default CurrentTimeDisplay;
<ide><path>src/js/control-bar/time-controls/duration-display.js
<ide> /**
<ide> * @file duration-display.js
<ide> */
<del>import document from 'global/document';
<add>import TimeDisplay from './time-display';
<ide> import Component from '../../component.js';
<del>import * as Dom from '../../utils/dom.js';
<del>import {bind, throttle} from '../../utils/fn.js';
<del>import formatTime from '../../utils/format-time.js';
<ide>
<ide> /**
<ide> * Displays the duration
<ide> *
<ide> * @extends Component
<ide> */
<del>class DurationDisplay extends Component {
<add>class DurationDisplay extends TimeDisplay {
<ide>
<ide> /**
<ide> * Creates an instance of this class.
<ide> class DurationDisplay extends Component {
<ide> constructor(player, options) {
<ide> super(player, options);
<ide>
<del> this.throttledUpdateContent = throttle(bind(this, this.updateContent), 25);
<del>
<ide> this.on(player, [
<ide> 'durationchange',
<ide>
<del> // Also listen for timeupdate and loadedmetadata because removing those
<add> // Also listen for timeupdate (in the parent) and loadedmetadata because removing those
<ide> // listeners could have broken dependent applications/libraries. These
<ide> // can likely be removed for 7.0.
<del> 'loadedmetadata',
<del> 'timeupdate'
<add> 'loadedmetadata'
<ide> ], this.throttledUpdateContent);
<ide> }
<ide>
<ide> /**
<del> * Create the `Component`'s DOM element
<add> * Builds the default DOM `className`.
<ide> *
<del> * @return {Element}
<del> * The element that was created.
<add> * @return {string}
<add> * The DOM `className` for this object.
<ide> */
<del> createEl() {
<del> const el = super.createEl('div', {
<del> className: 'vjs-duration vjs-time-control vjs-control'
<del> });
<del>
<del> this.contentEl_ = Dom.createEl('div', {
<del> className: 'vjs-duration-display'
<del> }, {
<del> // tell screen readers not to automatically read the time as it changes
<del> 'aria-live': 'off'
<del> }, Dom.createEl('span', {
<del> className: 'vjs-control-text',
<del> textContent: this.localize('Duration Time')
<del> }));
<del>
<del> this.updateTextNode_();
<del> el.appendChild(this.contentEl_);
<del> return el;
<del> }
<del>
<del> /**
<del> * Updates the "current time" text node with new content using the
<del> * contents of the `formattedTime_` property.
<del> *
<del> * @private
<del> */
<del> updateTextNode_() {
<del> if (this.textNode_) {
<del> this.contentEl_.removeChild(this.textNode_);
<del> }
<del> this.textNode_ = document.createTextNode(` ${this.formattedTime_ || '0:00'}`);
<del> this.contentEl_.appendChild(this.textNode_);
<add> buildCSSClass() {
<add> return 'vjs-duration';
<ide> }
<ide>
<ide> /**
<ide> class DurationDisplay extends Component {
<ide>
<ide> if (duration && this.duration_ !== duration) {
<ide> this.duration_ = duration;
<del> this.formattedTime_ = formatTime(duration);
<del> this.requestAnimationFrame(this.updateTextNode_);
<add> this.updateFormattedTime_(duration);
<ide> }
<ide> }
<ide> }
<ide>
<add>/**
<add> * The text that should display over the `DurationDisplay`s controls. Added to for localization.
<add> *
<add> * @type {string}
<add> * @private
<add> */
<add>DurationDisplay.prototype.controlText_ = 'Duration Time';
<add>
<ide> Component.registerComponent('DurationDisplay', DurationDisplay);
<ide> export default DurationDisplay;
<ide><path>src/js/control-bar/time-controls/remaining-time-display.js
<ide> /**
<ide> * @file remaining-time-display.js
<ide> */
<del>import document from 'global/document';
<add>import TimeDisplay from './time-display';
<ide> import Component from '../../component.js';
<del>import * as Dom from '../../utils/dom.js';
<del>import {bind, throttle} from '../../utils/fn.js';
<del>import formatTime from '../../utils/format-time.js';
<del>
<ide> /**
<ide> * Displays the time left in the video
<ide> *
<ide> * @extends Component
<ide> */
<del>class RemainingTimeDisplay extends Component {
<add>class RemainingTimeDisplay extends TimeDisplay {
<ide>
<ide> /**
<ide> * Creates an instance of this class.
<ide> class RemainingTimeDisplay extends Component {
<ide> */
<ide> constructor(player, options) {
<ide> super(player, options);
<del> this.throttledUpdateContent = throttle(bind(this, this.updateContent), 25);
<del> this.on(player, ['timeupdate', 'durationchange'], this.throttledUpdateContent);
<add> this.on(player, 'durationchange', this.throttledUpdateContent);
<ide> }
<ide>
<ide> /**
<del> * Create the `Component`'s DOM element
<add> * Builds the default DOM `className`.
<ide> *
<del> * @return {Element}
<del> * The element that was created.
<add> * @return {string}
<add> * The DOM `className` for this object.
<ide> */
<del> createEl() {
<del> const el = super.createEl('div', {
<del> className: 'vjs-remaining-time vjs-time-control vjs-control'
<del> });
<del>
<del> this.contentEl_ = Dom.createEl('div', {
<del> className: 'vjs-remaining-time-display'
<del> }, {
<del> // tell screen readers not to automatically read the time as it changes
<del> 'aria-live': 'off'
<del> }, Dom.createEl('span', {
<del> className: 'vjs-control-text',
<del> textContent: this.localize('Remaining Time')
<del> }));
<del>
<del> this.updateTextNode_();
<del> el.appendChild(this.contentEl_);
<del> return el;
<del> }
<del>
<del> /**
<del> * Updates the "remaining time" text node with new content using the
<del> * contents of the `formattedTime_` property.
<del> *
<del> * @private
<del> */
<del> updateTextNode_() {
<del> if (this.textNode_) {
<del> this.contentEl_.removeChild(this.textNode_);
<del> }
<del> this.textNode_ = document.createTextNode(` -${this.formattedTime_ || '0:00'}`);
<del> this.contentEl_.appendChild(this.textNode_);
<add> buildCSSClass() {
<add> return 'vjs-remaining-time';
<ide> }
<ide>
<ide> /**
<ide> class RemainingTimeDisplay extends Component {
<ide> * @listens Player#durationchange
<ide> */
<ide> updateContent(event) {
<del> if (this.player_.duration()) {
<del> const formattedTime = formatTime(this.player_.remainingTime());
<del>
<del> if (formattedTime !== this.formattedTime_) {
<del> this.formattedTime_ = formattedTime;
<del> this.requestAnimationFrame(this.updateTextNode_);
<del> }
<add> if (!this.player_.duration()) {
<add> return;
<ide> }
<add>
<add> this.updateFormattedTime_(this.player_.remainingTime());
<ide> }
<ide> }
<ide>
<add>/**
<add> * The text that should display over the `RemainingTimeDisplay`s controls. Added to for localization.
<add> *
<add> * @type {string}
<add> * @private
<add> */
<add>RemainingTimeDisplay.prototype.controlText_ = 'Remaining Time';
<add>
<ide> Component.registerComponent('RemainingTimeDisplay', RemainingTimeDisplay);
<ide> export default RemainingTimeDisplay;
<ide><path>src/js/control-bar/time-controls/time-display.js
<add>/**
<add> * @file time-display.js
<add> */
<add>import document from 'global/document';
<add>import Component from '../../component.js';
<add>import * as Dom from '../../utils/dom.js';
<add>import {bind, throttle} from '../../utils/fn.js';
<add>import formatTime from '../../utils/format-time.js';
<add>
<add>/**
<add> * Displays the time left in the video
<add> *
<add> * @extends Component
<add> */
<add>class TimeDisplay extends Component {
<add>
<add> /**
<add> * Creates an instance of this class.
<add> *
<add> * @param {Player} player
<add> * The `Player` that this class should be attached to.
<add> *
<add> * @param {Object} [options]
<add> * The key/value store of player options.
<add> */
<add> constructor(player, options) {
<add> super(player, options);
<add> this.throttledUpdateContent = throttle(bind(this, this.updateContent), 25);
<add> this.on(player, 'timeupdate', this.throttledUpdateContent);
<add> }
<add>
<add> /**
<add> * Create the `Component`'s DOM element
<add> *
<add> * @return {Element}
<add> * The element that was created.
<add> */
<add> createEl(plainName) {
<add> const className = this.buildCSSClass();
<add> const el = super.createEl('div', {
<add> className: `${className} vjs-time-control vjs-control`
<add> });
<add>
<add> this.contentEl_ = Dom.createEl('div', {
<add> className: `${className}-display`
<add> }, {
<add> // tell screen readers not to automatically read the time as it changes
<add> 'aria-live': 'off'
<add> }, Dom.createEl('span', {
<add> className: 'vjs-control-text',
<add> textContent: this.localize(this.contentText_)
<add> }));
<add>
<add> this.updateTextNode_();
<add> el.appendChild(this.contentEl_);
<add> return el;
<add> }
<add>
<add> /**
<add> * Updates the "remaining time" text node with new content using the
<add> * contents of the `formattedTime_` property.
<add> *
<add> * @private
<add> */
<add> updateTextNode_() {
<add> if (this.textNode_) {
<add> this.contentEl_.removeChild(this.textNode_);
<add> }
<add> this.textNode_ = document.createTextNode(` -${this.formattedTime_ || '0:00'}`);
<add> this.contentEl_.appendChild(this.textNode_);
<add> }
<add>
<add> /**
<add> * Updates the time display text node if it has what was passed in changed
<add> * the formatted time.
<add> *
<add> * @param {number} time
<add> * The time to update to
<add> *
<add> * @private
<add> */
<add> updateFormattedTime_(time) {
<add> const formattedTime = formatTime(time);
<add>
<add> if (formattedTime === this.formattedTime_) {
<add> return;
<add> }
<add>
<add> this.formattedTime_ = formattedTime;
<add> this.requestAnimationFrame(this.updateTextNode_);
<add> }
<add>
<add> /**
<add> * To be filled out in the child class, should update the displayed time
<add> * in accordance with the fact that the current time has changed.
<add> *
<add> * @param {EventTarget~Event} [event]
<add> * The `timeupdate` event that caused this to run.
<add> *
<add> * @listens Player#timeupdate
<add> */
<add> updateContent(event) {}
<add>}
<add>
<add>/**
<add> * The text that should display over the `TimeDisplay`s controls. Added to for localization.
<add> *
<add> * @type {string}
<add> * @private
<add> */
<add>TimeDisplay.prototype.controlText_ = 'Time';
<add>
<add>Component.registerComponent('TimeDisplay', TimeDisplay);
<add>export default TimeDisplay; | 4 |
Text | Text | reverse a string - portuguese | 222948d5aca27f03d8a91bfa21d6c49cc82c663d | <ide><path>curriculum/challenges/portuguese/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/reverse-a-string.portuguese.md
<ide> reverseString("hello");
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>function reverseString(str) {
<add> return str.split('').reverse().join('');
<add>}
<add>
<add>reverseString("hello");
<ide> ```
<ide> </section> | 1 |
Python | Python | use super instead of nodedriver.__init__ | c4e4ae2f536ae3ef22ed2c767d05c7c12afdbfd6 | <ide><path>libcloud/compute/drivers/cloudstack.py
<ide> def __init__(self, key, secret=None, secure=True, host=None,
<ide> 'you also need to provide url or host and path '
<ide> 'argument')
<ide>
<del> NodeDriver.__init__(self, key=key, secret=secret, secure=secure,
<del> host=host, port=port)
<add> super(CloudStackNodeDriver, self).__init__(key=key,
<add> secret=secret,
<add> secure=secure,
<add> host=host,
<add> port=port)
<ide>
<ide> def list_images(self, location=None):
<ide> args = { | 1 |
Python | Python | add convolutional layer tests | 0969c569a69e067bef903fdb50fc29a9cd6a8748 | <ide><path>tests/auto/keras/layers/test_convolutional.py
<add>import unittest
<add>import numpy as np
<add>from numpy.testing import assert_allclose
<add>import theano
<add>
<add>from keras.layers import convolutional
<add>
<add>
<add>class TestConvolutions(unittest.TestCase):
<add> def test_convolution_1d(self):
<add> nb_samples = 9
<add> nb_steps = 7
<add> input_dim = 10
<add> filter_length = 6
<add> nb_filter = 5
<add>
<add> weights_in = [np.ones((nb_filter, input_dim, filter_length, 1)), np.ones(nb_filter)]
<add>
<add> self.assertRaises(Exception, convolutional.Convolution1D,
<add> input_dim, nb_filter, filter_length, border_mode='foo')
<add>
<add> input = np.ones((nb_samples, nb_steps, input_dim))
<add> for weight in [None, weights_in]:
<add> for border_mode in ['valid', 'full']:
<add> for subsample_length in [1, 3]:
<add> for W_regularizer in [None, 'l2']:
<add> for b_regularizer in [None, 'l2']:
<add> layer = convolutional.Convolution1D(
<add> input_dim, nb_filter, filter_length, weights=weight,
<add> border_mode=border_mode, W_regularizer=W_regularizer,
<add> b_regularizer=b_regularizer, subsample_length=subsample_length)
<add>
<add> layer.input = theano.shared(value=input)
<add> for train in [True, False]:
<add> layer.get_output(train).eval()
<add>
<add> config = layer.get_config()
<add>
<add> def test_maxpooling_1d(self):
<add> nb_samples = 9
<add>
<add> nb_steps = 7
<add> input_dim = 10
<add>
<add> input = np.ones((nb_samples, nb_steps, input_dim))
<add> for ignore_border in [True, False]:
<add> for stride in [None, 2]:
<add> layer = convolutional.MaxPooling1D(stride=stride, ignore_border=ignore_border)
<add> layer.input = theano.shared(value=input)
<add> for train in [True, False]:
<add> layer.get_output(train).eval()
<add>
<add> config = layer.get_config()
<add>
<add> def test_convolution_2d(self):
<add> nb_samples = 8
<add>
<add> nb_filter = 9
<add> stack_size = 7
<add> nb_row = 10
<add> nb_col = 6
<add>
<add> input_nb_row = 11
<add> input_nb_col = 12
<add>
<add> weights_in = [np.ones((nb_filter, stack_size, nb_row, nb_col)), np.ones(nb_filter)]
<add>
<add> self.assertRaises(Exception, convolutional.Convolution2D,
<add> nb_filter, stack_size, nb_row, nb_col, border_mode='foo')
<add>
<add> input = np.ones((nb_samples, stack_size, input_nb_row, input_nb_col))
<add> for weight in [None, weights_in]:
<add> for border_mode in ['valid', 'full', 'same']:
<add> for subsample in [(1, 1), (2, 3)]:
<add> for W_regularizer in [None, 'l2']:
<add> for b_regularizer in [None, 'l2']:
<add> layer = convolutional.Convolution2D(
<add> nb_filter, stack_size, nb_row, nb_col, weights=weight,
<add> border_mode=border_mode, W_regularizer=W_regularizer,
<add> b_regularizer=b_regularizer, subsample=subsample)
<add>
<add> layer.input = theano.shared(value=input)
<add> for train in [True, False]:
<add> out = layer.get_output(train).eval()
<add> if border_mode == 'same' and subsample == (1, 1):
<add> assert out.shape[2:] == input.shape[2:]
<add>
<add> config = layer.get_config()
<add>
<add> def test_maxpooling_2d(self):
<add> nb_samples = 9
<add>
<add> stack_size = 7
<add> input_nb_row = 11
<add> input_nb_col = 12
<add> poolsize = (3, 3)
<add>
<add> input = np.ones((nb_samples, stack_size, input_nb_row, input_nb_col))
<add> for ignore_border in [True, False]:
<add> for stride in [None, (2, 2)]:
<add> layer = convolutional.MaxPooling2D(stride=stride, ignore_border=ignore_border, poolsize=poolsize)
<add> layer.input = theano.shared(value=input)
<add> for train in [True, False]:
<add> layer.get_output(train).eval()
<add>
<add> config = layer.get_config()
<add>
<add> def test_zero_padding_2d(self):
<add> nb_samples = 9
<add>
<add> stack_size = 7
<add> input_nb_row = 11
<add> input_nb_col = 12
<add>
<add> input = np.ones((nb_samples, stack_size, input_nb_row, input_nb_col))
<add> layer = convolutional.ZeroPadding2D(pad=(2,2))
<add> layer.input = theano.shared(value=input)
<add> for train in [True, False]:
<add> out = layer.get_output(train).eval()
<add> for offset in [0,1,-1,-2]:
<add> assert_allclose(out[:, :, offset, :], 0.)
<add> assert_allclose(out[:, :, :, offset], 0.)
<add> assert_allclose(out[:, :, 2:-2, 2:-2], 1.)
<add>
<add> config = layer.get_config()
<add>
<add>if __name__ == '__main__':
<add> unittest.main() | 1 |
Javascript | Javascript | fix incorrect usage of ember.deprecate | 73e5b11bba875253f80d11987aaaba4c02c91342 | <ide><path>packages/ember-routing-handlebars/lib/helpers/link_to.js
<ide> var LinkView = Ember.LinkView = EmberComponent.extend({
<ide> init: function() {
<ide> this._super.apply(this, arguments);
<ide>
<del> Ember.deprecate('Using currentWhen with {{link-to}} is deprecated in favor of `current-when`.', this.currentWhen);
<add> Ember.deprecate('Using currentWhen with {{link-to}} is deprecated in favor of `current-when`.', !this.currentWhen);
<ide>
<ide> // Map desired event name to invoke function
<ide> var eventName = get(this, 'eventName');
<ide><path>packages/ember/tests/helpers/link_to_test.js
<ide> test("The {{link-to}} helper supports currentWhen (DEPRECATED)", function() {
<ide> });
<ide>
<ide> Ember.TEMPLATES.index = Ember.Handlebars.compile("<h3>Home</h3>{{outlet}}");
<del> Ember.TEMPLATES['index/about'] = Ember.Handlebars.compile("{{#link-to 'item' id='other-link' current-when='index'}}ITEM{{/link-to}}");
<add> Ember.TEMPLATES['index/about'] = Ember.Handlebars.compile("{{#link-to 'item' id='other-link' currentWhen='index'}}ITEM{{/link-to}}");
<ide>
<ide> bootApplication();
<ide> | 2 |
Javascript | Javascript | change app.statemanager to app.router | d23ea3ab501fc0e8f591a793b927f572436647a1 | <ide><path>packages/ember-application/lib/system/application.js
<ide> Ember.Application = Ember.Namespace.extend(
<ide> }
<ide>
<ide> if (router) {
<del> set(this, 'stateManager', router);
<add> set(this, 'router', router);
<ide> }
<ide>
<ide> // By default, the router's namespace is the current application.
<ide><path>packages/ember-application/tests/system/application_test.js
<ide> test('initialized application go to initial route', function() {
<ide> });
<ide>
<ide> app.initialize(app.stateManager);
<del> equal(app.getPath('stateManager.currentState.path'), 'root.index', "The router moved the state into the right place");
<del>});
<del>
<del>test("initialize application with non routable stateManager", function() {
<del> Ember.run(function() {
<del> app = Ember.Application.create({
<del> rootElement: '#qunit-fixture'
<del> });
<del>
<del> app.stateManager = Ember.StateManager.create({
<del> start: Ember.State.extend()
<del> });
<del> });
<del>
<del> equal(app.getPath('stateManager.currentState.path'), 'start', "Application sucessfuly started");
<add> equal(app.getPath('router.currentState.path'), 'root.index', "The router moved the state into the right place");
<ide> });
<ide>
<ide> test("initialize application with stateManager via initialize call", function() {
<ide> test("initialize application with stateManager via initialize call", function()
<ide> app.initialize(app.Router.create());
<ide> });
<ide>
<del> equal(app.getPath('stateManager') instanceof Ember.Router, true, "Router was set from initialize call");
<del> equal(app.getPath('stateManager.location') instanceof Ember.NoneLocation, true, "Location was set from location implementation name");
<del> equal(app.getPath('stateManager.currentState.path'), 'root.index', "The router moved the state into the right place");
<add> equal(app.getPath('router') instanceof Ember.Router, true, "Router was set from initialize call");
<add> equal(app.getPath('router.location') instanceof Ember.NoneLocation, true, "Location was set from location implementation name");
<add> equal(app.getPath('router.currentState.path'), 'root.index', "The router moved the state into the right place");
<ide> });
<ide>
<ide> test("initialize application with stateManager via initialize call from Router class", function() {
<ide> test("initialize application with stateManager via initialize call from Router c
<ide> app.initialize();
<ide> });
<ide>
<del> equal(app.getPath('stateManager') instanceof Ember.Router, true, "Router was set from initialize call");
<del> equal(app.getPath('stateManager.currentState.path'), 'root.index', "The router moved the state into the right place");
<add> equal(app.getPath('router') instanceof Ember.Router, true, "Router was set from initialize call");
<add> equal(app.getPath('router.currentState.path'), 'root.index', "The router moved the state into the right place");
<ide> });
<ide>
<ide> test("injections can be registered in a specified order", function() {
<ide> test("ControllerObject class can be initialized with target, controllers and vie
<ide> stateManager.get('postController').set('view', Ember.View.create());
<ide> });
<ide>
<del> equal(app.getPath('stateManager.postController.target') instanceof Ember.StateManager, true, "controller has target");
<del> equal(app.getPath('stateManager.postController.controllers') instanceof Ember.StateManager, true, "controller has controllers");
<del> equal(app.getPath('stateManager.postController.view') instanceof Ember.View, true, "controller has view");
<add> equal(app.getPath('router.postController.target') instanceof Ember.StateManager, true, "controller has target");
<add> equal(app.getPath('router.postController.controllers') instanceof Ember.StateManager, true, "controller has controllers");
<add> equal(app.getPath('router.postController.view') instanceof Ember.View, true, "controller has view");
<ide> }); | 2 |
PHP | PHP | add filesystem configuration | 3ade971b2391b8811d9be9992870db6ad0f4f501 | <ide><path>config/filesystems.php
<add><?php
<add>
<add>return [
<add>
<add> /*
<add> |--------------------------------------------------------------------------
<add> | Default Filesystem Disk
<add> |--------------------------------------------------------------------------
<add> |
<add> | Here you may specify the default filesystem disk that should be used
<add> | by the framework. A "local" driver, as well as a variety of cloud
<add> | based drivers are available for your choosing. Just store away!
<add> |
<add> | Supported: "local", "s3", "rackspace"
<add> |
<add> */
<add>
<add> 'default' => 'local',
<add>
<add> /*
<add> |--------------------------------------------------------------------------
<add> | Default Cloud Filesystem Disk
<add> |--------------------------------------------------------------------------
<add> |
<add> | Many applications store files both locally and in the cloud. For this
<add> | reason, you may specify a default "cloud" driver here. This driver
<add> | will be bounc as the Cloud disk implementation in the container.
<add> |
<add> */
<add>
<add> 'cloud' => 's3',
<add>
<add> /*
<add> |--------------------------------------------------------------------------
<add> | Filesystem Disks
<add> |--------------------------------------------------------------------------
<add> |
<add> | Here you may configure as many filesystem "disks" as you wish, and you
<add> | may even configure multiple disks of the same driver. Defaults have
<add> | been setup for each driver as an example of the required options.
<add> |
<add> */
<add>
<add> 'disks' => [
<add>
<add> 'local' => [
<add> 'driver' => 'local',
<add> 'root' => base_path(),
<add> ],
<add>
<add> 's3' => [
<add> 'driver' => 's3',
<add> 'key' => 'your-key',
<add> 'secret' => 'your-secret',
<add> 'bucket' => 'your-bucket',
<add> ],
<add>
<add> 'rackspace' => [
<add> 'driver' => 'rackspace',
<add> 'username' => 'your-username',
<add> 'key' => 'your-key',
<add> 'container' => 'your-container',
<add> 'endpoint' => 'https://identity.api.rackspacecloud.com/v2.0/',
<add> 'region' => 'IAD',
<add> ],
<add>
<add> ],
<add>
<add>]; | 1 |
Python | Python | add current changes | 77e6775065e2aebd88ab99e4ef3ddc3569a5acb2 | <ide><path>tests/test_modeling_bart.py
<ide> def test_cnn_summarization_same_as_fairseq_hard_batch(self):
<ide> max_length=max_length + 2,
<ide> min_length=min_length + 1,
<ide> no_repeat_ngram_size=3,
<del> do_sample=False
<add> do_sample=False,
<add> early_stopping=True
<ide> )
<ide> decoded = [
<ide> tok.decode(g, skip_special_tokens=True, clean_up_tokenization_spaces=False) for g in hypotheses_batch | 1 |
Text | Text | add breaking change notice for issue 12506 | 67afd9dc6376724036231947ac6e7a78f81375ce | <ide><path>CHANGELOG.md
<ide> and/or `beforeRemoveClass` then the CSS classes will not be applied
<ide> in time for the children (and the parent class-based animation will not
<ide> be cancelled by any child animations).
<ide>
<add>- **$q** due to [6838c979](https://github.com/angular/angular.js/commit/6838c979451c109d959a15035177ccee715ccf19),
<add> When writing tests, there is no need to call `$timeout.flush()` to resolve a call to `$q.when` with a value.
<add>
<add>The previous behavior involved creating an extra promise that needed to be resolved. This is no longer needed when
<add>`$q.when` is called with a value. In the case that the test is not aware if `$q.when` is called with a value or
<add>another promise, it is possible to replace `$timeout.flush();` with `$timeout.flush(0);`.
<add>
<add>```js
<add>describe('$q.when', function() {
<add> it('should not need a call to $timeout.flush() to resolve already resolved promises',
<add> inject(function($q, $timeout) {
<add> $q.when('foo');
<add> // In Angular 1.4.3 a call to `$timeout.flush();` was needed
<add> $timeout.verifyNoPendingTasks();
<add> }));
<add>
<add> it('should accept $timeout.flush(0) when not sure if $q.when was called with a value or a promise’,
<add> inject(function($q, $timeout) {
<add> $q.when('foo');
<add> $timeout.flush(0);
<add> $timeout.verifyNoPendingTasks();
<add> }));
<add>
<add> it('should need a call to $timeout.flush() to resolve $q.when when called with a promise',
<add> inject(function($q, $timeout) {
<add> $q.when($q.when('foo'));
<add> $timeout.flush();
<add> $timeout.verifyNoPendingTasks();
<add> }));
<add>});
<add>```
<add>
<ide>
<ide> <a name="1.4.3"></a>
<ide> # 1.4.3 foam-acceleration (2015-07-15) | 1 |
Ruby | Ruby | allow methods arity below -1 in assert_responds | 0aeb11e5751c5c998f4d52b0084754d848e2865e | <ide><path>activerecord/test/cases/relation/delegation_test.rb
<ide> class DelegationTest < ActiveRecord::TestCase
<ide> def assert_responds(target, method)
<ide> assert target.respond_to?(method)
<ide> assert_nothing_raised do
<del> case target.to_a.method(method).arity
<del> when 0
<add> method_arity = target.to_a.method(method).arity
<add>
<add> if method_arity.zero?
<ide> target.send(method)
<del> when -1
<add> elsif method_arity < 0
<ide> if method == :shuffle!
<ide> target.send(method)
<ide> else | 1 |
Python | Python | fix typo in documentation | 9d104c87dd49771892ba22febcedddeeee2d1baf | <ide><path>keras/layers/preprocessing/string_lookup.py
<ide> def adapt(self, data, batch_size=None, steps=None):
<ide> During `adapt()`, the layer will build a vocabulary of all string tokens
<ide> seen in the dataset, sorted by occurance count, with ties broken by sort
<ide> order of the tokens (high to low). At the end of `adapt()`, if `max_tokens`
<del> is set, the voculary wil be truncated to `max_tokens` size. For example,
<add> is set, the vocabulary wil be truncated to `max_tokens` size. For example,
<ide> adapting a layer with `max_tokens=1000` will compute the 1000 most frequent
<ide> tokens occurring in the input dataset. If `output_mode='tf-idf'`, `adapt()`
<ide> will also learn the document frequencies of each token in the input dataset. | 1 |
Ruby | Ruby | switch callbacks to minitest hooks | 0b29c7bb7b40f66977e374667daf7239970bf635 | <ide><path>actionpack/test/abstract_unit.rb
<ide> def config
<ide> end
<ide>
<ide> class ActionDispatch::IntegrationTest < ActiveSupport::TestCase
<del> setup do
<add> def before_setup
<ide> @routes = SharedTestRoutes
<add> super
<ide> end
<ide>
<ide> def self.build_app(routes = nil)
<ide> def self.test_routes(&block)
<ide> class TestCase
<ide> include ActionDispatch::TestProcess
<ide>
<del> setup do
<add> def before_setup
<ide> @routes = SharedTestRoutes
<add> super
<ide> end
<ide> end
<ide> end
<ide> module ActionView
<ide> class TestCase
<ide> # Must repeat the setup because AV::TestCase is a duplication
<ide> # of AC::TestCase
<del> setup do
<add> def before_setup
<ide> @routes = SharedTestRoutes
<add> super
<ide> end
<ide> end
<ide> end | 1 |
Python | Python | update textcat ensemble model | c2a18e4fa35355124e9da78c90526a01557e7cfb | <ide><path>spacy/ml/models/textcat.py
<ide> def build_text_classifier_v2(
<ide> attention_layer = ParametricAttention(
<ide> width
<ide> ) # TODO: benchmark performance difference of this layer
<del> maxout_layer = Maxout(nO=width, nI=width)
<del> linear_layer = Linear(nO=nO, nI=width)
<add> maxout_layer = Maxout(nO=width, nI=width, dropout=0.0, normalize=True)
<ide> cnn_model = (
<ide> tok2vec
<ide> >> list2ragged()
<ide> >> attention_layer
<ide> >> reduce_sum()
<ide> >> residual(maxout_layer)
<del> >> linear_layer
<del> >> Dropout(0.0)
<ide> )
<ide>
<ide> nO_double = nO * 2 if nO else None
<ide> if exclusive_classes:
<ide> output_layer = Softmax(nO=nO, nI=nO_double)
<ide> else:
<del> output_layer = Linear(nO=nO, nI=nO_double) >> Dropout(0.0) >> Logistic()
<add> output_layer = Linear(nO=nO, nI=nO_double) >> Logistic()
<ide> model = (linear_model | cnn_model) >> output_layer
<ide> model.set_ref("tok2vec", tok2vec)
<ide> if model.has_dim("nO") is not False:
<ide> model.set_dim("nO", nO)
<ide> model.set_ref("output_layer", linear_model.get_ref("output_layer"))
<ide> model.set_ref("attention_layer", attention_layer)
<ide> model.set_ref("maxout_layer", maxout_layer)
<del> model.set_ref("linear_layer", linear_layer)
<ide> model.attrs["multi_label"] = not exclusive_classes
<ide>
<ide> model.init = init_ensemble_textcat
<ide> def init_ensemble_textcat(model, X, Y) -> Model:
<ide> model.get_ref("attention_layer").set_dim("nO", tok2vec_width)
<ide> model.get_ref("maxout_layer").set_dim("nO", tok2vec_width)
<ide> model.get_ref("maxout_layer").set_dim("nI", tok2vec_width)
<del> model.get_ref("linear_layer").set_dim("nI", tok2vec_width)
<ide> init_chain(model, X, Y)
<ide> return model
<ide> | 1 |
Javascript | Javascript | use quatequals on quaternions | 17cc0b08bd357d8cff144bcf2d066f8bf1ee7028 | <ide><path>test/unit/src/math/Euler.js
<ide> QUnit.test( "Quaternion.setFromEuler/Euler.fromQuaternion", function( assert ) {
<ide>
<ide> var v2 = new THREE.Euler().setFromQuaternion( q, v.order );
<ide> var q2 = new THREE.Quaternion().setFromEuler( v2 );
<del> assert.ok( eulerEquals( q, q2 ), "Passed!" );
<add> assert.ok( quatEquals( q, q2 ), "Passed!" );
<ide> }
<ide> });
<ide> | 1 |
Mixed | Java | convert image resizemode `contain` to fit_center | 2070efa019f6b5dfb38500d41e4d7e263f59f0d2 | <ide><path>Examples/UIExplorer/ImageExample.js
<ide> exports.examples = [
<ide> 'rendered within the frame.',
<ide> render: function() {
<ide> return (
<del> <View style={styles.horizontal}>
<del> <View>
<del> <Text style={[styles.resizeModeText]}>
<del> Contain
<del> </Text>
<del> <Image
<del> style={styles.resizeMode}
<del> resizeMode={Image.resizeMode.contain}
<del> source={fullImage}
<del> />
<del> </View>
<del> <View style={styles.leftMargin}>
<del> <Text style={[styles.resizeModeText]}>
<del> Cover
<del> </Text>
<del> <Image
<del> style={styles.resizeMode}
<del> resizeMode={Image.resizeMode.cover}
<del> source={fullImage}
<del> />
<del> </View>
<del> <View style={styles.leftMargin}>
<del> <Text style={[styles.resizeModeText]}>
<del> Stretch
<del> </Text>
<del> <Image
<del> style={styles.resizeMode}
<del> resizeMode={Image.resizeMode.stretch}
<del> source={fullImage}
<del> />
<del> </View>
<add> <View>
<add> {[smallImage, fullImage].map((image, index) => {
<add> return <View style={styles.horizontal} key={index}>
<add> <View>
<add> <Text style={[styles.resizeModeText]}>
<add> Contain
<add> </Text>
<add> <Image
<add> style={styles.resizeMode}
<add> resizeMode={Image.resizeMode.contain}
<add> source={image}
<add> />
<add> </View>
<add> <View style={styles.leftMargin}>
<add> <Text style={[styles.resizeModeText]}>
<add> Cover
<add> </Text>
<add> <Image
<add> style={styles.resizeMode}
<add> resizeMode={Image.resizeMode.cover}
<add> source={image}
<add> />
<add> </View>
<add> <View style={styles.leftMargin}>
<add> <Text style={[styles.resizeModeText]}>
<add> Stretch
<add> </Text>
<add> <Image
<add> style={styles.resizeMode}
<add> resizeMode={Image.resizeMode.stretch}
<add> source={image}
<add> />
<add> </View>
<add> </View>;
<add> })}
<ide> </View>
<ide> );
<ide> },
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModuleConstants.java
<ide> public static Map<String, Object> getConstants() {
<ide> "ContentMode",
<ide> MapBuilder.of(
<ide> "ScaleAspectFit",
<del> ImageView.ScaleType.CENTER_INSIDE.ordinal(),
<add> ImageView.ScaleType.FIT_CENTER.ordinal(),
<ide> "ScaleAspectFill",
<ide> ImageView.ScaleType.CENTER_CROP.ordinal())));
<ide>
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/image/ImageResizeMode.java
<ide> public class ImageResizeMode {
<ide> */
<ide> public static ScalingUtils.ScaleType toScaleType(@Nullable String resizeModeValue) {
<ide> if ("contain".equals(resizeModeValue)) {
<del> return ScalingUtils.ScaleType.CENTER_INSIDE;
<add> return ScalingUtils.ScaleType.FIT_CENTER;
<ide> }
<ide> if ("cover".equals(resizeModeValue)) {
<ide> return ScalingUtils.ScaleType.CENTER_CROP;
<ide><path>ReactAndroid/src/test/java/com/facebook/react/views/image/ImageResizeModeTest.java
<ide> public void testImageResizeMode() {
<ide> .isEqualTo(ScalingUtils.ScaleType.CENTER_CROP);
<ide>
<ide> assertThat(ImageResizeMode.toScaleType("contain"))
<del> .isEqualTo(ScalingUtils.ScaleType.CENTER_INSIDE);
<add> .isEqualTo(ScalingUtils.ScaleType.FIT_CENTER);
<ide>
<ide> assertThat(ImageResizeMode.toScaleType("cover"))
<ide> .isEqualTo(ScalingUtils.ScaleType.CENTER_CROP); | 4 |
PHP | PHP | skip validation when recovering trees | 544930f882a2e5c3acf65e17e9bfc5f2cea7ecbc | <ide><path>lib/Cake/Model/Behavior/TreeBehavior.php
<ide> public function recover(Model $Model, $mode = 'parent', $missingParentAction = n
<ide> $rght = $count++;
<ide> $Model->create(false);
<ide> $Model->id = $array[$Model->alias][$Model->primaryKey];
<del> $Model->save(array($left => $lft, $right => $rght), array('callbacks' => false));
<add> $Model->save(array($left => $lft, $right => $rght), array('callbacks' => false, 'validate' => false));
<ide> }
<ide> foreach ($Model->find('all', array('conditions' => $scope, 'fields' => array($Model->primaryKey, $parent), 'order' => $left)) as $array) {
<ide> $Model->create(false);
<ide> public function removeFromTree(Model $Model, $id = null, $delete = false) {
<ide> $Model->id = $id;
<ide> return $Model->save(
<ide> array($left => $edge + 1, $right => $edge + 2, $parent => null),
<del> array('callbacks' => false)
<add> array('callbacks' => false, 'validate' => false)
<ide> );
<ide> }
<ide> } | 1 |
Text | Text | add article by the nielsen norman group | 84324e704b68e152df62cc8b8504cc2ef6d2cb9e | <ide><path>guide/english/product-design/customer-journey-maps/index.md
<ide> This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/
<ide>
<ide> #### More Information:
<ide> <!-- Please add any articles you think might be helpful to read before writing the article -->
<del>
<del>
<add>- [When and How to Create Customer Journey Maps by The Nielsen Norman Group](https://www.nngroup.com/articles/customer-journey-mapping/) | 1 |
Text | Text | add hint to match ending string patterns | 848458b142dd71d127a18fbee3e412a876369be8 | <ide><path>client/src/guide/english/certifications/javascript-algorithms-and-data-structures/regular-expressions/match-ending-string-patterns/index.md
<add>---
<add>title: Match Ending String Patterns
<ide> ---
<del>title: Match Ending String Patterns
<del>---
<add>
<ide> ## Match Ending String Patterns
<ide>
<del>This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/javascript-algorithms-and-data-structures/regular-expressions/match-ending-string-patterns/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<add><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
<ide>
<del><a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<add>We need to use the anchor character (```$```) to match the string ```"caboose"``` at the end of the string ```caboose```.
<ide>
<del><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
<add>## Solution:
<add>
<add>```js
<add>let caboose = "The last car on a train is the caboose";
<add>let lastRegex = /caboose$/; // Change this line
<add>let result = lastRegex.test(caboose);
<add>``` | 1 |
Javascript | Javascript | avoid indexof when parsing | 7ec28a0a506efe9d1c03240fd028bea4a3d350da | <ide><path>lib/querystring.js
<ide> function parse(qs, sep, eq, options) {
<ide> }
<ide> const customDecode = (decode !== qsUnescape);
<ide>
<del> const keys = [];
<ide> var lastPos = 0;
<ide> var sepIdx = 0;
<ide> var eqIdx = 0;
<ide> function parse(qs, sep, eq, options) {
<ide> if (value.length > 0 && valEncoded)
<ide> value = decodeStr(value, decode);
<ide>
<del> // Use a key array lookup instead of using hasOwnProperty(), which is
<del> // slower
<del> if (keys.indexOf(key) === -1) {
<add> if (obj[key] === undefined) {
<ide> obj[key] = value;
<del> keys[keys.length] = key;
<ide> } else {
<ide> const curValue = obj[key];
<ide> // A simple Array-specific property check is enough here to
<ide> function parse(qs, sep, eq, options) {
<ide> key = decodeStr(key, decode);
<ide> if (value.length > 0 && valEncoded)
<ide> value = decodeStr(value, decode);
<del> // Use a key array lookup instead of using hasOwnProperty(), which is slower
<del> if (keys.indexOf(key) === -1) {
<add> if (obj[key] === undefined) {
<ide> obj[key] = value;
<del> keys[keys.length] = key;
<ide> } else {
<ide> const curValue = obj[key];
<ide> // A simple Array-specific property check is enough here to | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.