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 |
|---|---|---|---|---|---|
Ruby | Ruby | check env_url only once | d035ba143a46e64e6110b6a690e0655e8574fd49 | <ide><path>activerecord/lib/active_record/connection_handling.rb
<ide> def config
<ide> if key.to_s == env
<ide> env_url = ENV["DATABASE_URL"]
<ide> end
<add>
<ide> env_url ||= ENV["DATABASE_URL_#{key.upcase}"]
<del> entry ||= {} if env_url
<del> entry.merge!("url" => env_url) { |h, v1, v2| v1 || v2 } if entry.is_a?(Hash) && env_url
<add>
<add> if env_url
<add> entry ||= {}
<add> entry.merge!("url" => env_url) { |h, v1, v2| v1 || v2 } if entry.is_a?(Hash)
<add> end
<add>
<ide> hash[key] = entry if entry
<ide> end
<ide> | 1 |
Javascript | Javascript | make properties on blob and url enumerable | 6fb466bc38b1b489afe16ab4c88f08105b9ddb94 | <ide><path>lib/internal/blob.js
<ide> const {
<ide> ArrayFrom,
<ide> MathMax,
<ide> MathMin,
<add> ObjectDefineProperties,
<ide> ObjectDefineProperty,
<ide> PromiseResolve,
<ide> PromiseReject,
<ide> const {
<ide> createDeferredPromise,
<ide> customInspectSymbol: kInspect,
<ide> kEmptyObject,
<add> kEnumerableProperty,
<ide> } = require('internal/util');
<ide> const { inspect } = require('internal/util/inspect');
<ide>
<ide> ObjectDefineProperty(Blob.prototype, SymbolToStringTag, {
<ide> value: 'Blob',
<ide> });
<ide>
<add>ObjectDefineProperties(Blob.prototype, {
<add> size: kEnumerableProperty,
<add> type: kEnumerableProperty,
<add> slice: kEnumerableProperty,
<add> stream: kEnumerableProperty,
<add> text: kEnumerableProperty,
<add> arrayBuffer: kEnumerableProperty,
<add>});
<add>
<ide> function resolveObjectURL(url) {
<ide> url = `${url}`;
<ide> try {
<ide><path>lib/internal/url.js
<ide> ObjectDefineProperties(URL.prototype, {
<ide> toJSON: kEnumerableProperty,
<ide> });
<ide>
<add>ObjectDefineProperties(URL, {
<add> createObjectURL: kEnumerableProperty,
<add> revokeObjectURL: kEnumerableProperty,
<add>});
<add>
<ide> function update(url, params) {
<ide> if (!url)
<ide> return;
<ide><path>test/parallel/test-blob.js
<ide> assert.throws(() => new Blob({}), {
<ide> });
<ide> }
<ide>
<add>{
<add> const descriptors = Object.getOwnPropertyDescriptors(Blob.prototype);
<add> const enumerable = [
<add> 'size',
<add> 'type',
<add> 'slice',
<add> 'stream',
<add> 'text',
<add> 'arrayBuffer',
<add> ];
<add>
<add> for (const prop of enumerable) {
<add> assert.notStrictEqual(descriptors[prop], undefined);
<add> assert.strictEqual(descriptors[prop].enumerable, true);
<add> }
<add>}
<add>
<ide> {
<ide> const b = new Blob(['test', 42]);
<ide> b.text().then(common.mustCall((text) => {
<ide><path>test/parallel/test-whatwg-url-properties.js
<ide> const { URL, URLSearchParams } = require('url');
<ide> testAccessor(URL.prototype, name, readonly);
<ide> });
<ide>
<add>[
<add> { name: 'createObjectURL' },
<add> { name: 'revokeObjectURL' },
<add>].forEach(({ name }) => {
<add> testStaticAccessor(URL, name);
<add>});
<add>
<ide> [
<ide> { name: 'append' },
<ide> { name: 'delete' },
<ide> function testAccessor(target, name, readonly = false) {
<ide> );
<ide> }
<ide> }
<add>
<add>function testStaticAccessor(target, name) {
<add> const desc = Object.getOwnPropertyDescriptor(target, name);
<add> assert.notStrictEqual(desc, undefined);
<add>
<add> assert.strictEqual(desc.configurable, true);
<add> assert.strictEqual(desc.enumerable, true);
<add> assert.strictEqual(desc.writable, true);
<add>} | 4 |
Java | Java | remove actions utility methods | 24c535e85f396331106c621bd713a08964e0ba97 | <ide><path>src/main/java/rx/functions/Actions.java
<ide> public void call(Object... args) {
<ide> }
<ide> }
<ide>
<del> /**
<del> * Extracts a method reference to the Observer's {@link Observer#onNext onNext} method in the form of an
<del> * {@link Action1}.
<del> * <p>Java 8: observer::onNext</p>
<del> *
<del> * @param observer
<del> * the {@link Observer} to use
<del> * @return an action which calls observer's {@code onNext} method.
<del> */
<del> public static <T> Action1<T> onNextFrom(final Observer<T> observer) {
<del> return new Action1<T>() {
<del> @Override
<del> public void call(T t1) {
<del> observer.onNext(t1);
<del> }
<del> };
<del> }
<del>
<del> /**
<del> * Extracts a method reference to the Observer's {@link Observer#onError(java.lang.Throwable) onError}
<del> * method in the form of an {@link Action1}.
<del> * <p>Java 8: observer::onError</p>
<del> *
<del> * @param observer
<del> * the {@link Observer} to use
<del> * @return an action which calls observer's {@code onError} method.
<del> */
<del> public static <T> Action1<Throwable> onErrorFrom(final Observer<T> observer) {
<del> return new Action1<Throwable>() {
<del> @Override
<del> public void call(Throwable t1) {
<del> observer.onError(t1);
<del> }
<del> };
<del> }
<del>
<del> /**
<del> * Extracts a method reference to the Observer's {@link Observer#onCompleted() onCompleted} method in the
<del> * form of an {@link Action0}.
<del> * <p>Java 8: observer::onCompleted</p>
<del> *
<del> * @param observer
<del> * the {@link Observer} to use
<del> * @return an action which calls observer's {@code onCompleted} method.
<del> */
<del> public static <T> Action0 onCompletedFrom(final Observer<T> observer) {
<del> return new Action0() {
<del> @Override
<del> public void call() {
<del> observer.onCompleted();
<del> }
<del> };
<del> }
<del>
<ide> /**
<ide> * Converts an {@link Action0} to a function that calls the action and returns {@code null}.
<ide> * | 1 |
Ruby | Ruby | return a null object from `attributeset#[]` | 6d7ac31ddb9b5457177ee6b127624ad7e8cdd9d3 | <ide><path>activerecord/lib/active_record/attribute_methods/before_type_cast.rb
<ide> module BeforeTypeCast
<ide> # task.read_attribute_before_type_cast('completed_on') # => "2012-10-21"
<ide> # task.read_attribute_before_type_cast(:completed_on) # => "2012-10-21"
<ide> def read_attribute_before_type_cast(attr_name)
<del> if attr = @attributes[attr_name.to_s]
<del> attr.value_before_type_cast
<del> end
<add> @attributes[attr_name.to_s].value_before_type_cast
<ide> end
<ide>
<ide> # Returns a hash of attributes before typecasting and deserialization.
<ide><path>activerecord/lib/active_record/attribute_methods/dirty.rb
<ide> def keys_for_partial_write
<ide> end
<ide>
<ide> def _field_changed?(attr, old_value)
<del> attribute_named(attr).changed_from?(old_value)
<add> @attributes[attr].changed_from?(old_value)
<ide> end
<ide>
<ide> def changed_in_place
<ide> def changed_in_place
<ide>
<ide> def changed_in_place?(attr_name)
<ide> old_value = original_raw_attribute(attr_name)
<del> attribute_named(attr_name).changed_in_place_from?(old_value)
<add> @attributes[attr_name].changed_in_place_from?(old_value)
<ide> end
<ide>
<ide> def original_raw_attribute(attr_name)
<ide> def original_raw_attributes
<ide> end
<ide>
<ide> def store_original_raw_attribute(attr_name)
<del> original_raw_attributes[attr_name] = attribute_named(attr_name).value_for_database
<add> original_raw_attributes[attr_name] = @attributes[attr_name].value_for_database
<ide> end
<ide>
<ide> def store_original_raw_attributes
<ide><path>activerecord/lib/active_record/attribute_methods/read.rb
<ide> def read_attribute(attr_name)
<ide> def attribute(attribute_name)
<ide> read_attribute(attribute_name)
<ide> end
<del>
<del> def attribute_named(attribute_name)
<del> @attributes.fetch(attribute_name, Attribute::Null)
<del> end
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/lib/active_record/attribute_set.rb
<ide> def initialize(types)
<ide> end
<ide>
<ide> def build_from_database(values, additional_types = {})
<del> attributes = values.each_with_object({}) do |(name, value), hash|
<add> attributes = Hash.new(Attribute::Null)
<add> values.each_with_object(attributes) do |(name, value), hash|
<ide> type = additional_types.fetch(name, @types[name])
<ide> hash[name] = Attribute.from_database(value, type)
<ide> end
<ide><path>activerecord/lib/active_record/core.rb
<ide> def to_ary # :nodoc:
<ide>
<ide> def init_internals
<ide> pk = self.class.primary_key
<del> @attributes[pk] ||= Attribute.from_database(nil, type_for_attribute(pk))
<add> unless @attributes.include?(pk)
<add> @attributes[pk] = Attribute.from_database(nil, type_for_attribute(pk))
<add> end
<ide>
<ide> @aggregation_cache = {}
<ide> @association_cache = {}
<ide><path>activerecord/test/cases/attribute_set_test.rb
<ide> class AttributeSetTest < ActiveRecord::TestCase
<ide> assert_equal 4, attributes[:bar].value
<ide> end
<ide>
<add> test "[] returns a null object" do
<add> builder = AttributeSet::Builder.new(foo: Type::Float.new)
<add> attributes = builder.build_from_database(foo: '3.3')
<add>
<add> assert_equal '3.3', attributes[:foo].value_before_type_cast
<add> assert_equal nil, attributes[:bar].value_before_type_cast
<add> end
<add>
<ide> test "duping creates a new hash and dups each attribute" do
<ide> builder = AttributeSet::Builder.new(foo: Type::Integer.new, bar: Type::String.new)
<ide> attributes = builder.build_from_database(foo: 1, bar: 'foo') | 6 |
Javascript | Javascript | remove repeated compression algorithm | 242c1d97828b54032e151eab36c9b3913577b855 | <ide><path>lib/adapters/http.js
<ide> export default function httpAdapter(config) {
<ide> return reject(customErr);
<ide> }
<ide>
<del> headers.set('Accept-Encoding', 'gzip, deflate, gzip, br', false);
<add> headers.set('Accept-Encoding', 'gzip, deflate, br', false);
<ide>
<ide> const options = {
<ide> path: buildURL(parsed.path, config.params, config.paramsSerializer).replace(/^\?/, ''), | 1 |
Text | Text | add changelogs for vm | 08d5ab9aaed95f95fb9831b4e36c8c1ef4ebc7a3 | <ide><path>doc/api/vm.md
<ide> executed in specific sandboxes (or "contexts").
<ide> ### new vm.Script(code, options)
<ide> <!-- YAML
<ide> added: v0.3.1
<add>changes:
<add> - version: v5.7.0
<add> pr-url: https://github.com/nodejs/node/pull/4777
<add> description: The `cachedData` and `produceCachedData` options are
<add> supported now.
<ide> -->
<ide>
<ide> * `code` {string} The JavaScript code to compile.
<ide> each run, just for that run.
<ide> ### script.runInContext(contextifiedSandbox[, options])
<ide> <!-- YAML
<ide> added: v0.3.1
<add>changes:
<add> - version: v6.3.0
<add> pr-url: https://github.com/nodejs/node/pull/6635
<add> description: The `breakOnSigint` option is supported now.
<ide> -->
<ide>
<ide> * `contextifiedSandbox` {Object} A [contextified][] object as returned by the | 1 |
Text | Text | use https for hyperlinks in readme | 73415da25d964ee31ec1804d55f5af0199a1378e | <ide><path>build/fixtures/README.md
<ide>
<ide> > jQuery is a fast, small, and feature-rich JavaScript library.
<ide>
<del>For information on how to get started and how to use jQuery, please see [jQuery's documentation](http://api.jquery.com/).
<add>For information on how to get started and how to use jQuery, please see [jQuery's documentation](https://api.jquery.com/).
<ide> For source files and issues, please visit the [jQuery repo](https://github.com/jquery/jquery).
<ide>
<ide> If upgrading, please see the [blog post for @VERSION](@BLOG_POST_LINK). This includes notable differences from the previous version and a more readable changelog.
<ide> Below are some of the most common ways to include jQuery.
<ide>
<ide> #### Babel
<ide>
<del>[Babel](http://babeljs.io/) is a next generation JavaScript compiler. One of the features is the ability to use ES6/ES2015 modules now, even though browsers do not yet support this feature natively.
<add>[Babel](https://babeljs.io/) is a next generation JavaScript compiler. One of the features is the ability to use ES6/ES2015 modules now, even though browsers do not yet support this feature natively.
<ide>
<ide> ```js
<ide> import $ from "jquery";
<ide> var $ = require( "jquery" );
<ide>
<ide> #### AMD (Asynchronous Module Definition)
<ide>
<del>AMD is a module format built for the browser. For more information, we recommend [require.js' documentation](http://requirejs.org/docs/whyamd.html).
<add>AMD is a module format built for the browser. For more information, we recommend [require.js' documentation](https://requirejs.org/docs/whyamd.html).
<ide>
<ide> ```js
<ide> define( [ "jquery" ], function( $ ) {
<ide> define( [ "jquery" ], function( $ ) {
<ide>
<ide> ### Node
<ide>
<del>To include jQuery in [Node](nodejs.org), first install with npm.
<add>To include jQuery in [Node](https://nodejs.org/), first install with npm.
<ide>
<ide> ```sh
<ide> npm install jquery | 1 |
PHP | PHP | add braces to key call | 716b4a12e0f2a7fa6fbb0579152dfbf486d2936e | <ide><path>src/Http/Client/Response.php
<ide> public function __isset($name)
<ide> return $val !== null;
<ide> }
<ide>
<del> return isset($this->$key);
<add> return isset($this->{$key});
<ide> }
<ide> } | 1 |
Javascript | Javascript | remove duplicate import | cca8cde2c63700e45e0cd4c9a4d068ccacf301f8 | <ide><path>lib/ContextModule.js
<ide> const {
<ide> compareLocations,
<ide> concatComparators,
<ide> compareSelect,
<del> keepOriginalOrder
<add> keepOriginalOrder,
<add> compareModulesById
<ide> } = require("./util/comparators");
<del>const { compareModulesById } = require("./util/comparators");
<ide> const { contextify, parseResource } = require("./util/identifier");
<ide> const makeSerializable = require("./util/makeSerializable");
<ide> | 1 |
Javascript | Javascript | document the error event | 4e2b4a215c12071bf4efe85f45675dd142c463ea | <ide><path>src/js/player.js
<ide> vjs.Player.prototype.onFullscreenChange = function() {
<ide> }
<ide> };
<ide>
<add>/**
<add> * Fired when an error occurred
<add> * @event error
<add> */
<add>vjs.Player.prototype.onError;
<add>
<ide> // /* Player API
<ide> // ================================================================================ */
<ide> | 1 |
Text | Text | update supervisord example | e38678e6601cc597b621aaf3cf630419a7963ae9 | <ide><path>docs/admin/using_supervisord.md
<ide> parent = "engine_admin"
<ide> > - **If you don't like sudo** then see [*Giving non-root
<ide> > access*](../installation/binaries.md#giving-non-root-access)
<ide>
<del>Traditionally a Docker container runs a single process when it is
<del>launched, for example an Apache daemon or a SSH server daemon. Often
<del>though you want to run more than one process in a container. There are a
<del>number of ways you can achieve this ranging from using a simple Bash
<del>script as the value of your container's `CMD` instruction to installing
<del>a process management tool.
<del>
<del>In this example we're going to make use of the process management tool,
<del>[Supervisor](http://supervisord.org/), to manage multiple processes in
<del>our container. Using Supervisor allows us to better control, manage, and
<del>restart the processes we want to run. To demonstrate this we're going to
<del>install and manage both an SSH daemon and an Apache daemon.
<add>Traditionally a Docker container runs a single process when it is launched, for
<add>example an Apache daemon or a SSH server daemon. Often though you want to run
<add>more than one process in a container. There are a number of ways you can
<add>achieve this ranging from using a simple Bash script as the value of your
<add>container's `CMD` instruction to installing a process management tool.
<add>
<add>In this example you're going to make use of the process management tool,
<add>[Supervisor](http://supervisord.org/), to manage multiple processes in a
<add>container. Using Supervisor allows you to better control, manage, and restart
<add>the processes inside the container. To demonstrate this we're going to install
<add>and manage both an SSH daemon and an Apache daemon.
<ide>
<ide> ## Creating a Dockerfile
<ide>
<del>Let's start by creating a basic `Dockerfile` for our
<del>new image.
<add>Let's start by creating a basic `Dockerfile` for our new image.
<ide>
<del> FROM ubuntu:13.04
<del> MAINTAINER examples@docker.com
<add>```Dockerfile
<add>FROM ubuntu:16.04
<add>MAINTAINER examples@docker.com
<add>```
<ide>
<ide> ## Installing Supervisor
<ide>
<del>We can now install our SSH and Apache daemons as well as Supervisor in
<del>our container.
<add>You can now install the SSH and Apache daemons as well as Supervisor in the
<add>container.
<ide>
<del> RUN apt-get update && apt-get install -y openssh-server apache2 supervisor
<del> RUN mkdir -p /var/lock/apache2 /var/run/apache2 /var/run/sshd /var/log/supervisor
<add>```Dockerfile
<add>RUN apt-get update && apt-get install -y openssh-server apache2 supervisor
<add>RUN mkdir -p /var/lock/apache2 /var/run/apache2 /var/run/sshd /var/log/supervisor
<add>```
<ide>
<del>Here we're installing the `openssh-server`,
<del>`apache2` and `supervisor`
<del>(which provides the Supervisor daemon) packages. We're also creating four
<del>new directories that are needed to run our SSH daemon and Supervisor.
<add>The first `RUN` instruction installs the `openssh-server`, `apache2` and
<add>`supervisor` (which provides the Supervisor daemon) packages. The next `RUN`
<add>instruction creates four new directories that are needed to run the SSH daemon
<add>and Supervisor.
<ide>
<ide> ## Adding Supervisor's configuration file
<ide>
<del>Now let's add a configuration file for Supervisor. The default file is
<del>called `supervisord.conf` and is located in
<del>`/etc/supervisor/conf.d/`.
<add>Now let's add a configuration file for Supervisor. The default file is called
<add>`supervisord.conf` and is located in `/etc/supervisor/conf.d/`.
<ide>
<del> COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf
<add>```Dockerfile
<add>COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf
<add>```
<ide>
<del>Let's see what is inside our `supervisord.conf`
<del>file.
<add>Let's see what is inside the `supervisord.conf` file.
<ide>
<del> [supervisord]
<del> nodaemon=true
<add>```ini
<add>[supervisord]
<add>nodaemon=true
<ide>
<del> [program:sshd]
<del> command=/usr/sbin/sshd -D
<add>[program:sshd]
<add>command=/usr/sbin/sshd -D
<ide>
<del> [program:apache2]
<del> command=/bin/bash -c "source /etc/apache2/envvars && exec /usr/sbin/apache2 -DFOREGROUND"
<add>[program:apache2]
<add>command=/bin/bash -c "source /etc/apache2/envvars && exec /usr/sbin/apache2 -DFOREGROUND"
<add>```
<ide>
<del>The `supervisord.conf` configuration file contains
<del>directives that configure Supervisor and the processes it manages. The
<del>first block `[supervisord]` provides configuration
<del>for Supervisor itself. We're using one directive, `nodaemon`
<del>which tells Supervisor to run interactively rather than
<del>daemonize.
<add>The `supervisord.conf` configuration file contains directives that configure
<add>Supervisor and the processes it manages. The first block `[supervisord]`
<add>provides configuration for Supervisor itself. The `nodaemon` directive is used,
<add>which tells Supervisor to run interactively rather than daemonize.
<ide>
<del>The next two blocks manage the services we wish to control. Each block
<del>controls a separate process. The blocks contain a single directive,
<del>`command`, which specifies what command to run to
<del>start each process.
<add>The next two blocks manage the services we wish to control. Each block controls
<add>a separate process. The blocks contain a single directive, `command`, which
<add>specifies what command to run to start each process.
<ide>
<ide> ## Exposing ports and running Supervisor
<ide>
<del>Now let's finish our `Dockerfile` by exposing some
<del>required ports and specifying the `CMD` instruction
<del>to start Supervisor when our container launches.
<add>Now let's finish the `Dockerfile` by exposing some required ports and
<add>specifying the `CMD` instruction to start Supervisor when our container
<add>launches.
<ide>
<del> EXPOSE 22 80
<del> CMD ["/usr/bin/supervisord"]
<add>```Dockerfile
<add>EXPOSE 22 80
<add>CMD ["/usr/bin/supervisord"]
<add>```
<ide>
<del>Here we've exposed ports 22 and 80 on the container and we're running
<del>the `/usr/bin/supervisord` binary when the container
<del>launches.
<add>These instructions tell Docker that ports 22 and 80 are exposed by the
<add>container and that the `/usr/bin/supervisord` binary should be executed when
<add>the container launches.
<ide>
<ide> ## Building our image
<ide>
<del>We can now build our new image.
<add>Your completed Dockerfile now looks like this:
<add>
<add>```Dockerfile
<add>FROM ubuntu:16.04
<add>MAINTAINER examples@docker.com
<add>
<add>RUN apt-get update && apt-get install -y openssh-server apache2 supervisor
<add>RUN mkdir -p /var/lock/apache2 /var/run/apache2 /var/run/sshd /var/log/supervisor
<add>
<add>COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf
<add>
<add>EXPOSE 22 80
<add>CMD ["/usr/bin/supervisord"]
<add>```
<add>
<add>And your `supervisord.conf` file looks like this;
<add>
<add>```ini
<add>[supervisord]
<add>nodaemon=true
<add>
<add>[program:sshd]
<add>command=/usr/sbin/sshd -D
<add>
<add>[program:apache2]
<add>command=/bin/bash -c "source /etc/apache2/envvars && exec /usr/sbin/apache2 -DFOREGROUND"
<add>```
<add>
<add>
<add>You can now build the image using this command;
<ide>
<del> $ docker build -t <yourname>/supervisord .
<add>```bash
<add>$ docker build -t mysupervisord .
<add>```
<ide>
<del>## Running our Supervisor container
<add>## Running your Supervisor container
<ide>
<del>Once we've got a built image we can launch a container from it.
<add>Once you have built your image you can launch a container from it.
<ide>
<del> $ docker run -p 22 -p 80 -t -i <yourname>/supervisord
<del> 2013-11-25 18:53:22,312 CRIT Supervisor running as root (no user in config file)
<del> 2013-11-25 18:53:22,312 WARN Included extra file "/etc/supervisor/conf.d/supervisord.conf" during parsing
<del> 2013-11-25 18:53:22,342 INFO supervisord started with pid 1
<del> 2013-11-25 18:53:23,346 INFO spawned: 'sshd' with pid 6
<del> 2013-11-25 18:53:23,349 INFO spawned: 'apache2' with pid 7
<del> . . .
<add>```bash
<add>$ docker run -p 22 -p 80 -t -i mysupervisord
<add>2013-11-25 18:53:22,312 CRIT Supervisor running as root (no user in config file)
<add>2013-11-25 18:53:22,312 WARN Included extra file "/etc/supervisor/conf.d/supervisord.conf" during parsing
<add>2013-11-25 18:53:22,342 INFO supervisord started with pid 1
<add>2013-11-25 18:53:23,346 INFO spawned: 'sshd' with pid 6
<add>2013-11-25 18:53:23,349 INFO spawned: 'apache2' with pid 7
<add>...
<add>```
<ide>
<del>We've launched a new container interactively using the `docker run` command.
<add>You launched a new container interactively using the `docker run` command.
<ide> That container has run Supervisor and launched the SSH and Apache daemons with
<ide> it. We've specified the `-p` flag to expose ports 22 and 80. From here we can
<ide> now identify the exposed ports and connect to one or both of the SSH and Apache | 1 |
Ruby | Ruby | use bottlecollector in bottle softwarespec | e2af1cbeeb8f68150037dbf8612b69290b9e85aa | <ide><path>Library/Homebrew/bottles.rb
<ide> require 'extend/ARGV'
<ide> require 'bottle_version'
<ide>
<del>def bottle_filename f, bottle_revision=nil
<add>def bottle_filename f, options={:tag=>bottle_tag, :bottle_revision=>nil}
<ide> name = f.name.downcase
<ide> version = f.stable.version
<ide> bottle_revision ||= f.bottle.revision.to_i if f.bottle
<del> "#{name}-#{version}#{bottle_native_suffix(bottle_revision)}"
<add> "#{name}-#{version}#{bottle_native_suffix(options)}"
<ide> end
<ide>
<ide> def install_bottle? f, options={:warn=>false}
<ide> def bottle_file_outdated? f, file
<ide> bottle_ext && bottle_url_ext && bottle_ext != bottle_url_ext
<ide> end
<ide>
<del>def bottle_native_suffix revision=nil
<del> ".#{bottle_tag}#{bottle_suffix(revision)}"
<add>def bottle_native_suffix options={:tag=>bottle_tag}
<add> ".#{options[:tag]}#{bottle_suffix(options[:revision])}"
<ide> end
<ide>
<ide> def bottle_suffix revision=nil
<ide> def bottle_root_url f
<ide> root_url ||= 'https://downloads.sf.net/project/machomebrew/Bottles'
<ide> end
<ide>
<del>def bottle_url f
<del> "#{bottle_root_url(f)}/#{bottle_filename(f)}"
<add>def bottle_url f, tag=bottle_tag
<add> "#{bottle_root_url(f)}/#{bottle_filename(f, {:tag => tag})}"
<ide> end
<ide>
<ide> def bottle_tag
<ide> def add(checksum, tag, url=nil)
<ide> def fetch_bottle_for(tag)
<ide> return [@bottles[tag], tag] if @bottles[tag]
<ide>
<del> find_altivec_tag(tag) || find_or_later(tag)
<add> find_altivec_tag(tag) || find_or_later_tag(tag)
<ide> end
<ide>
<add> def keys; @bottles.keys; end
<add> def [](arg); @bottles[arg]; end
<add>
<ide> # This allows generic Altivec PPC bottles to be supported in some
<ide> # formulae, while also allowing specific bottles in others; e.g.,
<ide> # sometimes a formula has just :tiger_altivec, other times it has
<ide><path>Library/Homebrew/cmd/bottle.rb
<ide> def bottle_formula f
<ide> bottle_revision = -1
<ide> begin
<ide> bottle_revision += 1
<del> filename = bottle_filename(f, bottle_revision)
<add> filename = bottle_filename(f, :tag => bottle_tag, :bottle_revision => bottle_revision)
<ide> end while not ARGV.include? '--no-revision' \
<ide> and master_bottle_filenames.include? filename
<ide>
<ide><path>Library/Homebrew/formula.rb
<ide> def initialize name='__UNKNOWN__', path=nil
<ide> # into a validation method on the bottle instance.
<ide> unless bottle.checksum.nil? || bottle.checksum.empty?
<ide> @bottle = bottle
<del> bottle.url ||= bottle_url(self)
<add> bottle.url ||= bottle_url(self, bottle.current_tag)
<ide> end
<ide> end
<ide>
<ide><path>Library/Homebrew/software_spec.rb
<ide> require 'version'
<ide> require 'build_options'
<ide> require 'dependency_collector'
<add>require 'bottles'
<ide>
<ide> class SoftwareSpec
<ide> extend Forwardable
<ide> def verify_download_integrity fn
<ide>
<ide> class Bottle < SoftwareSpec
<ide> attr_rw :root_url, :prefix, :cellar, :revision
<add> attr_accessor :current_tag
<ide>
<ide> def_delegators :@resource, :version=, :url=
<ide>
<ide> def initialize
<ide> class_eval <<-EOS, __FILE__, __LINE__ + 1
<ide> def #{cksum}(val=nil)
<ide> return @#{cksum} if val.nil?
<del> @#{cksum} ||= Hash.new
<add> @#{cksum} ||= BottleCollector.new
<ide> case val
<ide> when Hash
<ide> key, value = val.shift
<del> @#{cksum}[value] = Checksum.new(:#{cksum}, key)
<add> @#{cksum}.add(Checksum.new(:#{cksum}, key), value)
<ide> end
<ide>
<del> if @#{cksum}.has_key? bottle_tag
<del> @resource.checksum = @#{cksum}[bottle_tag]
<del> end
<add> cksum, current_tag = @#{cksum}.fetch_bottle_for(bottle_tag)
<add> @resource.checksum = cksum if cksum
<add> @current_tag = current_tag if cksum
<ide> end
<ide> EOS
<ide> end
<ide><path>Library/Homebrew/test/test_software_spec.rb
<ide> def test_checksum_setters
<ide> end
<ide>
<ide> checksums.each_pair do |cat, sha1|
<del> assert_equal Checksum.new(:sha1, sha1),
<del> @spec.instance_variable_get(:@sha1)[cat]
<add> hsh, _ = @spec.instance_variable_get(:@sha1).fetch_bottle_for(cat)
<add> assert_equal Checksum.new(:sha1, sha1), hsh
<ide> end
<ide> end
<ide> | 5 |
Text | Text | fix syntax error in the doc [ci skip] | 97feb4996b1c88f770101dfce6d4d3a6baf6bb33 | <ide><path>guides/source/active_record_querying.md
<ide> This is almost the same as defining a class method, except for that scopes alway
<ide>
<ide> ```ruby
<ide> class Article < ApplicationRecord
<del> scope :by_user, ()-> { where(user: user) if user }
<add> scope :by_user, ->(user) { where(user: user) if user }
<ide> def self.published_since(date)
<ide> where('published_at > ?', date) if date
<ide> end | 1 |
Mixed | Go | add a docker_api_version env var | 6287ec9095f380449f0b4f1a06d4e5df43fc4449 | <ide><path>api/client/cli.go
<ide> func NewDockerCli(in io.ReadCloser, out, err io.Writer, clientFlags *cli.ClientF
<ide> }
<ide> customHeaders["User-Agent"] = "Docker-Client/" + dockerversion.Version + " (" + runtime.GOOS + ")"
<ide>
<del> client, err := lib.NewClient(host, string(api.Version), clientFlags.Common.TLSOptions, customHeaders)
<add> verStr := string(api.DefaultVersion)
<add> if tmpStr := os.Getenv("DOCKER_API_VERSION"); tmpStr != "" {
<add> verStr = tmpStr
<add> }
<add>
<add> client, err := lib.NewClient(host, verStr, clientFlags.Common.TLSOptions, customHeaders)
<ide> if err != nil {
<ide> return err
<ide> }
<ide><path>api/client/client.go
<ide> import (
<ide>
<ide> // apiClient is an interface that clients that talk with a docker server must implement.
<ide> type apiClient interface {
<add> ClientVersion() string
<ide> ContainerAttach(options types.ContainerAttachOptions) (types.HijackedResponse, error)
<ide> ContainerCommit(options types.ContainerCommitOptions) (types.ContainerCommitResponse, error)
<ide> ContainerCreate(config *runconfig.ContainerConfigWrapper, containerName string) (types.ContainerCreateResponse, error)
<ide><path>api/client/lib/client.go
<ide> func (cli *Client) getAPIPath(p string, query url.Values) string {
<ide> }
<ide> return apiPath
<ide> }
<add>
<add>// ClientVersion returns the version string associated with this
<add>// instance of the Client. Note that this value can be changed
<add>// via the DOCKER_API_VERSION env var.
<add>func (cli *Client) ClientVersion() string {
<add> return cli.version
<add>}
<ide><path>api/client/version.go
<ide> import (
<ide> "text/template"
<ide> "time"
<ide>
<del> "github.com/docker/docker/api"
<ide> "github.com/docker/docker/api/types"
<ide> Cli "github.com/docker/docker/cli"
<ide> "github.com/docker/docker/dockerversion"
<ide> flag "github.com/docker/docker/pkg/mflag"
<add> "github.com/docker/docker/pkg/version"
<ide> "github.com/docker/docker/utils"
<ide> )
<ide>
<ide> func (cli *DockerCli) CmdVersion(args ...string) (err error) {
<ide> vd := types.VersionResponse{
<ide> Client: &types.Version{
<ide> Version: dockerversion.Version,
<del> APIVersion: api.Version,
<add> APIVersion: version.Version(cli.client.ClientVersion()),
<ide> GoVersion: runtime.Version(),
<ide> GitCommit: dockerversion.GitCommit,
<ide> BuildTime: dockerversion.BuildTime,
<ide><path>api/common.go
<ide> import (
<ide> // Common constants for daemon and client.
<ide> const (
<ide> // Version of Current REST API
<del> Version version.Version = "1.22"
<add> DefaultVersion version.Version = "1.22"
<ide>
<ide> // MinVersion represents Minimum REST API version supported
<ide> MinVersion version.Version = "1.12"
<ide><path>api/server/middleware.go
<ide> func versionMiddleware(handler httputils.APIFunc) httputils.APIFunc {
<ide> return func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> apiVersion := version.Version(vars["version"])
<ide> if apiVersion == "" {
<del> apiVersion = api.Version
<add> apiVersion = api.DefaultVersion
<ide> }
<ide>
<del> if apiVersion.GreaterThan(api.Version) {
<del> return errors.ErrorCodeNewerClientVersion.WithArgs(apiVersion, api.Version)
<add> if apiVersion.GreaterThan(api.DefaultVersion) {
<add> return errors.ErrorCodeNewerClientVersion.WithArgs(apiVersion, api.DefaultVersion)
<ide> }
<ide> if apiVersion.LessThan(api.MinVersion) {
<del> return errors.ErrorCodeOldClientVersion.WithArgs(apiVersion, api.Version)
<add> return errors.ErrorCodeOldClientVersion.WithArgs(apiVersion, api.DefaultVersion)
<ide> }
<ide>
<ide> w.Header().Set("Server", "Docker/"+dockerversion.Version+" ("+runtime.GOOS+")")
<ide><path>api/server/router/system/system_routes.go
<ide> func (s *systemRouter) getInfo(ctx context.Context, w http.ResponseWriter, r *ht
<ide>
<ide> func (s *systemRouter) getVersion(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> info := s.backend.SystemVersion()
<del> info.APIVersion = api.Version
<add> info.APIVersion = api.DefaultVersion
<ide>
<ide> return httputils.WriteJSON(w, http.StatusOK, info)
<ide> }
<ide><path>docs/reference/commandline/cli.md
<ide> the [installation](../../installation/index.md) instructions for your operating
<ide> For easy reference, the following list of environment variables are supported
<ide> by the `docker` command line:
<ide>
<add>* `DOCKER_API_VERSION` The API version to use (e.g. `1.19`)
<ide> * `DOCKER_CONFIG` The location of your client configuration files.
<ide> * `DOCKER_CERT_PATH` The location of your authentication keys.
<ide> * `DOCKER_DRIVER` The graph driver to use.
<ide><path>integration-cli/docker_api_test.go
<ide> package main
<ide>
<ide> import (
<ide> "net/http"
<add> "net/http/httptest"
<ide> "net/http/httputil"
<add> "os"
<add> "os/exec"
<ide> "strconv"
<ide> "strings"
<ide> "time"
<ide> func (s *DockerSuite) TestApiVersionStatusCode(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestApiClientVersionNewerThanServer(c *check.C) {
<del> v := strings.Split(string(api.Version), ".")
<add> v := strings.Split(string(api.DefaultVersion), ".")
<ide> vMinInt, err := strconv.Atoi(v[1])
<ide> c.Assert(err, checker.IsNil)
<ide> vMinInt++
<ide> func (s *DockerSuite) TestApiClientVersionOldNotSupported(c *check.C) {
<ide> c.Assert(status, checker.Equals, http.StatusBadRequest)
<ide> c.Assert(len(string(body)), checker.Not(check.Equals), 0) // Expected not empty body
<ide> }
<add>
<add>func (s *DockerSuite) TestApiDockerApiVersion(c *check.C) {
<add> var svrVersion string
<add>
<add> server := httptest.NewServer(http.HandlerFunc(
<add> func(w http.ResponseWriter, r *http.Request) {
<add> url := r.URL.Path
<add> svrVersion = url
<add> }))
<add> defer server.Close()
<add>
<add> // Test using the env var first
<add> cmd := exec.Command(dockerBinary, "-H="+server.URL[7:], "version")
<add> cmd.Env = append([]string{"DOCKER_API_VERSION=xxx"}, os.Environ()...)
<add> out, _, _ := runCommandWithOutput(cmd)
<add>
<add> c.Assert(svrVersion, check.Equals, "/vxxx/version")
<add>
<add> if !strings.Contains(out, "API version: xxx") {
<add> c.Fatalf("Out didn't have 'xxx' for the API version, had:\n%s", out)
<add> }
<add>} | 9 |
Ruby | Ruby | remove most code related to serialized properties | 90c8be76a7d00475be5ff4db2eeedde5cc936c2d | <ide><path>activerecord/lib/active_record/attribute_methods.rb
<ide> def attributes
<ide> }
<ide> end
<ide>
<del> # Placeholder so it can be overriden when needed by serialization
<del> def attributes_for_coder # :nodoc:
<del> attributes_before_type_cast
<del> end
<del>
<ide> # Returns an <tt>#inspect</tt>-like string for the value of the
<ide> # attribute +attr_name+. String attributes are truncated upto 50
<ide> # characters, Date and Time attributes are returned in the
<ide><path>activerecord/lib/active_record/attribute_methods/read.rb
<ide> def #{temp_method}
<ide>
<ide> def cacheable_column?(column)
<ide> if attribute_types_cached_by_default == ATTRIBUTE_TYPES_CACHED_BY_DEFAULT
<del> ! serialized_attributes.include? column.name
<add> true
<ide> else
<ide> attribute_types_cached_by_default.include?(column.type)
<ide> end
<ide><path>activerecord/lib/active_record/attribute_methods/serialization.rb
<ide> def serialize(attr_name, class_name_or_coder = Object)
<ide> module Behavior # :nodoc:
<ide> extend ActiveSupport::Concern
<ide>
<del> module ClassMethods # :nodoc:
<del> def initialize_attributes(attributes, options = {})
<del> serialized = (options.delete(:serialized) { true }) ? :serialized : :unserialized
<del> super(attributes, options)
<del>
<del> serialized_attributes.each do |key, coder|
<del> if attributes.key?(key)
<del> attributes[key] = Type::Serialized::Attribute.new(coder, attributes[key], serialized)
<del> end
<del> end
<del>
<del> attributes
<del> end
<del> end
<del>
<ide> def should_record_timestamps?
<ide> super || (self.record_timestamps && (attributes.keys & self.class.serialized_attributes.keys).present?)
<ide> end
<ide> def _field_changed?(attr, old, value)
<ide> super
<ide> end
<ide> end
<del>
<del> def read_attribute_before_type_cast(attr_name)
<del> if self.class.serialized_attributes.include?(attr_name)
<del> super.unserialized_value
<del> else
<del> super
<del> end
<del> end
<del>
<del> def attributes_before_type_cast
<del> super.dup.tap do |attributes|
<del> self.class.serialized_attributes.each_key do |key|
<del> if attributes.key?(key)
<del> attributes[key] = attributes[key].unserialized_value
<del> end
<del> end
<del> end
<del> end
<del>
<del> def typecasted_attribute_value(name)
<del> if self.class.serialized_attributes.include?(name)
<del> @raw_attributes[name].serialized_value
<del> else
<del> super
<del> end
<del> end
<del>
<del> def attributes_for_coder
<del> attribute_names.each_with_object({}) do |name, attrs|
<del> attrs[name] = if self.class.serialized_attributes.include?(name)
<del> @raw_attributes[name].serialized_value
<del> else
<del> read_attribute_before_type_cast(name)
<del> end
<del> end
<del> end
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/lib/active_record/attribute_methods/write.rb
<ide> def __temp__#{safe_name}=(value)
<ide> # specified +value+. Empty strings for fixnum and float columns are
<ide> # turned into +nil+.
<ide> def write_attribute(attr_name, value)
<del> write_attribute_with_type_cast(attr_name, value, :type_cast_for_write)
<add> write_attribute_with_type_cast(attr_name, value, true)
<ide> end
<ide>
<ide> def raw_write_attribute(attr_name, value)
<del> write_attribute_with_type_cast(attr_name, value, :raw_type_cast_for_write)
<add> write_attribute_with_type_cast(attr_name, value, false)
<ide> end
<ide>
<ide> private
<ide> def attribute=(attribute_name, value)
<ide> write_attribute(attribute_name, value)
<ide> end
<ide>
<del> def write_attribute_with_type_cast(attr_name, value, type_cast_method)
<add> def write_attribute_with_type_cast(attr_name, value, should_type_cast)
<ide> attr_name = attr_name.to_s
<ide> attr_name = self.class.primary_key if attr_name == 'id' && self.class.primary_key
<ide> @attributes.delete(attr_name)
<ide> def write_attribute_with_type_cast(attr_name, value, type_cast_method)
<ide> @attributes[attr_name] = value
<ide> end
<ide>
<del> if column
<del> @raw_attributes[attr_name] = column.public_send(type_cast_method, value)
<del> elsif @raw_attributes.has_key?(attr_name)
<add> if column && should_type_cast
<add> @raw_attributes[attr_name] = column.type_cast_for_write(value)
<add> elsif !should_type_cast || @raw_attributes.has_key?(attr_name)
<ide> @raw_attributes[attr_name] = value
<ide> else
<ide> raise ActiveModel::MissingAttributeError, "can't write unknown attribute `#{attr_name}'"
<ide><path>activerecord/lib/active_record/connection_adapters/column.rb
<ide> module Format
<ide>
<ide> delegate :type, :precision, :scale, :limit, :klass, :accessor,
<ide> :text?, :number?, :binary?, :serialized?,
<del> :type_cast, :type_cast_for_write, :raw_type_cast_for_write, :type_cast_for_database,
<add> :type_cast, :type_cast_for_write, :type_cast_for_database,
<ide> :type_cast_for_schema,
<ide> to: :cast_type
<ide>
<ide> def human_name
<ide> end
<ide>
<ide> def extract_default(default)
<del> type_cast(default)
<add> type_cast_for_write(type_cast(default))
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/lib/active_record/core.rb
<ide> def initialize_dup(other) # :nodoc:
<ide> # Post.new.encode_with(coder)
<ide> # coder # => {"attributes" => {"id" => nil, ... }}
<ide> def encode_with(coder)
<del> coder['attributes'] = attributes_for_coder
<add> coder['attributes'] = @raw_attributes
<ide> end
<ide>
<ide> # Returns true if +comparison_object+ is the same exact object, or +comparison_object+
<ide><path>activerecord/lib/active_record/type/serialized.rb
<ide> def initialize(subtype, coder)
<ide> end
<ide>
<ide> def type_cast(value)
<del> if value.respond_to?(:unserialized_value)
<del> value.unserialized_value(super(value.value))
<add> if is_default_value?(value)
<add> value
<ide> else
<del> super
<add> coder.load(super)
<ide> end
<ide> end
<ide>
<ide> def type_cast_for_write(value)
<del> Attribute.new(coder, value, :unserialized)
<add> return if value.nil?
<add> unless is_default_value?(value)
<add> coder.dump(value)
<add> end
<ide> end
<ide>
<del> def raw_type_cast_for_write(value)
<del> Attribute.new(coder, value, :serialized)
<del> end
<add> alias type_cast_for_database type_cast_for_write
<ide>
<ide> def serialized?
<ide> true
<ide> def accessor
<ide> ActiveRecord::Store::IndifferentHashAccessor
<ide> end
<ide>
<del> class Attribute < Struct.new(:coder, :value, :state) # :nodoc:
<del> def unserialized_value(v = value)
<del> state == :serialized ? unserialize(v) : value
<del> end
<del>
<del> def serialized_value
<del> state == :unserialized ? serialize : value
<del> end
<del>
<del> def unserialize(v)
<del> self.state = :unserialized
<del> self.value = coder.load(v)
<del> end
<add> private
<ide>
<del> def serialize
<del> self.state = :serialized
<del> self.value = coder.dump(value)
<del> end
<add> def is_default_value?(value)
<add> value == coder.load(nil)
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/lib/active_record/type/value.rb
<ide> def klass # :nodoc:
<ide> def type_cast_for_write(value) # :nodoc:
<ide> value
<ide> end
<del> alias_method :raw_type_cast_for_write, :type_cast_for_write # :internal:
<ide>
<ide> private
<ide>
<ide><path>activerecord/lib/active_record/validations/uniqueness.rb
<ide> def validate_each(record, attribute, value)
<ide> finder_class = find_finder_class_for(record)
<ide> table = finder_class.arel_table
<ide> value = map_enum_attribute(finder_class, attribute, value)
<del> value = deserialize_attribute(record, attribute, value)
<ide>
<ide> relation = build_relation(finder_class, table, attribute, value)
<ide> relation = relation.and(table[finder_class.primary_key.to_sym].not_eq(record.id)) if record.persisted?
<ide> def scope_relation(record, table, relation)
<ide> relation
<ide> end
<ide>
<del> def deserialize_attribute(record, attribute, value)
<del> coder = record.class.serialized_attributes[attribute.to_s]
<del> value = coder.dump value if value && coder
<del> value
<del> end
<del>
<ide> def map_enum_attribute(klass, attribute, value)
<ide> mapping = klass.defined_enums[attribute.to_s]
<ide> value = mapping[value] if value && mapping
<ide><path>activerecord/test/cases/adapters/postgresql/composite_test.rb
<ide> def type_cast(value)
<ide> end
<ide>
<ide> def type_cast_for_write(value)
<add> return if value.nil?
<ide> "(#{value.city},#{value.street})"
<ide> end
<ide> end
<ide><path>activerecord/test/cases/attribute_methods_test.rb
<ide> def new_topic_like_ar_class(&block)
<ide> end
<ide>
<ide> def cached_columns
<del> Topic.columns.map(&:name) - Topic.serialized_attributes.keys
<add> Topic.columns.map(&:name)
<ide> end
<ide>
<ide> def time_related_columns_on_topic
<ide><path>activerecord/test/cases/serialized_attribute_test.rb
<ide> def test_serialized_attributes_from_database_on_subclass
<ide> def test_serialized_attribute_calling_dup_method
<ide> Topic.serialize :content, JSON
<ide>
<del> t = Topic.new(:content => { :foo => :bar }).dup
<del> assert_equal({ :foo => :bar }, t.content_before_type_cast)
<add> orig = Topic.new(content: { foo: :bar })
<add> clone = orig.dup
<add> assert_equal(orig.content, clone.content)
<ide> end
<ide>
<ide> def test_serialized_attribute_declared_in_subclass
<ide> def test_nil_not_serialized_with_class_constraint
<ide>
<ide> def test_serialized_attribute_should_raise_exception_on_save_with_wrong_type
<ide> Topic.serialize(:content, Hash)
<del> topic = Topic.new(:content => "string")
<del> assert_raise(ActiveRecord::SerializationTypeMismatch) { topic.save }
<add> assert_raise(ActiveRecord::SerializationTypeMismatch) do
<add> topic = Topic.new(content: 'string')
<add> topic.save
<add> end
<ide> end
<ide>
<ide> def test_should_raise_exception_on_serialized_attribute_with_type_mismatch | 12 |
Go | Go | use apierror in server version middleware | bcb0405239e0c820516b05ccc2bb7e8d4a1599f9 | <ide><path>api/server/httputils/errors.go
<ide> func GetHTTPErrorStatusCode(err error) int {
<ide> return statusCode
<ide> }
<ide>
<add>func apiVersionSupportsJSONErrors(version string) bool {
<add> const firstAPIVersionWithJSONErrors = "1.23"
<add> return version == "" || versions.GreaterThan(version, firstAPIVersionWithJSONErrors)
<add>}
<add>
<ide> // MakeErrorHandler makes an HTTP handler that decodes a Docker error and
<ide> // returns it in the response.
<ide> func MakeErrorHandler(err error) http.HandlerFunc {
<ide> return func(w http.ResponseWriter, r *http.Request) {
<ide> statusCode := GetHTTPErrorStatusCode(err)
<ide> vars := mux.Vars(r)
<del> if vars["version"] == "" || versions.GreaterThan(vars["version"], "1.23") {
<add> if apiVersionSupportsJSONErrors(vars["version"]) {
<ide> response := &types.ErrorResponse{
<ide> Message: err.Error(),
<ide> }
<ide><path>api/server/middleware/version.go
<ide> import (
<ide> "net/http"
<ide> "runtime"
<ide>
<add> "github.com/docker/docker/api/errors"
<ide> "github.com/docker/docker/api/types/versions"
<ide> "golang.org/x/net/context"
<ide> )
<ide>
<del>type badRequestError struct {
<del> error
<del>}
<del>
<del>func (badRequestError) HTTPErrorStatusCode() int {
<del> return http.StatusBadRequest
<del>}
<del>
<ide> // VersionMiddleware is a middleware that
<ide> // validates the client and server versions.
<ide> type VersionMiddleware struct {
<ide> func (v VersionMiddleware) WrapHandler(handler func(ctx context.Context, w http.
<ide> }
<ide>
<ide> if versions.GreaterThan(apiVersion, v.defaultVersion) {
<del> return badRequestError{fmt.Errorf("client is newer than server (client API version: %s, server API version: %s)", apiVersion, v.defaultVersion)}
<add> return errors.NewBadRequestError(fmt.Errorf("client is newer than server (client API version: %s, server API version: %s)", apiVersion, v.defaultVersion))
<ide> }
<ide> if versions.LessThan(apiVersion, v.minVersion) {
<del> return badRequestError{fmt.Errorf("client version %s is too old. Minimum supported API version is %s, please upgrade your client to a newer version", apiVersion, v.minVersion)}
<add> return errors.NewBadRequestError(fmt.Errorf("client version %s is too old. Minimum supported API version is %s, please upgrade your client to a newer version", apiVersion, v.minVersion))
<ide> }
<ide>
<ide> header := fmt.Sprintf("Docker/%s (%s)", v.serverVersion, runtime.GOOS) | 2 |
PHP | PHP | fix route cache path | dda4c05b2c5527a4b8ca9a460fec20fc0a264cf7 | <ide><path>src/Illuminate/Foundation/Application.php
<ide> public function routesAreCached()
<ide> */
<ide> public function getRouteCachePath()
<ide> {
<del> return $this['path'].'/routing/cache.php';
<add> return $this['path.storage'].'/meta/routes.php';
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Foundation/Console/RouteClearCommand.php
<ide> public function __construct(Filesystem $files)
<ide> */
<ide> public function fire()
<ide> {
<del> $this->files->delete($this->laravel['path'].'/routing/cache.php');
<add> $this->files->delete($this->laravel->getRouteCachePath());
<ide>
<ide> $this->info('Route cache cleared!');
<ide> } | 2 |
Go | Go | check error before defer | 04ef69a1e963e0c9bc9b685188f2c584ef275e45 | <ide><path>integration-cli/docker_cli_build_test.go
<ide> RUN [ $(ls -l /exists/exists_file | awk '{print $3":"$4}') = 'dockerio:dockerio'
<ide> "test_file3": "test3",
<ide> "test_file4": "test4",
<ide> })
<del> defer ctx.Close()
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> }
<add> defer ctx.Close()
<ide>
<ide> if _, err := buildImageFromContext(name, ctx, true); err != nil {
<ide> c.Fatal(err)
<ide> func (s *DockerSuite) TestBuildAddMultipleFilesToFile(c *check.C) {
<ide> "file1.txt": "test1",
<ide> "file2.txt": "test1",
<ide> })
<del> defer ctx.Close()
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> }
<add> defer ctx.Close()
<ide>
<ide> expected := "When using ADD with more than one source file, the destination must be a directory and end with a /"
<ide> if _, err := buildImageFromContext(name, ctx, true); err == nil || !strings.Contains(err.Error(), expected) {
<ide> func (s *DockerSuite) TestBuildJSONAddMultipleFilesToFile(c *check.C) {
<ide> "file1.txt": "test1",
<ide> "file2.txt": "test1",
<ide> })
<del> defer ctx.Close()
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> }
<add> defer ctx.Close()
<ide>
<ide> expected := "When using ADD with more than one source file, the destination must be a directory and end with a /"
<ide> if _, err := buildImageFromContext(name, ctx, true); err == nil || !strings.Contains(err.Error(), expected) {
<ide> func (s *DockerSuite) TestBuildAddMultipleFilesToFileWild(c *check.C) {
<ide> "file1.txt": "test1",
<ide> "file2.txt": "test1",
<ide> })
<del> defer ctx.Close()
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> }
<add> defer ctx.Close()
<ide>
<ide> expected := "When using ADD with more than one source file, the destination must be a directory and end with a /"
<ide> if _, err := buildImageFromContext(name, ctx, true); err == nil || !strings.Contains(err.Error(), expected) {
<ide> func (s *DockerSuite) TestBuildJSONAddMultipleFilesToFileWild(c *check.C) {
<ide> "file1.txt": "test1",
<ide> "file2.txt": "test1",
<ide> })
<del> defer ctx.Close()
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> }
<add> defer ctx.Close()
<ide>
<ide> expected := "When using ADD with more than one source file, the destination must be a directory and end with a /"
<ide> if _, err := buildImageFromContext(name, ctx, true); err == nil || !strings.Contains(err.Error(), expected) {
<ide> func (s *DockerSuite) TestBuildCopyMultipleFilesToFile(c *check.C) {
<ide> "file1.txt": "test1",
<ide> "file2.txt": "test1",
<ide> })
<del> defer ctx.Close()
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> }
<add> defer ctx.Close()
<ide>
<ide> expected := "When using COPY with more than one source file, the destination must be a directory and end with a /"
<ide> if _, err := buildImageFromContext(name, ctx, true); err == nil || !strings.Contains(err.Error(), expected) {
<ide> func (s *DockerSuite) TestBuildJSONCopyMultipleFilesToFile(c *check.C) {
<ide> "file1.txt": "test1",
<ide> "file2.txt": "test1",
<ide> })
<del> defer ctx.Close()
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> }
<add> defer ctx.Close()
<ide>
<ide> expected := "When using COPY with more than one source file, the destination must be a directory and end with a /"
<ide> if _, err := buildImageFromContext(name, ctx, true); err == nil || !strings.Contains(err.Error(), expected) {
<ide> RUN [ $(cat "/test dir/test_file6") = 'test6' ]`,
<ide> "test_dir/test_file5": "test5",
<ide> "test dir/test_file6": "test6",
<ide> })
<del> defer ctx.Close()
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> }
<add> defer ctx.Close()
<ide>
<ide> if _, err := buildImageFromContext(name, ctx, true); err != nil {
<ide> c.Fatal(err)
<ide> RUN [ $(cat "/test dir/test_file6") = 'test6' ]`,
<ide> "test_dir/test_file5": "test5",
<ide> "test dir/test_file6": "test6",
<ide> })
<del> defer ctx.Close()
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> }
<add> defer ctx.Close()
<ide>
<ide> if _, err := buildImageFromContext(name, ctx, true); err != nil {
<ide> c.Fatal(err)
<ide> func (s *DockerSuite) TestBuildAddMultipleFilesToFileWithWhitespace(c *check.C)
<ide> "test file1": "test1",
<ide> "test file2": "test2",
<ide> })
<del> defer ctx.Close()
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> }
<add> defer ctx.Close()
<ide>
<ide> expected := "When using ADD with more than one source file, the destination must be a directory and end with a /"
<ide> if _, err := buildImageFromContext(name, ctx, true); err == nil || !strings.Contains(err.Error(), expected) {
<ide> func (s *DockerSuite) TestBuildCopyMultipleFilesToFileWithWhitespace(c *check.C)
<ide> "test file1": "test1",
<ide> "test file2": "test2",
<ide> })
<del> defer ctx.Close()
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> }
<add> defer ctx.Close()
<ide>
<ide> expected := "When using COPY with more than one source file, the destination must be a directory and end with a /"
<ide> if _, err := buildImageFromContext(name, ctx, true); err == nil || !strings.Contains(err.Error(), expected) {
<ide> func (s *DockerSuite) TestBuildCopyWildcardNoFind(c *check.C) {
<ide> ctx, err := fakeContext(`FROM busybox
<ide> COPY file*.txt /tmp/
<ide> `, nil)
<del> defer ctx.Close()
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> }
<add> defer ctx.Close()
<ide>
<ide> _, err = buildImageFromContext(name, ctx, true)
<ide> if err == nil {
<ide> func (s *DockerSuite) TestBuildCopyWildcardCache(c *check.C) {
<ide> map[string]string{
<ide> "file1.txt": "test1",
<ide> })
<del> defer ctx.Close()
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> }
<add> defer ctx.Close()
<ide>
<ide> id1, err := buildImageFromContext(name, ctx, true)
<ide> if err != nil {
<ide> func (s *DockerSuite) TestBuildRelativeCopy(c *check.C) {
<ide> ctx, err := fakeContext(dockerfile, map[string]string{
<ide> "foo": "hello",
<ide> })
<del> defer ctx.Close()
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> }
<add> defer ctx.Close()
<ide> _, err = buildImageFromContext(name, ctx, false)
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> func (s *DockerSuite) TestBuildAddLocalFileWithCache(c *check.C) {
<ide> ctx, err := fakeContext(dockerfile, map[string]string{
<ide> "foo": "hello",
<ide> })
<del> defer ctx.Close()
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> }
<add> defer ctx.Close()
<ide> id1, err := buildImageFromContext(name, ctx, true)
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> func (s *DockerSuite) TestBuildAddMultipleLocalFileWithCache(c *check.C) {
<ide> ctx, err := fakeContext(dockerfile, map[string]string{
<ide> "foo": "hello",
<ide> })
<del> defer ctx.Close()
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> }
<add> defer ctx.Close()
<ide> id1, err := buildImageFromContext(name, ctx, true)
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> func (s *DockerSuite) TestBuildAddLocalFileWithoutCache(c *check.C) {
<ide> ctx, err := fakeContext(dockerfile, map[string]string{
<ide> "foo": "hello",
<ide> })
<del> defer ctx.Close()
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> }
<add> defer ctx.Close()
<ide> id1, err := buildImageFromContext(name, ctx, true)
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> func (s *DockerSuite) TestBuildCopyDirButNotFile(c *check.C) {
<ide> ctx, err := fakeContext(dockerfile, map[string]string{
<ide> "dir/foo": "hello",
<ide> })
<del> defer ctx.Close()
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> }
<add> defer ctx.Close()
<ide> id1, err := buildImageFromContext(name, ctx, true)
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> func (s *DockerSuite) TestBuildAddCurrentDirWithCache(c *check.C) {
<ide> ctx, err := fakeContext(dockerfile, map[string]string{
<ide> "foo": "hello",
<ide> })
<del> defer ctx.Close()
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> }
<add> defer ctx.Close()
<ide> id1, err := buildImageFromContext(name, ctx, true)
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> func (s *DockerSuite) TestBuildAddCurrentDirWithoutCache(c *check.C) {
<ide> ctx, err := fakeContext(dockerfile, map[string]string{
<ide> "foo": "hello",
<ide> })
<del> defer ctx.Close()
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> }
<add> defer ctx.Close()
<ide> id1, err := buildImageFromContext(name, ctx, true)
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> CMD ["cat", "/foo"]`,
<ide> "foo": "bar",
<ide> },
<ide> )
<del> defer ctx.Close()
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> }
<add> defer ctx.Close()
<ide> context, err := archive.Tar(ctx.Dir, compression)
<ide> if err != nil {
<ide> c.Fatalf("failed to build context tar: %v", err)
<ide> func (s *DockerSuite) TestBuildEntrypointRunCleanup(c *check.C) {
<ide> map[string]string{
<ide> "foo": "hello",
<ide> })
<del> defer ctx.Close()
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> }
<add> defer ctx.Close()
<ide> if _, err := buildImageFromContext(name, ctx, true); err != nil {
<ide> c.Fatal(err)
<ide> }
<ide> func (s *DockerSuite) TestBuildForbiddenContextPath(c *check.C) {
<ide> "test.txt": "test1",
<ide> "other.txt": "other",
<ide> })
<del> defer ctx.Close()
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> }
<add> defer ctx.Close()
<ide>
<ide> expected := "Forbidden path outside the build context: ../../ "
<ide> if _, err := buildImageFromContext(name, ctx, true); err == nil || !strings.Contains(err.Error(), expected) {
<ide> func (s *DockerSuite) TestBuildAddFileNotFound(c *check.C) {
<ide> ctx, err := fakeContext(`FROM scratch
<ide> ADD foo /usr/local/bar`,
<ide> map[string]string{"bar": "hello"})
<del> defer ctx.Close()
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> }
<add> defer ctx.Close()
<ide> if _, err := buildImageFromContext(name, ctx, true); err != nil {
<ide> if !strings.Contains(err.Error(), "foo: no such file or directory") {
<ide> c.Fatalf("Wrong error %v, must be about missing foo file or directory", err)
<ide> func (s *DockerSuite) TestBuildDockerignoringDockerignore(c *check.C) {
<ide> "Dockerfile": dockerfile,
<ide> ".dockerignore": ".dockerignore\n",
<ide> })
<del> defer ctx.Close()
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> }
<add> defer ctx.Close()
<ide> if _, err = buildImageFromContext(name, ctx, true); err != nil {
<ide> c.Fatalf("Didn't ignore .dockerignore correctly:%s", err)
<ide> }
<ide> func (s *DockerSuite) TestBuildDockerignoreTouchDockerfile(c *check.C) {
<ide> "Dockerfile": dockerfile,
<ide> ".dockerignore": "Dockerfile\n",
<ide> })
<del> defer ctx.Close()
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> }
<add> defer ctx.Close()
<ide>
<ide> if id1, err = buildImageFromContext(name, ctx, true); err != nil {
<ide> c.Fatalf("Didn't build it correctly:%s", err)
<ide> func (s *DockerSuite) TestBuildRenamedDockerfile(c *check.C) {
<ide> "dFile": "FROM busybox\nRUN echo from dFile",
<ide> "files/dFile2": "FROM busybox\nRUN echo from files/dFile2",
<ide> })
<del> defer ctx.Close()
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> }
<add> defer ctx.Close()
<ide>
<ide> out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "-t", "test1", ".")
<ide> if err != nil {
<ide> func (s *DockerSuite) TestBuildFromMixedcaseDockerfile(c *check.C) {
<ide> map[string]string{
<ide> "dockerfile": "FROM busybox\nRUN echo from dockerfile",
<ide> })
<del> defer ctx.Close()
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> }
<add> defer ctx.Close()
<ide>
<ide> out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "-t", "test1", ".")
<ide> if err != nil {
<ide> RUN echo from Dockerfile`,
<ide> map[string]string{
<ide> "dockerfile": "FROM busybox\nRUN echo from dockerfile",
<ide> })
<del> defer ctx.Close()
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> }
<add> defer ctx.Close()
<ide>
<ide> out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "-t", "test1", ".")
<ide> if err != nil {
<ide> RUN find /tmp/`})
<ide> ctx, err := fakeContext(`FROM busybox
<ide> RUN echo from Dockerfile`,
<ide> map[string]string{})
<del> defer ctx.Close()
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> }
<add> defer ctx.Close()
<ide>
<ide> // Make sure that -f is ignored and that we don't use the Dockerfile
<ide> // that's in the current dir
<ide> func (s *DockerSuite) TestBuildFromStdinWithF(c *check.C) {
<ide> ctx, err := fakeContext(`FROM busybox
<ide> RUN echo from Dockerfile`,
<ide> map[string]string{})
<del> defer ctx.Close()
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> }
<add> defer ctx.Close()
<ide>
<ide> // Make sure that -f is ignored and that we don't use the Dockerfile
<ide> // that's in the current dir
<ide> func (s *DockerSuite) TestBuildNullStringInAddCopyVolume(c *check.C) {
<ide> "nullfile": "test2",
<ide> },
<ide> )
<del> defer ctx.Close()
<ide> c.Assert(err, check.IsNil)
<add> defer ctx.Close()
<ide>
<ide> _, err = buildImageFromContext(name, ctx, true)
<ide> c.Assert(err, check.IsNil) | 1 |
Javascript | Javascript | introduce objecttypeannotation utility type | 688caa0bdc5cffe83e2e7b715eb28d45de82fd1b | <ide><path>packages/react-native-codegen/src/CodegenSchema.js
<ide> export type StringEnumTypeAnnotation = $ReadOnly<{|
<ide> |}>,
<ide> |}>;
<ide>
<del>type NamedShape<+T> = $ReadOnly<{
<add>type ObjectTypeAnnotation<+T> = $ReadOnly<{|
<add> type: 'ObjectTypeAnnotation',
<add> properties: $ReadOnlyArray<NamedShape<T>>,
<add>|}>;
<add>
<add>export type NamedShape<+T> = $ReadOnly<{
<ide> name: string,
<ide> optional: boolean,
<ide> typeAnnotation: T,
<ide> export type ComponentShape = $ReadOnly<{|
<ide> ...OptionsShape,
<ide> extendsProps: $ReadOnlyArray<ExtendsPropsShape>,
<ide> events: $ReadOnlyArray<EventTypeShape>,
<del> props: $ReadOnlyArray<PropTypeShape>,
<del> commands: $ReadOnlyArray<CommandTypeShape>,
<add> props: $ReadOnlyArray<NamedShape<PropTypeAnnotation>>,
<add> commands: $ReadOnlyArray<NamedShape<CommandsTypeAnnotation>>,
<ide> |}>;
<ide>
<ide> export type OptionsShape = $ReadOnly<{|
<ide> export type EventTypeShape = $ReadOnly<{|
<ide> paperTopLevelNameDeprecated?: string,
<ide> typeAnnotation: $ReadOnly<{|
<ide> type: 'EventTypeAnnotation',
<del> argument?: $ReadOnly<{|
<del> type: 'ObjectTypeAnnotation',
<del> properties: $ReadOnlyArray<EventObjectPropertyType>,
<del> |}>,
<add> argument?: ObjectTypeAnnotation<EventTypeAnnotation>,
<ide> |}>,
<ide> |}>;
<ide>
<del>export type EventObjectPropertyType = NamedShape<
<add>export type EventTypeAnnotation =
<ide> | BooleanTypeAnnotation
<ide> | StringTypeAnnotation
<ide> | DoubleTypeAnnotation
<ide> | FloatTypeAnnotation
<ide> | Int32TypeAnnotation
<ide> | StringEnumTypeAnnotation
<del> | $ReadOnly<{|
<del> type: 'ObjectTypeAnnotation',
<del> properties: $ReadOnlyArray<EventObjectPropertyType>,
<del> |}>,
<del>>;
<del>
<del>export type PropTypeShape = NamedShape<PropTypeTypeAnnotation>;
<add> | ObjectTypeAnnotation<EventTypeAnnotation>;
<ide>
<del>type PropTypeTypeAnnotation =
<add>export type PropTypeAnnotation =
<ide> | $ReadOnly<{|
<ide> type: 'BooleanTypeAnnotation',
<ide> default: boolean | null,
<ide> type PropTypeTypeAnnotation =
<ide> | 'PointPrimitive'
<ide> | 'EdgeInsetsPrimitive',
<ide> |}>
<del> | $ReadOnly<{|
<del> type: 'ObjectTypeAnnotation',
<del> properties: $ReadOnlyArray<PropTypeShape>,
<del> |}>
<add> | ObjectTypeAnnotation<PropTypeAnnotation>
<ide> | $ReadOnly<{|
<ide> type: 'ArrayTypeAnnotation',
<ide> elementType:
<ide> type PropTypeTypeAnnotation =
<ide> name: string,
<ide> |}>,
<ide> |}>
<del> | $ReadOnly<{|
<del> type: 'ObjectTypeAnnotation',
<del> properties: $ReadOnlyArray<PropTypeShape>,
<del> |}>
<add> | ObjectTypeAnnotation<PropTypeAnnotation>
<ide> | $ReadOnly<{|
<ide> type: 'ReservedPropTypeAnnotation',
<ide> name:
<ide> type PropTypeTypeAnnotation =
<ide> |}>
<ide> | $ReadOnly<{|
<ide> type: 'ArrayTypeAnnotation',
<del> elementType: $ReadOnly<{|
<del> type: 'ObjectTypeAnnotation',
<del> properties: $ReadOnlyArray<PropTypeShape>,
<del> |}>,
<add> elementType: ObjectTypeAnnotation<PropTypeAnnotation>,
<ide> |}>,
<ide> |}>;
<ide>
<del>export type CommandTypeShape = NamedShape<CommandsFunctionTypeAnnotation>;
<del>
<del>export type CommandsFunctionTypeAnnotation = $ReadOnly<{|
<add>// TODO: Unify this function type annotation with NativeModule schema
<add>export type CommandsTypeAnnotation = $ReadOnly<{|
<ide> type: 'FunctionTypeAnnotation',
<ide> params: $ReadOnlyArray<CommandsFunctionTypeParamAnnotation>,
<ide> |}>;
<ide>
<ide> export type CommandsFunctionTypeParamAnnotation = $ReadOnly<{|
<ide> name: string,
<del> typeAnnotation: CommandsTypeAnnotation,
<add> typeAnnotation: CommandsParamTypeAnnotation,
<ide> |}>;
<ide>
<del>export type CommandsTypeAnnotation =
<add>type CommandsParamTypeAnnotation =
<ide> | ReservedTypeAnnotation
<ide> | BooleanTypeAnnotation
<ide> | Int32TypeAnnotation
<ide> export type NativeModuleMethodParamSchema = NamedShape<
<ide> Nullable<NativeModuleParamTypeAnnotation>,
<ide> >;
<ide>
<del>export type NativeModuleObjectTypeAnnotation = $ReadOnly<{|
<del> type: 'ObjectTypeAnnotation',
<del> properties: $ReadOnlyArray<NativeModuleObjectTypeAnnotationPropertySchema>,
<del>|}>;
<add>export type NativeModuleObjectTypeAnnotation = ObjectTypeAnnotation<
<add> Nullable<NativeModuleBaseTypeAnnotation>,
<add>>;
<ide>
<ide> export type NativeModuleObjectTypeAnnotationPropertySchema = NamedShape<
<ide> Nullable<NativeModuleBaseTypeAnnotation>,
<ide><path>packages/react-native-codegen/src/generators/components/CppHelpers.js
<ide> */
<ide>
<ide> 'use strict';
<del>import type {PropTypeShape} from '../../CodegenSchema';
<add>import type {NamedShape, PropTypeAnnotation} from '../../CodegenSchema';
<ide>
<ide> function upperCaseFirst(inString: string): string {
<ide> if (inString.length === 0) {
<ide> function getCppTypeForAnnotation(
<ide> }
<ide> }
<ide>
<del>function getImports(properties: $ReadOnlyArray<PropTypeShape>): Set<string> {
<add>function getImports(
<add> properties: $ReadOnlyArray<NamedShape<PropTypeAnnotation>>,
<add>): Set<string> {
<ide> const imports: Set<string> = new Set();
<ide>
<ide> function addImportsForNativeName(name) {
<ide> function getEnumMaskName(enumName: string): string {
<ide>
<ide> function convertDefaultTypeToString(
<ide> componentName: string,
<del> prop: PropTypeShape,
<add> prop: NamedShape<PropTypeAnnotation>,
<ide> ): string {
<ide> const typeAnnotation = prop.typeAnnotation;
<ide> switch (typeAnnotation.type) {
<ide><path>packages/react-native-codegen/src/generators/components/GenerateComponentHObjCpp.js
<ide> 'use strict';
<ide>
<ide> import type {
<del> CommandTypeShape,
<add> NamedShape,
<add> CommandsTypeAnnotation,
<ide> ComponentShape,
<ide> SchemaType,
<ide> CommandsFunctionTypeParamAnnotation,
<ide> function generateConvertAndValidateParam(
<ide> }
<ide>
<ide> function generateCommandIfCase(
<del> command: CommandTypeShape,
<add> command: NamedShape<CommandsTypeAnnotation>,
<ide> componentName: string,
<ide> ) {
<ide> const params = command.typeAnnotation.params;
<ide><path>packages/react-native-codegen/src/generators/components/GenerateEventEmitterCpp.js
<ide> const {generateEventStructName} = require('./CppHelpers.js');
<ide>
<ide> import type {
<ide> ComponentShape,
<del> EventObjectPropertyType,
<add> NamedShape,
<add> EventTypeAnnotation,
<ide> SchemaType,
<ide> } from '../../CodegenSchema';
<ide>
<ide> function generateEnumSetter(variableName, propertyName, propertyParts) {
<ide>
<ide> function generateSetters(
<ide> parentPropertyName: string,
<del> properties: $ReadOnlyArray<EventObjectPropertyType>,
<add> properties: $ReadOnlyArray<NamedShape<EventTypeAnnotation>>,
<ide> propertyParts: $ReadOnlyArray<string>,
<ide> ): string {
<ide> const propSetters = properties
<ide><path>packages/react-native-codegen/src/generators/components/GenerateEventEmitterH.js
<ide> const {
<ide> import type {
<ide> ComponentShape,
<ide> EventTypeShape,
<del> EventObjectPropertyType,
<add> NamedShape,
<add> EventTypeAnnotation,
<ide> SchemaType,
<ide> } from '../../CodegenSchema';
<ide>
<ide> function indent(nice: string, spaces: number) {
<ide>
<ide> function getNativeTypeFromAnnotation(
<ide> componentName: string,
<del> eventProperty: EventObjectPropertyType,
<add> eventProperty: NamedShape<EventTypeAnnotation>,
<ide> nameParts: $ReadOnlyArray<string>,
<ide> ): string {
<ide> const {type} = eventProperty.typeAnnotation;
<ide> function generateStruct(
<ide> structs: StructsMap,
<ide> componentName: string,
<ide> nameParts: $ReadOnlyArray<string>,
<del> properties: $ReadOnlyArray<EventObjectPropertyType>,
<add> properties: $ReadOnlyArray<NamedShape<EventTypeAnnotation>>,
<ide> ): void {
<ide> const structNameParts = nameParts;
<ide> const structName = generateEventStructName(structNameParts);
<ide><path>packages/react-native-codegen/src/generators/components/GeneratePropsH.js
<ide> const {
<ide>
<ide> import type {
<ide> ExtendsPropsShape,
<del> PropTypeShape,
<add> NamedShape,
<add> PropTypeAnnotation,
<ide> SchemaType,
<ide> } from '../../CodegenSchema';
<ide>
<ide> function generateEnumString(componentName: string, component): string {
<ide>
<ide> function generatePropsString(
<ide> componentName: string,
<del> props: $ReadOnlyArray<PropTypeShape>,
<add> props: $ReadOnlyArray<NamedShape<PropTypeAnnotation>>,
<ide> ) {
<ide> return props
<ide> .map(prop => {
<ide> function getExtendsImports(
<ide> }
<ide>
<ide> function getLocalImports(
<del> properties: $ReadOnlyArray<PropTypeShape>,
<add> properties: $ReadOnlyArray<NamedShape<PropTypeAnnotation>>,
<ide> ): Set<string> {
<ide> const imports: Set<string> = new Set();
<ide>
<ide> function generateStruct(
<ide> structs: StructsMap,
<ide> componentName: string,
<ide> nameParts: $ReadOnlyArray<string>,
<del> properties: $ReadOnlyArray<PropTypeShape>,
<add> properties: $ReadOnlyArray<NamedShape<PropTypeAnnotation>>,
<ide> ): void {
<ide> const structNameParts = nameParts;
<ide> const structName = generateStructName(componentName, structNameParts);
<ide> function generateStruct(
<ide> })
<ide> .join('\n' + ' ');
<ide>
<del> properties.forEach((property: PropTypeShape) => {
<add> properties.forEach((property: NamedShape<PropTypeAnnotation>) => {
<ide> const name = property.name;
<ide> switch (property.typeAnnotation.type) {
<ide> case 'BooleanTypeAnnotation':
<ide><path>packages/react-native-codegen/src/generators/components/GeneratePropsJavaDelegate.js
<ide> 'use strict';
<ide>
<ide> import type {
<del> CommandTypeShape,
<add> NamedShape,
<add> CommandsTypeAnnotation,
<ide> ComponentShape,
<del> PropTypeShape,
<add> PropTypeAnnotation,
<ide> SchemaType,
<ide> } from '../../CodegenSchema';
<ide> const {
<ide> const commandsTemplate = `
<ide> `;
<ide>
<ide> function getJavaValueForProp(
<del> prop: PropTypeShape,
<add> prop: NamedShape<PropTypeAnnotation>,
<ide> componentName: string,
<ide> ): string {
<ide> const typeAnnotation = prop.typeAnnotation;
<ide> function getCommandArgJavaType(param, index) {
<ide> }
<ide> }
<ide>
<del>function getCommandArguments(command: CommandTypeShape): string {
<add>function getCommandArguments(
<add> command: NamedShape<CommandsTypeAnnotation>,
<add>): string {
<ide> return [
<ide> 'view',
<ide> ...command.typeAnnotation.params.map(getCommandArgJavaType),
<ide><path>packages/react-native-codegen/src/generators/components/GeneratePropsJavaInterface.js
<ide> 'use strict';
<ide>
<ide> import type {
<del> CommandTypeShape,
<add> NamedShape,
<add> CommandsTypeAnnotation,
<ide> ComponentShape,
<del> PropTypeShape,
<add> PropTypeAnnotation,
<ide> SchemaType,
<ide> } from '../../CodegenSchema';
<ide> const {
<ide> function addNullable(imports) {
<ide> imports.add('import androidx.annotation.Nullable;');
<ide> }
<ide>
<del>function getJavaValueForProp(prop: PropTypeShape, imports): string {
<add>function getJavaValueForProp(
<add> prop: NamedShape<PropTypeAnnotation>,
<add> imports,
<add>): string {
<ide> const typeAnnotation = prop.typeAnnotation;
<ide>
<ide> switch (typeAnnotation.type) {
<ide> function getCommandArgJavaType(param) {
<ide> }
<ide>
<ide> function getCommandArguments(
<del> command: CommandTypeShape,
<add> command: NamedShape<CommandsTypeAnnotation>,
<ide> componentName: string,
<ide> ): string {
<ide> return [
<ide><path>packages/react-native-codegen/src/parsers/flow/components/commands.js
<ide>
<ide> 'use strict';
<ide>
<del>import type {CommandTypeShape} from '../../../CodegenSchema.js';
<add>import type {
<add> NamedShape,
<add> CommandsTypeAnnotation,
<add>} from '../../../CodegenSchema.js';
<ide> import type {TypeDeclarationMap} from '../utils.js';
<ide>
<ide> const {getValueFromTypes} = require('../utils.js');
<ide> function buildCommandSchema(property, types: TypeDeclarationMap) {
<ide> function getCommands(
<ide> commandTypeAST: $ReadOnlyArray<EventTypeAST>,
<ide> types: TypeDeclarationMap,
<del>): $ReadOnlyArray<CommandTypeShape> {
<add>): $ReadOnlyArray<NamedShape<CommandsTypeAnnotation>> {
<ide> return commandTypeAST
<ide> .filter(property => property.type === 'ObjectTypeProperty')
<ide> .map(property => buildCommandSchema(property, types))
<ide><path>packages/react-native-codegen/src/parsers/flow/components/events.js
<ide>
<ide> import type {
<ide> EventTypeShape,
<del> EventObjectPropertyType,
<add> NamedShape,
<add> EventTypeAnnotation,
<ide> } from '../../../CodegenSchema.js';
<ide>
<ide> function getPropertyType(
<ide> name,
<ide> optional,
<ide> typeAnnotation,
<del>): EventObjectPropertyType {
<add>): NamedShape<EventTypeAnnotation> {
<ide> const type =
<ide> typeAnnotation.type === 'GenericTypeAnnotation'
<ide> ? typeAnnotation.id.name
<ide> function findEventArgumentsAndType(
<ide> }
<ide> }
<ide>
<del>function buildPropertiesForEvent(property): EventObjectPropertyType {
<add>function buildPropertiesForEvent(property): NamedShape<EventTypeAnnotation> {
<ide> const name = property.key.name;
<ide> const optional =
<ide> property.value.type === 'NullableTypeAnnotation' || property.optional;
<ide><path>packages/react-native-codegen/src/parsers/flow/components/props.js
<ide>
<ide> const {getValueFromTypes} = require('../utils.js');
<ide>
<del>import type {PropTypeShape} from '../../../CodegenSchema.js';
<add>import type {NamedShape, PropTypeAnnotation} from '../../../CodegenSchema.js';
<ide> import type {TypeDeclarationMap} from '../utils.js';
<ide>
<ide> function getPropProperties(
<ide> function getTypeAnnotation(
<ide> }
<ide> }
<ide>
<del>function buildPropSchema(property, types: TypeDeclarationMap): ?PropTypeShape {
<add>function buildPropSchema(
<add> property,
<add> types: TypeDeclarationMap,
<add>): ?NamedShape<PropTypeAnnotation> {
<ide> const name = property.key.name;
<ide>
<ide> const value = getValueFromTypes(property.value, types);
<ide> function flattenProperties(
<ide> function getProps(
<ide> typeDefinition: $ReadOnlyArray<PropAST>,
<ide> types: TypeDeclarationMap,
<del>): $ReadOnlyArray<PropTypeShape> {
<add>): $ReadOnlyArray<NamedShape<PropTypeAnnotation>> {
<ide> return flattenProperties(typeDefinition, types)
<ide> .map(property => buildPropSchema(property, types))
<ide> .filter(Boolean);
<ide><path>packages/react-native-codegen/src/parsers/flow/components/schema.js
<ide>
<ide> import type {
<ide> EventTypeShape,
<del> PropTypeShape,
<del> CommandTypeShape,
<add> NamedShape,
<add> CommandsTypeAnnotation,
<add> PropTypeAnnotation,
<ide> ExtendsPropsShape,
<ide> SchemaType,
<ide> OptionsShape,
<ide> export type ComponentSchemaBuilderConfig = $ReadOnly<{|
<ide> componentName: string,
<ide> extendsProps: $ReadOnlyArray<ExtendsPropsShape>,
<ide> events: $ReadOnlyArray<EventTypeShape>,
<del> props: $ReadOnlyArray<PropTypeShape>,
<del> commands: $ReadOnlyArray<CommandTypeShape>,
<add> props: $ReadOnlyArray<NamedShape<PropTypeAnnotation>>,
<add> commands: $ReadOnlyArray<NamedShape<CommandsTypeAnnotation>>,
<ide> options?: ?OptionsShape,
<ide> |}>;
<ide> | 12 |
Text | Text | add v3.28.3 to changelog.md | da6db350af275e7dff93e1b3a3042b2d15d5186d | <ide><path>CHANGELOG.md
<ide> - [#19695](https://github.com/emberjs/ember.js/pull/19695) [CLEANUP] Remove {{partial}}
<ide> - [#19691](https://github.com/emberjs/ember.js/pull/19691) Add build assertion against `{{outlet named}}`
<ide>
<add>## v3.28.3 (October 22, 2021)
<add>
<add>- [#19799](https://github.com/emberjs/ember.js/pull/19799) / [glimmerjs/glimmer-vm#1354](https://github.com/glimmerjs/glimmer-vm/pull/1354) Fixes for errors while precompiling inline templates (introduced in 3.28.2)
<add>
<ide> ## v3.28.2 (October 21, 2021)
<ide>
<ide> - [glimmerjs/glimmer-vm#1351](https://github.com/glimmerjs/glimmer-vm/pull/1351) Support lexical scope in loose mode | 1 |
Mixed | Go | support insecure registry in configuration reload | 582803f00addb597efbfc64a5143f2f848b76ae6 | <ide><path>daemon/daemon.go
<ide> func (daemon *Daemon) initDiscovery(config *Config) error {
<ide> // These are the settings that Reload changes:
<ide> // - Daemon labels.
<ide> // - Daemon debug log level.
<add>// - Daemon insecure registries.
<ide> // - Daemon max concurrent downloads
<ide> // - Daemon max concurrent uploads
<ide> // - Cluster discovery (reconfigure and restart).
<ide> func (daemon *Daemon) Reload(config *Config) (err error) {
<ide> if config.IsValueSet("debug") {
<ide> daemon.configStore.Debug = config.Debug
<ide> }
<add> if config.IsValueSet("insecure-registries") {
<add> daemon.configStore.InsecureRegistries = config.InsecureRegistries
<add> if err := daemon.RegistryService.LoadInsecureRegistries(config.InsecureRegistries); err != nil {
<add> return err
<add> }
<add> }
<ide> if config.IsValueSet("live-restore") {
<ide> daemon.configStore.LiveRestoreEnabled = config.LiveRestoreEnabled
<ide> if err := daemon.containerdRemote.UpdateOptions(libcontainerd.WithLiveRestore(config.LiveRestoreEnabled)); err != nil {
<ide> func (daemon *Daemon) Reload(config *Config) (err error) {
<ide> // We emit daemon reload event here with updatable configurations
<ide> attributes["debug"] = fmt.Sprintf("%t", daemon.configStore.Debug)
<ide> attributes["live-restore"] = fmt.Sprintf("%t", daemon.configStore.LiveRestoreEnabled)
<add>
<add> if daemon.configStore.InsecureRegistries != nil {
<add> insecureRegistries, err := json.Marshal(daemon.configStore.InsecureRegistries)
<add> if err != nil {
<add> return err
<add> }
<add> attributes["insecure-registries"] = string(insecureRegistries)
<add> } else {
<add> attributes["insecure-registries"] = "[]"
<add> }
<add>
<ide> attributes["cluster-store"] = daemon.configStore.ClusterStore
<ide> if daemon.configStore.ClusterOpts != nil {
<del> opts, _ := json.Marshal(daemon.configStore.ClusterOpts)
<add> opts, err := json.Marshal(daemon.configStore.ClusterOpts)
<add> if err != nil {
<add> return err
<add> }
<ide> attributes["cluster-store-opts"] = string(opts)
<ide> } else {
<ide> attributes["cluster-store-opts"] = "{}"
<ide> }
<ide> attributes["cluster-advertise"] = daemon.configStore.ClusterAdvertise
<add>
<ide> if daemon.configStore.Labels != nil {
<del> labels, _ := json.Marshal(daemon.configStore.Labels)
<add> labels, err := json.Marshal(daemon.configStore.Labels)
<add> if err != nil {
<add> return err
<add> }
<ide> attributes["labels"] = string(labels)
<ide> } else {
<ide> attributes["labels"] = "[]"
<ide> }
<add>
<ide> attributes["max-concurrent-downloads"] = fmt.Sprintf("%d", *daemon.configStore.MaxConcurrentDownloads)
<ide> attributes["max-concurrent-uploads"] = fmt.Sprintf("%d", *daemon.configStore.MaxConcurrentUploads)
<ide> attributes["shutdown-timeout"] = fmt.Sprintf("%d", daemon.configStore.ShutdownTimeout)
<ide><path>daemon/daemon_test.go
<ide> import (
<ide> _ "github.com/docker/docker/pkg/discovery/memory"
<ide> "github.com/docker/docker/pkg/registrar"
<ide> "github.com/docker/docker/pkg/truncindex"
<add> "github.com/docker/docker/registry"
<ide> "github.com/docker/docker/volume"
<ide> volumedrivers "github.com/docker/docker/volume/drivers"
<ide> "github.com/docker/docker/volume/local"
<ide> func TestDaemonReloadLabels(t *testing.T) {
<ide> },
<ide> }
<ide>
<del> daemon.Reload(newConfig)
<add> if err := daemon.Reload(newConfig); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<ide> label := daemon.configStore.Labels[0]
<ide> if label != "foo:baz" {
<ide> t.Fatalf("Expected daemon label `foo:baz`, got %s", label)
<ide> }
<ide> }
<ide>
<add>func TestDaemonReloadInsecureRegistries(t *testing.T) {
<add> daemon := &Daemon{}
<add> // initialize daemon with existing insecure registries: "127.0.0.0/8", "10.10.1.11:5000", "10.10.1.22:5000"
<add> daemon.RegistryService = registry.NewService(registry.ServiceOptions{
<add> InsecureRegistries: []string{
<add> "127.0.0.0/8",
<add> "10.10.1.11:5000",
<add> "10.10.1.22:5000", // this will be removed when reloading
<add> "docker1.com",
<add> "docker2.com", // this will be removed when reloading
<add> },
<add> })
<add>
<add> daemon.configStore = &Config{}
<add>
<add> insecureRegistries := []string{
<add> "127.0.0.0/8", // this will be kept
<add> "10.10.1.11:5000", // this will be kept
<add> "10.10.1.33:5000", // this will be newly added
<add> "docker1.com", // this will be kept
<add> "docker3.com", // this will be newly added
<add> }
<add>
<add> valuesSets := make(map[string]interface{})
<add> valuesSets["insecure-registries"] = insecureRegistries
<add>
<add> newConfig := &Config{
<add> CommonConfig: CommonConfig{
<add> ServiceOptions: registry.ServiceOptions{
<add> InsecureRegistries: insecureRegistries,
<add> },
<add> valuesSet: valuesSets,
<add> },
<add> }
<add>
<add> if err := daemon.Reload(newConfig); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> // After Reload, daemon.RegistryService will be changed which is useful
<add> // for registry communication in daemon.
<add> registries := daemon.RegistryService.ServiceConfig()
<add>
<add> // After Reload(), newConfig has come to registries.InsecureRegistryCIDRs and registries.IndexConfigs in daemon.
<add> // Then collect registries.InsecureRegistryCIDRs in dataMap.
<add> // When collecting, we need to convert CIDRS into string as a key,
<add> // while the times of key appears as value.
<add> dataMap := map[string]int{}
<add> for _, value := range registries.InsecureRegistryCIDRs {
<add> if _, ok := dataMap[value.String()]; !ok {
<add> dataMap[value.String()] = 1
<add> } else {
<add> dataMap[value.String()]++
<add> }
<add> }
<add>
<add> for _, value := range registries.IndexConfigs {
<add> if _, ok := dataMap[value.Name]; !ok {
<add> dataMap[value.Name] = 1
<add> } else {
<add> dataMap[value.Name]++
<add> }
<add> }
<add>
<add> // Finally compare dataMap with the original insecureRegistries.
<add> // Each value in insecureRegistries should appear in daemon's insecure registries,
<add> // and each can only appear exactly ONCE.
<add> for _, r := range insecureRegistries {
<add> if value, ok := dataMap[r]; !ok {
<add> t.Fatalf("Expected daemon insecure registry %s, got none", r)
<add> } else if value != 1 {
<add> t.Fatalf("Expected only 1 daemon insecure registry %s, got %d", r, value)
<add> }
<add> }
<add>
<add> // assert if "10.10.1.22:5000" is removed when reloading
<add> if value, ok := dataMap["10.10.1.22:5000"]; ok {
<add> t.Fatalf("Expected no insecure registry of 10.10.1.22:5000, got %d", value)
<add> }
<add>
<add> // assert if "docker2.com" is removed when reloading
<add> if value, ok := dataMap["docker2.com"]; ok {
<add> t.Fatalf("Expected no insecure registry of docker2.com, got %d", value)
<add> }
<add>}
<add>
<ide> func TestDaemonReloadNotAffectOthers(t *testing.T) {
<ide> daemon := &Daemon{}
<ide> daemon.configStore = &Config{
<ide> func TestDaemonReloadNotAffectOthers(t *testing.T) {
<ide> },
<ide> }
<ide>
<del> daemon.Reload(newConfig)
<add> if err := daemon.Reload(newConfig); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<ide> label := daemon.configStore.Labels[0]
<ide> if label != "foo:baz" {
<ide> t.Fatalf("Expected daemon label `foo:baz`, got %s", label)
<ide><path>docs/reference/commandline/dockerd.md
<ide> The list of currently supported options that can be reconfigured is this:
<ide> - `runtimes`: it updates the list of available OCI runtimes that can
<ide> be used to run containers
<ide> - `authorization-plugin`: specifies the authorization plugins to use.
<add>- `insecure-registries`: it replaces the daemon insecure registries with a new set of insecure registries. If some existing insecure registries in daemon's configuration are not in newly reloaded insecure resgitries, these existing ones will be removed from daemon's config.
<ide>
<ide> Updating and reloading the cluster configurations such as `--cluster-store`,
<ide> `--cluster-advertise` and `--cluster-store-opts` will take effect only if
<ide> these configurations were not previously configured. If `--cluster-store`
<ide> has been provided in flags and `cluster-advertise` not, `cluster-advertise`
<del>can be added in the configuration file without accompanied by `--cluster-store`
<add>can be added in the configuration file without accompanied by `--cluster-store`.
<ide> Configuration reload will log a warning message if it detects a change in
<ide> previously configured cluster configurations.
<ide>
<ide><path>integration-cli/docker_cli_events_unix_test.go
<ide> func (s *DockerDaemonSuite) TestDaemonEvents(c *check.C) {
<ide> out, err = s.d.Cmd("events", "--since=0", "--until", daemonUnixTime(c))
<ide> c.Assert(err, checker.IsNil)
<ide>
<del> c.Assert(out, checker.Contains, fmt.Sprintf("daemon reload %s (cluster-advertise=, cluster-store=, cluster-store-opts={}, debug=true, default-runtime=runc, labels=[\"bar=foo\"], live-restore=false, max-concurrent-downloads=1, max-concurrent-uploads=5, name=%s, runtimes=runc:{docker-runc []}, shutdown-timeout=10)", daemonID, daemonName))
<add> c.Assert(out, checker.Contains, fmt.Sprintf("daemon reload %s (cluster-advertise=, cluster-store=, cluster-store-opts={}, debug=true, default-runtime=runc, insecure-registries=[], labels=[\"bar=foo\"], live-restore=false, max-concurrent-downloads=1, max-concurrent-uploads=5, name=%s, runtimes=runc:{docker-runc []}, shutdown-timeout=10)", daemonID, daemonName))
<ide> }
<ide>
<ide> func (s *DockerDaemonSuite) TestDaemonEventsWithFilters(c *check.C) {
<ide><path>registry/config.go
<ide> func (options *ServiceOptions) InstallCliFlags(flags *pflag.FlagSet) {
<ide>
<ide> // newServiceConfig returns a new instance of ServiceConfig
<ide> func newServiceConfig(options ServiceOptions) *serviceConfig {
<del> // Localhost is by default considered as an insecure registry
<del> // This is a stop-gap for people who are running a private registry on localhost (especially on Boot2docker).
<del> //
<del> // TODO: should we deprecate this once it is easier for people to set up a TLS registry or change
<del> // daemon flags on boot2docker?
<del> options.InsecureRegistries = append(options.InsecureRegistries, "127.0.0.0/8")
<del>
<ide> config := &serviceConfig{
<ide> ServiceConfig: registrytypes.ServiceConfig{
<ide> InsecureRegistryCIDRs: make([]*registrytypes.NetIPNet, 0),
<ide> func newServiceConfig(options ServiceOptions) *serviceConfig {
<ide> },
<ide> V2Only: options.V2Only,
<ide> }
<del> // Split --insecure-registry into CIDR and registry-specific settings.
<del> for _, r := range options.InsecureRegistries {
<add>
<add> config.LoadInsecureRegistries(options.InsecureRegistries)
<add>
<add> return config
<add>}
<add>
<add>// LoadInsecureRegistries loads insecure registries to config
<add>func (config *serviceConfig) LoadInsecureRegistries(registries []string) error {
<add> // Localhost is by default considered as an insecure registry
<add> // This is a stop-gap for people who are running a private registry on localhost (especially on Boot2docker).
<add> //
<add> // TODO: should we deprecate this once it is easier for people to set up a TLS registry or change
<add> // daemon flags on boot2docker?
<add> registries = append(registries, "127.0.0.0/8")
<add>
<add> // Store original InsecureRegistryCIDRs and IndexConfigs
<add> // Clean InsecureRegistryCIDRs and IndexConfigs in config, as passed registries has all insecure registry info.
<add> originalCIDRs := config.ServiceConfig.InsecureRegistryCIDRs
<add> originalIndexInfos := config.ServiceConfig.IndexConfigs
<add>
<add> config.ServiceConfig.InsecureRegistryCIDRs = make([]*registrytypes.NetIPNet, 0)
<add> config.ServiceConfig.IndexConfigs = make(map[string]*registrytypes.IndexInfo, 0)
<add>
<add>skip:
<add> for _, r := range registries {
<add> // validate insecure registry
<add> if _, err := ValidateIndexName(r); err != nil {
<add> // before returning err, roll back to original data
<add> config.ServiceConfig.InsecureRegistryCIDRs = originalCIDRs
<add> config.ServiceConfig.IndexConfigs = originalIndexInfos
<add> return err
<add> }
<ide> // Check if CIDR was passed to --insecure-registry
<ide> _, ipnet, err := net.ParseCIDR(r)
<ide> if err == nil {
<del> // Valid CIDR.
<del> config.InsecureRegistryCIDRs = append(config.InsecureRegistryCIDRs, (*registrytypes.NetIPNet)(ipnet))
<add> // Valid CIDR. If ipnet is already in config.InsecureRegistryCIDRs, skip.
<add> data := (*registrytypes.NetIPNet)(ipnet)
<add> for _, value := range config.InsecureRegistryCIDRs {
<add> if value.IP.String() == data.IP.String() && value.Mask.String() == data.Mask.String() {
<add> continue skip
<add> }
<add> }
<add> // ipnet is not found, add it in config.InsecureRegistryCIDRs
<add> config.InsecureRegistryCIDRs = append(config.InsecureRegistryCIDRs, data)
<add>
<ide> } else {
<ide> // Assume `host:port` if not CIDR.
<ide> config.IndexConfigs[r] = ®istrytypes.IndexInfo{
<ide> func newServiceConfig(options ServiceOptions) *serviceConfig {
<ide> Official: true,
<ide> }
<ide>
<del> return config
<add> return nil
<ide> }
<ide>
<ide> // isSecureIndex returns false if the provided indexName is part of the list of insecure registries
<ide><path>registry/service.go
<ide> import (
<ide> "net/http"
<ide> "net/url"
<ide> "strings"
<add> "sync"
<ide>
<ide> "golang.org/x/net/context"
<ide>
<ide> type Service interface {
<ide> Search(ctx context.Context, term string, limit int, authConfig *types.AuthConfig, userAgent string, headers map[string][]string) (*registrytypes.SearchResults, error)
<ide> ServiceConfig() *registrytypes.ServiceConfig
<ide> TLSConfig(hostname string) (*tls.Config, error)
<add> LoadInsecureRegistries([]string) error
<ide> }
<ide>
<ide> // DefaultService is a registry service. It tracks configuration data such as a list
<ide> // of mirrors.
<ide> type DefaultService struct {
<ide> config *serviceConfig
<add> mu sync.Mutex
<ide> }
<ide>
<ide> // NewService returns a new instance of DefaultService ready to be
<ide> func NewService(options ServiceOptions) *DefaultService {
<ide>
<ide> // ServiceConfig returns the public registry service configuration.
<ide> func (s *DefaultService) ServiceConfig() *registrytypes.ServiceConfig {
<del> return &s.config.ServiceConfig
<add> s.mu.Lock()
<add> defer s.mu.Unlock()
<add>
<add> servConfig := registrytypes.ServiceConfig{
<add> InsecureRegistryCIDRs: make([]*(registrytypes.NetIPNet), 0),
<add> IndexConfigs: make(map[string]*(registrytypes.IndexInfo)),
<add> Mirrors: make([]string, 0),
<add> }
<add>
<add> // construct a new ServiceConfig which will not retrieve s.Config directly,
<add> // and look up items in s.config with mu locked
<add> servConfig.InsecureRegistryCIDRs = append(servConfig.InsecureRegistryCIDRs, s.config.ServiceConfig.InsecureRegistryCIDRs...)
<add>
<add> for key, value := range s.config.ServiceConfig.IndexConfigs {
<add> servConfig.IndexConfigs[key] = value
<add> }
<add>
<add> servConfig.Mirrors = append(servConfig.Mirrors, s.config.ServiceConfig.Mirrors...)
<add>
<add> return &servConfig
<add>}
<add>
<add>// LoadInsecureRegistries loads insecure registries for Service
<add>func (s *DefaultService) LoadInsecureRegistries(registries []string) error {
<add> s.mu.Lock()
<add> defer s.mu.Unlock()
<add>
<add> return s.config.LoadInsecureRegistries(registries)
<ide> }
<ide>
<ide> // Auth contacts the public registry with the provided credentials,
<ide> func (s *DefaultService) Search(ctx context.Context, term string, limit int, aut
<ide>
<ide> indexName, remoteName := splitReposSearchTerm(term)
<ide>
<add> // Search is a long-running operation, just lock s.config to avoid block others.
<add> s.mu.Lock()
<ide> index, err := newIndexInfo(s.config, indexName)
<add> s.mu.Unlock()
<add>
<ide> if err != nil {
<ide> return nil, err
<ide> }
<ide> func (s *DefaultService) Search(ctx context.Context, term string, limit int, aut
<ide> // ResolveRepository splits a repository name into its components
<ide> // and configuration of the associated registry.
<ide> func (s *DefaultService) ResolveRepository(name reference.Named) (*RepositoryInfo, error) {
<add> s.mu.Lock()
<add> defer s.mu.Unlock()
<ide> return newRepositoryInfo(s.config, name)
<ide> }
<ide>
<ide> func (e APIEndpoint) ToV1Endpoint(userAgent string, metaHeaders http.Header) (*V
<ide>
<ide> // TLSConfig constructs a client TLS configuration based on server defaults
<ide> func (s *DefaultService) TLSConfig(hostname string) (*tls.Config, error) {
<add> s.mu.Lock()
<add> defer s.mu.Unlock()
<add>
<add> return newTLSConfig(hostname, isSecureIndex(s.config, hostname))
<add>}
<add>
<add>// tlsConfig constructs a client TLS configuration based on server defaults
<add>func (s *DefaultService) tlsConfig(hostname string) (*tls.Config, error) {
<ide> return newTLSConfig(hostname, isSecureIndex(s.config, hostname))
<ide> }
<ide>
<ide> func (s *DefaultService) tlsConfigForMirror(mirrorURL *url.URL) (*tls.Config, error) {
<del> return s.TLSConfig(mirrorURL.Host)
<add> return s.tlsConfig(mirrorURL.Host)
<ide> }
<ide>
<ide> // LookupPullEndpoints creates a list of endpoints to try to pull from, in order of preference.
<ide> // It gives preference to v2 endpoints over v1, mirrors over the actual
<ide> // registry, and HTTPS over plain HTTP.
<ide> func (s *DefaultService) LookupPullEndpoints(hostname string) (endpoints []APIEndpoint, err error) {
<add> s.mu.Lock()
<add> defer s.mu.Unlock()
<add>
<ide> return s.lookupEndpoints(hostname)
<ide> }
<ide>
<ide> // LookupPushEndpoints creates a list of endpoints to try to push to, in order of preference.
<ide> // It gives preference to v2 endpoints over v1, and HTTPS over plain HTTP.
<ide> // Mirrors are not included.
<ide> func (s *DefaultService) LookupPushEndpoints(hostname string) (endpoints []APIEndpoint, err error) {
<add> s.mu.Lock()
<add> defer s.mu.Unlock()
<add>
<ide> allEndpoints, err := s.lookupEndpoints(hostname)
<ide> if err == nil {
<ide> for _, endpoint := range allEndpoints {
<ide><path>registry/service_v1.go
<ide> func (s *DefaultService) lookupV1Endpoints(hostname string) (endpoints []APIEndp
<ide> return endpoints, nil
<ide> }
<ide>
<del> tlsConfig, err = s.TLSConfig(hostname)
<add> tlsConfig, err = s.tlsConfig(hostname)
<ide> if err != nil {
<ide> return nil, err
<ide> }
<ide><path>registry/service_v2.go
<ide> func (s *DefaultService) lookupV2Endpoints(hostname string) (endpoints []APIEndp
<ide> return endpoints, nil
<ide> }
<ide>
<del> tlsConfig, err = s.TLSConfig(hostname)
<add> tlsConfig, err = s.tlsConfig(hostname)
<ide> if err != nil {
<ide> return nil, err
<ide> } | 8 |
Javascript | Javascript | remove unused options from swc-loader | 40cf9313387955c75e00c1b4f653fb0e63e28759 | <ide><path>packages/next/build/swc/index.js
<ide> async function transform(src, options) {
<ide> options.jsc.parser.syntax = options.jsc.parser.syntax ?? 'ecmascript'
<ide> }
<ide>
<del> const { plugin, ...newOptions } = options
<del>
<del> if (plugin) {
<del> const m =
<del> typeof src === 'string'
<del> ? await this.parse(src, options?.jsc?.parser)
<del> : src
<del> return this.transform(plugin(m), newOptions)
<del> }
<del>
<ide> return bindings.transform(
<ide> isModule ? JSON.stringify(src) : src,
<ide> isModule,
<del> toBuffer(newOptions)
<add> toBuffer(options)
<ide> )
<ide> }
<ide>
<ide> function transformSync(src, options) {
<ide> options.jsc.parser.syntax = options.jsc.parser.syntax ?? 'ecmascript'
<ide> }
<ide>
<del> const { plugin, ...newOptions } = options
<del>
<del> if (plugin) {
<del> const m =
<del> typeof src === 'string' ? this.parseSync(src, options?.jsc?.parser) : src
<del> return this.transformSync(plugin(m), newOptions)
<del> }
<del>
<ide> return bindings.transformSync(
<ide> isModule ? JSON.stringify(src) : src,
<ide> isModule,
<del> toBuffer(newOptions)
<add> toBuffer(options)
<ide> )
<ide> }
<ide> | 1 |
PHP | PHP | add missing sprintf in shell.php | 5b05adea8c8621addd0f870c3ad6cac49854811e | <ide><path>src/Console/Shell.php
<ide> public function startup() {
<ide> */
<ide> protected function _welcome() {
<ide> $this->out();
<del> $this->out('<info>Welcome to CakePHP %s Console</info>', 'v' . Configure::version());
<add> $this->out(sprintf('<info>Welcome to CakePHP %s Console</info>', 'v' . Configure::version()));
<ide> $this->hr();
<ide> $this->out(sprintf('App : %s', APP_DIR));
<ide> $this->out(sprintf('Path: %s', APP)); | 1 |
Javascript | Javascript | fix broken inline script | 4c2c45338a583b12c055750c57ae66710eaae384 | <ide><path>examples/amp-first/pages/index.js
<ide> const Home = props => (
<ide> id="hello-world"
<ide> layout="fixed-height"
<ide> height="64"
<del> script={() => {
<del> const btn = document.querySelector('button')
<add> script="
<add> const btn = document.querySelector('button');
<ide> btn.addEventListener('click', () => {
<ide> document.body.textContent = 'Hello World!'
<del> })
<del> }}
<add> })"
<ide> >
<ide> <button>Hello amp-script!</button>
<ide> </AmpScript> | 1 |
Go | Go | expect uncompressed tar for applydiff | 273f50c741e82a0be3e9f9d4c975cc18801dfe38 | <ide><path>daemon/graphdriver/aufs/aufs.go
<ide> func (a *Driver) Diff(id, parent string) (archive.Archive, error) {
<ide> }
<ide>
<ide> func (a *Driver) applyDiff(id string, diff archive.ArchiveReader) error {
<del> return chrootarchive.Untar(diff, path.Join(a.rootPath(), "diff", id), nil)
<add> return chrootarchive.UntarUncompressed(diff, path.Join(a.rootPath(), "diff", id), nil)
<ide> }
<ide>
<ide> // DiffSize calculates the changes between the specified id
<ide><path>daemon/graphdriver/driver.go
<ide> type Driver interface {
<ide> // ApplyDiff extracts the changeset from the given diff into the
<ide> // layer with the specified id and parent, returning the size of the
<ide> // new layer in bytes.
<add> // The archive.ArchiveReader must be an uncompressed stream.
<ide> ApplyDiff(id, parent string, diff archive.ArchiveReader) (size int64, err error)
<ide> // DiffSize calculates the changes between the specified id
<ide> // and its parent and returns the size in bytes of the changes
<ide><path>daemon/graphdriver/fsdiff.go
<ide> func (gdw *naiveDiffDriver) ApplyDiff(id, parent string, diff archive.ArchiveRea
<ide>
<ide> start := time.Now().UTC()
<ide> logrus.Debugf("Start untar layer")
<del> if size, err = chrootarchive.ApplyLayer(layerFs, diff); err != nil {
<add> if size, err = chrootarchive.ApplyUncompressedLayer(layerFs, diff); err != nil {
<ide> return
<ide> }
<ide> logrus.Debugf("Untar time: %vs", time.Now().UTC().Sub(start).Seconds())
<ide><path>daemon/graphdriver/overlay/overlay.go
<ide> func (d *Driver) ApplyDiff(id string, parent string, diff archive.ArchiveReader)
<ide> return 0, err
<ide> }
<ide>
<del> if size, err = chrootarchive.ApplyLayer(tmpRootDir, diff); err != nil {
<add> if size, err = chrootarchive.ApplyUncompressedLayer(tmpRootDir, diff); err != nil {
<ide> return 0, err
<ide> }
<ide> | 4 |
Ruby | Ruby | report some exceptions | c5cd206169c57609b1c6d2f4cff9e390b6350a27 | <ide><path>Library/brew.rb
<ide> def require?(path)
<ide> $stderr.puts # seemingly a newline is typical
<ide> exit 130
<ide> rescue BuildError => e
<add> report_analytics_exception(e)
<ide> e.dump
<ide> exit 1
<ide> rescue RuntimeError, SystemCallError => e
<add> report_analytics_exception(e)
<ide> raise if e.message.empty?
<ide> onoe e
<ide> $stderr.puts e.backtrace if ARGV.debug?
<ide> exit 1
<ide> rescue Exception => e
<add> report_analytics_exception(e)
<ide> onoe e
<ide> if internal_cmd
<ide> $stderr.puts "#{Tty.white}Please report this bug:" | 1 |
PHP | PHP | add tests for the required_without validation rule | 8523dd30312dea0c8e3ba017d5c052ce5ae5b777 | <ide><path>tests/Validation/ValidationValidatorTest.php
<ide> public function testValidateRequiredWith()
<ide> $this->assertFalse($v->passes());
<ide> }
<ide>
<add> public function testValidateRequiredWithout()
<add> {
<add> $trans = $this->getRealTranslator();
<add> $v = new Validator($trans, array('first' => 'Taylor'), array('last' => 'required_without:first'));
<add> $this->assertTrue($v->passes());
<add>
<add> $v = new Validator($trans, array('first' => 'Taylor', 'last' => ''), array('last' => 'required_without:first'));
<add> $this->assertTrue($v->passes());
<add>
<add> $v = new Validator($trans, array('first' => ''), array('last' => 'required_without:first'));
<add> $this->assertFalse($v->passes());
<add>
<add> $v = new Validator($trans, array(), array('last' => 'required_without:first'));
<add> $this->assertFalse($v->passes());
<add>
<add> $v = new Validator($trans, array('first' => 'Taylor', 'last' => 'Otwell'), array('last' => 'required_without:first'));
<add> $this->assertTrue($v->passes());
<add>
<add> $v = new Validator($trans, array('last' => 'Otwell'), array('last' => 'required_without:first'));
<add> $this->assertTrue($v->passes());
<add>
<add> $file = new File('', false);
<add> $v = new Validator($trans, array('file' => $file), array('foo' => 'required_without:file'));
<add> $this->assertFalse($v->passes());
<add>
<add> $foo = new File('', false);
<add> $v = new Validator($trans, array('foo' => $foo), array('foo' => 'required_without:file'));
<add> $this->assertFalse($v->passes());
<add>
<add> $foo = new File(__FILE__, false);
<add> $v = new Validator($trans, array('foo' => $foo), array('foo' => 'required_without:file'));
<add> $this->assertTrue($v->passes());
<add>
<add> $file = new File(__FILE__, false);
<add> $foo = new File(__FILE__, false);
<add> $v = new Validator($trans, array('file' => $file, 'foo' => $foo), array('foo' => 'required_without:file'));
<add> $this->assertTrue($v->passes());
<add>
<add> $file = new File(__FILE__, false);
<add> $foo = new File('', false);
<add> $v = new Validator($trans, array('file' => $file, 'foo' => $foo), array('foo' => 'required_without:file'));
<add> $this->assertTrue($v->passes());
<add>
<add> $file = new File('', false);
<add> $foo = new File(__FILE__, false);
<add> $v = new Validator($trans, array('file' => $file, 'foo' => $foo), array('foo' => 'required_without:file'));
<add> $this->assertTrue($v->passes());
<add>
<add> $file = new File('', false);
<add> $foo = new File('', false);
<add> $v = new Validator($trans, array('file' => $file, 'foo' => $foo), array('foo' => 'required_without:file'));
<add> $this->assertFalse($v->passes());
<add> }
<add>
<ide> public function testValidateConfirmed()
<ide> {
<ide> $trans = $this->getRealTranslator();
<ide> public function testValidateSize()
<ide> $file->expects($this->any())->method('getSize')->will($this->returnValue(4072));
<ide> $v = new Validator($trans, array(), array('photo' => 'Size:3'));
<ide> $v->setFiles(array('photo' => $file));
<del> $this->assertFalse($v->passes());
<add> $this->assertFalse($v->passes());
<ide> }
<ide>
<ide>
<ide> public function testValidateBetween()
<ide> $file->expects($this->any())->method('getSize')->will($this->returnValue(4072));
<ide> $v = new Validator($trans, array(), array('photo' => 'Between:1,2'));
<ide> $v->setFiles(array('photo' => $file));
<del> $this->assertFalse($v->passes());
<add> $this->assertFalse($v->passes());
<ide> }
<ide>
<ide>
<ide> public function testValidateMin()
<ide> $file->expects($this->any())->method('getSize')->will($this->returnValue(4072));
<ide> $v = new Validator($trans, array(), array('photo' => 'Min:10'));
<ide> $v->setFiles(array('photo' => $file));
<del> $this->assertFalse($v->passes());
<add> $this->assertFalse($v->passes());
<ide> }
<ide>
<ide>
<ide> public function testValidateMax()
<ide> $file->expects($this->any())->method('getSize')->will($this->returnValue(4072));
<ide> $v = new Validator($trans, array(), array('photo' => 'Max:2'));
<ide> $v->setFiles(array('photo' => $file));
<del> $this->assertFalse($v->passes());
<add> $this->assertFalse($v->passes());
<ide> }
<ide>
<ide> | 1 |
Mixed | Text | fix permute layer | 4b6bf1dbfe0d0b49f876c701b95a6ff66e9f206d | <ide><path>README.md
<ide> In the examples folder, you will find example models for real datasets:
<ide> - Reuters newswires topic classification: Multilayer Perceptron (MLP)
<ide> - MNIST handwritten digits classification: MLP & CNN
<ide> - Character-level text generation with LSTM
<add>
<ide> ...and more.
<ide>
<ide>
<ide><path>docs/sources/layers/core.md
<ide> Note that the output is still a single tensor; `RepeatVector` does not split the
<ide> - __Arguments__:
<ide> - __n__: int.
<ide>
<add>---
<add>
<add>## Permute
<add>```python
<add>keras.layers.core.Permute(dims)
<add>```
<add>Permute the dimensions of the input data according to the given tuple. Sometimes useful for connecting RNNs and convnets together.
<add>
<add>- __Input shape: This layer does not assume a specific input shape.
<add>
<add>- __Output shape: Same as the input shape, but with the dimensions re-ordered according to the ordering specified by the tuple.
<add>
<add>- __Argument: tuple specifying the permutation scheme (e.g. `(2, 1)` permutes the first and second dimension of the input).
<add>
<ide> - __Example__:
<add>```python
<add># input shape: (nb_samples, 10)
<add>model.add(Dense(10, 50)) # output shape: (nb_samples, 50)
<add>model.add(Reshape(10, 5)) # output shape: (nb_samples, 10, 5)
<add>model.add(Permute((2, 1))) #output shape: (nb_samples, 5, 10)
<add>```
<ide>
<ide> ---
<ide>
<ide><path>keras/layers/core.py
<ide> def __init__(self, dims):
<ide>
<ide> def get_output(self, train):
<ide> X = self.get_input(train)
<del> return X.dimshuffle(self.dims)
<add> return X.dimshuffle((0,) + self.dims)
<ide>
<ide> def get_config(self):
<ide> return {"name":self.__class__.__name__, | 3 |
Javascript | Javascript | ignore stylesheetvalidation if profiling | d7b34dd38d396bb692d6f5a3bb20245e5e3aac8f | <ide><path>Libraries/StyleSheet/StyleSheetValidation.js
<ide> const ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
<ide>
<ide> class StyleSheetValidation {
<ide> static validateStyleProp(prop: string, style: Object, caller: string) {
<del> if (!__DEV__) {
<add> if (!__DEV__ || global.__RCTProfileIsProfiling) {
<ide> return;
<ide> }
<ide> if (allStylePropTypes[prop] === undefined) {
<ide> class StyleSheetValidation {
<ide> }
<ide>
<ide> static validateStyle(name: string, styles: Object) {
<del> if (!__DEV__) {
<add> if (!__DEV__ || global.__RCTProfileIsProfiling) {
<ide> return;
<ide> }
<ide> for (const prop in styles[name]) {
<ide> class StyleSheetValidation {
<ide> }
<ide>
<ide> static addValidStylePropTypes(stylePropTypes) {
<add> if (!__DEV__ || global.__RCTProfileIsProfiling) {
<add> return;
<add> }
<ide> for (const key in stylePropTypes) {
<ide> allStylePropTypes[key] = stylePropTypes[key];
<ide> }
<ide> const styleError = function(message1, style, caller?, message2?) {
<ide>
<ide> const allStylePropTypes = {};
<ide>
<del>StyleSheetValidation.addValidStylePropTypes(ImageStylePropTypes);
<del>StyleSheetValidation.addValidStylePropTypes(TextStylePropTypes);
<del>StyleSheetValidation.addValidStylePropTypes(ViewStylePropTypes);
<add>if (__DEV__ && !global.__RCTProfileIsProfiling) {
<add> StyleSheetValidation.addValidStylePropTypes(ImageStylePropTypes);
<add> StyleSheetValidation.addValidStylePropTypes(TextStylePropTypes);
<add> StyleSheetValidation.addValidStylePropTypes(ViewStylePropTypes);
<add>}
<ide>
<ide> module.exports = StyleSheetValidation; | 1 |
Javascript | Javascript | fix the bookmark button and redo the anchor prefix | dd8c39d8e14d283777f8c4e5788ada2c719d9542 | <ide><path>web/viewer.js
<ide> var PDFView = {
<ide> },
<ide>
<ide> getDestinationHash: function pdfViewGetDestinationHash(dest) {
<del> // We add the full url for the extension so the anchor links don't come up
<del> // as resource:// urls and so open in new tab/window works.
<del> var url = PDFJS.isFirefoxExtension ? this.url.split('#')[0] : '';
<ide> if (typeof dest === 'string')
<del> return url + '#' + escape(dest);
<add> return PDFView.getAnchorUrl('#' + escape(dest));
<ide> if (dest instanceof Array) {
<ide> var destRef = dest[0]; // see navigateTo method for dest format
<ide> var pageNumber = destRef instanceof Object ?
<ide> this.pagesRefMap[destRef.num + ' ' + destRef.gen + ' R'] :
<ide> (destRef + 1);
<ide> if (pageNumber) {
<del> var pdfOpenParams = url + '#page=' + pageNumber;
<add> var pdfOpenParams = PDFView.getAnchorUrl('#page=' + pageNumber);
<ide> var destKind = dest[1];
<ide> if ('name' in destKind && destKind.name == 'XYZ') {
<ide> var scale = (dest[4] || this.currentScale);
<ide> var PDFView = {
<ide> return '';
<ide> },
<ide>
<add> /**
<add> * For the firefox extension we prefix the full url on anchor links so they
<add> * don't come up as resource:// urls and so open in new tab/window works.
<add> * @param {String} anchor The anchor hash include the #.
<add> */
<add> getAnchorUrl: function getAnchorUrl(anchor) {
<add> if (PDFJS.isFirefoxExtension)
<add> return this.url.split('#')[0] + anchor;
<add> return anchor;
<add> },
<add>
<ide> /**
<ide> * Show the error box.
<ide> * @param {String} message A message that is human readable.
<ide> function updateViewarea() {
<ide> store.set('zoom', normalizedScaleValue);
<ide> store.set('scrollLeft', Math.round(topLeft.x));
<ide> store.set('scrollTop', Math.round(topLeft.y));
<del>
<del> document.getElementById('viewBookmark').href = pdfOpenParams;
<add> var href = PDFView.getAnchorUrl(pdfOpenParams);
<add> document.getElementById('viewBookmark').href = href;
<ide> }
<ide>
<ide> window.addEventListener('scroll', function webViewerScroll(evt) { | 1 |
Javascript | Javascript | fix documentation for {{with}} helper | 826d33d2b6eaf178ac65a22d455b41e4a4c5b205 | <ide><path>packages/ember-htmlbars/lib/helpers/with.js
<ide> import shouldDisplay from "ember-views/streams/should_display";
<ide> Use the `{{with}}` helper when you want to alias a property to a new name. This is helpful
<ide> for semantic clarity as it allows you to retain default scope or to reference a property from another
<ide> `{{with}}` block.
<add>
<ide> If the aliased property is "falsey", for example: `false`, `undefined` `null`, `""`, `0` or
<ide> an empty array, the block will not be rendered.
<add>
<ide> ```handlebars
<del> // will only render if user.posts contains items
<add> {{! Will only render if user.posts contains items}}
<ide> {{#with user.posts as |blogPosts|}}
<ide> <div class="notice">
<ide> There are {{blogPosts.length}} blog posts written by {{user.name}}.
<ide> </div>
<del> {{#each post in blogPosts}}
<add> {{#each blogPosts as |post|}}
<ide> <li>{{post.title}}</li>
<ide> {{/each}}
<ide> {{/with}}
<ide> ```
<add>
<ide> Without the `as` operator, it would be impossible to reference `user.name` in the example above.
<add>
<ide> NOTE: The alias should not reuse a name from the bound property path.
<del> For example: `{{#with foo.bar as foo}}` is not supported because it attempts to alias using
<del> the first part of the property path, `foo`. Instead, use `{{#with foo.bar as baz}}`.
<add> For example: `{{#with foo.bar as |foo|}}` is not supported because it attempts to alias using
<add> the first part of the property path, `foo`. Instead, use `{{#with foo.bar as |baz|}}`.
<add>
<ide> ### `controller` option
<del> Adding `controller='something'` instructs the `{{with}}` helper to create and use an instance of
<del> the specified controller wrapping the aliased keyword.
<del> This is very similar to using an `itemController` option with the `{{each}}` helper.
<add>
<add> Adding `controller='someController'` instructs the `{{with}}` helper to create and use an instance of
<add> the specified controller wrapping the aliased keyword. This is very similar to using an
<add> `itemController` option with the [{{each}}](/api/classes/Ember.Handlebars.helpers.html#method_each) helper.
<add>
<add> ```javascript
<add> App.UserBlogPostsController = Ember.Controller.extend({
<add> isProlificBlogger: function() {
<add> return this.get('model.length') > 5;
<add> }.property('model.length')
<add> })
<add> ```
<add>
<ide> ```handlebars
<ide> {{#with users.posts controller='userBlogPosts' as |posts|}}
<del> {{!- `posts` is wrapped in our controller instance }}
<add> {{! `posts` is wrapped in our controller instance }}
<add> {{#if isProlificBlogger}}
<add> {{user.name}} has written more than {{posts.model.length}} blog posts!
<add> {{else}}
<add> {{user.name}} has only written {{posts.model.length}} blog posts.
<add> {{/if}}
<ide> {{/with}}
<ide> ```
<del> In the above example, the `posts` keyword is now wrapped in the `userBlogPost` controller,
<del> which provides an elegant way to decorate the context with custom
<del> functions/properties.
<add>
<add> In the above example, the `posts` keyword is now wrapped in the `userBlogPosts` controller,
<add> which provides an elegant way to decorate the context with custom functions/properties.
<add>
<ide> @method with
<ide> @for Ember.Handlebars.helpers
<ide> @param {Function} context | 1 |
Javascript | Javascript | add default options for *stat() | 4111c57f7ca3fd2993b60e86bea2abe63d124c65 | <ide><path>lib/fs.js
<ide> function readdirSync(path, options) {
<ide> return options.withFileTypes ? getDirents(path, result) : result;
<ide> }
<ide>
<del>function fstat(fd, options, callback) {
<add>function fstat(fd, options = { bigint: false }, callback) {
<ide> if (typeof options === 'function') {
<ide> callback = options;
<ide> options = {};
<ide> function fstat(fd, options, callback) {
<ide> binding.fstat(fd, options.bigint, req);
<ide> }
<ide>
<del>function lstat(path, options, callback) {
<add>function lstat(path, options = { bigint: false }, callback) {
<ide> if (typeof options === 'function') {
<ide> callback = options;
<ide> options = {};
<ide> function lstat(path, options, callback) {
<ide> binding.lstat(pathModule.toNamespacedPath(path), options.bigint, req);
<ide> }
<ide>
<del>function stat(path, options, callback) {
<add>function stat(path, options = { bigint: false }, callback) {
<ide> if (typeof options === 'function') {
<ide> callback = options;
<ide> options = {};
<ide><path>test/parallel/test-fs-stat.js
<ide> fs.stat(__filename, common.mustCall(function(err, s) {
<ide> }
<ide> );
<ide> });
<add>
<add>// Should not throw an error
<add>fs.stat(__filename, undefined, common.mustCall(() => {}));
<add>
<add>fs.open(__filename, 'r', undefined, common.mustCall((err, fd) => {
<add> // Should not throw an error
<add> fs.fstat(fd, undefined, common.mustCall(() => {}));
<add>}));
<add>
<add>// Should not throw an error
<add>fs.lstat(__filename, undefined, common.mustCall(() => {})); | 2 |
Java | Java | handle noclassdeffounderror consistently for tels | fb12e234fcee416c4ea6359a2242ce7e3977b0b6 | <ide><path>spring-test/src/main/java/org/springframework/test/context/TestContextManager.java
<ide> private TestExecutionListener[] retrieveTestExecutionListeners(Class<?> clazz) {
<ide> List<Class<? extends TestExecutionListener>> classesList = new ArrayList<Class<? extends TestExecutionListener>>();
<ide>
<ide> AnnotationDescriptor<TestExecutionListeners> descriptor = findAnnotationDescriptor(clazz, annotationType);
<del> boolean defaultListeners = false;
<ide>
<ide> // Use defaults?
<ide> if (descriptor == null) {
<ide> if (logger.isDebugEnabled()) {
<ide> logger.debug("@TestExecutionListeners is not present for class [" + clazz + "]: using defaults.");
<ide> }
<ide> classesList.addAll(getDefaultTestExecutionListenerClasses());
<del> defaultListeners = true;
<ide> }
<ide> else {
<ide> // Traverse the class hierarchy...
<ide> else if (!ObjectUtils.isEmpty(valueListenerClasses)) {
<ide> listeners.add(BeanUtils.instantiateClass(listenerClass));
<ide> }
<ide> catch (NoClassDefFoundError err) {
<del> if (defaultListeners) {
<del> if (logger.isDebugEnabled()) {
<del> logger.debug("Could not instantiate default TestExecutionListener class ["
<del> + listenerClass.getName()
<del> + "]. Specify custom listener classes or make the default listener classes available.");
<del> }
<del> }
<del> else {
<del> throw err;
<add> if (logger.isInfoEnabled()) {
<add> logger.info(String.format("Could not instantiate TestExecutionListener class [%s]. "
<add> + "Specify custom listener classes or make the default listener classes "
<add> + "(and their dependencies) available.", listenerClass.getName()));
<ide> }
<ide> }
<ide> } | 1 |
PHP | PHP | fix php 8.1 warnings | d5c49a1f4f646f63e56b23395f52d594048235ee | <ide><path>src/Database/Type/DateTimeType.php
<ide> public function marshal($value): ?DateTimeInterface
<ide> return null;
<ide> }
<ide>
<del> if (ctype_digit($value)) {
<add> if (is_int($value) || (is_string($value) && ctype_digit($value))) {
<ide> /** @var \Datetime|\DateTimeImmutable $dateTime */
<ide> $dateTime = new $class('@' . $value);
<ide>
<ide><path>src/ORM/Association/BelongsToMany.php
<ide> public function saveAssociated(EntityInterface $entity, array $options = [])
<ide> protected function _saveTarget(EntityInterface $parentEntity, array $entities, $options)
<ide> {
<ide> $joinAssociations = false;
<del> if (!empty($options['associated'][$this->_junctionProperty]['associated'])) {
<del> $joinAssociations = $options['associated'][$this->_junctionProperty]['associated'];
<add> if (isset($options['associated']) && is_array($options['associated'])) {
<add> if (!empty($options['associated'][$this->_junctionProperty]['associated'])) {
<add> $joinAssociations = $options['associated'][$this->_junctionProperty]['associated'];
<add> }
<add> unset($options['associated'][$this->_junctionProperty]);
<ide> }
<del> unset($options['associated'][$this->_junctionProperty]);
<ide>
<ide> $table = $this->getTarget();
<ide> $original = $entities;
<ide><path>tests/test_app/TestApp/Http/Client/Adapter/CakeStreamWrapper.php
<ide>
<ide> namespace TestApp\Http\Client\Adapter;
<ide>
<del>class CakeStreamWrapper implements \ArrayAccess
<add>use ArrayAccess;
<add>use ReturnTypeWillChange;
<add>
<add>class CakeStreamWrapper implements ArrayAccess
<ide> {
<ide> private $_stream;
<ide>
<ide> public function stream_set_option(int $option, int $arg1, int $arg2): bool
<ide> /**
<ide> * @inheritDoc
<ide> */
<del> public function offsetExists($offset)
<add> public function offsetExists($offset): bool
<ide> {
<ide> return isset($this->_data[$offset]);
<ide> }
<ide>
<ide> /**
<ide> * @inheritDoc
<ide> */
<add> #[ReturnTypeWillChange]
<ide> public function offsetGet($offset)
<ide> {
<ide> return $this->_data[$offset];
<ide> public function offsetGet($offset)
<ide> /**
<ide> * @inheritDoc
<ide> */
<del> public function offsetSet($offset, $value)
<add> public function offsetSet($offset, $value): void
<ide> {
<ide> $this->_data[$offset] = $value;
<ide> }
<ide>
<ide> /**
<ide> * @inheritDoc
<ide> */
<del> public function offsetUnset($offset)
<add> public function offsetUnset($offset): void
<ide> {
<ide> unset($this->_data[$offset]);
<ide> } | 3 |
Ruby | Ruby | fix cctools invocation check regular expression | e7554b0b3f71e0658e52e8dea974c511bc58aeba | <ide><path>Library/Homebrew/dev-cmd/audit.rb
<ide> def audit_line(line, _lineno)
<ide> problem "'fails_with :llvm' is now a no-op so should be removed"
<ide> end
<ide>
<del> if line =~ /system\s+['"](otool)|(install_name_tool)|(lipo)/
<add> if line =~ /system\s+['"](otool|install_name_tool|lipo)/ && formula.name != "cctools"
<ide> problem "Use ruby-macho instead of calling #{$1}"
<ide> end
<ide> | 1 |
Python | Python | fix typo in retinanet_model.py | 090c7149a7073bd4da4e057ddd4fa4398e095199 | <ide><path>official/vision/detection/modeling/retinanet_model.py
<ide> def __init__(self, params):
<ide> params.postprocess)
<ide>
<ide> self._transpose_input = params.train.transpose_input
<del> assert not self._transpose_input, 'Transpose input is not supportted.'
<add> assert not self._transpose_input, 'Transpose input is not supported.'
<ide> # Input layer.
<ide> input_shape = (
<ide> params.retinanet_parser.output_size + | 1 |
Python | Python | add a decoder layer for bert | cd6a59d5c1cb9c7905675fc82ce50df5e2bdf3f0 | <ide><path>transformers/modeling_bert.py
<ide> def forward(self, hidden_states, attention_mask=None, head_mask=None):
<ide> class BertDecoderLayer(nn.Module):
<ide> def __init__(self, config):
<ide> super(BertDecoderLayer, self).__init__()
<del> raise NotImplementedError
<add> self.self_attention = BertAttention(config)
<add> self.attention = BertAttention(config)
<add> self.intermediate = BertIntermediate(config)
<add> self.output = BertOutput(config)
<ide>
<del> def forward(self, hidden_state, encoder_output):
<del> raise NotImplementedError
<add> def forward(self, hidden_states, encoder_outputs, attention_mask=None, head_mask=None):
<add> self_attention_outputs = self.self_attention(query_tensor=hidden_states,
<add> key_tensor=hidden_states,
<add> value_tensor=hidden_states,
<add> attention_mask=attention_mask,
<add> head_mask=head_mask)
<add> self_attention_output = self_attention_outputs[0]
<add> attention_outputs = self.attention(query_tensor=self_attention_output,
<add> key_tensor=encoder_outputs,
<add> value_tensor=encoder_outputs,
<add> attention_mask=attention_mask,
<add> head_mask=head_mask)
<add> attention_output = attention_outputs[0]
<add> intermediate_output = self.intermediate(attention_output)
<add> layer_output = self.output(intermediate_output, attention_output)
<add> outputs = (layer_output,) + attention_outputs[1:]
<add> return outputs
<ide>
<ide>
<ide> class BertEncoder(nn.Module): | 1 |
PHP | PHP | fix coding standards and missing doc blocks | 53337387ad632d3ddddc3092a959376acf334a84 | <ide><path>Cake/Test/TestCase/View/Helper/PaginatorHelperTest.php
<ide> public function testTemplates() {
<ide> * @return void
<ide> */
<ide> public function testHasPrevious() {
<del> $this->assertFalse($this->Paginator->hasPrev());
<add> $this->assertSame($this->Paginator->hasPrev(), false);
<ide> $this->Paginator->request->params['paging']['Article']['prevPage'] = true;
<del> $this->assertTrue($this->Paginator->hasPrev());
<add> $this->assertSame($this->Paginator->hasPrev(), true);
<ide> $this->Paginator->request->params['paging']['Article']['prevPage'] = false;
<ide> }
<ide>
<ide> public function testHasPrevious() {
<ide> * @return void
<ide> */
<ide> public function testHasNext() {
<del> $this->assertTrue($this->Paginator->hasNext());
<add> $this->assertSame($this->Paginator->hasNext(), true);
<ide> $this->Paginator->request->params['paging']['Article']['nextPage'] = false;
<del> $this->assertFalse($this->Paginator->hasNext());
<add> $this->assertSame($this->Paginator->hasNext(), false);
<ide> $this->Paginator->request->params['paging']['Article']['nextPage'] = true;
<ide> }
<ide>
<ide> public function testNextAndPrevNonDefaultModel() {
<ide> $result = $this->Paginator->prev('Prev', [
<ide> 'model' => 'Client'
<ide> ]);
<del> $expected ='<li class="prev disabled"><span>Prev</span></li>';
<add> $expected = '<li class="prev disabled"><span>Prev</span></li>';
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $result = $this->Paginator->next('Next', [
<ide><path>Cake/View/Helper/PaginatorHelper.php
<ide> public function sortDir($model = null, $options = array()) {
<ide>
<ide> /**
<ide> * Generate an active/inactive link for next/prev methods.
<add> *
<add> * @param string $text The enabled text for the link.
<add> * @param boolean $enabled Whether or not the enabled/disabled version should be created.
<add> * @param array $options An array of options from the calling method.
<add> * @param array $templates An array of templates with the 'active' and 'disabled' keys.
<add> * @return string Generated HTML
<ide> */
<ide> protected function _toggledLink($text, $enabled, $options, $templates) {
<ide> $template = $templates['active'];
<ide> public function prev($title = '<< Previous', $options = []) {
<ide> $enabled = $this->hasPrev($options['model']);
<ide> $templates = [
<ide> 'active' => 'prevActive',
<del> 'disabled' => 'prevDisabled'
<add> 'disabled' => 'prevDisabled'
<ide> ];
<ide> return $this->_toggledLink($title, $enabled, $options, $templates);
<ide> }
<ide><path>Cake/View/StringTemplate.php
<ide> */
<ide> namespace Cake\View;
<ide>
<del>use Cake\Core\Plugin;
<ide> use Cake\Configure\Engine\PhpConfig;
<add>use Cake\Core\Plugin;
<ide> use Cake\Error;
<ide>
<ide> /** | 3 |
Text | Text | add note on compat import in tutorial | 02ae1682b5585581e88bbd996f7cb7fd22b146f7 | <ide><path>docs/tutorial/1-serialization.md
<ide> At this point we've translated the model instance into Python native datatypes.
<ide>
<ide> Deserialization is similar. First we parse a stream into Python native datatypes...
<ide>
<add> # This import will use either `StringIO.StringIO` or `io.BytesIO`
<add> # as appropriate, depending on if we're running Python 2 or Python 3.
<ide> from rest_framework.compat import BytesIO
<ide>
<ide> stream = BytesIO(content) | 1 |
Text | Text | improve dns introduction | 40d363d2bc31c1d454d2a248189684e1b9964c8b | <ide><path>doc/api/dns.md
<ide>
<ide> > Stability: 2 - Stable
<ide>
<del>The `dns` module contains functions belonging to two different categories:
<add>The `dns` module enables name resolution. For example, use it to look up IP
<add>addresses of host names.
<ide>
<del>1. Functions that use the underlying operating system facilities to perform
<del> name resolution, and that do not necessarily perform any network
<del> communication.
<del> This category contains only one function: [`dns.lookup()`][]. **Developers
<del> looking to perform name resolution in the same way that other applications
<del> on the same operating system behave should use [`dns.lookup()`][].**
<add>Although named for the Domain Name System (DNS), it does not always use the DNS
<add>protocol for lookups. [`dns.lookup()`][] uses the operating system facilities to
<add>perform name resolution. It may not need to perform any network communication.
<add>Developers looking to perform name resolution in the same way that other
<add>applications on the same operating system behave should use [`dns.lookup()`][].
<ide>
<del> For example, looking up `iana.org`.
<add>```js
<add>const dns = require('dns');
<ide>
<del> ```js
<del> const dns = require('dns');
<add>dns.lookup('example.org', (err, address, family) => {
<add> console.log('address: %j family: IPv%s', address, family);
<add>});
<add>// address: "93.184.216.34" family: IPv4
<add>```
<ide>
<del> dns.lookup('iana.org', (err, address, family) => {
<del> console.log('address: %j family: IPv%s', address, family);
<del> });
<del> // address: "192.0.43.8" family: IPv4
<del> ```
<del>
<del>2. Functions that connect to an actual DNS server to perform name resolution,
<del> and that _always_ use the network to perform DNS queries. This category
<del> contains all functions in the `dns` module _except_ [`dns.lookup()`][].
<del> These functions do not use the same set of configuration files used by
<del> [`dns.lookup()`][] (e.g. `/etc/hosts`). These functions should be used by
<del> developers who do not want to use the underlying operating system's
<del> facilities for name resolution, and instead want to _always_ perform DNS
<del> queries.
<del>
<del> Below is an example that resolves `'archive.org'` then reverse resolves the
<del> IP addresses that are returned.
<del>
<del> ```js
<del> const dns = require('dns');
<del>
<del> dns.resolve4('archive.org', (err, addresses) => {
<del> if (err) throw err;
<del>
<del> console.log(`addresses: ${JSON.stringify(addresses)}`);
<del>
<del> addresses.forEach((a) => {
<del> dns.reverse(a, (err, hostnames) => {
<del> if (err) {
<del> throw err;
<del> }
<del> console.log(`reverse for ${a}: ${JSON.stringify(hostnames)}`);
<del> });
<del> });
<add>All other functions in the `dns` module connect to an actual DNS server to
<add>perform name resolution. They will always use the network to perform DNS
<add>queries. These functions do not use the same set of configuration files used by
<add>[`dns.lookup()`][] (e.g. `/etc/hosts`). These functions should be used by
<add>developers who do not want to use the underlying operating system's
<add>facilities for name resolution, and instead want to always perform DNS queries.
<add>
<add>```js
<add>const dns = require('dns');
<add>
<add>dns.resolve4('archive.org', (err, addresses) => {
<add> if (err) throw err;
<add>
<add> console.log(`addresses: ${JSON.stringify(addresses)}`);
<add>
<add> addresses.forEach((a) => {
<add> dns.reverse(a, (err, hostnames) => {
<add> if (err) {
<add> throw err;
<add> }
<add> console.log(`reverse for ${a}: ${JSON.stringify(hostnames)}`);
<ide> });
<del> ```
<add> });
<add>});
<add>```
<ide>
<del>There are subtle consequences in choosing one over the other, please consult
<del>the [Implementation considerations section][] for more information.
<add>See the [Implementation considerations section][] for more information.
<ide>
<ide> ## Class: `dns.Resolver`
<ide> <!-- YAML | 1 |
Javascript | Javascript | fix typo in text-editor-spec.js | 08226f27b23622c6f51701da5d22fb4999e09cf2 | <ide><path>spec/text-editor-spec.js
<ide> describe('TextEditor', () => {
<ide>
<ide> describe('when there is a single selection', () => {
<ide> describe('when the selection spans a single line', () => {
<del> describe('when there is no fold in the preceeding row', () =>
<add> describe('when there is no fold in the preceding row', () =>
<ide> it('moves the line to the preceding row', () => {
<ide> expect(editor.lineTextForBufferRow(2)).toBe(
<ide> ' if (items.length <= 1) return items;'
<ide> describe('TextEditor', () => {
<ide> });
<ide> });
<ide>
<del> describe('when the preceeding row is a folded row', () => {
<del> it('moves the lines spanned by the selection to the preceeding row, but preserves the folded code', () => {
<add> describe('when the preceding row is a folded row', () => {
<add> it('moves the lines spanned by the selection to the preceding row, but preserves the folded code', () => {
<ide> expect(editor.lineTextForBufferRow(8)).toBe(
<ide> ' return sort(left).concat(pivot).concat(sort(right));'
<ide> );
<ide> describe('TextEditor', () => {
<ide> });
<ide>
<ide> describe('when the last line of selection does not end with a valid line ending', () => {
<del> it('appends line ending to last line and moves the lines spanned by the selection to the preceeding row', () => {
<add> it('appends line ending to last line and moves the lines spanned by the selection to the preceding row', () => {
<ide> expect(editor.lineTextForBufferRow(9)).toBe(' };');
<ide> expect(editor.lineTextForBufferRow(10)).toBe('');
<ide> expect(editor.lineTextForBufferRow(11)).toBe( | 1 |
Mixed | Ruby | fix inheritance of stored_attributes (fixes ) | 6de710d6648e451ef47e9215172901e8d736ba0c | <ide><path>activerecord/CHANGELOG.md
<add>* Fix `stored_attributes` to correctly merge the details of stored
<add> attributes defined in parent classes.
<add>
<add> Fixes #14672.
<add>
<add> *Brad Bennett*, *Jessica Yao*, *Lakshmi Parthasarathy*
<add>
<ide> * `change_column_default` allows `[]` as argument to `change_column_default`.
<ide>
<ide> Fixes #11586.
<ide><path>activerecord/lib/active_record/store.rb
<ide> module Store
<ide> extend ActiveSupport::Concern
<ide>
<ide> included do
<del> class_attribute :stored_attributes, instance_accessor: false
<del> self.stored_attributes = {}
<add> class << self
<add> attr_accessor :local_stored_attributes
<add> end
<ide> end
<ide>
<ide> module ClassMethods
<ide> def store_accessor(store_attribute, *keys)
<ide>
<ide> # assign new store attribute and create new hash to ensure that each class in the hierarchy
<ide> # has its own hash of stored attributes.
<del> self.stored_attributes = {} if self.stored_attributes.blank?
<del> self.stored_attributes[store_attribute] ||= []
<del> self.stored_attributes[store_attribute] |= keys
<add> self.local_stored_attributes ||= {}
<add> self.local_stored_attributes[store_attribute] ||= []
<add> self.local_stored_attributes[store_attribute] |= keys
<ide> end
<ide>
<ide> def _store_accessors_module
<ide> def _store_accessors_module
<ide> mod
<ide> end
<ide> end
<add>
<add> def stored_attributes
<add> parent = superclass.respond_to?(:stored_attributes) ? superclass.stored_attributes : {}
<add> if self.local_stored_attributes
<add> parent.merge!(self.local_stored_attributes) { |k, a, b| a | b }
<add> end
<add> parent
<add> end
<ide> end
<ide>
<ide> protected
<ide><path>activerecord/test/cases/store_test.rb
<ide> class StoreTest < ActiveRecord::TestCase
<ide> assert_equal [:width, :height], second_model.stored_attributes[:data]
<ide> end
<ide>
<add> test "stored_attributes are tracked per subclass" do
<add> first_model = Class.new(ActiveRecord::Base) do
<add> store_accessor :data, :color
<add> end
<add> second_model = Class.new(first_model) do
<add> store_accessor :data, :width, :height
<add> end
<add> third_model = Class.new(first_model) do
<add> store_accessor :data, :area, :volume
<add> end
<add>
<add> assert_equal [:color], first_model.stored_attributes[:data]
<add> assert_equal [:color, :width, :height], second_model.stored_attributes[:data]
<add> assert_equal [:color, :area, :volume], third_model.stored_attributes[:data]
<add> end
<add>
<ide> test "YAML coder initializes the store when a Nil value is given" do
<ide> assert_equal({}, @john.params)
<ide> end | 3 |
PHP | PHP | apply fixes from styleci | ab06a52f31f40583bf831ef8402b072c41f6c38f | <ide><path>src/Illuminate/Console/Command.php
<ide> protected function context()
<ide> 'no-ansi',
<ide> 'no-interaction',
<ide> 'quiet',
<del> 'verbose'
<add> 'verbose',
<ide> ]))->mapWithKeys(function ($value, $key) {
<ide> return ["--{$key}" => $value];
<ide> })->filter()->all(); | 1 |
PHP | PHP | rename some interfaces for consistency | 26982391b8ecf8f9160cec324c74ded96861f2b6 | <add><path>src/Illuminate/Contracts/Support/Arrayable.php
<del><path>src/Illuminate/Contracts/Support/ArrayableInterface.php
<ide> <?php namespace Illuminate\Contracts\Support;
<ide>
<del>interface ArrayableInterface {
<add>interface Arrayable {
<ide>
<ide> /**
<ide> * Get the instance as an array.
<add><path>src/Illuminate/Contracts/Support/Jsonable.php
<del><path>src/Illuminate/Contracts/Support/JsonableInterface.php
<ide> <?php namespace Illuminate\Contracts\Support;
<ide>
<del>interface JsonableInterface {
<add>interface Jsonable {
<ide>
<ide> /**
<ide> * Convert the object to its JSON representation.
<add><path>src/Illuminate/Contracts/Support/MessageProvider.php
<del><path>src/Illuminate/Contracts/Support/MessageProviderInterface.php
<ide> <?php namespace Illuminate\Contracts\Support;
<ide>
<del>interface MessageProviderInterface {
<add>interface MessageProvider {
<ide>
<ide> /**
<ide> * Get the messages for the instance.
<add><path>src/Illuminate/Contracts/Support/Renderable.php
<del><path>src/Illuminate/Contracts/Support/RenderableInterface.php
<ide> <?php namespace Illuminate\Contracts\Support;
<ide>
<del>interface RenderableInterface {
<add>interface Renderable {
<ide>
<ide> /**
<ide> * Get the evaluated contents of the object.
<add><path>src/Illuminate/Contracts/Support/ResponsePreparer.php
<del><path>src/Illuminate/Contracts/Support/ResponsePreparerInterface.php
<ide> <?php namespace Illuminate\Contracts\Support;
<ide>
<del>interface ResponsePreparerInterface {
<add>interface ResponsePreparer {
<ide>
<ide> /**
<ide> * Prepare the given value as a Response object.
<ide><path>src/Illuminate/Contracts/View/View.php
<ide> <?php namespace Illuminate\Contracts\View;
<ide>
<del>use Illuminate\Contracts\Support\RenderableInterface;
<add>use Illuminate\Contracts\Support\Renderable;
<ide>
<del>interface View extends RenderableInterface {
<add>interface View extends Renderable {
<ide>
<ide> /**
<ide> * Add a piece of data to the view.
<ide><path>src/Illuminate/Database/Eloquent/Model.php
<ide> use Carbon\Carbon;
<ide> use LogicException;
<ide> use JsonSerializable;
<add>use Illuminate\Contracts\Support\Jsonable;
<ide> use Illuminate\Contracts\Events\Dispatcher;
<add>use Illuminate\Contracts\Support\Arrayable;
<ide> use Illuminate\Contracts\Routing\UrlRoutable;
<ide> use Illuminate\Database\Eloquent\Relations\Pivot;
<ide> use Illuminate\Database\Eloquent\Relations\HasOne;
<ide> use Illuminate\Database\Eloquent\Relations\HasMany;
<ide> use Illuminate\Database\Eloquent\Relations\MorphTo;
<del>use Illuminate\Contracts\Support\JsonableInterface;
<del>use Illuminate\Contracts\Support\ArrayableInterface;
<ide> use Illuminate\Database\Eloquent\Relations\Relation;
<ide> use Illuminate\Database\Eloquent\Relations\MorphOne;
<ide> use Illuminate\Database\Eloquent\Relations\MorphMany;
<ide> use Illuminate\Database\Eloquent\Relations\HasManyThrough;
<ide> use Illuminate\Database\ConnectionResolverInterface as Resolver;
<ide>
<del>abstract class Model implements ArrayAccess, ArrayableInterface, JsonableInterface, UrlRoutable, JsonSerializable {
<add>abstract class Model implements ArrayAccess, Arrayable, Jsonable, UrlRoutable, JsonSerializable {
<ide>
<ide> /**
<ide> * The connection name for the model.
<ide> public function relationsToArray()
<ide> // If the values implements the Arrayable interface we can just call this
<ide> // toArray method on the instances which will convert both models and
<ide> // collections to their proper array form and we'll set the values.
<del> if ($value instanceof ArrayableInterface)
<add> if ($value instanceof Arrayable)
<ide> {
<ide> $relation = $value->toArray();
<ide> }
<ide> protected function mutateAttributeForArray($key, $value)
<ide> {
<ide> $value = $this->mutateAttribute($key, $value);
<ide>
<del> return $value instanceof ArrayableInterface ? $value->toArray() : $value;
<add> return $value instanceof Arrayable ? $value->toArray() : $value;
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Exception/Handler.php
<ide> use Exception;
<ide> use ErrorException;
<ide> use ReflectionFunction;
<del>use Illuminate\Contracts\Support\ResponsePreparerInterface;
<add>use Illuminate\Contracts\Support\ResponsePreparer;
<ide> use Illuminate\Contracts\Exception\Handler as HandlerContract;
<ide> use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
<ide> use Symfony\Component\Debug\Exception\FatalErrorException as FatalError;
<ide> class Handler implements HandlerContract {
<ide> /**
<ide> * The response preparer implementation.
<ide> *
<del> * @var \Illuminate\Contracts\Support\ResponsePreparerInterface
<add> * @var \Illuminate\Contracts\Support\ResponsePreparer
<ide> */
<ide> protected $responsePreparer;
<ide>
<ide> class Handler implements HandlerContract {
<ide> /**
<ide> * Create a new error handler instance.
<ide> *
<del> * @param \Illuminate\Contracts\Support\ResponsePreparerInterface $responsePreparer
<add> * @param \Illuminate\Contracts\Support\ResponsePreparer $responsePreparer
<ide> * @param \Illuminate\Exception\ExceptionDisplayerInterface $plainDisplayer
<ide> * @param \Illuminate\Exception\ExceptionDisplayerInterface $debugDisplayer
<ide> * @param bool $debug
<ide> * @return void
<ide> */
<del> public function __construct(ResponsePreparerInterface $responsePreparer,
<add> public function __construct(ResponsePreparer $responsePreparer,
<ide> ExceptionDisplayerInterface $plainDisplayer,
<ide> ExceptionDisplayerInterface $debugDisplayer,
<ide> $debug = true)
<ide><path>src/Illuminate/Foundation/Application.php
<ide> use Illuminate\Support\ServiceProvider;
<ide> use Illuminate\Events\EventServiceProvider;
<ide> use Illuminate\Routing\RoutingServiceProvider;
<add>use Illuminate\Contracts\Support\ResponsePreparer;
<ide> use Illuminate\Exception\ExceptionServiceProvider;
<ide> use Illuminate\Config\FileEnvironmentVariablesLoader;
<ide> use Symfony\Component\HttpKernel\HttpKernelInterface;
<ide> use Symfony\Component\HttpKernel\TerminableInterface;
<ide> use Symfony\Component\HttpKernel\Exception\HttpException;
<ide> use Symfony\Component\Debug\Exception\FatalErrorException;
<del>use Illuminate\Contracts\Support\ResponsePreparerInterface;
<ide> use Symfony\Component\HttpFoundation\Request as SymfonyRequest;
<ide> use Symfony\Component\HttpFoundation\Response as SymfonyResponse;
<ide> use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
<ide> class Application extends Container implements HttpKernelInterface,
<ide> TerminableInterface,
<ide> ApplicationContract,
<del> ResponsePreparerInterface {
<add> ResponsePreparer {
<ide>
<ide> /**
<ide> * The Laravel framework version.
<ide><path>src/Illuminate/Foundation/Console/Optimize/config.php
<ide>
<ide> return array_map('realpath', array(
<ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Contracts/Container/Container.php',
<del> $basePath.'/vendor/laravel/framework/src/Illuminate/Contracts/Support/RenderableInterface.php',
<del> $basePath.'/vendor/laravel/framework/src/Illuminate/Contracts/Support/ResponsePreparerInterface.php',
<add> $basePath.'/vendor/laravel/framework/src/Illuminate/Contracts/Support/Renderable.php',
<add> $basePath.'/vendor/laravel/framework/src/Illuminate/Contracts/Support/ResponsePreparer.php',
<ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Contracts/Config/Repository.php',
<ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Contracts/Url/Generator.php',
<ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Contracts/Events/Dispatcher.php',
<del> $basePath.'/vendor/laravel/framework/src/Illuminate/Contracts/Support/ArrayableInterface.php',
<del> $basePath.'/vendor/laravel/framework/src/Illuminate/Contracts/Support/JsonableInterface.php',
<add> $basePath.'/vendor/laravel/framework/src/Illuminate/Contracts/Support/Arrayable.php',
<add> $basePath.'/vendor/laravel/framework/src/Illuminate/Contracts/Support/Jsonable.php',
<ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Contracts/Cookie/Factory.php',
<ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Contracts/Cookie/QueueingFactory.php',
<ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Contracts/Encryption/Encrypter.php',
<ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Contracts/Routing/Registrar.php',
<ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Contracts/View/Factory.php',
<del> $basePath.'/vendor/laravel/framework/src/Illuminate/Contracts/Support/MessageProviderInterface.php',
<add> $basePath.'/vendor/laravel/framework/src/Illuminate/Contracts/Support/MessageProvider.php',
<ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Contracts/View/View.php',
<ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Container/Container.php',
<ide> $basePath.'/vendor/symfony/http-kernel/Symfony/Component/HttpKernel/HttpKernelInterface.php',
<ide><path>src/Illuminate/Http/JsonResponse.php
<ide> <?php namespace Illuminate\Http;
<ide>
<del>use Illuminate\Contracts\Support\JsonableInterface;
<add>use Illuminate\Contracts\Support\Jsonable;
<ide>
<ide> class JsonResponse extends \Symfony\Component\HttpFoundation\JsonResponse {
<ide>
<ide> public function getData($assoc = false, $depth = 512)
<ide> */
<ide> public function setData($data = array())
<ide> {
<del> $this->data = $data instanceof JsonableInterface
<add> $this->data = $data instanceof Jsonable
<ide> ? $data->toJson($this->jsonOptions)
<ide> : json_encode($data, $this->jsonOptions);
<ide>
<ide><path>src/Illuminate/Http/RedirectResponse.php
<ide> use Illuminate\Support\ViewErrorBag;
<ide> use Symfony\Component\HttpFoundation\Cookie;
<ide> use Illuminate\Session\Store as SessionStore;
<del>use Illuminate\Contracts\Support\MessageProviderInterface;
<add>use Illuminate\Contracts\Support\MessageProvider;
<ide>
<ide> class RedirectResponse extends \Symfony\Component\HttpFoundation\RedirectResponse {
<ide>
<ide> public function exceptInput()
<ide> /**
<ide> * Flash a container of errors to the session.
<ide> *
<del> * @param \Illuminate\Contracts\Support\MessageProviderInterface|array $provider
<add> * @param \Illuminate\Contracts\Support\MessageProvider|array $provider
<ide> * @param string $key
<ide> * @return $this
<ide> */
<ide> public function withErrors($provider, $key = 'default')
<ide> /**
<ide> * Parse the given errors into an appropriate value.
<ide> *
<del> * @param \Illuminate\Contracts\Support\MessageProviderInterface|array $provider
<add> * @param \Illuminate\Contracts\Support\MessageProvider|array $provider
<ide> * @return \Illuminate\Support\MessageBag
<ide> */
<ide> protected function parseErrors($provider)
<ide> {
<del> if ($provider instanceof MessageProviderInterface)
<add> if ($provider instanceof MessageProvider)
<ide> {
<ide> return $provider->getMessageBag();
<ide> }
<ide><path>src/Illuminate/Http/Response.php
<ide> <?php namespace Illuminate\Http;
<ide>
<ide> use ArrayObject;
<del>use Illuminate\Contracts\Support\JsonableInterface;
<del>use Illuminate\Contracts\Support\RenderableInterface;
<add>use Illuminate\Contracts\Support\Jsonable;
<add>use Illuminate\Contracts\Support\Renderable;
<ide>
<ide> class Response extends \Symfony\Component\HttpFoundation\Response {
<ide>
<ide> public function setContent($content)
<ide> $content = $this->morphToJson($content);
<ide> }
<ide>
<del> // If this content implements the "RenderableInterface", then we will call the
<add> // If this content implements the "Renderable" interface then we will call the
<ide> // render method on the object so we will avoid any "__toString" exceptions
<ide> // that might be thrown and have their errors obscured by PHP's handling.
<del> elseif ($content instanceof RenderableInterface)
<add> elseif ($content instanceof Renderable)
<ide> {
<ide> $content = $content->render();
<ide> }
<ide> public function setContent($content)
<ide> */
<ide> protected function morphToJson($content)
<ide> {
<del> if ($content instanceof JsonableInterface) return $content->toJson();
<add> if ($content instanceof Jsonable) return $content->toJson();
<ide>
<ide> return json_encode($content);
<ide> }
<ide> protected function morphToJson($content)
<ide> */
<ide> protected function shouldBeJson($content)
<ide> {
<del> return $content instanceof JsonableInterface ||
<add> return $content instanceof Jsonable ||
<ide> $content instanceof ArrayObject ||
<ide> is_array($content);
<ide> }
<ide><path>src/Illuminate/Log/Writer.php
<ide> use Monolog\Formatter\LineFormatter;
<ide> use Monolog\Handler\ErrorLogHandler;
<ide> use Monolog\Handler\RotatingFileHandler;
<add>use Illuminate\Contracts\Support\Jsonable;
<ide> use Illuminate\Contracts\Events\Dispatcher;
<add>use Illuminate\Contracts\Support\Arrayable;
<ide> use Psr\Log\LoggerInterface as PsrLoggerInterface;
<del>use Illuminate\Contracts\Support\JsonableInterface;
<del>use Illuminate\Contracts\Support\ArrayableInterface;
<ide> use Illuminate\Contracts\Logging\Log as LogContract;
<ide>
<ide> class Writer implements LogContract, PsrLoggerInterface {
<ide> protected function formatMessage($message)
<ide> {
<ide> return var_export($message, true);
<ide> }
<del> elseif ($message instanceof JsonableInterface)
<add> elseif ($message instanceof Jsonable)
<ide> {
<ide> return $message->toJson();
<ide> }
<del> elseif ($message instanceof ArrayableInterface)
<add> elseif ($message instanceof Arrayable)
<ide> {
<ide> return var_export($message->toArray(), true);
<ide> }
<ide><path>src/Illuminate/Pagination/Paginator.php
<ide> use ArrayIterator;
<ide> use IteratorAggregate;
<ide> use Illuminate\Support\Collection;
<del>use Illuminate\Contracts\Support\JsonableInterface;
<del>use Illuminate\Contracts\Support\ArrayableInterface;
<add>use Illuminate\Contracts\Support\Jsonable;
<add>use Illuminate\Contracts\Support\Arrayable;
<ide>
<del>class Paginator implements ArrayableInterface, ArrayAccess, Countable, IteratorAggregate, JsonableInterface {
<add>class Paginator implements Arrayable, ArrayAccess, Countable, IteratorAggregate, Jsonable {
<ide>
<ide> /**
<ide> * The pagination factory.
<ide><path>src/Illuminate/Support/Collection.php
<ide> use CachingIterator;
<ide> use JsonSerializable;
<ide> use IteratorAggregate;
<del>use Illuminate\Contracts\Support\JsonableInterface;
<del>use Illuminate\Contracts\Support\ArrayableInterface;
<add>use Illuminate\Contracts\Support\Jsonable;
<add>use Illuminate\Contracts\Support\Arrayable;
<ide>
<del>class Collection implements ArrayAccess, ArrayableInterface, Countable, IteratorAggregate, JsonableInterface, JsonSerializable {
<add>class Collection implements ArrayAccess, Arrayable, Countable, IteratorAggregate, Jsonable, JsonSerializable {
<ide>
<ide> /**
<ide> * The items contained in the collection.
<ide> public function contains($value)
<ide> /**
<ide> * Diff the collection with the given items.
<ide> *
<del> * @param \Illuminate\Support\Collection|\Illuminate\Contracts\Support\ArrayableInterface|array $items
<add> * @param \Illuminate\Support\Collection|\Illuminate\Contracts\Support\Arrayable|array $items
<ide> * @return static
<ide> */
<ide> public function diff($items)
<ide> public function implode($value, $glue = null)
<ide> /**
<ide> * Intersect the collection with the given items.
<ide> *
<del> * @param \Illuminate\Support\Collection|\Illuminate\Contracts\Support\ArrayableInterface|array $items
<add> * @param \Illuminate\Support\Collection|\Illuminate\Contracts\Support\Arrayable|array $items
<ide> * @return static
<ide> */
<ide> public function intersect($items)
<ide> public function map(Closure $callback)
<ide> /**
<ide> * Merge the collection with the given items.
<ide> *
<del> * @param \Illuminate\Support\Collection|\Illuminate\Contracts\Support\ArrayableInterface|array $items
<add> * @param \Illuminate\Support\Collection|\Illuminate\Contracts\Support\Arrayable|array $items
<ide> * @return static
<ide> */
<ide> public function merge($items)
<ide> public function toArray()
<ide> {
<ide> return array_map(function($value)
<ide> {
<del> return $value instanceof ArrayableInterface ? $value->toArray() : $value;
<add> return $value instanceof Arrayable ? $value->toArray() : $value;
<ide>
<ide> }, $this->items);
<ide> }
<ide> public function __toString()
<ide> }
<ide>
<ide> /**
<del> * Results array of items from Collection or ArrayableInterface.
<add> * Results array of items from Collection or Arrayable.
<ide> *
<del> * @param \Illuminate\Support\Collection|\Illuminate\Contracts\Support\ArrayableInterface|array $items
<add> * @param \Illuminate\Support\Collection|\Illuminate\Contracts\Support\Arrayable|array $items
<ide> * @return array
<ide> */
<ide> protected function getArrayableItems($items)
<ide> protected function getArrayableItems($items)
<ide> {
<ide> $items = $items->all();
<ide> }
<del> elseif ($items instanceof ArrayableInterface)
<add> elseif ($items instanceof Arrayable)
<ide> {
<ide> $items = $items->toArray();
<ide> }
<ide><path>src/Illuminate/Support/Facades/Response.php
<ide>
<ide> use Illuminate\Support\Str;
<ide> use Illuminate\Http\JsonResponse;
<add>use Illuminate\Contracts\Support\Arrayable;
<ide> use Illuminate\Support\Traits\MacroableTrait;
<ide> use Illuminate\Http\Response as IlluminateResponse;
<del>use Illuminate\Contracts\Support\ArrayableInterface;
<ide> use Symfony\Component\HttpFoundation\StreamedResponse;
<ide> use Symfony\Component\HttpFoundation\BinaryFileResponse;
<ide>
<ide> public static function view($view, $data = array(), $status = 200, array $header
<ide> */
<ide> public static function json($data = array(), $status = 200, array $headers = array(), $options = 0)
<ide> {
<del> if ($data instanceof ArrayableInterface)
<add> if ($data instanceof Arrayable)
<ide> {
<ide> $data = $data->toArray();
<ide> }
<ide><path>src/Illuminate/Support/Fluent.php
<ide>
<ide> use ArrayAccess;
<ide> use JsonSerializable;
<del>use Illuminate\Contracts\Support\JsonableInterface;
<del>use Illuminate\Contracts\Support\ArrayableInterface;
<add>use Illuminate\Contracts\Support\Jsonable;
<add>use Illuminate\Contracts\Support\Arrayable;
<ide>
<del>class Fluent implements ArrayAccess, ArrayableInterface, JsonableInterface, JsonSerializable {
<add>class Fluent implements ArrayAccess, Arrayable, Jsonable, JsonSerializable {
<ide>
<ide> /**
<ide> * All of the attributes set on the container.
<ide><path>src/Illuminate/Support/MessageBag.php
<ide>
<ide> use Countable;
<ide> use JsonSerializable;
<del>use Illuminate\Contracts\Support\JsonableInterface;
<del>use Illuminate\Contracts\Support\ArrayableInterface;
<del>use Illuminate\Contracts\Support\MessageProviderInterface;
<add>use Illuminate\Contracts\Support\Jsonable;
<add>use Illuminate\Contracts\Support\Arrayable;
<add>use Illuminate\Contracts\Support\MessageProvider;
<ide>
<del>class MessageBag implements ArrayableInterface, Countable, JsonableInterface, MessageProviderInterface, JsonSerializable {
<add>class MessageBag implements Arrayable, Countable, Jsonable, MessageProvider, JsonSerializable {
<ide>
<ide> /**
<ide> * All of the registered messages.
<ide> public function add($key, $message)
<ide> /**
<ide> * Merge a new array of messages into the bag.
<ide> *
<del> * @param \Illuminate\Contracts\Support\MessageProviderInterface|array $messages
<add> * @param \Illuminate\Contracts\Support\MessageProvider|array $messages
<ide> * @return $this
<ide> */
<ide> public function merge($messages)
<ide> {
<del> if ($messages instanceof MessageProviderInterface)
<add> if ($messages instanceof MessageProvider)
<ide> {
<ide> $messages = $messages->getMessageBag()->getMessages();
<ide> }
<ide><path>src/Illuminate/Validation/Validator.php
<ide> use Illuminate\Support\MessageBag;
<ide> use Illuminate\Container\Container;
<ide> use Symfony\Component\HttpFoundation\File\File;
<add>use Illuminate\Contracts\Support\MessageProvider;
<ide> use Symfony\Component\Translation\TranslatorInterface;
<ide> use Symfony\Component\HttpFoundation\File\UploadedFile;
<del>use Illuminate\Contracts\Support\MessageProviderInterface;
<ide>
<del>class Validator implements MessageProviderInterface {
<add>class Validator implements MessageProvider {
<ide>
<ide> /**
<ide> * The Translator implementation.
<ide><path>src/Illuminate/View/Factory.php
<ide>
<ide> use Closure;
<ide> use Illuminate\Container\Container;
<add>use Illuminate\Contracts\Support\Arrayable;
<ide> use Illuminate\View\Engines\EngineResolver;
<ide> use Illuminate\Contracts\Events\Dispatcher;
<ide> use Illuminate\Contracts\View\Factory as FactoryContract;
<del>use Illuminate\Contracts\Support\ArrayableInterface as Arrayable;
<ide>
<ide> class Factory implements FactoryContract {
<ide>
<ide><path>src/Illuminate/View/View.php
<ide> use Closure;
<ide> use ArrayAccess;
<ide> use Illuminate\Support\MessageBag;
<add>use Illuminate\Contracts\Support\Arrayable;
<ide> use Illuminate\View\Engines\EngineInterface;
<add>use Illuminate\Contracts\Support\Renderable;
<add>use Illuminate\Contracts\Support\MessageProvider;
<ide> use Illuminate\Contracts\View\View as ViewContract;
<del>use Illuminate\Contracts\Support\RenderableInterface;
<del>use Illuminate\Contracts\Support\MessageProviderInterface;
<del>use Illuminate\Contracts\Support\ArrayableInterface as Arrayable;
<ide>
<ide> class View implements ArrayAccess, ViewContract {
<ide>
<ide> protected function gatherData()
<ide>
<ide> foreach ($data as $key => $value)
<ide> {
<del> if ($value instanceof RenderableInterface)
<add> if ($value instanceof Renderable)
<ide> {
<ide> $data[$key] = $value->render();
<ide> }
<ide> public function nest($key, $view, array $data = array())
<ide> /**
<ide> * Add validation errors to the view.
<ide> *
<del> * @param \Illuminate\Contracts\Support\MessageProviderInterface|array $provider
<add> * @param \Illuminate\Contracts\Support\MessageProvider|array $provider
<ide> * @return $this
<ide> */
<ide> public function withErrors($provider)
<ide> {
<del> if ($provider instanceof MessageProviderInterface)
<add> if ($provider instanceof MessageProvider)
<ide> {
<ide> $this->with('errors', $provider->getMessageBag());
<ide> }
<ide><path>tests/Exception/HandlerTest.php
<ide> class HandlerTest extends PHPUnit_Framework_TestCase
<ide> {
<ide> protected function setUp()
<ide> {
<del> $this->responsePreparer = m::mock('Illuminate\Contracts\Support\ResponsePreparerInterface');
<add> $this->responsePreparer = m::mock('Illuminate\Contracts\Support\ResponsePreparer');
<ide> $this->plainDisplayer = m::mock('Illuminate\Exception\ExceptionDisplayerInterface');
<ide> $this->debugDisplayer = m::mock('Illuminate\Exception\ExceptionDisplayerInterface');
<ide> $this->handler = new Handler($this->responsePreparer, $this->plainDisplayer, $this->debugDisplayer);
<ide><path>tests/Http/HttpResponseTest.php
<ide> use Mockery as m;
<ide> use Illuminate\Http\Request;
<ide> use Illuminate\Http\RedirectResponse;
<del>use Illuminate\Contracts\Support\JsonableInterface;
<add>use Illuminate\Contracts\Support\Jsonable;
<ide>
<ide> class HttpResponseTest extends PHPUnit_Framework_TestCase {
<ide>
<ide> public function testJsonResponsesAreConvertedAndHeadersAreSet()
<ide>
<ide> public function testRenderablesAreRendered()
<ide> {
<del> $mock = m::mock('Illuminate\Contracts\Support\RenderableInterface');
<add> $mock = m::mock('Illuminate\Contracts\Support\Renderable');
<ide> $mock->shouldReceive('render')->once()->andReturn('foo');
<ide> $response = new Illuminate\Http\Response($mock);
<ide> $this->assertEquals('foo', $response->getContent());
<ide> public function testFlashingErrorsOnRedirect()
<ide> $response->setSession($session = m::mock('Illuminate\Session\Store'));
<ide> $session->shouldReceive('get')->with('errors', m::type('Illuminate\Support\ViewErrorBag'))->andReturn(new Illuminate\Support\ViewErrorBag);
<ide> $session->shouldReceive('flash')->once()->with('errors', m::type('Illuminate\Support\ViewErrorBag'));
<del> $provider = m::mock('Illuminate\Contracts\Support\MessageProviderInterface');
<add> $provider = m::mock('Illuminate\Contracts\Support\MessageProvider');
<ide> $provider->shouldReceive('getMessageBag')->once()->andReturn(new Illuminate\Support\MessageBag);
<ide> $response->withErrors($provider);
<ide> }
<ide> public function testMagicCallException()
<ide>
<ide> }
<ide>
<del>class JsonableStub implements JsonableInterface {
<add>class JsonableStub implements Jsonable {
<ide> public function toJson($options = 0) { return 'foo'; }
<ide> }
<ide><path>tests/Support/SupportCollectionTest.php
<ide> public function testEmptyCollectionIsEmpty()
<ide>
<ide> public function testToArrayCallsToArrayOnEachItemInCollection()
<ide> {
<del> $item1 = m::mock('Illuminate\Contracts\Support\ArrayableInterface');
<add> $item1 = m::mock('Illuminate\Contracts\Support\Arrayable');
<ide> $item1->shouldReceive('toArray')->once()->andReturn('foo.array');
<del> $item2 = m::mock('Illuminate\Contracts\Support\ArrayableInterface');
<add> $item2 = m::mock('Illuminate\Contracts\Support\Arrayable');
<ide> $item2->shouldReceive('toArray')->once()->andReturn('bar.array');
<ide> $c = new Collection(array($item1, $item2));
<ide> $results = $c->toArray();
<ide><path>tests/Support/SupportFacadeResponseTest.php
<ide> public function tearDown()
<ide>
<ide> public function testArrayableSendAsJson()
<ide> {
<del> $data = m::mock('Illuminate\Contracts\Support\ArrayableInterface');
<add> $data = m::mock('Illuminate\Contracts\Support\Arrayable');
<ide> $data->shouldReceive('toArray')->andReturn(array('foo' => 'bar'));
<ide>
<ide> $response = Response::json($data);
<ide><path>tests/View/ViewTest.php
<ide>
<ide> use Mockery as m;
<ide> use Illuminate\View\View;
<del>use Illuminate\Contracts\Support\ArrayableInterface;
<add>use Illuminate\Contracts\Support\Arrayable;
<ide>
<ide> class ViewTest extends PHPUnit_Framework_TestCase {
<ide>
<ide> public function testViewNestBindsASubView()
<ide>
<ide> public function testViewAcceptsArrayableImplementations()
<ide> {
<del> $arrayable = m::mock('Illuminate\Contracts\Support\ArrayableInterface');
<add> $arrayable = m::mock('Illuminate\Contracts\Support\Arrayable');
<ide> $arrayable->shouldReceive('toArray')->once()->andReturn(array('foo' => 'bar', 'baz' => array('qux', 'corge')));
<ide>
<ide> $view = new View(
<ide> public function testViewGatherDataWithRenderable()
<ide> $view->getFactory()->shouldReceive('decrementRender')->once()->ordered();
<ide> $view->getFactory()->shouldReceive('flushSectionsIfDoneRendering')->once();
<ide>
<del> $view->renderable = m::mock('Illuminate\Contracts\Support\RenderableInterface');
<add> $view->renderable = m::mock('Illuminate\Contracts\Support\Renderable');
<ide> $view->renderable->shouldReceive('render')->once()->andReturn('text');
<ide> $view->render();
<ide> } | 27 |
Text | Text | reduce confusion about passing an object to `push` | aac4e21d46f300d8433b0bd94a7a0f51e443b7d4 | <ide><path>packages/next/README.md
<ide> function ReadMore() {
<ide> export default ReadMore
<ide> ```
<ide>
<del>This uses the same exact parameters as in the `<Link>` component.
<add>This uses the same exact parameters as [in the `<Link>` component](#with-url-object). The first parameter maps to `href` while the second parameter maps to `as` in the `<Link>` component as documented [here](#with-url-object).
<ide>
<ide> ##### Router Events
<ide> | 1 |
PHP | PHP | fix route match | e8d523cbbc1fc5270925b1532cb166ea0855b537 | <ide><path>src/Illuminate/Routing/Route.php
<ide> protected static function compileParameters($value, array $wheres = array())
<ide> {
<ide> $value = static::compileWhereParameters($value, $wheres);
<ide>
<del> return preg_replace('/\{(([\w\-]+)[^?])\}/', static::$wildcard, $value);
<add> return preg_replace('/\{([\w\-]+)\}/', static::$wildcard, $value);
<ide> }
<ide>
<ide> /** | 1 |
Go | Go | fix relative path on windows for uuid paths | 684633f734f86b6a66873b42c9356eb543e12917 | <ide><path>builder/remotecontext/lazycontext.go
<ide> import (
<ide> "io"
<ide> "os"
<ide> "path/filepath"
<add> "runtime"
<add> "strings"
<ide>
<ide> "github.com/docker/docker/builder"
<ide> "github.com/docker/docker/pkg/pools"
<ide> func (c *lazyContext) Stat(path string) (string, builder.FileInfo, error) {
<ide> return "", nil, errors.WithStack(convertPathError(err, cleanPath))
<ide> }
<ide>
<del> relPath, err := filepath.Rel(c.root, fullPath)
<add> relPath, err := rel(c.root, fullPath)
<ide> if err != nil {
<ide> return "", nil, errors.WithStack(convertPathError(err, cleanPath))
<ide> }
<ide> func (c *lazyContext) Walk(root string, walkFn builder.WalkFunc) error {
<ide> return err
<ide> }
<ide> return filepath.Walk(fullPath, func(fullPath string, fi os.FileInfo, err error) error {
<del> relPath, err := filepath.Rel(c.root, fullPath)
<add> relPath, err := rel(c.root, fullPath)
<ide> if err != nil {
<ide> return errors.WithStack(err)
<ide> }
<ide> func convertPathError(err error, cleanpath string) error {
<ide> }
<ide> return err
<ide> }
<add>
<add>func rel(basepath, targpath string) (string, error) {
<add> // filepath.Rel can't handle UUID paths in windows
<add> if runtime.GOOS == "windows" {
<add> pfx := basepath + `\`
<add> if strings.HasPrefix(targpath, pfx) {
<add> p := strings.TrimPrefix(targpath, pfx)
<add> if p == "" {
<add> p = "."
<add> }
<add> return p, nil
<add> }
<add> }
<add> return filepath.Rel(basepath, targpath)
<add>} | 1 |
Text | Text | add missing toc entry in contributing.md | 3f1cca4817653606a5d78fa3653427ffd211dd43 | <ide><path>CONTRIBUTING.md
<ide> expect throughout each step of the process.
<ide> * [Commit message guidelines](#commit-message-guidelines)
<ide> * [Step 5: Rebase](#step-5-rebase)
<ide> * [Step 6: Test](#step-6-test)
<add> * [Test Coverage](#test-coverage)
<ide> * [Step 7: Push](#step-7-push)
<ide> * [Step 8: Opening the Pull Request](#step-8-opening-the-pull-request)
<ide> * [Step 9: Discuss and Update](#step-9-discuss-and-update) | 1 |
Ruby | Ruby | remove deprecation warning | 75e3464e5868522c3c277d7008238d0d3ed93bf8 | <ide><path>activerecord/lib/active_record/fixtures.rb
<ide> def initialize(connection, name, class_name, path, config = ActiveRecord::Base)
<ide> @config = config
<ide> @model_class = nil
<ide>
<del> if class_name.is_a?(String)
<del> ActiveSupport::Deprecation.warn("The ability to pass in strings as a class name to `FixtureSet.new` will be removed in Rails 4.2. Use the class itself instead.")
<del> end
<del>
<ide> if class_name.is_a?(Class) # TODO: Should be an AR::Base type class, or any?
<ide> @model_class = class_name
<ide> else | 1 |
Javascript | Javascript | fix installation instructions | 921f80e1eabf04ecd4dcfda85e7ac801a8f17728 | <ide><path>src/ngMock/angular-mocks.js
<ide> angular.mock.$ComponentControllerProvider = ['$compileProvider', function($compi
<ide> * First, download the file:
<ide> * * [Google CDN](https://developers.google.com/speed/libraries/devguide#angularjs) e.g.
<ide> * `"//ajax.googleapis.com/ajax/libs/angularjs/X.Y.Z/"`
<del> * * [NPM](https://www.npmjs.com/) e.g. `npm install {$ doc.packageName $}@X.Y.Z`
<del> * * [Bower](http://bower.io) e.g. `bower install {$ doc.packageName $}@X.Y.Z`
<add> * * [NPM](https://www.npmjs.com/) e.g. `npm install angular-mocks@X.Y.Z`
<add> * * [Bower](http://bower.io) e.g. `bower install angular-mocks@X.Y.Z`
<ide> * * [code.angularjs.org](https://code.angularjs.org/) (discouraged for production use) e.g.
<del> * `"//code.angularjs.org/X.Y.Z/{$ doc.packageFile $}"`
<add> * `"//code.angularjs.org/X.Y.Z/angular-mocks.js"`
<ide> *
<ide> * where X.Y.Z is the AngularJS version you are running.
<ide> * | 1 |
Go | Go | create a copy of dockerinit | 110c4f20434af89d81580670f2cec25b1e82633a | <ide><path>runtime.go
<ide> type Capabilities struct {
<ide>
<ide> type Runtime struct {
<ide> repository string
<add> sysInitPath string
<ide> containers *list.List
<ide> networkManager *NetworkManager
<ide> graph *Graph
<ide> func (runtime *Runtime) Create(config *Config, name string) (*Container, []strin
<ide> return nil, nil, fmt.Errorf("No command specified")
<ide> }
<ide>
<del> sysInitPath := utils.DockerInitPath()
<del> if sysInitPath == "" {
<del> return nil, nil, fmt.Errorf("Could not locate dockerinit: This usually means docker was built incorrectly. See http://docs.docker.io/en/latest/contributing/devenvironment for official build instructions.")
<del> }
<del>
<ide> // Generate id
<ide> id := GenerateID()
<ide>
<ide> func (runtime *Runtime) Create(config *Config, name string) (*Container, []strin
<ide> Image: img.ID, // Always use the resolved image id
<ide> NetworkSettings: &NetworkSettings{},
<ide> // FIXME: do we need to store this in the container?
<del> SysInitPath: sysInitPath,
<add> SysInitPath: runtime.sysInitPath,
<ide> Name: name,
<ide> Driver: runtime.driver.String(),
<ide> }
<ide> func NewRuntimeFromDirectory(config *DaemonConfig) (*Runtime, error) {
<ide> return nil, err
<ide> }
<ide>
<add> localCopy := path.Join(config.Root, "init", fmt.Sprintf("dockerinit-%s", VERSION))
<add> sysInitPath := utils.DockerInitPath(localCopy)
<add> if sysInitPath == "" {
<add> return nil, fmt.Errorf("Could not locate dockerinit: This usually means docker was built incorrectly. See http://docs.docker.io/en/latest/contributing/devenvironment for official build instructions.")
<add> }
<add>
<add> if !utils.IAMSTATIC {
<add> if err := os.Mkdir(path.Join(config.Root, fmt.Sprintf("init")), 0700); err != nil && !os.IsExist(err) {
<add> return nil, err
<add> }
<add>
<add> if _, err := utils.CopyFile(sysInitPath, localCopy); err != nil {
<add> return nil, err
<add> }
<add> sysInitPath = localCopy
<add> if err := os.Chmod(sysInitPath, 0700); err != nil {
<add> return nil, err
<add> }
<add> }
<add>
<ide> runtime := &Runtime{
<ide> repository: runtimeRepo,
<ide> containers: list.New(),
<ide> func NewRuntimeFromDirectory(config *DaemonConfig) (*Runtime, error) {
<ide> config: config,
<ide> containerGraph: graph,
<ide> driver: driver,
<add> sysInitPath: sysInitPath,
<ide> }
<ide>
<ide> if err := runtime.restore(); err != nil {
<ide><path>utils/utils.go
<ide> func isValidDockerInitPath(target string, selfPath string) bool { // target and
<ide> }
<ide>
<ide> // Figure out the path of our dockerinit (which may be SelfPath())
<del>func DockerInitPath() string {
<add>func DockerInitPath(localCopy string) string {
<ide> selfPath := SelfPath()
<ide> if isValidDockerInitPath(selfPath, selfPath) {
<ide> // if we're valid, don't bother checking anything else
<ide> return selfPath
<ide> }
<ide> var possibleInits = []string{
<add> localCopy,
<ide> filepath.Join(filepath.Dir(selfPath), "dockerinit"),
<ide> // "/usr/libexec includes internal binaries that are not intended to be executed directly by users or shell scripts. Applications may use a single subdirectory under /usr/libexec."
<ide> "/usr/libexec/docker/dockerinit",
<ide> func GetCallerName(depth int) string {
<ide> callerShortName := parts[len(parts)-1]
<ide> return callerShortName
<ide> }
<add>
<add>func CopyFile(src, dst string) (int64, error) {
<add> if src == dst {
<add> return 0, nil
<add> }
<add> sf, err := os.Open(src)
<add> if err != nil {
<add> return 0, err
<add> }
<add> defer sf.Close()
<add> if err := os.Remove(dst); err != nil && !os.IsNotExist(err) {
<add> return 0, err
<add> }
<add> df, err := os.Create(dst)
<add> if err != nil {
<add> return 0, err
<add> }
<add> defer df.Close()
<add> return io.Copy(df, sf)
<add>} | 2 |
Ruby | Ruby | pass caller to deprecation warning | 29f04510e9529a7f3b1e09a6ec6e8f296e7c0993 | <ide><path>actionpack/lib/action_controller/base.rb
<ide> def url_for(options = {}, *parameters_for_method_reference) #:doc:
<ide> when Symbol
<ide> ActiveSupport::Deprecation.warn(
<ide> "You called url_for(:#{options}), which is a deprecated API call. Instead you should use the named " +
<del> "route directly, like #{options}(). Using symbols and parameters with url_for will be removed from Rails 2.0."
<add> "route directly, like #{options}(). Using symbols and parameters with url_for will be removed from Rails 2.0.",
<add> caller
<ide> )
<ide>
<ide> send(options, *parameters_for_method_reference)
<ide> def render(options = nil, deprecated_status = nil, &block) #:doc:
<ide> else
<ide> ActiveSupport::Deprecation.warn(
<ide> "You called render('#{options}'), which is a deprecated API call. Instead you use " +
<del> "render :file => #{options}. Calling render with just a string will be removed from Rails 2.0."
<add> "render :file => #{options}. Calling render with just a string will be removed from Rails 2.0.",
<add> caller
<ide> )
<ide>
<ide> return render_file(options, deprecated_status, true) | 1 |
Python | Python | add test for setdiff1d on character arrays | c7b8c2842dff3f62f1dba62cd4a3431377a68bd7 | <ide><path>numpy/lib/tests/test_arraysetops.py
<ide> def check_setdiff1d( self ):
<ide>
<ide> assert_array_equal([], setdiff1d([],[]))
<ide>
<add> def check_setdiff1d_char_array(self):
<add> a = numpy.array(['a','b','c'])
<add> b = numpy.array(['a','b','s'])
<add> assert_array_equal(setdiff1d(a,b),numpy.array(['c']))
<ide>
<ide> ##
<ide> # 03.11.2005, c | 1 |
Javascript | Javascript | change conditon style | 706a375a06e963e32b9ad86af405a5170514d3ae | <ide><path>examples/js/lines/LineSegments2.js
<ide> THREE.LineSegments2.prototype = Object.assign( Object.create( THREE.Mesh.prototy
<ide>
<ide> }
<ide>
<del> var threshold = 0;
<del> if ( 'Line2' in raycaster.params ) {
<del>
<del> threshold = raycaster.params.Line2.threshold || 0.0;
<del>
<del> }
<add> var threshold = ( raycaster.params.Line2 !== undefined ) ? raycaster.params.Line2.threshold || 0 : 0;
<ide>
<ide> var ray = raycaster.ray;
<ide> var camera = raycaster.camera;
<ide><path>examples/jsm/lines/LineSegments2.js
<ide> LineSegments2.prototype = Object.assign( Object.create( Mesh.prototype ), {
<ide>
<ide> }
<ide>
<del> var threshold = 0;
<del> if ( 'Line2' in raycaster.params ) {
<del>
<del> threshold = raycaster.params.Line2.threshold || 0.0;
<del>
<del> }
<add> var threshold = ( raycaster.params.Line2 !== undefined ) ? raycaster.params.Line2.threshold || 0 : 0;
<ide>
<ide> var ray = raycaster.ray;
<ide> var camera = raycaster.camera; | 2 |
Javascript | Javascript | add a space in <foo /> | b2cd77d2e63281e8105c57c27c72cb613d2f491e | <ide><path>src/devtools/views/utils.js
<ide> export function createRegExp(string: string): RegExp {
<ide> export function getMetaValueLabel(data: Object): string | null {
<ide> switch (data[meta.type]) {
<ide> case 'react_element':
<del> return `<${data[meta.name]}/>`;
<add> return `<${data[meta.name]} />`;
<ide> case 'function':
<ide> return `${data[meta.name] || 'fn'}()`;
<ide> case 'object': | 1 |
Text | Text | apply sentence-consistently in c++ style guide | a0df3a8b79a82ed3b34ee073c5127ee6e24b4f41 | <ide><path>doc/guides/cpp-style-guide.md
<del># C++ Style Guide
<add># C++ style guide
<ide>
<ide> See also the [C++ codebase README](../../src/README.md) for C++ idioms in the
<ide> Node.js codebase not related to stylistic issues.
<ide>
<del>## Table of Contents
<add>## Table of contents
<ide>
<del>* [Guides and References](#guides-and-references)
<add>* [Guides and references](#guides-and-references)
<ide> * [Formatting](#formatting)
<ide> * [Left-leaning (C++ style) asterisks for pointer declarations](#left-leaning-c-style-asterisks-for-pointer-declarations)
<ide> * [C++ style comments](#c-style-comments)
<ide> Node.js codebase not related to stylistic issues.
<ide> * [`snake_case_` for private class fields](#snake_case_-for-private-class-fields)
<ide> * [`snake_case` for C-like structs](#snake_case-for-c-like-structs)
<ide> * [Space after `template`](#space-after-template)
<del>* [Memory Management](#memory-management)
<add>* [Memory management](#memory-management)
<ide> * [Memory allocation](#memory-allocation)
<ide> * [Use `nullptr` instead of `NULL` or `0`](#use-nullptr-instead-of-null-or-0)
<ide> * [Use explicit pointer comparisons](#use-explicit-pointer-comparisons)
<del> * [Ownership and Smart Pointers](#ownership-and-smart-pointers)
<add> * [Ownership and smart pointers](#ownership-and-smart-pointers)
<ide> * [Avoid non-const references](#avoid-non-const-references)
<ide> * [Use AliasedBuffers to manipulate TypedArrays](#use-aliasedbuffers-to-manipulate-typedarrays)
<ide> * [Others](#others)
<ide> Node.js codebase not related to stylistic issues.
<ide> * [Avoid throwing JavaScript errors in C++ methods](#avoid-throwing-javascript-errors-in-c)
<ide> * [Avoid throwing JavaScript errors in nested C++ methods](#avoid-throwing-javascript-errors-in-nested-c-methods)
<ide>
<del>## Guides and References
<add>## Guides and references
<ide>
<ide> The Node.js C++ codebase strives to be consistent in its use of language
<ide> features and idioms, as well as have some specific guidelines for the use of
<ide> class FancyContainer {
<ide> }
<ide> ```
<ide>
<del>## Memory Management
<add>## Memory management
<ide>
<ide> ### Memory allocation
<ide>
<ide> Use explicit comparisons to `nullptr` when testing pointers, i.e.
<ide> `if (foo == nullptr)` instead of `if (foo)` and
<ide> `foo != nullptr` instead of `!foo`.
<ide>
<del>### Ownership and Smart Pointers
<add>### Ownership and smart pointers
<ide>
<ide> * [R.20][]: Use `std::unique_ptr` or `std::shared_ptr` to represent ownership
<ide> * [R.21][]: Prefer `unique_ptr` over `shared_ptr` unless you need to share | 1 |
Javascript | Javascript | use isserializationfirstnode in _rendermode test | 24070c437bcce9c8e563081b32a28ee549decf4e | <ide><path>packages/ember-application/tests/system/visit_test.js
<ide> import Application from '../../system/application';
<ide> import ApplicationInstance from '../../system/application-instance';
<ide> import Engine from '../../system/engine';
<ide> import { Route } from 'ember-routing';
<del>import { Component, helper } from 'ember-glimmer';
<add>import { Component, helper, isSerializationFirstNode } from 'ember-glimmer';
<ide> import { compile } from 'ember-template-compiler';
<ide> import { ENV } from 'ember-environment';
<ide>
<ide> moduleFor('Application - visit()', class extends ApplicationTestCase {
<ide>
<ide> return this.visit('/', bootOptions)
<ide> .then((instance) => {
<del> assert.equal(
<del> instance.rootElement.firstChild.nodeValue,
<del> '%+b:0%',
<add> assert.ok(
<add> isSerializationFirstNode(instance.rootElement.firstChild),
<ide> 'glimmer-vm comment node was not found'
<ide> );
<ide> }).then(() =>{ | 1 |
Ruby | Ruby | support stringinquirer string | 2bf0b217545527b5eb85a11e297d0ff2dfc676e3 | <ide><path>lib/arel/visitors/to_sql.rb
<ide> def visit_String o; quote(o, @last_column) end
<ide> alias :visit_Time :visit_String
<ide> alias :visit_TrueClass :visit_String
<ide> alias :visit_NilClass :visit_String
<add> alias :visit_ActiveSupport_StringInquirer :visit_String
<ide>
<ide> def quote value, column = nil
<ide> @connection.quote value, column | 1 |
PHP | PHP | add logoutcurrentdevice method | 6cd0b1bd909cd48ca40d2d8e1826364684e123ec | <ide><path>src/Illuminate/Auth/Events/CurrentDeviceLogout.php
<add><?php
<add>
<add>namespace Illuminate\Auth\Events;
<add>
<add>use Illuminate\Queue\SerializesModels;
<add>
<add>class CurrentDeviceLogout
<add>{
<add> use SerializesModels;
<add>
<add> /**
<add> * The authentication guard name.
<add> *
<add> * @var string
<add> */
<add> public $guard;
<add>
<add> /**
<add> * The authenticated user.
<add> *
<add> * @var \Illuminate\Contracts\Auth\Authenticatable
<add> */
<add> public $user;
<add>
<add> /**
<add> * Create a new event instance.
<add> *
<add> * @param string $guard
<add> * @param \Illuminate\Contracts\Auth\Authenticatable $user
<add> * @return void
<add> */
<add> public function __construct($guard, $user)
<add> {
<add> $this->user = $user;
<add> $this->guard = $guard;
<add> }
<add>}
<ide><path>src/Illuminate/Auth/SessionGuard.php
<ide> protected function cycleRememberToken(AuthenticatableContract $user)
<ide> $this->provider->updateRememberToken($user, $token);
<ide> }
<ide>
<add> /**
<add> * Log this session out for the current user.
<add> *
<add> * @return void
<add> */
<add> public function logoutCurrentDevice()
<add> {
<add> $user = $this->user();
<add>
<add> // If we have an event dispatcher instance, we can fire off the logout event
<add> // so any further processing can be done. This allows the developer to be
<add> // listening for anytime a user signs out of this application manually.
<add> $this->clearUserDataFromStorage();
<add>
<add> if (isset($this->events)) {
<add> $this->events->dispatch(new Events\CurrentDeviceLogout($this->name, $user));
<add> }
<add>
<add> // Once we have fired the logout event we will clear the users out of memory
<add> // so they are no longer available as the user is no longer considered as
<add> // being signed into this application and should not be available here.
<add> $this->user = null;
<add>
<add> $this->loggedOut = true;
<add> }
<add>
<ide> /**
<ide> * Invalidate other sessions for the current user.
<ide> *
<ide><path>tests/Auth/AuthGuardTest.php
<ide> use Symfony\Component\HttpFoundation\Request;
<ide> use Illuminate\Contracts\Auth\Authenticatable;
<ide> use Illuminate\Contracts\Encryption\Encrypter;
<add>use Illuminate\Auth\Events\CurrentDeviceLogout;
<ide> use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
<ide>
<ide> class AuthGuardTest extends TestCase
<ide> public function testLogoutDoesNotSetRememberTokenIfNotPreviouslySet()
<ide> $mock->logout();
<ide> }
<ide>
<add> public function testLogoutCurrentDeviceRemovesRememberMeCookie()
<add> {
<add> [$session, $provider, $request, $cookie] = $this->getMocks();
<add> $mock = $this->getMockBuilder(SessionGuard::class)->setMethods(['getName', 'getRecallerName', 'recaller'])->setConstructorArgs(['default', $provider, $session, $request])->getMock();
<add> $mock->setCookieJar($cookies = m::mock(CookieJar::class));
<add> $user = m::mock(Authenticatable::class);
<add> $mock->expects($this->once())->method('getName')->will($this->returnValue('foo'));
<add> $mock->expects($this->once())->method('getRecallerName')->will($this->returnValue('bar'));
<add> $mock->expects($this->once())->method('recaller')->will($this->returnValue('non-null-cookie'));
<add>
<add> $cookie = m::mock(Cookie::class);
<add> $cookies->shouldReceive('forget')->once()->with('bar')->andReturn($cookie);
<add> $cookies->shouldReceive('queue')->once()->with($cookie);
<add> $mock->getSession()->shouldReceive('remove')->once()->with('foo');
<add> $mock->setUser($user);
<add> $mock->logoutCurrentDevice();
<add> $this->assertNull($mock->getUser());
<add> }
<add>
<add> public function testLogoutCurrentDeviceDoesNotEnqueueRememberMeCookieForDeletionIfCookieDoesntExist()
<add> {
<add> [$session, $provider, $request, $cookie] = $this->getMocks();
<add> $mock = $this->getMockBuilder(SessionGuard::class)->setMethods(['getName', 'recaller'])->setConstructorArgs(['default', $provider, $session, $request])->getMock();
<add> $mock->setCookieJar($cookies = m::mock(CookieJar::class));
<add> $user = m::mock(Authenticatable::class);
<add> $user->shouldReceive('getRememberToken')->andReturn(null);
<add> $mock->expects($this->once())->method('getName')->will($this->returnValue('foo'));
<add> $mock->expects($this->once())->method('recaller')->will($this->returnValue(null));
<add>
<add> $mock->getSession()->shouldReceive('remove')->once()->with('foo');
<add> $mock->setUser($user);
<add> $mock->logoutCurrentDevice();
<add> $this->assertNull($mock->getUser());
<add> }
<add>
<add> public function testLogoutCurrentDeviceFiresLogoutEvent()
<add> {
<add> [$session, $provider, $request, $cookie] = $this->getMocks();
<add> $mock = $this->getMockBuilder(SessionGuard::class)->setMethods(['clearUserDataFromStorage'])->setConstructorArgs(['default', $provider, $session, $request])->getMock();
<add> $mock->expects($this->once())->method('clearUserDataFromStorage');
<add> $mock->setDispatcher($events = m::mock(Dispatcher::class));
<add> $user = m::mock(Authenticatable::class);
<add> $user->shouldReceive('getRememberToken')->andReturn(null);
<add> $events->shouldReceive('dispatch')->once()->with(m::type(Authenticated::class));
<add> $mock->setUser($user);
<add> $events->shouldReceive('dispatch')->once()->with(m::type(CurrentDeviceLogout::class));
<add> $mock->logoutCurrentDevice();
<add> }
<add>
<ide> public function testLoginMethodQueuesCookieWhenRemembering()
<ide> {
<ide> [$session, $provider, $request, $cookie] = $this->getMocks();
<ide><path>tests/Integration/Auth/AuthenticationTest.php
<ide> public function test_logging_in_out_via_attempt_remembering()
<ide> $this->assertNotEquals($oldToken, $user->getRememberToken());
<ide> }
<ide>
<add> public function test_logging_in_out_current_device_via_remembering()
<add> {
<add> $this->assertTrue(
<add> $this->app['auth']->attempt(['email' => 'email', 'password' => 'password'], true)
<add> );
<add> $this->assertInstanceOf(AuthenticationTestUser::class, $this->app['auth']->user());
<add> $this->assertTrue($this->app['auth']->check());
<add> $this->assertNotNull($this->app['auth']->user()->getRememberToken());
<add>
<add> $oldToken = $this->app['auth']->user()->getRememberToken();
<add> $user = $this->app['auth']->user();
<add>
<add> $this->app['auth']->logoutCurrentDevice();
<add>
<add> $this->assertNotNull($user->getRememberToken());
<add> $this->assertEquals($oldToken, $user->getRememberToken());
<add> }
<add>
<ide> public function test_auth_via_attempt_remembering()
<ide> {
<ide> $provider = new EloquentUserProvider(app('hash'), AuthenticationTestUser::class); | 4 |
Go | Go | simplify the nopwriter code | 27ee261e6048c6fa0334bcce2116610dcd04aaed | <ide><path>utils/utils.go
<ide> func SelfPath() string {
<ide> return path
<ide> }
<ide>
<del>type NopWriter struct {
<del>}
<add>type NopWriter struct{}
<ide>
<del>func (w *NopWriter) Write(buf []byte) (int, error) {
<add>func (*NopWriter) Write(buf []byte) (int, error) {
<ide> return len(buf), nil
<ide> }
<ide> | 1 |
PHP | PHP | add missing return type to manytophp | 4dd7cfce9d5dde3c7d85b72b84974192e9aff220 | <ide><path>src/Database/Type/DateTimeType.php
<ide> public function setKeepDatabaseTimezone(bool $keep)
<ide> /**
<ide> * @inheritDoc
<ide> */
<del> public function manyToPHP(array $values, array $fields, DriverInterface $driver)
<add> public function manyToPHP(array $values, array $fields, DriverInterface $driver): array
<ide> {
<ide> foreach ($fields as $field) {
<ide> if (!isset($values[$field])) { | 1 |
Text | Text | add require statement in the example | 48d2aca39b5d9a42afb2e2598e7e463406798eac | <ide><path>doc/api/v8.md
<ide> Chrome DevTools. The JSON schema is undocumented and specific to the
<ide> V8 engine, and may change from one version of V8 to the next.
<ide>
<ide> ```js
<add>// Print heap snapshot to the console
<add>const v8 = require('v8');
<ide> const stream = v8.getHeapSnapshot();
<ide> stream.pipe(process.stdout);
<ide> ``` | 1 |
Python | Python | remove default value of exponential_term | 806b3864c36e24459cb4685b400e74c5685f5674 | <ide><path>maths/bailey_borwein_plouffe.py
<ide> def _subsum(
<ide> sum = 0.0
<ide> for sum_index in range(digit_pos_to_extract + precision):
<ide> denominator = 8 * sum_index + denominator_addend
<del> exponential_term = 0.0
<ide> if sum_index < digit_pos_to_extract:
<ide> # if the exponential term is an integer and we mod it by the denominator
<ide> # before dividing, only the integer part of the sum will change; | 1 |
Javascript | Javascript | remove the line requiring events | 1cb6fe47fce9ad02622b790e398cbbd3d600ec55 | <ide><path>lib/util.js
<ide> // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
<ide> // USE OR OTHER DEALINGS IN THE SOFTWARE.
<ide>
<del>var events = require('events');
<del>
<del>
<ide> var formatRegExp = /%[sdj%]/g;
<ide> exports.format = function(f) {
<ide> if (typeof f !== 'string') { | 1 |
Text | Text | add way to compile and run c programs via cygwin | 785f22e985ad3766797e37bf14643798fa969383 | <ide><path>guide/english/c/index.md
<ide> Once you've got it compiled, run the following command:
<ide>
<ide> If everything has gone well, you should see `Hello, World!` printed to the screen.
<ide>
<add>##### Compilation and running C in Windows with Cygwin
<add>[*Cygwin*](htttp://www.cygwin.com) is a program that provides a *UNIX* environment for the Windows operating system. With *Cygwin*, one can compile and run C programs with gcc that comes with it.
<add>
<add>You do not need to specify the path (prepending the name of the C program with `./`) in Windows as you would in Linux and macOS.
<add>
<ide> #### Compilation and running C with CodeBlocks
<ide> <a href='http://www.codeblocks.org/downloads/26' target='_blank' rel='nofollow'>Codeblocks can be downloaded from here.</a>
<ide> Make a new program with `file` -> `new` -> `file`, select C/C++ source, select C as your language, and then copy over the helloworld.c code that you read through earlier. Compile and run it with `Build` -> `Build and Run`.
<ide> Make a new program with `file` -> `new` -> `file`, select C/C++ source, select C
<ide> Make a new program with `file` -> `new` -> `Source File`, then copy over the helloworld.c text that you read through earlier and then save the file with`file` -> `save As` as hello.c , and Compile and run the code with `Execute` -> `Compile & Run`.
<ide>
<ide> ## Review
<del>* `C` is the common language or *lingua franca* of programming languages; many other languages are based on `C`.
<del>* `C` was used to re-implement the Unix operating system as Linux.
<del>* `C` is useful because it's small, fast, and has access to low-level operations. Because of this, it gets used a lot in robotics, operating systems, and consumer electronics, and if you really wanted to even to generate webpages.
<del>
<del>* A `C` program has a few critical parts:
<del> * The include directive, tells the `C` preprocessor where to find additional code that will be used to compile the program.
<del> * The main function, which is where the code will first be executed and is required in order to compile.
<del> * Code within the main function will get executed, including a return statement that exits the function, ends the program and returns the value to the operating system that called it.
<del> * `C` code needs to be compiled in order to run.
<del> * `C` can be used to access specific hardware addresses and to perform type punning to match externally imposed interface requirements, with a low run-time demand on system resources.
<add>- `C` is the common language or *lingua franca* of programming languages; many other languages are based on `C`.
<add>- `C` was used to re-implement the Unix operating system as Linux.
<add>- `C` is useful because it's small, fast, and has access to low-level operations. Because of this, it gets used a lot in robotics, operating systems, and consumer electronics, and if you really wanted to even to generate webpages.
<add>
<add>- A `C` program has a few critical parts:
<add> - The include directive, tells the `C` preprocessor where to find additional code that will be used to compile the program.
<add> - The main function, which is where the code will first be executed and is required in order to compile.
<add> - Code within the main function will get executed, including a return statement that exits the function, ends the program and returns the value to the operating system that called it.
<add> - `C` code needs to be compiled in order to run.
<add> - `C` can be used to access specific hardware addresses and to perform type punning to match externally imposed interface requirements, with a low run-time demand on system resources.
<ide>
<ide> #### More information:
<ide> | 1 |
Ruby | Ruby | move defaultscope and namedscope under scoping | 2b22564c4efaa63d4bbc006762838c4025c1bdca | <ide><path>activerecord/lib/active_record.rb
<ide> module ActiveRecord
<ide> autoload :Base
<ide> autoload :Callbacks
<ide> autoload :CounterCache
<del> autoload :DefaultScope
<ide> autoload :DynamicMatchers
<ide> autoload :DynamicFinderMatch
<ide> autoload :DynamicScopeMatch
<ide> module ActiveRecord
<ide> autoload :Migration
<ide> autoload :Migrator, 'active_record/migration'
<ide> autoload :ModelSchema
<del> autoload :NamedScope
<ide> autoload :NestedAttributes
<ide> autoload :Observer
<ide> autoload :Persistence
<ide> module ConnectionAdapters
<ide> end
<ide> end
<ide>
<add> module Scoping
<add> extend ActiveSupport::Autoload
<add>
<add> eager_autoload do
<add> autoload :Named
<add> autoload :Default
<add> end
<add> end
<add>
<ide> autoload :TestCase
<ide> autoload :TestFixtures, 'active_record/fixtures'
<ide> end
<ide><path>activerecord/lib/active_record/base.rb
<ide> def to_ary # :nodoc:
<ide> extend Translation
<ide> include Inheritance
<ide> include Scoping
<del> include DefaultScope
<ide> extend DynamicMatchers
<ide> include Sanitization
<ide> include Integration
<ide> def to_ary # :nodoc:
<ide> include Locking::Optimistic, Locking::Pessimistic
<ide> include AttributeMethods
<ide> include Callbacks, ActiveModel::Observing, Timestamp
<del> include Associations, NamedScope
<add> include Associations
<ide> include IdentityMap
<ide> include ActiveModel::SecurePassword
<ide> include Explain
<ide><path>activerecord/lib/active_record/default_scope.rb
<del>require 'active_support/concern'
<del>
<del>module ActiveRecord
<del> module DefaultScope
<del> extend ActiveSupport::Concern
<del>
<del> included do
<del> # Stores the default scope for the class
<del> class_attribute :default_scopes, :instance_writer => false
<del> self.default_scopes = []
<del> end
<del>
<del> module ClassMethods
<del> # Returns a scope for this class without taking into account the default_scope.
<del> #
<del> # class Post < ActiveRecord::Base
<del> # def self.default_scope
<del> # where :published => true
<del> # end
<del> # end
<del> #
<del> # Post.all # Fires "SELECT * FROM posts WHERE published = true"
<del> # Post.unscoped.all # Fires "SELECT * FROM posts"
<del> #
<del> # This method also accepts a block meaning that all queries inside the block will
<del> # not use the default_scope:
<del> #
<del> # Post.unscoped {
<del> # Post.limit(10) # Fires "SELECT * FROM posts LIMIT 10"
<del> # }
<del> #
<del> # It is recommended to use block form of unscoped because chaining unscoped with <tt>scope</tt>
<del> # does not work. Assuming that <tt>published</tt> is a <tt>scope</tt> following two statements are same.
<del> #
<del> # Post.unscoped.published
<del> # Post.published
<del> def unscoped #:nodoc:
<del> block_given? ? relation.scoping { yield } : relation
<del> end
<del>
<del> def before_remove_const #:nodoc:
<del> self.current_scope = nil
<del> end
<del>
<del> protected
<del>
<del> # Use this macro in your model to set a default scope for all operations on
<del> # the model.
<del> #
<del> # class Article < ActiveRecord::Base
<del> # default_scope where(:published => true)
<del> # end
<del> #
<del> # Article.all # => SELECT * FROM articles WHERE published = true
<del> #
<del> # The <tt>default_scope</tt> is also applied while creating/building a record. It is not
<del> # applied while updating a record.
<del> #
<del> # Article.new.published # => true
<del> # Article.create.published # => true
<del> #
<del> # You can also use <tt>default_scope</tt> with a block, in order to have it lazily evaluated:
<del> #
<del> # class Article < ActiveRecord::Base
<del> # default_scope { where(:published_at => Time.now - 1.week) }
<del> # end
<del> #
<del> # (You can also pass any object which responds to <tt>call</tt> to the <tt>default_scope</tt>
<del> # macro, and it will be called when building the default scope.)
<del> #
<del> # If you use multiple <tt>default_scope</tt> declarations in your model then they will
<del> # be merged together:
<del> #
<del> # class Article < ActiveRecord::Base
<del> # default_scope where(:published => true)
<del> # default_scope where(:rating => 'G')
<del> # end
<del> #
<del> # Article.all # => SELECT * FROM articles WHERE published = true AND rating = 'G'
<del> #
<del> # This is also the case with inheritance and module includes where the parent or module
<del> # defines a <tt>default_scope</tt> and the child or including class defines a second one.
<del> #
<del> # If you need to do more complex things with a default scope, you can alternatively
<del> # define it as a class method:
<del> #
<del> # class Article < ActiveRecord::Base
<del> # def self.default_scope
<del> # # Should return a scope, you can call 'super' here etc.
<del> # end
<del> # end
<del> def default_scope(scope = {})
<del> scope = Proc.new if block_given?
<del> self.default_scopes = default_scopes + [scope]
<del> end
<del>
<del> def build_default_scope #:nodoc:
<del> if method(:default_scope).owner != DefaultScope::ClassMethods
<del> evaluate_default_scope { default_scope }
<del> elsif default_scopes.any?
<del> evaluate_default_scope do
<del> default_scopes.inject(relation) do |default_scope, scope|
<del> if scope.is_a?(Hash)
<del> default_scope.apply_finder_options(scope)
<del> elsif !scope.is_a?(Relation) && scope.respond_to?(:call)
<del> default_scope.merge(scope.call)
<del> else
<del> default_scope.merge(scope)
<del> end
<del> end
<del> end
<del> end
<del> end
<del>
<del> def ignore_default_scope? #:nodoc:
<del> Thread.current["#{self}_ignore_default_scope"]
<del> end
<del>
<del> def ignore_default_scope=(ignore) #:nodoc:
<del> Thread.current["#{self}_ignore_default_scope"] = ignore
<del> end
<del>
<del> # The ignore_default_scope flag is used to prevent an infinite recursion situation where
<del> # a default scope references a scope which has a default scope which references a scope...
<del> def evaluate_default_scope
<del> return if ignore_default_scope?
<del>
<del> begin
<del> self.ignore_default_scope = true
<del> yield
<del> ensure
<del> self.ignore_default_scope = false
<del> end
<del> end
<del>
<del> end
<del> end
<del>end
<ide><path>activerecord/lib/active_record/named_scope.rb
<del>require 'active_support/core_ext/array'
<del>require 'active_support/core_ext/hash/except'
<del>require 'active_support/core_ext/kernel/singleton_class'
<del>require 'active_support/core_ext/object/blank'
<del>require 'active_support/core_ext/class/attribute'
<del>
<del>module ActiveRecord
<del> # = Active Record Named \Scopes
<del> module NamedScope
<del> extend ActiveSupport::Concern
<del>
<del> module ClassMethods
<del> # Returns an anonymous \scope.
<del> #
<del> # posts = Post.scoped
<del> # posts.size # Fires "select count(*) from posts" and returns the count
<del> # posts.each {|p| puts p.name } # Fires "select * from posts" and loads post objects
<del> #
<del> # fruits = Fruit.scoped
<del> # fruits = fruits.where(:color => 'red') if options[:red_only]
<del> # fruits = fruits.limit(10) if limited?
<del> #
<del> # Anonymous \scopes tend to be useful when procedurally generating complex
<del> # queries, where passing intermediate values (\scopes) around as first-class
<del> # objects is convenient.
<del> #
<del> # You can define a \scope that applies to all finders using
<del> # ActiveRecord::Base.default_scope.
<del> def scoped(options = nil)
<del> if options
<del> scoped.apply_finder_options(options)
<del> else
<del> if current_scope
<del> current_scope.clone
<del> else
<del> scope = relation.clone
<del> scope.default_scoped = true
<del> scope
<del> end
<del> end
<del> end
<del>
<del> ##
<del> # Collects attributes from scopes that should be applied when creating
<del> # an AR instance for the particular class this is called on.
<del> def scope_attributes # :nodoc:
<del> if current_scope
<del> current_scope.scope_for_create
<del> else
<del> scope = relation.clone
<del> scope.default_scoped = true
<del> scope.scope_for_create
<del> end
<del> end
<del>
<del> ##
<del> # Are there default attributes associated with this scope?
<del> def scope_attributes? # :nodoc:
<del> current_scope || default_scopes.any?
<del> end
<del>
<del> # Adds a class method for retrieving and querying objects. A \scope represents a narrowing of a database query,
<del> # such as <tt>where(:color => :red).select('shirts.*').includes(:washing_instructions)</tt>.
<del> #
<del> # class Shirt < ActiveRecord::Base
<del> # scope :red, where(:color => 'red')
<del> # scope :dry_clean_only, joins(:washing_instructions).where('washing_instructions.dry_clean_only = ?', true)
<del> # end
<del> #
<del> # The above calls to <tt>scope</tt> define class methods Shirt.red and Shirt.dry_clean_only. Shirt.red,
<del> # in effect, represents the query <tt>Shirt.where(:color => 'red')</tt>.
<del> #
<del> # Note that this is simply 'syntactic sugar' for defining an actual class method:
<del> #
<del> # class Shirt < ActiveRecord::Base
<del> # def self.red
<del> # where(:color => 'red')
<del> # end
<del> # end
<del> #
<del> # Unlike <tt>Shirt.find(...)</tt>, however, the object returned by Shirt.red is not an Array; it
<del> # resembles the association object constructed by a <tt>has_many</tt> declaration. For instance,
<del> # you can invoke <tt>Shirt.red.first</tt>, <tt>Shirt.red.count</tt>, <tt>Shirt.red.where(:size => 'small')</tt>.
<del> # Also, just as with the association objects, named \scopes act like an Array, implementing Enumerable;
<del> # <tt>Shirt.red.each(&block)</tt>, <tt>Shirt.red.first</tt>, and <tt>Shirt.red.inject(memo, &block)</tt>
<del> # all behave as if Shirt.red really was an Array.
<del> #
<del> # These named \scopes are composable. For instance, <tt>Shirt.red.dry_clean_only</tt> will produce
<del> # all shirts that are both red and dry clean only.
<del> # Nested finds and calculations also work with these compositions: <tt>Shirt.red.dry_clean_only.count</tt>
<del> # returns the number of garments for which these criteria obtain. Similarly with
<del> # <tt>Shirt.red.dry_clean_only.average(:thread_count)</tt>.
<del> #
<del> # All \scopes are available as class methods on the ActiveRecord::Base descendant upon which
<del> # the \scopes were defined. But they are also available to <tt>has_many</tt> associations. If,
<del> #
<del> # class Person < ActiveRecord::Base
<del> # has_many :shirts
<del> # end
<del> #
<del> # then <tt>elton.shirts.red.dry_clean_only</tt> will return all of Elton's red, dry clean
<del> # only shirts.
<del> #
<del> # Named \scopes can also be procedural:
<del> #
<del> # class Shirt < ActiveRecord::Base
<del> # scope :colored, lambda { |color| where(:color => color) }
<del> # end
<del> #
<del> # In this example, <tt>Shirt.colored('puce')</tt> finds all puce shirts.
<del> #
<del> # On Ruby 1.9 you can use the 'stabby lambda' syntax:
<del> #
<del> # scope :colored, ->(color) { where(:color => color) }
<del> #
<del> # Note that scopes defined with \scope will be evaluated when they are defined, rather than
<del> # when they are used. For example, the following would be incorrect:
<del> #
<del> # class Post < ActiveRecord::Base
<del> # scope :recent, where('published_at >= ?', Time.now - 1.week)
<del> # end
<del> #
<del> # The example above would be 'frozen' to the <tt>Time.now</tt> value when the <tt>Post</tt>
<del> # class was defined, and so the resultant SQL query would always be the same. The correct
<del> # way to do this would be via a lambda, which will re-evaluate the scope each time
<del> # it is called:
<del> #
<del> # class Post < ActiveRecord::Base
<del> # scope :recent, lambda { where('published_at >= ?', Time.now - 1.week) }
<del> # end
<del> #
<del> # Named \scopes can also have extensions, just as with <tt>has_many</tt> declarations:
<del> #
<del> # class Shirt < ActiveRecord::Base
<del> # scope :red, where(:color => 'red') do
<del> # def dom_id
<del> # 'red_shirts'
<del> # end
<del> # end
<del> # end
<del> #
<del> # Scopes can also be used while creating/building a record.
<del> #
<del> # class Article < ActiveRecord::Base
<del> # scope :published, where(:published => true)
<del> # end
<del> #
<del> # Article.published.new.published # => true
<del> # Article.published.create.published # => true
<del> #
<del> # Class methods on your model are automatically available
<del> # on scopes. Assuming the following setup:
<del> #
<del> # class Article < ActiveRecord::Base
<del> # scope :published, where(:published => true)
<del> # scope :featured, where(:featured => true)
<del> #
<del> # def self.latest_article
<del> # order('published_at desc').first
<del> # end
<del> #
<del> # def self.titles
<del> # map(&:title)
<del> # end
<del> #
<del> # end
<del> #
<del> # We are able to call the methods like this:
<del> #
<del> # Article.published.featured.latest_article
<del> # Article.featured.titles
<del>
<del> def scope(name, scope_options = {})
<del> name = name.to_sym
<del> valid_scope_name?(name)
<del> extension = Module.new(&Proc.new) if block_given?
<del>
<del> scope_proc = lambda do |*args|
<del> options = scope_options.respond_to?(:call) ? scope_options.call(*args) : scope_options
<del> options = scoped.apply_finder_options(options) if options.is_a?(Hash)
<del>
<del> relation = scoped.merge(options)
<del>
<del> extension ? relation.extending(extension) : relation
<del> end
<del>
<del> singleton_class.send(:redefine_method, name, &scope_proc)
<del> end
<del>
<del> protected
<del>
<del> def valid_scope_name?(name)
<del> if respond_to?(name, true)
<del> logger.warn "Creating scope :#{name}. " \
<del> "Overwriting existing method #{self.name}.#{name}."
<del> end
<del> end
<del> end
<del> end
<del>end
<ide><path>activerecord/lib/active_record/scoping.rb
<ide> module ActiveRecord
<ide> module Scoping
<ide> extend ActiveSupport::Concern
<ide>
<add> included do
<add> include Default
<add> include Named
<add> end
<add>
<ide> module ClassMethods
<ide> # with_scope lets you apply options to inner block incrementally. It takes a hash and the keys must be
<ide> # <tt>:find</tt> or <tt>:create</tt>. <tt>:find</tt> parameter is <tt>Relation</tt> while
<ide><path>activerecord/lib/active_record/scoping/default.rb
<add>require 'active_support/concern'
<add>
<add>module ActiveRecord
<add> module Scoping
<add> module Default
<add> extend ActiveSupport::Concern
<add>
<add> included do
<add> # Stores the default scope for the class
<add> class_attribute :default_scopes, :instance_writer => false
<add> self.default_scopes = []
<add> end
<add>
<add> module ClassMethods
<add> # Returns a scope for this class without taking into account the default_scope.
<add> #
<add> # class Post < ActiveRecord::Base
<add> # def self.default_scope
<add> # where :published => true
<add> # end
<add> # end
<add> #
<add> # Post.all # Fires "SELECT * FROM posts WHERE published = true"
<add> # Post.unscoped.all # Fires "SELECT * FROM posts"
<add> #
<add> # This method also accepts a block meaning that all queries inside the block will
<add> # not use the default_scope:
<add> #
<add> # Post.unscoped {
<add> # Post.limit(10) # Fires "SELECT * FROM posts LIMIT 10"
<add> # }
<add> #
<add> # It is recommended to use block form of unscoped because chaining unscoped with <tt>scope</tt>
<add> # does not work. Assuming that <tt>published</tt> is a <tt>scope</tt> following two statements are same.
<add> #
<add> # Post.unscoped.published
<add> # Post.published
<add> def unscoped #:nodoc:
<add> block_given? ? relation.scoping { yield } : relation
<add> end
<add>
<add> def before_remove_const #:nodoc:
<add> self.current_scope = nil
<add> end
<add>
<add> protected
<add>
<add> # Use this macro in your model to set a default scope for all operations on
<add> # the model.
<add> #
<add> # class Article < ActiveRecord::Base
<add> # default_scope where(:published => true)
<add> # end
<add> #
<add> # Article.all # => SELECT * FROM articles WHERE published = true
<add> #
<add> # The <tt>default_scope</tt> is also applied while creating/building a record. It is not
<add> # applied while updating a record.
<add> #
<add> # Article.new.published # => true
<add> # Article.create.published # => true
<add> #
<add> # You can also use <tt>default_scope</tt> with a block, in order to have it lazily evaluated:
<add> #
<add> # class Article < ActiveRecord::Base
<add> # default_scope { where(:published_at => Time.now - 1.week) }
<add> # end
<add> #
<add> # (You can also pass any object which responds to <tt>call</tt> to the <tt>default_scope</tt>
<add> # macro, and it will be called when building the default scope.)
<add> #
<add> # If you use multiple <tt>default_scope</tt> declarations in your model then they will
<add> # be merged together:
<add> #
<add> # class Article < ActiveRecord::Base
<add> # default_scope where(:published => true)
<add> # default_scope where(:rating => 'G')
<add> # end
<add> #
<add> # Article.all # => SELECT * FROM articles WHERE published = true AND rating = 'G'
<add> #
<add> # This is also the case with inheritance and module includes where the parent or module
<add> # defines a <tt>default_scope</tt> and the child or including class defines a second one.
<add> #
<add> # If you need to do more complex things with a default scope, you can alternatively
<add> # define it as a class method:
<add> #
<add> # class Article < ActiveRecord::Base
<add> # def self.default_scope
<add> # # Should return a scope, you can call 'super' here etc.
<add> # end
<add> # end
<add> def default_scope(scope = {})
<add> scope = Proc.new if block_given?
<add> self.default_scopes = default_scopes + [scope]
<add> end
<add>
<add> def build_default_scope #:nodoc:
<add> if method(:default_scope).owner != ActiveRecord::Scoping::Default::ClassMethods
<add> evaluate_default_scope { default_scope }
<add> elsif default_scopes.any?
<add> evaluate_default_scope do
<add> default_scopes.inject(relation) do |default_scope, scope|
<add> if scope.is_a?(Hash)
<add> default_scope.apply_finder_options(scope)
<add> elsif !scope.is_a?(Relation) && scope.respond_to?(:call)
<add> default_scope.merge(scope.call)
<add> else
<add> default_scope.merge(scope)
<add> end
<add> end
<add> end
<add> end
<add> end
<add>
<add> def ignore_default_scope? #:nodoc:
<add> Thread.current["#{self}_ignore_default_scope"]
<add> end
<add>
<add> def ignore_default_scope=(ignore) #:nodoc:
<add> Thread.current["#{self}_ignore_default_scope"] = ignore
<add> end
<add>
<add> # The ignore_default_scope flag is used to prevent an infinite recursion situation where
<add> # a default scope references a scope which has a default scope which references a scope...
<add> def evaluate_default_scope
<add> return if ignore_default_scope?
<add>
<add> begin
<add> self.ignore_default_scope = true
<add> yield
<add> ensure
<add> self.ignore_default_scope = false
<add> end
<add> end
<add>
<add> end
<add> end
<add> end
<add>end
<ide><path>activerecord/lib/active_record/scoping/named.rb
<add>require 'active_support/core_ext/array'
<add>require 'active_support/core_ext/hash/except'
<add>require 'active_support/core_ext/kernel/singleton_class'
<add>require 'active_support/core_ext/object/blank'
<add>require 'active_support/core_ext/class/attribute'
<add>
<add>module ActiveRecord
<add> # = Active Record Named \Scopes
<add> module Scoping
<add> module Named
<add> extend ActiveSupport::Concern
<add>
<add> module ClassMethods
<add> # Returns an anonymous \scope.
<add> #
<add> # posts = Post.scoped
<add> # posts.size # Fires "select count(*) from posts" and returns the count
<add> # posts.each {|p| puts p.name } # Fires "select * from posts" and loads post objects
<add> #
<add> # fruits = Fruit.scoped
<add> # fruits = fruits.where(:color => 'red') if options[:red_only]
<add> # fruits = fruits.limit(10) if limited?
<add> #
<add> # Anonymous \scopes tend to be useful when procedurally generating complex
<add> # queries, where passing intermediate values (\scopes) around as first-class
<add> # objects is convenient.
<add> #
<add> # You can define a \scope that applies to all finders using
<add> # ActiveRecord::Base.default_scope.
<add> def scoped(options = nil)
<add> if options
<add> scoped.apply_finder_options(options)
<add> else
<add> if current_scope
<add> current_scope.clone
<add> else
<add> scope = relation.clone
<add> scope.default_scoped = true
<add> scope
<add> end
<add> end
<add> end
<add>
<add> ##
<add> # Collects attributes from scopes that should be applied when creating
<add> # an AR instance for the particular class this is called on.
<add> def scope_attributes # :nodoc:
<add> if current_scope
<add> current_scope.scope_for_create
<add> else
<add> scope = relation.clone
<add> scope.default_scoped = true
<add> scope.scope_for_create
<add> end
<add> end
<add>
<add> ##
<add> # Are there default attributes associated with this scope?
<add> def scope_attributes? # :nodoc:
<add> current_scope || default_scopes.any?
<add> end
<add>
<add> # Adds a class method for retrieving and querying objects. A \scope represents a narrowing of a database query,
<add> # such as <tt>where(:color => :red).select('shirts.*').includes(:washing_instructions)</tt>.
<add> #
<add> # class Shirt < ActiveRecord::Base
<add> # scope :red, where(:color => 'red')
<add> # scope :dry_clean_only, joins(:washing_instructions).where('washing_instructions.dry_clean_only = ?', true)
<add> # end
<add> #
<add> # The above calls to <tt>scope</tt> define class methods Shirt.red and Shirt.dry_clean_only. Shirt.red,
<add> # in effect, represents the query <tt>Shirt.where(:color => 'red')</tt>.
<add> #
<add> # Note that this is simply 'syntactic sugar' for defining an actual class method:
<add> #
<add> # class Shirt < ActiveRecord::Base
<add> # def self.red
<add> # where(:color => 'red')
<add> # end
<add> # end
<add> #
<add> # Unlike <tt>Shirt.find(...)</tt>, however, the object returned by Shirt.red is not an Array; it
<add> # resembles the association object constructed by a <tt>has_many</tt> declaration. For instance,
<add> # you can invoke <tt>Shirt.red.first</tt>, <tt>Shirt.red.count</tt>, <tt>Shirt.red.where(:size => 'small')</tt>.
<add> # Also, just as with the association objects, named \scopes act like an Array, implementing Enumerable;
<add> # <tt>Shirt.red.each(&block)</tt>, <tt>Shirt.red.first</tt>, and <tt>Shirt.red.inject(memo, &block)</tt>
<add> # all behave as if Shirt.red really was an Array.
<add> #
<add> # These named \scopes are composable. For instance, <tt>Shirt.red.dry_clean_only</tt> will produce
<add> # all shirts that are both red and dry clean only.
<add> # Nested finds and calculations also work with these compositions: <tt>Shirt.red.dry_clean_only.count</tt>
<add> # returns the number of garments for which these criteria obtain. Similarly with
<add> # <tt>Shirt.red.dry_clean_only.average(:thread_count)</tt>.
<add> #
<add> # All \scopes are available as class methods on the ActiveRecord::Base descendant upon which
<add> # the \scopes were defined. But they are also available to <tt>has_many</tt> associations. If,
<add> #
<add> # class Person < ActiveRecord::Base
<add> # has_many :shirts
<add> # end
<add> #
<add> # then <tt>elton.shirts.red.dry_clean_only</tt> will return all of Elton's red, dry clean
<add> # only shirts.
<add> #
<add> # Named \scopes can also be procedural:
<add> #
<add> # class Shirt < ActiveRecord::Base
<add> # scope :colored, lambda { |color| where(:color => color) }
<add> # end
<add> #
<add> # In this example, <tt>Shirt.colored('puce')</tt> finds all puce shirts.
<add> #
<add> # On Ruby 1.9 you can use the 'stabby lambda' syntax:
<add> #
<add> # scope :colored, ->(color) { where(:color => color) }
<add> #
<add> # Note that scopes defined with \scope will be evaluated when they are defined, rather than
<add> # when they are used. For example, the following would be incorrect:
<add> #
<add> # class Post < ActiveRecord::Base
<add> # scope :recent, where('published_at >= ?', Time.now - 1.week)
<add> # end
<add> #
<add> # The example above would be 'frozen' to the <tt>Time.now</tt> value when the <tt>Post</tt>
<add> # class was defined, and so the resultant SQL query would always be the same. The correct
<add> # way to do this would be via a lambda, which will re-evaluate the scope each time
<add> # it is called:
<add> #
<add> # class Post < ActiveRecord::Base
<add> # scope :recent, lambda { where('published_at >= ?', Time.now - 1.week) }
<add> # end
<add> #
<add> # Named \scopes can also have extensions, just as with <tt>has_many</tt> declarations:
<add> #
<add> # class Shirt < ActiveRecord::Base
<add> # scope :red, where(:color => 'red') do
<add> # def dom_id
<add> # 'red_shirts'
<add> # end
<add> # end
<add> # end
<add> #
<add> # Scopes can also be used while creating/building a record.
<add> #
<add> # class Article < ActiveRecord::Base
<add> # scope :published, where(:published => true)
<add> # end
<add> #
<add> # Article.published.new.published # => true
<add> # Article.published.create.published # => true
<add> #
<add> # Class methods on your model are automatically available
<add> # on scopes. Assuming the following setup:
<add> #
<add> # class Article < ActiveRecord::Base
<add> # scope :published, where(:published => true)
<add> # scope :featured, where(:featured => true)
<add> #
<add> # def self.latest_article
<add> # order('published_at desc').first
<add> # end
<add> #
<add> # def self.titles
<add> # map(&:title)
<add> # end
<add> #
<add> # end
<add> #
<add> # We are able to call the methods like this:
<add> #
<add> # Article.published.featured.latest_article
<add> # Article.featured.titles
<add>
<add> def scope(name, scope_options = {})
<add> name = name.to_sym
<add> valid_scope_name?(name)
<add> extension = Module.new(&Proc.new) if block_given?
<add>
<add> scope_proc = lambda do |*args|
<add> options = scope_options.respond_to?(:call) ? scope_options.call(*args) : scope_options
<add> options = scoped.apply_finder_options(options) if options.is_a?(Hash)
<add>
<add> relation = scoped.merge(options)
<add>
<add> extension ? relation.extending(extension) : relation
<add> end
<add>
<add> singleton_class.send(:redefine_method, name, &scope_proc)
<add> end
<add>
<add> protected
<add>
<add> def valid_scope_name?(name)
<add> if respond_to?(name, true)
<add> logger.warn "Creating scope :#{name}. " \
<add> "Overwriting existing method #{self.name}.#{name}."
<add> end
<add> end
<add> end
<add> end
<add> end
<add>end | 7 |
Python | Python | simplify unicode test | 05a220dd9289d9c38ac22b9ffd7ca00830033e65 | <ide><path>numpy/core/tests/test_unicode.py
<ide> from numpy.compat import unicode
<ide> from numpy.testing import assert_, assert_equal, assert_array_equal
<ide>
<del># Python 3.3+ uses a flexible string representation
<del>ucs4 = False
<del>
<ide> def buffer_length(arr):
<ide> if isinstance(arr, unicode):
<ide> arr = str(arr)
<ide> def content_check(self, ua, ua_scalar, nbytes):
<ide> # Encode to ascii and double check
<ide> assert_(ua_scalar.encode('ascii') == b'')
<ide> # Check buffer lengths for scalars
<del> if ucs4:
<del> assert_(buffer_length(ua_scalar) == 0)
<del> else:
<del> assert_(buffer_length(ua_scalar) == 0)
<add> assert_(buffer_length(ua_scalar) == 0)
<ide>
<ide> def test_zeros0D(self):
<ide> # Check creation of 0-dimensional objects
<ide> def content_check(self, ua, ua_scalar, nbytes):
<ide> assert_(ua_scalar.encode('utf-8') ==
<ide> (self.ucs_value*self.ulen).encode('utf-8'))
<ide> # Check buffer lengths for scalars
<del> if ucs4:
<del> assert_(buffer_length(ua_scalar) == 4*self.ulen)
<add> if self.ucs_value == ucs4_value:
<add> # In UCS2, the \U0010FFFF will be represented using a
<add> # surrogate *pair*
<add> assert_(buffer_length(ua_scalar) == 2*2*self.ulen)
<ide> else:
<del> if self.ucs_value == ucs4_value:
<del> # In UCS2, the \U0010FFFF will be represented using a
<del> # surrogate *pair*
<del> assert_(buffer_length(ua_scalar) == 2*2*self.ulen)
<del> else:
<del> # In UCS2, the \uFFFF will be represented using a
<del> # regular 2-byte word
<del> assert_(buffer_length(ua_scalar) == 2*self.ulen)
<add> # In UCS2, the \uFFFF will be represented using a
<add> # regular 2-byte word
<add> assert_(buffer_length(ua_scalar) == 2*self.ulen)
<ide>
<ide> def test_values0D(self):
<ide> # Check creation of 0-dimensional objects with values
<ide> def content_check(self, ua, ua_scalar, nbytes):
<ide> assert_(ua_scalar.encode('utf-8') ==
<ide> (self.ucs_value*self.ulen).encode('utf-8'))
<ide> # Check buffer lengths for scalars
<del> if ucs4:
<del> assert_(buffer_length(ua_scalar) == 4*self.ulen)
<add> if self.ucs_value == ucs4_value:
<add> # In UCS2, the \U0010FFFF will be represented using a
<add> # surrogate *pair*
<add> assert_(buffer_length(ua_scalar) == 2*2*self.ulen)
<ide> else:
<del> if self.ucs_value == ucs4_value:
<del> # In UCS2, the \U0010FFFF will be represented using a
<del> # surrogate *pair*
<del> assert_(buffer_length(ua_scalar) == 2*2*self.ulen)
<del> else:
<del> # In UCS2, the \uFFFF will be represented using a
<del> # regular 2-byte word
<del> assert_(buffer_length(ua_scalar) == 2*self.ulen)
<add> # In UCS2, the \uFFFF will be represented using a
<add> # regular 2-byte word
<add> assert_(buffer_length(ua_scalar) == 2*self.ulen)
<ide>
<ide> def test_values0D(self):
<ide> # Check assignment of 0-dimensional objects with values | 1 |
Javascript | Javascript | change assetemitted hook to include more info | ba1a3e6f261b0165ad46d6b97ce1784b72424df7 | <ide><path>lib/Compiler.js
<ide> const { makePathsRelative } = require("./util/identifier");
<ide> * @param {Compilation=} compilation
<ide> */
<ide>
<add>/**
<add> * @typedef {Object} AssetEmittedInfo
<add> * @property {Buffer} content
<add> * @property {Source} source
<add> * @property {Compilation} compilation
<add> * @property {string} outputPath
<add> * @property {string} targetPath
<add> */
<add>
<ide> /**
<ide> * @param {string[]} array an array
<ide> * @returns {boolean} true, if the array is sorted
<ide> class Compiler {
<ide> run: new AsyncSeriesHook(["compiler"]),
<ide> /** @type {AsyncSeriesHook<[Compilation]>} */
<ide> emit: new AsyncSeriesHook(["compilation"]),
<del> /** @type {AsyncSeriesHook<[string, Buffer]>} */
<del> assetEmitted: new AsyncSeriesHook(["file", "content"]),
<add> /** @type {AsyncSeriesHook<[string, AssetEmittedInfo]>} */
<add> assetEmitted: new AsyncSeriesHook(["file", "info"]),
<ide> /** @type {AsyncSeriesHook<[Compilation]>} */
<ide> afterEmit: new AsyncSeriesHook(["compilation"]),
<ide>
<ide> class Compiler {
<ide> : targetFileGeneration + 1;
<ide> cacheEntry.writtenTo.set(targetPath, newGeneration);
<ide> this._assetEmittingWrittenFiles.set(targetPath, newGeneration);
<del> this.hooks.assetEmitted.callAsync(file, content, callback);
<add> this.hooks.assetEmitted.callAsync(
<add> file,
<add> {
<add> content,
<add> source,
<add> outputPath,
<add> compilation,
<add> targetPath
<add> },
<add> callback
<add> );
<ide> });
<ide> };
<ide>
<ide><path>test/configCases/asset-emitted/normal/webpack.config.js
<add>const Compilation = require("../../../../lib/Compilation");
<add>const Source = require("webpack-sources").Source;
<add>
<ide> module.exports = {
<ide> plugins: [
<ide> compiler => {
<ide> const files = {};
<del> compiler.hooks.assetEmitted.tap("Test", (file, buffer) => {
<del> files[file] = Buffer.isBuffer(buffer);
<del> });
<add> compiler.hooks.assetEmitted.tap(
<add> "Test",
<add> (file, { content, source, outputPath, compilation, targetPath }) => {
<add> expect(Buffer.isBuffer(content)).toBe(true);
<add> expect(source).toBeInstanceOf(Source);
<add> expect(typeof outputPath).toBe("string");
<add> expect(typeof targetPath).toBe("string");
<add> expect(compilation).toBeInstanceOf(Compilation);
<add> files[file] = true;
<add> }
<add> );
<ide> compiler.hooks.afterEmit.tap("Test", () => {
<ide> expect(files).toMatchInlineSnapshot(`
<ide> Object { | 2 |
Javascript | Javascript | add mit license header | e79b945f75ae7fa0fe3858082f6b4006df19ae50 | <ide><path>Libraries/vendor/core/whatwg-fetch.js
<add>/**
<add>* Copyright (c) 2015-present, Facebook, Inc.
<add>*
<add>* This source code is licensed under the MIT license found in the
<add>* LICENSE file in the root directory of this source tree.
<add>*
<add>* @format
<add>*/
<add>
<ide> // Fork of https://github.com/github/fetch/blob/master/fetch.js that does not
<ide> // use reponseType: 'blob' by default. RN already has specific native implementations
<ide> // for different response types so there is no need to add the extra blob overhead. | 1 |
Javascript | Javascript | fix bugs in prefer-primordials linter rule | 6700b5c9e114d507f3e5425e4da3ca5724d3e23c | <ide><path>test/parallel/test-eslint-prefer-primordials.js
<ide> new RuleTester({
<ide> `,
<ide> options: [{ name: 'Function' }],
<ide> },
<add> {
<add> code: 'function identifier() {}',
<add> options: [{ name: 'identifier' }]
<add> },
<add> {
<add> code: 'function* identifier() {}',
<add> options: [{ name: 'identifier' }]
<add> },
<add> {
<add> code: 'class identifier {}',
<add> options: [{ name: 'identifier' }]
<add> },
<add> {
<add> code: 'new class { identifier(){} }',
<add> options: [{ name: 'identifier' }]
<add> },
<add> {
<add> code: 'const a = { identifier: \'4\' }',
<add> options: [{ name: 'identifier' }]
<add> },
<add> {
<add> code: 'identifier:{const a = 4}',
<add> options: [{ name: 'identifier' }]
<add> },
<add> {
<add> code: 'switch(0){case identifier:}',
<add> options: [{ name: 'identifier' }]
<add> },
<ide> ],
<ide> invalid: [
<ide> {
<ide><path>tools/eslint-rules/prefer-primordials.js
<ide> function getDestructuringAssignmentParent(scope, node) {
<ide> return declaration.defs[0].node.init;
<ide> }
<ide>
<del>const identifierSelector =
<del> '[type!=VariableDeclarator][type!=MemberExpression]>Identifier';
<add>const parentSelectors = [
<add> // We want to select identifiers that refer to other references, not the ones
<add> // that create a new reference.
<add> 'ClassDeclaration',
<add> 'FunctionDeclaration',
<add> 'LabeledStatement',
<add> 'MemberExpression',
<add> 'MethodDefinition',
<add> 'SwitchCase',
<add> 'VariableDeclarator',
<add>];
<add>const identifierSelector = parentSelectors.map((selector) => `[type!=${selector}]`).join('') + '>Identifier';
<ide>
<ide> module.exports = {
<ide> meta: {
<ide> module.exports = {
<ide> reported = new Set();
<ide> },
<ide> [identifierSelector](node) {
<add> if (node.parent.type === 'Property' && node.parent.key === node) {
<add> // If the identifier is the key for this property declaration, it
<add> // can't be referring to a primordials member.
<add> return;
<add> }
<ide> if (reported.has(node.range[0])) {
<ide> return;
<ide> } | 2 |
Go | Go | fix bug on lxc container start. fixes | 752c57ae567813f354aca66ff51d8d64100ae01b | <ide><path>daemon/execdriver/lxc/driver.go
<ide> func (d *driver) waitForStart(c *execdriver.Command, waitLock chan struct{}) (in
<ide> }
<ide>
<ide> output, err = d.getInfo(c.ID)
<del> if err != nil {
<del> output, err = d.getInfo(c.ID)
<add> if err == nil {
<add> info, err := parseLxcInfo(string(output))
<ide> if err != nil {
<ide> return -1, err
<ide> }
<del> }
<del> info, err := parseLxcInfo(string(output))
<del> if err != nil {
<del> return -1, err
<del> }
<del> if info.Running {
<del> return info.Pid, nil
<add> if info.Running {
<add> return info.Pid, nil
<add> }
<ide> }
<ide> time.Sleep(50 * time.Millisecond)
<ide> } | 1 |
Text | Text | add clairfication on nan | 4225f20c912c31ada8eb76d522ac3c16738a9e69 | <ide><path>guide/english/javascript/booleans/index.md
<ide> There are only a few values that will be coerced to false:
<ide> - false (not really coerced as it already is false)
<ide> - null
<ide> - undefined
<del>- NaN
<add>- NaN (stands for "Not a number")
<ide> - 0
<ide> - '' or "" (empty string)
<ide> | 1 |
Go | Go | add tests for long log-lines and trailing lines | ee34dd9f8a8a0246dae94385ed2ca56691085842 | <ide><path>daemon/logger/copier_test.go
<ide> import (
<ide> "fmt"
<ide> "io"
<ide> "os"
<add> "strings"
<ide> "sync"
<ide> "testing"
<ide> "time"
<ide> func (l *TestLoggerJSON) Name() string { return "json" }
<ide> func TestCopier(t *testing.T) {
<ide> stdoutLine := "Line that thinks that it is log line from docker stdout"
<ide> stderrLine := "Line that thinks that it is log line from docker stderr"
<add> stdoutTrailingLine := "stdout trailing line"
<add> stderrTrailingLine := "stderr trailing line"
<add>
<ide> var stdout bytes.Buffer
<ide> var stderr bytes.Buffer
<ide> for i := 0; i < 30; i++ {
<ide> func TestCopier(t *testing.T) {
<ide> }
<ide> }
<ide>
<add> // Test remaining lines without line-endings
<add> if _, err := stdout.WriteString(stdoutTrailingLine); err != nil {
<add> t.Fatal(err)
<add> }
<add> if _, err := stderr.WriteString(stderrTrailingLine); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> var jsonBuf bytes.Buffer
<add>
<add> jsonLog := &TestLoggerJSON{Encoder: json.NewEncoder(&jsonBuf)}
<add>
<add> c := NewCopier(
<add> map[string]io.Reader{
<add> "stdout": &stdout,
<add> "stderr": &stderr,
<add> },
<add> jsonLog)
<add> c.Run()
<add> wait := make(chan struct{})
<add> go func() {
<add> c.Wait()
<add> close(wait)
<add> }()
<add> select {
<add> case <-time.After(1 * time.Second):
<add> t.Fatal("Copier failed to do its work in 1 second")
<add> case <-wait:
<add> }
<add> dec := json.NewDecoder(&jsonBuf)
<add> for {
<add> var msg Message
<add> if err := dec.Decode(&msg); err != nil {
<add> if err == io.EOF {
<add> break
<add> }
<add> t.Fatal(err)
<add> }
<add> if msg.Source != "stdout" && msg.Source != "stderr" {
<add> t.Fatalf("Wrong Source: %q, should be %q or %q", msg.Source, "stdout", "stderr")
<add> }
<add> if msg.Source == "stdout" {
<add> if string(msg.Line) != stdoutLine && string(msg.Line) != stdoutTrailingLine {
<add> t.Fatalf("Wrong Line: %q, expected %q or %q", msg.Line, stdoutLine, stdoutTrailingLine)
<add> }
<add> }
<add> if msg.Source == "stderr" {
<add> if string(msg.Line) != stderrLine && string(msg.Line) != stderrTrailingLine {
<add> t.Fatalf("Wrong Line: %q, expected %q or %q", msg.Line, stderrLine, stderrTrailingLine)
<add> }
<add> }
<add> }
<add>}
<add>
<add>// TestCopierLongLines tests long lines without line breaks
<add>func TestCopierLongLines(t *testing.T) {
<add> // Long lines (should be split at "bufSize")
<add> const bufSize = 16 * 1024
<add> stdoutLongLine := strings.Repeat("a", bufSize)
<add> stderrLongLine := strings.Repeat("b", bufSize)
<add> stdoutTrailingLine := "stdout trailing line"
<add> stderrTrailingLine := "stderr trailing line"
<add>
<add> var stdout bytes.Buffer
<add> var stderr bytes.Buffer
<add>
<add> for i := 0; i < 3; i++ {
<add> if _, err := stdout.WriteString(stdoutLongLine); err != nil {
<add> t.Fatal(err)
<add> }
<add> if _, err := stderr.WriteString(stderrLongLine); err != nil {
<add> t.Fatal(err)
<add> }
<add> }
<add>
<add> if _, err := stdout.WriteString(stdoutTrailingLine); err != nil {
<add> t.Fatal(err)
<add> }
<add> if _, err := stderr.WriteString(stderrTrailingLine); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<ide> var jsonBuf bytes.Buffer
<ide>
<ide> jsonLog := &TestLoggerJSON{Encoder: json.NewEncoder(&jsonBuf)}
<ide> func TestCopier(t *testing.T) {
<ide> t.Fatalf("Wrong Source: %q, should be %q or %q", msg.Source, "stdout", "stderr")
<ide> }
<ide> if msg.Source == "stdout" {
<del> if string(msg.Line) != stdoutLine {
<del> t.Fatalf("Wrong Line: %q, expected %q", msg.Line, stdoutLine)
<add> if string(msg.Line) != stdoutLongLine && string(msg.Line) != stdoutTrailingLine {
<add> t.Fatalf("Wrong Line: %q, expected 'stdoutLongLine' or 'stdoutTrailingLine'", msg.Line)
<ide> }
<ide> }
<ide> if msg.Source == "stderr" {
<del> if string(msg.Line) != stderrLine {
<del> t.Fatalf("Wrong Line: %q, expected %q", msg.Line, stderrLine)
<add> if string(msg.Line) != stderrLongLine && string(msg.Line) != stderrTrailingLine {
<add> t.Fatalf("Wrong Line: %q, expected 'stderrLongLine' or 'stderrTrailingLine'", msg.Line)
<ide> }
<ide> }
<ide> } | 1 |
Text | Text | add missing instructions for lang attribute | 85b8029582ba27af6c13088d7888f3205e192347 | <ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-css-animation-by-building-a-ferris-wheel/6140c7e645d8e905819f1dd4.md
<ide> dashedName: step-1
<ide>
<ide> # --description--
<ide>
<del>Begin with the standard boilerplate. Add your `DOCTYPE` declaration, your `html` element, your `head` and `body` elements.
<add>Begin with the standard boilerplate. Add your `DOCTYPE` declaration, your `html` element with the language set to English, your `head` and `body` elements.
<ide>
<ide> Add your `meta` element for the correct `charset`, your `title` element, and a `link` element for the `./styles.css` file.
<ide>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-css-grid-by-building-a-magazine/61437d575fb98f57fa8f7f36.md
<ide> dashedName: step-1
<ide>
<ide> # --description--
<ide>
<del>Begin with your standard HTML boilerplate. Add a `DOCTYPE` declaration, an `html` element, a `head` element, and a `body` element.
<add>Begin with your standard HTML boilerplate. Add a `DOCTYPE` declaration, an `html` element specifying this page is in English, a `head` element, and a `body` element.
<ide>
<ide> Add a `<meta>` tag with the appropriate `charset` and a `<meta>` tag for mobile responsiveness within the `head` element.
<ide>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-css-transforms-by-building-a-penguin/619665c9abd72906f3ad30f9.md
<ide> dashedName: step-1
<ide>
<ide> You will be building a happy Flappy Penguin, and further exploring CSS transforms and animations in the process.
<ide>
<del>Begin with your basic HTML boilerplate. Include the `DOCTYPE` declaration, `html` element, the appropriate `meta` tags, a `head`, `body`, and `title` element. Also, link your stylesheet to the page.
<add>Begin with your basic HTML boilerplate. Include the `DOCTYPE` declaration, `html` element with a language set to English, the appropriate `meta` tags, a `head`, `body`, and `title` element. Also, link your stylesheet to the page.
<ide>
<ide> # --hints--
<ide>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-css-variables-by-building-a-city-skyline/5d822fd413a79914d39e98ca.md
<ide> dashedName: step-2
<ide>
<ide> # --description--
<ide>
<del>Add opening and closing `html` tags below the `DOCTYPE` so you have a place to start putting some code. Be sure to set the language.
<add>Add opening and closing `html` tags below the `DOCTYPE` so you have a place to start putting some code. Be sure to set the language to English.
<ide>
<ide> # --hints--
<ide>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-more-about-css-pseudo-selectors-by-building-a-balance-sheet/61fd5a93fd62bb35968adeab.md
<ide> dashedName: step-1
<ide>
<ide> # --description--
<ide>
<del>Set up your HTML with the `DOCTYPE`, `html`, `head`, and `body` elements. Give your `head` element the appropriate `meta` elements for the `charset` and `viewport`, a `title` element with an appropriate title, and a `link` element for your stylesheet.
<add>Set up your HTML with the `DOCTYPE`, `html` indicating this document is in English, `head`, and `body` elements.
<add>
<add>Give your `head` element the appropriate `meta` elements for the `charset` and `viewport`, a `title` element with an appropriate title, and a `link` element for your stylesheet.
<ide>
<ide> # --hints--
<ide>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-responsive-web-design-by-building-a-piano/612e6afc009b450a437940a1.md
<ide> dashedName: step-1
<ide>
<ide> # --description--
<ide>
<del>Begin with the basic HTML structure. Add a `DOCTYPE` declaration and `html`, `head`, `body`, and `title` elements. Set the `title` to `Piano`.
<add>Begin with the basic HTML structure. Add a `DOCTYPE` declaration and `html`, `head`, `body`, and `title` elements.
<add>
<add>Set the language of this page to English. Set the `title` to `Piano`.
<ide>
<ide> # --hints--
<ide>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-the-css-box-model-by-building-a-rothko-painting/60a3e3396c7b40068ad6996a.md
<ide> dashedName: step-1
<ide>
<ide> By now, you should be familiar with the basic elements an HTML page should have.
<ide>
<del>Set up your code with a `DOCTYPE` declaration, an `html` element, a `head` element, and a `body` element.
<add>Set up your code with a `DOCTYPE` declaration, an `html` element with the language set to English, a `head` element, and a `body` element.
<ide>
<ide> # --hints--
<ide>
<ide> Your code should have a `<!DOCTYPE html>` declaration.
<ide> assert(code.match(/<!DOCTYPE html>/i));
<ide> ```
<ide>
<del>Your code should have an `html` element.
<add>You should have an opening `<html>` tag with a `lang` attribute of `en`.
<ide>
<ide> ```js
<del>assert(document.querySelectorAll('html').length === 1);
<add>assert(code.match(/<html\s+lang\s*=\s*('|")en\1\s*>/gi));
<ide> ```
<ide>
<ide> Your code should have a `head` element within the `html` element. | 7 |
Ruby | Ruby | remove test that does not apply anymore | f4d600865c6bcb170f34d9ba5bfc8ace432fee8b | <ide><path>activerecord/test/cases/relation/merging_test.rb
<ide> def test_relation_merging_with_association
<ide> assert merged.to_sql.include?("bbq")
<ide> end
<ide>
<del> def test_merging_removes_rhs_bind_parameters
<del> left = Post.where(id: Arel::Nodes::BindParam.new('?'))
<del> column = Post.columns_hash['id']
<del> left.bind_values += [[column, 20]]
<del> right = Post.where(id: 10)
<del>
<del> merged = left.merge(right)
<del> assert_equal [], merged.bind_values
<del> end
<del>
<ide> def test_merging_keeps_lhs_bind_parameters
<ide> column = Post.columns_hash['id']
<ide> binds = [[column, 20]]
<ide>
<del> right = Post.where(id: Arel::Nodes::BindParam.new('?'))
<del> right.bind_values += binds
<add> right = Post.where(id: 20)
<ide> left = Post.where(id: 10)
<ide>
<ide> merged = left.merge(right) | 1 |
Python | Python | extend pipelines for automodel tupels | 2056f26e853574034e426d97e4f803b47f8c7159 | <ide><path>src/transformers/pipelines/__init__.py
<ide> PipelineDataFormat,
<ide> PipelineException,
<ide> get_default_model,
<del> infer_framework_from_model,
<add> infer_framework_load_model,
<ide> )
<ide> from .conversational import Conversation, ConversationalPipeline
<ide> from .feature_extraction import FeatureExtractionPipeline
<ide> SUPPORTED_TASKS = {
<ide> "feature-extraction": {
<ide> "impl": FeatureExtractionPipeline,
<del> "tf": TFAutoModel if is_tf_available() else None,
<del> "pt": AutoModel if is_torch_available() else None,
<add> "tf": (TFAutoModel,) if is_tf_available() else (),
<add> "pt": (AutoModel,) if is_torch_available() else (),
<ide> "default": {"model": {"pt": "distilbert-base-cased", "tf": "distilbert-base-cased"}},
<ide> },
<ide> "text-classification": {
<ide> "impl": TextClassificationPipeline,
<del> "tf": TFAutoModelForSequenceClassification if is_tf_available() else None,
<del> "pt": AutoModelForSequenceClassification if is_torch_available() else None,
<add> "tf": (TFAutoModelForSequenceClassification,) if is_tf_available() else (),
<add> "pt": (AutoModelForSequenceClassification,) if is_torch_available() else (),
<ide> "default": {
<ide> "model": {
<ide> "pt": "distilbert-base-uncased-finetuned-sst-2-english",
<ide> },
<ide> "token-classification": {
<ide> "impl": TokenClassificationPipeline,
<del> "tf": TFAutoModelForTokenClassification if is_tf_available() else None,
<del> "pt": AutoModelForTokenClassification if is_torch_available() else None,
<add> "tf": (TFAutoModelForTokenClassification,) if is_tf_available() else (),
<add> "pt": (AutoModelForTokenClassification,) if is_torch_available() else (),
<ide> "default": {
<ide> "model": {
<ide> "pt": "dbmdz/bert-large-cased-finetuned-conll03-english",
<ide> },
<ide> "question-answering": {
<ide> "impl": QuestionAnsweringPipeline,
<del> "tf": TFAutoModelForQuestionAnswering if is_tf_available() else None,
<del> "pt": AutoModelForQuestionAnswering if is_torch_available() else None,
<add> "tf": (TFAutoModelForQuestionAnswering,) if is_tf_available() else (),
<add> "pt": (AutoModelForQuestionAnswering,) if is_torch_available() else (),
<ide> "default": {
<ide> "model": {"pt": "distilbert-base-cased-distilled-squad", "tf": "distilbert-base-cased-distilled-squad"},
<ide> },
<ide> },
<ide> "table-question-answering": {
<ide> "impl": TableQuestionAnsweringPipeline,
<del> "pt": AutoModelForTableQuestionAnswering if is_torch_available() else None,
<del> "tf": None,
<add> "pt": (AutoModelForTableQuestionAnswering,) if is_torch_available() else (),
<add> "tf": (),
<ide> "default": {
<ide> "model": {
<ide> "pt": "google/tapas-base-finetuned-wtq",
<ide> },
<ide> "fill-mask": {
<ide> "impl": FillMaskPipeline,
<del> "tf": TFAutoModelForMaskedLM if is_tf_available() else None,
<del> "pt": AutoModelForMaskedLM if is_torch_available() else None,
<add> "tf": (TFAutoModelForMaskedLM,) if is_tf_available() else (),
<add> "pt": (AutoModelForMaskedLM,) if is_torch_available() else (),
<ide> "default": {"model": {"pt": "distilroberta-base", "tf": "distilroberta-base"}},
<ide> },
<ide> "summarization": {
<ide> "impl": SummarizationPipeline,
<del> "tf": TFAutoModelForSeq2SeqLM if is_tf_available() else None,
<del> "pt": AutoModelForSeq2SeqLM if is_torch_available() else None,
<add> "tf": (TFAutoModelForSeq2SeqLM,) if is_tf_available() else (),
<add> "pt": (AutoModelForSeq2SeqLM,) if is_torch_available() else (),
<ide> "default": {"model": {"pt": "sshleifer/distilbart-cnn-12-6", "tf": "t5-small"}},
<ide> },
<ide> # This task is a special case as it's parametrized by SRC, TGT languages.
<ide> "translation": {
<ide> "impl": TranslationPipeline,
<del> "tf": TFAutoModelForSeq2SeqLM if is_tf_available() else None,
<del> "pt": AutoModelForSeq2SeqLM if is_torch_available() else None,
<add> "tf": (TFAutoModelForSeq2SeqLM,) if is_tf_available() else (),
<add> "pt": (AutoModelForSeq2SeqLM,) if is_torch_available() else (),
<ide> "default": {
<ide> ("en", "fr"): {"model": {"pt": "t5-base", "tf": "t5-base"}},
<ide> ("en", "de"): {"model": {"pt": "t5-base", "tf": "t5-base"}},
<ide> },
<ide> "text2text-generation": {
<ide> "impl": Text2TextGenerationPipeline,
<del> "tf": TFAutoModelForSeq2SeqLM if is_tf_available() else None,
<del> "pt": AutoModelForSeq2SeqLM if is_torch_available() else None,
<add> "tf": (TFAutoModelForSeq2SeqLM,) if is_tf_available() else (),
<add> "pt": (AutoModelForSeq2SeqLM,) if is_torch_available() else (),
<ide> "default": {"model": {"pt": "t5-base", "tf": "t5-base"}},
<ide> },
<ide> "text-generation": {
<ide> "impl": TextGenerationPipeline,
<del> "tf": TFAutoModelForCausalLM if is_tf_available() else None,
<del> "pt": AutoModelForCausalLM if is_torch_available() else None,
<add> "tf": (TFAutoModelForCausalLM,) if is_tf_available() else (),
<add> "pt": (AutoModelForCausalLM,) if is_torch_available() else (),
<ide> "default": {"model": {"pt": "gpt2", "tf": "gpt2"}},
<ide> },
<ide> "zero-shot-classification": {
<ide> "impl": ZeroShotClassificationPipeline,
<del> "tf": TFAutoModelForSequenceClassification if is_tf_available() else None,
<del> "pt": AutoModelForSequenceClassification if is_torch_available() else None,
<add> "tf": (TFAutoModelForSequenceClassification,) if is_tf_available() else (),
<add> "pt": (AutoModelForSequenceClassification,) if is_torch_available() else (),
<ide> "default": {
<ide> "model": {"pt": "facebook/bart-large-mnli", "tf": "roberta-large-mnli"},
<ide> "config": {"pt": "facebook/bart-large-mnli", "tf": "roberta-large-mnli"},
<ide> },
<ide> "conversational": {
<ide> "impl": ConversationalPipeline,
<del> "tf": TFAutoModelForCausalLM if is_tf_available() else None,
<del> "pt": AutoModelForCausalLM if is_torch_available() else None,
<add> "tf": (TFAutoModelForSeq2SeqLM, TFAutoModelForCausalLM) if is_tf_available() else (),
<add> "pt": (AutoModelForSeq2SeqLM, AutoModelForCausalLM) if is_torch_available() else (),
<ide> "default": {"model": {"pt": "microsoft/DialoGPT-medium", "tf": "microsoft/DialoGPT-medium"}},
<ide> },
<ide> "image-classification": {
<ide> "impl": ImageClassificationPipeline,
<del> "tf": None,
<del> "pt": AutoModelForImageClassification if is_torch_available() else None,
<add> "tf": (),
<add> "pt": (AutoModelForImageClassification,) if is_torch_available() else (),
<ide> "default": {"model": {"pt": "google/vit-base-patch16-224"}},
<ide> },
<ide> }
<ide> def pipeline(
<ide> >>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
<ide> >>> pipeline('ner', model=model, tokenizer=tokenizer)
<ide> """
<add>
<ide> # Retrieve the task
<ide> targeted_task, task_options = check_task(task)
<add> task_class = targeted_task["impl"]
<ide>
<ide> # Use default model/config/tokenizer for the task if no model is provided
<ide> if model is None:
<ide> # At that point framework might still be undetermined
<ide> model = get_default_model(targeted_task, framework, task_options)
<ide>
<del> model_name = model if isinstance(model, str) else None
<del>
<del> # Infer the framework form the model
<del> if framework is None:
<del> framework, model = infer_framework_from_model(model, targeted_task, revision=revision, task=task)
<del>
<del> task_class, model_class = targeted_task["impl"], targeted_task[framework]
<del>
<del> # Retrieve use_auth_token and add it to model_kwargs to be used in .from_pretrained
<del> model_kwargs["use_auth_token"] = model_kwargs.get("use_auth_token", use_auth_token)
<del>
<add> # Config is the primordial information item.
<ide> # Instantiate config if needed
<ide> if isinstance(config, str):
<ide> config = AutoConfig.from_pretrained(config, revision=revision, _from_pipeline=task, **model_kwargs)
<add> elif config is None and isinstance(model, str):
<add> config = AutoConfig.from_pretrained(model, revision=revision, _from_pipeline=task, **model_kwargs)
<ide>
<del> # Instantiate model if needed
<del> if isinstance(model, str):
<del> # Handle transparent TF/PT model conversion
<del> if framework == "pt" and model.endswith(".h5"):
<del> model_kwargs["from_tf"] = True
<del> logger.warning(
<del> "Model might be a TensorFlow model (ending with `.h5`) but TensorFlow is not available. "
<del> "Trying to load the model with PyTorch."
<del> )
<del> elif framework == "tf" and model.endswith(".bin"):
<del> model_kwargs["from_pt"] = True
<del> logger.warning(
<del> "Model might be a PyTorch model (ending with `.bin`) but PyTorch is not available. "
<del> "Trying to load the model with Tensorflow."
<del> )
<add> model_name = model if isinstance(model, str) else None
<ide>
<del> if model_class is None:
<del> raise ValueError(
<del> f"Pipeline using {framework} framework, but this framework is not supported by this pipeline."
<del> )
<add> # Retrieve use_auth_token and add it to model_kwargs to be used in .from_pretrained
<add> model_kwargs["use_auth_token"] = model_kwargs.get("use_auth_token", use_auth_token)
<ide>
<del> model = model_class.from_pretrained(
<del> model, config=config, revision=revision, _from_pipeline=task, **model_kwargs
<del> )
<add> # Infer the framework from the model
<add> # Forced if framework already defined, inferred if it's None
<add> # Will load the correct model if possible
<add> model_classes = {"tf": targeted_task["tf"], "pt": targeted_task["pt"]}
<add> framework, model = infer_framework_load_model(
<add> model, model_classes=model_classes, config=config, framework=framework, revision=revision, task=task
<add> )
<ide>
<ide> model_config = model.config
<ide>
<ide><path>src/transformers/pipelines/base.py
<ide> # See the License for the specific language governing permissions and
<ide> # limitations under the License.
<ide> import csv
<add>import importlib
<ide> import json
<ide> import os
<ide> import pickle
<ide> from abc import ABC, abstractmethod
<ide> from contextlib import contextmanager
<ide> from os.path import abspath, exists
<del>from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
<add>from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union
<ide>
<ide> from ..feature_extraction_utils import PreTrainedFeatureExtractor
<ide> from ..file_utils import add_end_docstrings, is_tf_available, is_torch_available
<ide> from ..modelcard import ModelCard
<add>from ..models.auto.configuration_auto import AutoConfig
<ide> from ..tokenization_utils import PreTrainedTokenizer, TruncationStrategy
<ide> from ..utils import logging
<ide>
<ide> logger = logging.get_logger(__name__)
<ide>
<ide>
<del>def infer_framework_from_model(
<del> model, model_classes: Optional[Dict[str, type]] = None, task: Optional[str] = None, **model_kwargs
<add>def infer_framework_load_model(
<add> model,
<add> config: AutoConfig,
<add> model_classes: Optional[Dict[str, Tuple[type]]] = None,
<add> task: Optional[str] = None,
<add> framework: Optional[str] = None,
<add> **model_kwargs
<ide> ):
<ide> """
<ide> Select framework (TensorFlow or PyTorch) to use from the :obj:`model` passed. Returns a tuple (framework, model).
<ide> def infer_framework_from_model(
<ide> model (:obj:`str`, :class:`~transformers.PreTrainedModel` or :class:`~transformers.TFPreTrainedModel`):
<ide> The model to infer the framework from. If :obj:`str`, a checkpoint name. The model to infer the framewrok
<ide> from.
<add> config (:class:`~transformers.AutoConfig`):
<add> The config associated with the model to help using the correct class
<ide> model_classes (dictionary :obj:`str` to :obj:`type`, `optional`):
<ide> A mapping framework to class.
<ide> task (:obj:`str`):
<ide> def infer_framework_from_model(
<ide> )
<ide> if isinstance(model, str):
<ide> model_kwargs["_from_pipeline"] = task
<del> if is_torch_available() and not is_tf_available():
<del> model_class = model_classes.get("pt", AutoModel)
<del> model = model_class.from_pretrained(model, **model_kwargs)
<del> elif is_tf_available() and not is_torch_available():
<del> model_class = model_classes.get("tf", TFAutoModel)
<del> model = model_class.from_pretrained(model, **model_kwargs)
<del> else:
<add> class_tuple = ()
<add> look_pt = is_torch_available() and framework in {"pt", None}
<add> look_tf = is_tf_available() and framework in {"tf", None}
<add> if model_classes:
<add> if look_pt:
<add> class_tuple = class_tuple + model_classes.get("pt", (AutoModel,))
<add> if look_tf:
<add> class_tuple = class_tuple + model_classes.get("tf", (TFAutoModel,))
<add> if config.architectures:
<add> classes = []
<add> for architecture in config.architectures:
<add> transformers_module = importlib.import_module("transformers")
<add> if look_tf:
<add> _class = getattr(transformers_module, architecture, None)
<add> if _class is not None:
<add> classes.append(_class)
<add> if look_pt:
<add> _class = getattr(transformers_module, f"TF{architecture}", None)
<add> if _class is not None:
<add> classes.append(_class)
<add> class_tuple = class_tuple + tuple(classes)
<add>
<add> if len(class_tuple) == 0:
<add> raise ValueError(f"Pipeline cannot infer suitable model classes from {model}")
<add>
<add> for model_class in class_tuple:
<add> kwargs = model_kwargs.copy()
<add> if framework == "pt" and model.endswith(".h5"):
<add> kwargs["from_tf"] = True
<add> logger.warning(
<add> "Model might be a TensorFlow model (ending with `.h5`) but TensorFlow is not available. "
<add> "Trying to load the model with PyTorch."
<add> )
<add> elif framework == "tf" and model.endswith(".bin"):
<add> kwargs["from_pt"] = True
<add> logger.warning(
<add> "Model might be a PyTorch model (ending with `.bin`) but PyTorch is not available. "
<add> "Trying to load the model with Tensorflow."
<add> )
<add>
<ide> try:
<del> model_class = model_classes.get("pt", AutoModel)
<del> model = model_class.from_pretrained(model, **model_kwargs)
<del> except OSError:
<del> model_class = model_classes.get("tf", TFAutoModel)
<del> model = model_class.from_pretrained(model, **model_kwargs)
<add> model = model_class.from_pretrained(model, **kwargs)
<add> # Stop loading on the first successful load.
<add> break
<add> except (OSError, ValueError):
<add> continue
<add>
<add> if isinstance(model, str):
<add> raise ValueError(f"Could not load model {model} with any of the following classes: {class_tuple}.")
<ide>
<ide> framework = "tf" if model.__class__.__name__.startswith("TF") else "pt"
<ide> return framework, model
<ide>
<ide>
<add>def infer_framework_from_model(
<add> model,
<add> model_classes: Optional[Dict[str, Tuple[type]]] = None,
<add> task: Optional[str] = None,
<add> framework: Optional[str] = None,
<add> **model_kwargs
<add>):
<add> """
<add> Select framework (TensorFlow or PyTorch) to use from the :obj:`model` passed. Returns a tuple (framework, model).
<add>
<add> If :obj:`model` is instantiated, this function will just infer the framework from the model class. Otherwise
<add> :obj:`model` is actually a checkpoint name and this method will try to instantiate it using :obj:`model_classes`.
<add> Since we don't want to instantiate the model twice, this model is returned for use by the pipeline.
<add>
<add> If both frameworks are installed and available for :obj:`model`, PyTorch is selected.
<add>
<add> Args:
<add> model (:obj:`str`, :class:`~transformers.PreTrainedModel` or :class:`~transformers.TFPreTrainedModel`):
<add> The model to infer the framework from. If :obj:`str`, a checkpoint name. The model to infer the framewrok
<add> from.
<add> model_classes (dictionary :obj:`str` to :obj:`type`, `optional`):
<add> A mapping framework to class.
<add> task (:obj:`str`):
<add> The task defining which pipeline will be returned.
<add> model_kwargs:
<add> Additional dictionary of keyword arguments passed along to the model's :obj:`from_pretrained(...,
<add> **model_kwargs)` function.
<add>
<add> Returns:
<add> :obj:`Tuple`: A tuple framework, model.
<add> """
<add> if isinstance(model, str):
<add> config = AutoConfig.from_pretrained(model, _from_pipeline=task, **model_kwargs)
<add> else:
<add> config = model.config
<add> return infer_framework_load_model(
<add> model, config, model_classes=model_classes, _from_pipeline=task, task=task, framework=framework, **model_kwargs
<add> )
<add>
<add>
<ide> def get_framework(model, revision: Optional[str] = None):
<ide> """
<ide> Select framework (TensorFlow or PyTorch) to use.
<ide> def __init__(
<ide> ):
<ide>
<ide> if framework is None:
<del> framework, model = infer_framework_from_model(model)
<add> framework, model = infer_framework_load_model(model, config=model.config)
<ide>
<ide> self.task = task
<ide> self.model = model
<ide><path>tests/test_pipelines_conversational.py
<ide> AutoModelForCausalLM,
<ide> AutoModelForSeq2SeqLM,
<ide> AutoTokenizer,
<add> BlenderbotSmallForConditionalGeneration,
<add> BlenderbotSmallTokenizer,
<ide> Conversation,
<ide> ConversationalPipeline,
<ide> is_torch_available,
<ide> def test_integration_torch_conversation_encoder_decoder(self):
<ide> self.assertEqual(result[0].generated_responses[1], "i don't have any plans yet. i'm not sure what to do yet.")
<ide> self.assertEqual(result[1].past_user_inputs[1], "What's your name?")
<ide> self.assertEqual(result[1].generated_responses[1], "i don't have a name, but i'm going to see a horror movie.")
<add>
<add> @require_torch
<add> @slow
<add> def test_from_pipeline_conversation(self):
<add> model_id = "facebook/blenderbot_small-90M"
<add>
<add> # from model id
<add> conversation_agent_from_model_id = pipeline("conversational", model=model_id, tokenizer=model_id)
<add>
<add> # from model object
<add> model = BlenderbotSmallForConditionalGeneration.from_pretrained(model_id)
<add> tokenizer = BlenderbotSmallTokenizer.from_pretrained(model_id)
<add> conversation_agent_from_model = pipeline("conversational", model=model, tokenizer=tokenizer)
<add>
<add> conversation = Conversation("My name is Sarah and I live in London")
<add> conversation_copy = Conversation("My name is Sarah and I live in London")
<add>
<add> result_model_id = conversation_agent_from_model_id([conversation])
<add> result_model = conversation_agent_from_model([conversation_copy])
<add>
<add> # check for equality
<add> self.assertEqual(
<add> result_model_id.generated_responses[0],
<add> "hi sarah, i live in london as well. do you have any plans for the weekend?",
<add> )
<add> self.assertEqual(
<add> result_model_id.generated_responses[0],
<add> result_model.generated_responses[0],
<add> ) | 3 |
Ruby | Ruby | handle failing devel requirements | ec852045b14029557e6d27d91e5eab8167803397 | <ide><path>Library/Contributions/cmd/brew-test-bot.rb
<ide> def skip formula
<ide> puts "#{Tty.blue}==>#{Tty.white} SKIPPING: #{formula}#{Tty.reset}"
<ide> end
<ide>
<add> def satisfied_requirements? formula_object, spec=:stable
<add> requirements = if spec == :stable
<add> formula_object.recursive_requirements
<add> else
<add> formula_object.send(spec).requirements
<add> end
<add>
<add> unsatisfied_requirements = requirements.reject do |requirement|
<add> requirement.satisfied? || requirement.default_formula?
<add> end
<add>
<add> if unsatisfied_requirements.empty?
<add> true
<add> else
<add> formula = formula_object.name
<add> formula += " (#{spec})" unless spec == :stable
<add> skip formula
<add> unsatisfied_requirements.each {|r| puts r.message}
<add> false
<add> end
<add> end
<add>
<ide> def setup
<ide> @category = __method__
<ide> return if ARGV.include? "--skip-setup"
<ide> def formula formula
<ide> dependencies -= `brew list`.split("\n")
<ide> dependencies = dependencies.join(' ')
<ide> formula_object = Formula.factory(formula)
<del> requirements = formula_object.recursive_requirements
<del> unsatisfied_requirements = requirements.reject {|r| r.satisfied? or r.default_formula?}
<del> unless unsatisfied_requirements.empty?
<del> skip formula
<del> unsatisfied_requirements.each {|r| puts r.message}
<del> return
<del> end
<add> return unless satisfied_requirements? formula_object
<ide>
<ide> installed_gcc = false
<ide> begin
<ide> def formula formula
<ide> test "brew test --verbose #{formula}" if formula_object.test_defined?
<ide> test "brew uninstall --force #{formula}"
<ide> end
<del> if formula_object.devel and not ARGV.include? '--HEAD'
<add>
<add> if formula_object.devel && !ARGV.include?('--HEAD') \
<add> && satisfied_requirements?(formula_object, :devel)
<ide> test "brew fetch --retry --devel#{formula_fetch_options} #{formula}"
<ide> test "brew install --devel --verbose #{formula}"
<ide> devel_install_passed = steps.last.passed? | 1 |
PHP | PHP | fix sortby bug | 307f6fb8d9579427a9521a07e8700355a3e9d948 | <ide><path>src/Illuminate/Collections/Collection.php
<ide> public function sortDesc($options = SORT_REGULAR)
<ide> */
<ide> public function sortBy($callback, $options = SORT_REGULAR, $descending = false)
<ide> {
<del> if (is_array($callback)) {
<add> if (is_array($callback) && ! is_callable($callback)) {
<ide> return $this->sortByMany($callback);
<ide> }
<ide> | 1 |
Javascript | Javascript | add flow-typing to messagequeue | acdd08aef725e283cf290b4785205a7dfb181ad2 | <ide><path>Libraries/Utilities/MessageQueue.js
<ide> * of patent rights can be found in the PATENTS file in the same directory.
<ide> *
<ide> * @providesModule MessageQueue
<add> * @flow
<ide> */
<ide>
<ide> /*eslint no-bitwise: 0*/
<ide>
<ide> 'use strict';
<ide>
<del>const Systrace = require('Systrace');
<ide> const ErrorUtils = require('ErrorUtils');
<ide> const JSTimersExecution = require('JSTimersExecution');
<add>const Systrace = require('Systrace');
<ide>
<del>const invariant = require('fbjs/lib/invariant');
<del>const keyMirror = require('fbjs/lib/keyMirror');
<ide> const deepFreezeAndThrowOnMutationInDev = require('deepFreezeAndThrowOnMutationInDev');
<add>const defineLazyObjectProperty = require('defineLazyObjectProperty');
<add>const invariant = require('fbjs/lib/invariant');
<ide> const stringifySafe = require('stringifySafe');
<ide>
<add>export type ConfigProvider = () => {
<add> remoteModuleConfig: Array<ModuleConfig>,
<add>};
<add>export type MethodType = 'async' | 'promise' | 'sync';
<add>export type ModuleConfig = [
<add> string, /* name */
<add> ?Object, /* constants */
<add> Array<string>, /* functions */
<add> Array<number>, /* promise method IDs */
<add> Array<number>, /* sync method IDs */
<add>];
<add>export type SpyData = {
<add> type: number,
<add> module: ?string,
<add> method: string|number,
<add> args: any
<add>}
<add>
<add>const TO_JS = 0;
<add>const TO_NATIVE = 1;
<add>
<ide> const MODULE_IDS = 0;
<ide> const METHOD_IDS = 1;
<ide> const PARAMS = 2;
<ide> const MIN_TIME_BETWEEN_FLUSHES_MS = 5;
<ide>
<del>const TO_NATIVE = 1;
<del>const TO_JS = 0;
<del>
<ide> const TRACE_TAG_REACT_APPS = 1 << 17;
<ide>
<ide> const DEBUG_INFO_LIMIT = 32;
<ide>
<del>const MethodTypes = keyMirror({
<del> async: null,
<del> promise: null,
<del> sync: null,
<del>});
<del>
<ide> const guard = (fn) => {
<ide> try {
<ide> fn();
<ide> const guard = (fn) => {
<ide> }
<ide> };
<ide>
<del>type Config = {
<del> remoteModuleConfig: Object,
<del>};
<del>
<ide> class MessageQueue {
<del> constructor(configProvider: () => Config) {
<add> _callableModules: {[key: string]: Object};
<add> _queue: [Array<number>, Array<number>, Array<any>];
<add> _callbacks: [];
<add> _callbackID: number;
<add> _callID: number;
<add> _lastFlush: number;
<add> _eventLoopStartTime: number;
<add>
<add> RemoteModules: Object;
<add>
<add> _debugInfo: Object;
<add> _remoteModuleTable: Object;
<add> _remoteMethodTable: Object;
<add>
<add> __spy: ?(data: SpyData) => void;
<add>
<add> constructor(configProvider: ConfigProvider) {
<ide> this._callableModules = {};
<ide> this._queue = [[], [], [], 0];
<ide> this._callbacks = [];
<ide> class MessageQueue {
<ide> this._remoteMethodTable = {};
<ide> }
<ide>
<del> [
<del> 'invokeCallbackAndReturnFlushedQueue',
<del> 'callFunctionReturnFlushedQueue',
<del> 'callFunctionReturnResultAndFlushedQueue',
<del> 'flushedQueue',
<del> ].forEach((fn) => (this[fn] = this[fn].bind(this)));
<add> (this:any).callFunctionReturnFlushedQueue = this.callFunctionReturnFlushedQueue.bind(this);
<add> (this:any).callFunctionReturnResultAndFlushedQueue = this.callFunctionReturnResultAndFlushedQueue.bind(this);
<add> (this:any).flushedQueue = this.flushedQueue.bind(this);
<add> (this:any).invokeCallbackAndReturnFlushedQueue = this.invokeCallbackAndReturnFlushedQueue.bind(this);
<ide>
<del> lazyProperty(this, 'RemoteModules', () => {
<add> defineLazyObjectProperty(this, 'RemoteModules', {get: () => {
<ide> const {remoteModuleConfig} = configProvider();
<del> const modulesConfig = remoteModuleConfig;
<del> return this._genModules(modulesConfig);
<del> });
<add> return this._genModules(remoteModuleConfig);
<add> }});
<ide> }
<ide>
<ide> /**
<ide> * Public APIs
<ide> */
<ide>
<del> static spy(spyOrToggle){
<add> static spy(spyOrToggle: boolean|(data: SpyData) => void){
<ide> if (spyOrToggle === true){
<del> MessageQueue.prototype.__spy = (info)=>{
<add> MessageQueue.prototype.__spy = info => {
<ide> console.log(`${info.type == TO_JS ? 'N->JS' : 'JS->N'} : ` +
<ide> `${info.module ? (info.module + '.') : ''}${info.method}` +
<ide> `(${JSON.stringify(info.args)})`);
<ide> class MessageQueue {
<ide> }
<ide> }
<ide>
<del> callFunctionReturnFlushedQueue(module, method, args) {
<add> callFunctionReturnFlushedQueue(module: string, method: string, args: Array<any>) {
<ide> guard(() => {
<ide> this.__callFunction(module, method, args);
<ide> this.__callImmediates();
<ide> class MessageQueue {
<ide> return this.flushedQueue();
<ide> }
<ide>
<del> callFunctionReturnResultAndFlushedQueue(module, method, args) {
<add> callFunctionReturnResultAndFlushedQueue(module: string, method: string, args: Array<any>) {
<ide> let result;
<ide> guard(() => {
<ide> result = this.__callFunction(module, method, args);
<ide> class MessageQueue {
<ide> return [result, this.flushedQueue()];
<ide> }
<ide>
<del> invokeCallbackAndReturnFlushedQueue(cbID, args) {
<add> invokeCallbackAndReturnFlushedQueue(cbID: number, args: Array<any>) {
<ide> guard(() => {
<ide> this.__invokeCallback(cbID, args);
<ide> this.__callImmediates();
<ide> class MessageQueue {
<ide> return queue[0].length ? queue : null;
<ide> }
<ide>
<del> processModuleConfig(config, moduleID) {
<add> processModuleConfig(config: ModuleConfig, moduleID: number) {
<ide> const info = this._genModule(config, moduleID);
<add> if (!info) {
<add> return null;
<add> }
<add>
<ide> this.RemoteModules[info.name] = info.module;
<ide> if (__DEV__) {
<del> this._createDebugLookup(config, moduleID, this._remoteModuleTable, this._remoteMethodTable);
<add> this._createDebugLookup(config, moduleID);
<ide> }
<ide> return info.module;
<ide> }
<ide> class MessageQueue {
<ide> return new Date().getTime() - this._eventLoopStartTime;
<ide> }
<ide>
<del> registerCallableModule(name, methods) {
<del> this._callableModules[name] = methods;
<add> registerCallableModule(name: string, module: Object) {
<add> this._callableModules[name] = module;
<ide> }
<ide>
<ide> /**
<ide> class MessageQueue {
<ide> Systrace.endEvent();
<ide> }
<ide>
<del> __nativeCall(module, method, params, onFail, onSucc) {
<add> __nativeCall(moduleID: number, methodID: number, params: Array<any>, onFail: ?Function, onSucc: ?Function) {
<ide> if (onFail || onSucc) {
<ide> if (__DEV__) {
<ide> const callId = this._callbackID >> 1;
<del> this._debugInfo[callId] = [module, method];
<add> this._debugInfo[callId] = [moduleID, methodID];
<ide> if (callId > DEBUG_INFO_LIMIT) {
<ide> delete this._debugInfo[callId - DEBUG_INFO_LIMIT];
<ide> }
<ide> class MessageQueue {
<ide> }
<ide> this._callID++;
<ide>
<del> this._queue[MODULE_IDS].push(module);
<del> this._queue[METHOD_IDS].push(method);
<add> this._queue[MODULE_IDS].push(moduleID);
<add> this._queue[METHOD_IDS].push(methodID);
<ide>
<ide> if (__DEV__) {
<ide> // Any params sent over the bridge should be encodable as JSON
<ide> JSON.stringify(params);
<ide>
<ide> // The params object should not be mutated after being queued
<del> deepFreezeAndThrowOnMutationInDev(params);
<add> deepFreezeAndThrowOnMutationInDev((params:any));
<ide> }
<ide> this._queue[PARAMS].push(params);
<ide>
<ide> class MessageQueue {
<ide> this._lastFlush = now;
<ide> }
<ide> Systrace.counterEvent('pending_js_to_native_queue', this._queue[0].length);
<del> if (__DEV__ && this.__spy && isFinite(module)) {
<add> if (__DEV__ && this.__spy && isFinite(moduleID)) {
<ide> this.__spy(
<ide> { type: TO_NATIVE,
<del> module: this._remoteModuleTable[module],
<del> method: this._remoteMethodTable[module][method],
<add> module: this._remoteModuleTable[moduleID],
<add> method: this._remoteMethodTable[moduleID][methodID],
<ide> args: params }
<ide> );
<ide> }
<ide> }
<ide>
<del> __callFunction(module: string, method: string, args: any) {
<add> __callFunction(module: string, method: string, args: Array<any>) {
<ide> this._lastFlush = new Date().getTime();
<ide> this._eventLoopStartTime = this._lastFlush;
<ide> Systrace.beginEvent(`${module}.${method}()`);
<ide> class MessageQueue {
<ide> return result;
<ide> }
<ide>
<del> __invokeCallback(cbID, args) {
<add> __invokeCallback(cbID: number, args: Array<any>) {
<ide> this._lastFlush = new Date().getTime();
<ide> this._eventLoopStartTime = this._lastFlush;
<ide> const callback = this._callbacks[cbID];
<ide> class MessageQueue {
<ide> }
<ide>
<ide> if (__DEV__) {
<del> this._createDebugLookup(config, moduleID, this._remoteModuleTable, this._remoteMethodTable);
<add> this._createDebugLookup(config, moduleID);
<ide> }
<ide> });
<ide> return modules;
<ide> }
<ide>
<del> _genModule(config, moduleID): ?Object {
<add> _genModule(config: ModuleConfig, moduleID: number): ?{name: string, module: Object} {
<ide> if (!config) {
<ide> return null;
<ide> }
<ide> class MessageQueue {
<ide> if (moduleHasConstants(config)) {
<ide> [moduleName, constants, methods, promiseMethods, syncMethods] = config;
<ide> } else {
<del> [moduleName, methods, promiseMethods, syncMethods] = config;
<add> [moduleName, methods, promiseMethods, syncMethods] = (config:any);
<ide> }
<ide>
<ide> const module = {};
<ide> methods && methods.forEach((methodName, methodID) => {
<ide> const isPromise = promiseMethods && arrayContains(promiseMethods, methodID);
<ide> const isSync = syncMethods && arrayContains(syncMethods, methodID);
<ide> invariant(!isPromise || !isSync, 'Cannot have a method that is both async and a sync hook');
<del> const methodType = isPromise ? MethodTypes.promise :
<del> isSync ? MethodTypes.sync : MethodTypes.async;
<add> const methodType = isPromise ? 'promise' : isSync ? 'sync' : 'async';
<ide> module[methodName] = this._genMethod(moduleID, methodID, methodType);
<ide> });
<ide> Object.assign(module, constants);
<ide> class MessageQueue {
<ide> return { name: moduleName, module };
<ide> }
<ide>
<del> _genMethod(module, method, type) {
<add> _genMethod(moduleID: number, methodID: number, type: MethodType) {
<ide> let fn = null;
<ide> const self = this;
<del> if (type === MethodTypes.promise) {
<del> fn = function(...args) {
<add> if (type === 'promise') {
<add> fn = function(...args: Array<any>) {
<ide> return new Promise((resolve, reject) => {
<del> self.__nativeCall(module, method, args,
<add> self.__nativeCall(moduleID, methodID, args,
<ide> (data) => resolve(data),
<ide> (errorData) => reject(createErrorFromErrorData(errorData)));
<ide> });
<ide> };
<del> } else if (type === MethodTypes.sync) {
<del> fn = function(...args) {
<del> return global.nativeCallSyncHook(module, method, args);
<add> } else if (type === 'sync') {
<add> fn = function(...args: Array<any>) {
<add> return global.nativeCallSyncHook(moduleID, methodID, args);
<ide> };
<ide> } else {
<del> fn = function(...args) {
<add> fn = function(...args: Array<any>) {
<ide> const lastArg = args.length > 0 ? args[args.length - 1] : null;
<ide> const secondLastArg = args.length > 1 ? args[args.length - 2] : null;
<ide> const hasSuccessCallback = typeof lastArg === 'function';
<ide> class MessageQueue {
<ide> const onFail = hasErrorCallback ? secondLastArg : null;
<ide> const callbackCount = hasSuccessCallback + hasErrorCallback;
<ide> args = args.slice(0, args.length - callbackCount);
<del> return self.__nativeCall(module, method, args, onFail, onSuccess);
<add> return self.__nativeCall(moduleID, methodID, args, onFail, onSuccess);
<ide> };
<ide> }
<ide> fn.type = type;
<ide> return fn;
<ide> }
<ide>
<del> _createDebugLookup(config, moduleID, moduleTable, methodTable) {
<add> _createDebugLookup(config: ModuleConfig, moduleID: number) {
<ide> if (!config) {
<ide> return;
<ide> }
<ide> class MessageQueue {
<ide> if (moduleHasConstants(config)) {
<ide> [moduleName, , methods] = config;
<ide> } else {
<del> [moduleName, methods] = config;
<add> [moduleName, methods] = (config:any);
<ide> }
<ide>
<del> moduleTable[moduleID] = moduleName;
<del> methodTable[moduleID] = Object.assign({}, methods);
<add> this._remoteModuleTable[moduleID] = moduleName;
<add> this._remoteMethodTable[moduleID] = methods;
<ide> }
<ide> }
<ide>
<del>function moduleHasConstants(moduleArray: Array<Object|Array<>>): boolean {
<add>function moduleHasConstants(moduleArray: ModuleConfig): boolean {
<ide> return !Array.isArray(moduleArray[1]);
<ide> }
<ide>
<ide> function createErrorFromErrorData(errorData: {message: string}): Error {
<ide> ...extraErrorInfo,
<ide> } = errorData;
<ide> const error = new Error(message);
<del> error.framesToPop = 1;
<add> (error:any).framesToPop = 1;
<ide> return Object.assign(error, extraErrorInfo);
<ide> }
<ide>
<del>function lazyProperty(target: Object, name: string, f: () => any) {
<del> Object.defineProperty(target, name, {
<del> configurable: true,
<del> enumerable: true,
<del> get() {
<del> const value = f();
<del> Object.defineProperty(target, name, {
<del> configurable: true,
<del> enumerable: true,
<del> writeable: true,
<del> value: value,
<del> });
<del> return value;
<del> }
<del> });
<del>}
<del>
<ide> module.exports = MessageQueue;
<ide><path>Libraries/Utilities/__tests__/MessageQueue-test.js
<ide>
<ide> const MessageQueueTestConfig = require('MessageQueueTestConfig');
<ide> jest.unmock('MessageQueue');
<add>jest.unmock('defineLazyObjectProperty');
<ide>
<ide> let MessageQueue;
<ide> let MessageQueueTestModule1; | 2 |
Javascript | Javascript | preserve case as long as we can | cfa7f99b01c063a7f74ee265399473230eda6ec5 | <ide><path>src/git-repository-async.js
<ide> export default class GitRepositoryAsync {
<ide>
<ide> workingDirectory = workingDirectory.replace(/\/$/, '')
<ide>
<add> const originalPath = _path
<ide> if (this.isCaseInsensitive) {
<ide> _path = _path.toLowerCase()
<ide> workingDirectory = workingDirectory.toLowerCase()
<ide> export default class GitRepositoryAsync {
<ide> _path = _path.replace(/^\/private\//, '/')
<ide> workingDirectory = workingDirectory.replace(/^\/private\//, '/')
<ide>
<del> const originalPath = _path
<ide> if (_path.indexOf(workingDirectory) === 0) {
<ide> return originalPath.substring(workingDirectory.length + 1)
<ide> } else if (_path === workingDirectory) { | 1 |
Go | Go | move var and comment to where it's used | 3b9b5842b3d6f27283b952bb190db5641307ee4d | <ide><path>pkg/idtools/idtools_unix.go
<ide> var (
<ide> )
<ide>
<ide> func mkdirAs(path string, mode os.FileMode, owner Identity, mkAll, chownExisting bool) error {
<del> // make an array containing the original path asked for, plus (for mkAll == true)
<del> // all path components leading up to the complete path that don't exist before we MkdirAll
<del> // so that we can chown all of them properly at the end. If chownExisting is false, we won't
<del> // chown the full directory path if it exists
<del>
<del> var paths []string
<ide> path, err := filepath.Abs(path)
<ide> if err != nil {
<ide> return err
<ide> func mkdirAs(path string, mode os.FileMode, owner Identity, mkAll, chownExisting
<ide> return setPermissions(path, mode, owner.UID, owner.GID, stat)
<ide> }
<ide>
<add> // make an array containing the original path asked for, plus (for mkAll == true)
<add> // all path components leading up to the complete path that don't exist before we MkdirAll
<add> // so that we can chown all of them properly at the end. If chownExisting is false, we won't
<add> // chown the full directory path if it exists
<add> var paths []string
<ide> if os.IsNotExist(err) {
<ide> paths = []string{path}
<ide> } | 1 |
Python | Python | add test for ndarray.flat modifying data | 883205409195195d33877a787fd3220fb0b0db1e | <ide><path>numpy/core/tests/test_regression.py
<ide> def test_ticket_1770(self):
<ide> except:
<ide> raise AssertionError
<ide>
<add> def test_ticket_1608(self):
<add> "x.flat shouldn't modify data"
<add> x = np.array([[1,2],[3,4]]).T
<add> y = np.array(x.flat)
<add> assert_equal(x, [[1,3],[2,4]])
<add>
<ide> if __name__ == "__main__":
<ide> run_module_suite() | 1 |
PHP | PHP | use one line | 622cdda7cf014121c01ba2090003c9902be3cceb | <ide><path>config/cache.php
<ide> |
<ide> */
<ide>
<del> 'prefix' => env(
<del> 'CACHE_PREFIX',
<del> Str::slug(env('APP_NAME', 'laravel'), '_').'_cache'
<del> ),
<add> 'prefix' => env('CACHE_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_cache'),
<ide>
<ide> ]; | 1 |
PHP | PHP | add missing middlewareinterface check | e8e444f5b300dddc94fd870a80a9239aa62c9186 | <ide><path>src/Http/MiddlewareQueue.php
<ide> protected function resolve($middleware): ?MiddlewareInterface
<ide> $middleware = new $className();
<ide> }
<ide>
<add> if ($middleware instanceof MiddlewareInterface) {
<add> return $middleware;
<add> }
<add>
<ide> if (!$middleware instanceof Closure) {
<ide> return new DoublePassDecoratorMiddleware($middleware);
<ide> } | 1 |
Python | Python | add common class to access to the cpu | c66a7a8fd2607a1d3b4d1143a9f757c134c69fe0 | <ide><path>glances/core/glances_cpu_percent.py
<add># -*- coding: utf-8 -*-
<add>#
<add># This file is part of Glances.
<add>#
<add># Copyright (C) 2015 Nicolargo <nicolas@nicolargo.com>
<add>#
<add># Glances is free software; you can redistribute it and/or modify
<add># it under the terms of the GNU Lesser General Public License as published by
<add># the Free Software Foundation, either version 3 of the License, or
<add># (at your option) any later version.
<add>#
<add># Glances is distributed in the hope that it will be useful,
<add># but WITHOUT ANY WARRANTY; without even the implied warranty of
<add># MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
<add># GNU Lesser General Public License for more details.
<add>#
<add># You should have received a copy of the GNU Lesser General Public License
<add># along with this program. If not, see <http://www.gnu.org/licenses/>.
<add>
<add>"""CPU percent stats shared between CPU and Quicklook plugins."""
<add>
<add>import psutil
<add>
<add>from glances.core.glances_timer import Timer
<add>
<add>
<add>class CpuPercent(object):
<add> """Get and strore the CPU percent"""
<add>
<add> def __init__(self, cached_time=1):
<add> self.cpu_percent = 0
<add>
<add> # cached_time is the minimum time interval between stats updates
<add> # since last update is passed (will retrieve old cached info instead)
<add> self.timer = Timer(0)
<add> self.cached_time = cached_time
<add>
<add> def get(self):
<add> """Update and/or return the CPU using the PSUtil lib"""
<add> # Never update more than 1 time per cached_time
<add> if self.timer.finished():
<add> self.cpu_percent = psutil.cpu_percent(interval=0.0)
<add> self.timer = Timer(self.cached_time)
<add> return self.cpu_percent
<add>
<add>
<add># CpuPercent instance shared between plugins
<add>cpu_percent = CpuPercent() | 1 |
Java | Java | remove return statements in finally blocks | bb8be509cdcd2d9512bcbab487dd5d85c6e888fe | <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/DispatcherServlet.java
<ide> protected void doService(HttpServletRequest request, HttpServletResponse respons
<ide> doDispatch(request, response);
<ide> }
<ide> finally {
<del> if (WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted()) {
<del> return;
<del> }
<del> // Restore the original attribute snapshot, in case of an include.
<del> if (attributesSnapshot != null) {
<del> restoreAttributesAfterInclude(request, attributesSnapshot);
<add> if (!WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted()) {
<add> // Restore the original attribute snapshot, in case of an include.
<add> if (attributesSnapshot != null) {
<add> restoreAttributesAfterInclude(request, attributesSnapshot);
<add> }
<ide> }
<ide> }
<ide> }
<ide> protected void doDispatch(HttpServletRequest request, HttpServletResponse respon
<ide> return;
<ide> }
<ide>
<del> try {
<del> // Actually invoke the handler.
<del> mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
<del> }
<del> finally {
<del> if (asyncManager.isConcurrentHandlingStarted()) {
<del> return;
<del> }
<add> // Actually invoke the handler.
<add> mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
<add>
<add> if (asyncManager.isConcurrentHandlingStarted()) {
<add> return;
<ide> }
<ide>
<ide> applyDefaultViewName(request, mv);
<ide> protected void doDispatch(HttpServletRequest request, HttpServletResponse respon
<ide> finally {
<ide> if (asyncManager.isConcurrentHandlingStarted()) {
<ide> // Instead of postHandle and afterCompletion
<del> mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response);
<del> return;
<add> if (mappedHandler != null) {
<add> mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response);
<add> }
<ide> }
<del> // Clean up any resources used by a multipart request.
<del> if (multipartRequestParsed) {
<del> cleanupMultipart(processedRequest);
<add> else {
<add> // Clean up any resources used by a multipart request.
<add> if (multipartRequestParsed) {
<add> cleanupMultipart(processedRequest);
<add> }
<ide> }
<ide> }
<ide> } | 1 |
Javascript | Javascript | ensure proper handling in runinasyncscope | 503900b4633a541ecbebc159487f775c2669f54d | <ide><path>lib/async_hooks.js
<ide> const {
<ide> executionAsyncId,
<ide> triggerAsyncId,
<ide> // Private API
<del> hasAsyncIdStack,
<ide> getHookArrays,
<ide> enableHooks,
<ide> disableHooks,
<ide> class AsyncResource {
<ide> runInAsyncScope(fn, thisArg, ...args) {
<ide> const asyncId = this[async_id_symbol];
<ide> emitBefore(asyncId, this[trigger_async_id_symbol]);
<del> try {
<del> if (thisArg === undefined)
<del> return fn(...args);
<del> return ReflectApply(fn, thisArg, args);
<del> } finally {
<del> if (hasAsyncIdStack())
<del> emitAfter(asyncId);
<del> }
<add>
<add> const ret = thisArg === undefined ?
<add> fn(...args) :
<add> ReflectApply(fn, thisArg, args);
<add>
<add> emitAfter(asyncId);
<add> return ret;
<ide> }
<ide>
<ide> emitDestroy() { | 1 |
Javascript | Javascript | use const where applicable in compilation | 0bc09a803357e89b0445f3164e00eb74b47af2dd | <ide><path>lib/Compilation.js
<ide> class Compilation extends Tapable {
<ide> let _this = this;
<ide> const start = _this.profile && +new Date();
<ide>
<del> let factories = [];
<add> const factories = [];
<ide> for(let i = 0; i < dependencies.length; i++) {
<ide> const factory = _this.dependencyFactories.get(dependencies[i][0].constructor);
<ide> if(!factory) { | 1 |
Mixed | Javascript | add dynamic layouts with _app.js example | 6dcc9bd59a1ad8200f28d32ffe07a805a9fa5368 | <ide><path>examples/with-dynamic-app-layout/layouts/BlueLayout.js
<add>export default ({ children }) => {
<add> return <main style={{ border: '4px dashed blue' }}>
<add> {children}
<add> </main>
<add>}
<ide><path>examples/with-dynamic-app-layout/layouts/GreenLayout.js
<add>export default ({ children }) => {
<add> return <main style={{ border: '4px dashed green' }}>
<add> {children}
<add> </main>
<add>}
<ide><path>examples/with-dynamic-app-layout/layouts/RedLayout.js
<add>export default ({ children }) => {
<add> return <main style={{ border: '4px dashed red' }}>
<add> {children}
<add> </main>
<add>}
<ide><path>examples/with-dynamic-app-layout/pages/_app.js
<add>import React from 'react'
<add>import App, { Container } from 'next/app'
<add>
<add>export default class MyApp extends App {
<add> render () {
<add> const { Component, pageProps } = this.props
<add> return <Container>
<add> <Component.Layout>
<add> <Component {...pageProps} />
<add> </Component.Layout>
<add> </Container>
<add> }
<add>}
<ide><path>examples/with-dynamic-app-layout/pages/green.js
<add>import React from 'react'
<add>import Link from 'next/link'
<add>
<add>import GreenLayout from '../layouts/GreenLayout'
<add>
<add>const GreenPage = () => {
<add> return <p>
<add> This is the <strong style={{ color: 'green' }}>Green</strong> page, it's borders are green<br /><br />
<add> Go back to the <Link href='/'><a style={{ color: 'blue' }}>Blue Page</a></Link>
<add> </p>
<add>}
<add>
<add>GreenPage.Layout = GreenLayout
<add>
<add>export default GreenPage
<ide><path>examples/with-dynamic-app-layout/pages/index.js
<add>import React from 'react'
<add>import Link from 'next/link'
<add>
<add>import BlueLayout from '../layouts/BlueLayout'
<add>
<add>const BluePage = () => {
<add> return <p>
<add> This is the <strong style={{ color: 'blue' }}>Blue</strong> page, it's borders are blue<br /><br />
<add> Go to the <Link href='/red'><a style={{ color: 'red' }}>Red Page</a></Link><br /><br />
<add> Go to the <Link href='/green'><a style={{ color: 'green' }} >Green Page</a></Link>
<add> </p>
<add>}
<add>
<add>BluePage.Layout = BlueLayout
<add>
<add>export default BluePage
<ide><path>examples/with-dynamic-app-layout/pages/red.js
<add>import React from 'react'
<add>import Link from 'next/link'
<add>
<add>import RedLayout from '../layouts/RedLayout'
<add>
<add>const RedPage = () => {
<add> return <p>
<add> This is the <strong style={{ color: 'red' }} >Red</strong> page, it's borders are red<br /><br />
<add> Go back to the <Link href='/'><a>Blue Page</a></Link>
<add> </p>
<add>}
<add>
<add>RedPage.Layout = RedLayout
<add>
<add>export default RedPage
<ide><path>examples/with-dynamic-app-layout/readme.md
<add>[](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-dynamic-app-layout)
<add>
<add># With dynamic `App` layout example
<add>
<add>## How to use
<add>
<add>### Using `create-next-app`
<add>
<add>Execute [`create-next-app`](https://github.com/segmentio/create-next-app) with [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/) or [npx](https://github.com/zkat/npx#readme) to bootstrap the example:
<add>
<add>```bash
<add>npx create-next-app --example with-dynamic-app-layout with-dynamic-app-layout-app
<add># or
<add>yarn create next-app --example with-dynamic-app-layout with-dynamic-app-layout-app
<add>```
<add>
<add>### Download manually
<add>
<add>Download the example:
<add>
<add>```bash
<add>curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-dynamic-app-layout
<add>cd with-dynamic-app-layout
<add>```
<add>
<add>Install it and run:
<add>
<add>```bash
<add>npm install
<add>npm run dev
<add># or
<add>yarn
<add>yarn dev
<add>```
<add>
<add>Deploy it to the cloud with [now](https://zeit.co/now) ([download](https://zeit.co/download))
<add>
<add>```bash
<add>now
<add>```
<add>
<add>## The idea behind the example
<add>
<add>Shows how to use _app.js to implement _dynamic_ layouts for pages.
<add>This is achieved by attaching a static `Layout` property to each page that needs a different layout. In that way, once we use `_app.js` to wrap our pages, we can get it from `Component.Layout` and render it accordingly. | 8 |
Javascript | Javascript | fix array expansion when using "..." | e63e73371324bee6bc45d40c0dd37726f064ab7b | <ide><path>lib/config/defaults.js
<ide> const A = (obj, prop, factory) => {
<ide> const item = value[i];
<ide> if (item === "...") {
<ide> if (newArray === undefined) {
<del> newArray = i > 0 ? value.slice(0, i - 1) : [];
<add> newArray = value.slice(0, i);
<ide> obj[prop] = /** @type {T[P]} */ (/** @type {unknown} */ (newArray));
<ide> }
<ide> const items = /** @type {any[]} */ (/** @type {unknown} */ (factory())); | 1 |
Ruby | Ruby | replace env["home"] with dir.home | e78665f4f7a73bf18a26f2cb32d310de38e67898 | <ide><path>Library/Homebrew/cask/artifact/abstract_uninstall.rb
<ide> def uninstall_launchctl(*services, command: nil, **_)
<ide> +"/Library/LaunchAgents/#{service}.plist",
<ide> +"/Library/LaunchDaemons/#{service}.plist",
<ide> ]
<del> paths.each { |elt| elt.prepend(ENV["HOME"]).freeze } unless with_sudo
<add> paths.each { |elt| elt.prepend(Dir.home).freeze } unless with_sudo
<ide> paths = paths.map { |elt| Pathname(elt) }.select(&:exist?)
<ide> paths.each do |path|
<ide> command.run!("/bin/rm", args: ["-f", "--", path], sudo: with_sudo)
<ide><path>Library/Homebrew/cask/artifact/relocated.rb
<ide> def add_altname_metadata(file, altname, command: nil)
<ide> end
<ide>
<ide> def printable_target
<del> target.to_s.sub(/^#{ENV['HOME']}(#{File::SEPARATOR}|$)/, "~/")
<add> target.to_s.sub(/^#{Dir.home}(#{File::SEPARATOR}|$)/, "~/")
<ide> end
<ide> end
<ide> end
<ide><path>Library/Homebrew/cask/cask.rb
<ide> def to_h
<ide>
<ide> def to_h_string_gsubs(string)
<ide> string.to_s
<del> .gsub(ENV["HOME"], "$HOME")
<add> .gsub(Dir.home, "$HOME")
<ide> .gsub(HOMEBREW_PREFIX, "$(brew --prefix)")
<ide> end
<ide>
<ide><path>Library/Homebrew/cask/config.rb
<ide> def explicit_s
<ide> key = "language"
<ide> value = T.cast(explicit.fetch(:languages, []), T::Array[String]).join(",")
<ide> end
<del> "#{key}: \"#{value.to_s.sub(/^#{ENV['HOME']}/, "~")}\""
<add> "#{key}: \"#{value.to_s.sub(/^#{Dir.home}/, "~")}\""
<ide> end.join(", ")
<ide> end
<ide>
<ide><path>Library/Homebrew/diagnostic.rb
<ide> def inject_file_list(list, string)
<ide> end
<ide>
<ide> def user_tilde(path)
<del> path.gsub(ENV["HOME"], "~")
<add> path.gsub(Dir.home, "~")
<ide> end
<ide>
<ide> sig { returns(String) }
<ide> def check_for_non_prefixed_coreutils
<ide> end
<ide>
<ide> def check_for_pydistutils_cfg_in_home
<del> return unless File.exist? "#{ENV["HOME"]}/.pydistutils.cfg"
<add> return unless File.exist? "#{Dir.home}/.pydistutils.cfg"
<ide>
<ide> <<~EOS
<ide> A '.pydistutils.cfg' file was found in $HOME, which may cause Python
<ide><path>Library/Homebrew/formula.rb
<ide> def common_stage_test_env
<ide> GOCACHE: "#{HOMEBREW_CACHE}/go_cache",
<ide> GOPATH: "#{HOMEBREW_CACHE}/go_mod_cache",
<ide> CARGO_HOME: "#{HOMEBREW_CACHE}/cargo_cache",
<del> CURL_HOME: ENV["CURL_HOME"] || ENV["HOME"],
<add> CURL_HOME: ENV.fetch("CURL_HOME") { Dir.home },
<ide> }
<ide> end
<ide>
<ide><path>Library/Homebrew/formula_installer.rb
<ide> def build
<ide> sandbox = Sandbox.new
<ide> formula.logs.mkpath
<ide> sandbox.record_log(formula.logs/"build.sandbox.log")
<del> sandbox.allow_write_path(ENV["HOME"]) if interactive?
<add> sandbox.allow_write_path(Dir.home) if interactive?
<ide> sandbox.allow_write_temp_and_cache
<ide> sandbox.allow_write_log(formula)
<ide> sandbox.allow_cvs
<ide><path>Library/Homebrew/test/support/fixtures/cask/Casks/with-uninstall-script-user-relative.rb
<ide> app "MyFancyApp/MyFancyApp.app", target: "~/MyFancyApp.app"
<ide>
<ide> postflight do
<del> File.write "#{ENV["HOME"]}/MyFancyApp.app/uninstall.sh", <<~SH
<add> File.write "#{Dir.home}/MyFancyApp.app/uninstall.sh", <<~SH
<ide> #!/bin/sh
<del> /bin/rm -r "#{ENV["HOME"]}/MyFancyApp.app"
<add> /bin/rm -r "#{Dir.home}/MyFancyApp.app"
<ide> SH
<ide> end
<ide>
<ide><path>Library/Homebrew/utils.rb
<ide> def interactive_shell(f = nil)
<ide> ENV["HOMEBREW_DEBUG_INSTALL"] = f.full_name
<ide> end
<ide>
<del> if ENV["SHELL"].include?("zsh") && (home = ENV["HOME"])&.start_with?(HOMEBREW_TEMP.resolved_path.to_s)
<add> if ENV["SHELL"].include?("zsh") && (home = Dir.home).start_with?(HOMEBREW_TEMP.resolved_path.to_s)
<ide> FileUtils.mkdir_p home
<ide> FileUtils.touch "#{home}/.zshrc"
<ide> end
<ide><path>Library/Homebrew/utils/shell.rb
<ide> def export_value(key, value, shell = preferred)
<ide> def profile
<ide> case preferred
<ide> when :bash
<del> bash_profile = "#{ENV["HOME"]}/.bash_profile"
<add> bash_profile = "#{Dir.home}/.bash_profile"
<ide> return bash_profile if File.exist? bash_profile
<ide> when :zsh
<ide> return "#{ENV["ZDOTDIR"]}/.zshrc" if ENV["ZDOTDIR"].present? | 10 |
Text | Text | update highlighted lines in tutorial | 42dee34146c7ef24cf6bf6962a39a1b468bcd03a | <ide><path>docs/docs/tutorial.md
<ide> That's it!
<ide>
<ide> Let's replace the hard-coded data with some dynamic data from the server. We will remove the data prop and replace it with a URL to fetch:
<ide>
<del>```javascript{2}
<add>```javascript{3}
<ide> // tutorial11.js
<ide> React.renderComponent(
<ide> <CommentBox url="comments.json" />,
<ide> We will use jQuery to help make an asynchronous request to the server.
<ide>
<ide> Note: because this is becoming an AJAX application you'll need to develop your app using a web server rather than as a file sitting on your file system. The easiest way to do this is to run `python -m SimpleHTTPServer` in your application's directory.
<ide>
<del>```javascript{4-11}
<add>```javascript{4-10}
<ide> // tutorial13.js
<ide> var CommentBox = React.createClass({
<ide> getInitialState: function() {
<ide> var CommentBox = React.createClass({
<ide>
<ide> The key is the call to `this.setState()`. We replace the old array of comments with the new one from the server and the UI automatically updates itself. Because of this reactivity, it is trivial to add live updates. We will use simple polling here but you could easily use WebSockets or other technologies.
<ide>
<del>```javascript{3,17-21,35}
<add>```javascript{3,14-17,30}
<ide> // tutorial14.js
<ide> var CommentBox = React.createClass({
<ide> loadCommentsFromServer: function() {
<ide> var CommentForm = React.createClass({
<ide>
<ide> Let's make the form interactive. When the user submits the form, we should clear it, submit a request to the server, and refresh the list of comments. To start, let's listen for the form's submit event and clear it.
<ide>
<del>```javascript{3-13,16,21}
<add>```javascript{3-13,16-17,21}
<ide> // tutorial16.js
<ide> var CommentForm = React.createClass({
<ide> handleSubmit: function() {
<ide> When a user submits a comment, we will need to refresh the list of comments to i
<ide>
<ide> We need to pass data from the child component to its parent. We do this by passing a `callback` in props from parent to child:
<ide>
<del>```javascript{13-15,32}
<add>```javascript{11-13,27}
<ide> // tutorial17.js
<ide> var CommentBox = React.createClass({
<ide> loadCommentsFromServer: function() {
<ide> var CommentForm = React.createClass({
<ide>
<ide> Now that the callbacks are in place, all we have to do is submit to the server and refresh the list:
<ide>
<del>```javascript{14-22}
<add>```javascript{12-19}
<ide> // tutorial19.js
<ide> var CommentBox = React.createClass({
<ide> loadCommentsFromServer: function() {
<ide> var CommentBox = React.createClass({
<ide>
<ide> Our application is now feature complete but it feels slow to have to wait for the request to complete before your comment appears in the list. We can optimistically add this comment to the list to make the app feel faster.
<ide>
<del>```javascript{14-16}
<add>```javascript{12-14}
<ide> // tutorial20.js
<ide> var CommentBox = React.createClass({
<ide> loadCommentsFromServer: function() { | 1 |
Javascript | Javascript | simplify `reactnativestyleattributes` type | 33b385825c7220e89d02cc2de42e45563b9b5e30 | <ide><path>Libraries/Components/View/ReactNativeStyleAttributes.js
<ide> * @flow
<ide> */
<ide>
<del>'use strict';
<ide> import DeprecatedImageStylePropTypes from '../../DeprecatedPropTypes/DeprecatedImageStylePropTypes';
<ide> import DeprecatedTextStylePropTypes from '../../DeprecatedPropTypes/DeprecatedTextStylePropTypes';
<ide> import DeprecatedViewStylePropTypes from '../../DeprecatedPropTypes/DeprecatedViewStylePropTypes';
<add>import type {AnyAttributeType} from '../../Renderer/shims/ReactNativeTypes';
<ide> import processColor from '../../StyleSheet/processColor';
<ide> import processTransform from '../../StyleSheet/processTransform';
<ide> import sizesDiffer from '../../Utilities/differ/sizesDiffer';
<ide>
<del>type ReturnBoolType = <V>(V) => true;
<del>type BoolifiedDeprecatedViewStylePropTypes = $ObjMap<
<del> typeof DeprecatedViewStylePropTypes,
<del> ReturnBoolType,
<del>>;
<del>type BoolifiedDeprecatedTextStylePropTypes = $ObjMapi<
<del> typeof DeprecatedTextStylePropTypes,
<del> ReturnBoolType,
<del>>;
<del>type BoolifiedDeprecatedImageStylePropTypes = $ObjMapi<
<del> typeof DeprecatedImageStylePropTypes,
<del> ReturnBoolType,
<del>>;
<del>
<del>type StyleAttributesType = {
<del> ...BoolifiedDeprecatedViewStylePropTypes,
<del> ...BoolifiedDeprecatedTextStylePropTypes,
<del> ...BoolifiedDeprecatedImageStylePropTypes,
<del> transform: $ReadOnly<{|process: typeof processTransform|}> | true,
<del> shadowOffset: $ReadOnly<{|diff: typeof sizesDiffer|}> | true,
<del> backgroundColor: typeof colorAttributes | true,
<del> borderBottomColor: typeof colorAttributes | true,
<del> borderColor: typeof colorAttributes | true,
<del> borderLeftColor: typeof colorAttributes | true,
<del> borderRightColor: typeof colorAttributes | true,
<del> borderTopColor: typeof colorAttributes | true,
<del> borderStartColor: typeof colorAttributes | true,
<del> borderEndColor: typeof colorAttributes | true,
<del> color: typeof colorAttributes | true,
<del> shadowColor: typeof colorAttributes | true,
<del> textDecorationColor: typeof colorAttributes | true,
<del> tintColor: typeof colorAttributes | true,
<del> textShadowColor: typeof colorAttributes | true,
<del> overlayColor: typeof colorAttributes | true,
<del> ...
<del>};
<del>
<del>const ReactNativeStyleAttributes: StyleAttributesType = {};
<add>const ReactNativeStyleAttributes: {[string]: AnyAttributeType} = {};
<ide>
<ide> for (const attributeName of Object.keys({
<ide> ...DeprecatedViewStylePropTypes,
<ide><path>Libraries/Renderer/shims/ReactNativeTypes.js
<ide> *
<ide> * @format
<ide> * @flow strict
<del> * @generated SignedSource<<51285a8509b134326b535fbea3608c87>>
<add> * @generated SignedSource<<d970268c93059bcc9626426c0c280439>>
<ide> */
<ide>
<ide> import type {ElementRef, ElementType, Element, AbstractComponent} from 'react';
<ide> export type MeasureLayoutOnSuccessCallback = (
<ide> height: number,
<ide> ) => void;
<ide>
<del>type AttributeType<T, V> =
<add>export type AttributeType<T, V> =
<ide> | true
<ide> | $ReadOnly<{|
<ide> diff?: (arg1: T, arg2: T) => boolean,
<ide> type AttributeType<T, V> =
<ide>
<ide> // We either force that `diff` and `process` always use mixed,
<ide> // or we allow them to define specific types and use this hack
<del>type AnyAttributeType = AttributeType<$FlowFixMe, $FlowFixMe>;
<add>export type AnyAttributeType = AttributeType<$FlowFixMe, $FlowFixMe>;
<ide>
<ide> export type AttributeConfiguration = $ReadOnly<{
<ide> [propName: string]: AnyAttributeType,
<ide> export type AttributeConfiguration = $ReadOnly<{
<ide> ...
<ide> }>;
<ide>
<del>type PartialAttributeConfiguration = $ReadOnly<{
<add>export type PartialAttributeConfiguration = $ReadOnly<{
<ide> [propName: string]: AnyAttributeType,
<ide> style?: $ReadOnly<{
<ide> [propName: string]: AnyAttributeType,
<ide><path>Libraries/StyleSheet/StyleSheet.js
<ide> module.exports = {
<ide> let value;
<ide>
<ide> if (ReactNativeStyleAttributes[property] === true) {
<del> value = {};
<add> value = {process};
<ide> } else if (typeof ReactNativeStyleAttributes[property] === 'object') {
<del> value = ReactNativeStyleAttributes[property];
<add> value = {...ReactNativeStyleAttributes[property], process};
<ide> } else {
<ide> console.error(`${property} is not a valid style attribute`);
<ide> return;
<ide> module.exports = {
<ide> console.warn(`Overwriting ${property} style attribute preprocessor`);
<ide> }
<ide>
<del> ReactNativeStyleAttributes[property] = {...value, process};
<add> ReactNativeStyleAttributes[property] = value;
<ide> },
<ide>
<ide> /** | 3 |
Javascript | Javascript | update interpolation to use new color format | 042862a010da0ceda4af507d5c8ca1b3ac764681 | <ide><path>Libraries/Animated/src/Interpolation.js
<ide> function colorToRgba(input: string): string {
<ide>
<ide> int32Color = int32Color || 0; // $FlowIssue
<ide>
<del> var a = ((int32Color & 0xff000000) >>> 24) / 255;
<del> var r = (int32Color & 0x00ff0000) >>> 16;
<del> var g = (int32Color & 0x0000ff00) >>> 8;
<del> var b = int32Color & 0x000000ff;
<add> var r = (int32Color & 0xff000000) >>> 24;
<add> var g = (int32Color & 0x00ff0000) >>> 16;
<add> var b = (int32Color & 0x0000ff00) >>> 8;
<add> var a = (int32Color & 0x000000ff) / 255;
<ide>
<ide> return `rgba(${r}, ${g}, ${b}, ${a})`;
<ide> } | 1 |
Javascript | Javascript | remove extra call to _getlabelcapacity | 251f3832bc472f530747a66131200045c51032af | <ide><path>src/scales/scale.time.js
<ide> function determineMajorUnit(unit) {
<ide> * Important: this method can return ticks outside the min and max range, it's the
<ide> * responsibility of the calling code to clamp values if needed.
<ide> */
<del>function generate(scale, min, max, capacity) {
<add>function generate(scale) {
<ide> const adapter = scale._adapter;
<add> const min = scale.min;
<add> const max = scale.max;
<ide> const options = scale.options;
<ide> const timeOpts = options.time;
<del> const minor = timeOpts.unit || determineUnitForAutoTicks(timeOpts.minUnit, min, max, capacity);
<add> const minor = timeOpts.unit || determineUnitForAutoTicks(timeOpts.minUnit, min, max, scale._getLabelCapacity(min));
<ide> const stepSize = resolve([timeOpts.stepSize, timeOpts.unitStepSize, 1]);
<ide> const weekday = minor === 'week' ? timeOpts.isoWeekday : false;
<ide> const ticks = [];
<ide> function getAllTimestamps(scale) {
<ide>
<ide>
<ide> function getTimestampsForTicks(scale) {
<del> const min = scale.min;
<del> const max = scale.max;
<ide> const options = scale.options;
<del> const capacity = scale._getLabelCapacity(min);
<ide> const source = options.ticks.source;
<del> let timestamps;
<ide>
<ide> if (source === 'data' || (source === 'auto' && options.distribution === 'series')) {
<del> timestamps = getAllTimestamps(scale);
<add> return getAllTimestamps(scale);
<ide> } else if (source === 'labels') {
<del> timestamps = getLabelTimestamps(scale);
<del> } else {
<del> timestamps = generate(scale, min, max, capacity, options);
<add> return getLabelTimestamps(scale);
<ide> }
<del>
<del> return timestamps;
<add> return generate(scale);
<ide> }
<ide>
<ide> function getTimestampsForTable(scale) { | 1 |
Javascript | Javascript | add handle ref/unref stubs in rr mode | fa98b97171d9b8519bdbf5d9f8dbd8639ac3c050 | <ide><path>lib/cluster.js
<ide> function workerInit() {
<ide> return 0;
<ide> }
<ide>
<add> // XXX(bnoordhuis) Probably no point in implementing ref() and unref()
<add> // because the control channel is going to keep the worker alive anyway.
<add> function ref() {
<add> }
<add>
<add> function unref() {
<add> }
<add>
<ide> // Faux handle. Mimics a TCPWrap with just enough fidelity to get away
<ide> // with it. Fools net.Server into thinking that it's backed by a real
<ide> // handle.
<ide> var handle = {
<ide> close: close,
<del> listen: listen
<add> listen: listen,
<add> ref: ref,
<add> unref: unref,
<ide> };
<ide> if (message.sockname) {
<ide> handle.getsockname = getsockname; // TCP handles only.
<ide><path>test/parallel/test-cluster-rr-ref.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const cluster = require('cluster');
<add>const net = require('net');
<add>
<add>if (cluster.isMaster) {
<add> cluster.fork().on('message', function(msg) {
<add> if (msg === 'done') this.kill();
<add> });
<add>} else {
<add> const server = net.createServer(assert.fail);
<add> server.listen(common.PORT, function() {
<add> server.unref();
<add> server.ref();
<add> server.close(function() {
<add> process.send('done');
<add> });
<add> });
<add>} | 2 |
Go | Go | remove unused daemon/sorter.go | 8913ec4912e529be44b7cc2aaf465b0d9b03ffc9 | <ide><path>daemon/sorter.go
<del>package daemon
<del>
<del>import "sort"
<del>
<del>type containerSorter struct {
<del> containers []*Container
<del> by func(i, j *Container) bool
<del>}
<del>
<del>func (s *containerSorter) Len() int {
<del> return len(s.containers)
<del>}
<del>
<del>func (s *containerSorter) Swap(i, j int) {
<del> s.containers[i], s.containers[j] = s.containers[j], s.containers[i]
<del>}
<del>
<del>func (s *containerSorter) Less(i, j int) bool {
<del> return s.by(s.containers[i], s.containers[j])
<del>}
<del>
<del>func sortContainers(containers []*Container, predicate func(i, j *Container) bool) {
<del> s := &containerSorter{containers, predicate}
<del> sort.Sort(s)
<del>} | 1 |
PHP | PHP | fix another failing test | ba373574de0964d329a0cf4facea27df73c38698 | <ide><path>tests/TestCase/Command/HelpCommandTest.php
<ide> public function testMainAsXml()
<ide> $find = '<shell name="sample" call_as="sample" provider="TestApp\Shell\SampleShell" help="sample -h"';
<ide> $this->assertOutputContains($find);
<ide>
<del> $find = '<shell name="schema_cache" call_as="schema_cache" provider="Cake\Shell\SchemaCacheShell" help="schema_cache -h"';
<add> $find = '<shell name="schema_cache build" call_as="schema_cache build" ' .
<add> 'provider="Cake\Command\SchemacacheBuildCommand" help="schema_cache build -h"';
<ide> $this->assertOutputContains($find);
<ide>
<ide> $find = '<shell name="test_plugin.sample" call_as="test_plugin.sample" provider="TestPlugin\Shell\SampleShell" help="test_plugin.sample -h"'; | 1 |
PHP | PHP | use correct argument order | ed1a64ca04dce5f21833f0e9fbad0c632a670e2f | <ide><path>lib/Cake/Utility/Xml.php
<ide> protected static function _fromArray($dom, $node, &$data, $format) {
<ide> if ($key[0] === '@') {
<ide> throw new XmlException(__d('cake_dev', 'Invalid array'));
<ide> }
<del> if (is_numeric(implode(array_keys($value), ''))) { // List
<add> if (is_numeric(implode('', array_keys($value)))) { // List
<ide> foreach ($value as $item) {
<ide> $itemData = compact('dom', 'node', 'key', 'format');
<ide> $itemData['value'] = $item; | 1 |
Javascript | Javascript | fix a mistake in reactchildren refactor | 6498f62edcdf0bcc02ed96efdad92b7e89330d8a | <ide><path>packages/react-dom/src/client/ReactDOMOption.js
<ide> function flattenChildren(children) {
<ide> if (child == null) {
<ide> return;
<ide> }
<del> content += child;
<add> content += (child: any);
<ide> // Note: we don't warn about invalid children here.
<ide> // Instead, this is done separately below so that
<ide> // it happens during the hydration codepath too.
<ide> export function validateProps(element: Element, props: Object) {
<ide> if (typeof child === 'string' || typeof child === 'number') {
<ide> return;
<ide> }
<del> if (typeof child.type !== 'string') {
<add> if (typeof (child: any).type !== 'string') {
<ide> return;
<ide> }
<ide> if (!didWarnInvalidChild) {
<ide><path>packages/react-dom/src/server/ReactPartialRenderer.js
<ide> function flattenOptionChildren(children: mixed): ?string {
<ide> let content = '';
<ide> // Flatten children and warn if they aren't strings or numbers;
<ide> // invalid types are ignored.
<del> React.Children.forEach(children, function(child) {
<add> React.Children.forEach((children: any), function(child) {
<ide> if (child == null) {
<ide> return;
<ide> }
<del> content += child;
<add> content += (child: any);
<ide> if (__DEV__) {
<ide> if (
<ide> !didWarnInvalidOptionChildren &&
<ide><path>packages/react/src/ReactChildren.js
<ide> *
<ide> * This source code is licensed under the MIT license found in the
<ide> * LICENSE file in the root directory of this source tree.
<add> *
<add> * @flow
<ide> */
<ide>
<add>import type {ReactNodeList} from 'shared/ReactTypes';
<add>
<ide> import invariant from 'shared/invariant';
<ide> import {
<ide> getIteratorFn,
<ide> const SUBSEPARATOR = ':';
<ide> * @param {string} key to be escaped.
<ide> * @return {string} the escaped key.
<ide> */
<del>function escape(key) {
<add>function escape(key: string): string {
<ide> const escapeRegex = /[=:]/g;
<ide> const escaperLookup = {
<ide> '=': '=0',
<ide> ':': '=2',
<ide> };
<del> const escapedString = ('' + key).replace(escapeRegex, function(match) {
<add> const escapedString = key.replace(escapeRegex, function(match) {
<ide> return escaperLookup[match];
<ide> });
<ide>
<ide> function escape(key) {
<ide> let didWarnAboutMaps = false;
<ide>
<ide> const userProvidedKeyEscapeRegex = /\/+/g;
<del>function escapeUserProvidedKey(text) {
<del> return ('' + text).replace(userProvidedKeyEscapeRegex, '$&/');
<add>function escapeUserProvidedKey(text: string): string {
<add> return text.replace(userProvidedKeyEscapeRegex, '$&/');
<ide> }
<ide>
<ide> /**
<del> * Generate a key string that identifies a component within a set.
<add> * Generate a key string that identifies a element within a set.
<ide> *
<del> * @param {*} component A component that could contain a manual key.
<add> * @param {*} element A element that could contain a manual key.
<ide> * @param {number} index Index that is used if a manual key is not provided.
<ide> * @return {string}
<ide> */
<del>function getComponentKey(component, index) {
<add>function getElementKey(element: any, index: number): string {
<ide> // Do some typechecking here since we call this blindly. We want to ensure
<ide> // that we don't block potential future ES APIs.
<del> if (
<del> typeof component === 'object' &&
<del> component !== null &&
<del> component.key != null
<del> ) {
<add> if (typeof element === 'object' && element !== null && element.key != null) {
<ide> // Explicit key
<del> return escape(component.key);
<add> return escape('' + element.key);
<ide> }
<ide> // Implicit key determined by the index in the set
<ide> return index.toString(36);
<ide> }
<ide>
<del>function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) {
<add>function mapIntoArray(
<add> children: ?ReactNodeList,
<add> array: Array<React$Node>,
<add> escapedPrefix: string,
<add> nameSoFar: string,
<add> callback: (?React$Node) => ?ReactNodeList,
<add>): number {
<ide> const type = typeof children;
<ide>
<ide> if (type === 'undefined' || type === 'boolean') {
<ide> function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) {
<ide> invokeCallback = true;
<ide> break;
<ide> case 'object':
<del> switch (children.$$typeof) {
<add> switch ((children: any).$$typeof) {
<ide> case REACT_ELEMENT_TYPE:
<ide> case REACT_PORTAL_TYPE:
<ide> invokeCallback = true;
<ide> function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) {
<ide> // If it's the only child, treat the name as if it was wrapped in an array
<ide> // so that it's consistent if the number of children grows:
<ide> let childKey =
<del> nameSoFar === '' ? SEPARATOR + getComponentKey(child, 0) : nameSoFar;
<add> nameSoFar === '' ? SEPARATOR + getElementKey(child, 0) : nameSoFar;
<ide> if (Array.isArray(mappedChild)) {
<ide> let escapedChildKey = '';
<ide> if (childKey != null) {
<ide> escapedChildKey = escapeUserProvidedKey(childKey) + '/';
<ide> }
<del> mapIntoArray(mappedChild, array, escapedChildKey, c => c);
<add> mapIntoArray(mappedChild, array, escapedChildKey, '', c => c);
<ide> } else if (mappedChild != null) {
<ide> if (isValidElement(mappedChild)) {
<ide> mappedChild = cloneAndReplaceKey(
<ide> mappedChild,
<ide> // Keep both the (mapped) and old keys if they differ, just as
<ide> // traverseAllChildren used to do for objects as children
<ide> escapedPrefix +
<add> // $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key
<ide> (mappedChild.key && (!child || child.key !== mappedChild.key)
<del> ? escapeUserProvidedKey(mappedChild.key) + '/'
<add> ? // $FlowFixMe Flow incorrectly thinks existing element's key can be a number
<add> escapeUserProvidedKey('' + mappedChild.key) + '/'
<ide> : '') +
<ide> childKey,
<ide> );
<ide> function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) {
<ide> if (Array.isArray(children)) {
<ide> for (let i = 0; i < children.length; i++) {
<ide> child = children[i];
<del> nextName = nextNamePrefix + getComponentKey(child, i);
<add> nextName = nextNamePrefix + getElementKey(child, i);
<ide> subtreeCount += mapIntoArray(
<ide> child,
<ide> array,
<ide> function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) {
<ide> } else {
<ide> const iteratorFn = getIteratorFn(children);
<ide> if (typeof iteratorFn === 'function') {
<add> const iterableChildren: Iterable<React$Node> & {
<add> entries: any,
<add> } = (children: any);
<ide> if (disableMapsAsChildren) {
<ide> invariant(
<del> iteratorFn !== children.entries,
<add> iteratorFn !== iterableChildren.entries,
<ide> 'Maps are not valid as a React child (found: %s). Consider converting ' +
<ide> 'children to an array of keyed ReactElements instead.',
<del> children,
<add> iterableChildren,
<ide> );
<ide> }
<ide>
<ide> if (__DEV__) {
<ide> // Warn about using Maps as children
<del> if (iteratorFn === children.entries) {
<add> if (iteratorFn === iterableChildren.entries) {
<ide> if (!didWarnAboutMaps) {
<ide> console.warn(
<ide> 'Using Maps as children is deprecated and will be removed in ' +
<ide> function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) {
<ide> }
<ide> }
<ide>
<del> const iterator = iteratorFn.call(children);
<add> const iterator = iteratorFn.call(iterableChildren);
<ide> let step;
<ide> let ii = 0;
<ide> while (!(step = iterator.next()).done) {
<ide> child = step.value;
<del> nextName = nextNamePrefix + getComponentKey(child, ii++);
<add> nextName = nextNamePrefix + getElementKey(child, ii++);
<ide> subtreeCount += mapIntoArray(
<ide> child,
<ide> array,
<ide> function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) {
<ide> 'instead.' +
<ide> ReactDebugCurrentFrame.getStackAddendum();
<ide> }
<del> const childrenString = '' + children;
<add> const childrenString = '' + (children: any);
<ide> invariant(
<ide> false,
<ide> 'Objects are not valid as a React child (found: %s).%s',
<ide> childrenString === '[object Object]'
<del> ? 'object with keys {' + Object.keys(children).join(', ') + '}'
<add> ? 'object with keys {' + Object.keys((children: any)).join(', ') + '}'
<ide> : childrenString,
<ide> addendum,
<ide> );
<ide> function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) {
<ide> return subtreeCount;
<ide> }
<ide>
<add>type MapFunc = (child: ?React$Node) => ?ReactNodeList;
<add>
<ide> /**
<ide> * Maps children that are typically specified as `props.children`.
<ide> *
<ide> function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) {
<ide> * @param {*} context Context for mapFunction.
<ide> * @return {object} Object containing the ordered map of results.
<ide> */
<del>function mapChildren(children, func, context) {
<add>function mapChildren(
<add> children: ?ReactNodeList,
<add> func: MapFunc,
<add> context: mixed,
<add>): ?Array<React$Node> {
<ide> if (children == null) {
<ide> return children;
<ide> }
<ide> const result = [];
<ide> let count = 0;
<del> mapIntoArray(
<del> children,
<del> result,
<del> '',
<del> '',
<del> function(child) {
<del> return func.call(context, child, count++);
<del> },
<del> context,
<del> );
<add> mapIntoArray(children, result, '', '', function(child) {
<add> return func.call(context, child, count++);
<add> });
<ide> return result;
<ide> }
<ide>
<ide> function mapChildren(children, func, context) {
<ide> * @param {?*} children Children tree container.
<ide> * @return {number} The number of children.
<ide> */
<del>function countChildren(children) {
<add>function countChildren(children: ?ReactNodeList): number {
<ide> let n = 0;
<del> mapChildren(children, () => n++);
<add> mapChildren(children, () => {
<add> n++;
<add> // Don't return anything
<add> });
<ide> return n;
<ide> }
<ide>
<add>type ForEachFunc = (child: ?React$Node) => void;
<add>
<ide> /**
<ide> * Iterates through children that are typically specified as `props.children`.
<ide> *
<ide> function countChildren(children) {
<ide> * @param {function(*, int)} forEachFunc
<ide> * @param {*} forEachContext Context for forEachContext.
<ide> */
<del>function forEachChildren(children, forEachFunc, forEachContext) {
<add>function forEachChildren(
<add> children: ?ReactNodeList,
<add> forEachFunc: ForEachFunc,
<add> forEachContext: mixed,
<add>): void {
<ide> mapChildren(
<ide> children,
<ide> function() {
<ide> function forEachChildren(children, forEachFunc, forEachContext) {
<ide> *
<ide> * See https://reactjs.org/docs/react-api.html#reactchildrentoarray
<ide> */
<del>function toArray(children) {
<add>function toArray(children: ?ReactNodeList): Array<React$Node> {
<ide> return mapChildren(children, child => child) || [];
<ide> }
<ide>
<ide> function toArray(children) {
<ide> * @return {ReactElement} The first and only `ReactElement` contained in the
<ide> * structure.
<ide> */
<del>function onlyChild(children) {
<add>function onlyChild<T>(children: T): T {
<ide> invariant(
<ide> isValidElement(children),
<ide> 'React.Children.only expected to receive a single React element child.',
<ide><path>packages/react/src/__tests__/ReactChildren-test.js
<ide> describe('ReactChildren', () => {
<ide> ]);
<ide> });
<ide>
<add> it('should combine keys when map returns an array', () => {
<add> const instance = (
<add> <div>
<add> <div key="a" />
<add> {false}
<add> <div key="b" />
<add> <p />
<add> </div>
<add> );
<add> const mappedChildren = React.Children.map(
<add> instance.props.children,
<add> // Try a few things: keyed, unkeyed, hole, and a cloned element.
<add> kid => [
<add> <span key="x" />,
<add> null,
<add> <span key="y" />,
<add> kid,
<add> kid && React.cloneElement(kid, {key: 'z'}),
<add> <hr />,
<add> ],
<add> );
<add> expect(mappedChildren.length).toBe(18);
<add>
<add> // <div key="a">
<add> expect(mappedChildren[0].type).toBe('span');
<add> expect(mappedChildren[0].key).toBe('.$a/.$x');
<add> expect(mappedChildren[1].type).toBe('span');
<add> expect(mappedChildren[1].key).toBe('.$a/.$y');
<add> expect(mappedChildren[2].type).toBe('div');
<add> expect(mappedChildren[2].key).toBe('.$a/.$a');
<add> expect(mappedChildren[3].type).toBe('div');
<add> expect(mappedChildren[3].key).toBe('.$a/.$z');
<add> expect(mappedChildren[4].type).toBe('hr');
<add> expect(mappedChildren[4].key).toBe('.$a/.5');
<add>
<add> // false
<add> expect(mappedChildren[5].type).toBe('span');
<add> expect(mappedChildren[5].key).toBe('.1/.$x');
<add> expect(mappedChildren[6].type).toBe('span');
<add> expect(mappedChildren[6].key).toBe('.1/.$y');
<add> expect(mappedChildren[7].type).toBe('hr');
<add> expect(mappedChildren[7].key).toBe('.1/.5');
<add>
<add> // <div key="b">
<add> expect(mappedChildren[8].type).toBe('span');
<add> expect(mappedChildren[8].key).toBe('.$b/.$x');
<add> expect(mappedChildren[9].type).toBe('span');
<add> expect(mappedChildren[9].key).toBe('.$b/.$y');
<add> expect(mappedChildren[10].type).toBe('div');
<add> expect(mappedChildren[10].key).toBe('.$b/.$b');
<add> expect(mappedChildren[11].type).toBe('div');
<add> expect(mappedChildren[11].key).toBe('.$b/.$z');
<add> expect(mappedChildren[12].type).toBe('hr');
<add> expect(mappedChildren[12].key).toBe('.$b/.5');
<add>
<add> // <p>
<add> expect(mappedChildren[13].type).toBe('span');
<add> expect(mappedChildren[13].key).toBe('.3/.$x');
<add> expect(mappedChildren[14].type).toBe('span');
<add> expect(mappedChildren[14].key).toBe('.3/.$y');
<add> expect(mappedChildren[15].type).toBe('p');
<add> expect(mappedChildren[15].key).toBe('.3/.3');
<add> expect(mappedChildren[16].type).toBe('p');
<add> expect(mappedChildren[16].key).toBe('.3/.$z');
<add> expect(mappedChildren[17].type).toBe('hr');
<add> expect(mappedChildren[17].key).toBe('.3/.5');
<add> });
<add>
<ide> it('should throw on object', () => {
<ide> expect(function() {
<ide> React.Children.forEach({a: 1, b: 2}, function() {}, null); | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.