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 |
|---|---|---|---|---|---|
Mixed | Ruby | add additional options to time `change` methods | 851b7f866e13518d900407c78dcd6eb477afad06 | <ide><path>activesupport/CHANGELOG.md
<add>* Add support for `:offset` and `:zone` to `ActiveSupport::TimeWithZone#change`
<add>
<add> *Andrew White*
<add>
<add>* Add support for `:offset` to `Time#change`
<add>
<add> Fixes #28723.
<add>
<add> *Andrew White*
<add>
<ide> * Add `fetch_values` for `HashWithIndifferentAccess`
<ide>
<ide> The method was originally added to `Hash` in Ruby 2.3.0.
<ide><path>activesupport/lib/active_support/core_ext/time/calculations.rb
<ide> def sec_fraction
<ide> # to the +options+ parameter. The time options (<tt>:hour</tt>, <tt>:min</tt>,
<ide> # <tt>:sec</tt>, <tt>:usec</tt>, <tt>:nsec</tt>) reset cascadingly, so if only
<ide> # the hour is passed, then minute, sec, usec and nsec is set to 0. If the hour
<del> # and minute is passed, then sec, usec and nsec is set to 0. The +options+
<del> # parameter takes a hash with any of these keys: <tt>:year</tt>, <tt>:month</tt>,
<del> # <tt>:day</tt>, <tt>:hour</tt>, <tt>:min</tt>, <tt>:sec</tt>, <tt>:usec</tt>
<del> # <tt>:nsec</tt>. Pass either <tt>:usec</tt> or <tt>:nsec</tt>, not both.
<add> # and minute is passed, then sec, usec and nsec is set to 0. The +options+ parameter
<add> # takes a hash with any of these keys: <tt>:year</tt>, <tt>:month</tt>, <tt>:day</tt>,
<add> # <tt>:hour</tt>, <tt>:min</tt>, <tt>:sec</tt>, <tt>:usec</tt>, <tt>:nsec</tt>,
<add> # <tt>:offset</tt>. Pass either <tt>:usec</tt> or <tt>:nsec</tt>, not both.
<ide> #
<ide> # Time.new(2012, 8, 29, 22, 35, 0).change(day: 1) # => Time.new(2012, 8, 1, 22, 35, 0)
<ide> # Time.new(2012, 8, 29, 22, 35, 0).change(year: 1981, day: 1) # => Time.new(1981, 8, 1, 22, 35, 0)
<ide> # Time.new(2012, 8, 29, 22, 35, 0).change(year: 1981, hour: 0) # => Time.new(1981, 8, 29, 0, 0, 0)
<ide> def change(options)
<del> new_year = options.fetch(:year, year)
<del> new_month = options.fetch(:month, month)
<del> new_day = options.fetch(:day, day)
<del> new_hour = options.fetch(:hour, hour)
<del> new_min = options.fetch(:min, options[:hour] ? 0 : min)
<del> new_sec = options.fetch(:sec, (options[:hour] || options[:min]) ? 0 : sec)
<add> new_year = options.fetch(:year, year)
<add> new_month = options.fetch(:month, month)
<add> new_day = options.fetch(:day, day)
<add> new_hour = options.fetch(:hour, hour)
<add> new_min = options.fetch(:min, options[:hour] ? 0 : min)
<add> new_sec = options.fetch(:sec, (options[:hour] || options[:min]) ? 0 : sec)
<add> new_offset = options.fetch(:offset, nil)
<ide>
<ide> if new_nsec = options[:nsec]
<ide> raise ArgumentError, "Can't change both :nsec and :usec at the same time: #{options.inspect}" if options[:usec]
<ide> def change(options)
<ide> new_usec = options.fetch(:usec, (options[:hour] || options[:min] || options[:sec]) ? 0 : Rational(nsec, 1000))
<ide> end
<ide>
<del> if utc?
<del> ::Time.utc(new_year, new_month, new_day, new_hour, new_min, new_sec, new_usec)
<add> raise ArgumentError, "argument out of range" if new_usec >= 1000000
<add>
<add> new_sec += Rational(new_usec, 1000000)
<add>
<add> if new_offset
<add> ::Time.new(new_year, new_month, new_day, new_hour, new_min, new_sec, new_offset)
<add> elsif utc?
<add> ::Time.utc(new_year, new_month, new_day, new_hour, new_min, new_sec)
<ide> elsif zone
<del> ::Time.local(new_year, new_month, new_day, new_hour, new_min, new_sec, new_usec)
<add> ::Time.local(new_year, new_month, new_day, new_hour, new_min, new_sec)
<ide> else
<del> raise ArgumentError, "argument out of range" if new_usec >= 1000000
<del> ::Time.new(new_year, new_month, new_day, new_hour, new_min, new_sec + (new_usec.to_r / 1000000), utc_offset)
<add> ::Time.new(new_year, new_month, new_day, new_hour, new_min, new_sec, utc_offset)
<ide> end
<ide> end
<ide>
<ide><path>activesupport/lib/active_support/time_with_zone.rb
<ide> def ago(other)
<ide> since(-other)
<ide> end
<ide>
<add> # Returns a new +ActiveSupport::TimeWithZone+ where one or more of the elements have
<add> # been changed according to the +options+ parameter. The time options (<tt>:hour</tt>,
<add> # <tt>:min</tt>, <tt>:sec</tt>, <tt>:usec</tt>, <tt>:nsec</tt>) reset cascadingly,
<add> # so if only the hour is passed, then minute, sec, usec and nsec is set to 0. If the
<add> # hour and minute is passed, then sec, usec and nsec is set to 0. The +options+
<add> # parameter takes a hash with any of these keys: <tt>:year</tt>, <tt>:month</tt>,
<add> # <tt>:day</tt>, <tt>:hour</tt>, <tt>:min</tt>, <tt>:sec</tt>, <tt>:usec</tt>,
<add> # <tt>:nsec</tt>, <tt>:offset</tt>, <tt>:zone</tt>. Pass either <tt>:usec</tt>
<add> # or <tt>:nsec</tt>, not both. Similarly, pass either <tt>:zone</tt> or
<add> # <tt>:offset</tt>, not both.
<add> #
<add> # t = Time.zone.now # => Fri, 14 Apr 2017 11:45:15 EST -05:00
<add> # t.change(year: 2020) # => Tue, 14 Apr 2020 11:45:15 EST -05:00
<add> # t.change(hour: 12) # => Fri, 14 Apr 2017 12:00:00 EST -05:00
<add> # t.change(min: 30) # => Fri, 14 Apr 2017 11:30:00 EST -05:00
<add> # t.change(offset: "-10:00") # => Fri, 14 Apr 2017 11:45:15 HST -10:00
<add> # t.change(zone: "Hawaii") # => Fri, 14 Apr 2017 11:45:15 HST -10:00
<add> def change(options)
<add> if options[:zone] && options[:offset]
<add> raise ArgumentError, "Can't change both :offset and :zone at the same time: #{options.inspect}"
<add> end
<add>
<add> new_time = time.change(options)
<add>
<add> if options[:zone]
<add> new_zone = ::Time.find_zone(options[:zone])
<add> elsif options[:offset]
<add> new_zone = ::Time.find_zone(new_time.utc_offset)
<add> end
<add>
<add> new_zone ||= time_zone
<add> periods = new_zone.periods_for_local(new_time)
<add>
<add> self.class.new(nil, new_zone, new_time, periods.include?(period) ? period : nil)
<add> end
<add>
<ide> # Uses Date to provide precise Time calculations for years, months, and days
<ide> # according to the proleptic Gregorian calendar. The result is returned as a
<ide> # new TimeWithZone object.
<ide><path>activesupport/test/core_ext/date_time_ext_test.rb
<ide> def test_change
<ide> assert_equal DateTime.civil(2005, 2, 22, 16, 45), DateTime.civil(2005, 2, 22, 15, 15, 10).change(hour: 16, min: 45)
<ide> assert_equal DateTime.civil(2005, 2, 22, 15, 45), DateTime.civil(2005, 2, 22, 15, 15, 10).change(min: 45)
<ide>
<add> # datetime with non-zero offset
<add> assert_equal DateTime.civil(2005, 2, 22, 15, 15, 10, Rational(-5, 24)), DateTime.civil(2005, 2, 22, 15, 15, 10, 0).change(offset: Rational(-5, 24))
<add>
<ide> # datetime with fractions of a second
<ide> assert_equal DateTime.civil(2005, 2, 1, 15, 15, 10.7), DateTime.civil(2005, 2, 22, 15, 15, 10.7).change(day: 1)
<ide> assert_equal DateTime.civil(2005, 1, 2, 11, 22, Rational(33000008, 1000000)), DateTime.civil(2005, 1, 2, 11, 22, 33).change(usec: 8)
<ide><path>activesupport/test/core_ext/time_ext_test.rb
<ide> def test_offset_change
<ide> assert_raise(ArgumentError) { Time.new(2005, 2, 22, 15, 15, 45, "-08:00").change(nsec: 1000000000) }
<ide> end
<ide>
<add> def test_change_offset
<add> assert_equal Time.new(2006, 2, 22, 15, 15, 10, "-08:00"), Time.new(2006, 2, 22, 15, 15, 10, "+01:00").change(offset: "-08:00")
<add> assert_equal Time.new(2006, 2, 22, 15, 15, 10, -28800), Time.new(2006, 2, 22, 15, 15, 10, 3600).change(offset: -28800)
<add> assert_raise(ArgumentError) { Time.new(2005, 2, 22, 15, 15, 45, "+01:00").change(usec: 1000000, offset: "-08:00") }
<add> assert_raise(ArgumentError) { Time.new(2005, 2, 22, 15, 15, 45, "+01:00").change(nsec: 1000000000, offset: -28800) }
<add> end
<add>
<ide> def test_advance
<ide> assert_equal Time.local(2006, 2, 28, 15, 15, 10), Time.local(2005, 2, 28, 15, 15, 10).advance(years: 1)
<ide> assert_equal Time.local(2005, 6, 28, 15, 15, 10), Time.local(2005, 2, 28, 15, 15, 10).advance(months: 4)
<ide><path>activesupport/test/core_ext/time_with_zone_test.rb
<ide> def test_change
<ide> assert_equal "Fri, 31 Dec 1999 06:00:00 EST -05:00", @twz.change(hour: 6).inspect
<ide> assert_equal "Fri, 31 Dec 1999 19:15:00 EST -05:00", @twz.change(min: 15).inspect
<ide> assert_equal "Fri, 31 Dec 1999 19:00:30 EST -05:00", @twz.change(sec: 30).inspect
<add> assert_equal "Fri, 31 Dec 1999 19:00:00 HST -10:00", @twz.change(offset: "-10:00").inspect
<add> assert_equal "Fri, 31 Dec 1999 19:00:00 HST -10:00", @twz.change(offset: -36000).inspect
<add> assert_equal "Fri, 31 Dec 1999 19:00:00 HST -10:00", @twz.change(zone: "Hawaii").inspect
<add> assert_equal "Fri, 31 Dec 1999 19:00:00 HST -10:00", @twz.change(zone: -10).inspect
<add> assert_equal "Fri, 31 Dec 1999 19:00:00 HST -10:00", @twz.change(zone: -36000).inspect
<add> assert_equal "Fri, 31 Dec 1999 19:00:00 HST -10:00", @twz.change(zone: "Pacific/Honolulu").inspect
<ide> end
<ide>
<ide> def test_change_at_dst_boundary | 6 |
PHP | PHP | apply fixes from styleci | 3f93af4fa18a16caf32b916cea813984ba4243c7 | <ide><path>tests/Routing/RoutingUrlGeneratorTest.php
<ide> public function testBasicRouteGeneration()
<ide> * With Default Parameter
<ide> */
<ide> $url->defaults(['locale' => 'en']);
<del> $route = new Route(['GET'], 'foo', ['as' => 'defaults', 'domain' => '{locale}.example.com', function () {}]);
<add> $route = new Route(['GET'], 'foo', ['as' => 'defaults', 'domain' => '{locale}.example.com', function () {
<add> }]);
<ide> $routes->add($route);
<ide>
<ide> $this->assertEquals('/', $url->route('plain', [], false)); | 1 |
Javascript | Javascript | add test for 06cfff9 regression | 6bf85bc81e7e61b4126c50d05555d5928343423b | <ide><path>test/parallel/test-http-request-dont-override-options.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const http = require('http');
<add>
<add>var requests = 0;
<add>
<add>http.createServer(function(req, res) {
<add> res.writeHead(200);
<add> res.end('ok');
<add>
<add> requests++;
<add>}).listen(common.PORT).unref();
<add>
<add>var agent = new http.Agent();
<add>agent.defaultPort = common.PORT;
<add>
<add>// options marked as explicitly undefined for readability
<add>// in this test, they should STAY undefined as options should not
<add>// be mutable / modified
<add>var options = {
<add> host: undefined,
<add> hostname: common.localhostIPv4,
<add> port: undefined,
<add> defaultPort: undefined,
<add> path: undefined,
<add> method: undefined,
<add> agent: agent
<add>};
<add>
<add>http.request(options, function(res) {
<add> res.resume();
<add>}).end();
<add>
<add>process.on('exit', function() {
<add> assert.equal(requests, 1);
<add>
<add> assert.strictEqual(options.host, undefined);
<add> assert.strictEqual(options.hostname, common.localhostIPv4);
<add> assert.strictEqual(options.port, undefined);
<add> assert.strictEqual(options.defaultPort, undefined);
<add> assert.strictEqual(options.path, undefined);
<add> assert.strictEqual(options.method, undefined);
<add>}); | 1 |
Javascript | Javascript | fix layout in casting screen | d34a75e9e5932adcac4a16f5b815bb909c3aa0dd | <ide><path>Libraries/Components/StatusBar/StatusBar.js
<ide> class StatusBar extends React.Component<Props> {
<ide> if (!oldProps || oldProps.hidden.value !== mergedProps.hidden.value) {
<ide> NativeStatusBarManagerAndroid.setHidden(mergedProps.hidden.value);
<ide> }
<del> if (!oldProps || oldProps.translucent !== mergedProps.translucent) {
<add> // Activities are not translucent by default, so always set if true.
<add> if (
<add> !oldProps ||
<add> oldProps.translucent !== mergedProps.translucent ||
<add> mergedProps.translucent
<add> ) {
<ide> NativeStatusBarManagerAndroid.setTranslucent(mergedProps.translucent);
<ide> }
<ide> } | 1 |
Javascript | Javascript | add todo notes for nativeid hack | 8fc8cd9aeacde05cc9e85452bf25eed3e055e79b | <ide><path>Libraries/Animated/src/createAnimatedComponent.js
<ide> function createAnimatedComponent<Props: {+[string]: mixed, ...}, Instance>(
<ide> {...passthruProps}
<ide> style={mergedStyle}
<ide> ref={this._setComponentRef}
<del> nativeID={this._isFabric() ? 'animatedComponent' : undefined}
<add> nativeID={
<add> this._isFabric() ? 'animatedComponent' : undefined
<add> } /* TODO: T68258846. */
<ide> // The native driver updates views directly through the UI thread so we
<ide> // have to make sure the view doesn't get optimized away because it cannot
<ide> // go through the NativeViewHierarchyManager since it operates on the shadow
<ide><path>Libraries/Components/ScrollView/ScrollView.js
<ide> class ScrollView extends React.Component<Props, State> {
<ide> return (
<ide> <StickyHeaderComponent
<ide> key={key}
<del> nativeID={'StickyHeader-' + key}
<add> nativeID={'StickyHeader-' + key} /* TODO: T68258846. */
<ide> ref={ref => this._setStickyHeaderRef(key, ref)}
<ide> nextHeaderLayoutY={this._headerLayoutYs.get(
<ide> this._getKeyForIndex(nextIndex, childArray),
<ide><path>Libraries/Inspector/InspectorOverlay.js
<ide> class InspectorOverlay extends React.Component<Props> {
<ide> <View
<ide> onStartShouldSetResponder={this.shouldSetResponser}
<ide> onResponderMove={this.findViewForTouchEvent}
<del> nativeID="inspectorOverlay"
<add> nativeID="inspectorOverlay" /* TODO: T68258846. */
<ide> style={[styles.inspector, {height: Dimensions.get('window').height}]}>
<ide> {content}
<ide> </View> | 3 |
Javascript | Javascript | add a key to line number divs | c2dcc0121b71e770f4c542c975129efae5296e1b | <ide><path>src/text-editor-component.js
<ide> class TextEditorComponent {
<ide> children = new Array(visibleTileCount)
<ide>
<ide> let previousBufferRow = (firstTileStartRow > 0) ? this.getModel().bufferRowForScreenRow(firstTileStartRow - 1) : -1
<add> let softWrapCount = 0
<ide> for (let tileStartRow = firstTileStartRow; tileStartRow <= lastTileStartRow; tileStartRow += this.getRowsPerTile()) {
<ide> const currentTileEndRow = tileStartRow + this.getRowsPerTile()
<ide> const lineNumberNodes = []
<ide>
<ide> for (let row = tileStartRow; row < currentTileEndRow && row <= approximateLastScreenRow; row++) {
<ide> const bufferRow = this.getModel().bufferRowForScreenRow(row)
<ide> const foldable = this.getModel().isFoldableAtBufferRow(bufferRow)
<del> const softWrapped = (bufferRow === previousBufferRow)
<add> let softWrapped = false
<add> let key
<add> if (bufferRow === previousBufferRow) {
<add> softWrapped = true
<add> softWrapCount++
<add> key = `${bufferRow}-${softWrapCount}`
<add> } else {
<add> softWrapCount = 0
<add> key = bufferRow
<add> }
<ide>
<ide> let className = 'line-number'
<ide> let lineNumber
<ide> class TextEditorComponent {
<ide> }
<ide> lineNumber = NBSP_CHARACTER.repeat(maxLineNumberDigits - lineNumber.length) + lineNumber
<ide>
<del> lineNumberNodes.push($.div({className},
<add> lineNumberNodes.push($.div({key, className},
<ide> lineNumber,
<ide> $.div({className: 'icon-right'})
<ide> )) | 1 |
Ruby | Ruby | allow overriding filename in `blob#service_url` | 8f52d93576ec23c8e87c96f048585445f871efe5 | <ide><path>activestorage/app/models/active_storage/blob.rb
<ide> def representable?
<ide> # with users. Instead, the +service_url+ should only be exposed as a redirect from a stable, possibly authenticated URL.
<ide> # Hiding the +service_url+ behind a redirect also gives you the power to change services without updating all URLs. And
<ide> # it allows permanent URLs that redirect to the +service_url+ to be cached in the view.
<del> def service_url(expires_in: service.url_expires_in, disposition: :inline)
<add> def service_url(expires_in: service.url_expires_in, disposition: :inline, filename: self.filename)
<ide> service.url key, expires_in: expires_in, disposition: forcibly_serve_as_binary? ? :attachment : disposition, filename: filename, content_type: content_type
<ide> end
<ide>
<ide><path>activestorage/test/models/blob_test.rb
<ide> class ActiveStorage::BlobTest < ActiveSupport::TestCase
<ide> end
<ide> end
<ide>
<add> test "urls allow for custom filename" do
<add> blob = create_blob(filename: "original.txt")
<add> new_filename = ActiveStorage::Filename.new("new.txt")
<add>
<add> freeze_time do
<add> assert_equal expected_url_for(blob), blob.service_url
<add> assert_equal expected_url_for(blob, filename: new_filename), blob.service_url(filename: new_filename)
<add> end
<add> end
<add>
<ide> test "purge deletes file from external service" do
<ide> blob = create_blob
<ide>
<ide> class ActiveStorage::BlobTest < ActiveSupport::TestCase
<ide> end
<ide>
<ide> private
<del> def expected_url_for(blob, disposition: :inline)
<del> query_string = { content_type: blob.content_type, disposition: "#{disposition}; #{blob.filename.parameters}" }.to_param
<del> "/rails/active_storage/disk/#{ActiveStorage.verifier.generate(blob.key, expires_in: 5.minutes, purpose: :blob_key)}/#{blob.filename}?#{query_string}"
<add> def expected_url_for(blob, disposition: :inline, filename: nil)
<add> filename ||= blob.filename
<add> query_string = { content_type: blob.content_type, disposition: "#{disposition}; #{filename.parameters}" }.to_param
<add> "/rails/active_storage/disk/#{ActiveStorage.verifier.generate(blob.key, expires_in: 5.minutes, purpose: :blob_key)}/#{filename}?#{query_string}"
<ide> end
<ide> end | 2 |
Javascript | Javascript | set background to null only if it's a color | 4f708fbcd1d22f3e79b07bbf30a1e6189aa05bca | <ide><path>src/extras/PMREMGenerator.js
<ide> class PMREMGenerator {
<ide> if ( background && background.isColor ) {
<ide>
<ide> _backgroundColor.copy( background );
<add> scene.background = null;
<ide>
<ide> } else {
<ide>
<ide> class PMREMGenerator {
<ide> _backgroundColor.multiplyScalar( Math.pow( 2.0, - fExp ) );
<ide> const alpha = ( fExp + 128.0 ) / 255.0;
<ide> renderer.setClearColor( _backgroundColor, alpha );
<del> scene.background = null;
<ide>
<ide>
<ide> for ( let i = 0; i < 6; i ++ ) { | 1 |
Go | Go | create the working directory on container creation | cde0ed67a14e3983ba83af8c75434558c865b2bc | <ide><path>daemon/create_unix.go
<ide> func (daemon *Daemon) createContainerPlatformSpecificSettings(container *contain
<ide> }
<ide> defer daemon.Unmount(container)
<ide>
<add> if err := container.SetupWorkingDirectory(); err != nil {
<add> return err
<add> }
<add>
<ide> for spec := range config.Volumes {
<ide> name := stringid.GenerateNonCryptoID()
<ide> destination := filepath.Clean(spec)
<ide><path>integration-cli/docker_cli_build_test.go
<ide> func (s *DockerSuite) TestBuildBuildTimeArgExpansion(c *check.C) {
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> }
<del> if res != wdVal {
<del> c.Fatalf("Config.WorkingDir value mismatch. Expected: %s, got: %s", wdVal, res)
<add> if res != filepath.Clean(wdVal) {
<add> c.Fatalf("Config.WorkingDir value mismatch. Expected: %s, got: %s", filepath.Clean(wdVal), res)
<ide> }
<ide>
<ide> err = inspectFieldAndMarshall(imgName, "Config.Env", &resArr)
<ide><path>integration-cli/docker_cli_create_test.go
<ide> func (s *DockerSuite) TestCreateStopSignal(c *check.C) {
<ide> c.Assert(res, checker.Contains, "9")
<ide>
<ide> }
<add>
<add>func (s *DockerSuite) TestCreateWithWorkdir(c *check.C) {
<add> testRequires(c, DaemonIsLinux)
<add> name := "foo"
<add> dir := "/home/foo/bar"
<add> dockerCmd(c, "create", "--name", name, "-w", dir, "busybox")
<add> dockerCmd(c, "cp", fmt.Sprintf("%s:%s", name, dir), "/tmp")
<add>} | 3 |
Python | Python | simplify code in cov function a bit | a0bd6c78671a63b9aa1f875bffb4937e4991bbd6 | <ide><path>numpy/lib/function_base.py
<ide> def cov(m, y=None, rowvar=1, bias=0, ddof=None, fweights=None, aweights=None):
<ide> # Determine the normalization
<ide> if w is None:
<ide> fact = float(X.shape[1] - ddof)
<add> elif ddof == 0:
<add> fact = w_sum
<add> elif aweights is None:
<add> fact = w_sum - ddof
<ide> else:
<del> if ddof == 0:
<del> fact = w_sum
<del> elif aweights is None:
<del> fact = w_sum - ddof
<del> else:
<del> fact = w_sum - ddof*sum(w*aweights)/w_sum
<add> fact = w_sum - ddof*sum(w*aweights)/w_sum
<ide>
<ide> if fact <= 0:
<ide> warnings.warn("Degrees of freedom <= 0 for slice", RuntimeWarning) | 1 |
PHP | PHP | fix failing test | 6406e528f07923ccd357762eed3e87e58ef97af6 | <ide><path>lib/Cake/Routing/Route/RedirectRoute.php
<ide> public function parse($url) {
<ide> if (isset($this->options['status']) && ($this->options['status'] >= 300 && $this->options['status'] < 400)) {
<ide> $status = $this->options['status'];
<ide> }
<del> $this->response->header(array('Location' => Router::url($redirect, true)));
<add> $this->response->header(array(
<add> 'Location' => Router::url($redirect, true)
<add> ));
<ide> $this->response->statusCode($status);
<ide> $this->response->send();
<ide> $this->_stop();
<ide><path>lib/Cake/Test/TestCase/Routing/RouterTest.php
<ide> public function testRouteRedirection() {
<ide> Router::setRouteCollection($routes);
<ide>
<ide> Router::redirect('/blog', array('controller' => 'posts'), array('status' => 302));
<del> $this->assertEquals(1, count($routes));
<add> Router::connect('/:controller', array('action' => 'index'));
<add>
<add> $this->assertEquals(2, count($routes));
<ide>
<del> $routes->get(0)->response = $this->getMock('Cake\Network\Response', array('_sendHeader'));
<add> $routes->get(0)->response = $this->getMock(
<add> 'Cake\Network\Response',
<add> array('_sendHeader')
<add> );
<ide> $routes->get(0)->stop = false;
<ide> $this->assertEquals(302, $routes->get(0)->options['status']);
<ide>
<ide> public function testRouteRedirection() {
<ide> $this->assertEquals(Router::url('/posts', true), $header['Location']);
<ide> $this->assertEquals(302, $routes->get(0)->response->statusCode());
<ide>
<del> $routes->get(0)->response = $this->getMock('Cake\Network\Response', array('_sendHeader'));
<add> $routes->get(0)->response = $this->getMock(
<add> 'Cake\Network\Response',
<add> array('_sendHeader')
<add> );
<ide> Router::parse('/not-a-match');
<ide> $this->assertEquals(array(), $routes->get(0)->response->header());
<ide> } | 2 |
Ruby | Ruby | remove unused attribute | 375c073cec0ce0c18e11fa039e2cbbd4baaa9751 | <ide><path>Library/Homebrew/exceptions.rb
<ide> def message
<ide> end
<ide>
<ide> class BuildError < Homebrew::InstallationError
<del> attr_reader :exit_status, :command, :env
<add> attr_reader :command, :env
<ide>
<del> def initialize formula, cmd, args, es
<add> def initialize formula, cmd, args
<ide> @command = cmd
<ide> @env = ENV.to_hash
<del> @exit_status = es.exitstatus rescue 1
<ide> args = args.map{ |arg| arg.to_s.gsub " ", "\\ " }.join(" ")
<ide> super formula, "Failed executing: #{command} #{args}"
<ide> end
<ide><path>Library/Homebrew/formula.rb
<ide> def system cmd, *args
<ide> f.puts
<ide> require 'cmd/config'
<ide> Homebrew.write_build_config(f)
<del> raise BuildError.new(self, cmd, args, $?)
<add> raise BuildError.new(self, cmd, args)
<ide> end
<ide> end
<ide> ensure | 2 |
Python | Python | add axis to bn config | 8823fa520bf35478f9d6d4b36f291d1e14300a05 | <ide><path>keras/layers/normalization.py
<ide> def get_config(self):
<ide> config = {"name": self.__class__.__name__,
<ide> "epsilon": self.epsilon,
<ide> "mode": self.mode,
<add> "axis": self.axis,
<ide> "momentum": self.momentum}
<ide> base_config = super(BatchNormalization, self).get_config()
<ide> return dict(list(base_config.items()) + list(config.items())) | 1 |
Text | Text | stabilize subpath patterns | 0c3e10005e524a27f190856e3415baaa2267e3c6 | <ide><path>doc/api/packages.md
<ide> analogous to the exports field.
<ide>
<ide> ### Subpath patterns
<ide>
<del>> Stability: 1 - Experimental
<del>
<ide> For packages with a small number of exports or imports, we recommend
<ide> explicitly listing each exports subpath entry. But for packages that have
<ide> large numbers of subpaths, this might cause `package.json` bloat and | 1 |
Mixed | Python | sentiment analysis implmenttion in pure keras. | 61ec6026722e71771b902f9bec1ff0ce36d49b54 | <ide><path>research/sentiment_analysis/README.md
<ide> ## Overview
<ide> This is an implementation of the Sentiment Analysis model as described in the [this paper](https://arxiv.org/abs/1412.1058). The implementation is with the reference to [paddle version](https://github.com/mlperf/reference/tree/master/sentiment_analysis/paddle).
<ide>
<del>The model makes use of concatenation of two CNN layers with different kernel sizes. Dropout and batch normalization layers are used to prevent over-fitting.
<add>The model makes use of concatenation of two CNN layers with different kernel sizes. Batch normalization and dropout layers are used to prevent over-fitting.
<ide>
<ide> ## Dataset
<ide> The [keras](https://keras.io)'s [IMDB Movie reviews sentiment classification](https://keras.io/datasets/#imdb-movie-reviews-sentiment-classification) dataset is used. The dataset file download is handled by keras module, and the downloaded files are stored at ``~/.keras/datasets` directory. The compressed file's filesize as of June 15 2018 is 17MB.
<ide> To train and evaluate the model, issue the following command:
<ide> python sentiment_main.py
<ide> ```
<ide> Arguments:
<del> * `--vocabulary_size`: The number of words included in the dataset. The most frequent words are chosen. The default is 6000.
<del> * `--sentence_length`: The length of the sentence
<ide> * `--dataset`: The dataset name to be downloaded and preprocessed. By default, it is `imdb`.
<ide>
<ide> There are other arguments about models and training process. Use the `--help` or `-h` flag to get a full list of possible arguments with detailed descriptions.
<ide>
<del>## Benchmarks (TBA)
<ide>\ No newline at end of file
<add>## Benchmarks
<add>The model was recorded to have the accuracy of 90.1% for the IMDB dataset.
<ide><path>research/sentiment_analysis/data/dataset.py
<add>"""Dataset module for sentiment analysis.
<add>
<add>Currently imdb dataset is available.
<add>"""
<add>
<add>from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<add>
<ide> import data.imdb as imdb
<ide>
<ide> DATASET_IMDB = "imdb"
<ide>
<ide>
<del>def construct_input_fns(dataset, batch_size, vocabulary_size,
<del> sentence_length, repeat=1):
<del> """Returns training and evaluation input functions.
<add>def load(dataset, vocabulary_size, sentence_length):
<add> """Returns training and evaluation input.
<ide>
<ide> Args:
<ide> dataset: Dataset to be trained and evaluated.
<ide> Currently only imdb is supported.
<del> batch_size: Number of data in each batch.
<ide> vocabulary_size: The number of the most frequent tokens
<ide> to be used from the corpus.
<ide> sentence_length: The number of words in each sentence.
<ide> Longer sentences get cut, shorter ones padded.
<del> repeat: The number of epoch.
<ide> Raises:
<ide> ValueError: if the dataset value is not valid.
<ide> Returns:
<del> A tuple of training and evaluation input function.
<add> A tuple of length 4, for training sentences, labels,
<add> evaluation sentences, and evaluation labels,
<add> each being an numpy array.
<ide> """
<ide> if dataset == DATASET_IMDB:
<del> train_input_fn, eval_input_fn = imdb.construct_input_fns(
<del> vocabulary_size, sentence_length, batch_size, repeat=repeat)
<del> return train_input_fn, eval_input_fn
<add> return imdb.load(vocabulary_size, sentence_length)
<ide> else:
<ide> raise ValueError("unsupported dataset: " + dataset)
<ide>
<ide> def get_num_class(dataset):
<ide> Raises:
<ide> ValueError: if the dataset value is not valid.
<ide> Returns:
<del> str: The dataset name.
<add> int: The number of label classes.
<ide> """
<ide> if dataset == DATASET_IMDB:
<ide> return imdb.NUM_CLASS
<ide><path>research/sentiment_analysis/data/imdb.py
<del>from data.util import pad_sentence, to_dataset, START_CHAR, OOV_CHAR
<del>import tensorflow as tf, numpy as np
<add>"""IMDB Dataset module for sentiment analysis."""
<add>
<add>from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<add>
<add>import numpy as np
<add>import tensorflow as tf
<add>
<add>from data.util import OOV_CHAR
<add>from data.util import pad_sentence
<add>from data.util import START_CHAR
<ide>
<ide> NUM_CLASS = 2
<ide>
<ide>
<del>def construct_input_fns(vocabulary_size, sentence_length,
<del> batch_size, repeat=1):
<del> """Returns training and evaluation input functions.
<add>def load(vocabulary_size, sentence_length):
<add> """Returns training and evaluation input for imdb dataset.
<ide>
<ide> Args:
<ide> vocabulary_size: The number of the most frequent tokens
<ide> to be used from the corpus.
<ide> sentence_length: The number of words in each sentence.
<ide> Longer sentences get cut, shorter ones padded.
<del> batch_size: Number of data in each batch.
<del> repeat: The number of epoch.
<ide> Raises:
<ide> ValueError: if the dataset value is not valid.
<ide> Returns:
<del> A tuple of training and evaluation input function.
<add> A tuple of length 4, for training and evaluation data,
<add> each being an numpy array.
<ide> """
<ide> (x_train, y_train), (x_test, y_test) = tf.keras.datasets.imdb.load_data(
<ide> path="imdb.npz",
<ide> def construct_input_fns(vocabulary_size, sentence_length,
<ide> seed=113,
<ide> start_char=START_CHAR,
<ide> oov_char=OOV_CHAR,
<del> index_from=OOV_CHAR + 1)
<del>
<del> def train_input_fn():
<del> dataset = to_dataset(
<del> np.array([pad_sentence(s, sentence_length) for s in x_train]),
<del> np.eye(NUM_CLASS)[y_train], batch_size, repeat)
<del> dataset = dataset.shuffle(len(x_train), reshuffle_each_iteration=True)
<del> return dataset
<del>
<del> def eval_input_fn():
<del> dataset = to_dataset(
<del> np.array([pad_sentence(s, sentence_length) for s in x_test]),
<del> np.eye(NUM_CLASS)[y_test], batch_size, repeat)
<del> return dataset
<del>
<del> return train_input_fn, eval_input_fn
<add> index_from=OOV_CHAR+1)
<add>
<add> x_train_processed = []
<add> for sen in x_train:
<add> sen = pad_sentence(sen, sentence_length)
<add> x_train_processed.append(np.array(sen))
<add> x_train_processed = np.array(x_train_processed)
<add>
<add> x_test_processed = []
<add> for sen in x_test:
<add> sen = pad_sentence(sen, sentence_length)
<add> x_test_processed.append(np.array(sen))
<add> x_test_processed = np.array(x_test_processed)
<add>
<add> return x_train_processed, np.eye(NUM_CLASS)[y_train], \
<add> x_test_processed, np.eye(NUM_CLASS)[y_test]
<ide><path>research/sentiment_analysis/data/util.py
<add>"""Utility module for sentiment analysis."""
<add>
<add>from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<add>
<ide> import numpy as np
<del>import tensorflow as tf
<ide>
<ide> START_CHAR = 1
<ide> END_CHAR = 2
<ide> OOV_CHAR = 3
<ide>
<ide>
<del>def pad_sentence(sen, sentence_length):
<del> sen = sen[:sentence_length]
<del> if len(sen) < sentence_length:
<del> sen = np.pad(sen, (0, sentence_length - len(sen)), "constant",
<del> constant_values=(START_CHAR, END_CHAR))
<del> return sen
<del>
<add>def pad_sentence(sentence, sentence_length):
<add> """Pad the given sentense at the end.
<ide>
<del>def to_dataset(x, y, batch_size, repeat):
<del> dataset = tf.data.Dataset.from_tensor_slices((x, y))
<add> If the input is longer than sentence_length,
<add> the remaining portion is dropped.
<add> END_CHAR is used for the padding.
<ide>
<del> # Repeat and batch the dataset
<del> dataset = dataset.repeat(repeat)
<del> dataset = dataset.batch(batch_size)
<add> Args:
<add> sentence: A numpy array of integers.
<add> sentence_length: The length of the input after the padding.
<add> Returns:
<add> A numpy array of integers of the given length.
<add> """
<add> sentence = sentence[:sentence_length]
<add> if len(sentence) < sentence_length:
<add> sentence = np.pad(sentence, (0, sentence_length - len(sentence)),
<add> "constant", constant_values=(START_CHAR, END_CHAR))
<ide>
<del> # Prefetch to improve speed of input pipeline.
<del> dataset = dataset.prefetch(10)
<del> return dataset
<add> return sentence
<ide><path>research/sentiment_analysis/sentiment_main.py
<del>"""The main module for sentiment analysis.
<add>"""Main function for the sentiment analysis model.
<ide>
<del>The model makes use of concatenation of two CNN layers
<del>with different kernel sizes.
<del>See `sentiment_model.py` for more details about the models.
<add>The model makes use of concatenation of two CNN layers with
<add>different kernel sizes. See `sentiment_model.py`
<add>for more details about the models.
<ide> """
<add>
<ide> from __future__ import absolute_import
<ide> from __future__ import division
<ide> from __future__ import print_function
<ide>
<del>from absl import app as absl_app
<del>from absl import flags
<del>from data import dataset
<del>from official.utils.flags import core as flags_core
<del>from official.utils.logs import hooks_helper
<del>from official.utils.logs import logger
<del>from official.utils.misc import distribution_utils
<del>import sentiment_model
<del>import tensorflow as tf
<del>
<del>
<del>def convert_keras_to_estimator(keras_model, num_gpus, model_dir=None):
<del> """Convert keras model into tensorflow estimator."""
<del>
<del> keras_model.compile(optimizer="rmsprop",
<del> loss="categorical_crossentropy", metrics=["accuracy"])
<del>
<del> distribution = distribution_utils.get_distribution_strategy(
<del> num_gpus, all_reduce_alg=None)
<del> run_config = tf.estimator.RunConfig(train_distribute=distribution)
<del>
<del> estimator = tf.keras.estimator.model_to_estimator(
<del> keras_model=keras_model, model_dir=model_dir, config=run_config)
<del>
<del> return estimator
<del>
<del>
<del>def run_model(flags_obj):
<del> """Run training and eval loop."""
<add>import argparse
<ide>
<del> num_class = dataset.get_num_class(flags_obj.dataset)
<del>
<del> tf.logging.info("Loading the dataset...")
<del>
<del> train_input_fn, eval_input_fn = dataset.construct_input_fns(
<del> flags_obj.dataset, flags_obj.batch_size, flags_obj.vocabulary_size,
<del> flags_obj.sentence_length, repeat=flags_obj.epochs_between_evals)
<del>
<del> keras_model = sentiment_model.CNN(
<del> flags_obj.embedding_dim, flags_obj.vocabulary_size,
<del> flags_obj.sentence_length,
<del> flags_obj.cnn_filters, num_class, flags_obj.dropout_rate)
<del> num_gpus = flags_core.get_num_gpus(FLAGS)
<del> tf.logging.info("Creating Estimator from Keras model...")
<del> estimator = convert_keras_to_estimator(
<del> keras_model, num_gpus, flags_obj.model_dir)
<del>
<del> # Create hooks that log information about the training and metric values
<del> train_hooks = hooks_helper.get_train_hooks(
<del> flags_obj.hooks,
<del> batch_size=flags_obj.batch_size # for ExamplesPerSecondHook
<del> )
<del> run_params = {
<del> "batch_size": flags_obj.batch_size,
<del> "train_epochs": flags_obj.train_epochs,
<del> }
<del> benchmark_logger = logger.get_benchmark_logger()
<del> benchmark_logger.log_run_info(
<del> model_name="sentiment_analysis",
<del> dataset_name=flags_obj.dataset,
<del> run_params=run_params,
<del> test_id=flags_obj.benchmark_test_id)
<del>
<del> # Training and evaluation cycle
<del> total_training_cycle = flags_obj.train_epochs\
<del> // flags_obj.epochs_between_evals
<del>
<del> for cycle_index in range(total_training_cycle):
<del> tf.logging.info("Starting a training cycle: {}/{}".format(
<del> cycle_index + 1, total_training_cycle))
<del>
<del> # Train the model
<del> estimator.train(input_fn=train_input_fn, hooks=train_hooks)
<del>
<del> # Evaluate the model
<del> eval_results = estimator.evaluate(input_fn=eval_input_fn)
<del>
<del> # Benchmark the evaluation results
<del> benchmark_logger.log_evaluation_result(eval_results)
<add>import tensorflow as tf
<ide>
<del> tf.logging.info("Iteration {}".format(eval_results))
<add>from data import dataset
<add>import sentiment_model
<ide>
<del> # Clear the session explicitly to avoid session delete error
<del> tf.keras.backend.clear_session()
<add>_DROPOUT_RATE = 0.95
<ide>
<ide>
<del>def main(_):
<del> with logger.benchmark_context(FLAGS):
<del> run_model(FLAGS)
<add>def run_model(dataset_name, emb_dim, voc_size, sen_len,
<add> hid_dim, batch_size, epochs):
<add> """Run training loop and an evaluation at the end.
<ide>
<add> Args:
<add> dataset_name: Dataset name to be trained and evaluated.
<add> emb_dim: The dimension of the Embedding layer.
<add> voc_size: The number of the most frequent tokens
<add> to be used from the corpus.
<add> sen_len: The number of words in each sentence.
<add> Longer sentences get cut, shorter ones padded.
<add> hid_dim: The dimension of the Embedding layer.
<add> batch_size: The size of each batch during training.
<add> epochs: The number of the iteration over the training set for training.
<add> """
<ide>
<del>def define_flags():
<del> """Add flags to run the main function."""
<add> model = sentiment_model.CNN(emb_dim, voc_size, sen_len,
<add> hid_dim, dataset.get_num_class(dataset_name),
<add> _DROPOUT_RATE)
<add> model.summary()
<ide>
<del> # Add common flags
<del> flags_core.define_base(export_dir=False)
<del> flags_core.define_performance(
<del> num_parallel_calls=False,
<del> inter_op=False,
<del> intra_op=False,
<del> synthetic_data=False,
<del> max_train_steps=False,
<del> dtype=False
<del> )
<del> flags_core.define_benchmark()
<add> model.compile(loss="categorical_crossentropy",
<add> optimizer="rmsprop",
<add> metrics=["accuracy"])
<ide>
<del> flags.adopt_module_key_flags(flags_core)
<add> tf.logging.info("Loading the data")
<add> x_train, y_train, x_test, y_test = dataset.load(
<add> dataset_name, voc_size, sen_len)
<ide>
<del> flags_core.set_defaults(
<del> model_dir=None,
<del> train_epochs=30,
<del> batch_size=30,
<del> hooks="")
<del>
<del> # Add domain-specific flags
<del> flags.DEFINE_enum(
<del> name="dataset", default=dataset.DATASET_IMDB,
<del> enum_values=[dataset.DATASET_IMDB], case_sensitive=False,
<del> help=flags_core.help_wrap(
<del> "Dataset to be trained and evaluated."))
<del>
<del> flags.DEFINE_integer(
<del> name="vocabulary_size", default=6000,
<del> help=flags_core.help_wrap(
<del> "The number of the most frequent tokens"
<del> "to be used from the corpus."))
<del>
<del> flags.DEFINE_integer(
<del> name="sentence_length", default=200,
<del> help=flags_core.help_wrap(
<del> "The number of words in each sentence. Longer sentences get cut,"
<del> "shorter ones padded."))
<del>
<del> flags.DEFINE_integer(
<del> name="embedding_dim", default=256,
<del> help=flags_core.help_wrap("The dimension of the Embedding layer."))
<del>
<del> flags.DEFINE_integer(
<del> name="cnn_filters", default=512,
<del> help=flags_core.help_wrap("The number of the CNN layer filters."))
<del>
<del> flags.DEFINE_float(
<del> name="dropout_rate", default=0.7,
<del> help=flags_core.help_wrap("The rate for the Dropout layer."))
<add> model.fit(x_train, y_train, batch_size=batch_size,
<add> validation_split=0.4, epochs=epochs)
<add> score = model.evaluate(x_test, y_test, batch_size=batch_size)
<add> tf.logging.info("Score: {}".format(score))
<ide>
<ide> if __name__ == "__main__":
<del> tf.logging.set_verbosity(tf.logging.INFO)
<del> define_flags()
<del> FLAGS = flags.FLAGS
<del> absl_app.run(main)
<add> parser = argparse.ArgumentParser()
<add> parser.add_argument("-d", "--dataset", help="Dataset to be trained "
<add> "and evaluated.",
<add> type=str, choices=["imdb"], default="imdb")
<add>
<add> parser.add_argument("-e", "--embedding_dim",
<add> help="The dimension of the Embedding layer.",
<add> type=int, default=512)
<add>
<add> parser.add_argument("-v", "--vocabulary_size",
<add> help="The number of the words to be considered "
<add> "in the dataset corpus.",
<add> type=int, default=6000)
<add>
<add> parser.add_argument("-s", "--sentence_length",
<add> help="The number of words in a data point."
<add> "Entries of smaller length are padded.",
<add> type=int, default=600)
<add>
<add> parser.add_argument("-c", "--hidden_dim",
<add> help="The number of the CNN layer filters.",
<add> type=int, default=512)
<add>
<add> parser.add_argument("-b", "--batch_size",
<add> help="The size of each batch for training.",
<add> type=int, default=500)
<add>
<add> parser.add_argument("-p", "--epochs",
<add> help="The number of epochs for training.",
<add> type=int, default=55)
<add>
<add> args = parser.parse_args()
<add>
<add> run_model(args.dataset, args.embedding_dim, args.vocabulary_size,
<add> args.sentence_length, args.hidden_dim,
<add> args.batch_size, args.epochs)
<ide><path>research/sentiment_analysis/sentiment_model.py
<add>"""Model for sentiment analysis.
<add>
<add>The model makes use of concatenation of two CNN layers with
<add>different kernel sizes.
<add>"""
<add>
<ide> from __future__ import absolute_import
<ide> from __future__ import division
<ide> from __future__ import print_function
<ide>
<ide> import tensorflow as tf
<ide>
<ide>
<del>def _dynamic_pooling(w_embs):
<del> """Dynamic Pooling layer.
<del>
<del> Given the variable-sized output of the convolution layer,
<del> the pooling with a fixed pooling kernel size and stride would
<del> produce variable-sized output, whereas the following fully-connected
<del> layer expects fixes input layer size.
<del> Thus we fix the number of pooling units (to 2) and dynamically
<del> determine the pooling region size on each data point.
<del>
<del> Args:
<del> w_embs: a input tensor with dimensionality of 1.
<del> Returns:
<del> A tensor of size 2.
<del> """
<del> # a Lambda layer maintain separate context, so that tf should be imported
<del> # here.
<del> import tensorflow as tf
<del> t = tf.expand_dims(w_embs, 2)
<del> pool_size = w_embs.shape[1].value / 2
<del> pooled = tf.keras.backend.pool2d(t, (pool_size, 1), strides=(
<del> pool_size, 1), data_format="channels_last")
<del> return tf.squeeze(pooled, 2)
<del>
<del>
<del>def _dynamic_pooling_output_shape(input_shape):
<del> """Output shape for the dynamic pooling layer.
<del>
<del> This function is used for keras Lambda layer to indicate
<del> the output shape of the dynamic poolic layer.
<del>
<del> Args:
<del> input_shape: A tuple for the input shape.
<del> Returns:
<del> output shape for the dynamic pooling layer.
<del> """
<del> shape = list(input_shape)
<del> assert len(shape) == 2 # only valid for 2D tensors
<del> shape[1] = 2
<del> return tuple(shape)
<del>
<del>
<ide> class CNN(tf.keras.models.Model):
<ide> """CNN for sentimental analysis."""
<ide>
<ide> def __init__(self, emb_dim, num_words, sentence_length, hid_dim,
<del> class_dim, dropout_rate):
<add> class_dim, dropout_rate):
<ide> """Initialize CNN model.
<ide>
<ide> Args:
<ide> def __init__(self, emb_dim, num_words, sentence_length, hid_dim,
<ide> class_dim: The number of the CNN layer filters.
<ide> dropout_rate: The portion of kept value in the Dropout layer.
<ide> Returns:
<del> tf.keras.models.Model: A model.
<add> tf.keras.models.Model: A Keras model.
<ide> """
<ide>
<del> input = tf.keras.layers.Input(shape=(sentence_length,), dtype=tf.int32)
<add> input_layer = tf.keras.layers.Input(shape=(sentence_length,), dtype=tf.int32)
<ide>
<del> layer = tf.keras.layers.Embedding(num_words, output_dim=emb_dim)(input)
<add> layer = tf.keras.layers.Embedding(num_words, output_dim=emb_dim)(input_layer)
<ide>
<ide> layer_conv3 = tf.keras.layers.Conv1D(hid_dim, 3, activation="relu")(layer)
<del> layer_conv3 = tf.keras.layers.Lambda(_dynamic_pooling,
<del> output_shape=_dynamic_pooling_output_shape)(layer_conv3)
<del> layer_conv3 = tf.keras.layers.Flatten()(layer_conv3)
<add> layer_conv3 = tf.keras.layers.GlobalMaxPooling1D()(layer_conv3)
<ide>
<del> layer_conv2 = tf.keras.layers.Conv1D(hid_dim, 2, activation="relu")(layer)
<del> layer_conv2 = tf.keras.layers.Lambda(_dynamic_pooling,
<del> output_shape=_dynamic_pooling_output_shape)(layer_conv2)
<del> layer_conv2 = tf.keras.layers.Flatten()(layer_conv2)
<add> layer_conv4 = tf.keras.layers.Conv1D(hid_dim, 2, activation="relu")(layer)
<add> layer_conv4 = tf.keras.layers.GlobalMaxPooling1D()(layer_conv4)
<ide>
<del> layer = tf.keras.layers.concatenate([layer_conv2, layer_conv3], axis=1)
<del> layer = tf.keras.layers.Dropout(dropout_rate)(layer)
<add> layer = tf.keras.layers.concatenate([layer_conv4, layer_conv3], axis=1)
<ide> layer = tf.keras.layers.BatchNormalization()(layer)
<add> layer = tf.keras.layers.Dropout(dropout_rate)(layer)
<ide>
<ide> output = tf.keras.layers.Dense(class_dim, activation="softmax")(layer)
<ide>
<del> super(CNN, self).__init__(inputs=[input], outputs=output)
<add> super(CNN, self).__init__(inputs=[input_layer], outputs=output) | 6 |
PHP | PHP | fix incorrect definition | 1d95529e3c98ab71eccae397da9e29ccaa53abd9 | <ide><path>src/Illuminate/Foundation/Console/VendorPublishCommand.php
<ide> class VendorPublishCommand extends Command
<ide> * @var string
<ide> */
<ide> protected $signature = 'vendor:publish {--force : Overwrite any existing files.}
<del> {--provider? : The service provider that has assets you want to publish.}
<del> {--tag?* : One or many tags that have assets you want to publish.}';
<add> {--provider= : The service provider that has assets you want to publish.}
<add> {--tag=* : One or many tags that have assets you want to publish.}';
<ide>
<ide> /**
<ide> * The console command description. | 1 |
Text | Text | release notes for 1.2.10 | 4f827f587b340ff7563ca01fe68c244a6cd0d5c4 | <ide><path>CHANGELOG.md
<add><a name="1.2.10"></a>
<add># 1.2.10 augmented-serendipity (2014-01-24)
<add>
<add>
<add>## Bug Fixes
<add>
<add>- **$parse:** do not use locals to resolve object properties
<add> ([f09b6aa5](https://github.com/angular/angular.js/commit/f09b6aa5b58c090e3b8f8811fb7735e38d4b7623),
<add> [#5838](https://github.com/angular/angular.js/issues/5838), [#5862](https://github.com/angular/angular.js/issues/5862))
<add>- **a:** don't call preventDefault on click when a SVGAElement has an xlink:href attribute
<add> ([e0209169](https://github.com/angular/angular.js/commit/e0209169bf1463465ad07484421620748a4d3908),
<add> [#5896](https://github.com/angular/angular.js/issues/5896), [#5897](https://github.com/angular/angular.js/issues/5897))
<add>- **input:** use Chromium's email validation regexp
<add> ([79e519fe](https://github.com/angular/angular.js/commit/79e519fedaec54390a8bdacfb1926bfce57a1eb6),
<add> [#5899](https://github.com/angular/angular.js/issues/5899), [#5924](https://github.com/angular/angular.js/issues/5924))
<add>- **ngRoute:** pipe preceding route param no longer masks ? or * operator
<add> ([fd6bac7d](https://github.com/angular/angular.js/commit/fd6bac7de56f728a89782dc80c78f7d5c21bbc65),
<add> [#5920](https://github.com/angular/angular.js/issues/5920))
<add>
<add>
<add>## Features
<add>
<add>- **$animate:** provide support for a close callback
<add> ([ca6b7d0f](https://github.com/angular/angular.js/commit/ca6b7d0fa2e355ebd764230260758cee9a4ebe1e),
<add> [#5685](https://github.com/angular/angular.js/issues/5685), [#5053](https://github.com/angular/angular.js/issues/5053), [#4993](https://github.com/angular/angular.js/issues/4993))
<add>
<add>
<ide> <a name="1.2.9"></a>
<ide> # 1.2.9 enchanted-articulacy (2014-01-15)
<ide> | 1 |
Javascript | Javascript | check number of message events | b5b6f5d6a9a5402e55f5080928d740e12e7295a4 | <ide><path>test/parallel/test-child-process-fork-ref2.js
<ide> if (process.argv[2] === 'child') {
<ide>
<ide> setTimeout(function() {
<ide> console.log('child -> will this keep it alive?');
<del> process.on('message', common.noop);
<add> process.on('message', common.mustNotCall());
<ide> }, 400);
<ide>
<ide> } else {
<ide><path>test/sequential/test-child-process-pass-fd.js
<ide> if (process.argv[2] !== 'child') {
<ide> // the only thing keeping this worker alive will be IPC. This is important,
<ide> // because it means a worker with no parent will have no referenced handles,
<ide> // thus no work to do, and will exit immediately, preventing process leaks.
<del> process.on('message', common.noop);
<add> process.on('message', common.mustCall());
<ide>
<ide> const server = net.createServer((c) => {
<ide> process.once('message', function(msg) { | 2 |
Javascript | Javascript | add missing semicolon | b32fbef7c51462287b4e56ec989398d994b093ee | <ide><path>src/core/__tests__/ReactCompositeComponent-test.js
<ide> describe('ReactCompositeComponent', function() {
<ide> getInitialState: function() {
<ide> return {
<ide> flag: false
<del> }
<add> };
<ide> },
<ide>
<ide> render: function() { | 1 |
Python | Python | remove side effects from tests | bb19b9179ac645156a59054a34f147ca6b146b9f | <ide><path>tests/api_connexion/endpoints/test_connection_endpoint.py
<ide> from parameterized import parameterized
<ide>
<ide> from airflow.models import Connection
<del>from airflow.utils.session import create_session, provide_session
<add>from airflow.utils.session import provide_session
<ide> from airflow.www import app
<ide> from tests.test_utils.config import conf_vars
<ide> from tests.test_utils.db import clear_db_connections
<ide> def setUpClass(cls) -> None:
<ide> def setUp(self) -> None:
<ide> self.client = self.app.test_client() # type:ignore
<ide> # we want only the connection created here for this test
<del> with create_session() as session:
<del> session.query(Connection).delete()
<add> clear_db_connections()
<ide>
<ide> def tearDown(self) -> None:
<ide> clear_db_connections()
<ide><path>tests/api_connexion/endpoints/test_event_log_endpoint.py
<ide> from airflow.models import Log, TaskInstance
<ide> from airflow.operators.dummy_operator import DummyOperator
<ide> from airflow.utils import timezone
<del>from airflow.utils.session import create_session, provide_session
<add>from airflow.utils.session import provide_session
<ide> from airflow.www import app
<ide> from tests.test_utils.config import conf_vars
<add>from tests.test_utils.db import clear_db_logs
<ide>
<ide>
<ide> class TestEventLogEndpoint(unittest.TestCase):
<ide> def setUpClass(cls) -> None:
<ide>
<ide> def setUp(self) -> None:
<ide> self.client = self.app.test_client() # type:ignore
<del> with create_session() as session:
<del> session.query(Log).delete()
<add> clear_db_logs()
<ide> self.default_time = "2020-06-10T20:00:00+00:00"
<ide> self.default_time_2 = '2020-06-11T07:00:00+00:00'
<ide>
<ide> def tearDown(self) -> None:
<del> with create_session() as session:
<del> session.query(Log).delete()
<add> clear_db_logs()
<ide>
<ide> def _create_task_instance(self):
<ide> dag = DAG('TEST_DAG_ID', start_date=timezone.parse(self.default_time),
<ide><path>tests/api_connexion/endpoints/test_xcom_endpoint.py
<ide>
<ide> from airflow.models import DagRun as DR, XCom
<ide> from airflow.utils.dates import parse_execution_date
<del>from airflow.utils.session import create_session, provide_session
<add>from airflow.utils.session import provide_session
<ide> from airflow.utils.types import DagRunType
<ide> from airflow.www import app
<add>from tests.test_utils.db import clear_db_runs, clear_db_xcom
<ide>
<ide>
<ide> class TestXComEndpoint(unittest.TestCase):
<ide> def setUpClass(cls) -> None:
<ide> super().setUpClass()
<ide> cls.app = app.create_app(testing=True) # type:ignore
<ide>
<add> @staticmethod
<add> def clean_db():
<add> clear_db_runs()
<add> clear_db_xcom()
<add>
<ide> def setUp(self) -> None:
<ide> """
<ide> Setup For XCom endpoint TC
<ide> """
<ide> self.client = self.app.test_client() # type:ignore
<ide> # clear existing xcoms
<del> with create_session() as session:
<del> session.query(XCom).delete()
<del> session.query(DR).delete()
<add> self.clean_db()
<ide>
<ide> def tearDown(self) -> None:
<ide> """
<ide> Clear Hanging XComs
<ide> """
<del> with create_session() as session:
<del> session.query(XCom).delete()
<del> session.query(DR).delete()
<add> self.clean_db()
<ide>
<ide>
<ide> class TestDeleteXComEntry(TestXComEndpoint):
<ide><path>tests/jobs/test_backfill_job.py
<ide> def _times_called_with(self, method, class_):
<ide> def setUpClass(cls):
<ide> cls.dagbag = DagBag(include_examples=True)
<ide>
<del> def setUp(self):
<add> @staticmethod
<add> def clean_db():
<ide> clear_db_runs()
<ide> clear_db_pools()
<ide>
<add> def setUp(self):
<add> self.clean_db()
<ide> self.parser = cli_parser.get_parser()
<ide>
<add> def tearDown(self) -> None:
<add> self.clean_db()
<add>
<ide> def test_unfinished_dag_runs_set_to_failed(self):
<ide> dag = self._get_dummy_dag('dummy_dag')
<ide>
<ide><path>tests/jobs/test_local_task_job.py
<ide> from airflow.utils.state import State
<ide> from airflow.utils.timeout import timeout
<ide> from tests.test_utils.asserts import assert_queries_count
<del>from tests.test_utils.db import clear_db_runs
<add>from tests.test_utils.db import clear_db_jobs, clear_db_runs
<ide> from tests.test_utils.mock_executor import MockExecutor
<ide>
<ide> DEFAULT_DATE = timezone.datetime(2016, 1, 1)
<ide>
<ide> class TestLocalTaskJob(unittest.TestCase):
<ide> def setUp(self):
<add> clear_db_jobs()
<ide> clear_db_runs()
<ide> patcher = patch('airflow.jobs.base_job.sleep')
<ide> self.addCleanup(patcher.stop)
<ide> self.mock_base_job_sleep = patcher.start()
<ide>
<add> def tearDown(self) -> None:
<add> clear_db_jobs()
<add> clear_db_runs()
<add>
<ide> def test_localtaskjob_essential_attr(self):
<ide> """
<ide> Check whether essential attributes
<ide> def success_callback(context):
<ide> @pytest.fixture()
<ide> def clean_db_helper():
<ide> yield
<add> clear_db_jobs()
<ide> clear_db_runs()
<ide>
<ide>
<ide><path>tests/jobs/test_scheduler_job.py
<ide> from tests.test_utils.asserts import assert_queries_count
<ide> from tests.test_utils.config import conf_vars, env_vars
<ide> from tests.test_utils.db import (
<del> clear_db_dags, clear_db_errors, clear_db_pools, clear_db_runs, clear_db_sla_miss, set_default_pool_slots,
<add> clear_db_dags, clear_db_errors, clear_db_jobs, clear_db_pools, clear_db_runs, clear_db_sla_miss,
<add> set_default_pool_slots,
<ide> )
<ide> from tests.test_utils.mock_executor import MockExecutor
<ide>
<ide> def disable_load_example():
<ide>
<ide> @pytest.mark.usefixtures("disable_load_example")
<ide> class TestDagFileProcessor(unittest.TestCase):
<del> def setUp(self):
<add>
<add> @staticmethod
<add> def clean_db():
<ide> clear_db_runs()
<ide> clear_db_pools()
<ide> clear_db_dags()
<ide> clear_db_sla_miss()
<ide> clear_db_errors()
<add> clear_db_jobs()
<add>
<add> def setUp(self):
<add> self.clean_db()
<ide>
<ide> # Speed up some tests by not running the tasks, just look at what we
<ide> # enqueue!
<ide> self.null_exec = MockExecutor()
<ide>
<ide> def tearDown(self) -> None:
<del> clear_db_runs()
<del> clear_db_pools()
<del> clear_db_dags()
<del> clear_db_sla_miss()
<del> clear_db_errors()
<add> self.clean_db()
<ide>
<ide> def create_test_dag(self, start_date=DEFAULT_DATE, end_date=DEFAULT_DATE + timedelta(hours=1), **kwargs):
<ide> dag = DAG(
<ide><path>tests/models/test_cleartasks.py
<ide> from airflow.utils.session import create_session
<ide> from airflow.utils.state import State
<ide> from tests.models import DEFAULT_DATE
<add>from tests.test_utils import db
<ide>
<ide>
<ide> class TestClearTasks(unittest.TestCase):
<ide>
<add> def setUp(self) -> None:
<add> db.clear_db_runs()
<add>
<ide> def tearDown(self):
<del> with create_session() as session:
<del> session.query(TI).delete()
<add> db.clear_db_runs()
<ide>
<ide> def test_clear_task_instances(self):
<ide> dag = DAG('test_clear_task_instances', start_date=DEFAULT_DATE,
<ide><path>tests/models/test_dagbag.py
<ide> from airflow.utils.session import create_session
<ide> from tests.models import TEST_DAGS_FOLDER
<ide> from tests.test_utils.config import conf_vars
<add>from tests.test_utils.db import clear_db_dags
<ide>
<ide>
<ide> class TestDagBag(unittest.TestCase):
<ide> def setUpClass(cls):
<ide> def tearDownClass(cls):
<ide> shutil.rmtree(cls.empty_dir)
<ide>
<add> def setUp(self) -> None:
<add> clear_db_dags()
<add>
<add> def tearDown(self) -> None:
<add> clear_db_dags()
<add>
<ide> def test_get_existing_dag(self):
<ide> """
<ide> Test that we're able to parse some example DAGs and retrieve them
<ide><path>tests/models/test_taskinstance.py
<ide> from airflow import models, settings
<ide> from airflow.exceptions import AirflowException, AirflowFailException, AirflowSkipException
<ide> from airflow.models import (
<del> DAG, DagRun, Pool, RenderedTaskInstanceFields, TaskFail, TaskInstance as TI, TaskReschedule, Variable,
<add> DAG, DagRun, Pool, RenderedTaskInstanceFields, TaskInstance as TI, TaskReschedule, Variable,
<ide> )
<ide> from airflow.operators.bash import BashOperator
<ide> from airflow.operators.dummy_operator import DummyOperator
<ide> from tests.test_utils import db
<ide> from tests.test_utils.asserts import assert_queries_count
<ide> from tests.test_utils.config import conf_vars
<del>from tests.test_utils.db import (
<del> clear_db_dags, clear_db_errors, clear_db_pools, clear_db_runs, clear_db_sla_miss,
<del>)
<ide>
<ide>
<ide> class CallbackWrapper:
<ide> def success_handler(self, context): # pylint: disable=unused-argument
<ide>
<ide> class TestTaskInstance(unittest.TestCase):
<ide>
<del> def setUp(self):
<add> @staticmethod
<add> def clean_db():
<ide> db.clear_db_pools()
<add> db.clear_db_runs()
<add> db.clear_db_task_fail()
<ide> db.clear_rendered_ti_fields()
<add> db.clear_db_task_reschedule()
<add>
<add> def setUp(self):
<add> self.clean_db()
<ide> with create_session() as session:
<ide> test_pool = Pool(pool='test_pool', slots=1)
<ide> session.add(test_pool)
<ide> session.commit()
<ide>
<ide> def tearDown(self):
<del> db.clear_db_pools()
<del> db.clear_rendered_ti_fields()
<del> with create_session() as session:
<del> session.query(TaskFail).delete()
<del> session.query(TaskReschedule).delete()
<del> session.query(models.TaskInstance).delete()
<del> session.query(models.DagRun).delete()
<add> self.clean_db()
<ide>
<ide> def test_set_task_dates(self):
<ide> """
<ide> class TestRunRawTaskQueriesCount(unittest.TestCase):
<ide>
<ide> @staticmethod
<ide> def _clean():
<del> clear_db_runs()
<del> clear_db_pools()
<del> clear_db_dags()
<del> clear_db_sla_miss()
<del> clear_db_errors()
<add> db.clear_db_runs()
<add> db.clear_db_pools()
<add> db.clear_db_dags()
<add> db.clear_db_sla_miss()
<add> db.clear_db_errors()
<ide>
<ide> def setUp(self) -> None:
<ide> self._clean()
<ide><path>tests/models/test_variable.py
<ide>
<ide> from airflow import settings
<ide> from airflow.models import Variable, crypto
<add>from tests.test_utils import db
<ide> from tests.test_utils.config import conf_vars
<ide>
<ide>
<ide> class TestVariable(unittest.TestCase):
<ide> def setUp(self):
<ide> crypto._fernet = None
<add> db.clear_db_variables()
<ide>
<ide> def tearDown(self):
<ide> crypto._fernet = None
<add> db.clear_db_variables()
<ide>
<ide> @conf_vars({('core', 'fernet_key'): ''})
<ide> def test_variable_no_encryption(self):
<ide><path>tests/models/test_xcom.py
<ide> from airflow.configuration import conf
<ide> from airflow.models.xcom import BaseXCom, XCom, resolve_xcom_backend
<ide> from airflow.utils import timezone
<add>from tests.test_utils import db
<ide> from tests.test_utils.config import conf_vars
<ide>
<ide>
<ide> def serialize_value(_):
<ide>
<ide>
<ide> class TestXCom(unittest.TestCase):
<add>
<add> def setUp(self) -> None:
<add> db.clear_db_xcom()
<add>
<add> def tearDown(self) -> None:
<add> db.clear_db_xcom()
<add>
<ide> @conf_vars({("core", "xcom_backend"): "tests.models.test_xcom.CustomXCom"})
<ide> def test_resolve_xcom_class(self):
<ide> cls = resolve_xcom_backend()
<ide><path>tests/sensors/test_base_sensor.py
<ide> from freezegun import freeze_time
<ide>
<ide> from airflow.exceptions import AirflowException, AirflowRescheduleException, AirflowSensorTimeout
<del>from airflow.models import DagBag, DagRun, TaskInstance, TaskReschedule
<del>from airflow.models.dag import DAG, settings
<add>from airflow.models import DagBag, TaskInstance, TaskReschedule
<add>from airflow.models.dag import DAG
<ide> from airflow.operators.dummy_operator import DummyOperator
<ide> from airflow.sensors.base_sensor_operator import BaseSensorOperator, poke_mode_only
<ide> from airflow.ti_deps.deps.ready_to_reschedule import ReadyToRescheduleDep
<ide> from airflow.utils import timezone
<ide> from airflow.utils.state import State
<ide> from airflow.utils.timezone import datetime
<ide> from airflow.utils.types import DagRunType
<add>from tests.test_utils import db
<ide>
<ide> DEFAULT_DATE = datetime(2015, 1, 1)
<ide> TEST_DAG_ID = 'unit_test_dag'
<ide> def poke(self, context):
<ide>
<ide>
<ide> class TestBaseSensor(unittest.TestCase):
<add> @staticmethod
<add> def clean_db():
<add> db.clear_db_runs()
<add> db.clear_db_task_reschedule()
<add> db.clear_db_xcom()
<add>
<ide> def setUp(self):
<ide> args = {
<ide> 'owner': 'airflow',
<ide> 'start_date': DEFAULT_DATE
<ide> }
<ide> self.dag = DAG(TEST_DAG_ID, default_args=args)
<add> self.clean_db()
<ide>
<del> session = settings.Session()
<del> session.query(TaskReschedule).delete()
<del> session.query(DagRun).delete()
<del> session.query(TaskInstance).delete()
<del> session.commit()
<add> def tearDown(self) -> None:
<add> self.clean_db()
<ide>
<ide> def _make_dag_run(self):
<ide> return self.dag.create_dagrun(
<ide><path>tests/sensors/test_weekday_sensor.py
<ide> from parameterized import parameterized
<ide>
<ide> from airflow.exceptions import AirflowSensorTimeout
<del>from airflow.models import DagBag, TaskFail, TaskInstance
<add>from airflow.models import DagBag
<ide> from airflow.models.dag import DAG
<ide> from airflow.sensors.weekday_sensor import DayOfWeekSensor
<del>from airflow.settings import Session
<ide> from airflow.utils.timezone import datetime
<ide> from airflow.utils.weekday import WeekDay
<add>from tests.test_utils import db
<ide>
<ide> DEFAULT_DATE = datetime(2018, 12, 10)
<ide> WEEKDAY_DATE = datetime(2018, 12, 20)
<ide>
<ide> class TestDayOfWeekSensor(unittest.TestCase):
<ide>
<add> @staticmethod
<add> def clean_db():
<add> db.clear_db_runs()
<add> db.clear_db_task_fail()
<add>
<ide> def setUp(self):
<add> self.clean_db()
<ide> self.dagbag = DagBag(
<ide> dag_folder=DEV_NULL,
<ide> include_examples=True
<ide> def setUp(self):
<ide> self.dag = dag
<ide>
<ide> def tearDown(self):
<del> session = Session()
<del> session.query(TaskInstance).filter_by(
<del> dag_id=TEST_DAG_ID).delete()
<del> session.query(TaskFail).filter_by(
<del> dag_id=TEST_DAG_ID).delete()
<del> session.commit()
<del> session.close()
<add> self.clean_db()
<ide>
<ide> @parameterized.expand([
<ide> ("with-string", 'Thursday'),
<ide><path>tests/test_utils/db.py
<ide> # KIND, either express or implied. See the License for the
<ide> # specific language governing permissions and limitations
<ide> # under the License.
<add>from airflow.jobs.base_job import BaseJob
<ide> from airflow.models import (
<del> Connection, DagModel, DagRun, DagTag, Pool, RenderedTaskInstanceFields, SlaMiss, TaskInstance, Variable,
<del> XCom, errors,
<add> Connection, DagModel, DagRun, DagTag, Log, Pool, RenderedTaskInstanceFields, SlaMiss, TaskFail,
<add> TaskInstance, TaskReschedule, Variable, XCom, errors,
<ide> )
<ide> from airflow.models.dagcode import DagCode
<ide> from airflow.models.serialized_dag import SerializedDagModel
<ide> def clear_db_import_errors():
<ide> def clear_db_xcom():
<ide> with create_session() as session:
<ide> session.query(XCom).delete()
<add>
<add>
<add>def clear_db_logs():
<add> with create_session() as session:
<add> session.query(Log).delete()
<add>
<add>
<add>def clear_db_jobs():
<add> with create_session() as session:
<add> session.query(BaseJob).delete()
<add>
<add>
<add>def clear_db_task_fail():
<add> with create_session() as session:
<add> session.query(TaskFail).delete()
<add>
<add>
<add>def clear_db_task_reschedule():
<add> with create_session() as session:
<add> session.query(TaskReschedule).delete() | 14 |
Python | Python | fix behaviour when pool does not exist | 7ce64e925b25c5b8ef42a38763c91951a53f4cf3 | <ide><path>libcloud/loadbalancer/drivers/dimensiondata.py
<ide> def _to_balancer(self, element):
<ide> port = findtext(element, 'port', TYPES_URN)
<ide> extra = {}
<ide>
<del> extra['pool_id'] = element.find(fixxpath(
<add> pool_element = element.find(fixxpath(
<ide> 'pool',
<del> TYPES_URN)).get('id')
<add> TYPES_URN))
<add> if pool_element is None:
<add> extra['pool_id'] = None
<add>
<add> else:
<add> extra['pool_id'] = pool_element.get('id')
<add>
<ide> extra['network_domain_id'] = findtext(element, 'networkDomainId',
<ide> TYPES_URN)
<ide> | 1 |
Ruby | Ruby | use .find here as it is simpler and faster | 69f97f469747777ed1c457715f5361f6b8a0ab7b | <ide><path>actionpack/lib/action_dispatch/routing/mapper.rb
<ide> def name_for_action(as, action)
<ide> end
<ide>
<ide> candidate = name.select(&:present?).join("_").presence
<del> candidate unless as.nil? && @set.routes.map(&:name).include?(candidate)
<add> candidate unless as.nil? && @set.routes.find { |r| r.name == candidate }
<ide> end
<ide> end
<ide> | 1 |
Text | Text | clarify getauthtag with authtaglength | dd601619d38d76efbc7f014a9d4b8afd0d4e8045 | <ide><path>doc/api/crypto.md
<ide> added: v1.0.0
<ide> The `cipher.getAuthTag()` method should only be called after encryption has
<ide> been completed using the [`cipher.final()`][] method.
<ide>
<add>If the `authTagLength` option was set during the `cipher` instance's creation,
<add>this function will return exactly `authTagLength` bytes.
<add>
<ide> ### `cipher.setAAD(buffer[, options])`
<ide>
<ide> <!-- YAML | 1 |
PHP | PHP | add support for testing eloquent model events | 0ca99db6739195971a76df6efd7dc5621698ed4e | <ide><path>src/Illuminate/Foundation/Testing/Concerns/MocksApplicationServices.php
<ide>
<ide> use Mockery;
<ide> use Exception;
<add>use Illuminate\Database\Eloquent\Model;
<ide> use Illuminate\Contracts\Notifications\Dispatcher as NotificationDispatcher;
<ide>
<ide> trait MocksApplicationServices
<ide> trait MocksApplicationServices
<ide> */
<ide> protected $firedEvents = [];
<ide>
<add> /**
<add> * All of the fired model events.
<add> *
<add> * @var array
<add> */
<add> protected $firedModelEvents = [];
<add>
<ide> /**
<ide> * All of the dispatched jobs.
<ide> *
<ide> protected function withoutEvents()
<ide> return $this;
<ide> }
<ide>
<add> /**
<add> * Mock the model event dispatcher so all events are silenced and collected.
<add> *
<add> * @return $this
<add> */
<add> protected function withoutModelEvents()
<add> {
<add> $mock = Mockery::mock('Illuminate\Contracts\Events\Dispatcher');
<add>
<add> $mock->shouldReceive('fire')->andReturnUsing(function ($called) {
<add> $this->firedModelEvents[] = $called;
<add> });
<add>
<add> $mock->shouldReceive('until')->andReturnUsing(function ($called) {
<add> $this->firedModelEvents[] = $called;
<add>
<add> return true;
<add> });
<add>
<add> $mock->shouldReceive('listen')->andReturnUsing(function ($event, $listener, $priority) {
<add> //
<add> });
<add>
<add> Model::setEventDispatcher($mock);
<add>
<add> return $this;
<add> }
<add>
<add> /**
<add> * Specify a list of events that should be fired for the given operation.
<add> *
<add> * These events will be mocked, so that handlers will not actually be executed.
<add> *
<add> * @param array|string $events
<add> * @return $this
<add> *
<add> * @throws \Exception
<add> */
<add> public function expectsModelEvents($events)
<add> {
<add> $events = is_array($events) ? $events : func_get_args();
<add>
<add> $this->withoutModelEvents();
<add>
<add> $this->beforeApplicationDestroyed(function () use ($events) {
<add> $fired = $this->getFiredModelEvents($events);
<add>
<add> if ($eventsNotFired = array_diff($events, $fired)) {
<add> throw new Exception(
<add> 'These expected events were not fired: ['.implode(', ', $eventsNotFired).']'
<add> );
<add> }
<add> });
<add>
<add> return $this;
<add> }
<add>
<add> /**
<add> * Specify a list of events that should not be fired for the given operation.
<add> *
<add> * These events will be mocked, so that handlers will not actually be executed.
<add> *
<add> * @param array|string $events
<add> * @return $this
<add> */
<add> public function doesntExpectModelEvents($events)
<add> {
<add> $events = is_array($events) ? $events : func_get_args();
<add>
<add> $this->withoutModelEvents();
<add>
<add> $this->beforeApplicationDestroyed(function () use ($events) {
<add> if ($fired = $this->getFiredModelEvents($events)) {
<add> throw new Exception(
<add> 'These unexpected events were fired: ['.implode(', ', $fired).']'
<add> );
<add> }
<add> });
<add>
<add> return $this;
<add> }
<add>
<ide> /**
<ide> * Specify a list of observers that will not run for the given operation.
<ide> *
<ide> protected function getFiredEvents(array $events)
<ide> return $this->getDispatched($events, $this->firedEvents);
<ide> }
<ide>
<add> /**
<add> * Filter the given events against the fired events.
<add> *
<add> * @param array $events
<add> * @return array
<add> */
<add> protected function getFiredModelEvents(array $events)
<add> {
<add> return $this->getDispatched($events, $this->firedModelEvents);
<add> }
<add>
<ide> /**
<ide> * Specify a list of jobs that should be dispatched for the given operation.
<ide> *
<ide><path>src/Illuminate/Foundation/Testing/TestCase.php
<ide>
<ide> use Mockery;
<ide> use PHPUnit_Framework_TestCase;
<add>use Illuminate\Database\Eloquent\Model;
<ide>
<ide> abstract class TestCase extends PHPUnit_Framework_TestCase
<ide> {
<ide> protected function refreshApplication()
<ide> putenv('APP_ENV=testing');
<ide>
<ide> $this->app = $this->createApplication();
<add> Model::setEventDispatcher($this->app['events']);
<ide> }
<ide>
<ide> /**
<ide><path>tests/Foundation/FoundationExpectsModelEventsTest.php
<add><?php
<add>
<add>use Illuminate\Events\Dispatcher;
<add>use Mockery\MockInterface as Mock;
<add>use Illuminate\Foundation\Application;
<add>use Illuminate\Database\Eloquent\Model;
<add>use Illuminate\Foundation\Testing\TestCase;
<add>use Illuminate\Database\Capsule\Manager as DB;
<add>use Illuminate\Database\Eloquent\Model as Eloquent;
<add>
<add>class FoundationExpectsModelEventsTest extends TestCase
<add>{
<add> public function createApplication()
<add> {
<add> $app = new Application;
<add>
<add> $db = new DB;
<add>
<add> $db->addConnection([
<add> 'driver' => 'sqlite',
<add> 'database' => ':memory:',
<add> ]);
<add>
<add> $db->bootEloquent();
<add> $db->setAsGlobal();
<add>
<add> $this->createSchema();
<add>
<add> return $app;
<add> }
<add>
<add> /** @test */
<add> public function a_mock_replaces_the_event_dispatcher_when_calling_expects_model_events()
<add> {
<add> $this->assertInstanceOf(Dispatcher::class, Model::getEventDispatcher());
<add>
<add> $this->assertNotInstanceOf(Mock::class, Model::getEventDispatcher());
<add>
<add> $this->expectsModelEvents([]);
<add>
<add> $this->assertNotInstanceOf(Dispatcher::class, Model::getEventDispatcher());
<add> $this->assertInstanceOf(Mock::class, Model::getEventDispatcher());
<add> }
<add>
<add> /** @test */
<add> public function a_mock_does_not_carry_over_between_tests()
<add> {
<add> $this->assertInstanceOf(Dispatcher::class, Model::getEventDispatcher());
<add>
<add> $this->assertNotInstanceOf(Mock::class, Model::getEventDispatcher());
<add> }
<add>
<add> /** @test */
<add> public function fired_events_can_be_checked_for()
<add> {
<add> $this->expectsModelEvents([
<add> 'eloquent.booting: EloquentTestModel',
<add> 'eloquent.booted: EloquentTestModel',
<add>
<add> 'eloquent.creating: EloquentTestModel',
<add> 'eloquent.created: EloquentTestModel',
<add>
<add> 'eloquent.saving: EloquentTestModel',
<add> 'eloquent.saved: EloquentTestModel',
<add>
<add> 'eloquent.updating: EloquentTestModel',
<add> 'eloquent.updated: EloquentTestModel',
<add>
<add> 'eloquent.deleting: EloquentTestModel',
<add> 'eloquent.deleted: EloquentTestModel',
<add> ]);
<add>
<add> $model = EloquentTestModel::create(['field' => 1]);
<add> $model->field = 2;
<add> $model->save();
<add> $model->delete();
<add> }
<add>
<add> /** @test */
<add> public function observers_do_not_fire_when_mocking_events()
<add> {
<add> $this->expectsModelEvents([
<add> 'eloquent.saving: EloquentTestModel',
<add> 'eloquent.saved: EloquentTestModel',
<add> ]);
<add>
<add> EloquentTestModel::observe(new EloquentTestModelFailingObserver);
<add>
<add> EloquentTestModel::create(['field' => 1]);
<add> }
<add>
<add> protected function createSchema()
<add> {
<add> $this->schema('default')->create('test', function ($table) {
<add> $table->increments('id');
<add> $table->string('field');
<add> $table->timestamps();
<add> });
<add> }
<add>
<add> /**
<add> * Get a database connection instance.
<add> *
<add> * @return Connection
<add> */
<add> protected function connection($connection = 'default')
<add> {
<add> return Eloquent::getConnectionResolver()->connection($connection);
<add> }
<add>
<add> /**
<add> * Get a schema builder instance.
<add> *
<add> * @return Schema\Builder
<add> */
<add> protected function schema($connection = 'default')
<add> {
<add> return $this->connection($connection)->getSchemaBuilder();
<add> }
<add>}
<add>
<add>class EloquentTestModel extends Eloquent
<add>{
<add> protected $guarded = [];
<add> protected $table = 'test';
<add>}
<add>
<add>class EloquentTestModelFailingObserver
<add>{
<add> public function saving()
<add> {
<add> PHPUnit_Framework_Assert::fail('The [saving] method should not be called on '.static::class);
<add> }
<add>
<add> public function saved()
<add> {
<add> PHPUnit_Framework_Assert::fail('The [saved] method should not be called on '.static::class);
<add> }
<add>} | 3 |
Java | Java | fix classcastexception in formhttpmessageconverter | b94e8c4bef90c78231063ad2c6f5bec8fc11b899 | <ide><path>spring-web/src/main/java/org/springframework/http/converter/FormHttpMessageConverter.java
<ide> public void write(MultiValueMap<String, ?> map, @Nullable MediaType contentType,
<ide> throws IOException, HttpMessageNotWritableException {
<ide>
<ide> if (!isMultipart(map, contentType)) {
<del> writeForm((MultiValueMap<String, String>) map, contentType, outputMessage);
<add> writeForm((MultiValueMap<String, Object>) map, contentType, outputMessage);
<ide> }
<ide> else {
<ide> writeMultipart((MultiValueMap<String, Object>) map, outputMessage);
<ide> private boolean isMultipart(MultiValueMap<String, ?> map, @Nullable MediaType co
<ide> return false;
<ide> }
<ide>
<del> private void writeForm(MultiValueMap<String, String> formData, @Nullable MediaType contentType,
<add> private void writeForm(MultiValueMap<String, Object> formData, @Nullable MediaType contentType,
<ide> HttpOutputMessage outputMessage) throws IOException {
<ide>
<ide> contentType = getMediaType(contentType);
<ide> else if (mediaType.getCharset() == null) {
<ide> }
<ide> }
<ide>
<del> protected String serializeForm(MultiValueMap<String, String> formData, Charset charset) {
<add> protected String serializeForm(MultiValueMap<String, Object> formData, Charset charset) {
<ide> StringBuilder builder = new StringBuilder();
<ide> formData.forEach((name, values) ->
<ide> values.forEach(value -> {
<ide> protected String serializeForm(MultiValueMap<String, String> formData, Charset c
<ide> builder.append(URLEncoder.encode(name, charset.name()));
<ide> if (value != null) {
<ide> builder.append('=');
<del> builder.append(URLEncoder.encode(value, charset.name()));
<add> builder.append(URLEncoder.encode(String.valueOf(value), charset.name()));
<ide> }
<ide> }
<ide> catch (UnsupportedEncodingException ex) { | 1 |
Ruby | Ruby | optimize uri escaping | a61792574d9c8904590895f7a2f56803e02a6c52 | <ide><path>actionpack/lib/action_dispatch/journey/router/utils.rb
<del>require 'uri'
<del>
<ide> module ActionDispatch
<ide> module Journey # :nodoc:
<ide> class Router # :nodoc:
<ide> def self.normalize_path(path)
<ide>
<ide> # URI path and fragment escaping
<ide> # http://tools.ietf.org/html/rfc3986
<del> module UriEscape # :nodoc:
<del> # Symbol captures can generate multiple path segments, so include /.
<del> reserved_segment = '/'
<del> reserved_fragment = '/?'
<del> reserved_pchar = ':@&=+$,;'
<del>
<del> safe_pchar = "#{URI::REGEXP::PATTERN::UNRESERVED}#{reserved_pchar}"
<del> safe_segment = "#{safe_pchar}#{reserved_segment}"
<del> safe_fragment = "#{safe_pchar}#{reserved_fragment}"
<del> UNSAFE_SEGMENT = Regexp.new("[^#{safe_segment}]", false).freeze
<del> UNSAFE_FRAGMENT = Regexp.new("[^#{safe_fragment}]", false).freeze
<add> class UriEncoder # :nodoc:
<add> ENCODE = "%%%02X".freeze
<add> ENCODING = Encoding::US_ASCII
<add> EMPTY = "".force_encoding(ENCODING).freeze
<add> DEC2HEX = (0..255).to_a.map{ |i| ENCODE % i }.map{ |s| s.force_encoding(ENCODING) }
<add>
<add> ALPHA = "a-zA-Z".freeze
<add> DIGIT = "0-9".freeze
<add> UNRESERVED = "#{ALPHA}#{DIGIT}\\-\\._~".freeze
<add> SUB_DELIMS = "!\\$&'\\(\\)\\*\\+,;=".freeze
<add>
<add> ESCAPED = /%[a-zA-Z0-9]{2}/.freeze
<add>
<add> FRAGMENT = /[^#{UNRESERVED}#{SUB_DELIMS}:@\/\?]/.freeze
<add> PATH = /[^#{UNRESERVED}#{SUB_DELIMS}:@\/]/.freeze
<add>
<add> def escape_fragment(fragment)
<add> escape(fragment, FRAGMENT)
<add> end
<add>
<add> def escape_path(path)
<add> escape(path, PATH)
<add> end
<add>
<add> def unescape_uri(uri)
<add> uri.gsub(ESCAPED) { [$&[1, 2].hex].pack('C') }.force_encoding(uri.encoding)
<add> end
<add>
<add> protected
<add> def escape(component, pattern)
<add> component.gsub(pattern){ |unsafe| percent_encode(unsafe) }.force_encoding(ENCODING)
<add> end
<add>
<add> def percent_encode(unsafe)
<add> safe = EMPTY.dup
<add> unsafe.each_byte { |b| safe << DEC2HEX[b] }
<add> safe
<add> end
<ide> end
<ide>
<del> Parser = URI::Parser.new
<add> ENCODER = UriEncoder.new
<ide>
<ide> def self.escape_path(path)
<del> Parser.escape(path.to_s, UriEscape::UNSAFE_SEGMENT)
<add> ENCODER.escape_path(path.to_s)
<ide> end
<ide>
<ide> def self.escape_fragment(fragment)
<del> Parser.escape(fragment.to_s, UriEscape::UNSAFE_FRAGMENT)
<add> ENCODER.escape_fragment(fragment.to_s)
<ide> end
<ide>
<ide> def self.unescape_uri(uri)
<del> Parser.unescape(uri)
<add> ENCODER.unescape_uri(uri)
<ide> end
<ide> end
<ide> end | 1 |
Text | Text | fix the locale id | a869a0f7b07aa44ea51a58da115522716e82d8c0 | <add><path>docs/docs/getting-started.ja-JP.md
<del><path>docs/docs/getting-started.jp.md
<ide> ---
<del>id: getting-started-ja
<add>id: getting-started-ja-JP
<ide> title: 始めてみましょう
<del>next: tutorial-ja.html
<del>redirect_from: "docs/index-ja.html"
<add>next: tutorial-ja-JP.html
<add>redirect_from: "docs/index-ja-JP.html"
<ide> ---
<ide>
<ide> ## JSFiddle
<add><path>docs/docs/tutorial.ja-JP.md
<del><path>docs/docs/tutorial.jp.md
<ide> ---
<del>id: tutorial
<add>id: tutorial-ja-JP
<ide> title: チュートリアル
<del>prev: getting-started-ja.html
<del>next: thinking-in-react-ja.html
<add>prev: getting-started-ja-JP.html
<add>next: thinking-in-react-ja-JP.html
<ide> ---
<ide>
<ide> これから、シンプルながらも現実的なコメントボックスを作ってみましょう。ブログにも設置できるようなもので、Disqus や LiveFyre、Facebook comments が採用しているリアルタイムコメントの基本機能を備えたものを想定しています。 | 2 |
Ruby | Ruby | enable zeitwerk by default on truffleruby | a011422bc20d62960f3a677b1c77a052d9bf71d3 | <ide><path>railties/lib/rails/application/configuration.rb
<ide> def load_defaults(target_version)
<ide> when "6.0"
<ide> load_defaults "5.2"
<ide>
<del> self.autoloader = :zeitwerk if RUBY_ENGINE == "ruby"
<add> self.autoloader = :zeitwerk if %w[ruby truffleruby].include?(RUBY_ENGINE)
<ide>
<ide> if respond_to?(:action_view)
<ide> action_view.default_enforce_utf8 = false | 1 |
Ruby | Ruby | add a test case for comparing rails versions | ec92d8440fa51aea40de1567eed7974422bff000 | <ide><path>railties/test/rails_info_test.rb
<ide> def test_property_with_block
<ide> assert_property 'Goodbye', 'World'
<ide> end
<ide>
<add> def test_rails_version
<add> assert_property 'Rails version',
<add> File.read(File.realpath('../../../RAILS_VERSION', __FILE__)).chomp
<add> end
<add>
<ide> def test_framework_version
<ide> assert_property 'Active Support version', ActiveSupport.version.to_s
<ide> end | 1 |
Ruby | Ruby | add nodoc to arel filter classes | e27c419d448ce7eed78aa8e42f22af3522a76a1f | <ide><path>activerecord/lib/arel/filter_predications.rb
<ide> # frozen_string_literal: true
<ide>
<del>module Arel
<add>module Arel # :nodoc: all
<ide> module FilterPredications
<ide> def filter(expr)
<ide> Nodes::Filter.new(self, expr)
<ide><path>activerecord/lib/arel/nodes/filter.rb
<ide> # frozen_string_literal: true
<ide>
<del>module Arel
<add>module Arel # :nodoc: all
<ide> module Nodes
<ide> class Filter < Binary
<ide> include Arel::WindowPredications | 2 |
PHP | PHP | remove deprecated code in shell package | 89965ad221f9aa08b1312d40c7c68a27eed73839 | <ide><path>src/Shell/CommandListShell.php
<del><?php
<del>/**
<del> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<del> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<del> *
<del> * Licensed under The MIT License
<del> * For full copyright and license information, please see the LICENSE.txt
<del> * Redistributions of files must retain the above copyright notice.
<del> *
<del> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<del> * @link https://cakephp.org CakePHP Project
<del> * @since 2.0.0
<del> * @license https://opensource.org/licenses/mit-license.php MIT License
<del> */
<del>namespace Cake\Shell;
<del>
<del>use Cake\Console\ConsoleOutput;
<del>use Cake\Console\Shell;
<del>use Cake\Core\Configure;
<del>use Cake\Core\Plugin;
<del>use Cake\Utility\Inflector;
<del>use SimpleXMLElement;
<del>
<del>/**
<del> * Shows a list of commands available from the console.
<del> *
<del> * @property \Cake\Shell\Task\CommandTask $Command
<del> * @deprecated 3.5.0 Replaced by Cake\Shell\HelpShell
<del> */
<del>class CommandListShell extends Shell
<del>{
<del>
<del> /**
<del> * Contains tasks to load and instantiate
<del> *
<del> * @var array
<del> */
<del> public $tasks = ['Command'];
<del>
<del> /**
<del> * Displays a header for the shell
<del> *
<del> * @return void
<del> */
<del> protected function _welcome()
<del> {
<del> $this->out();
<del> $this->out(sprintf('<info>Welcome to CakePHP %s Console</info>', 'v' . Configure::version()));
<del> $this->hr();
<del> $this->out(sprintf('App : %s', APP_DIR));
<del> $this->out(sprintf('Path: %s', APP));
<del> $this->out(sprintf('PHP : %s', PHP_VERSION));
<del> $this->hr();
<del> }
<del>
<del> /**
<del> * startup
<del> *
<del> * @return void
<del> */
<del> public function startup()
<del> {
<del> if (!$this->param('xml') && !$this->param('version')) {
<del> parent::startup();
<del> }
<del> }
<del>
<del> /**
<del> * Main function Prints out the list of shells.
<del> *
<del> * @return void
<del> */
<del> public function main()
<del> {
<del> if (!$this->param('xml') && !$this->param('version')) {
<del> $this->out('<info>Current Paths:</info>', 2);
<del> $this->out('* app: ' . APP_DIR);
<del> $this->out('* root: ' . rtrim(ROOT, DIRECTORY_SEPARATOR));
<del> $this->out('* core: ' . rtrim(CORE_PATH, DIRECTORY_SEPARATOR));
<del> $this->out('');
<del>
<del> $this->out('<info>Available Shells:</info>', 2);
<del> }
<del>
<del> if ($this->param('version')) {
<del> $this->out(Configure::version());
<del>
<del> return;
<del> }
<del>
<del> $shellList = $this->Command->getShellList();
<del> if (!$shellList) {
<del> return;
<del> }
<del>
<del> if (!$this->param('xml')) {
<del> $this->_asText($shellList);
<del> } else {
<del> $this->_asXml($shellList);
<del> }
<del> }
<del>
<del> /**
<del> * Output text.
<del> *
<del> * @param array $shellList The shell list.
<del> * @return void
<del> */
<del> protected function _asText($shellList)
<del> {
<del> foreach ($shellList as $plugin => $commands) {
<del> sort($commands);
<del> $this->out(sprintf('[<info>%s</info>] %s', $plugin, implode(', ', $commands)));
<del> $this->out();
<del> }
<del>
<del> $this->out('To run an app or core command, type <info>`cake shell_name [args]`</info>');
<del> $this->out('To run a plugin command, type <info>`cake Plugin.shell_name [args]`</info>');
<del> $this->out('To get help on a specific command, type <info>`cake shell_name --help`</info>', 2);
<del> }
<del>
<del> /**
<del> * Output as XML
<del> *
<del> * @param array $shellList The shell list.
<del> * @return void
<del> */
<del> protected function _asXml($shellList)
<del> {
<del> $plugins = Plugin::loaded();
<del> $shells = new SimpleXMLElement('<shells></shells>');
<del> foreach ($shellList as $plugin => $commands) {
<del> foreach ($commands as $command) {
<del> $callable = $command;
<del> if (in_array($plugin, $plugins)) {
<del> $callable = Inflector::camelize($plugin) . '.' . $command;
<del> }
<del>
<del> $shell = $shells->addChild('shell');
<del> $shell->addAttribute('name', $command);
<del> $shell->addAttribute('call_as', $callable);
<del> $shell->addAttribute('provider', $plugin);
<del> $shell->addAttribute('help', $callable . ' -h');
<del> }
<del> }
<del> $this->_io->setOutputAs(ConsoleOutput::RAW);
<del> $this->out($shells->saveXML());
<del> }
<del>
<del> /**
<del> * Gets the option parser instance and configures it.
<del> *
<del> * @return \Cake\Console\ConsoleOptionParser
<del> */
<del> public function getOptionParser()
<del> {
<del> $parser = parent::getOptionParser();
<del>
<del> $parser->setDescription(
<del> 'Get the list of available shells for this CakePHP application.'
<del> )->addOption('xml', [
<del> 'help' => 'Get the listing as XML.',
<del> 'boolean' => true
<del> ])->addOption('version', [
<del> 'help' => 'Prints the currently installed version of CakePHP. (deprecated - use `cake --version` instead)',
<del> 'boolean' => true
<del> ]);
<del>
<del> return $parser;
<del> }
<del>}
<ide><path>src/Shell/OrmCacheShell.php
<del><?php
<del>/**
<del> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<del> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<del> *
<del> * Licensed under The MIT License
<del> * For full copyright and license information, please see the LICENSE.txt
<del> * Redistributions of files must retain the above copyright notice.
<del> *
<del> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<del> * @link https://cakephp.org CakePHP(tm) Project
<del> * @since 3.0.0
<del> * @license https://opensource.org/licenses/mit-license.php MIT License
<del> */
<del>namespace Cake\Shell;
<del>
<del>/**
<del> * ORM Cache Shell.
<del> *
<del> * Provides a CLI interface to the ORM metadata caching features.
<del> * This tool is intended to be used by deployment scripts so that you
<del> * can prevent thundering herd effects on the metadata cache when new
<del> * versions of your application are deployed, or when migrations
<del> * requiring updated metadata are required.
<del> *
<del> * @deprecated 3.6.0 Use \Cake\Shell\SchemaCacheShell instead
<del> */
<del>class OrmCacheShell extends SchemaCacheShell
<del>{
<del>
<del>}
<ide><path>tests/TestCase/Shell/CommandListShellTest.php
<del><?php
<del>/**
<del> * CakePHP : Rapid Development Framework (https://cakephp.org)
<del> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<del> *
<del> * Licensed under The MIT License
<del> * For full copyright and license information, please see the LICENSE.txt
<del> * Redistributions of files must retain the above copyright notice.
<del> *
<del> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<del> * @link https://cakephp.org CakePHP Project
<del> * @since 2.0.0
<del> * @license https://opensource.org/licenses/mit-license.php MIT License
<del> */
<del>namespace Cake\Test\TestCase\Shell;
<del>
<del>use Cake\Console\Shell;
<del>use Cake\Core\Configure;
<del>use Cake\Core\Plugin;
<del>use Cake\TestSuite\ConsoleIntegrationTestCase;
<del>
<del>/**
<del> * CommandListShellTest
<del> */
<del>class CommandListShellTest extends ConsoleIntegrationTestCase
<del>{
<del>
<del> /**
<del> * setUp method
<del> *
<del> * @return void
<del> */
<del> public function setUp()
<del> {
<del> parent::setUp();
<del> Plugin::load(['TestPlugin', 'TestPluginTwo']);
<del> }
<del>
<del> /**
<del> * tearDown
<del> *
<del> * @return void
<del> */
<del> public function tearDown()
<del> {
<del> parent::tearDown();
<del> Plugin::unload();
<del> }
<del>
<del> /**
<del> * test that main finds core shells.
<del> *
<del> * @return void
<del> */
<del> public function testMain()
<del> {
<del> $this->exec('command_list');
<del>
<del> $expected = "/\[.*TestPlugin.*\] example/";
<del> $this->assertOutputRegExp($expected);
<del>
<del> $expected = "/\[.*TestPluginTwo.*\] example, unique, welcome/";
<del> $this->assertOutputRegExp($expected);
<del>
<del> $expected = "/\[.*CORE.*\] cache, help, i18n, orm_cache, plugin, routes, schema_cache, server/";
<del> $this->assertOutputRegExp($expected);
<del>
<del> $expected = "/\[.*app.*\] demo, i18m, integration, merge, sample/";
<del> $this->assertOutputRegExp($expected);
<del> $this->assertExitCode(Shell::CODE_SUCCESS);
<del> $this->assertErrorEmpty();
<del> }
<del>
<del> /**
<del> * If there is an app shell with the same name as a core shell,
<del> * tests that the app shell is the one displayed and the core one is hidden.
<del> *
<del> * @return void
<del> */
<del> public function testMainAppPriority()
<del> {
<del> rename(APP . 'Shell' . DS . 'I18mShell.php', APP . 'Shell' . DS . 'I18nShell.php');
<del> $this->exec('command_list');
<del> rename(APP . 'Shell' . DS . 'I18nShell.php', APP . 'Shell' . DS . 'I18mShell.php');
<del>
<del> $expected = "/\[.*CORE.*\] cache, help, orm_cache, plugin, routes, schema_cache, server, version/";
<del> $this->assertOutputRegExp($expected);
<del>
<del> $expected = "/\[.*app.*\] demo, i18n, integration, merge, sample/";
<del> $this->assertOutputRegExp($expected);
<del> $this->assertExitCode(Shell::CODE_SUCCESS);
<del> $this->assertErrorEmpty();
<del> }
<del>
<del> /**
<del> * test xml output.
<del> *
<del> * @return void
<del> */
<del> public function testMainXml()
<del> {
<del> $this->exec('command_list --xml');
<del>
<del> $find = '<shell name="sample" call_as="sample" provider="app" help="sample -h"';
<del> $this->assertOutputContains($find);
<del>
<del> $find = '<shell name="orm_cache" call_as="orm_cache" provider="CORE" help="orm_cache -h"';
<del> $this->assertOutputContains($find);
<del>
<del> $find = '<shell name="welcome" call_as="TestPluginTwo.welcome" provider="TestPluginTwo" help="TestPluginTwo.welcome -h"';
<del> $this->assertOutputContains($find);
<del> $this->assertExitCode(Shell::CODE_SUCCESS);
<del> $this->assertErrorEmpty();
<del> }
<del>
<del> /**
<del> * test that main prints the cakephp's version.
<del> *
<del> * @return void
<del> */
<del> public function testMainVersion()
<del> {
<del> $this->exec('command_list --version');
<del> $expected = Configure::version();
<del> $this->assertOutputContains($expected);
<del> $this->assertExitCode(Shell::CODE_SUCCESS);
<del> $this->assertErrorEmpty();
<del> }
<del>}
<ide><path>tests/TestCase/Shell/CompletionShellTest.php
<ide> public function testCommands()
<ide> $output = $this->out->output;
<ide>
<ide> $expected = 'TestPlugin.example TestPlugin.sample TestPluginTwo.example unique welcome ' .
<del> 'cache help i18n orm_cache plugin routes schema_cache server version ' .
<add> 'cache help i18n plugin routes schema_cache server version ' .
<ide> "demo i18m integration merge sample shell_test testing_dispatch\n";
<ide> $this->assertTextEquals($expected, $output);
<ide> }
<ide> public function testOptionsNonExistingCommand()
<ide> */
<ide> public function testOptions()
<ide> {
<del> $this->Shell->runCommand(['options', 'orm_cache']);
<add> $this->Shell->runCommand(['options', 'schema_cache']);
<ide> $output = $this->out->output;
<ide>
<ide> $expected = "--connection -c --help -h --quiet -q --verbose -v\n";
<ide> public function testOptionsTask()
<ide> */
<ide> public function testSubCommandsCorePlugin()
<ide> {
<del> $this->Shell->runCommand(['subcommands', 'CORE.orm_cache']);
<add> $this->Shell->runCommand(['subcommands', 'CORE.schema_cache']);
<ide> $output = $this->out->output;
<ide>
<ide> $expected = "build clear\n";
<ide> public function testSubCommandsNonExistingCommand()
<ide> */
<ide> public function testSubCommands()
<ide> {
<del> $this->Shell->runCommand(['subcommands', 'orm_cache']);
<add> $this->Shell->runCommand(['subcommands', 'schema_cache']);
<ide> $output = $this->out->output;
<ide>
<ide> $expected = "build clear\n"; | 4 |
Java | Java | add systrace to reactrootview | 658f632f595828673fffe683b048ded73ce3d8f1 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactRootView.java
<ide> public ReactRootView(Context context, AttributeSet attrs, int defStyle) {
<ide>
<ide> @Override
<ide> protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
<del> setMeasuredDimension(
<add> Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "ReactRootView.onMeasure");
<add> try {
<add> setMeasuredDimension(
<ide> MeasureSpec.getSize(widthMeasureSpec),
<ide> MeasureSpec.getSize(heightMeasureSpec));
<ide>
<del> mWasMeasured = true;
<del> // Check if we were waiting for onMeasure to attach the root view
<del> if (mReactInstanceManager != null && !mIsAttachedToInstance) {
<del> // Enqueue it to UIThread not to block onMeasure waiting for the catalyst instance creation
<del> UiThreadUtil.runOnUiThread(new Runnable() {
<del> @Override
<del> public void run() {
<del> attachToReactInstanceManager();
<del> }
<del> });
<add> mWasMeasured = true;
<add> // Check if we were waiting for onMeasure to attach the root view.
<add> if (mReactInstanceManager != null && !mIsAttachedToInstance) {
<add> // Enqueue it to UIThread not to block onMeasure waiting for the catalyst instance creation.
<add> UiThreadUtil.runOnUiThread(new Runnable() {
<add> @Override
<add> public void run() {
<add> attachToReactInstanceManager();
<add> }
<add> });
<add> }
<add> } finally {
<add> Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE);
<ide> }
<ide> }
<ide>
<ide> public void startReactApplication(
<ide> ReactInstanceManager reactInstanceManager,
<ide> String moduleName,
<ide> @Nullable Bundle initialProperties) {
<del> UiThreadUtil.assertOnUiThread();
<add> Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "startReactApplication");
<add> try {
<add> UiThreadUtil.assertOnUiThread();
<ide>
<del> // TODO(6788889): Use POJO instead of bundle here, apparently we can't just use WritableMap
<del> // here as it may be deallocated in native after passing via JNI bridge, but we want to reuse
<del> // it in the case of re-creating the catalyst instance
<del> Assertions.assertCondition(
<add> // TODO(6788889): Use POJO instead of bundle here, apparently we can't just use WritableMap
<add> // here as it may be deallocated in native after passing via JNI bridge, but we want to reuse
<add> // it in the case of re-creating the catalyst instance
<add> Assertions.assertCondition(
<ide> mReactInstanceManager == null,
<ide> "This root view has already been attached to a catalyst instance manager");
<ide>
<del> mReactInstanceManager = reactInstanceManager;
<del> mJSModuleName = moduleName;
<del> mAppProperties = initialProperties;
<add> mReactInstanceManager = reactInstanceManager;
<add> mJSModuleName = moduleName;
<add> mAppProperties = initialProperties;
<ide>
<del> if (!mReactInstanceManager.hasStartedCreatingInitialContext()) {
<del> mReactInstanceManager.createReactContextInBackground();
<del> }
<add> if (!mReactInstanceManager.hasStartedCreatingInitialContext()) {
<add> mReactInstanceManager.createReactContextInBackground();
<add> }
<ide>
<del> // We need to wait for the initial onMeasure, if this view has not yet been measured, we set which
<del> // will make this view startReactApplication itself to instance manager once onMeasure is called.
<del> if (mWasMeasured) {
<del> attachToReactInstanceManager();
<add> // We need to wait for the initial onMeasure, if this view has not yet been measured, we set
<add> // which will make this view startReactApplication itself to instance manager once onMeasure
<add> // is called.
<add> if (mWasMeasured) {
<add> attachToReactInstanceManager();
<add> }
<add> } finally {
<add> Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE);
<ide> }
<ide> }
<ide>
<ide> private CustomGlobalLayoutListener getCustomGlobalLayoutListener() {
<ide> }
<ide>
<ide> private void attachToReactInstanceManager() {
<del> if (mIsAttachedToInstance) {
<del> return;
<del> }
<add> Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "attachToReactInstanceManager");
<add> try {
<add> if (mIsAttachedToInstance) {
<add> return;
<add> }
<ide>
<del> mIsAttachedToInstance = true;
<del> Assertions.assertNotNull(mReactInstanceManager).attachMeasuredRootView(this);
<del> getViewTreeObserver().addOnGlobalLayoutListener(getCustomGlobalLayoutListener());
<add> mIsAttachedToInstance = true;
<add> Assertions.assertNotNull(mReactInstanceManager).attachMeasuredRootView(this);
<add> getViewTreeObserver().addOnGlobalLayoutListener(getCustomGlobalLayoutListener());
<add> } finally {
<add> Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE);
<add> }
<ide> }
<ide>
<ide> @Override | 1 |
Javascript | Javascript | set color based on theme | 8f73a92e1660b33a407e96ebfdec493a4959b3fd | <ide><path>client/src/components/Donation/components/DonateForm.js
<ide> const propTypes = {
<ide> isSignedIn: PropTypes.bool,
<ide> stripe: PropTypes.shape({
<ide> createToken: PropTypes.func.isRequired
<del> })
<add> }),
<add> theme: PropTypes.string
<ide> };
<ide> const initialState = {
<ide> donationAmount: 500,
<ide> const initialState = {
<ide> const mapStateToProps = createSelector(
<ide> userSelector,
<ide> isSignedInSelector,
<del> ({ email }, isSignedIn) => ({ email, isSignedIn })
<add> ({ email, theme }, isSignedIn) => ({ email, theme, isSignedIn })
<ide> );
<ide>
<ide> class DonateForm extends Component {
<ide> class DonateForm extends Component {
<ide>
<ide> renderDonateForm() {
<ide> const { isFormValid } = this.state;
<add> const { theme } = this.props;
<ide> return (
<ide> <Row>
<ide> <Col sm={10} smOffset={1} xs={12}>
<ide> class DonateForm extends Component {
<ide> value={this.getUserEmail()}
<ide> />
<ide> </FormGroup>
<del> <StripeCardForm getValidationState={this.getValidationState} />
<add> <StripeCardForm
<add> getValidationState={this.getValidationState}
<add> theme={theme}
<add> />
<ide> <Button
<ide> block={true}
<ide> bsStyle='primary'
<ide><path>client/src/components/Donation/components/StripeCardForm.js
<ide> import { ControlLabel, FormGroup } from '@freecodecamp/react-bootstrap';
<ide> import '../Donation.css';
<ide>
<ide> const propTypes = {
<del> getValidationState: PropTypes.func.isRequired
<add> getValidationState: PropTypes.func.isRequired,
<add> theme: PropTypes.string
<ide> };
<ide>
<ide> const style = {
<ide> base: {
<del> color: '#0a0a23',
<ide> fontSize: '18px'
<ide> }
<ide> };
<ide> class StripeCardForm extends Component {
<ide> }
<ide>
<ide> render() {
<add> // set color based on theme
<add> style.base.color = this.props.theme === 'night' ? '#fff' : '#0a0a23';
<ide> return (
<ide> <div className='donation-elements'>
<ide> <FormGroup> | 2 |
Python | Python | increase timeouts even longer for on_kill test | 5a4eb84a12bca055e9fcba086cb2559b3243c8c2 | <ide><path>tests/task/task_runner/test_standard_task_runner.py
<ide> def test_on_kill(self):
<ide> processes = list(self._procs_in_pgroup(runner_pgid))
<ide>
<ide> logging.info("Waiting for the task to start")
<del> with timeout(seconds=4):
<add> with timeout(seconds=20):
<ide> while True:
<ide> if os.path.exists(path_on_kill_running):
<ide> break | 1 |
Python | Python | list the language_data package in the setup.py | 97521c95b3efa1d8b6d5dcade30c030b0e984163 | <ide><path>setup.py
<ide> 'spacy.it',
<ide> 'spacy.pt',
<ide> 'spacy.nl',
<add> 'spacy.language_data',
<ide> 'spacy.serialize',
<ide> 'spacy.syntax',
<ide> 'spacy.munge', | 1 |
Text | Text | add profiling reference links for python | c861c03f9d1f7356fd25ed5d2f427c0c57a0f80d | <ide><path>guide/english/python/index.md
<ide> As stated python is a general purpose language. You can use it to do anything yo
<ide> ## Want to learn more?
<ide>
<ide> Free Code Camp has some great resources. The web is a big place, there's plenty more to explore:
<add>
<ide> * [Python Practice Book](http://anandology.com/python-practice-book/index.html)
<ide> * [Think Python](http://greenteapress.com/thinkpython/html/index.html)
<ide> * [Practical Business Python](http://pbpython.com/)
<ide> * [Real Python](https://realpython.com)
<ide> * [Full Stack Python](https://www.fullstackpython.com/)
<del>* Learn the Basics [[codecademy](https://www.codecademy.com/learn/learn-python)]
<del>* Computer science using Python [[edX](https://www.edx.org/course/introduction-computer-science-mitx-6-00-1x-11)]
<del>* Intro to Computer Science CS101 [[Udacity](https://www.udacity.com/course/intro-to-computer-science--cs101)]
<del>* List of more resources for learning python [Awesome Python](https://awesome-python.com)
<add>* [Learn the Basics on codecademy](https://www.codecademy.com/learn/learn-python)
<add>* [Computer science using Python on edX](https://www.edx.org/course/introduction-computer-science-mitx-6-00-1x-11)
<add>* [Intro to Computer Science CS101 on Udacity](https://www.udacity.com/course/intro-to-computer-science--cs101)
<add>* [List of more resources for learning python on Awesome Python](https://awesome-python.com)
<ide> * [Interactive Python - How to Think Like a Computer Scientist](http://interactivepython.org/runestone/static/thinkcspy/index.html)
<ide> * [Everyday Python Project](http://interactivepython.org/runestone/static/everyday/index.html)
<ide> * [Python Developer’s Guide](https://devguide.python.org)
<ide> * [Learn Python the Hard Way book](https://learnpythonthehardway.org/python3)
<del>* Introduction to Python Programming [[Udacity](https://www.udacity.com/course/introduction-to-python--ud1110)]
<add>* [Introduction to Python Programming on Udacity](https://www.udacity.com/course/introduction-to-python--ud1110)
<add>* [Profiling in Python](https://docs.python.org/2/library/profile.html) | 1 |
Text | Text | add changelog entry for | b8de7ae9a35b029c92445a112d20d943249c3f42 | <ide><path>activerecord/CHANGELOG.md
<add>* Support foreign key creation for SQLite3.
<add>
<add> *Ryuta Kamizono*
<add>
<ide> * Remove `initialize_schema_migrations_table` and `initialize_internal_metadata_table`
<ide> internal public methods.
<ide>
<ide>
<ide> *Kevin Glowacz*
<ide>
<del>* Raise `ActiveRecord::InvalidForeignKey` when a foreign key constraint fails on Sqlite3.
<add>* Raise `ActiveRecord::InvalidForeignKey` when a foreign key constraint fails on SQLite3.
<ide>
<ide> *Ryuta Kamizono*
<ide>
<ide>
<ide> *Ryuta Kamizono*
<ide>
<del>* Sqlite3 migrations to add a column to an existing table can now be
<add>* SQLite3 migrations to add a column to an existing table can now be
<ide> successfully rolled back when the column was given and invalid column
<ide> type.
<ide> | 1 |
Text | Text | add missing shasums for v0.10.19 release | cfa03ad2e3423693f6bc56a82696f9c362d71ed0 | <ide><path>doc/blog/release/v0.10.19.md
<ide> Documentation: http://nodejs.org/docs/v0.10.19/api/
<ide>
<ide> Shasums:
<ide> ```
<add>74f1db96742fcc0128d1c14d3cb808ef5c847749 node-v0.10.19-darwin-x64.tar.gz
<add>71ef9bd63d3926a2b78a43a5d077838c43e7e2ea node-v0.10.19-darwin-x86.tar.gz
<add>ebc6dc67276f7461dbd45496924b36949c75e7e0 node-v0.10.19-linux-x64.tar.gz
<add>226b507f554fa5cc07296c30f08db76f5eaeb157 node-v0.10.19-linux-x86.tar.gz
<add>3b324613b79d1c4ab3b9414b0644a3a559c2aec9 node-v0.10.19-sunos-x64.tar.gz
<add>83cb3e58e9ac925ea22c8533cabc712625faa3f7 node-v0.10.19-sunos-x86.tar.gz
<add>dcbe7db6d0c93f83f539f38807cd3c1923969721 node-v0.10.19-x86.msi
<add>e6397e1df4e74864e3f0e5fc7bd24178828497f4 node-v0.10.19.pkg
<add>39478caf7024af6d992007457540f8941104c5d9 node-v0.10.19.tar.gz
<add>0fe9364b443e76f7364f8694751da15479417bdf node.exe
<add>63555cdb67c2fd63411726dc691b08af520b27f6 node.exp
<add>c4d33b56cff97c47b12df3ad237977a57d4c798d node.lib
<add>19a603db8f8c30b1736124740a6a1c856f2d21d8 node.pdb
<add>ca32da0335ecb09ab7316b6e18f23461e298768e pkgsrc/nodejs-ia32-0.10.19.tgz
<add>b0b05a7f74d980720677a3232e82e23df211c122 pkgsrc/nodejs-x64-0.10.19.tgz
<add>45aed04478346035e8dc7933d120ab636d56eac4 x64/node-v0.10.19-x64.msi
<add>b81788c17fec167b77883dcbaf8c629ad7560c4d x64/node.exe
<add>086761bf6ff4622714d24d7979548a37aaaea57e x64/node.exp
<add>cc554a431039952207adfcb3997a7366ad7182e8 x64/node.lib
<add>02d18f042f3d25663ea4d979dff8120435982079 x64/node.pdb
<ide> ``` | 1 |
Ruby | Ruby | improve formula/cask disambiguation | 7d5216c500a5754da766937de3d61ebf8d70d643 | <ide><path>Library/Homebrew/dev-cmd/bump.rb
<ide> def bump
<ide> if formulae_and_casks
<ide> Livecheck.load_other_tap_strategies(formulae_and_casks)
<ide>
<add> ambiguous_casks = []
<add> if !args.formula? && !args.cask?
<add> ambiguous_casks = formulae_and_casks
<add> .group_by { |item| Livecheck.formula_or_cask_name(item, full_name: true) }
<add> .select { |_name, items| items.length > 1 }
<add> .values.flatten
<add> .select { |item| item.is_a?(Cask::Cask) }
<add> end
<add>
<ide> formulae_and_casks.each_with_index do |formula_or_cask, i|
<ide> puts if i.positive?
<ide>
<ide> def bump
<ide> end
<ide>
<ide> package_data = Repology.single_package_query(name, repository: repository)
<del> retrieve_and_display_info(formula_or_cask, name, package_data&.values&.first, args: args)
<add> retrieve_and_display_info(
<add> formula_or_cask,
<add> name,
<add> package_data&.values&.first,
<add> args: args,
<add> ambiguous_cask: ambiguous_casks.include?(formula_or_cask),
<add> )
<ide> end
<ide> else
<ide> api_response = {}
<ide> def bump
<ide> next
<ide> end
<ide> name = Livecheck.formula_or_cask_name(formula_or_cask)
<add> ambiguous_cask = begin
<add> formula_or_cask.is_a?(Cask::Cask) && !args.cask? && Formula[name] ? true : false
<add> rescue FormulaUnavailableError
<add> false
<add> end
<ide>
<ide> puts if i.positive?
<del> retrieve_and_display_info(formula_or_cask, name, repositories, args: args)
<add> retrieve_and_display_info(formula_or_cask, name, repositories, args: args, ambiguous_cask: ambiguous_cask)
<ide>
<ide> break if limit && i >= limit
<ide> end
<ide> def retrieve_pull_requests(formula_or_cask, name)
<ide> pull_requests
<ide> end
<ide>
<del> def retrieve_and_display_info(formula_or_cask, name, repositories, args:)
<add> def retrieve_and_display_info(formula_or_cask, name, repositories, args:, ambiguous_cask: false)
<ide> current_version = if formula_or_cask.is_a?(Formula)
<ide> formula_or_cask.stable.version
<ide> else
<ide> def retrieve_and_display_info(formula_or_cask, name, repositories, args:)
<ide> livecheck_latest = livecheck_result(formula_or_cask)
<ide> pull_requests = retrieve_pull_requests(formula_or_cask, name) unless args.no_pull_requests?
<ide>
<del> name += begin
<del> (" (cask)" if formula_or_cask.is_a?(Cask::Cask) && !args.cask? && Formula[name]).to_s
<del> rescue FormulaUnavailableError
<del> ""
<del> end
<del>
<add> name += " (cask)" if ambiguous_cask
<ide> title = if current_version == repology_latest &&
<ide> current_version == livecheck_latest
<ide> "#{name} is up to date!"
<ide><path>Library/Homebrew/dev-cmd/livecheck.rb
<ide> def livecheck
<ide> options = {
<ide> json: args.json?,
<ide> full_name: args.full_name?,
<del> handle_name_conflict: !args.cask?,
<add> handle_name_conflict: !args.formula? && !args.cask?,
<ide> newer_only: args.newer_only?,
<ide> quiet: args.quiet?,
<ide> debug: args.debug?,
<ide><path>Library/Homebrew/livecheck/livecheck.rb
<ide> def livecheck_strategy_names
<ide>
<ide> # Uses `formulae_and_casks_to_check` to identify taps in use other than
<ide> # homebrew/core and homebrew/cask and loads strategies from them.
<del> sig { params(formulae_and_casks_to_check: T::Enumerable[T.any(Formula, Cask::Cask)]).void }
<add> sig { params(formulae_and_casks_to_check: T::Array[T.any(Formula, Cask::Cask)]).void }
<ide> def load_other_tap_strategies(formulae_and_casks_to_check)
<ide> other_taps = {}
<ide> formulae_and_casks_to_check.each do |formula_or_cask|
<ide> def load_other_tap_strategies(formulae_and_casks_to_check)
<ide> # `formulae_and_casks_to_check` array and prints the results.
<ide> sig {
<ide> params(
<del> formulae_and_casks_to_check: T::Enumerable[T.any(Formula, Cask::Cask)],
<add> formulae_and_casks_to_check: T::Array[T.any(Formula, Cask::Cask)],
<ide> full_name: T::Boolean,
<ide> handle_name_conflict: T::Boolean,
<ide> json: T::Boolean,
<ide> def run_checks(
<ide> )
<ide> load_other_tap_strategies(formulae_and_casks_to_check)
<ide>
<add> ambiguous_casks = []
<add> if handle_name_conflict
<add> ambiguous_casks = formulae_and_casks_to_check
<add> .group_by { |item| formula_or_cask_name(item, full_name: true) }
<add> .select { |_name, items| items.length > 1 }
<add> .values.flatten
<add> .select { |item| item.is_a?(Cask::Cask) }
<add> end
<add>
<ide> has_a_newer_upstream_version = T.let(false, T::Boolean)
<ide>
<ide> if json && !quiet && $stderr.tty?
<ide> def run_checks(
<ide> next info
<ide> end
<ide>
<del> print_latest_version(info, verbose: verbose, handle_name_conflict: handle_name_conflict)
<add> print_latest_version(info, verbose: verbose, ambiguous_cask: ambiguous_casks.include?(formula_or_cask))
<ide> nil
<ide> rescue => e
<ide> Homebrew.failed = true
<ide> def run_checks(
<ide> status_hash(formula_or_cask, "error", [e.to_s], full_name: full_name, verbose: verbose)
<ide> elsif !quiet
<ide> name = formula_or_cask_name(formula_or_cask, full_name: full_name)
<del> name += begin
<del> (" (cask)" if cask && handle_name_conflict && Formula[name]).to_s
<del> rescue FormulaUnavailableError
<del> ""
<del> end
<add> name += " (cask)" if ambiguous_casks.include?(formula_or_cask)
<ide>
<ide> onoe "#{Tty.blue}#{name}#{Tty.reset}: #{e}"
<ide> $stderr.puts e.backtrace if debug && !e.is_a?(Livecheck::Error)
<ide> def status_hash(formula_or_cask, status_str, messages = nil, full_name: false, v
<ide> end
<ide>
<ide> # Formats and prints the livecheck result for a formula.
<del> sig { params(info: Hash, verbose: T::Boolean, handle_name_conflict: T::Boolean).void }
<del> def print_latest_version(info, verbose:, handle_name_conflict: false)
<add> sig { params(info: Hash, verbose: T::Boolean, ambiguous_cask: T::Boolean).void }
<add> def print_latest_version(info, verbose:, ambiguous_cask: false)
<ide> formula_or_cask_s = "#{Tty.blue}#{info[:formula] || info[:cask]}#{Tty.reset}"
<del> formula_or_cask_s += begin
<del> (" (cask)" if info[:cask] && handle_name_conflict && Formula[info[:cask]]).to_s
<del> rescue FormulaUnavailableError
<del> ""
<del> end
<add> formula_or_cask_s += " (cask)" if ambiguous_cask
<ide> formula_or_cask_s += " (guessed)" if !info[:meta][:livecheckable] && verbose
<ide>
<ide> current_s = if info[:version][:newer_than_upstream] | 3 |
Python | Python | open the temporaryfile in ascii mode | df813e52675cf873d4b82347b53ed8eda5c6cc06 | <ide><path>numpy/distutils/tests/test_exec_command.py
<ide> def test_exec_command_stdout():
<ide>
<ide> def test_exec_command_stderr():
<ide> # Test posix version:
<del> with redirect_stdout(TemporaryFile()):
<add> with redirect_stdout(TemporaryFile(mode='w+')):
<ide> with redirect_stderr(StringIO.StringIO()):
<ide> exec_command.exec_command("cd '.'")
<ide> | 1 |
Text | Text | reduce repetitiveness on consensus seeking | 2f27f1144edd5772467597da26c8faf41a1dbd99 | <ide><path>doc/guides/collaborator-guide.md
<ide> pull request creator pushed new code since the last CI run.
<ide>
<ide> ### Consensus Seeking
<ide>
<del>If there are no objecting Collaborators, a pull request may land if it has the
<del>needed [approvals](#code-reviews), [CI](#testing-and-ci), and
<del>[wait time](#waiting-for-approvals). If a pull request meets all requirements
<del>except the [wait time](#waiting-for-approvals), please add the
<add>A pull request may land if it has the needed [approvals](#code-reviews),
<add>[CI](#testing-and-ci), [wait time](#waiting-for-approvals) and no
<add>[outstanding objections](#objections). [Breaking changes](#breaking-changes)
<add>must receive [TSC review](#involving-the-tsc) in addition to other
<add>requirements. If a pull request meets all requirements except the
<add>[wait time](#waiting-for-approvals), please add the
<ide> [`author ready`](#author-ready-pull-requests) label.
<ide>
<del>If a collaborator believes a pull request should not land as is, **the "Request
<del>Changes" GitHub feature must be used to make the objection explicit**. An
<del>implicit objection not using the "Request Changes" feature is not a
<del>blocker for a pull request. Pull requests with an explicit objection should
<del>not land until all objections are satisfied. Collaborators should not block a
<del>pull request without providing a reason. **Providing a set of actionable steps
<del>alongside the objection is recommended, and the objector must be willing to
<del>work with the pull request author to reach a consensus about the direction of
<del>the pull request**. If reaching consensus is not possible, a Collaborator may
<del>escalate the issue to the TSC.
<add>#### Objections
<add>
<add>**Collaborators may object to a pull request by using the "Request
<add>Changes" GitHub feature**. Dissent comments alone don't constitute an
<add>objection. **Any PR objection must include a clear reason for that objection,
<add>and the objector must remain responsive for further discussion towards
<add>consensus about the direction of the pull request**. Providing a set of
<add>actionable steps alongside the objection is recommended.
<ide>
<ide> If the objection is not clear to others, another Collaborator may ask an
<ide> objecting Collaborator to explain their objection or to provide actionable
<ide> steps to resolve the objection. **If the objector is unresponsive for seven
<ide> days after a collaborator asks for clarification, another Collaborator may
<ide> dismiss the objection**.
<ide>
<del>[Breaking changes](#breaking-changes) must receive
<del>[TSC review](#involving-the-tsc). If two TSC members approve the pull request
<del>and no Collaborators object, then it may land. If there are objections, a
<del>Collaborator may apply the `tsc-agenda` label. That will put the pull request on
<del>the TSC meeting agenda.
<add>**Pull requests with outstanding objections must remain open until all
<add>objections are satisfied**. If reaching consensus is not possible, a
<add>Collaborator may escalate the issue to the TSC by pinging `@nodejs/tsc` and
<add>adding the `tsc-agenda` label to the issue.
<ide>
<ide> #### Helpful resources
<ide> | 1 |
Javascript | Javascript | add flowtype to function signature | 5cff212072beb58b00e6475d1cd2d57413f73e2c | <ide><path>packages/react-reconciler/src/ReactFiberBeginWork.js
<ide> export function reconcileChildren(
<ide> }
<ide> }
<ide>
<del>function updateForwardRef(current, workInProgress, renderExpirationTime) {
<add>function updateForwardRef(
<add> current: Fiber | null,
<add> workInProgress: Fiber,
<add> renderExpirationTime: ExpirationTime,
<add>) {
<ide> const render = workInProgress.type.render;
<ide> const nextProps = workInProgress.pendingProps;
<ide> const ref = workInProgress.ref;
<ide> function updateForwardRef(current, workInProgress, renderExpirationTime) {
<ide> return workInProgress.child;
<ide> }
<ide>
<del>function updateFragment(current, workInProgress, renderExpirationTime) {
<add>function updateFragment(
<add> current: Fiber | null,
<add> workInProgress: Fiber,
<add> renderExpirationTime: ExpirationTime,
<add>) {
<ide> const nextChildren = workInProgress.pendingProps;
<ide> reconcileChildren(
<ide> current,
<ide> function updateFragment(current, workInProgress, renderExpirationTime) {
<ide> return workInProgress.child;
<ide> }
<ide>
<del>function updateMode(current, workInProgress, renderExpirationTime) {
<add>function updateMode(
<add> current: Fiber | null,
<add> workInProgress: Fiber,
<add> renderExpirationTime: ExpirationTime,
<add>) {
<ide> const nextChildren = workInProgress.pendingProps.children;
<ide> reconcileChildren(
<ide> current,
<ide> function updateMode(current, workInProgress, renderExpirationTime) {
<ide> return workInProgress.child;
<ide> }
<ide>
<del>function updateProfiler(current, workInProgress, renderExpirationTime) {
<add>function updateProfiler(
<add> current: Fiber | null,
<add> workInProgress: Fiber,
<add> renderExpirationTime: ExpirationTime,
<add>) {
<ide> if (enableProfilerTimer) {
<ide> workInProgress.effectTag |= Update;
<ide> }
<ide> function updatePlaceholderComponent(
<ide> }
<ide> }
<ide>
<del>function updatePortalComponent(current, workInProgress, renderExpirationTime) {
<add>function updatePortalComponent(
<add> current: Fiber | null,
<add> workInProgress: Fiber,
<add> renderExpirationTime: ExpirationTime,
<add>) {
<ide> pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
<ide> const nextChildren = workInProgress.pendingProps;
<ide> if (current === null) {
<ide> function updatePortalComponent(current, workInProgress, renderExpirationTime) {
<ide> return workInProgress.child;
<ide> }
<ide>
<del>function updateContextProvider(current, workInProgress, renderExpirationTime) {
<add>function updateContextProvider(
<add> current: Fiber | null,
<add> workInProgress: Fiber,
<add> renderExpirationTime: ExpirationTime,
<add>) {
<ide> const providerType: ReactProviderType<any> = workInProgress.type;
<ide> const context: ReactContext<any> = providerType._context;
<ide>
<ide> function updateContextProvider(current, workInProgress, renderExpirationTime) {
<ide> return workInProgress.child;
<ide> }
<ide>
<del>function updateContextConsumer(current, workInProgress, renderExpirationTime) {
<add>function updateContextConsumer(
<add> current: Fiber | null,
<add> workInProgress: Fiber,
<add> renderExpirationTime: ExpirationTime,
<add>) {
<ide> const context: ReactContext<any> = workInProgress.type;
<ide> const newProps = workInProgress.pendingProps;
<ide> const render = newProps.children; | 1 |
PHP | PHP | remove unused parameter | 76e30db8fe666f11648bc21d731a0cdbb56ebf8e | <ide><path>src/Illuminate/Translation/Translator.php
<ide> public function choice($key, $number, array $replace = [], $locale = null)
<ide> $replace['count'] = $number;
<ide>
<ide> return $this->makeReplacements(
<del> $this->getSelector()->choose($line, $number, $locale), $replace
<add> $this->getSelector()->choose($line, $number), $replace
<ide> );
<ide> }
<ide>
<ide><path>tests/Translation/TranslationTranslatorTest.php
<ide> public function testChoiceMethodProperlyLoadsAndRetrievesItem()
<ide> $t = $this->getMockBuilder('Illuminate\Translation\Translator')->setMethods(['get'])->setConstructorArgs([$this->getLoader(), 'en'])->getMock();
<ide> $t->expects($this->once())->method('get')->with($this->equalTo('foo'), $this->equalTo(['replace']), $this->equalTo('en'))->will($this->returnValue('line'));
<ide> $t->setSelector($selector = m::mock('Illuminate\Translation\MessageSelector'));
<del> $selector->shouldReceive('choose')->once()->with('line', 10, 'en')->andReturn('choiced');
<add> $selector->shouldReceive('choose')->once()->with('line', 10)->andReturn('choiced');
<ide>
<ide> $t->choice('foo', 10, ['replace']);
<ide> }
<ide> public function testChoiceMethodProperlyCountsCollectionsAndLoadsAndRetrievesIte
<ide> $t = $this->getMockBuilder('Illuminate\Translation\Translator')->setMethods(['get'])->setConstructorArgs([$this->getLoader(), 'en'])->getMock();
<ide> $t->expects($this->exactly(2))->method('get')->with($this->equalTo('foo'), $this->equalTo(['replace']), $this->equalTo('en'))->will($this->returnValue('line'));
<ide> $t->setSelector($selector = m::mock('Illuminate\Translation\MessageSelector'));
<del> $selector->shouldReceive('choose')->twice()->with('line', 3, 'en')->andReturn('choiced');
<add> $selector->shouldReceive('choose')->twice()->with('line', 3)->andReturn('choiced');
<ide>
<ide> $values = ['foo', 'bar', 'baz'];
<ide> $t->choice('foo', $values, ['replace']); | 2 |
Go | Go | allow push of a single tag | e648a186d68dcb3ee0d6123b041c5aa66438cc89 | <ide><path>api/client/commands.go
<ide> func (cli *DockerCli) CmdImport(args ...string) error {
<ide> }
<ide>
<ide> func (cli *DockerCli) CmdPush(args ...string) error {
<del> cmd := cli.Subcmd("push", "NAME", "Push an image or a repository to the registry")
<add> cmd := cli.Subcmd("push", "NAME[:TAG]", "Push an image or a repository to the registry")
<ide> if err := cmd.Parse(args); err != nil {
<ide> return nil
<ide> }
<ide> func (cli *DockerCli) CmdPush(args ...string) error {
<ide>
<ide> cli.LoadConfigFile()
<ide>
<add> remote, tag := utils.ParseRepositoryTag(name)
<add>
<ide> // Resolve the Repository name from fqn to hostname + name
<del> hostname, _, err := registry.ResolveRepositoryName(name)
<add> hostname, _, err := registry.ResolveRepositoryName(remote)
<ide> if err != nil {
<ide> return err
<ide> }
<ide> func (cli *DockerCli) CmdPush(args ...string) error {
<ide> }
<ide>
<ide> v := url.Values{}
<add> v.Set("tag", tag)
<ide> push := func(authConfig registry.AuthConfig) error {
<ide> buf, err := json.Marshal(authConfig)
<ide> if err != nil {
<ide> func (cli *DockerCli) CmdPush(args ...string) error {
<ide> base64.URLEncoding.EncodeToString(buf),
<ide> }
<ide>
<del> return cli.stream("POST", "/images/"+name+"/push?"+v.Encode(), nil, cli.out, map[string][]string{
<add> return cli.stream("POST", "/images/"+remote+"/push?"+v.Encode(), nil, cli.out, map[string][]string{
<ide> "X-Registry-Auth": registryAuthHeader,
<ide> })
<ide> }
<ide><path>api/server/server.go
<ide> func postImagesPush(eng *engine.Engine, version version.Version, w http.Response
<ide> job := eng.Job("push", vars["name"])
<ide> job.SetenvJson("metaHeaders", metaHeaders)
<ide> job.SetenvJson("authConfig", authConfig)
<add> job.Setenv("tag", r.Form.Get("tag"))
<ide> if version.GreaterThan("1.0") {
<ide> job.SetenvBool("json", true)
<ide> streamJSON(job, w, true)
<ide><path>server/server.go
<ide> func (srv *Server) ImagePull(job *engine.Job) engine.Status {
<ide> }
<ide>
<ide> // Retrieve the all the images to be uploaded in the correct order
<del>func (srv *Server) getImageList(localRepo map[string]string) ([]string, map[string][]string, error) {
<add>func (srv *Server) getImageList(localRepo map[string]string, requestedTag string) ([]string, map[string][]string, error) {
<ide> var (
<ide> imageList []string
<ide> imagesSeen map[string]bool = make(map[string]bool)
<ide> tagsByImage map[string][]string = make(map[string][]string)
<ide> )
<ide>
<ide> for tag, id := range localRepo {
<add> if requestedTag != "" && requestedTag != tag {
<add> continue
<add> }
<ide> var imageListForThisTag []string
<ide>
<ide> tagsByImage[id] = append(tagsByImage[id], tag)
<ide> func (srv *Server) getImageList(localRepo map[string]string) ([]string, map[stri
<ide> // append to main image list
<ide> imageList = append(imageList, imageListForThisTag...)
<ide> }
<del>
<add> if len(imageList) == 0 {
<add> return nil, nil, fmt.Errorf("No images found for the requested repository / tag")
<add> }
<ide> utils.Debugf("Image list: %v", imageList)
<ide> utils.Debugf("Tags by image: %v", tagsByImage)
<ide>
<ide> return imageList, tagsByImage, nil
<ide> }
<ide>
<del>func (srv *Server) pushRepository(r *registry.Registry, out io.Writer, localName, remoteName string, localRepo map[string]string, sf *utils.StreamFormatter) error {
<add>func (srv *Server) pushRepository(r *registry.Registry, out io.Writer, localName, remoteName string, localRepo map[string]string, tag string, sf *utils.StreamFormatter) error {
<ide> out = utils.NewWriteFlusher(out)
<ide> utils.Debugf("Local repo: %s", localRepo)
<del> imgList, tagsByImage, err := srv.getImageList(localRepo)
<add> imgList, tagsByImage, err := srv.getImageList(localRepo, tag)
<ide> if err != nil {
<ide> return err
<ide> }
<ide>
<ide> out.Write(sf.FormatStatus("", "Sending image list"))
<ide>
<del> var repoData *registry.RepositoryData
<del> var imageIndex []*registry.ImgData
<add> var (
<add> repoData *registry.RepositoryData
<add> imageIndex []*registry.ImgData
<add> )
<ide>
<ide> for _, imgId := range imgList {
<ide> if tags, exists := tagsByImage[imgId]; exists {
<ide> func (srv *Server) pushRepository(r *registry.Registry, out io.Writer, localName
<ide> return err
<ide> }
<ide>
<add> nTag := 1
<add> if tag == "" {
<add> nTag = len(localRepo)
<add> }
<ide> for _, ep := range repoData.Endpoints {
<del> out.Write(sf.FormatStatus("", "Pushing repository %s (%d tags)", localName, len(localRepo)))
<add> out.Write(sf.FormatStatus("", "Pushing repository %s (%d tags)", localName, nTag))
<ide>
<ide> for _, imgId := range imgList {
<ide> if r.LookupRemoteImage(imgId, ep, repoData.Tokens) {
<ide> func (srv *Server) ImagePush(job *engine.Job) engine.Status {
<ide> metaHeaders map[string][]string
<ide> )
<ide>
<add> tag := job.Getenv("tag")
<ide> job.GetenvJson("authConfig", authConfig)
<ide> job.GetenvJson("metaHeaders", metaHeaders)
<ide> if _, err := srv.poolAdd("push", localName); err != nil {
<ide> func (srv *Server) ImagePush(job *engine.Job) engine.Status {
<ide> }
<ide>
<ide> if err != nil {
<del> reposLen := len(srv.runtime.Repositories().Repositories[localName])
<add> reposLen := 1
<add> if tag == "" {
<add> reposLen = len(srv.runtime.Repositories().Repositories[localName])
<add> }
<ide> job.Stdout.Write(sf.FormatStatus("", "The push refers to a repository [%s] (len: %d)", localName, reposLen))
<ide> // If it fails, try to get the repository
<ide> if localRepo, exists := srv.runtime.Repositories().Repositories[localName]; exists {
<del> if err := srv.pushRepository(r, job.Stdout, localName, remoteName, localRepo, sf); err != nil {
<add> if err := srv.pushRepository(r, job.Stdout, localName, remoteName, localRepo, tag, sf); err != nil {
<ide> return job.Error(err)
<ide> }
<ide> return engine.StatusOK | 3 |
Ruby | Ruby | improve the test case introduced by bd0d47e | 39542fba54328ca048fb75a5d5b37f8e1d4c1f37 | <ide><path>activerecord/test/cases/calculations_test.rb
<ide> def test_pluck_columns_with_same_name
<ide> end
<ide>
<ide> def test_calculation_with_polymorphic_relation
<del> sp = ShipPart.create! name: "no trinket"
<del> sp_with_trinket = ShipPart.create! name: "has_trinket"
<del> sp_with_trinket.trinkets.create!
<del> ship_parts = [sp.id,sp_with_trinket.id]
<del>
<del> sp_with_trinket_relation = ShipPart.where(id:ship_parts).joins(:trinkets)
<del> sp_with_trinket_relation2 = sp_with_trinket_relation.where(name:"has_trinket")
<del> sp_with_trinket_relation3 = sp_with_trinket_relation.where(treasures: {looter_type:"ShipPart"})
<del> sp_with_trinket_relation4 = ShipPart.where(id:ship_parts).eager_load(:trinkets).where.not(treasures:{id:nil})
<del>
<del> [sp_with_trinket_relation,sp_with_trinket_relation2,
<del> sp_with_trinket_relation3,sp_with_trinket_relation4].each do |with_trinket_rel|
<del> assert_equal 1, with_trinket_rel.count
<del> assert_equal [sp_with_trinket.id], with_trinket_rel.pluck(:id)
<del> assert_equal sp_with_trinket.id, with_trinket_rel.sum(:id)
<del> assert_equal ({"has_trinket" => sp_with_trinket.id}), with_trinket_rel.group('ship_parts.name').sum(:id)
<del> assert_equal ({"has_trinket" => sp_with_trinket.id}), with_trinket_rel.where(id:sp_with_trinket.id).
<del> group('ship_parts.name').sum(:id)
<del> end
<add> part = ShipPart.create!(name: "has trinket")
<add> part.trinkets.create!
<add>
<add> assert_equal part.id, ShipPart.joins(:trinkets).sum(:id)
<ide> end
<ide>
<add> def test_grouped_calculation_with_polymorphic_relation
<add> part = ShipPart.create!(name: "has trinket")
<add> part.trinkets.create!
<add>
<add> assert_equal({ "has trinket" => part.id }, ShipPart.joins(:trinkets).group("ship_parts.name").sum(:id))
<add> end
<ide> end | 1 |
Ruby | Ruby | fix a typo | 9cb12265d8a08c219c82e4e4d305a6d60b0af35c | <ide><path>actionpack/lib/action_view/template/resolver.rb
<ide> def initialize(options = {})
<ide> NAME_BLOCK = lambda {|cache, name| cache[name] = SmallCache.new(&PREFIX_BLOCK)}
<ide> KEY_BLOCK = lambda {|cache, key| cache[key] = SmallCache.new(&NAME_BLOCK)}
<ide>
<del> # usually a majority of template look ups return nothing, use this canonical preallocated array to safe memory
<add> # usually a majority of template look ups return nothing, use this canonical preallocated array to save memory
<ide> NO_TEMPLATES = [].freeze
<ide>
<ide> def initialize | 1 |
Text | Text | add docs for ip-forward | 85fffe1341fc4e957a9a40dbc3cedded8cb44e70 | <ide><path>docs/man/docker.1.md
<ide> unix://[/path/to/socket] to use.
<ide> Default IP address to use when binding container ports. Default is `0.0.0.0`.
<ide>
<ide> **--ip-forward**=*true*|*false*
<del> Docker will enable IP forwarding. Default is true. If `--fixed-cidr-v6` is set. IPv6 forwarding will be activated, too. This may reject Router Advertisements and interfere with the host's existing IPv6 configuration. For more information please consult the documentation about "Advanced Networking - IPv6".
<add> Enables IP forwarding on the Docker host. The default is `true`. This flag interacts with the IP forwarding setting on your host system's kernel. If your system has IP forwarding disabled, this setting enables it. If your system has IP forwarding enabled, setting this flag to `--ip-forward=false` has no effect.
<add>
<add> This setting will also enable IPv6 forwarding if you have both `--ip-forward=true` and `--fixed-cidr-v6` set. Note that this may reject Router Advertisements and interfere with the host's existing IPv6 configuration. For more information, please consult the documentation about "Advanced Networking - IPv6".
<ide>
<ide> **--ip-masq**=*true*|*false*
<ide> Enable IP masquerading for bridge's IP range. Default is true.
<ide><path>docs/sources/articles/networking.md
<ide> Whether a container can talk to the world is governed by two factors.
<ide> containers if this parameter is `1`. Usually you will simply leave
<ide> the Docker server at its default setting `--ip-forward=true` and
<ide> Docker will go set `ip_forward` to `1` for you when the server
<del> starts up. To check the setting or turn it on manually:
<add> starts up. If you set `--ip-forward=false` and your system's kernel
<add> has it enabled, the `--ip-forward=false` option has no effect.
<add> To check the setting on your kernel or to turn it on manually:
<ide>
<ide> $ sysctl net.ipv4.conf.all.forwarding
<ide> net.ipv4.conf.all.forwarding = 0 | 2 |
Python | Python | remove redundant raise from docstring | 5ab9ebeec4f5d34dac00545691e7daae62ed6448 | <ide><path>celery/app/task.py
<ide> def retry(self, args=None, kwargs=None, exc=None, throw=True,
<ide> ... twitter.post_status_update(message)
<ide> ... except twitter.FailWhale as exc:
<ide> ... # Retry in 5 minutes.
<del> ... raise self.retry(countdown=60 * 5, exc=exc)
<add> ... self.retry(countdown=60 * 5, exc=exc)
<ide>
<ide> Note:
<ide> Although the task will never return above as `retry` raises an | 1 |
Ruby | Ruby | add a `time` method for use as the build time | 3776ba9756de63fad533167baa2db77088ba1817 | <ide><path>Library/Homebrew/formula.rb
<ide> def rpath
<ide> "@loader_path/../lib"
<ide> end
<ide>
<add> # Creates a new `Time` object for use in the formula as the build time.
<add> #
<add> # @see https://www.rubydoc.info/stdlib/time/Time Time
<add> sig { returns(Time) }
<add> def time
<add> if ENV["SOURCE_DATE_EPOCH"].present?
<add> Time.at(ENV["SOURCE_DATE_EPOCH"].to_i).utc
<add> else
<add> Time.now.utc
<add> end
<add> end
<add>
<ide> # an array of all core {Formula} names
<ide> # @private
<ide> def self.core_names | 1 |
Ruby | Ruby | remove forgotten puts | aaa85cde6068f4db6fabe7bfef664f73bbc6938f | <ide><path>activesupport/lib/active_support/testing/performance.rb
<ide> module Performance
<ide> :output => 'tmp/performance',
<ide> :benchmark => true }
<ide> else
<del> puts "not"
<ide> { :runs => 1,
<ide> :output => 'tmp/performance',
<ide> :benchmark => false } | 1 |
PHP | PHP | add test for overwriting keys | e227c3762b1b2216e3b98ab507a61d23450e1248 | <ide><path>tests/Support/SupportCollectionTest.php
<ide> public function testNth()
<ide> $this->assertEquals(['d'], $data->nth(4, 3)->all());
<ide> }
<ide>
<add> public function testMapWithKeysOverwritingKeys()
<add> {
<add> $data = new Collection([
<add> ['id' => 1, 'name' => 'A'],
<add> ['id' => 2, 'name' => 'B'],
<add> ['id' => 1, 'name' => 'C'],
<add> ]);
<add> $data = $data->mapWithKeys(function ($item) {
<add> return [$item['id'] => $item['name']];
<add> });
<add> $this->assertSame(
<add> [
<add> 1 => 'C',
<add> 2 => 'B',
<add> ],
<add> $data->all()
<add> );
<add> }
<add>
<ide> public function testTransform()
<ide> {
<ide> $data = new Collection(['first' => 'taylor', 'last' => 'otwell']); | 1 |
Javascript | Javascript | feature detect el.matches() for ie11 | fded30f8f8969b1beb780b9d93ee0da0f5755ce6 | <ide><path>src/js/player.js
<ide> class Player extends Component {
<ide> */
<ide> documentFullscreenChange_(e) {
<ide> const fsApi = FullscreenApi;
<add> const el = this.el();
<add> let isFs = document[fsApi.fullscreenElement] === el;
<ide>
<del> this.isFullscreen(document[fsApi.fullscreenElement] === this.el() || this.el().matches(':' + fsApi.fullscreen));
<add> if (!isFs && el.matches) {
<add> isFs = el.matches(':' + fsApi.fullscreen);
<add> } else if (!isFs && el.msMatchesSelector) {
<add> isFs = el.msMatchesSelector(':' + fsApi.fullscreen);
<add> }
<add>
<add> this.isFullscreen(isFs);
<ide>
<ide> // If cancelling fullscreen, remove event listener.
<ide> if (this.isFullscreen() === false) { | 1 |
Javascript | Javascript | fix eslint errors | c26405508704bcceea751f3769a282024dc2730b | <ide><path>.eslintrc.js
<ide> module.exports = {
<ide> files: [
<ide> 'packages/*/tests/**/*.js',
<ide> 'packages/@ember/*/tests/**/*.js',
<add> 'packages/@ember/-internals/*/tests/**/*.js',
<ide> 'packages/internal-test-helpers/**/*.js',
<ide> ],
<ide> env: {
<ide><path>packages/@ember/application/lib/application.js
<ide> import { hasDOM } from '@ember/-internals/browser-environment';
<ide> import { assert, isTesting } from '@ember/debug';
<ide> import { DEBUG } from '@glimmer/env';
<ide> import { bind, join, once, run, schedule } from '@ember/runloop';
<del>import { libraries, processAllNamespaces, setNamespaceSearchDisabled } from '@ember/-internals/metal';
<add>import {
<add> libraries,
<add> processAllNamespaces,
<add> setNamespaceSearchDisabled,
<add>} from '@ember/-internals/metal';
<ide> import { _loaded, runLoadHooks } from './lazy_load';
<ide> import { RSVP } from 'ember-runtime';
<ide> import { EventDispatcher, jQuery, jQueryDisabled } from '@ember/-internals/views';
<ide><path>packages/@ember/object/lib/computed/reduce_computed_macros.js
<ide> @module @ember/object
<ide> */
<ide> import { assert } from '@ember/debug';
<del>import { get, ComputedProperty, addObserver, removeObserver, getProperties } from '@ember/-internals/metal';
<add>import {
<add> get,
<add> ComputedProperty,
<add> addObserver,
<add> removeObserver,
<add> getProperties,
<add>} from '@ember/-internals/metal';
<ide> import { compare, isArray, A as emberA, uniqBy as uniqByArray } from 'ember-runtime';
<ide>
<ide> function reduceMacro(dependentKey, callback, initialValue, name) {
<ide><path>packages/ember-runtime/lib/mixins/evented.js
<del>import { Mixin, addListener, removeListener, hasListeners, sendEvent } from '@ember/-internals/metal';
<add>import {
<add> Mixin,
<add> addListener,
<add> removeListener,
<add> hasListeners,
<add> sendEvent,
<add>} from '@ember/-internals/metal';
<ide>
<ide> /**
<ide> @module @ember/object
<ide><path>packages/ember-runtime/tests/system/object/computed_test.js
<del>import { alias, computed, set, get, getWithDefault, observer, defineProperty } from '@ember/-internals/metal';
<add>import {
<add> alias,
<add> computed,
<add> set,
<add> get,
<add> getWithDefault,
<add> observer,
<add> defineProperty,
<add>} from '@ember/-internals/metal';
<ide> import { oneWay as reads } from '@ember/object/computed';
<ide> import EmberObject from '../../../lib/system/object';
<ide> import { moduleFor, AbstractTestCase } from 'internal-test-helpers';
<ide><path>packages/ember-runtime/tests/system/object/destroy_test.js
<ide> import { run } from '@ember/runloop';
<del>import { observer, get, set, beginPropertyChanges, endPropertyChanges } from '@ember/-internals/metal';
<add>import {
<add> observer,
<add> get,
<add> set,
<add> beginPropertyChanges,
<add> endPropertyChanges,
<add>} from '@ember/-internals/metal';
<ide> import { peekMeta } from 'ember-meta';
<ide> import EmberObject from '../../../lib/system/object';
<ide> import { DEBUG } from '@glimmer/env';
<ide><path>packages/ember-runtime/tests/system/object/es-compatibility-test.js
<ide> import EmberObject from '../../../lib/system/object';
<del>import { Mixin, defineProperty, computed, addObserver, addListener, sendEvent } from '@ember/-internals/metal';
<add>import {
<add> Mixin,
<add> defineProperty,
<add> computed,
<add> addObserver,
<add> addListener,
<add> sendEvent,
<add>} from '@ember/-internals/metal';
<ide> import { moduleFor, AbstractTestCase } from 'internal-test-helpers';
<ide>
<ide> moduleFor(
<ide><path>packages/ember-runtime/tests/system/object_proxy_test.js
<ide> import { DEBUG } from '@glimmer/env';
<del>import { addObserver, computed, get, set, isWatching, removeObserver } from '@ember/-internals/metal';
<add>import {
<add> addObserver,
<add> computed,
<add> get,
<add> set,
<add> isWatching,
<add> removeObserver,
<add>} from '@ember/-internals/metal';
<ide> import { HAS_NATIVE_PROXY } from '@ember/-internals/utils';
<ide> import ObjectProxy from '../../lib/system/object_proxy';
<ide> import { moduleFor, AbstractTestCase } from 'internal-test-helpers'; | 8 |
Text | Text | fix a typo [ci skip] | 1a2341038080155ca691a198f6497dba31bc8ce5 | <ide><path>guides/source/constant_autoloading_and_reloading.md
<ide> derivation.
<ide>
<ide> ### Loading Mechanism
<ide>
<del>Rails autoloads files with `Kerne#load` when `config.cache_classes` is false,
<add>Rails autoloads files with `Kernel#load` when `config.cache_classes` is false,
<ide> the default in development mode, and with `Kernel#require` otherwise, the
<ide> default in production mode.
<ide> | 1 |
Ruby | Ruby | allow namespaced configuration on generators | 7022b58842ec3490d85efc5b947d86a0fd72d0cb | <ide><path>railties/lib/generators.rb
<ide>
<ide> module Rails
<ide> module Generators
<del> DEFAULT_ALIASES = {
<del> :actions => '-a',
<del> :fixture_replacement => '-r',
<del> :orm => '-o',
<del> :resource_controller => '-c',
<del> :scaffold_controller => '-c',
<del> :stylesheets => '-y',
<del> :test_framework => '-t',
<del> :template_engine => '-e'
<del> }
<del>
<del> DEFAULT_OPTIONS = {
<del> :fixture => true,
<del> :force_plural => false,
<del> :helper => true,
<del> :integration_tool => :test_unit,
<del> :layout => true,
<del> :migration => true,
<del> :orm => :active_record,
<del> :performance_tool => :test_unit,
<del> :resource_controller => :controller,
<del> :scaffold_controller => :scaffold_controller,
<del> :singleton => false,
<del> :stylesheets => true,
<del> :test_framework => :test_unit,
<del> :template_engine => :erb,
<del> :timestamps => true
<del> }
<add> DEFAULT_ALIASES = Hash.new{ |h,k| h[k] = {} }
<add> DEFAULT_ALIASES.merge!(
<add> :rails => {
<add> :actions => '-a',
<add> :orm => '-o',
<add> :resource_controller => '-c',
<add> :scaffold_controller => '-c',
<add> :stylesheets => '-y',
<add> :template_engine => '-e',
<add> :test_framework => '-t'
<add> },
<add>
<add> :test_unit => {
<add> :fixture_replacement => '-r',
<add> },
<add>
<add> :plugin => {
<add> :generator => '-g',
<add> :tasks => '-r'
<add> }
<add> )
<add>
<add> DEFAULT_OPTIONS = Hash.new{ |h,k| h[k] = {} }
<add> DEFAULT_OPTIONS.merge!(
<add> :active_record => {
<add> :migration => true,
<add> :timestamps => true
<add> },
<add>
<add> :erb => {
<add> :layout => true
<add> },
<add>
<add> :rails => {
<add> :force_plural => false,
<add> :helper => true,
<add> :layout => true,
<add> :orm => :active_record,
<add> :integration_tool => :test_unit,
<add> :performance_tool => :test_unit,
<add> :resource_controller => :controller,
<add> :scaffold_controller => :scaffold_controller,
<add> :singleton => false,
<add> :stylesheets => true,
<add> :template_engine => :erb,
<add> :test_framework => :test_unit
<add> },
<add>
<add> :test_unit => {
<add> :fixture => true,
<add> :fixture_replacement => nil
<add> },
<add>
<add> :plugin => {
<add> :generator => false,
<add> :tasks => false
<add> }
<add> )
<ide>
<ide> def self.aliases
<ide> @@aliases ||= DEFAULT_ALIASES.dup
<ide><path>railties/lib/generators/base.rb
<ide> def self.hook_for(*names, &block)
<ide> names.each do |name|
<ide> defaults = if options[:type] == :boolean
<ide> { }
<del> elsif [true, false].include?(options.fetch(:default, Rails::Generators.options[name]))
<add> elsif [true, false].include?(options.fetch(:default, default_value_for_option(name)))
<ide> { :banner => "" }
<ide> else
<ide> { :desc => "#{name.to_s.humanize} to be invoked", :banner => "NAME" }
<ide> def self.remove_hook_for(*names)
<ide> #
<ide> def self.class_option(name, options={}) #:nodoc:
<ide> options[:desc] = "Indicates when to generate #{name.to_s.humanize.downcase}" unless options.key?(:desc)
<del> options[:aliases] = Rails::Generators.aliases[name] unless options.key?(:aliases)
<del> options[:default] = Rails::Generators.options[name] unless options.key?(:default)
<add> options[:aliases] = default_aliases_for_option(name) unless options.key?(:aliases)
<add> options[:default] = default_value_for_option(name) unless options.key?(:default)
<ide> super(name, options)
<ide> end
<ide>
<ide> def self.generator_name
<ide> end
<ide> end
<ide>
<add> # Return the default value for the option name given doing a lookup in
<add> # Rails::Generators.options.
<add> #
<add> def self.default_value_for_option(option)
<add> options = Rails::Generators.options
<add>
<add> if options[generator_name.to_sym].key?(option)
<add> options[generator_name.to_sym][option]
<add> elsif options[base_name.to_sym].key?(option)
<add> options[base_name.to_sym][option]
<add> else
<add> options[:rails][option]
<add> end
<add> end
<add>
<add> # Return default aliases for the option name given doing a lookup in
<add> # Rails::Generators.aliases.
<add> #
<add> def self.default_aliases_for_option(option)
<add> aliases = Rails::Generators.aliases
<add>
<add> if aliases[generator_name.to_sym].key?(option)
<add> aliases[generator_name.to_sym][option]
<add> elsif aliases[base_name.to_sym].key?(option)
<add> aliases[base_name.to_sym][option]
<add> else
<add> aliases[:rails][option]
<add> end
<add> end
<add>
<ide> # Keep hooks configuration that are used on prepare_for_invocation.
<ide> #
<ide> def self.hooks #:nodoc:
<ide><path>railties/lib/generators/rails/app/templates/config/environment.rb
<ide>
<ide> # Configure generators default options.
<ide> config.generators do |g|
<del> # Scaffold configuration
<del> g.helper = true
<del> g.layout = true
<del> g.stylesheets = true
<add> g.rails do |r|
<add> r.helper = true
<add> r.stylesheets = true
<add> end
<ide>
<del> # ORM configuration
<del> g.orm = :active_record
<del> g.timestamps = true
<add> g.orm :active_record do |ar|
<add> ar.migration = true
<add> ar.timestamps = true
<add> end
<ide>
<del> # Template engine configuration
<del> g.template_engine = :erb
<add> g.template_engine :erb do |erb|
<add> erb.layout = true
<add> end
<ide>
<del> # Test framework configuration
<del> g.test_framework = :test_unit
<del> g.fixtures = true
<add> g.test_framework :test_unit do |tu|
<add> tu.fixtures = true
<add> end
<ide> end
<ide> end
<ide><path>railties/lib/generators/rails/plugin/plugin_generator.rb
<ide> module Rails
<ide> module Generators
<ide> class PluginGenerator < NamedBase
<del> class_option :tasks, :type => :boolean, :aliases => "-t", :default => false,
<del> :desc => "When supplied creates tasks base files."
<add> class_option :tasks, :desc => "When supplied creates tasks base files."
<ide>
<ide> check_class_collision
<ide>
<ide> def create_tasks_files
<ide> directory 'tasks', plugin_dir('tasks')
<ide> end
<ide>
<del> hook_for :generator, :aliases => "-g", :type => :boolean do |instance, generator|
<add> hook_for :generator do |instance, generator|
<ide> instance.inside_with_padding instance.send(:plugin_dir) do
<ide> instance.invoke generator, [ instance.name ], :namespace => false
<ide> end
<ide><path>railties/lib/initializer.rb
<ide> def self.run(initializer = nil, config = nil)
<ide> Initializer.default.add :initialize_generators do
<ide> if defined?(Rails::Generators)
<ide> Rails::Generators.no_color! unless config.generators.colorize_logging
<del> Rails::Generators.aliases.merge! config.generators.aliases
<del> Rails::Generators.options.merge! config.generators.options
<add> Rails::Generators.aliases.deep_merge! config.generators.aliases
<add> Rails::Generators.options.deep_merge! config.generators.options
<ide> end
<ide> end
<ide> end
<ide><path>railties/lib/rails/configuration.rb
<ide> def reload_plugins?
<ide>
<ide> # Holds generators configuration:
<ide> #
<del> # config.generators.orm = :datamapper
<del> # config.generators.test_framework = :rspec
<del> # config.generators.template_engine = :haml
<del> #
<del> # A block can also be given for less verbose configuration:
<del> #
<ide> # config.generators do |g|
<del> # g.orm = :datamapper
<del> # g.test_framework = :datamapper
<del> # g.template_engine = :haml
<del> # end
<add> # g.orm :datamapper do |dm|
<add> # dm.migration = true
<add> # dm.timestamps = false
<add> # end
<ide> #
<del> # You can also configure/override aliases:
<add> # g.template_engine = :haml
<add> # g.test_framework = :datamapper
<ide> #
<del> # config.generators.aliases = :test_framework => "-w"
<add> # g.plugin do |p|
<add> # p.aliases :generator => "-g"
<add> # p.generator = true
<add> # end
<add> # end
<ide> #
<del> # Finally, to disable color in console, do:
<add> # If you want to disable color in console, do:
<ide> #
<ide> # config.generators.colorize_logging = false
<ide> #
<ide> def generators
<ide> end
<ide>
<ide> class Generators #:nodoc:
<del> attr_accessor :aliases, :options, :colorize_logging
<add> attr_reader :aliases, :options
<add> attr_accessor :colorize_logging
<ide>
<ide> def initialize
<del> @aliases, @options, @colorize_logging = {}, {}, true
<add> @namespace, @colorize_logging = :rails, true
<add> @aliases = Hash.new { |h,k| h[k] = {} }
<add> @options = Hash.new { |h,k| h[k] = {} }
<ide> end
<ide>
<del> def method_missing(method, *args, &block)
<del> method = method.to_s
<del> if method.gsub!(/=$/, '')
<del> @options[method.to_sym] = args.first
<del> else
<del> super(method.to_sym, *args, &block)
<add> def aliases(another=nil)
<add> @aliases[@namespace].merge!(another) if another
<add> @aliases
<add> end
<add> alias :aliases= :aliases
<add>
<add> def method_missing(method, *args)
<add> sanitized_method = method.to_s.sub(/=$/, '').to_sym
<add> @options[@namespace][sanitized_method] = args.first if args.first
<add>
<add> if block_given?
<add> previous_namespace = @namespace
<add> @namespace = (args.first || sanitized_method).to_sym
<add> yield self
<add> @namespace = previous_namespace
<ide> end
<ide> end
<ide> end
<ide><path>railties/lib/vendor/thor-0.11.1/lib/thor/parser/option.rb
<ide> def usage(padding=0)
<ide> end
<ide> end
<ide>
<del> def input_required?
<del> type != :boolean
<add> # Allow some type predicates as: boolean?, string? and etc.
<add> #
<add> def method_missing(method, *args, &block)
<add> given = method.to_s.sub(/\?$/, '').to_sym
<add> if valid_type?(given)
<add> self.type == given
<add> else
<add> super
<add> end
<ide> end
<ide>
<ide> protected
<ide>
<ide> def validate!
<del> raise ArgumentError, "An option cannot be boolean and required." if type == :boolean && required?
<add> raise ArgumentError, "An option cannot be boolean and required." if boolean? && required?
<ide> end
<ide>
<ide> def valid_type?(type)
<ide><path>railties/lib/vendor/thor-0.11.1/lib/thor/parser/options.rb
<ide> def parse_boolean(switch)
<ide> # Parse the value at the peek analyzing if it requires an input or not.
<ide> #
<ide> def parse_peek(switch, option)
<del> if option.input_required?
<del> return nil if no_or_skip?(switch)
<del> raise MalformattedArgumentError, "no value provided for option '#{switch}'" unless current_is_value?
<add> unless current_is_value?
<add> if option.boolean?
<add> # No problem for boolean types
<add> elsif no_or_skip?(switch)
<add> return nil # User set value to nil
<add> elsif option.string? && !option.required?
<add> return option.human_name # Return the option name
<add> else
<add> raise MalformattedArgumentError, "no value provided for option '#{switch}'"
<add> end
<ide> end
<ide>
<ide> @non_assigned_required.delete(option)
<ide><path>railties/test/initializer_test.rb
<ide> def test_generators_default_values
<ide> assert_equal({}, @configuration.generators.options)
<ide> end
<ide>
<del> def test_generators_set_options
<add> def test_generators_set_rails_options
<ide> @configuration.generators.orm = :datamapper
<ide> @configuration.generators.test_framework = :rspec
<del> assert_equal({ :orm => :datamapper, :test_framework => :rspec }, @configuration.generators.options)
<add> expected = { :rails => { :orm => :datamapper, :test_framework => :rspec } }
<add> assert_equal expected, @configuration.generators.options
<ide> end
<ide>
<del> def test_generators_set_aliases
<add> def test_generators_set_rails_aliases
<ide> @configuration.generators.aliases = { :test_framework => "-w" }
<del> assert_equal({ :test_framework => "-w" }, @configuration.generators.aliases)
<add> expected = { :rails => { :test_framework => "-w" } }
<add> assert_equal expected, @configuration.generators.aliases
<ide> end
<ide>
<del> def test_generators_with_block
<add> def test_generators_with_block_for_rails_configuration
<ide> @configuration.generators do |g|
<ide> g.orm = :datamapper
<ide> g.test_framework = :rspec
<ide> end
<del> assert_equal({ :orm => :datamapper, :test_framework => :rspec }, @configuration.generators.options)
<add> expected = { :rails => { :orm => :datamapper, :test_framework => :rspec } }
<add> assert_equal expected, @configuration.generators.options
<ide> end
<ide>
<ide> def test_generators_aliases_and_options_on_initialization
<del> @configuration.generators.aliases = { :test_framework => "-w" }
<del> @configuration.generators.orm = :datamapper
<del> @configuration.generators.test_framework = :rspec
<add> @configuration.generators.aliases :test_framework => "-w"
<add> @configuration.generators.orm :datamapper
<add> @configuration.generators.test_framework :rspec
<ide>
<del> RAILS_ENV.replace "generators"
<ide> @initializer.run(:initialize_generators)
<ide>
<del> assert_equal :rspec, Rails::Generators.options[:test_framework]
<del> assert_equal "-w", Rails::Generators.aliases[:test_framework]
<add> assert_equal :rspec, Rails::Generators.options[:rails][:test_framework]
<add> assert_equal "-w", Rails::Generators.aliases[:rails][:test_framework]
<ide> end
<ide>
<ide> def test_generators_no_color_on_initialization
<ide> @configuration.generators.colorize_logging = false
<del> RAILS_ENV.replace "generators"
<ide> @initializer.run(:initialize_generators)
<ide> assert_equal Thor::Base.shell, Thor::Shell::Basic
<ide> end
<ide>
<del> def test_generators_raise_no_method_error_non_setters
<del> assert_raise NoMethodError do
<del> @configuration.generators.foo
<del> end
<add> def test_generators_with_namespaced_blocks_for_options_and_aliases
<add> namespaced_configuration!
<add> expected = {
<add> :rails => { :orm => :datamapper },
<add> :plugin => { :generator => true },
<add> :datamapper => { :migrations => true }
<add> }
<add> assert_equal expected, @configuration.generators.options
<add> assert_equal({ :plugin => { :generator => "-g" } }, @configuration.generators.aliases)
<add> end
<add>
<add> def test_generators_with_namespaced_configuration_are_deep_merged
<add> namespaced_configuration!
<add> @initializer.run(:initialize_generators)
<add> assert Rails::Generators.aliases.size >= 1
<add> assert Rails::Generators.options.size >= 1
<ide> end
<ide>
<ide> protected
<ide>
<add> def namespaced_configuration!
<add> @configuration.generators do |g|
<add> g.orm :datamapper do |dm|
<add> dm.migrations = true
<add> end
<add>
<add> g.plugin do |p|
<add> p.aliases = { :generator => "-g" }
<add> p.generator = true
<add> end
<add> end
<add> end
<add>
<ide> def teardown
<ide> Rails::Generators.clear_aliases!
<ide> Rails::Generators.clear_options! | 9 |
Text | Text | add link to patchwelcome and help wanted issues | 924b7ce825962bfe4c16e02eb411c7f66ee75a55 | <ide><path>CONTRIBUTING.md
<ide> More information on how to contribute to this and other jQuery organization proj
<ide>
<ide> When opening a pull request, you'll be asked to sign our Contributor License Agreement. Both the Corporate and Individual agreements can be [previewed on GitHub](https://github.com/openjs-foundation/easycla).
<ide>
<add>If you're looking for some good issues to start with, [here are some issues labeled "help wanted" or "patch welcome"](https://github.com/jquery/jquery/issues?q=is%3Aissue+label%3A%22help+wanted%22%2C%22Patch+Welcome%22).
<add>
<ide> ## Questions and Discussion
<ide>
<ide> ### Forum and IRC | 1 |
Text | Text | fix typo in docs | f394b1d77614d33e85c93ecb10f0a6676538b2e7 | <ide><path>docs/api/v1.22.md
<ide> Create a container
<ide> `"BlkioDeviceWriteBps": [{"Path": "/dev/sda", "Rate": "1024"}]"`
<ide> - **BlkioDeviceReadIOps** - Limit read rate (IO per second) from a device in the form of: `"BlkioDeviceReadIOps": [{"Path": "device_path", "Rate": rate}]`, for example:
<ide> `"BlkioDeviceReadIOps": [{"Path": "/dev/sda", "Rate": "1000"}]`
<del> - **BlkioDeviceWiiteIOps** - Limit write rate (IO per second) to a device in the form of: `"BlkioDeviceWriteIOps": [{"Path": "device_path", "Rate": rate}]`, for example:
<add> - **BlkioDeviceWriteIOps** - Limit write rate (IO per second) to a device in the form of: `"BlkioDeviceWriteIOps": [{"Path": "device_path", "Rate": rate}]`, for example:
<ide> `"BlkioDeviceWriteIOps": [{"Path": "/dev/sda", "Rate": "1000"}]`
<ide> - **MemorySwappiness** - Tune a container's memory swappiness behavior. Accepts an integer between 0 and 100.
<ide> - **OomKillDisable** - Boolean value, whether to disable OOM Killer for the container or not.
<ide><path>docs/api/v1.23.md
<ide> Create a container
<ide> `"BlkioDeviceWriteBps": [{"Path": "/dev/sda", "Rate": "1024"}]"`
<ide> - **BlkioDeviceReadIOps** - Limit read rate (IO per second) from a device in the form of: `"BlkioDeviceReadIOps": [{"Path": "device_path", "Rate": rate}]`, for example:
<ide> `"BlkioDeviceReadIOps": [{"Path": "/dev/sda", "Rate": "1000"}]`
<del> - **BlkioDeviceWiiteIOps** - Limit write rate (IO per second) to a device in the form of: `"BlkioDeviceWriteIOps": [{"Path": "device_path", "Rate": rate}]`, for example:
<add> - **BlkioDeviceWriteIOps** - Limit write rate (IO per second) to a device in the form of: `"BlkioDeviceWriteIOps": [{"Path": "device_path", "Rate": rate}]`, for example:
<ide> `"BlkioDeviceWriteIOps": [{"Path": "/dev/sda", "Rate": "1000"}]`
<ide> - **MemorySwappiness** - Tune a container's memory swappiness behavior. Accepts an integer between 0 and 100.
<ide> - **OomKillDisable** - Boolean value, whether to disable OOM Killer for the container or not.
<ide><path>docs/api/v1.24.md
<ide> Create a container
<ide> `"BlkioDeviceWriteBps": [{"Path": "/dev/sda", "Rate": "1024"}]"`
<ide> - **BlkioDeviceReadIOps** - Limit read rate (IO per second) from a device in the form of: `"BlkioDeviceReadIOps": [{"Path": "device_path", "Rate": rate}]`, for example:
<ide> `"BlkioDeviceReadIOps": [{"Path": "/dev/sda", "Rate": "1000"}]`
<del> - **BlkioDeviceWiiteIOps** - Limit write rate (IO per second) to a device in the form of: `"BlkioDeviceWriteIOps": [{"Path": "device_path", "Rate": rate}]`, for example:
<add> - **BlkioDeviceWriteIOps** - Limit write rate (IO per second) to a device in the form of: `"BlkioDeviceWriteIOps": [{"Path": "device_path", "Rate": rate}]`, for example:
<ide> `"BlkioDeviceWriteIOps": [{"Path": "/dev/sda", "Rate": "1000"}]`
<ide> - **MemorySwappiness** - Tune a container's memory swappiness behavior. Accepts an integer between 0 and 100.
<ide> - **OomKillDisable** - Boolean value, whether to disable OOM Killer for the container or not. | 3 |
Javascript | Javascript | improve normalize encoding performance | 341770fedf77ff5b8e0c646070029152b58fc746 | <ide><path>benchmark/buffers/buffer-normalize-encoding.js
<add>'use strict';
<add>
<add>const common = require('../common.js');
<add>
<add>const bench = common.createBenchmark(main, {
<add> encoding: [
<add> 'ascii',
<add> 'ASCII',
<add> 'base64',
<add> 'BASE64',
<add> 'binary',
<add> 'BINARY',
<add> 'hex',
<add> 'HEX',
<add> 'latin1',
<add> 'LATIN1',
<add> 'ucs-2',
<add> 'UCS-2',
<add> 'ucs2',
<add> 'UCS2',
<add> 'utf-16le',
<add> 'UTF-16LE',
<add> 'utf-8',
<add> 'UTF-8',
<add> 'utf16le',
<add> 'UTF16LE',
<add> 'utf8',
<add> 'UTF8'
<add> ],
<add> n: [1e6]
<add>}, {
<add> flags: ['--expose-internals']
<add>});
<add>
<add>function main({ encoding, n }) {
<add> const { normalizeEncoding } = require('internal/util');
<add>
<add> bench.start();
<add> for (var i = 0; i < n; i++) {
<add> normalizeEncoding(encoding);
<add> }
<add> bench.end(n);
<add>}
<ide><path>lib/buffer.js
<ide> function assertSize(size) {
<ide> err = new errors.RangeError('ERR_INVALID_OPT_VALUE', 'size', size);
<ide> }
<ide>
<del> if (err) {
<add> if (err !== null) {
<ide> Error.captureStackTrace(err, assertSize);
<ide> throw err;
<ide> }
<ide> Buffer.compare = function compare(a, b) {
<ide>
<ide> Buffer.isEncoding = function isEncoding(encoding) {
<ide> return typeof encoding === 'string' &&
<del> typeof normalizeEncoding(encoding) === 'string';
<add> normalizeEncoding(encoding) !== undefined;
<ide> };
<ide> Buffer[kIsEncodingSymbol] = Buffer.isEncoding;
<ide>
<ide><path>lib/internal/util.js
<ide> function assertCrypto() {
<ide> throw new errors.Error('ERR_NO_CRYPTO');
<ide> }
<ide>
<del>// The loop should only run at most twice, retrying with lowercased enc
<del>// if there is no match in the first pass.
<del>// We use a loop instead of branching to retry with a helper
<del>// function in order to avoid the performance hit.
<ide> // Return undefined if there is no match.
<add>// Move the "slow cases" to a separate function to make sure this function gets
<add>// inlined properly. That prioritizes the common case.
<ide> function normalizeEncoding(enc) {
<del> if (enc == null || enc === '') return 'utf8';
<del> let retried;
<del> while (true) {
<del> switch (enc) {
<del> case 'utf8':
<del> case 'utf-8':
<del> return 'utf8';
<del> case 'ucs2':
<del> case 'ucs-2':
<del> case 'utf16le':
<del> case 'utf-16le':
<add> if (enc == null || enc === 'utf8' || enc === 'utf-8') return 'utf8';
<add> return slowCases(enc);
<add>}
<add>
<add>function slowCases(enc) {
<add> switch (enc.length) {
<add> case 4:
<add> if (enc === 'UTF8') return 'utf8';
<add> if (enc === 'ucs2' || enc === 'UCS2') return 'utf16le';
<add> enc = `${enc}`.toLowerCase();
<add> if (enc === 'utf8') return 'utf8';
<add> if (enc === 'ucs2' || enc === 'UCS2') return 'utf16le';
<add> break;
<add> case 3:
<add> if (enc === 'hex' || enc === 'HEX' || `${enc}`.toLowerCase() === 'hex')
<add> return 'hex';
<add> break;
<add> case 5:
<add> if (enc === 'ascii') return 'ascii';
<add> if (enc === 'ucs-2') return 'utf16le';
<add> if (enc === 'UTF-8') return 'utf8';
<add> if (enc === 'ASCII') return 'ascii';
<add> if (enc === 'UCS-2') return 'utf16le';
<add> enc = `${enc}`.toLowerCase();
<add> if (enc === 'utf-8') return 'utf8';
<add> if (enc === 'ascii') return 'ascii';
<add> if (enc === 'usc-2') return 'utf16le';
<add> break;
<add> case 6:
<add> if (enc === 'base64') return 'base64';
<add> if (enc === 'latin1' || enc === 'binary') return 'latin1';
<add> if (enc === 'BASE64') return 'base64';
<add> if (enc === 'LATIN1' || enc === 'BINARY') return 'latin1';
<add> enc = `${enc}`.toLowerCase();
<add> if (enc === 'base64') return 'base64';
<add> if (enc === 'latin1' || enc === 'binary') return 'latin1';
<add> break;
<add> case 7:
<add> if (enc === 'utf16le' || enc === 'UTF16LE' ||
<add> `${enc}`.toLowerCase() === 'utf16le')
<ide> return 'utf16le';
<del> case 'latin1':
<del> case 'binary':
<del> return 'latin1';
<del> case 'base64':
<del> case 'ascii':
<del> case 'hex':
<del> return enc;
<del> default:
<del> if (retried) return; // undefined
<del> enc = ('' + enc).toLowerCase();
<del> retried = true;
<del> }
<add> break;
<add> case 8:
<add> if (enc === 'utf-16le' || enc === 'UTF-16LE' ||
<add> `${enc}`.toLowerCase() === 'utf-16le')
<add> return 'utf16le';
<add> break;
<add> default:
<add> if (enc === '') return 'utf8';
<ide> }
<ide> }
<ide>
<ide><path>lib/string_decoder.js
<ide> const kNativeDecoder = Symbol('kNativeDecoder');
<ide> // modules monkey-patch it to support additional encodings
<ide> function normalizeEncoding(enc) {
<ide> const nenc = internalUtil.normalizeEncoding(enc);
<del> if (typeof nenc !== 'string' &&
<del> (Buffer.isEncoding === isEncoding || !Buffer.isEncoding(enc)))
<del> throw new errors.TypeError('ERR_UNKNOWN_ENCODING', enc);
<del> return nenc || enc;
<add> if (nenc === undefined) {
<add> if (Buffer.isEncoding === isEncoding || !Buffer.isEncoding(enc))
<add> throw new errors.TypeError('ERR_UNKNOWN_ENCODING', enc);
<add> return enc;
<add> }
<add> return nenc;
<ide> }
<ide>
<ide> const encodingsMap = {}; | 4 |
PHP | PHP | add tests for templatevars & textarea widget | 2cedf1a1b2e7840b6cc50b9c0d4374961d79c800 | <ide><path>tests/TestCase/View/Widget/TextareaWidgetTest.php
<ide> public function testRenderWithValue()
<ide> ];
<ide> $this->assertHtml($expected, $result);
<ide> }
<add>
<add> /**
<add> * Ensure templateVars option is hooked up.
<add> *
<add> * @return void
<add> */
<add> public function testRenderTemplateVars()
<add> {
<add> $this->templates->add([
<add> 'textarea' => '<textarea custom="{{custom}}" name="{{name}}"{{attrs}}>{{value}}</textarea>',
<add> ]);
<add>
<add> $input = new TextareaWidget($this->templates);
<add> $data = [
<add> 'templateVars' => ['custom' => 'value'],
<add> 'name' => 'comment',
<add> 'val' => 'body'
<add> ];
<add> $result = $input->render($data, $this->context);
<add> $expected = [
<add> 'textarea' => ['name' => 'comment', 'rows' => 5, 'custom' => 'value'],
<add> 'body',
<add> '/textarea',
<add> ];
<add> $this->assertHtml($expected, $result);
<add> }
<ide> } | 1 |
Text | Text | fix 2 more entries | cbec8c1a890c809f104d826d970f41a4498e38fb | <ide><path>docs/cookbook/11-dom-event-listeners.md
<ide> var Box = React.createClass({
<ide> this.setState({windowWidth: window.innerWidth});
<ide> },
<ide> componentDidMount: function() {
<del> window.addEventListener("resize", this.handleResize);
<add> window.addEventListener('resize', this.handleResize);
<ide> },
<ide> componentWillUnmount: function() {
<del> window.removeEventListener("resize", this.handleResize);
<add> window.removeEventListener('resize', this.handleResize);
<ide> },
<ide> render: function() {
<ide> return <div>Current window width: {this.state.windowWidth}</div>;
<ide><path>docs/cookbook/12-initial-ajax.md
<ide> var UserGist = React.createClass({
<ide> });
<ide>
<ide> React.renderComponent(
<del> <UserGist source="https://api.github.com/users/octocat/gists" />, mountNode
<add> <UserGist source="https://api.github.com/users/octocat/gists" />,
<add> mountNode
<ide> );
<ide> ``` | 2 |
PHP | PHP | update deprecation message | eb888b469d07e4514edd6ab04197caa875b2ff5e | <ide><path>src/View/ViewVarsTrait.php
<ide> trait ViewVarsTrait
<ide> * Variables for the view
<ide> *
<ide> * @var array
<del> * @deprecated 3.7.0 Use `$this->viewBuilder()->setVar()/getVar()` instead.
<add> * @deprecated 3.7.0 Use `$this->set()` instead.
<ide> */
<ide> public $viewVars = [];
<ide> | 1 |
Ruby | Ruby | add broken test | 2ca6f57f85fe06932f64685bea2687fec7d6c3d3 | <ide><path>actionpack/test/controller/routing_test.rb
<ide> def test_default_route_should_work_with_action_but_no_id
<ide> o = {:controller => 'accounts', :action => 'list_all'}
<ide> assert_equal '/accounts/list_all', default_route.generate(o, o, {})
<ide> end
<add>
<add> def test_default_route_should_escape_pluses_in_id
<add> expected = {:controller => 'accounts', :action => 'show', :id => 'hello world'}
<add> assert_equal expected, default_route.recognize('/accounts/show/hello+world')
<add> end
<ide>
<ide> def test_matches_controller_and_action
<ide> # requirement_for should only be called for the action and controller _once_ | 1 |
PHP | PHP | fix failing tests around prefixes | 12c5f5bb72dc4d55161ccb242b918ef90b26788a | <ide><path>src/Routing/Route/Route.php
<ide> public function getName() {
<ide> return $this->_name;
<ide> }
<ide> $name = '';
<del> if (isset($this->defaults['plugin'])) {
<del> $name = $this->defaults['plugin'] . '.';
<del> }
<del> if (strpos($this->template, ':plugin') !== false) {
<del> $name = '_plugin.';
<del> }
<del> foreach (array('controller', 'action') as $key) {
<del> if ($key === 'action') {
<del> $name .= ':';
<del> }
<del> $var = ':' . $key;
<del> if (strpos($this->template, $var) !== false) {
<del> $name .= '_' . $key;
<add> $keys = [
<add> 'prefix' => ':',
<add> 'plugin' => '.',
<add> 'controller' => ':',
<add> 'action' => ''
<add> ];
<add> foreach ($keys as $key => $glue) {
<add> $value = null;
<add> if (strpos($this->template, ':' . $key) !== false) {
<add> $value = '_' . $key;
<ide> } elseif (isset($this->defaults[$key])) {
<del> $name .= $this->defaults[$key];
<add> $value = $this->defaults[$key];
<add> }
<add>
<add> if ($value === null) {
<add> continue;
<add> }
<add> if (is_bool($value)) {
<add> $value = $value ? '1' : '0';
<ide> }
<add> $name .= $value . $glue;
<ide> }
<ide> return $this->_name = strtolower($name);
<ide> }
<ide><path>src/Routing/RouteCollection.php
<ide> public function parse($url) {
<ide> */
<ide> protected function _getNames($url) {
<ide> $plugin = false;
<del> if (isset($url['plugin'])) {
<add> if (isset($url['plugin']) && $url['plugin'] !== false) {
<ide> $plugin = strtolower($url['plugin']);
<ide> }
<add> $prefix = false;
<add> if (isset($url['prefix']) && $url['prefix'] !== false) {
<add> $prefix = strtolower($url['prefix']);
<add> }
<ide> $controller = strtolower($url['controller']);
<ide> $action = strtolower($url['action']);
<ide>
<del> $fallbacks = [
<add> $names = [
<ide> "${controller}:${action}",
<ide> "${controller}:_action",
<ide> "_controller:${action}",
<ide> "_controller:_action"
<ide> ];
<del> if ($plugin) {
<del> $fallbacks = [
<add>
<add> // No prefix, no plugin
<add> if ($prefix === false && $plugin === false) {
<add> return $names;
<add> }
<add>
<add> // Only a plugin
<add> if ($prefix === false) {
<add> return [
<ide> "${plugin}.${controller}:${action}",
<ide> "${plugin}.${controller}:_action",
<ide> "${plugin}._controller:${action}",
<ide> "${plugin}._controller:_action",
<ide> "_plugin.${controller}:${action}",
<add> "_plugin.${controller}:_action",
<ide> "_plugin._controller:${action}",
<ide> "_plugin._controller:_action",
<del> "_controller:_action"
<ide> ];
<ide> }
<del> return $fallbacks;
<add>
<add> // Only a prefix
<add> if ($plugin === false) {
<add> return [
<add> "${prefix}:${controller}:${action}",
<add> "${prefix}:${controller}:_action",
<add> "${prefix}:_controller:${action}",
<add> "${prefix}:_controller:_action",
<add> "_prefix:${controller}:${action}",
<add> "_prefix:${controller}:_action",
<add> "_prefix:_controller:${action}",
<add> "_prefix:_controller:_action"
<add> ];
<add> }
<add>
<add> // Prefix and plugin has the most options
<add> // as there are 4 factors.
<add> return [
<add> "${prefix}:${plugin}.${controller}:${action}",
<add> "${prefix}:${plugin}.${controller}:_action",
<add> "${prefix}:${plugin}._controller:${action}",
<add> "${prefix}:${plugin}._controller:_action",
<add> "${prefix}:_plugin.${controller}:${action}",
<add> "${prefix}:_plugin.${controller}:_action",
<add> "${prefix}:_plugin._controller:${action}",
<add> "${prefix}:_plugin._controller:_action",
<add> "_prefix:${plugin}.${controller}:${action}",
<add> "_prefix:${plugin}.${controller}:_action",
<add> "_prefix:${plugin}._controller:${action}",
<add> "_prefix:${plugin}._controller:_action",
<add> "_prefix:_plugin.${controller}:${action}",
<add> "_prefix:_plugin.${controller}:_action",
<add> "_prefix:_plugin._controller:${action}",
<add> "_prefix:_plugin._controller:_action",
<add> ];
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/Controller/ControllerTest.php
<ide> public function testInvokeActionBaseMethods() {
<ide> $Controller->invokeAction();
<ide> }
<ide>
<del>/**
<del> * test invoking controller methods.
<del> *
<del> * @expectedException \Cake\Controller\Error\PrivateActionException
<del> * @expectedExceptionMessage Private Action TestController::admin_add() is not directly accessible.
<del> * @return void
<del> */
<del> public function testInvokeActionPrefixProtection() {
<del> Configure::write('Routing.prefixes', array('admin'));
<del> Router::reload();
<del> Router::connect('/admin/:controller/:action/*', array('prefix' => 'admin'));
<del>
<del> $url = new Request('test/admin_add/');
<del> $url->addParams(array('controller' => 'test_controller', 'action' => 'admin_add'));
<del> $response = $this->getMock('Cake\Network\Response');
<del>
<del> $Controller = new TestController($url, $response);
<del> $Controller->invokeAction();
<del> }
<del>
<ide> /**
<ide> * test invoking controller methods.
<ide> *
<ide><path>tests/TestCase/Routing/Route/RouteTest.php
<ide>
<ide> /**
<ide> * Test case for Route
<del> *
<ide> */
<ide> class RouteTest extends TestCase {
<ide>
<ide> public function testGetNamePlugins() {
<ide> $this->assertEquals('asset.assets:get', $route->getName());
<ide> }
<ide>
<add>/**
<add> * Test getName() with prefixes.
<add> *
<add> * @return void
<add> */
<add> public function testGetNamePrefix() {
<add> $route = new Route(
<add> '/admin/:controller/:action',
<add> array('prefix' => 'admin')
<add> );
<add> $this->assertEquals('admin:_controller:_action', $route->getName());
<add>
<add> $route = new Route(
<add> '/:prefix/assets/:action',
<add> array('controller' => 'assets')
<add> );
<add> $this->assertEquals('_prefix:assets:_action', $route->getName());
<add>
<add> $route = new Route(
<add> '/admin/assets/get',
<add> array('prefix' => 'admin', 'plugin' => 'asset', 'controller' => 'assets', 'action' => 'get')
<add> );
<add> $this->assertEquals('admin:asset.assets:get', $route->getName());
<add>
<add> $route = new Route(
<add> '/:prefix/:plugin/:controller/:action/*',
<add> []
<add> );
<add> $this->assertEquals('_prefix:_plugin._controller:_action', $route->getName());
<add> }
<add>
<ide> /**
<ide> * test that utf-8 patterns work for :section
<ide> *
<ide><path>tests/TestCase/Routing/RouteBuilderTest.php
<ide> public function testResourcesNested() {
<ide> * @return void
<ide> */
<ide> public function testFallbacks() {
<del> $routes = new ScopedRouteCollection('/api', ['prefix' => 'api']);
<add> $routes = new RouteBuilder($this->collection, '/api', ['prefix' => 'api']);
<ide> $routes->fallbacks();
<ide>
<del> $all = $routes->routes();
<add> $all = $this->collection->routes();
<ide> $this->assertEquals('/api/:controller', $all[0]->template);
<ide> $this->assertEquals('/api/:controller/:action/*', $all[1]->template);
<ide> }
<ide><path>tests/TestCase/Routing/RouterTest.php
<ide> public function testUrlWritingWithPrefixes() {
<ide> $expected = '/company/users/login';
<ide> $this->assertEquals($expected, $result);
<ide>
<del> $result = Router::url(array('controller' => 'users', 'action' => 'login', 'prefix' => 'company'));
<del> $expected = '/company/users/login';
<del> $this->assertEquals($expected, $result);
<del>
<ide> $request = new Request();
<ide> Router::setRequestInfo(
<ide> $request->addParams(array( | 6 |
Ruby | Ruby | use different variable name | 73956a1b77af135600888750148cc303b2d999f1 | <ide><path>Library/Contributions/cmd/brew-test-bot.rb
<ide> def formula formula
<ide>
<ide> installed_gcc = false
<ide> begin
<del> dependencies = formula_object.stable.deps
<add> deps = formula_object.stable.deps
<ide> if formula_object.devel && !ARGV.include?('--HEAD')
<del> dependencies += formula_object.devel.deps
<add> deps += formula_object.devel.deps
<ide> end
<del> dependencies.each {|f| CompilerSelector.new(f.to_formula).compiler }
<add> deps.each {|f| CompilerSelector.new(f.to_formula).compiler }
<ide>
<ide> CompilerSelector.new(formula_object).compiler
<ide> rescue CompilerSelectionError => e | 1 |
Javascript | Javascript | fix title [ci skip] | 2f83848b1fd75371278a7c6060b7d9ca619a9e07 | <ide><path>website/src/components/title.js
<ide> const Title = ({
<ide> children,
<ide> ...props
<ide> }) => {
<del> const hasApiDetails = Object.values(apiDetails).some(v => v)
<add> const hasApiDetails = Object.values(apiDetails || {}).some(v => v)
<ide> const metaIconProps = { className: classes.metaIcon, width: 18 }
<ide> return (
<ide> <header className={classes.root}> | 1 |
Javascript | Javascript | use common.js to check platform | f6b1eb2ec4addc3d8d7da3839b89614eeaae6e42 | <ide><path>test/parallel/test-fs-readfile-error.js
<ide> const path = require('path');
<ide>
<ide> // `fs.readFile('/')` does not fail on FreeBSD, because you can open and read
<ide> // the directory there.
<del>if (process.platform === 'freebsd') {
<add>if (common.isFreeBSD) {
<ide> common.skip('platform not supported.');
<ide> return;
<ide> } | 1 |
Javascript | Javascript | create plnkr examples with correct angular version | db02008fe274410d2b8e2715fa4a3c8c9b2ce809 | <ide><path>docs/app/src/examples.js
<ide> angular.module('examples', [])
<ide> filePromises.push($http.get(exampleFolder + '/' + filename, { transformResponse: [] })
<ide> .then(function(response) {
<ide>
<del> // The manifests provide the production index file but Plunkr wants
<del> // a straight index.html
<del> if (filename === 'index-production.html') {
<add> // Plunkr needs an index file that's simply named index.html
<add> if (filename === 'index-plnkr.html') {
<ide> filename = 'index.html';
<ide> }
<ide>
<ide><path>docs/config/index.js
<ide> module.exports = new Package('angularjs', [
<ide> .factory(require('./services/deployments/default'))
<ide> .factory(require('./services/deployments/jquery'))
<ide> .factory(require('./services/deployments/production'))
<add>.factory(require('./services/deployments/plnkr'))
<ide>
<ide> .factory(require('./inline-tag-defs/type'))
<ide>
<ide> module.exports = new Package('angularjs', [
<ide> generateProtractorTestsProcessor,
<ide> generateExamplesProcessor,
<ide> debugDeployment, defaultDeployment,
<del> jqueryDeployment, productionDeployment) {
<add> jqueryDeployment, productionDeployment,
<add> plnkrDeployment) {
<ide>
<ide> generateIndexPagesProcessor.deployments = [
<ide> debugDeployment,
<ide> module.exports = new Package('angularjs', [
<ide> debugDeployment,
<ide> defaultDeployment,
<ide> jqueryDeployment,
<del> productionDeployment
<add> productionDeployment,
<add> plnkrDeployment
<ide> ];
<ide> })
<ide>
<ide><path>docs/config/services/deployments/plnkr.js
<add>'use strict';
<add>// Special deployment that is only used for the examples on plnkr.
<add>// While the embedded examples use the Angular files relative the docs folder,
<add>// plnkr uses the CDN urls, and needs to switch between Google CDN for tagged versions
<add>// and the code.angularjs.org server for the snapshot (master) version.
<add>
<add>var versionInfo = require('../../../../lib/versions/version-info');
<add>var isSnapshot = versionInfo.currentVersion.isSnapshot;
<add>
<add>var cdnUrl = isSnapshot ?
<add> '//code.angularjs.org/snapshot' :
<add> '//ajax.googleapis.com/ajax/libs/angularjs/' + versionInfo.cdnVersion;
<add>
<add>module.exports = function plnkrDeployment(getVersion) {
<add> return {
<add> name: 'plnkr',
<add> examples: {
<add> commonFiles: {
<add> scripts: [cdnUrl + '/angular.min.js']
<add> },
<add> dependencyPath: cdnUrl + '/'
<add> },
<add> scripts: [
<add> cdnUrl + '/angular.min.js',
<add> cdnUrl + '/angular-resource.min.js',
<add> cdnUrl + '/angular-route.min.js',
<add> cdnUrl + '/angular-cookies.min.js',
<add> cdnUrl + '/angular-sanitize.min.js',
<add> cdnUrl + '/angular-touch.min.js',
<add> cdnUrl + '/angular-animate.min.js',
<add> 'components/marked-' + getVersion('marked', 'node_modules', 'package.json') + '/lib/marked.js',
<add> 'js/angular-bootstrap/dropdown-toggle.min.js',
<add> 'components/lunr.js-' + getVersion('lunr.js') + '/lunr.min.js',
<add> 'components/google-code-prettify-' + getVersion('google-code-prettify') + '/src/prettify.js',
<add> 'components/google-code-prettify-' + getVersion('google-code-prettify') + '/src/lang-css.js',
<add> 'js/versions-data.js',
<add> 'js/pages-data.js',
<add> 'js/nav-data.js',
<add> 'js/docs.min.js'
<add> ],
<add> stylesheets: [
<add> 'components/bootstrap-' + getVersion('bootstrap') + '/css/bootstrap.min.css',
<add> 'components/open-sans-fontface-' + getVersion('open-sans-fontface') + '/open-sans.css',
<add> 'css/prettify-theme.css',
<add> 'css/docs.css',
<add> 'css/animations.css'
<add> ]
<add> };
<add>}; | 3 |
PHP | PHP | make test check for failure instead of pass | 16726e65f0c687745a83de1d99d8a8749b7289a3 | <ide><path>tests/TestCase/Controller/Component/SecurityComponentTest.php
<ide> public function testValidatePostOnGetWithData()
<ide> $event = new Event('Controller.startup', $this->Controller);
<ide> $this->Controller->Security->startup($event);
<ide>
<del> $fields = '68730b0747d4889ec2766f9117405f9635f5fd5e%3AModel.valid';
<add> $fields = 'an-invalid-token';
<ide> $unlocked = '';
<ide>
<ide> $this->Controller->request->env('REQUEST_METHOD', 'GET');
<ide> public function testValidatePostOnGetWithData()
<ide> '_Token' => compact('fields', 'unlocked')
<ide> ];
<ide> $this->Controller->Security->startup($event);
<del> $this->assertFalse($this->Controller->failed);
<add> $this->assertTrue($this->Controller->failed);
<ide> }
<ide>
<ide> /** | 1 |
Text | Text | make instructions for cafe css step 24 specificer | 2d7b01aac9ae1de0f63e90e6fe2b0f8e7a137ca9 | <ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-basic-css-by-building-a-cafe-menu/5f356ed63e0fa262326eef05.md
<ide> dashedName: step-24
<ide>
<ide> # --description--
<ide>
<del>Now make the background color of the `div` element to be `burlywood`.
<add>Now use the existing `div` selector to set the background color of the `div` element to be `burlywood`.
<ide>
<ide> # --hints--
<ide> | 1 |
Javascript | Javascript | fix fs.realpath to work on windows | 424bca15c8e227a9170cfe00f9ba7d9daae6fb03 | <ide><path>lib/fs.js
<ide> var normalize = pathModule.normalize;
<ide> // result is [base_with_slash, base], e.g. ['somedir/', 'somedir']
<ide> var nextPartRe = /(.*?)(?:[\/]+|$)/g;
<ide>
<add>// Regex to split a windows path into three parts: [*, device, slash,
<add>// tail] windows-only
<add>var splitDeviceRe =
<add> /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?([\\\/])?([\s\S]*?)$/;
<add>
<ide> fs.realpathSync = function realpathSync(p, cache) {
<ide> // make p is absolute
<ide> p = pathModule.resolve(p);
<ide> fs.realpathSync = function realpathSync(p, cache) {
<ide> pos = nextPartRe.lastIndex;
<ide>
<ide> // continue if not a symlink, or if root
<del> if (!base || knownHard[base] || (cache && cache[base] === base)) {
<add> var isRoot = !base;
<add> if (isWindows) {
<add> // if it doens't have a tail, then it's the root.
<add> var split = base.match(splitDeviceRe);
<add> if (split) {
<add> isRoot = !split[2];
<add> }
<add> }
<add> if (isRoot || knownHard[base] || (cache && cache[base] === base)) {
<ide> continue;
<ide> }
<ide>
<ide> fs.realpathSync = function realpathSync(p, cache) {
<ide> }
<ide>
<ide> // read the link if it wasn't read before
<del> var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
<del> if (!seenLinks[id]) {
<add> // dev/ino always return 0 on windows, so skip the check.
<add> var linkTarget;
<add> if (!isWindows) {
<add> var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
<add> if (seenLinks[id]) {
<add> linkTarget = seenLinks[id];
<add> }
<add> }
<add> if (!linkTarget) {
<ide> fs.statSync(base);
<del> seenLinks[id] = fs.readlinkSync(base);
<del> resolvedLink = pathModule.resolve(previous, seenLinks[id]);
<add> linkTarget = fs.readlinkSync(base);
<add> resolvedLink = pathModule.resolve(previous, linkTarget);
<ide> // track this, if given a cache.
<ide> if (cache) cache[base] = resolvedLink;
<add> if (!isWindows) seenLinks[id] = linkTarget;
<ide> }
<ide> }
<ide>
<ide> fs.realpath = function realpath(p, cache, cb) {
<ide> base = previous + result[1];
<ide> pos = nextPartRe.lastIndex;
<ide>
<del> // continue if known to be hard or if root or in cache already.
<del> if (!base || knownHard[base] || (cache && cache[base] === base)) {
<add> // continue if not a symlink, or if root
<add> var isRoot = !base;
<add> if (isWindows) {
<add> // if it doens't have a tail, then it's the root.
<add> var split = base.match(splitDeviceRe);
<add> if (split) {
<add> isRoot = !split[2];
<add> }
<add> }
<add> if (isRoot || knownHard[base] || (cache && cache[base] === base)) {
<ide> return process.nextTick(LOOP);
<ide> }
<ide>
<ide> fs.realpath = function realpath(p, cache, cb) {
<ide>
<ide> // stat & read the link if not read before
<ide> // call gotTarget as soon as the link target is known
<del> var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
<del> if (seenLinks[id]) {
<del> return gotTarget(null, seenLinks[id], base);
<add> // dev/ino always return 0 on windows, so skip the check.
<add> if (!isWindows) {
<add> var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
<add> if (seenLinks[id]) {
<add> return gotTarget(null, seenLinks[id], base);
<add> }
<ide> }
<ide> fs.stat(base, function(err) {
<ide> if (err) return cb(err);
<ide>
<ide> fs.readlink(base, function(err, target) {
<del> gotTarget(err, seenLinks[id] = target);
<add> if (!isWindows) seenLinks[id] = target;
<add> gotTarget(err, target);
<ide> });
<ide> });
<ide> } | 1 |
Python | Python | make docstring match args | 76779363160a598f130433209a77f8a747351b61 | <ide><path>src/transformers/modeling_bart.py
<ide> def forward(
<ide> **unused
<ide> ):
<ide> r"""
<del> masked_lm_labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):
<add> lm_labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):
<ide> Labels for computing the masked language modeling loss.
<ide> Indices should either be in ``[0, ..., config.vocab_size]`` or -100 (see ``input_ids`` docstring).
<ide> Tokens with indices set to ``-100`` are ignored (masked), the loss is only computed for the tokens
<ide> def forward(
<ide>
<ide> Returns:
<ide> :obj:`tuple(torch.FloatTensor)` comprising various elements depending on the configuration (:class:`~transformers.RobertaConfig`) and inputs:
<del> masked_lm_loss (`optional`, returned when ``masked_lm_labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``:
<add> masked_lm_loss (`optional`, returned when ``lm_labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``:
<ide> Masked language modeling loss.
<ide> prediction_scores (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, config.vocab_size)`)
<ide> Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
<ide><path>src/transformers/modeling_gpt2.py
<ide> def forward(
<ide> r"""
<ide> labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):
<ide> Labels for language modeling.
<del> Note that the labels **are shifted** inside the model, i.e. you can set ``lm_labels = input_ids``
<add> Note that the labels **are shifted** inside the model, i.e. you can set ``labels = input_ids``
<ide> Indices are selected in ``[-100, 0, ..., config.vocab_size]``
<ide> All labels set to ``-100`` are ignored (masked), the loss is only
<ide> computed for labels in ``[0, ..., config.vocab_size]``
<ide><path>src/transformers/modeling_openai.py
<ide> def forward(
<ide> r"""
<ide> labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):
<ide> Labels for language modeling.
<del> Note that the labels **are shifted** inside the model, i.e. you can set ``lm_labels = input_ids``
<add> Note that the labels **are shifted** inside the model, i.e. you can set ``labels = input_ids``
<ide> Indices are selected in ``[-100, 0, ..., config.vocab_size]``
<ide> All labels set to ``-100`` are ignored (masked), the loss is only
<ide> computed for labels in ``[0, ..., config.vocab_size]``
<ide><path>src/transformers/modeling_transfo_xl.py
<ide> def forward(self, input_ids=None, mems=None, head_mask=None, inputs_embeds=None,
<ide> r"""
<ide> labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):
<ide> Labels for language modeling.
<del> Note that the labels **are shifted** inside the model, i.e. you can set ``lm_labels = input_ids``
<add> Note that the labels **are shifted** inside the model, i.e. you can set ``labels = input_ids``
<ide> Indices are selected in ``[-100, 0, ..., config.vocab_size]``
<ide> All labels set to ``-100`` are ignored (masked), the loss is only
<ide> computed for labels in ``[0, ..., config.vocab_size]``
<ide><path>src/transformers/modeling_xlm.py
<ide> def forward(
<ide> r"""
<ide> labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):
<ide> Labels for language modeling.
<del> Note that the labels **are shifted** inside the model, i.e. you can set ``lm_labels = input_ids``
<add> Note that the labels **are shifted** inside the model, i.e. you can set ``labels = input_ids``
<ide> Indices are selected in ``[-100, 0, ..., config.vocab_size]``
<ide> All labels set to ``-100`` are ignored (masked), the loss is only
<ide> computed for labels in ``[0, ..., config.vocab_size]`` | 5 |
Python | Python | add update_exc and expand_exc to util | 60db497525a88fd44351d91e260c36f7fabe878c | <ide><path>spacy/language_data/__init__.py
<ide> from .punctuation import *
<ide> from .tag_map import *
<ide> from .entity_rules import *
<del>from .util import *
<ide> from .tokenizer_exceptions import *
<ide><path>spacy/language_data/util.py
<del># coding: utf8
<del>from __future__ import unicode_literals
<del>
<del>from ..symbols import *
<del>
<del>try:
<del> unicode
<del>except:
<del> unicode = str
<del>
<del>
<del>PRON_LEMMA = "-PRON-"
<del>DET_LEMMA = "-DET-"
<del>ENT_ID = "ent_id"
<del>
<del>
<del>def update_exc(exc, additions):
<del> for orth, token_attrs in additions.items():
<del> if not all(isinstance(attr[ORTH], unicode) for attr in token_attrs):
<del> msg = "Invalid value for ORTH in exception: key='%s', orths='%s'"
<del> raise ValueError(msg % (orth, token_attrs))
<del> described_orth = ''.join(attr[ORTH] for attr in token_attrs)
<del> if orth != described_orth:
<del> # TODO: Better error
<del> msg = "Invalid tokenizer exception: key='%s', orths='%s'"
<del> raise ValueError(msg % (orth, described_orth))
<del> overlap = set(exc.keys()).intersection(set(additions))
<del> assert not overlap, overlap
<del> exc.update(additions)
<del>
<del>
<del>def strings_to_exc(orths):
<del> return {orth: [{ORTH: orth}] for orth in orths}
<del>
<del>
<del>def expand_exc(excs, search, replace):
<del> updates = {}
<del>
<del> for token_string, tokens in excs.items():
<del> if search in token_string:
<del> new_key = token_string.replace(search, replace)
<del> new_value = [_fix_token(t, search, replace) for t in tokens]
<del>
<del> updates[new_key] = new_value
<del>
<del> return updates
<del>
<del>
<del>def _fix_token(token, search, replace):
<del> fixed = dict(token)
<del> fixed[ORTH] = fixed[ORTH].replace(search, replace)
<del> return fixed
<ide><path>spacy/util.py
<ide> import sys
<ide> import textwrap
<ide>
<del>from .compat import path2str, basestring_, input_
<add>from .symbols import ORTH
<add>from .compat import path2str, basestring_, input_, unicode_
<ide>
<ide>
<ide> LANGUAGES = {}
<ide> def compile_infix_regex(entries):
<ide> return re.compile(expression)
<ide>
<ide>
<add>def update_exc(base_exceptions, *addition_dicts):
<add> exc = dict(base_exceptions)
<add> for additions in addition_dicts:
<add> for orth, token_attrs in additions.items():
<add> if not all(isinstance(attr[ORTH], unicode_) for attr in token_attrs):
<add> msg = "Invalid value for ORTH in exception: key='%s', orths='%s'"
<add> raise ValueError(msg % (orth, token_attrs))
<add> described_orth = ''.join(attr[ORTH] for attr in token_attrs)
<add> if orth != described_orth:
<add> # TODO: Better error
<add> msg = "Invalid tokenizer exception: key='%s', orths='%s'"
<add> raise ValueError(msg % (orth, described_orth))
<add> # overlap = set(exc.keys()).intersection(set(additions))
<add> # assert not overlap, overlap
<add> exc.update(additions)
<add> expand_exc(exc, "'", "’")
<add> return exc
<add>
<add>
<add>def expand_exc(excs, search, replace):
<add> def _fix_token(token, search, replace):
<add> fixed = dict(token)
<add> fixed[ORTH] = fixed[ORTH].replace(search, replace)
<add> return fixed
<add> updates = {}
<add> for token_string, tokens in excs.items():
<add> if search in token_string:
<add> new_key = token_string.replace(search, replace)
<add> new_value = [_fix_token(t, search, replace) for t in tokens]
<add> updates[new_key] = new_value
<add> return updates
<add>
<add>
<ide> def normalize_slice(length, start, stop, step=None):
<ide> if not (step is None or step == 1):
<ide> raise ValueError("Stepped slices not supported in Span objects." | 3 |
Javascript | Javascript | make cache print less noisy | d5f15d5b3a4e0190b999f434f9f618a1a8a61368 | <ide><path>tooling/print-cache-file.js
<ide> const printData = async (data, indent) => {
<ide> if (item === ESCAPE) {
<ide> const nextItem = read();
<ide> if (nextItem === ESCAPE_ESCAPE_VALUE) {
<del> printLine(`- null`);
<add> printLine("null");
<ide> } else if (nextItem === ESCAPE_UNDEFINED) {
<del> printLine(`- undefined`);
<add> printLine("undefined");
<ide> } else if (nextItem === ESCAPE_END_OBJECT) {
<ide> indent = indent.slice(0, indent.length - 2);
<ide> printLine(`} = #${currentReference++}`);
<ide> } else if (typeof nextItem === "number" && nextItem < 0) {
<del> printLine(`- Reference ${nextItem} => #${currentReference + nextItem}`);
<add> printLine(`Reference ${nextItem} => #${currentReference + nextItem}`);
<ide> } else {
<ide> const request = nextItem;
<ide> if (typeof request === "number") {
<ide> printLine(
<del> `- Object (Reference ${request} => @${currentTypeReference -
<add> `Object (Reference ${request} => @${currentTypeReference -
<ide> request}) {`
<ide> );
<ide> } else {
<ide> const name = read();
<ide> printLine(
<del> `- Object (${request} / ${name} @${currentTypeReference++}) {`
<add> `Object (${request} / ${name} @${currentTypeReference++}) {`
<ide> );
<ide> }
<ide> indent += " ";
<ide> }
<ide> } else if (typeof item === "string") {
<ide> if (item !== "") {
<del> printLine(`- string ${JSON.stringify(item)} = #${currentReference++}`);
<add> printLine(`${JSON.stringify(item)} = #${currentReference++}`);
<ide> } else {
<del> printLine('- string ""');
<add> printLine('""');
<ide> }
<ide> } else if (Buffer.isBuffer(item)) {
<del> printLine(`- buffer ${item.toString("hex")} = #${currentReference++}`);
<add> printLine(`buffer ${item.toString("hex")} = #${currentReference++}`);
<ide> } else if (typeof item === "function") {
<ide> const innerData = await item();
<del> printLine(`- lazy {`);
<add> printLine(`lazy {`);
<ide> await printData(innerData, indent + " ");
<ide> printLine(`}`);
<ide> } else {
<del> printLine(`- ${item}`);
<add> printLine(`${item}`);
<ide> }
<ide> }
<ide> }; | 1 |
Python | Python | add decorator to flaky test | 31ec424b3df6938418128b8fa3e165a5f3e0f10d | <ide><path>examples/pytorch/test_accelerate_examples.py
<ide> import torch
<ide>
<ide> from accelerate.utils import write_basic_config
<del>from transformers.testing_utils import TestCasePlus, get_gpu_count, run_command, slow, torch_device
<add>from transformers.testing_utils import TestCasePlus, get_gpu_count, is_flaky, run_command, slow, torch_device
<ide> from transformers.utils import is_apex_available
<ide>
<ide>
<ide> def test_run_ner_no_trainer(self):
<ide> self.assertTrue(os.path.exists(os.path.join(tmp_dir, "epoch_0")))
<ide> self.assertTrue(os.path.exists(os.path.join(tmp_dir, "ner_no_trainer")))
<ide>
<add> @is_flaky()
<ide> @mock.patch.dict(os.environ, {"WANDB_MODE": "offline"})
<ide> def test_run_squad_no_trainer(self):
<ide> tmp_dir = self.get_auto_remove_tmp_dir() | 1 |
Javascript | Javascript | add link to the guides in deprecation warning | 9acdd097555d566382f626bd2ee4f6ce9e2bc7fb | <ide><path>packages/ember-metal/lib/computed.js
<ide> function ComputedProperty(config, opts) {
<ide> config.__ember_arity = config.length;
<ide> this._getter = config;
<ide> if (config.__ember_arity > 1) {
<del> Ember.deprecate("Using the same function as getter and setter is deprecated");
<add> Ember.deprecate("Using the same function as getter and setter is deprecated.", false, {
<add> url: "http://emberjs.com/deprecations/v1.x/#toc_deprecate-using-the-same-function-as-getter-and-setter-in-computed-properties"
<add> });
<ide> this._setter = config;
<ide> }
<ide> } else { | 1 |
Python | Python | check regexp in monitored list. correct issue #378 | 58c34d70446260e37511f7cee3ecd301c31ed566 | <ide><path>glances/core/glances_monitor_list.py
<ide> def __set_monitor_list(self, section, key):
<ide> if description is not None and regex is not None:
<ide> # Build the new item
<ide> value["description"] = description
<del> value["regex"] = regex
<add> try:
<add> re.compile(regex)
<add> except:
<add> continue
<add> else:
<add> value["regex"] = regex
<ide> value["command"] = command
<ide> value["countmin"] = countmin
<ide> value["countmax"] = countmax | 1 |
PHP | PHP | remove the count | 666241ebc6c99cd3af0c3ce7fc63d7107c6edc3b | <ide><path>src/Illuminate/Database/Eloquent/Builder.php
<ide> protected function addHasWhere(Builder $hasQuery, Relation $relation, $operator,
<ide> {
<ide> $this->mergeWheresToHas($hasQuery, $relation);
<ide>
<del> $count = new Expression((int) $count);
<del>
<ide> return $this->where(new Expression('('.$hasQuery->toSql().')'), $operator, $count, $boolean);
<ide> }
<ide> | 1 |
Ruby | Ruby | add missing require | e9b6659c4ccd4272a363835274ec2e36e778dcd8 | <ide><path>activerecord/test/cases/adapters/postgresql/utils_test.rb
<add>require 'cases/helper'
<add>
<ide> class PostgreSQLUtilsTest < ActiveSupport::TestCase
<ide> include ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::Utils
<ide> | 1 |
Text | Text | fix the rxclojure project link | 1e871051f309dbc64159cf94c10fe392b37c88f3 | <ide><path>README.md
<ide> Some of the goals of RxJava are:
<ide>
<ide> - Stay close to other Rx implementations while adjusting naming conventions and idioms to Java
<ide> - Match contracts of Rx should be the same
<del>- Target the JVM not a language to allow JVM-language bindings (such as [Scala](https://github.com/ReactiveX/RxScala), [Groovy](https://github.com/ReactiveX/RxGroovy), [Clojure](https://github.com/ReactiveX/RxGroovy) and [Kotlin](https://github.com/ReactiveX/RxKotlin)).
<add>- Target the JVM not a language to allow JVM-language bindings (such as [Scala](https://github.com/ReactiveX/RxScala), [Groovy](https://github.com/ReactiveX/RxGroovy), [Clojure](https://github.com/ReactiveX/RxClojure) and [Kotlin](https://github.com/ReactiveX/RxKotlin)).
<ide> - Support Java 6+ (to include Android support)
<ide>
<ide> Learn more about RxJava on the <a href="https://github.com/ReactiveX/RxJava/wiki">Wiki Home</a> and the <a href="http://techblog.netflix.com/2013/02/rxjava-netflix-api.html">Netflix TechBlog post</a> where RxJava was introduced. | 1 |
Text | Text | translate 02-displaying-data.md to japanese | af34ca7b41fa83efde6c6bce03f7fb2ed2873be5 | <ide><path>docs/docs/02-displaying-data.ja-JP.md
<add>---
<add>id: displaying-data-ja-JP
<add>title: データを表示する
<add>permalink: displaying-data-ja-JP.html
<add>prev: why-react-ja-JP.html
<add>next: jsx-in-depth-ja-JP.html
<add>
<add>---
<add>
<add>UIについて、最も基本的なことは、いくつかのデータを表示することです。Reactはデータを表示し、変更された時にはインターフェースを最新の状態に自動的に保つことが簡単にできるようになっています。
<add>
<add>## はじめに
<add>
<add>本当に単純な例を見てみましょう。`hello-react.html` ファイルを以下のようなコードで作成してください。
<add>
<add>```html
<add><!DOCTYPE html>
<add><html>
<add> <head>
<add> <title>Hello React</title>
<add> <script src="https://fb.me/react-{{site.react_version}}.js"></script>
<add> <script src="https://fb.me/JSXTransformer-{{site.react_version}}.js"></script>
<add> </head>
<add> <body>
<add> <div id="example"></div>
<add> <script type="text/jsx">
<add>
<add> // ** コードをここに書きます! **
<add>
<add> </script>
<add> </body>
<add></html>
<add>```
<add>
<add>このドキュメントの中では、JavaScriptのコードにのみフォーカスします。そして、それが上のようなテンプレートに挿入されていると考えます。
<add>
<add>```javascript
<add>var HelloWorld = React.createClass({
<add> render: function() {
<add> return (
<add> <p>
<add> Hello, <input type="text" placeholder="Your name here" />!
<add> It is {this.props.date.toTimeString()}
<add> </p>
<add> );
<add> }
<add>});
<add>
<add>setInterval(function() {
<add> React.render(
<add> <HelloWorld date={new Date()} />,
<add> document.getElementById('example')
<add> );
<add>}, 500);
<add>```
<add>
<add>
<add>## リアクティブなアップデート
<add>
<add>`hello-react.html` をウェブブラウザで開き、テキストフィールドにあなたの名前を入力してください。ReactはUIのうち、時間の文字列しか変更しないことに注意してください。あなたがテキストフィールドに入力したものは残っています。あなたはそういったコードを書いていないのにも関わらずです。Reactはあなたのことを理解しており、正しいことを行います。
<add>
<add>このことについて私たちが理解できる方法は、Reactは必要になるまで、DOMの操作を行わないということです。 **Reactは、DOMの変化を表現し、あなたにもっとも効率的なDOMの変化を見積もるために早い、内部のモックのDOMを使っています。**
<add>
<add>このコンポーネントのインプットは `props` と呼ばれるものです。"properties" の省略形です。それらはJSXシンタックスの中でアトリビュートとして渡されます。それらはコンポーネントの中で不変と考えるべきで、 **`this.props` と書かないようにしてください**
<add>
<add>## コンポーネントは関数のようなものです。
<add>
<add>Reactのコンポーネントはとても単純です。それらは `props` や `state` (後述します)を取り、HTMLをレンダリングする単純な関数だと考えることができます。この考えの下では、コンポーネントは簡単に理解することができます。
<add>
<add>> 注意:
<add>>
<add>> **1つの制限**: Reactのコンポーネントは単一の最上位のノードだけをレンダリングします。複数のノードをリターンしたい場合は、単一の最上位のもので *ラップする必要があります* 。
<add>
<add>## JSXシンタックス
<add>
<add>私たちは関心を分離する正しい方法は「テンプレート」と「ディスプレイロジック」ではなくコンポーネントであると強く考えています。ビューを生成するマークアップとコードは密接につながっていると考えています。加えて、ディスプレイロジックはとても複雑になりえますし、ビューを表現するのにテンプレート言語を使うことはとてもややこしくなりえます。
<add>
<add>私たちは、この問題の最適解は、UIを構築するのにリアルなプログラミング言語の表現力の全てを使うことができるように、JavaScriptのコードからHTMLやコンポーネントのツリーを直接生成することだと発見しました。
<add>
<add>上記のことを簡単に行うために、私たちはReactのツリーノードを構築するためのとても単純で、 **オプショナルな** HTMLに似たシンタックスを加えました。
<add>
<add>**JSXはHTMLのシンタックスを使ってJavaScriptのオブジェクトを構築するのを可能にします。** 純粋にJavaScriptを使ってReactでリンクを構築するには、以下のように書きます。
<add>
<add>`React.createElement('a', {href: 'https://facebook.github.io/react/'}, 'Hello!')`
<add>
<add>JSXでは、以下のように変換されます。
<add>
<add>`<a href="https://facebook.github.io/react/">Hello!</a>`
<add>
<add>以上のようなことで、Reactのアプリを作成するのは簡単になりましたし、デザイナーはこのシンタックスを好むようになると発見しました。しかし、人は自分自身のワークフローを持っているものです。 **JSXはReactを使う際に必ずしも必要ではありません。**
<add>
<add>JSXはとても小さいです。さらに学ぶためには、[JSXの深層](/react/docs/jsx-in-depth-ja-JP.html)を参照ください。または、[ライブJSXコンパイラー](/react/jsx-compiler.html)で変換の動作を確認してください。
<add>
<add>JSXはHTMLに似ていますが、正確に同じではありません。いくつかのキーの違いについては[JSXの理解](/react/docs/jsx-gotchas.html) をご覧ください。
<add>
<add>The easiest way to get started with JSX is to use the in-browser `JSXTransformer`. We strongly recommend that you don't use this in production. You can precompile your code using our command-line [react-tools](https://www.npmjs.com/package/react-tools) package.
<add>JSXを初めて使う際に最も簡単なのは、ブラウザで `JSXTransformer` を使う方法です。これはプロダクションでは使わないことを強くお勧めします。コードは、コマンドラインの[react-tools](https://www.npmjs.com/package/react-tools)パッケージを使うことでプリコンパイルできます。
<add>
<add>## JSXを使わないReact
<add>
<add>JSXは完全にオプションです。Reactと一緒にJSXを使う必要はありません。`React.createElement` を使って、ただのJavaScriptでReactの要素を作ることもできます。それは、タグの名前やコンポーネント、プロパティのオブジェクト、いくつかのオプションの子要素をとります。
<add>
<add>```javascript
<add>var child1 = React.createElement('li', null, 'First Text Content');
<add>var child2 = React.createElement('li', null, 'Second Text Content');
<add>var root = React.createElement('ul', { className: 'my-list' }, child1, child2);
<add>React.render(root, document.getElementById('example'));
<add>```
<add>便利に書くために、カスタムコンポーネントで要素を作るために簡略した記法でファクトリー関数を作ることができます。
<add>
<add>```javascript
<add>var Factory = React.createFactory(ComponentClass);
<add>...
<add>var root = Factory({ custom: 'prop' });
<add>React.render(root, document.getElementById('example'));
<add>```
<add>
<add>Reactはすでに、共通なHTMLのタグについてはビルトインの関数を持っています。
<add>
<add>```javascript
<add>var root = React.DOM.ul({ className: 'my-list' },
<add> React.DOM.li(null, 'Text Content')
<add> );
<add>``` | 1 |
Go | Go | add ipvlan_flag option, support l3s ipvlan_mode | f70a9788c54d720aaad9e63b2d9f79959e0b2930 | <ide><path>libnetwork/drivers/ipvlan/ipvlan.go
<ide> const (
<ide> vethLen = 7
<ide> containerVethPrefix = "eth"
<ide> vethPrefix = "veth"
<del> ipvlanType = "ipvlan" // driver type name
<del> modeL2 = "l2" // ipvlan mode l2 is the default
<del> modeL3 = "l3" // ipvlan L3 mode
<del> parentOpt = "parent" // parent interface -o parent
<del> modeOpt = "_mode" // ipvlan mode ux opt suffix
<del>)
<ide>
<del>var driverModeOpt = ipvlanType + modeOpt // mode -o ipvlan_mode
<add> ipvlanType = "ipvlan" // driver type name
<add> parentOpt = "parent" // parent interface -o parent
<add> driverModeOpt = ipvlanType + "_mode" // mode -o ipvlan_mode
<add> driverFlagOpt = ipvlanType + "_flag" // flag -o ipvlan_flag
<add>
<add> modeL2 = "l2" // ipvlan L2 mode (default)
<add> modeL3 = "l3" // ipvlan L3 mode
<add> modeL3S = "l3s" // ipvlan L3S mode
<add>
<add> flagBridge = "bridge" // ipvlan flag bridge (default)
<add> flagPrivate = "private" // ipvlan flag private
<add> flagVepa = "vepa" // ipvlan flag vepa
<add>)
<ide>
<ide> type endpointTable map[string]*endpoint
<ide>
<ide><path>libnetwork/drivers/ipvlan/ipvlan_joinleave.go
<ide> func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo,
<ide> return fmt.Errorf("error generating an interface name: %v", err)
<ide> }
<ide> // create the netlink ipvlan interface
<del> vethName, err := createIPVlan(containerIfName, n.config.Parent, n.config.IpvlanMode)
<add> vethName, err := createIPVlan(containerIfName, n.config.Parent, n.config.IpvlanMode, n.config.IpvlanFlag)
<ide> if err != nil {
<ide> return err
<ide> }
<ide> func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo,
<ide> return fmt.Errorf("could not find endpoint with id %s", eid)
<ide> }
<ide> if !n.config.Internal {
<del> if n.config.IpvlanMode == modeL3 {
<add> switch n.config.IpvlanMode {
<add> case modeL3, modeL3S:
<ide> // disable gateway services to add a default gw using dev eth0 only
<ide> jinfo.DisableGatewayService()
<ide> defaultRoute, err := ifaceGateway(defaultV4RouteCidr)
<ide> if err != nil {
<ide> return err
<ide> }
<ide> if err := jinfo.AddStaticRoute(defaultRoute.Destination, defaultRoute.RouteType, defaultRoute.NextHop); err != nil {
<del> return fmt.Errorf("failed to set an ipvlan l3 mode ipv4 default gateway: %v", err)
<add> return fmt.Errorf("failed to set an ipvlan l3/l3s mode ipv4 default gateway: %v", err)
<ide> }
<ide> logrus.Debugf("Ipvlan Endpoint Joined with IPv4_Addr: %s, Ipvlan_Mode: %s, Parent: %s",
<ide> ep.addr.IP.String(), n.config.IpvlanMode, n.config.Parent)
<ide> func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo,
<ide> return err
<ide> }
<ide> if err = jinfo.AddStaticRoute(default6Route.Destination, default6Route.RouteType, default6Route.NextHop); err != nil {
<del> return fmt.Errorf("failed to set an ipvlan l3 mode ipv6 default gateway: %v", err)
<add> return fmt.Errorf("failed to set an ipvlan l3/l3s mode ipv6 default gateway: %v", err)
<ide> }
<ide> logrus.Debugf("Ipvlan Endpoint Joined with IPv6_Addr: %s, Ipvlan_Mode: %s, Parent: %s",
<ide> ep.addrv6.IP.String(), n.config.IpvlanMode, n.config.Parent)
<ide> }
<del> }
<del> if n.config.IpvlanMode == modeL2 {
<add> case modeL2:
<ide> // parse and correlate the endpoint v4 address with the available v4 subnets
<ide> if len(n.config.Ipv4Subnets) > 0 {
<ide> s := n.getSubnetforIPv4(ep.addr)
<ide><path>libnetwork/drivers/ipvlan/ipvlan_network.go
<ide> func (d *driver) CreateNetwork(nid string, option map[string]interface{}, nInfo
<ide> config.IpvlanMode = modeL2
<ide> case modeL3:
<ide> config.IpvlanMode = modeL3
<add> case modeL3S:
<add> config.IpvlanMode = modeL3S
<ide> default:
<ide> return fmt.Errorf("requested ipvlan mode '%s' is not valid, 'l2' mode is the ipvlan driver default", config.IpvlanMode)
<ide> }
<add> // verify the ipvlan flag from -o ipvlan_flag option
<add> switch config.IpvlanFlag {
<add> case "", flagBridge:
<add> // default to bridge if -o ipvlan_flag is empty
<add> config.IpvlanFlag = flagBridge
<add> case flagPrivate:
<add> config.IpvlanFlag = flagPrivate
<add> case flagVepa:
<add> config.IpvlanFlag = flagVepa
<add> default:
<add> return fmt.Errorf("requested ipvlan flag '%s' is not valid, 'bridge' is the ipvlan driver default", config.IpvlanFlag)
<add> }
<ide> // loopback is not a valid parent link
<ide> if config.Parent == "lo" {
<ide> return fmt.Errorf("loopback interface is not a valid %s parent link", ipvlanType)
<ide> func (config *configuration) fromOptions(labels map[string]string) error {
<ide> case driverModeOpt:
<ide> // parse driver option '-o ipvlan_mode'
<ide> config.IpvlanMode = value
<add> case driverFlagOpt:
<add> // parse driver option '-o ipvlan_flag'
<add> config.IpvlanFlag = value
<ide> }
<ide> }
<ide> return nil
<ide><path>libnetwork/drivers/ipvlan/ipvlan_setup.go
<ide> const (
<ide> )
<ide>
<ide> // createIPVlan Create the ipvlan slave specifying the source name
<del>func createIPVlan(containerIfName, parent, ipvlanMode string) (string, error) {
<del> // Set the ipvlan mode. Default is bridge mode
<add>func createIPVlan(containerIfName, parent, ipvlanMode, ipvlanFlag string) (string, error) {
<add> // Set the ipvlan mode and flag. Default is L2 bridge
<ide> mode, err := setIPVlanMode(ipvlanMode)
<ide> if err != nil {
<ide> return "", fmt.Errorf("Unsupported %s ipvlan mode: %v", ipvlanMode, err)
<ide> }
<add> // Set the ipvlan flag. Default is bridge
<add> flag, err := setIPVlanFlag(ipvlanFlag)
<add> if err != nil {
<add> return "", fmt.Errorf("Unsupported %s ipvlan flag: %v", ipvlanFlag, err)
<add> }
<ide> // verify the Docker host interface acting as the macvlan parent iface exists
<ide> if !parentExists(parent) {
<ide> return "", fmt.Errorf("the requested parent interface %s was not found on the Docker host", parent)
<ide> func createIPVlan(containerIfName, parent, ipvlanMode string) (string, error) {
<ide> ParentIndex: parentLink.Attrs().Index,
<ide> },
<ide> Mode: mode,
<add> Flag: flag,
<ide> }
<ide> if err := ns.NlHandle().LinkAdd(ipvlan); err != nil {
<ide> // If a user creates a macvlan and ipvlan on same parent, only one slave iface can be active at a time.
<ide> func createIPVlan(containerIfName, parent, ipvlanMode string) (string, error) {
<ide> return ipvlan.Attrs().Name, nil
<ide> }
<ide>
<del>// setIPVlanMode setter for one of the two ipvlan port types
<add>// setIPVlanMode setter for one of the three ipvlan port types
<ide> func setIPVlanMode(mode string) (netlink.IPVlanMode, error) {
<ide> switch mode {
<ide> case modeL2:
<ide> return netlink.IPVLAN_MODE_L2, nil
<ide> case modeL3:
<ide> return netlink.IPVLAN_MODE_L3, nil
<add> case modeL3S:
<add> return netlink.IPVLAN_MODE_L3S, nil
<ide> default:
<ide> return 0, fmt.Errorf("Unknown ipvlan mode: %s", mode)
<ide> }
<ide> }
<ide>
<add>// setIPVlanFlag setter for one of the three ipvlan port flags
<add>func setIPVlanFlag(flag string) (netlink.IPVlanFlag, error) {
<add> switch flag {
<add> case flagBridge:
<add> return netlink.IPVLAN_FLAG_BRIDGE, nil
<add> case flagPrivate:
<add> return netlink.IPVLAN_FLAG_PRIVATE, nil
<add> case flagVepa:
<add> return netlink.IPVLAN_FLAG_VEPA, nil
<add> default:
<add> return 0, fmt.Errorf("unknown ipvlan flag: %s", flag)
<add> }
<add>}
<add>
<ide> // parentExists check if the specified interface exists in the default namespace
<ide> func parentExists(ifaceStr string) bool {
<ide> _, err := ns.NlHandle().LinkByName(ifaceStr)
<ide><path>libnetwork/drivers/ipvlan/ipvlan_setup_test.go
<ide> func TestSetIPVlanMode(t *testing.T) {
<ide> if mode != netlink.IPVLAN_MODE_L3 {
<ide> t.Fatalf("expected %d got %d", netlink.IPVLAN_MODE_L3, mode)
<ide> }
<add> // test ipvlan l3s mode
<add> mode, err = setIPVlanMode(modeL3S)
<add> if err != nil {
<add> t.Fatalf("error parsing %v vlan mode: %v", mode, err)
<add> }
<add> if mode != netlink.IPVLAN_MODE_L3S {
<add> t.Fatalf("expected %d got %d", netlink.IPVLAN_MODE_L3S, mode)
<add> }
<ide> // test invalid mode
<ide> mode, err = setIPVlanMode("foo")
<ide> if err == nil {
<ide> func TestSetIPVlanMode(t *testing.T) {
<ide> t.Fatalf("expected 0 got %d", mode)
<ide> }
<ide> }
<add>
<add>// TestSetIPVlanFlag tests the ipvlan flag setter
<add>func TestSetIPVlanFlag(t *testing.T) {
<add> // test ipvlan bridge flag
<add> flag, err := setIPVlanFlag(flagBridge)
<add> if err != nil {
<add> t.Fatalf("error parsing %v vlan flag: %v", flag, err)
<add> }
<add> if flag != netlink.IPVLAN_FLAG_BRIDGE {
<add> t.Fatalf("expected %d got %d", netlink.IPVLAN_FLAG_BRIDGE, flag)
<add> }
<add> // test ipvlan private flag
<add> flag, err = setIPVlanFlag(flagPrivate)
<add> if err != nil {
<add> t.Fatalf("error parsing %v vlan flag: %v", flag, err)
<add> }
<add> if flag != netlink.IPVLAN_FLAG_PRIVATE {
<add> t.Fatalf("expected %d got %d", netlink.IPVLAN_FLAG_PRIVATE, flag)
<add> }
<add> // test ipvlan vepa flag
<add> flag, err = setIPVlanFlag(flagVepa)
<add> if err != nil {
<add> t.Fatalf("error parsing %v vlan flag: %v", flag, err)
<add> }
<add> if flag != netlink.IPVLAN_FLAG_VEPA {
<add> t.Fatalf("expected %d got %d", netlink.IPVLAN_FLAG_VEPA, flag)
<add> }
<add> // test invalid flag
<add> flag, err = setIPVlanFlag("foo")
<add> if err == nil {
<add> t.Fatal("invalid ipvlan flag should have returned an error")
<add> }
<add> if flag != 0 {
<add> t.Fatalf("expected 0 got %d", flag)
<add> }
<add> // test null flag
<add> flag, err = setIPVlanFlag("")
<add> if err == nil {
<add> t.Fatal("invalid ipvlan flag should have returned an error")
<add> }
<add> if flag != 0 {
<add> t.Fatalf("expected 0 got %d", flag)
<add> }
<add>}
<ide><path>libnetwork/drivers/ipvlan/ipvlan_store.go
<ide> type configuration struct {
<ide> Internal bool
<ide> Parent string
<ide> IpvlanMode string
<add> IpvlanFlag string
<ide> CreatedSlaveLink bool
<ide> Ipv4Subnets []*ipv4Subnet
<ide> Ipv6Subnets []*ipv6Subnet | 6 |
Javascript | Javascript | fix prefilter comment typo | 1326510324380aaab162331b2d271a986a634c48 | <ide><path>src/ajax.js
<ide> jQuery.extend({
<ide> // Apply prefilters
<ide> inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
<ide>
<del> // If request was aborted inside a prefiler, stop there
<add> // If request was aborted inside a prefilter, stop there
<ide> if ( state === 2 ) {
<ide> return false;
<ide> } | 1 |
Python | Python | add failing test for | f02b7f1329012aafca3851df3340b719c28d4586 | <ide><path>tests/test_filters.py
<ide> def test_must_call_distinct(self):
<ide> )
<ide>
<ide>
<add>class Blog(models.Model):
<add> name = models.CharField(max_length=20)
<add>
<add>
<add>class Entry(models.Model):
<add> blog = models.ForeignKey(Blog, on_delete=models.CASCADE)
<add> headline = models.CharField(max_length=120)
<add> pub_date = models.DateField(null=True)
<add>
<add>
<add>class BlogSerializer(serializers.ModelSerializer):
<add> class Meta:
<add> model = Blog
<add> fields = '__all__'
<add>
<add>
<add>class SearchFilterToManyTests(TestCase):
<add>
<add> @classmethod
<add> def setUpTestData(cls):
<add> b1 = Blog.objects.create(name='Blog 1')
<add> b2 = Blog.objects.create(name='Blog 2')
<add>
<add> Entry.objects.create(blog=b1, headline='Something about Lennon', pub_date=datetime.date(1979, 1, 1))
<add> Entry.objects.create(blog=b1, headline='Another thing about Lennon', pub_date=datetime.date(1979, 6, 1))
<add>
<add> Entry.objects.create(blog=b2, headline='Something unrelated', pub_date=datetime.date(1979, 1, 1))
<add> Entry.objects.create(blog=b2, headline='Retrospective on Lennon', pub_date=datetime.date(1990, 6, 1))
<add>
<add> def test_multiple_filter_conditions(self):
<add> class SearchListView(generics.ListAPIView):
<add> queryset = Blog.objects.all()
<add> serializer_class = BlogSerializer
<add> filter_backends = (filters.SearchFilter,)
<add> search_fields = ('=name', 'entry__headline', '=entry__pub_date__year')
<add>
<add> view = SearchListView.as_view()
<add> request = factory.get('/', {'search': 'Lennon,1979'})
<add> response = view(request)
<add> assert len(response.data) == 1
<add>
<add>
<ide> class OrderingFilterModel(models.Model):
<ide> title = models.CharField(max_length=20, verbose_name='verbose title')
<ide> text = models.CharField(max_length=100) | 1 |
Python | Python | update hubconf for gpt2 torchhub compatibility | 2576a5c6db0b2b97b79c1e649a2546d9ca6182bc | <ide><path>hubconf.py
<ide> openAIGPTModel,
<ide> openAIGPTLMHeadModel,
<ide> openAIGPTDoubleHeadsModel
<del>)
<ide>\ No newline at end of file
<add>)
<add>from hubconfs.gpt2_hubconf import (
<add> gpt2Tokenizer,
<add> gpt2Model,
<add> gpt2LMHeadModel,
<add> gpt2DoubleHeadsModel
<add>) | 1 |
Text | Text | clarify serverresponse explanations | 16accff90f25543b31c4e3dc0e71c5766795dc18 | <ide><path>doc/api/http.md
<ide> the data is read it will consume memory that can eventually lead to a
<ide> Node.js does not check whether Content-Length and the length of the
<ide> body which has been transmitted are equal or not.
<ide>
<del>The request implements the [Writable Stream][] interface. This is an
<del>[`EventEmitter`][] with the following events:
<add>The request inherits from [Stream][], and additionally implements the
<add>following:
<ide>
<ide> ### Event: 'abort'
<ide> <!-- YAML
<ide> added: v0.1.17
<ide> This object is created internally by an HTTP server — not by the user. It is
<ide> passed as the second parameter to the [`'request'`][] event.
<ide>
<del>The response implements, but does not inherit from, the [Writable Stream][]
<del>interface. This is an [`EventEmitter`][] with the following events:
<add>The response inherits from [Stream][], and additionally implements the
<add>following:
<ide>
<ide> ### Event: 'close'
<ide> <!-- YAML
<ide> not abort the request or do anything besides add a `'timeout'` event.
<ide> [`'upgrade'`]: #http_event_upgrade
<ide> [`Agent`]: #http_class_http_agent
<ide> [`Duplex`]: stream.html#stream_class_stream_duplex
<del>[`EventEmitter`]: events.html#events_class_eventemitter
<ide> [`TypeError`]: errors.html#errors_class_typeerror
<ide> [`URL`]: url.html#url_the_whatwg_url_api
<ide> [`agent.createConnection()`]: #http_agent_createconnection_options_callback
<ide> not abort the request or do anything besides add a `'timeout'` event.
<ide> [`socket.unref()`]: net.html#net_socket_unref
<ide> [`url.parse()`]: url.html#url_url_parse_urlstring_parsequerystring_slashesdenotehost
<ide> [Readable Stream]: stream.html#stream_class_stream_readable
<del>[Writable Stream]: stream.html#stream_class_stream_writable
<ide><path>doc/api/http2.md
<ide> added: v8.4.0
<ide> This object is created internally by an HTTP server — not by the user. It is
<ide> passed as the second parameter to the [`'request'`][] event.
<ide>
<del>The response implements, but does not inherit from, the [Writable Stream][]
<del>interface. This is an [`EventEmitter`][] with the following events:
<add>The response inherits from [Stream][], and additionally implements the
<add>following:
<ide>
<ide> #### Event: 'close'
<ide> <!-- YAML
<ide> following additional properties:
<ide> [Readable Stream]: stream.html#stream_class_stream_readable
<ide> [RFC 7838]: https://tools.ietf.org/html/rfc7838
<ide> [Using `options.selectPadding()`]: #http2_using_options_selectpadding
<del>[Writable Stream]: stream.html#stream_writable_streams
<ide> [`'checkContinue'`]: #http2_event_checkcontinue
<ide> [`'request'`]: #http2_event_request
<ide> [`'unknownProtocol'`]: #http2_event_unknownprotocol
<ide> [`ClientHttp2Stream`]: #http2_class_clienthttp2stream
<ide> [`Duplex`]: stream.html#stream_class_stream_duplex
<del>[`EventEmitter`]: events.html#events_class_eventemitter
<ide> [`Http2ServerRequest`]: #http2_class_http2_http2serverrequest
<ide> [`Http2Session` and Sockets]: #http2_http2session_and_sockets
<ide> [`Http2Stream`]: #http2_class_http2stream | 2 |
Javascript | Javascript | replace obsolete tt element | 7a04968673228e3d0afa957a271add6934a6cafc | <ide><path>src/ng/directive/form.js
<ide> function FormController(element, attrs, $scope, $animate, $interpolate) {
<ide> <form name="myForm" ng-controller="FormController" class="my-form">
<ide> userType: <input name="input" ng-model="userType" required>
<ide> <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
<del> <tt>userType = {{userType}}</tt><br>
<del> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br>
<del> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br>
<del> <tt>myForm.$valid = {{myForm.$valid}}</tt><br>
<del> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
<add> <code>userType = {{userType}}</code><br>
<add> <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br>
<add> <code>myForm.input.$error = {{myForm.input.$error}}</code><br>
<add> <code>myForm.$valid = {{myForm.$valid}}</code><br>
<add> <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br>
<ide> </form>
<ide> </file>
<ide> <file name="protractor.js" type="protractor"> | 1 |
Javascript | Javascript | add test case for loading 404 on invalid bundle | 1c057e779256d8f153d33651301e603e5cf9d276 | <ide><path>test/integration/client-404/pages/invalid-link.js
<add>import Link from 'next/link'
<add>
<add>export default () => (
<add> <Link href="/[id]/non-existent" as="/another/non-existent">
<add> <a id="to-nonexistent">to 404</a>
<add> </Link>
<add>)
<ide><path>test/integration/client-404/test/client-navigation.js
<ide> /* eslint-env jest */
<ide> import webdriver from 'next-webdriver'
<add>import { check } from 'next-test-utils'
<ide>
<ide> export default (context) => {
<ide> describe('Client Navigation 404', () => {
<ide> export default (context) => {
<ide> await browser.close()
<ide> })
<ide> })
<add>
<add> it('should hard navigate to URL on failing to load bundle', async () => {
<add> const browser = await webdriver(context.appPort, '/invalid-link')
<add> await browser.eval(() => (window.beforeNav = 'hi'))
<add> await browser.elementByCss('#to-nonexistent').click()
<add> await check(() => browser.elementByCss('#errorStatusCode').text(), /404/)
<add> expect(await browser.eval(() => window.beforeNav)).not.toBe('hi')
<add> })
<ide> })
<ide> }
<ide><path>test/integration/client-404/test/index.test.js
<ide> /* eslint-env jest */
<ide>
<ide> import { join } from 'path'
<del>import { renderViaHTTP, findPort, launchApp, killApp } from 'next-test-utils'
<add>import {
<add> renderViaHTTP,
<add> findPort,
<add> launchApp,
<add> killApp,
<add> nextBuild,
<add> nextStart,
<add>} from 'next-test-utils'
<ide>
<ide> // test suite
<ide> import clientNavigation from './client-navigation'
<ide>
<ide> const context = {}
<add>const appDir = join(__dirname, '../')
<ide> jest.setTimeout(1000 * 60 * 5)
<ide>
<add>const runTests = () => {
<add> clientNavigation(context, (p, q) => renderViaHTTP(context.appPort, p, q))
<add>}
<add>
<ide> describe('Client 404', () => {
<del> beforeAll(async () => {
<del> context.appPort = await findPort()
<del> context.server = await launchApp(join(__dirname, '../'), context.appPort)
<add> describe('dev mode', () => {
<add> beforeAll(async () => {
<add> context.appPort = await findPort()
<add> context.server = await launchApp(appDir, context.appPort)
<add>
<add> // pre-build page at the start
<add> await renderViaHTTP(context.appPort, '/')
<add> })
<add> afterAll(() => killApp(context.server))
<ide>
<del> // pre-build page at the start
<del> await renderViaHTTP(context.appPort, '/')
<add> runTests()
<ide> })
<del> afterAll(() => killApp(context.server))
<ide>
<del> clientNavigation(context, (p, q) => renderViaHTTP(context.appPort, p, q))
<add> describe('production mode', () => {
<add> beforeAll(async () => {
<add> await nextBuild(appDir)
<add> context.appPort = await findPort()
<add> context.server = await nextStart(appDir, context.appPort)
<add> })
<add> afterAll(() => killApp(context.server))
<add>
<add> runTests()
<add> })
<ide> }) | 3 |
Javascript | Javascript | add modelview and normalview matrices | b59ce1721c59b687e0870958a4b477ea195b3269 | <ide><path>src/renderers/WebGLRenderer.js
<ide> function WebGLRenderer( parameters ) {
<ide> object.onBeforeRender( _this, scene, camera, geometry, material, group );
<ide> currentRenderState = renderStates.get( scene, _currentArrayCamera || camera );
<ide>
<del> object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
<del> object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
<add> if ( multiview.isEnabled() ) {
<add>
<add> multiview.computeObjectMatrices( object, camera );
<add>
<add> } else {
<add>
<add> object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
<add> object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
<add>
<add> }
<ide>
<ide> if ( object.isImmediateRenderObject ) {
<ide>
<ide> function WebGLRenderer( parameters ) {
<ide>
<ide> // common matrices
<ide>
<del> p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
<del> p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
<add> if ( material.supportsMultiview && multiview.isEnabled() ) {
<add>
<add> p_uniforms.setValue( _gl, 'modelViewMatrices', object.modelViewMatrices );
<add> p_uniforms.setValue( _gl, 'normalMatrices', object.normalMatrices );
<add>
<add> } else {
<add>
<add> p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
<add> p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
<add>
<add> }
<add>
<ide> p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
<ide>
<ide> return program;
<ide><path>src/renderers/webgl/WebGLMultiview.js
<ide> */
<ide>
<ide> import { WebGLRenderTarget } from '../WebGLRenderTarget.js';
<add>import { Matrix3 } from '../../math/Matrix3.js';
<add>import { Matrix4 } from '../../math/Matrix4.js';
<ide>
<ide> function WebGLMultiview( requested, gl, canvas, extensions, capabilities, properties ) {
<ide>
<ide> function WebGLMultiview( requested, gl, canvas, extensions, capabilities, proper
<ide>
<ide> };
<ide>
<del>
<ide> if ( requested && ! this.isAvailable() ) {
<ide>
<ide> console.warn( 'WebGLRenderer: Multiview requested but not supported by the browser' );
<ide> function WebGLMultiview( requested, gl, canvas, extensions, capabilities, proper
<ide> depthStencil: null
<ide> };
<ide>
<add> this.computeObjectMatrices = function ( object, camera ) {
<add>
<add> if ( ! object.modelViewMatrices ) {
<add>
<add> object.modelViewMatrices = new Array( numViews );
<add> object.normalMatrices = new Array( numViews );
<add>
<add> for ( var i = 0; i < numViews; i ++ ) {
<add>
<add> object.modelViewMatrices[ i ] = new Matrix4();
<add> object.normalMatrices[ i ] = new Matrix3();
<add>
<add> }
<add>
<add> }
<add>
<add> if ( camera.isArrayCamera ) {
<add>
<add> for ( var i = 0; i < numViews; i ++ ) {
<add>
<add> object.modelViewMatrices[ i ].multiplyMatrices( camera.cameras[ i ].matrixWorldInverse, object.matrixWorld );
<add> object.normalMatrices[ i ].getNormalMatrix( object.modelViewMatrices[ i ] );
<add>
<add> }
<add>
<add> } else {
<add>
<add> // In this case we still need to provide an array of matrices but just the first one will be used
<add> object.modelViewMatrices[ 0 ].multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
<add> object.normalMatrices[ 0 ].getNormalMatrix( object.modelViewMatrices[ 0 ] );
<add>
<add> for ( var i = 0; i < numViews; i ++ ) {
<add>
<add> object.modelViewMatrices[ i ].copy( object.modelViewMatrices[ 0 ] );
<add> object.normalMatrices[ i ].copy( object.normalMatrices[ 0 ] );
<add>
<add> }
<add>
<add> }
<add>
<add> };
<ide>
<ide> // @todo Get ArrayCamera
<ide> this.createMultiviewRenderTargetTexture = function () {
<ide><path>src/renderers/webgl/WebGLProgram.js
<ide> function WebGLProgram( renderer, extensions, code, material, shader, parameters,
<ide> 'uniform vec3 cameraPosition;',
<ide>
<ide> material.supportsMultiview && renderer.multiview.isEnabled() ? [
<del> 'uniform mat4 modelViewMatrix;',
<del> 'uniform mat3 normalMatrix;',
<add> 'uniform mat4 modelViewMatrices[2];',
<add> 'uniform mat3 normalMatrices[2];',
<ide> 'uniform mat4 viewMatrices[2];',
<ide> 'uniform mat4 projectionMatrices[2];',
<ide>
<add> '#define modelViewMatrix modelViewMatrices[VIEW_ID]',
<add> '#define normalMatrix normalMatrices[VIEW_ID]',
<ide> '#define viewMatrix viewMatrices[VIEW_ID]',
<ide> '#define projectionMatrix projectionMatrices[VIEW_ID]'
<ide> | 3 |
Text | Text | add changelog for | f186a00aac8f5b79aaee06cdd9d52dbedb427b3c | <ide><path>activesupport/CHANGELOG.md
<add>* Allow serializing any module or class to JSON by name
<add>
<add> *Tyler Rick*, *Zachary Scott*
<add>
<ide> * Raise `ActiveSupport::EncryptedFile::MissingKeyError` when the
<ide> `RAILS_MASTER_KEY` environment variable is blank (e.g. `""`).
<ide> | 1 |
Java | Java | fix checkstyle violation | b1b25fab00739eafad82bb80b9409cac61b0a5be | <ide><path>spring-oxm/src/main/java/org/springframework/oxm/castor/CastorMarshaller.java
<ide> import java.io.Reader;
<ide> import java.io.Writer;
<ide> import java.util.Map;
<add>
<ide> import javax.xml.stream.XMLEventReader;
<ide> import javax.xml.stream.XMLEventWriter;
<ide> import javax.xml.stream.XMLStreamReader; | 1 |
Ruby | Ruby | ignore unused parameter | 95a8a50aa0d968f6ab762bef7ca9f78bb7043463 | <ide><path>Library/Homebrew/install_renamed.rb
<ide> module InstallRenamed
<del> def install_p src, new_basename = nil
<add> def install_p _, new_basename = nil
<ide> super do |src, dst|
<ide> dst += "/#{File.basename(src)}" if File.directory? dst
<ide> | 1 |
Ruby | Ruby | relation#sum compatibility with array#sum | e7bec4e435d05eb517f515a4661186ce8d088238 | <ide><path>activerecord/lib/active_record/relation/calculations.rb
<ide> def maximum(column_name, options = {})
<ide> # +calculate+ for examples with options.
<ide> #
<ide> # Person.sum('age') # => 4562
<del> def sum(column_name, options = {})
<del> calculate(:sum, column_name, options)
<add> def sum(*args)
<add> if block_given?
<add> self.to_a.sum(*args) {|*block_args| yield(*block_args)}
<add> else
<add> calculate(:sum, *args)
<add> end
<ide> end
<ide>
<ide> # This calculates aggregate values in the given column. Methods for count, sum, average,
<ide><path>activerecord/test/cases/calculations_test.rb
<ide> def test_sum_with_from_option
<ide> Account.sum(:credit_limit, :from => 'accounts', :conditions => "credit_limit > 50")
<ide> end
<ide>
<add> def test_sum_array_compatibility
<add> assert_equal Account.sum(:credit_limit), Account.sum(&:credit_limit)
<add> end
<add>
<ide> def test_average_with_from_option
<ide> assert_equal Account.average(:credit_limit), Account.average(:credit_limit, :from => 'accounts')
<ide> assert_equal Account.average(:credit_limit, :conditions => "credit_limit > 50"), | 2 |
PHP | PHP | remove unused filesystem | f27fd58b42ef1b84215879aee21729e4202e4f3f | <ide><path>src/Illuminate/Foundation/start.php
<ide> */
<ide>
<ide> use Illuminate\Http\Request;
<del>use Illuminate\Filesystem\Filesystem;
<ide> use Illuminate\Support\Facades\Facade;
<ide> use Illuminate\Foundation\AliasLoader;
<ide> use Illuminate\Config\Repository as Config;
<ide>
<ide> if (file_exists($routes)) require $routes;
<ide>
<del>});
<ide>\ No newline at end of file
<add>}); | 1 |
Go | Go | reset removalinprogress flag on daemon restart | ce724731973159a4fcedf16d0996571684cc3843 | <ide><path>daemon/daemon.go
<ide> func (daemon *Daemon) restore() error {
<ide> mapLock.Unlock()
<ide> }
<ide>
<add> if c.RemovalInProgress {
<add> // We probably crashed in the middle of a removal, reset
<add> // the flag.
<add> //
<add> // We DO NOT remove the container here as we do not
<add> // know if the user had requested for either the
<add> // associated volumes, network links or both to also
<add> // be removed. So we put the container in the "dead"
<add> // state and leave further processing up to them.
<add> logrus.Debugf("Resetting RemovalInProgress flag from %v", c.ID)
<add> c.ResetRemovalInProgress()
<add> c.SetDead()
<add> c.ToDisk()
<add> }
<add>
<ide> // if c.hostConfig.Links is nil (not just empty), then it is using the old sqlite links and needs to be migrated
<ide> if c.HostConfig != nil && c.HostConfig.Links == nil {
<ide> migrateLegacyLinks = true | 1 |
Java | Java | use bytebuf instead of buffer in reactor-netty | 0e5a892bad25a3ebcf018763c46fc6c8cfa15de8 | <ide><path>spring-web-reactive/src/main/java/org/springframework/http/client/reactive/ReactorClientHttpRequest.java
<ide> import java.net.URI;
<ide> import java.util.Collection;
<ide>
<add>import io.netty.buffer.ByteBuf;
<add>import io.netty.buffer.Unpooled;
<ide> import io.netty.handler.codec.http.cookie.DefaultCookie;
<ide> import org.reactivestreams.Publisher;
<ide> import reactor.core.publisher.Flux;
<ide> import reactor.core.publisher.Mono;
<del>import reactor.io.buffer.Buffer;
<ide> import reactor.io.netty.http.HttpClient;
<ide>
<ide> import org.springframework.core.io.buffer.DataBuffer;
<ide> import org.springframework.core.io.buffer.DataBufferAllocator;
<add>import org.springframework.core.io.buffer.DefaultDataBufferAllocator;
<add>import org.springframework.core.io.buffer.NettyDataBuffer;
<add>import org.springframework.core.io.buffer.NettyDataBufferAllocator;
<ide> import org.springframework.http.HttpHeaders;
<ide> import org.springframework.http.HttpMethod;
<ide>
<ide> public class ReactorClientHttpRequest extends AbstractClientHttpRequest {
<ide>
<ide> private final HttpClient httpClient;
<ide>
<del> private Flux<Buffer> body;
<add> private Flux<ByteBuf> body;
<ide>
<ide>
<del> public ReactorClientHttpRequest(HttpMethod httpMethod, URI uri, HttpClient httpClient, HttpHeaders headers,
<del> DataBufferAllocator allocator) {
<add> public ReactorClientHttpRequest(HttpMethod httpMethod, URI uri, HttpClient httpClient, HttpHeaders headers) {
<ide> super(headers);
<del> this.allocator = allocator;
<add> //FIXME use Netty allocator
<add> this.allocator = new DefaultDataBufferAllocator();
<ide> this.httpMethod = httpMethod;
<ide> this.uri = uri;
<ide> this.httpClient = httpClient;
<ide> public URI getURI() {
<ide> @Override
<ide> public Mono<Void> setBody(Publisher<DataBuffer> body) {
<ide>
<del> this.body = Flux.from(body).map(b -> new Buffer(b.asByteBuffer()));
<add> this.body = Flux.from(body).map(this::toByteBuf);
<ide> return Mono.empty();
<ide> }
<ide>
<ide> public Mono<ClientHttpResponse> execute() {
<ide> .map(httpChannel -> new ReactorClientHttpResponse(httpChannel, allocator));
<ide> }
<ide>
<del>
<add> private ByteBuf toByteBuf(DataBuffer buffer) {
<add> if (buffer instanceof NettyDataBuffer) {
<add> return ((NettyDataBuffer) buffer).getNativeBuffer();
<add> }
<add> else {
<add> return Unpooled.wrappedBuffer(buffer.asByteBuffer());
<add> }
<add> }
<ide>
<ide> }
<ide>
<ide><path>spring-web-reactive/src/main/java/org/springframework/http/client/reactive/ReactorClientHttpResponse.java
<ide>
<ide> import org.springframework.core.io.buffer.DataBuffer;
<ide> import org.springframework.core.io.buffer.DataBufferAllocator;
<add>import org.springframework.core.io.buffer.NettyDataBufferAllocator;
<ide> import org.springframework.http.HttpHeaders;
<ide> import org.springframework.http.HttpStatus;
<ide> import org.springframework.http.ResponseCookie;
<ide> public ReactorClientHttpResponse(HttpInbound channel, DataBufferAllocator alloca
<ide>
<ide> @Override
<ide> public Flux<DataBuffer> getBody() {
<del> return channel.receive().map(b -> allocator.wrap(b.byteBuffer()));
<add> return channel.receiveByteBuffer().map(allocator::wrap);
<ide> }
<ide>
<ide> @Override
<ide><path>spring-web-reactive/src/main/java/org/springframework/http/client/reactive/ReactorHttpClientRequestFactory.java
<ide>
<ide> import org.springframework.core.io.buffer.DataBufferAllocator;
<ide> import org.springframework.core.io.buffer.DefaultDataBufferAllocator;
<add>import org.springframework.core.io.buffer.NettyDataBufferAllocator;
<ide> import org.springframework.http.HttpHeaders;
<ide> import org.springframework.http.HttpMethod;
<ide> import org.springframework.util.Assert;
<ide> */
<ide> public class ReactorHttpClientRequestFactory implements ClientHttpRequestFactory {
<ide>
<del> private final DataBufferAllocator allocator;
<del>
<ide> private final HttpClient httpClient;
<ide>
<ide> public ReactorHttpClientRequestFactory() {
<del> this(new DefaultDataBufferAllocator());
<del> }
<del>
<del> public ReactorHttpClientRequestFactory(DataBufferAllocator allocator) {
<del> this(allocator, reactor.io.netty.http.HttpClient.create());
<add> this(reactor.io.netty.http.HttpClient.create());
<ide> }
<ide>
<del> protected ReactorHttpClientRequestFactory(DataBufferAllocator allocator, HttpClient httpClient) {
<del> this.allocator = allocator;
<add> protected ReactorHttpClientRequestFactory(HttpClient httpClient) {
<ide> this.httpClient = httpClient;
<ide> }
<ide>
<ide> public ClientHttpRequest createRequest(HttpMethod httpMethod, URI uri, HttpHeade
<ide> Assert.notNull(uri, "request URI is required");
<ide> Assert.notNull(headers, "request headers are required");
<ide>
<del> return new ReactorClientHttpRequest(httpMethod, uri, this.httpClient, headers, this.allocator);
<add> return new ReactorClientHttpRequest(httpMethod, uri, this.httpClient, headers);
<ide> }
<ide>
<ide> }
<ide><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/ReactorHttpHandlerAdapter.java
<ide>
<ide> package org.springframework.http.server.reactive;
<ide>
<add>import io.netty.buffer.ByteBuf;
<ide> import reactor.core.publisher.Mono;
<del>import reactor.io.buffer.Buffer;
<ide> import reactor.io.ipc.ChannelHandler;
<ide> import reactor.io.netty.http.HttpChannel;
<ide>
<del>import org.springframework.core.io.buffer.DataBufferAllocator;
<add>import org.springframework.core.io.buffer.NettyDataBufferAllocator;
<ide> import org.springframework.util.Assert;
<ide>
<ide> /**
<ide> * @author Stephane Maldini
<ide> */
<ide> public class ReactorHttpHandlerAdapter
<del> implements ChannelHandler<Buffer, Buffer, HttpChannel> {
<add> implements ChannelHandler<ByteBuf, ByteBuf, HttpChannel> {
<ide>
<ide> private final HttpHandler httpHandler;
<ide>
<del> private final DataBufferAllocator allocator;
<del>
<del> public ReactorHttpHandlerAdapter(HttpHandler httpHandler,
<del> DataBufferAllocator allocator) {
<add> public ReactorHttpHandlerAdapter(HttpHandler httpHandler) {
<ide> Assert.notNull(httpHandler, "'httpHandler' is required.");
<ide> this.httpHandler = httpHandler;
<del> this.allocator = allocator;
<ide> }
<ide>
<ide> @Override
<ide> public Mono<Void> apply(HttpChannel channel) {
<add> NettyDataBufferAllocator allocator =
<add> new NettyDataBufferAllocator(channel.delegate().alloc());
<add>
<ide> ReactorServerHttpRequest adaptedRequest =
<ide> new ReactorServerHttpRequest(channel, allocator);
<ide> ReactorServerHttpResponse adaptedResponse =
<ide><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/ReactorServerHttpRequest.java
<ide>
<ide> import org.springframework.core.io.buffer.DataBuffer;
<ide> import org.springframework.core.io.buffer.DataBufferAllocator;
<add>import org.springframework.core.io.buffer.NettyDataBufferAllocator;
<ide> import org.springframework.http.HttpCookie;
<ide> import org.springframework.http.HttpHeaders;
<ide> import org.springframework.http.HttpMethod;
<ide> public class ReactorServerHttpRequest extends AbstractServerHttpRequest {
<ide>
<ide> private final HttpChannel channel;
<ide>
<del> private final DataBufferAllocator allocator;
<add> private final NettyDataBufferAllocator allocator;
<ide>
<ide> public ReactorServerHttpRequest(HttpChannel request,
<del> DataBufferAllocator allocator) {
<add> NettyDataBufferAllocator allocator) {
<ide> Assert.notNull("'request' must not be null");
<ide> Assert.notNull(allocator, "'allocator' must not be null");
<ide> this.channel = request;
<ide> protected MultiValueMap<String, HttpCookie> initCookies() {
<ide>
<ide> @Override
<ide> public Flux<DataBuffer> getBody() {
<del> return Flux.from(this.channel.receive()).map(bytes -> {
<del> ByteBuffer byteBuffer = bytes.byteBuffer();
<del> return allocator.wrap(byteBuffer);
<del> });
<add> return this.channel.receive().map(allocator::wrap);
<ide> }
<ide>
<ide> }
<ide><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/ReactorServerHttpResponse.java
<ide>
<ide> package org.springframework.http.server.reactive;
<ide>
<add>import io.netty.buffer.ByteBuf;
<add>import io.netty.buffer.Unpooled;
<ide> import io.netty.handler.codec.http.HttpResponseStatus;
<ide> import io.netty.handler.codec.http.cookie.Cookie;
<ide> import io.netty.handler.codec.http.cookie.DefaultCookie;
<ide> import org.reactivestreams.Publisher;
<ide> import reactor.core.publisher.Flux;
<ide> import reactor.core.publisher.Mono;
<del>import reactor.io.buffer.Buffer;
<ide> import reactor.io.netty.http.HttpChannel;
<ide>
<ide> import org.springframework.core.io.buffer.DataBuffer;
<ide> import org.springframework.core.io.buffer.DataBufferAllocator;
<add>import org.springframework.core.io.buffer.NettyDataBuffer;
<ide> import org.springframework.http.HttpStatus;
<ide> import org.springframework.http.ResponseCookie;
<ide> import org.springframework.util.Assert;
<ide> public void setStatusCode(HttpStatus status) {
<ide>
<ide> @Override
<ide> protected Mono<Void> setBodyInternal(Publisher<DataBuffer> publisher) {
<del> return Mono.from(this.channel.send(
<del> Flux.from(publisher).map(buffer -> new Buffer(buffer.asByteBuffer()))));
<add> return this.channel.send(Flux.from(publisher).map(this::toByteBuf));
<ide> }
<ide>
<ide> @Override
<ide> protected void writeCookies() {
<ide> }
<ide> }
<ide>
<add> private ByteBuf toByteBuf(DataBuffer buffer) {
<add> if (buffer instanceof NettyDataBuffer) {
<add> return ((NettyDataBuffer) buffer).getNativeBuffer();
<add> }
<add> else {
<add> return Unpooled.wrappedBuffer(buffer.asByteBuffer());
<add> }
<add> }
<ide> }
<ide><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/boot/ReactorHttpServer.java
<ide>
<ide> import reactor.core.flow.Loopback;
<ide> import reactor.core.state.Completable;
<del>import reactor.io.buffer.Buffer;
<ide>
<del>import org.springframework.core.io.buffer.DataBufferAllocator;
<del>import org.springframework.core.io.buffer.DefaultDataBufferAllocator;
<ide> import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter;
<ide> import org.springframework.util.Assert;
<ide>
<ide> public class ReactorHttpServer extends HttpServerSupport
<ide>
<ide> private reactor.io.netty.http.HttpServer reactorServer;
<ide>
<del> private DataBufferAllocator allocator = new DefaultDataBufferAllocator();
<del>
<ide> private boolean running;
<ide>
<del> public void setAllocator(DataBufferAllocator allocator) {
<del> this.allocator = allocator;
<del> }
<del>
<ide> @Override
<ide> public void afterPropertiesSet() throws Exception {
<ide>
<ide> Assert.notNull(getHttpHandler());
<del> this.reactorHandler = new ReactorHttpHandlerAdapter(getHttpHandler(), allocator);
<add> this.reactorHandler = new ReactorHttpHandlerAdapter(getHttpHandler());
<ide>
<ide> this.reactorServer = (getPort() != -1 ? reactor.io.netty.http.HttpServer.create(getPort()) :
<ide> reactor.io.netty.http.HttpServer.create());
<ide><path>spring-web-reactive/src/test/java/org/springframework/web/client/reactive/WebClientIntegrationTests.java
<ide> public void shouldGetHeaders() throws Exception {
<ide> .perform(get(baseUrl.toString()))
<ide> .extract(headers());
<ide>
<del> TestSubscriber<HttpHeaders> ts = new TestSubscriber();
<add> TestSubscriber<HttpHeaders> ts = new TestSubscriber<>();
<ide> result.subscribe(ts);
<ide> ts.awaitAndAssertNextValuesWith(
<ide> httpHeaders -> {
<ide> public void shouldGetPlainTextResponseAsObject() throws Exception {
<ide> .extract(body(String.class));
<ide>
<ide>
<del> TestSubscriber<String> ts = new TestSubscriber();
<add> TestSubscriber<String> ts = new TestSubscriber<>();
<ide> result.subscribe(ts);
<ide> ts.awaitAndAssertNextValues("Hello Spring!").assertComplete();
<ide>
<ide> public void shouldGetPlainTextResponse() throws Exception {
<ide> .accept(MediaType.TEXT_PLAIN))
<ide> .extract(response(String.class));
<ide>
<del> TestSubscriber<ResponseEntity<String>> ts = new TestSubscriber();
<add> TestSubscriber<ResponseEntity<String>> ts = new TestSubscriber<>();
<ide> result.subscribe(ts);
<del> ts.awaitAndAssertNextValuesWith(new Consumer<ResponseEntity<String>>() {
<del> @Override
<del> public void accept(ResponseEntity<String> response) {
<del> assertEquals(200, response.getStatusCode().value());
<del> assertEquals(MediaType.TEXT_PLAIN, response.getHeaders().getContentType());
<del> assertEquals("Hello Spring!", response.getBody());
<del> }
<add> ts.awaitAndAssertNextValuesWith((Consumer<ResponseEntity<String>>) response -> {
<add> assertEquals(200, response.getStatusCode().value());
<add> assertEquals(MediaType.TEXT_PLAIN, response.getHeaders().getContentType());
<add> assertEquals("Hello Spring!", response.getBody());
<ide> });
<ide> RecordedRequest request = server.takeRequest();
<ide> assertEquals(1, server.getRequestCount());
<ide> public void shouldGetJsonAsMonoOfString() throws Exception {
<ide> .accept(MediaType.APPLICATION_JSON))
<ide> .extract(body(String.class));
<ide>
<del> TestSubscriber<String> ts = new TestSubscriber();
<add> TestSubscriber<String> ts = new TestSubscriber<>();
<ide> result.subscribe(ts);
<ide> ts.awaitAndAssertNextValues(content).assertComplete();
<ide> RecordedRequest request = server.takeRequest();
<ide> public void shouldGetJsonAsMonoOfPojo() throws Exception {
<ide> .accept(MediaType.APPLICATION_JSON))
<ide> .extract(body(Pojo.class));
<ide>
<del> TestSubscriber<Pojo> ts = new TestSubscriber();
<add> TestSubscriber<Pojo> ts = new TestSubscriber<>();
<ide> result.subscribe(ts);
<ide> ts.awaitAndAssertNextValuesWith(p -> assertEquals("barbar", p.getBar())).assertComplete();
<ide> RecordedRequest request = server.takeRequest();
<ide> public void shouldGetJsonAsFluxOfPojos() throws Exception {
<ide> .accept(MediaType.APPLICATION_JSON))
<ide> .extract(bodyStream(Pojo.class));
<ide>
<del> TestSubscriber<Pojo> ts = new TestSubscriber();
<add> TestSubscriber<Pojo> ts = new TestSubscriber<>();
<ide> result.subscribe(ts);
<ide> ts.awaitAndAssertNextValuesWith(
<ide> p -> assertThat(p.getBar(), Matchers.is("bar1")),
<ide> public void shouldGetJsonAsResponseOfPojosStream() throws Exception {
<ide> .accept(MediaType.APPLICATION_JSON))
<ide> .extract(responseStream(Pojo.class));
<ide>
<del> TestSubscriber<ResponseEntity<Flux<Pojo>>> ts = new TestSubscriber();
<add> TestSubscriber<ResponseEntity<Flux<Pojo>>> ts = new TestSubscriber<>();
<ide> result.subscribe(ts);
<ide> ts.awaitAndAssertNextValuesWith(
<ide> response -> {
<ide> public void shouldPostPojoAsJson() throws Exception {
<ide> .accept(MediaType.APPLICATION_JSON))
<ide> .extract(body(Pojo.class));
<ide>
<del> TestSubscriber<Pojo> ts = new TestSubscriber();
<add> TestSubscriber<Pojo> ts = new TestSubscriber<>();
<ide> result.subscribe(ts);
<ide> ts.awaitAndAssertNextValuesWith(p -> assertEquals("BARBAR", p.getBar())).assertComplete();
<ide>
<ide> public void shouldGetErrorWhen404() throws Exception {
<ide> .extract(body(String.class));
<ide>
<ide>
<del> TestSubscriber<String> ts = new TestSubscriber();
<add> TestSubscriber<String> ts = new TestSubscriber<>();
<ide> result.subscribe(ts);
<ide> // TODO: error message should be converted to a ClientException
<ide> ts.await().assertError(); | 8 |
PHP | PHP | remove unneeded property. can use ignore method | ce3e006d61299bdd3bd2b99ec5489577e55a296a | <ide><path>app/Exceptions/Handler.php
<ide>
<ide> class Handler extends ExceptionHandler
<ide> {
<del> /**
<del> * A list of the exception types that are not reported.
<del> *
<del> * @var array
<del> */
<del> protected $dontReport = [
<del> //
<del> ];
<del>
<ide> /**
<ide> * A list of the inputs that are never flashed for validation exceptions.
<ide> * | 1 |
PHP | PHP | fix failing test | 9fd3a007655260dc50608011be4fe60a4c850aa6 | <ide><path>lib/Cake/Test/TestCase/Database/Schema/TableTest.php
<ide> public function testPrimaryKey() {
<ide> $table->addColumn('id', 'integer')
<ide> ->addColumn('title', 'string')
<ide> ->addColumn('author_id', 'integer')
<del> ->addIndex('author_idx', [
<add> ->addConstraint('author_idx', [
<ide> 'columns' => ['author_id'],
<ide> 'type' => 'unique'
<del> ])->addIndex('primary', [
<add> ])->addConstraint('primary', [
<ide> 'type' => 'primary',
<ide> 'columns' => ['id']
<ide> ]); | 1 |
Go | Go | add containercreateresponse type | f57c26553b91e16fa3ee6a815943eaf8f29af82b | <ide><path>api/client/commands.go
<ide> func (cid *cidFile) Write(id string) error {
<ide> return nil
<ide> }
<ide>
<del>func (cli *DockerCli) createContainer(config *runconfig.Config, hostConfig *runconfig.HostConfig, cidfile, name string) (engine.Env, error) {
<add>func (cli *DockerCli) createContainer(config *runconfig.Config, hostConfig *runconfig.HostConfig, cidfile, name string) (*types.ContainerCreateResponse, error) {
<ide> containerValues := url.Values{}
<ide> if name != "" {
<ide> containerValues.Set("name", name)
<ide> func (cli *DockerCli) createContainer(config *runconfig.Config, hostConfig *runc
<ide> return nil, err
<ide> }
<ide>
<del> var result engine.Env
<del> if err := result.Decode(stream); err != nil {
<add> var response types.ContainerCreateResponse
<add> if err := json.NewDecoder(stream).Decode(&response); err != nil {
<ide> return nil, err
<ide> }
<del>
<del> for _, warning := range result.GetList("Warnings") {
<add> for _, warning := range response.Warnings {
<ide> fmt.Fprintf(cli.err, "WARNING: %s\n", warning)
<ide> }
<del>
<ide> if containerIDFile != nil {
<del> if err = containerIDFile.Write(result.Get("Id")); err != nil {
<add> if err = containerIDFile.Write(response.ID); err != nil {
<ide> return nil, err
<ide> }
<ide> }
<del>
<del> return result, nil
<del>
<add> return &response, nil
<ide> }
<ide>
<ide> func (cli *DockerCli) CmdCreate(args ...string) error {
<ide> func (cli *DockerCli) CmdCreate(args ...string) error {
<ide> cmd.Usage()
<ide> return nil
<ide> }
<del>
<del> createResult, err := cli.createContainer(config, hostConfig, hostConfig.ContainerIDFile, *flName)
<add> response, err := cli.createContainer(config, hostConfig, hostConfig.ContainerIDFile, *flName)
<ide> if err != nil {
<ide> return err
<ide> }
<del>
<del> fmt.Fprintf(cli.out, "%s\n", createResult.Get("Id"))
<del>
<add> fmt.Fprintf(cli.out, "%s\n", response.ID)
<ide> return nil
<ide> }
<ide>
<ide> func (cli *DockerCli) CmdRun(args ...string) error {
<ide> sigProxy = false
<ide> }
<ide>
<del> runResult, err := cli.createContainer(config, hostConfig, hostConfig.ContainerIDFile, *flName)
<add> createResponse, err := cli.createContainer(config, hostConfig, hostConfig.ContainerIDFile, *flName)
<ide> if err != nil {
<ide> return err
<ide> }
<del>
<ide> if sigProxy {
<del> sigc := cli.forwardAllSignals(runResult.Get("Id"))
<add> sigc := cli.forwardAllSignals(createResponse.ID)
<ide> defer signal.StopCatch(sigc)
<ide> }
<del>
<ide> var (
<ide> waitDisplayId chan struct{}
<ide> errCh chan error
<ide> )
<del>
<ide> if !config.AttachStdout && !config.AttachStderr {
<ide> // Make this asynchronous to allow the client to write to stdin before having to read the ID
<ide> waitDisplayId = make(chan struct{})
<ide> go func() {
<ide> defer close(waitDisplayId)
<del> fmt.Fprintf(cli.out, "%s\n", runResult.Get("Id"))
<add> fmt.Fprintf(cli.out, "%s\n", createResponse.ID)
<ide> }()
<ide> }
<del>
<ide> if *flAutoRemove && (hostConfig.RestartPolicy.Name == "always" || hostConfig.RestartPolicy.Name == "on-failure") {
<ide> return ErrConflictRestartPolicyAndAutoRemove
<ide> }
<del>
<ide> // We need to instantiate the chan because the select needs it. It can
<ide> // be closed but can't be uninitialized.
<ide> hijacked := make(chan io.Closer)
<del>
<ide> // Block the return until the chan gets closed
<ide> defer func() {
<ide> log.Debugf("End of CmdRun(), Waiting for hijack to finish.")
<ide> if _, ok := <-hijacked; ok {
<ide> log.Errorf("Hijack did not finish (chan still open)")
<ide> }
<ide> }()
<del>
<ide> if config.AttachStdin || config.AttachStdout || config.AttachStderr {
<ide> var (
<ide> out, stderr io.Writer
<ide> in io.ReadCloser
<ide> v = url.Values{}
<ide> )
<ide> v.Set("stream", "1")
<del>
<ide> if config.AttachStdin {
<ide> v.Set("stdin", "1")
<ide> in = cli.in
<ide> func (cli *DockerCli) CmdRun(args ...string) error {
<ide> stderr = cli.err
<ide> }
<ide> }
<del>
<ide> errCh = promise.Go(func() error {
<del> return cli.hijack("POST", "/containers/"+runResult.Get("Id")+"/attach?"+v.Encode(), config.Tty, in, out, stderr, hijacked, nil)
<add> return cli.hijack("POST", "/containers/"+createResponse.ID+"/attach?"+v.Encode(), config.Tty, in, out, stderr, hijacked, nil)
<ide> })
<ide> } else {
<ide> close(hijacked)
<ide> }
<del>
<ide> // Acknowledge the hijack before starting
<ide> select {
<ide> case closer := <-hijacked:
<ide> func (cli *DockerCli) CmdRun(args ...string) error {
<ide> }
<ide>
<ide> //start the container
<del> if _, _, err = readBody(cli.call("POST", "/containers/"+runResult.Get("Id")+"/start", nil, false)); err != nil {
<add> if _, _, err = readBody(cli.call("POST", "/containers/"+createResponse.ID+"/start", nil, false)); err != nil {
<ide> return err
<ide> }
<ide>
<ide> if (config.AttachStdin || config.AttachStdout || config.AttachStderr) && config.Tty && cli.isTerminalOut {
<del> if err := cli.monitorTtySize(runResult.Get("Id"), false); err != nil {
<add> if err := cli.monitorTtySize(createResponse.ID, false); err != nil {
<ide> log.Errorf("Error monitoring TTY size: %s", err)
<ide> }
<ide> }
<ide> func (cli *DockerCli) CmdRun(args ...string) error {
<ide> if *flAutoRemove {
<ide> // Autoremove: wait for the container to finish, retrieve
<ide> // the exit code and remove the container
<del> if _, _, err := readBody(cli.call("POST", "/containers/"+runResult.Get("Id")+"/wait", nil, false)); err != nil {
<add> if _, _, err := readBody(cli.call("POST", "/containers/"+createResponse.ID+"/wait", nil, false)); err != nil {
<ide> return err
<ide> }
<del> if _, status, err = getExitCode(cli, runResult.Get("Id")); err != nil {
<add> if _, status, err = getExitCode(cli, createResponse.ID); err != nil {
<ide> return err
<ide> }
<del> if _, _, err := readBody(cli.call("DELETE", "/containers/"+runResult.Get("Id")+"?v=1", nil, false)); err != nil {
<add> if _, _, err := readBody(cli.call("DELETE", "/containers/"+createResponse.ID+"?v=1", nil, false)); err != nil {
<ide> return err
<ide> }
<ide> } else {
<ide> // No Autoremove: Simply retrieve the exit code
<ide> if !config.Tty {
<ide> // In non-TTY mode, we can't detach, so we must wait for container exit
<del> if status, err = waitForExit(cli, runResult.Get("Id")); err != nil {
<add> if status, err = waitForExit(cli, createResponse.ID); err != nil {
<ide> return err
<ide> }
<ide> } else {
<ide> // In TTY mode, there is a race: if the process dies too slowly, the state could
<ide> // be updated after the getExitCode call and result in the wrong exit code being reported
<del> if _, status, err = getExitCode(cli, runResult.Get("Id")); err != nil {
<add> if _, status, err = getExitCode(cli, createResponse.ID); err != nil {
<ide> return err
<ide> }
<ide> }
<ide><path>api/server/server.go
<ide> import (
<ide>
<ide> log "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/api"
<add> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/daemon/networkdriver/portallocator"
<ide> "github.com/docker/docker/engine"
<ide> "github.com/docker/docker/pkg/listenbuffer"
<ide> func httpError(w http.ResponseWriter, err error) {
<ide> }
<ide> }
<ide>
<del>func writeJSON(w http.ResponseWriter, code int, v engine.Env) error {
<add>// writeJSONEnv writes the engine.Env values to the http response stream as a
<add>// json encoded body.
<add>func writeJSONEnv(w http.ResponseWriter, code int, v engine.Env) error {
<ide> w.Header().Set("Content-Type", "application/json")
<ide> w.WriteHeader(code)
<ide> return v.Encode(w)
<ide> }
<ide>
<add>// writeJSON writes the value v to the http response stream as json with standard
<add>// json encoding.
<add>func writeJSON(w http.ResponseWriter, code int, v interface{}) error {
<add> w.Header().Set("Content-Type", "application/json")
<add> w.WriteHeader(code)
<add> return json.NewEncoder(w).Encode(v)
<add>}
<add>
<ide> func streamJSON(job *engine.Job, w http.ResponseWriter, flush bool) {
<ide> w.Header().Set("Content-Type", "application/json")
<ide> if flush {
<ide> func postAuth(eng *engine.Engine, version version.Version, w http.ResponseWriter
<ide> if status := engine.Tail(stdoutBuffer, 1); status != "" {
<ide> var env engine.Env
<ide> env.Set("Status", status)
<del> return writeJSON(w, http.StatusOK, env)
<add> return writeJSONEnv(w, http.StatusOK, env)
<ide> }
<ide> w.WriteHeader(http.StatusNoContent)
<ide> return nil
<ide> func postCommit(eng *engine.Engine, version version.Version, w http.ResponseWrit
<ide> return err
<ide> }
<ide> env.Set("Id", engine.Tail(stdoutBuffer, 1))
<del> return writeJSON(w, http.StatusCreated, env)
<add> return writeJSONEnv(w, http.StatusCreated, env)
<ide> }
<ide>
<ide> // Creates an image from Pull or from Import
<ide> func postContainersCreate(eng *engine.Engine, version version.Version, w http.Re
<ide> if err := parseForm(r); err != nil {
<ide> return nil
<ide> }
<add> if err := checkForJson(r); err != nil {
<add> return err
<add> }
<ide> var (
<del> out engine.Env
<ide> job = eng.Job("create", r.Form.Get("name"))
<ide> outWarnings []string
<ide> stdoutBuffer = bytes.NewBuffer(nil)
<ide> warnings = bytes.NewBuffer(nil)
<ide> )
<ide>
<del> if err := checkForJson(r); err != nil {
<del> return err
<del> }
<del>
<ide> if err := job.DecodeEnv(r.Body); err != nil {
<ide> return err
<ide> }
<ide> func postContainersCreate(eng *engine.Engine, version version.Version, w http.Re
<ide> for scanner.Scan() {
<ide> outWarnings = append(outWarnings, scanner.Text())
<ide> }
<del> out.Set("Id", engine.Tail(stdoutBuffer, 1))
<del> out.SetList("Warnings", outWarnings)
<del>
<del> return writeJSON(w, http.StatusCreated, out)
<add> return writeJSON(w, http.StatusCreated, &types.ContainerCreateResponse{
<add> ID: engine.Tail(stdoutBuffer, 1),
<add> Warnings: outWarnings,
<add> })
<ide> }
<ide>
<ide> func postContainersRestart(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> func postContainersWait(eng *engine.Engine, version version.Version, w http.Resp
<ide> }
<ide>
<ide> env.Set("StatusCode", engine.Tail(stdoutBuffer, 1))
<del> return writeJSON(w, http.StatusOK, env)
<add> return writeJSONEnv(w, http.StatusOK, env)
<ide> }
<ide>
<ide> func postContainersResize(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> func postContainerExecCreate(eng *engine.Engine, version version.Version, w http
<ide> // Return the ID
<ide> out.Set("Id", engine.Tail(stdoutBuffer, 1))
<ide>
<del> return writeJSON(w, http.StatusCreated, out)
<add> return writeJSONEnv(w, http.StatusCreated, out)
<ide> }
<ide>
<ide> // TODO(vishh): Refactor the code to avoid having to specify stream config as part of both create and start.
<ide><path>api/types/types.go
<add>package types
<add>
<add>// ContainerCreateResponse contains the information returned to a client on the
<add>// creation of a new container.
<add>type ContainerCreateResponse struct {
<add> // ID is the ID of the created container.
<add> ID string `json:"Id"`
<add>
<add> // Warnings are any warnings encountered during the creation of the container.
<add> Warnings []string `json:"Warnings"`
<add>} | 3 |
Ruby | Ruby | ask the form builder for form tag attributes | 497c4bbd474fce78bed9289a1788c09fbf9b514a | <ide><path>actionpack/lib/action_view/helpers/form_helper.rb
<ide> def form_for(record, options = {}, &proc)
<ide> builder = options[:parent_builder] = instantiate_builder(object_name, object, options)
<ide> fields_for = fields_for(object_name, object, options, &proc)
<ide> default_options = builder.multipart? ? { multipart: true } : {}
<del> default_options.merge!(options[:html])
<add> default_options.merge! builder.form_tag_attributes
<ide>
<ide> form_tag(options[:url] || {}, default_options) { fields_for }
<ide> end
<ide> class FormBuilder
<ide>
<ide> attr_accessor :object_name, :object, :options
<ide>
<del> attr_reader :multipart, :parent_builder, :index
<add> attr_reader :multipart, :parent_builder, :index, :form_tag_attributes
<ide> alias :multipart? :multipart
<ide>
<ide> def multipart=(multipart)
<ide> def initialize(object_name, object, template, options, block=nil)
<ide>
<ide> @nested_child_index = {}
<ide> @object_name, @object, @template, @options = object_name, object, template, options
<add> @form_tag_attributes = options.fetch(:html, {})
<ide> @parent_builder = options[:parent_builder]
<ide> @default_options = @options ? @options.slice(:index, :namespace) : {}
<ide> if @object_name.to_s.match(/\[\]$/) | 1 |
Ruby | Ruby | fix syntax error | ea5840ed6192a2c2602223faf53dfcd5f32a26d7 | <ide><path>Library/Homebrew/keg_relocate.rb
<ide> def fix_install_names(options = {})
<ide>
<ide> each_install_name_for(file) do |bad_name|
<ide> # Don't fix absolute paths unless they are rooted in the build directory
<del> next if bad_name.start_with? "/" && !bad_name.start_with?(HOMEBREW_TEMP.to_s)
<add> next if bad_name.start_with?("/") && !bad_name.start_with?(HOMEBREW_TEMP.to_s)
<ide>
<ide> new_name = fixed_name(file, bad_name)
<ide> change_install_name(bad_name, new_name, file) unless new_name == bad_name | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.