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 | move dependency logic out of generated methods | ea8181b65637af65db5bb834f1c86df57969516e | <ide><path>activerecord/lib/active_record/associations/belongs_to_association.rb
<ide> module ActiveRecord
<ide> # = Active Record Belongs To Associations
<ide> module Associations
<ide> class BelongsToAssociation < SingularAssociation #:nodoc:
<add>
<add> def handle_dependency
<add> target.send(options[:dependent]) if load_target
<add> end
<add>
<ide> def replace(record)
<ide> raise_on_type_mismatch(record) if record
<ide>
<ide><path>activerecord/lib/active_record/associations/builder/association.rb
<ide> def validate_dependent_option(valid_options)
<ide> )
<ide> end
<ide> end
<del>
<del> def define_restrict_with_exception_dependency_method
<del> name = self.name
<del> mixin.redefine_method(dependency_method_name) do
<del> has_one_macro = association(name).reflection.macro == :has_one
<del> if has_one_macro ? !send(name).nil? : send(name).exists?
<del> raise ActiveRecord::DeleteRestrictionError.new(name)
<del> end
<del> end
<del> end
<del> alias define_restrict_dependency_method define_restrict_with_exception_dependency_method
<del>
<del> def define_restrict_with_error_dependency_method
<del> name = self.name
<del> mixin.redefine_method(dependency_method_name) do
<del> has_one_macro = association(name).reflection.macro == :has_one
<del> if has_one_macro ? !send(name).nil? : send(name).exists?
<del> key = has_one_macro ? "one" : "many"
<del> errors.add(:base, :"restrict_dependent_destroy.#{key}",
<del> :record => self.class.human_attribute_name(name).downcase)
<del> false
<del> end
<del> end
<del> end
<ide> end
<ide> end
<ide><path>activerecord/lib/active_record/associations/builder/belongs_to.rb
<ide> def configure_dependency
<ide> if dependent = options[:dependent]
<ide> validate_dependent_option [:destroy, :delete]
<ide>
<del> method_name = "belongs_to_dependent_#{dependent}_for_#{name}"
<ide> model.send(:class_eval, <<-eoruby, __FILE__, __LINE__ + 1)
<del> def #{method_name}
<del> association = #{name}
<del> association.#{dependent} if association
<add> def #{dependency_method_name}
<add> association(:#{name}).handle_dependency
<ide> end
<ide> eoruby
<del> model.after_destroy method_name
<add>
<add> model.after_destroy dependency_method_name
<ide> end
<ide> end
<add>
<add> def dependency_method_name
<add> "belongs_to_dependent_for_#{name}"
<add> end
<ide> end
<ide> end
<ide><path>activerecord/lib/active_record/associations/builder/has_many.rb
<ide> def build
<ide> def configure_dependency
<ide> if dependent = options[:dependent]
<ide> validate_dependent_option [:destroy, :delete_all, :nullify, :restrict, :restrict_with_error, :restrict_with_exception]
<del> send("define_#{dependent}_dependency_method")
<del> model.before_destroy dependency_method_name
<del> end
<del> end
<ide>
<del> def define_destroy_dependency_method
<del> name = self.name
<del> mixin.redefine_method(dependency_method_name) do
<del> send(name).each do |o|
<del> # No point in executing the counter update since we're going to destroy the parent anyway
<del> o.mark_for_destruction
<add> name = self.name
<add> mixin.redefine_method(dependency_method_name) do
<add> association(name).handle_dependency
<ide> end
<ide>
<del> send(name).delete_all
<del> end
<del> end
<del>
<del> def define_delete_all_dependency_method
<del> name = self.name
<del> mixin.redefine_method(dependency_method_name) do
<del> association(name).delete_all
<del> end
<del> end
<del>
<del> def define_nullify_dependency_method
<del> name = self.name
<del> mixin.redefine_method(dependency_method_name) do
<del> send(name).delete_all
<add> model.before_destroy dependency_method_name
<ide> end
<ide> end
<ide>
<ide><path>activerecord/lib/active_record/associations/builder/has_one.rb
<ide> def build
<ide> def configure_dependency
<ide> if dependent = options[:dependent]
<ide> validate_dependent_option [:destroy, :delete, :nullify, :restrict, :restrict_with_error, :restrict_with_exception]
<del> send("define_#{dependent}_dependency_method")
<del> model.before_destroy dependency_method_name
<del> end
<del> end
<ide>
<del> def define_destroy_dependency_method
<del> name = self.name
<del> mixin.redefine_method(dependency_method_name) do
<del> association(name).delete
<add> name = self.name
<add> mixin.redefine_method(dependency_method_name) do
<add> association(name).handle_dependency
<add> end
<add>
<add> model.before_destroy dependency_method_name
<ide> end
<ide> end
<del> alias :define_delete_dependency_method :define_destroy_dependency_method
<del> alias :define_nullify_dependency_method :define_destroy_dependency_method
<ide>
<ide> def dependency_method_name
<del> "has_one_dependent_#{options[:dependent]}_for_#{name}"
<add> "has_one_dependent_for_#{name}"
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/lib/active_record/associations/has_many_association.rb
<ide> module Associations
<ide> # is provided by its child HasManyThroughAssociation.
<ide> class HasManyAssociation < CollectionAssociation #:nodoc:
<ide>
<add> def handle_dependency
<add> case options[:dependent]
<add> when :restrict, :restrict_with_exception
<add> raise ActiveRecord::DeleteRestrictionError.new(reflection.name) unless empty?
<add>
<add> when :restrict_with_error
<add> unless empty?
<add> record = klass.human_attribute_name(reflection.name).downcase
<add> owner.errors.add(:base, :"restrict_dependent_destroy.many", record: record)
<add> false
<add> end
<add>
<add> else
<add> if options[:dependent] == :destroy
<add> # No point in executing the counter update since we're going to destroy the parent anyway
<add> load_target.each(&:mark_for_destruction)
<add> end
<add>
<add> delete_all
<add> end
<add> end
<add>
<ide> def insert_record(record, validate = true, raise = false)
<ide> set_owner_attributes(record)
<ide>
<ide><path>activerecord/lib/active_record/associations/has_one_association.rb
<ide> module ActiveRecord
<ide> # = Active Record Belongs To Has One Association
<ide> module Associations
<ide> class HasOneAssociation < SingularAssociation #:nodoc:
<add>
<add> def handle_dependency
<add> case options[:dependent]
<add> when :restrict, :restrict_with_exception
<add> raise ActiveRecord::DeleteRestrictionError.new(reflection.name) if load_target
<add>
<add> when :restrict_with_error
<add> if load_target
<add> record = klass.human_attribute_name(reflection.name).downcase
<add> owner.errors.add(:base, :"restrict_dependent_destroy.one", record: record)
<add> false
<add> end
<add>
<add> else
<add> delete
<add> end
<add> end
<add>
<ide> def replace(record, save = true)
<ide> raise_on_type_mismatch(record) if record
<ide> load_target | 7 |
Text | Text | use code markup/markdown in headers | fe4a7a21833dac765739456a9ae18cd1613bacc1 | <ide><path>doc/api/https.md
<ide> HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a
<ide> separate module.
<ide>
<del>## Class: https.Agent
<add>## Class: `https.Agent`
<ide> <!-- YAML
<ide> added: v0.4.5
<ide> changes:
<ide> changes:
<ide> An [`Agent`][] object for HTTPS similar to [`http.Agent`][]. See
<ide> [`https.request()`][] for more information.
<ide>
<del>### new Agent(\[options\])
<add>### `new Agent([options])`
<ide> <!-- YAML
<ide> changes:
<ide> - version: v12.5.0
<ide> changes:
<ide>
<ide> See [`Session Resumption`][] for information about TLS session reuse.
<ide>
<del>#### Event: 'keylog'
<add>#### Event: `'keylog'`
<ide> <!-- YAML
<ide> added: v13.2.0
<ide> -->
<ide> https.globalAgent.on('keylog', (line, tlsSocket) => {
<ide> });
<ide> ```
<ide>
<del>## Class: https.Server
<add>## Class: `https.Server`
<ide> <!-- YAML
<ide> added: v0.3.4
<ide> -->
<ide> added: v0.3.4
<ide>
<ide> See [`http.Server`][] for more information.
<ide>
<del>### server.close(\[callback\])
<add>### `server.close([callback])`
<ide> <!-- YAML
<ide> added: v0.1.90
<ide> -->
<ide> added: v0.1.90
<ide>
<ide> See [`server.close()`][`http.close()`] from the HTTP module for details.
<ide>
<del>### server.headersTimeout
<add>### `server.headersTimeout`
<ide> <!-- YAML
<ide> added: v11.3.0
<ide> -->
<ide> added: v11.3.0
<ide>
<ide> See [`http.Server#headersTimeout`][].
<ide>
<del>### server.listen()
<add>### `server.listen()`
<ide>
<ide> Starts the HTTPS server listening for encrypted connections.
<ide> This method is identical to [`server.listen()`][] from [`net.Server`][].
<ide>
<del>### server.maxHeadersCount
<add>### `server.maxHeadersCount`
<ide>
<ide> * {number} **Default:** `2000`
<ide>
<ide> See [`http.Server#maxHeadersCount`][].
<ide>
<del>### server.setTimeout(\[msecs\]\[, callback\])
<add>### `server.setTimeout([msecs][, callback])`
<ide> <!-- YAML
<ide> added: v0.11.2
<ide> -->
<ide> added: v0.11.2
<ide>
<ide> See [`http.Server#setTimeout()`][].
<ide>
<del>### server.timeout
<add>### `server.timeout`
<ide> <!-- YAML
<ide> added: v0.11.2
<ide> -->
<ide> added: v0.11.2
<ide>
<ide> See [`http.Server#timeout`][].
<ide>
<del>### server.keepAliveTimeout
<add>### `server.keepAliveTimeout`
<ide> <!-- YAML
<ide> added: v8.0.0
<ide> -->
<ide> added: v8.0.0
<ide>
<ide> See [`http.Server#keepAliveTimeout`][].
<ide>
<del>## https.createServer(\[options\]\[, requestListener\])
<add>## `https.createServer([options][, requestListener])`
<ide> <!-- YAML
<ide> added: v0.3.4
<ide> -->
<ide> https.createServer(options, (req, res) => {
<ide> }).listen(8000);
<ide> ```
<ide>
<del>## https.get(options\[, callback\])
<del>## https.get(url\[, options\]\[, callback\])
<add>## `https.get(options[, callback])`
<add>## `https.get(url[, options][, callback])`
<ide> <!-- YAML
<ide> added: v0.3.6
<ide> changes:
<ide> https.get('https://encrypted.google.com/', (res) => {
<ide> });
<ide> ```
<ide>
<del>## https.globalAgent
<add>## `https.globalAgent`
<ide> <!-- YAML
<ide> added: v0.5.9
<ide> -->
<ide>
<ide> Global instance of [`https.Agent`][] for all HTTPS client requests.
<ide>
<del>## https.request(options\[, callback\])
<del>## https.request(url\[, options\]\[, callback\])
<add>## `https.request(options[, callback])`
<add>## `https.request(url[, options][, callback])`
<ide> <!-- YAML
<ide> added: v0.3.6
<ide> changes: | 1 |
Python | Python | improve announce tool | a000f9bc517a7334dd3f3fce5ef3c593910d42eb | <ide><path>tools/announce.py
<ide> names contributed a patch for the first time.
<ide> """
<ide>
<add>pull_request_msg =\
<add>u"""
<add>A total of %d pull requests were merged for this release.
<add>"""
<ide>
<ide> def get_authors(revision_range):
<ide> pat = u'.*\\t(.*)\\n'
<ide> lst_release, cur_release = [r.strip() for r in revision_range.split('..')]
<ide>
<add> # authors, in current release and previous to current release.
<ide> cur = set(re.findall(pat, this_repo.git.shortlog('-s', revision_range)))
<ide> pre = set(re.findall(pat, this_repo.git.shortlog('-s', lst_release)))
<add>
<add> # Homu is the author of auto merges, clean him out.
<add> cur.discard('Homu')
<add> pre.discard('Homu')
<add>
<add> # Append '+' to new authors.
<ide> authors = [s + u' +' for s in cur - pre] + [s for s in cur & pre]
<ide> authors.sort()
<ide> return authors
<ide>
<ide>
<del>def get_prs(repo, revision_range):
<del> # get pull request numbers from merges
<add>def get_pull_requests(repo, revision_range):
<add> prnums = []
<add>
<add> # From regular merges
<ide> merges = this_repo.git.log(
<ide> '--oneline', '--merges', revision_range)
<ide> issues = re.findall(u"Merge pull request \#(\d*)", merges)
<del> merge_prnums = [int(s) for s in issues]
<add> prnums.extend(int(s) for s in issues)
<add>
<add> # From Homu merges (Auto merges)
<add> issues = re. findall(u"Auto merge of \#(\d*)", merges)
<add> prnums.extend(int(s) for s in issues)
<ide>
<del> # get pull request numbers from fast forward squash-merges
<add> # From fast forward squash-merges
<ide> commits = this_repo.git.log(
<ide> '--oneline', '--no-merges', '--first-parent', revision_range)
<ide> issues = re.findall(u'.*\(\#(\d+)\)\n', commits)
<del> squash_prnums = [int(s) for s in issues]
<add> prnums.extend(int(s) for s in issues)
<ide>
<ide> # get PR data from github repo
<del> prs = [repo.get_pull(n) for n in sorted(merge_prnums + squash_prnums)]
<add> prnums.sort()
<add> prs = [repo.get_pull(n) for n in prnums]
<ide> return prs
<ide>
<ide>
<ide> def main(token, revision_range):
<ide> print()
<ide> print(heading)
<ide> print(u"-"*len(heading))
<del> print()
<add> print(author_msg % len(authors))
<add>
<ide> for s in authors:
<ide> print(u'- ' + s)
<del> print(author_msg % len(authors))
<ide>
<ide> # document pull requests
<add> pull_requests = get_pull_requests(github_repo, revision_range)
<ide> heading = u"Pull requests merged for {0}".format(cur_release)
<ide> print()
<ide> print(heading)
<ide> print(u"-"*len(heading))
<del> print()
<del> for pull in get_prs(github_repo, revision_range):
<add> print(pull_request_msg % len(pull_requests))
<add>
<add> for pull in pull_requests:
<ide> pull_msg = u"- `#{0} <{1}>`__: {2}"
<ide> title = re.sub(u"\s+", u" ", pull.title.strip())
<ide> if len(title) > 60: | 1 |
Mixed | Ruby | improve a dump of the primary key support | 3628025c0dea3e08ea386700ec5eea27a26ce5d6 | <ide><path>activerecord/CHANGELOG.md
<add>* Improve a dump of the primary key support. If it is not a default primary key,
<add> correctly dump the type and options.
<add>
<add> Fixes #14169, #16599.
<add>
<add> *Ryuta Kamizono*
<add>
<ide> * Provide `:touch` option to `save()` to accommodate saving without updating
<ide> timestamps.
<ide>
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_dumper.rb
<ide> def column_spec(column)
<ide> spec
<ide> end
<ide>
<add> def column_spec_for_primary_key(column)
<add> return if column.type == :integer
<add> spec = { id: column.type.inspect }
<add> spec.merge!(prepare_column_options(column).delete_if { |key, _| [:name, :type].include?(key) })
<add> end
<add>
<ide> # This can be overridden on a Adapter level basis to support other
<ide> # extended datatypes (Example: Adding an array option in the
<ide> # PostgreSQLAdapter)
<ide><path>activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
<ide> def schema_creation
<ide> SchemaCreation.new self
<ide> end
<ide>
<add> def column_spec_for_primary_key(column)
<add> spec = {}
<add> if column.extra == 'auto_increment'
<add> return unless column.limit == 8
<add> spec[:id] = ':bigint'
<add> else
<add> spec[:id] = column.type.inspect
<add> spec.merge!(prepare_column_options(column).delete_if { |key, _| [:name, :type, :null].include?(key) })
<add> end
<add> spec
<add> end
<add>
<ide> class Column < ConnectionAdapters::Column # :nodoc:
<ide> attr_reader :collation, :strict, :extra
<ide>
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql/column.rb
<ide> def initialize(name, default, cast_type, sql_type = nil, null = true, default_fu
<ide>
<ide> @default_function = default_function
<ide> end
<add>
<add> def serial?
<add> default_function && default_function =~ /\Anextval\(.*\)\z/
<add> end
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
<ide> def schema_creation # :nodoc:
<ide> PostgreSQL::SchemaCreation.new self
<ide> end
<ide>
<add> def column_spec_for_primary_key(column)
<add> spec = {}
<add> if column.serial?
<add> return unless column.sql_type == 'bigint'
<add> spec[:id] = ':bigserial'
<add> elsif column.type == :uuid
<add> spec[:id] = ':uuid'
<add> spec[:default] = column.default_function.inspect
<add> else
<add> spec[:id] = column.type.inspect
<add> spec.merge!(prepare_column_options(column).delete_if { |key, _| [:name, :type, :null].include?(key) })
<add> end
<add> spec
<add> end
<add>
<ide> # Adds +:array+ option to the default set provided by the
<ide> # AbstractAdapter
<ide> def prepare_column_options(column) # :nodoc:
<ide><path>activerecord/lib/active_record/schema_dumper.rb
<ide> def table(table, stream)
<ide> if pkcol
<ide> if pk != 'id'
<ide> tbl.print %Q(, primary_key: "#{pk}")
<del> elsif pkcol.sql_type == 'bigint'
<del> tbl.print ", id: :bigserial"
<del> elsif pkcol.sql_type == 'uuid'
<del> tbl.print ", id: :uuid"
<del> tbl.print %Q(, default: #{pkcol.default_function.inspect})
<add> end
<add> pkcolspec = @connection.column_spec_for_primary_key(pkcol)
<add> if pkcolspec
<add> pkcolspec.each do |key, value|
<add> tbl.print ", #{key}: #{value}"
<add> end
<ide> end
<ide> else
<ide> tbl.print ", id: false"
<ide><path>activerecord/test/cases/primary_keys_test.rb
<ide> require "cases/helper"
<add>require 'support/schema_dumping_helper'
<ide> require 'models/topic'
<ide> require 'models/reply'
<ide> require 'models/subscriber'
<ide> def test_set_primary_key_with_no_connection
<ide> end
<ide>
<ide> class PrimaryKeyAnyTypeTest < ActiveRecord::TestCase
<add> include SchemaDumpingHelper
<add>
<ide> self.use_transactional_fixtures = false
<ide>
<ide> class Barcode < ActiveRecord::Base
<ide> def test_any_type_primary_key
<ide> assert_equal :string, column_type.type
<ide> assert_equal 42, column_type.limit
<ide> end
<add>
<add> test "schema dump primary key includes type and options" do
<add> schema = dump_table_schema "barcodes"
<add> assert_match %r{create_table "barcodes", primary_key: "code", id: :string, limit: 42}, schema
<add> end
<ide> end
<ide>
<ide> if current_adapter?(:MysqlAdapter, :Mysql2Adapter)
<ide> def test_primary_key_method_with_ansi_quotes
<ide>
<ide> if current_adapter?(:PostgreSQLAdapter, :MysqlAdapter, :Mysql2Adapter)
<ide> class PrimaryKeyBigSerialTest < ActiveRecord::TestCase
<add> include SchemaDumpingHelper
<add>
<ide> self.use_transactional_fixtures = false
<ide>
<ide> class Widget < ActiveRecord::Base
<ide> class Widget < ActiveRecord::Base
<ide> widget = Widget.create!
<ide> assert_not_nil widget.id
<ide> end
<add>
<add> test "schema dump primary key with bigserial" do
<add> schema = dump_table_schema "widgets"
<add> if current_adapter?(:PostgreSQLAdapter)
<add> assert_match %r{create_table "widgets", id: :bigserial}, schema
<add> else
<add> assert_match %r{create_table "widgets", id: :bigint}, schema
<add> end
<add> end
<ide> end
<ide> end | 7 |
Javascript | Javascript | add an author | d22e472012f1c3891ee450c8ed5b26ec75f1432d | <ide><path>examples/js/loaders/GLTFLoader.js
<ide> * @author Rich Tibbett / https://github.com/richtr
<ide> * @author mrdoob / http://mrdoob.com/
<ide> * @author Tony Parisi / http://www.tonyparisi.com/
<add> * @author Takahiro / https://github.com/takahirox
<ide> */
<ide>
<ide> THREE.GLTFLoader = ( function () { | 1 |
Ruby | Ruby | handle conflicts where links point at symlinks | 1eafe3bc354626b3d54164c263a5c57313d8eeeb | <ide><path>Library/Homebrew/keg.rb
<ide> def delete_pyc_files!
<ide> private
<ide>
<ide> def resolve_any_conflicts dst, mode
<del> # if it isn't a directory then a severe conflict is about to happen. Let
<del> # it, and the exception that is generated will message to the user about
<del> # the situation
<del> if dst.symlink? and dst.directory?
<del> src = dst.resolved_path
<add> src = dst.resolved_path
<add> # src itself may be a symlink, so check lstat to ensure we are dealing with
<add> # a directory, and not a symlink pointing at a directory (which needs to be
<add> # treated as a file). In other words, we onlly want to resolve one symlink.
<add> # If it isn't a directory, make_relative_symlink will raise an exception.
<add> if dst.symlink? && src.lstat.directory?
<ide> keg = Keg.for(src)
<ide> dst.unlink unless mode.dry_run
<ide> keg.link_dir(src, mode) { :mkpath }
<ide><path>Library/Homebrew/test/test_keg.rb
<ide> def test_symlinks_are_linked_directly
<ide> assert_predicate link.resolved_path, :symlink?
<ide> assert_predicate link.lstat, :symlink?
<ide> end
<add>
<add> def test_links_to_symlinks_are_not_removed
<add> a = HOMEBREW_CELLAR.join("a", "1.0")
<add> b = HOMEBREW_CELLAR.join("b", "1.0")
<add>
<add> a.join("lib", "example").mkpath
<add> a.join("lib", "example2").make_symlink "example"
<add> b.join("lib", "example2").mkpath
<add>
<add> Keg.new(a).link
<add>
<add> lib = HOMEBREW_PREFIX.join("lib")
<add> assert_equal 2, lib.children.length
<add> assert_raises(Keg::ConflictError) { Keg.new(b).link }
<add> assert_equal 2, lib.children.length
<add> end
<ide> end | 2 |
Mixed | Text | adjust documentation for `devel` deprecation | 1eefc4c5846a7035e7ab42435a86db12c7871a02 | <ide><path>Library/Homebrew/formula.rb
<ide> def stable(&block)
<ide> # depends_on "cairo"
<ide> # depends_on "pixman"
<ide> # end</pre>
<add> # @private
<ide> def devel(&block)
<ide> @devel ||= SoftwareSpec.new
<ide> return @devel unless block_given?
<ide> def head(val = nil, specs = {}, &block)
<ide> end
<ide>
<ide> # Additional downloads can be defined as resources and accessed in the
<del> # install method. Resources can also be defined inside a {.stable}, {.devel} or
<add> # install method. Resources can also be defined inside a {.stable} or
<ide> # {.head} block. This mechanism replaces ad-hoc "subformula" classes.
<ide> # <pre>resource "additional_files" do
<ide> # url "https://example.com/additional-stuff.tar.gz"
<ide> def deprecated_option(hash)
<ide> # sha256 "c6bc3f48ce8e797854c4b865f6a8ff969867bbcaebd648ae6fd825683e59fef2"
<ide> # end</pre>
<ide> #
<del> # Patches can be declared in stable, devel, and head blocks. This form is
<add> # Patches can be declared in stable and head blocks. This form is
<ide> # preferred over using conditionals.
<ide> # <pre>stable do
<ide> # patch do
<ide><path>docs/Formula-Cookbook.md
<ide> patch :p0 do
<ide> end
<ide> ```
<ide>
<del>[`patch`](https://rubydoc.brew.sh/Formula#patch-class_method)es can be declared in [`stable`](https://rubydoc.brew.sh/Formula#stable-class_method), [`devel`](https://rubydoc.brew.sh/Formula#devel-class_method), and [`head`](https://rubydoc.brew.sh/Formula#head-class_method) blocks. Always use a block instead of a conditional, i.e. `stable do ... end` instead of `if build.stable? then ... end`.
<add>[`patch`](https://rubydoc.brew.sh/Formula#patch-class_method)es can be declared in [`stable`](https://rubydoc.brew.sh/Formula#stable-class_method) and [`head`](https://rubydoc.brew.sh/Formula#head-class_method) blocks. Always use a block instead of a conditional, i.e. `stable do ... end` instead of `if build.stable? then ... end`.
<ide>
<ide> ```ruby
<ide> stable do
<ide> Instead of `git diff | pbcopy`, for some editors `git diff >> path/to/your/formu
<ide>
<ide> If anything isn’t clear, you can usually figure it out by `grep`ping the `$(brew --repo homebrew/core)` directory. Please submit a pull request to amend this document if you think it will help!
<ide>
<del>### Unstable versions (`devel`, `head`)
<add>### Unstable versions (`head`)
<ide>
<del>Formulae can specify alternate downloads for the upstream project’s [`head`](https://rubydoc.brew.sh/Formula#head-class_method) (`master`/`trunk`) or [`devel`](https://rubydoc.brew.sh/Formula#devel-class_method) release (unstable but not `master`/`trunk`).
<add>Formulae can specify an alternate download for the upstream project’s [`head`](https://rubydoc.brew.sh/Formula#head-class_method) (`master`/`trunk`).
<ide>
<ide> #### `head`
<ide>
<ide> class Foo < Formula
<ide> end
<ide> ```
<ide>
<del>#### `devel`
<del>
<del>The [`devel`](https://rubydoc.brew.sh/Formula#devel-class_method) spec (activated by passing `--devel`) is used for a project’s unstable releases. `devel` specs are not allowed in Homebrew/homebrew-core.
<del>
<del>A `devel` spec is specified in a block:
<del>
<del>```ruby
<del>devel do
<del> url "https://foo.com/foo-0.1.tar.gz"
<del> sha256 "85cc828a96735bdafcf29eb6291ca91bac846579bcef7308536e0c875d6c81d7"
<del>end
<del>```
<del>
<del>You can test if the [`devel`](https://rubydoc.brew.sh/Formula#devel-class_method) spec is in use with `build.devel?`.
<del>
<ide> ### Compiler selection
<ide>
<ide> Sometimes a package fails to build when using a certain compiler. Since recent [Xcode versions](Xcode.md) no longer include a GCC compiler we cannot simply force the use of GCC. Instead, the correct way to declare this is the [`fails_with`](https://rubydoc.brew.sh/Formula#fails_with-class_method) DSL method. A properly constructed [`fails_with`](https://rubydoc.brew.sh/Formula#fails_with-class_method) block documents the latest compiler build version known to cause compilation to fail, and the cause of the failure. For example:
<ide> In summary, environment variables used by a formula need to conform to these fil
<ide>
<ide> ## Updating formulae
<ide>
<del>Eventually a new version of the software will be released. In this case you should update the [`url`](https://rubydoc.brew.sh/Formula#url-class_method) and [`sha256`](https://rubydoc.brew.sh/Formula#sha256%3D-class_method). If a [`revision`](https://rubydoc.brew.sh/Formula#revision%3D-class_method) line exists outside any `bottle do` block *and* the new release is stable rather than devel, it should be removed.
<add>Eventually a new version of the software will be released. In this case you should update the [`url`](https://rubydoc.brew.sh/Formula#url-class_method) and [`sha256`](https://rubydoc.brew.sh/Formula#sha256%3D-class_method). If a [`revision`](https://rubydoc.brew.sh/Formula#revision%3D-class_method) line exists outside any `bottle do` block it should be removed.
<ide>
<ide> Leave the `bottle do ... end` block as-is; our CI system will update it when we pull your change.
<ide>
<ide><path>docs/How-To-Open-a-Homebrew-Pull-Request.md
<ide> To make a new branch and submit it for review, create a GitHub pull request with
<ide> brew audit --strict <CHANGED_FORMULA>
<ide> ```
<ide> 6. [Make a separate commit](Formula-Cookbook.md#commit) for each changed formula with `git add` and `git commit`.
<del> * Please note that our preferred commit message format for simple version updates is "`<FORMULA_NAME> <NEW_VERSION>`", e.g. "`source-highlight 3.1.8`" but `devel` version updates should have the commit message suffixed with `(devel)`, e.g. "`nginx 1.9.1 (devel)`". If updating both `stable` and `devel`, the format should be a concatenation of these two forms, e.g. "`x264 r2699, r2705 (devel)`".
<add> * Please note that our preferred commit message format for simple version updates is "`<FORMULA_NAME> <NEW_VERSION>`", e.g. "`source-highlight 3.1.8`".
<ide> 7. Upload your branch of new commits to your fork:
<ide> ```sh
<ide> git push --set-upstream <YOUR_USERNAME> <YOUR_BRANCH_NAME> | 3 |
Javascript | Javascript | move actiontypes to a private export | b62248bdb46ea2491d9bf4d7d4cc88849d49176d | <ide><path>src/combineReducers.js
<del>import { ActionTypes } from './createStore'
<add>import ActionTypes from './utils/actionTypes'
<ide> import isPlainObject from 'lodash/isPlainObject'
<ide> import warning from './utils/warning'
<ide>
<ide><path>src/createStore.js
<ide> import isPlainObject from 'lodash/isPlainObject'
<ide> import $$observable from 'symbol-observable'
<ide>
<del>/**
<del> * These are private action types reserved by Redux.
<del> * For any unknown actions, you must return the current state.
<del> * If the current state is undefined, you must return the initial state.
<del> * Do not reference these action types directly in your code.
<del> */
<del>export const ActionTypes = {
<del> INIT: '@@redux/INIT'
<del>}
<add>import ActionTypes from './utils/actionTypes'
<ide>
<ide> /**
<ide> * Creates a Redux store that holds the state tree.
<ide><path>src/utils/actionTypes.js
<add>/**
<add> * These are private action types reserved by Redux.
<add> * For any unknown actions, you must return the current state.
<add> * If the current state is undefined, you must return the initial state.
<add> * Do not reference these action types directly in your code.
<add> */
<add>var ActionTypes = {
<add> INIT: '@@redux/INIT'
<add>}
<add>
<add>export default ActionTypes
<ide><path>test/combineReducers.spec.js
<ide> /* eslint-disable no-console */
<ide> import { combineReducers } from '../src'
<del>import createStore, { ActionTypes } from '../src/createStore'
<add>import createStore from '../src/createStore'
<add>import ActionTypes from '../src/utils/actionTypes'
<ide>
<ide> describe('Utils', () => {
<ide> describe('combineReducers', () => { | 4 |
Java | Java | return sslinfo only if x509certificate[] present | 1e4a3a2370b9ded44a62155aea59c0d81c36149f | <ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/DefaultSslInfo.java
<ide> final class DefaultSslInfo implements SslInfo {
<ide> private final X509Certificate[] peerCertificates;
<ide>
<ide>
<del> DefaultSslInfo(String sessionId, X509Certificate[] peerCertificates) {
<add> DefaultSslInfo(@Nullable String sessionId, X509Certificate[] peerCertificates) {
<ide> Assert.notNull(peerCertificates, "No SSL certificates");
<ide> this.sessionId = sessionId;
<ide> this.peerCertificates = peerCertificates;
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/ServletServerHttpRequest.java
<ide> */
<ide> class ServletServerHttpRequest extends AbstractServerHttpRequest {
<ide>
<del> private static final String X509_CERTIFICATE_ATTRIBUTE = "javax.servlet.request.X509Certificate";
<del>
<del> private static final String SSL_SESSION_ID_ATTRIBUTE = "javax.servlet.request.ssl_session_id";
<del>
<ide> static final DataBuffer EOF_BUFFER = new DefaultDataBufferFactory().allocateBuffer(0);
<ide>
<ide>
<ide> public InetSocketAddress getRemoteAddress() {
<ide>
<ide> @Nullable
<ide> protected SslInfo initSslInfo() {
<del> if (!this.request.isSecure()) {
<del> return null;
<del> }
<del> return new DefaultSslInfo(
<del> (String) request.getAttribute(SSL_SESSION_ID_ATTRIBUTE),
<del> (X509Certificate[]) request.getAttribute(X509_CERTIFICATE_ATTRIBUTE));
<add> X509Certificate[] certificates = getX509Certificates();
<add> return certificates != null ? new DefaultSslInfo(getSslSessionId(), certificates) : null;
<add> }
<add>
<add> @Nullable
<add> private String getSslSessionId() {
<add> return (String) this.request.getAttribute("javax.servlet.request.ssl_session_id");
<add> }
<add>
<add> @Nullable
<add> private X509Certificate[] getX509Certificates() {
<add> String name = "javax.servlet.request.X509Certificate";
<add> return (X509Certificate[]) this.request.getAttribute(name);
<ide> }
<ide>
<ide> @Override | 2 |
PHP | PHP | fix errors in mailer | 9aeded6ff52471144c039c0400bca71d42953d2e | <ide><path>src/Mailer/TransportRegistry.php
<ide> protected function _throwMissingClassError(string $class, ?string $plugin): void
<ide> protected function _create($class, string $alias, array $config): AbstractTransport
<ide> {
<ide> $instance = null;
<del>
<ide> if (is_object($class)) {
<ide> $instance = $class;
<del> }
<del>
<del> if (!$instance) {
<add> } else {
<ide> $instance = new $class($config);
<ide> }
<ide> | 1 |
PHP | PHP | remove dead code | eec011e99e071b7460ded64e6253283d342bd1ad | <ide><path>src/TestSuite/TestCase.php
<ide> public function tearDown() {
<ide> Configure::clear();
<ide> Configure::write($this->_configure);
<ide> }
<del> if (isset($_GET['debug']) && $_GET['debug']) {
<del> ob_flush();
<del> }
<del> }
<del>
<del>/**
<del> * See Cake\TestSuite\TestSuiteDispatcher::date()
<del> *
<del> * @param string $format format to be used.
<del> * @return string
<del> */
<del> public static function date($format = 'Y-m-d H:i:s') {
<del> return TestSuiteDispatcher::date($format);
<ide> }
<ide>
<ide> /** | 1 |
Text | Text | add 2.8.0-beta.1 to changelog.md | 14eb40ce1d55faa282f3da90dbdcd227fd16db88 | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### 2.8.0-beta.1 (July 25, 2016)
<add>
<add>- [#13757](https://github.com/emberjs/ember.js/pull/13757) / [#13773](https://github.com/emberjs/ember.js/pull/13773) [CLEANUP] Remove legacy view layer features.
<add>- [#13819](https://github.com/emberjs/ember.js/pull/13819) [DOC] Add documentation for container (getOwner, etc.)
<add>- [#13855](https://github.com/emberjs/ember.js/pull/13855) [FEATURE ember-string-ishtmlsafe] Enable by defaut.
<add>- [#13855](https://github.com/emberjs/ember.js/pull/13855) [FEATURE ember-application-engines] Enable by default.
<add>- [#13855](https://github.com/emberjs/ember.js/pull/13855) [FEATURE ember-runtime-enumerable-includes] Enable by default.
<add>- [#13855](https://github.com/emberjs/ember.js/pull/13855) [FEATURE ember-testing-check-waiters] Enable by default.
<add>
<ide> ### 2.7.0 (July 25, 2016)
<ide>
<ide> - [#13764](https://github.com/emberjs/ember.js/pull/13764) [BUGFIX] Keep rest positional parameters when nesting contextual components if needed. | 1 |
PHP | PHP | move the location of some storage files | cfa7fcb60fd60b3870606c910559e67186a7a8a8 | <ide><path>src/Illuminate/Foundation/Application.php
<ide> public function runningUnitTests()
<ide> */
<ide> public function registerConfiguredProviders()
<ide> {
<del> $manifestPath = $this->storagePath().DIRECTORY_SEPARATOR.'framework'.DIRECTORY_SEPARATOR.'services.json';
<add> $manifestPath = $this->basePath().'/vendor/services.json';
<ide>
<ide> (new ProviderRepository($this, new Filesystem, $manifestPath))
<ide> ->load($this->config['app.providers']);
<ide> public function routesAreCached()
<ide> */
<ide> public function getCachedRoutesPath()
<ide> {
<del> return $this['path.storage'].DIRECTORY_SEPARATOR.'framework'.DIRECTORY_SEPARATOR.'routes.php';
<add> return $this->basePath().'/vendor/routes.php';
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Foundation/Console/ClearCompiledCommand.php
<ide> class ClearCompiledCommand extends Command {
<ide> */
<ide> public function fire()
<ide> {
<del> if (file_exists($path = $this->laravel->storagePath().'/framework/compiled.php'))
<add> if (file_exists($path = $this->laravel->basePath().'/vendor/compiled.php'))
<ide> {
<ide> @unlink($path);
<ide> }
<ide>
<del> if (file_exists($path = $this->laravel->storagePath().'/framework/services.json'))
<add> if (file_exists($path = $this->laravel->basePath().'/vendor/services.json'))
<ide> {
<ide> @unlink($path);
<ide> }
<ide><path>src/Illuminate/Foundation/Console/OptimizeCommand.php
<ide> protected function compileClasses()
<ide> {
<ide> $this->registerClassPreloaderCommand();
<ide>
<del> $outputPath = $this->laravel['path.storage'].'/framework/compiled.php';
<add> $outputPath = $this->laravel['path.base'].'/vendor/compiled.php';
<ide>
<ide> $this->callSilent('compile', array(
<ide> '--config' => implode(',', $this->getClassFiles()), | 3 |
Javascript | Javascript | fix 0.15 compatibility | f8335168b6257a8e908c2e9d4529134da5748fee | <ide><path>src/renderers/native/ReactNative/ReactNativeBaseComponent.js
<ide> ReactNativeBaseComponent.Mixin = {
<ide> return this;
<ide> },
<ide>
<del> construct: function(element) {
<del> this._currentElement = element;
<del> },
<del>
<ide> unmountComponent: function() {
<ide> deleteAllListeners(this._rootNodeID);
<ide> this.unmountChildren();
<ide> ReactNativeBaseComponent.Mixin = {
<ide> }
<ide> },
<ide>
<add> /**
<add> * Currently this still uses IDs for reconciliation so this can return null.
<add> *
<add> * @return {null} Null.
<add> */
<add> getNativeNode: function() {
<add> return null;
<add> },
<add>
<ide> /**
<ide> * @param {string} rootID Root ID of this subtree.
<ide> * @param {Transaction} transaction For creating/updating.
<ide><path>src/renderers/native/ReactNative/ReactNativeDefaultInjection.js
<ide> var ReactElement = require('ReactElement');
<ide> var ReactComponentEnvironment = require('ReactComponentEnvironment');
<ide> var ReactDefaultBatchingStrategy = require('ReactDefaultBatchingStrategy');
<ide> var ReactEmptyComponent = require('ReactEmptyComponent');
<del>var ReactInstanceHandles = require('ReactInstanceHandles');
<ide> var ReactNativeComponentEnvironment = require('ReactNativeComponentEnvironment');
<ide> var ReactNativeGlobalInteractionHandler = require('ReactNativeGlobalInteractionHandler');
<ide> var ReactNativeGlobalResponderHandler = require('ReactNativeGlobalResponderHandler');
<del>var ReactNativeMount = require('ReactNativeMount');
<ide> var ReactNativeTextComponent = require('ReactNativeTextComponent');
<ide> var ReactNativeComponent = require('ReactNativeComponent');
<add>var ReactSimpleEmptyComponent = require('ReactSimpleEmptyComponent');
<ide> var ReactUpdates = require('ReactUpdates');
<ide> var ResponderEventPlugin = require('ResponderEventPlugin');
<ide> var UniversalWorkerNodeHandle = require('UniversalWorkerNodeHandle');
<ide> function inject() {
<ide> * Inject module for resolving DOM hierarchy and plugin ordering.
<ide> */
<ide> EventPluginHub.injection.injectEventPluginOrder(IOSDefaultEventPluginOrder);
<del> EventPluginHub.injection.injectInstanceHandle(ReactInstanceHandles);
<ide>
<ide> ResponderEventPlugin.injection.injectGlobalResponderHandler(
<ide> ReactNativeGlobalResponderHandler
<ide> function inject() {
<ide> ReactNativeComponentEnvironment
<ide> );
<ide>
<del> var EmptyComponent = () => {
<add> var EmptyComponent = (instantiate) => {
<ide> // Can't import View at the top because it depends on React to make its composite
<ide> var View = require('View');
<del> return ReactElement.createElement(View, {
<del> collapsable: true,
<del> style: { position: 'absolute' }
<del> });
<add> return new ReactSimpleEmptyComponent(
<add> ReactElement.createElement(View, {
<add> collapsable: true,
<add> style: { position: 'absolute' }
<add> }),
<add> instantiate
<add> );
<ide> };
<del> ReactEmptyComponent.injection.injectEmptyComponent(EmptyComponent);
<ide>
<del> EventPluginUtils.injection.injectMount(ReactNativeMount);
<add> ReactEmptyComponent.injection.injectEmptyComponentFactory(EmptyComponent);
<ide>
<ide> ReactNativeComponent.injection.injectTextComponentClass(
<ide> ReactNativeTextComponent
<ide><path>src/renderers/native/ReactNative/ReactNativeEventEmitter.js
<ide> 'use strict';
<ide>
<ide> var EventPluginHub = require('EventPluginHub');
<add>var EventPluginRegistry = require('EventPluginRegistry');
<ide> var ReactEventEmitterMixin = require('ReactEventEmitterMixin');
<ide> var ReactNativeTagHandles = require('ReactNativeTagHandles');
<ide> var NodeHandle = require('NodeHandle');
<ide> var removeTouchesAtIndices = function(
<ide> */
<ide> var ReactNativeEventEmitter = merge(ReactEventEmitterMixin, {
<ide>
<del> registrationNames: EventPluginHub.registrationNameModules,
<add> registrationNames: EventPluginRegistry.registrationNameModules,
<ide>
<ide> putListener: EventPluginHub.putListener,
<ide>
<ide><path>src/renderers/native/ReactNative/createReactNativeComponentClass.js
<ide> var createReactNativeComponentClass = function(
<ide> ): ReactClass<any> {
<ide> var Constructor = function(element) {
<ide> this._currentElement = element;
<add> this._topLevelWrapper = null;
<ide>
<ide> this._rootNodeID = null;
<ide> this._renderedChildren = null; | 4 |
Ruby | Ruby | parse <css> block as code (used in engines guide) | c46374a9d949004761d71570a4d703838c694e74 | <ide><path>guides/rails_guides/textile_extensions.rb
<ide> def brush_for(code_type)
<ide> end
<ide>
<ide> def code(body)
<del> body.gsub!(%r{<(yaml|shell|ruby|erb|html|sql|plain)>(.*?)</\1>}m) do |m|
<add> body.gsub!(%r{<(yaml|shell|ruby|erb|html|sql|css|plain)>(.*?)</\1>}m) do |m|
<ide> <<HTML
<ide> <notextile>
<ide> <div class="code_container"> | 1 |
Javascript | Javascript | add test for messageport.onmessage | f5db04dcbdaf64b95bd6ca670224d2a9aec31a28 | <ide><path>test/parallel/test-worker-onmessage.js
<add>// Flags: --experimental-worker
<add>'use strict';
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const { Worker, isMainThread, parentPort } = require('worker_threads');
<add>
<add>if (isMainThread) {
<add> const w = new Worker(__filename);
<add> w.on('message', common.mustCall((message) => {
<add> assert.strictEqual(message, 4);
<add> w.terminate();
<add> }));
<add> w.postMessage(2);
<add>} else {
<add> parentPort.onmessage = common.mustCall((message) => {
<add> parentPort.postMessage(message * 2);
<add> });
<add>} | 1 |
PHP | PHP | allow easier extending of url generator | ab675d4718e7bd587ae91deb7231f90d34df5786 | <ide><path>src/Illuminate/Routing/RoutingServiceProvider.php
<ide> use Psr\Http\Message\ServerRequestInterface;
<ide> use Symfony\Bridge\PsrHttpMessage\Factory\DiactorosFactory;
<ide> use Illuminate\Contracts\View\Factory as ViewFactoryContract;
<add>use Illuminate\Contracts\Routing\UrlGenerator as UrlGeneratorContract;
<ide> use Illuminate\Contracts\Routing\ResponseFactory as ResponseFactoryContract;
<ide> use Illuminate\Routing\Contracts\ControllerDispatcher as ControllerDispatcherContract;
<ide>
<ide> protected function registerUrlGenerator()
<ide> // and all the registered routes will be available to the generator.
<ide> $app->instance('routes', $routes);
<ide>
<del> $url = new UrlGenerator(
<add> return new UrlGenerator(
<ide> $routes, $app->rebinding(
<ide> 'request', $this->requestRebinder()
<ide> ), $app['config']['app.asset_url']
<ide> );
<add> });
<ide>
<add> $this->app->extend('url', function (UrlGeneratorContract $url, $app) {
<ide> // Next we will set a few service resolvers on the URL generator so it can
<ide> // get the information it needs to function. This just provides some of
<ide> // the convenience features to this URL generator like "signed" URLs. | 1 |
Python | Python | add a toy test in inspect | a0ae03a54e4f0e7c96aa00040b95629623fd373d | <ide><path>numpy/lib/inspect.py
<ide> def stack(context=1):
<ide> def trace(context=1):
<ide> """Return a list of records for the stack below the current exception."""
<ide> return getinnerframes(sys.exc_info()[2], context)
<add>
<add>if __name__ == '__main__':
<add> import inspect
<add> def foo(x, y, z=None):
<add> return None
<add>
<add> print inspect.getargs(foo.func_code)
<add> print getargs(foo.func_code)
<add>
<add> print inspect.getargspec(foo)
<add> print getargspec(foo)
<add>
<add> print inspect.formatargspec(*inspect.getargspec(foo))
<add> print formatargspec(*getargspec(foo)) | 1 |
Go | Go | add dep to test | 65aba0c9d6a72fc89f87c328e9ca21e20bf3cf7a | <ide><path>integration-cli/docker_cli_build_test.go
<ide> func (s *DockerSuite) TestBuildEmptyStringVolume(c *check.C) {
<ide>
<ide> func TestBuildContainerWithCgroupParent(t *testing.T) {
<ide> testRequires(t, NativeExecDriver)
<add> testRequires(t, SameHostDaemon)
<ide> defer deleteImages()
<ide>
<ide> cgroupParent := "test" | 1 |
Javascript | Javascript | remove conda from nightly install widget [ci skip] | 448bfbdc30a29225547562e3f222c08565b50021 | <ide><path>website/src/widgets/quickstart-install.js
<ide> const CUDA = {
<ide> '11.0': 'cuda110',
<ide> }
<ide> const LANG_EXTRAS = ['ja'] // only for languages with models
<del>const DATA = [
<del> {
<del> id: 'os',
<del> title: 'Operating system',
<del> options: [
<del> { id: 'mac', title: 'macOS / OSX', checked: true },
<del> { id: 'windows', title: 'Windows' },
<del> { id: 'linux', title: 'Linux' },
<del> ],
<del> },
<del> {
<del> id: 'package',
<del> title: 'Package manager',
<del> options: [
<del> { id: 'pip', title: 'pip', checked: true },
<del> { id: 'conda', title: 'conda' },
<del> { id: 'source', title: 'from source' },
<del> ],
<del> },
<del> {
<del> id: 'hardware',
<del> title: 'Hardware',
<del> options: [
<del> { id: 'cpu', title: 'CPU', checked: DEFAULT_HARDWARE === 'cpu' },
<del> { id: 'gpu', title: 'GPU', checked: DEFAULT_HARDWARE == 'gpu' },
<del> ],
<del> dropdown: Object.keys(CUDA).map(id => ({ id: CUDA[id], title: `CUDA ${id}` })),
<del> defaultValue: DEFAULT_CUDA,
<del> },
<del> {
<del> id: 'config',
<del> title: 'Configuration',
<del> multiple: true,
<del> options: [
<del> {
<del> id: 'venv',
<del> title: 'virtual env',
<del> help: 'Use a virtual environment and install spaCy into a user directory',
<del> },
<del> {
<del> id: 'train',
<del> title: 'train models',
<del> help:
<del> 'Check this if you plan to train your own models with spaCy to install extra dependencies and data resources',
<del> },
<del> ],
<del> },
<del>]
<ide>
<ide> const QuickstartInstall = ({ id, title }) => {
<ide> const [train, setTrain] = useState(false)
<ide> const QuickstartInstall = ({ id, title }) => {
<ide> const pkg = nightly ? 'spacy-nightly' : 'spacy'
<ide> const models = languages.filter(({ models }) => models !== null)
<ide> const data = [
<del> ...DATA,
<add> {
<add> id: 'os',
<add> title: 'Operating system',
<add> options: [
<add> { id: 'mac', title: 'macOS / OSX', checked: true },
<add> { id: 'windows', title: 'Windows' },
<add> { id: 'linux', title: 'Linux' },
<add> ],
<add> },
<add> {
<add> id: 'package',
<add> title: 'Package manager',
<add> options: [
<add> { id: 'pip', title: 'pip', checked: true },
<add> !nightly ? { id: 'conda', title: 'conda' } : null,
<add> { id: 'source', title: 'from source' },
<add> ].filter(o => o),
<add> },
<add> {
<add> id: 'hardware',
<add> title: 'Hardware',
<add> options: [
<add> { id: 'cpu', title: 'CPU', checked: DEFAULT_HARDWARE === 'cpu' },
<add> { id: 'gpu', title: 'GPU', checked: DEFAULT_HARDWARE == 'gpu' },
<add> ],
<add> dropdown: Object.keys(CUDA).map(id => ({
<add> id: CUDA[id],
<add> title: `CUDA ${id}`,
<add> })),
<add> defaultValue: DEFAULT_CUDA,
<add> },
<add> {
<add> id: 'config',
<add> title: 'Configuration',
<add> multiple: true,
<add> options: [
<add> {
<add> id: 'venv',
<add> title: 'virtual env',
<add> help:
<add> 'Use a virtual environment and install spaCy into a user directory',
<add> },
<add> {
<add> id: 'train',
<add> title: 'train models',
<add> help:
<add> 'Check this if you plan to train your own models with spaCy to install extra dependencies and data resources',
<add> },
<add> ],
<add> },
<ide> {
<ide> id: 'models',
<ide> title: 'Trained pipelines',
<ide> const QuickstartInstall = ({ id, title }) => {
<ide> setters={setters}
<ide> showDropdown={showDropdown}
<ide> >
<del> {nightly && (
<del> <QS package="conda" comment prompt={false}>
<del> # 🚨 Nightly releases are currently only available via pip
<del> </QS>
<del> )}
<ide> <QS config="venv">python -m venv .env</QS>
<ide> <QS config="venv" os="mac">
<ide> source .env/bin/activate | 1 |
Ruby | Ruby | add audit tests for migrated audit exception lists | b0d10fdf28869e1f599e5e97ce2e9a1a8573d9a9 | <ide><path>Library/Homebrew/test/dev-cmd/audit_spec.rb
<ide> class Foo < Formula
<ide> end
<ide> end
<ide>
<add> describe "#audit_specs" do
<add> let(:throttle_list) { { throttled_formulae: { "foo" => 10 } } }
<add> let(:versioned_head_spec_list) { { versioned_head_spec_allowlist: ["foo"] } }
<add>
<add> it "allows versions with no throttle rate" do
<add> fa = formula_auditor "bar", <<~RUBY, core_tap: true, tap_audit_exceptions: throttle_list
<add> class Bar < Formula
<add> url "https://brew.sh/foo-1.0.1.tgz"
<add> end
<add> RUBY
<add>
<add> fa.audit_specs
<add> expect(fa.problems).to be_empty
<add> end
<add>
<add> it "allows major/minor versions with throttle rate" do
<add> fa = formula_auditor "foo", <<~RUBY, core_tap: true, tap_audit_exceptions: throttle_list
<add> class Foo < Formula
<add> url "https://brew.sh/foo-1.0.0.tgz"
<add> end
<add> RUBY
<add>
<add> fa.audit_specs
<add> expect(fa.problems).to be_empty
<add> end
<add>
<add> it "allows patch versions to be multiples of the throttle rate" do
<add> fa = formula_auditor "foo", <<~RUBY, core_tap: true, tap_audit_exceptions: throttle_list
<add> class Foo < Formula
<add> url "https://brew.sh/foo-1.0.10.tgz"
<add> end
<add> RUBY
<add>
<add> fa.audit_specs
<add> expect(fa.problems).to be_empty
<add> end
<add>
<add> it "doesn't allow patch versions that aren't multiples of the throttle rate" do
<add> fa = formula_auditor "foo", <<~RUBY, core_tap: true, tap_audit_exceptions: throttle_list
<add> class Foo < Formula
<add> url "https://brew.sh/foo-1.0.1.tgz"
<add> end
<add> RUBY
<add>
<add> fa.audit_specs
<add> expect(fa.problems.first[:message]).to match "should only be updated every 10 releases on multiples of 10"
<add> end
<add>
<add> it "allows non-versioned formulae to have a `HEAD` spec" do
<add> fa = formula_auditor "bar", <<~RUBY, core_tap: true, tap_audit_exceptions: versioned_head_spec_list
<add> class Bar < Formula
<add> url "https://brew.sh/foo-1.0.tgz"
<add> head "https://brew.sh/foo-1.0.tgz"
<add> end
<add> RUBY
<add>
<add> fa.audit_specs
<add> expect(fa.problems).to be_empty
<add> end
<add>
<add> it "doesn't allow versioned formulae to have a `HEAD` spec" do
<add> fa = formula_auditor "bar@1", <<~RUBY, core_tap: true, tap_audit_exceptions: versioned_head_spec_list
<add> class BarAT1 < Formula
<add> url "https://brew.sh/foo-1.0.tgz"
<add> head "https://brew.sh/foo-1.0.tgz"
<add> end
<add> RUBY
<add>
<add> fa.audit_specs
<add> expect(fa.problems.first[:message]).to match "Versioned formulae should not have a `HEAD` spec"
<add> end
<add>
<add> it "allows ersioned formulae on the allowlist to have a `HEAD` spec" do
<add> fa = formula_auditor "foo", <<~RUBY, core_tap: true, tap_audit_exceptions: versioned_head_spec_list
<add> class Foo < Formula
<add> url "https://brew.sh/foo-1.0.tgz"
<add> head "https://brew.sh/foo-1.0.tgz"
<add> end
<add> RUBY
<add>
<add> fa.audit_specs
<add> expect(fa.problems).to be_empty
<add> end
<add> end
<add>
<ide> describe "#audit_deps" do
<ide> describe "a dependency on a macOS-provided keg-only formula" do
<ide> describe "which is allowlisted" do | 1 |
Ruby | Ruby | introduce nodeexpression as parent of scalar nodes | 2d78e3a160068d7a024e30b2178084d16cea9807 | <ide><path>lib/arel/nodes.rb
<ide> # frozen_string_literal: true
<ide> # node
<ide> require 'arel/nodes/node'
<add>require 'arel/nodes/node_expression'
<ide> require 'arel/nodes/select_statement'
<ide> require 'arel/nodes/select_core'
<ide> require 'arel/nodes/insert_statement'
<ide><path>lib/arel/nodes/binary.rb
<ide> # frozen_string_literal: true
<ide> module Arel
<ide> module Nodes
<del> class Binary < Arel::Nodes::Node
<add> class Binary < Arel::Nodes::NodeExpression
<ide> attr_accessor :left, :right
<ide>
<ide> def initialize left, right
<ide><path>lib/arel/nodes/case.rb
<ide> module Arel
<ide> module Nodes
<ide> class Case < Arel::Nodes::Node
<del> include Arel::OrderPredications
<del> include Arel::Predications
<del> include Arel::AliasPredication
<del>
<ide> attr_accessor :case, :conditions, :default
<ide>
<ide> def initialize expression = nil, default = nil
<ide><path>lib/arel/nodes/casted.rb
<ide> # frozen_string_literal: true
<ide> module Arel
<ide> module Nodes
<del> class Casted < Arel::Nodes::Node # :nodoc:
<add> class Casted < Arel::Nodes::NodeExpression # :nodoc:
<ide> attr_reader :val, :attribute
<ide> def initialize val, attribute
<ide> @val = val
<ide><path>lib/arel/nodes/extract.rb
<ide> module Arel
<ide> module Nodes
<ide> class Extract < Arel::Nodes::Unary
<del> include Arel::AliasPredication
<del> include Arel::Predications
<del>
<ide> attr_accessor :field
<ide>
<ide> def initialize expr, field
<ide><path>lib/arel/nodes/false.rb
<ide> # frozen_string_literal: true
<ide> module Arel
<ide> module Nodes
<del> class False < Arel::Nodes::Node
<add> class False < Arel::Nodes::NodeExpression
<ide> def hash
<ide> self.class.hash
<ide> end
<ide><path>lib/arel/nodes/function.rb
<ide> # frozen_string_literal: true
<ide> module Arel
<ide> module Nodes
<del> class Function < Arel::Nodes::Node
<del> include Arel::Predications
<add> class Function < Arel::Nodes::NodeExpression
<ide> include Arel::WindowPredications
<del> include Arel::OrderPredications
<ide> attr_accessor :expressions, :alias, :distinct
<ide>
<ide> def initialize expr, aliaz = nil
<ide><path>lib/arel/nodes/grouping.rb
<ide> module Arel
<ide> module Nodes
<ide> class Grouping < Unary
<del> include Arel::Predications
<ide> end
<ide> end
<ide> end
<ide><path>lib/arel/nodes/node_expression.rb
<add>module Arel
<add> module Nodes
<add> class NodeExpression < Arel::Nodes::Node
<add> include Arel::Expressions
<add> include Arel::Predications
<add> include Arel::AliasPredication
<add> include Arel::OrderPredications
<add> include Arel::Math
<add> end
<add> end
<add>end
<ide><path>lib/arel/nodes/select_statement.rb
<ide> # frozen_string_literal: true
<ide> module Arel
<ide> module Nodes
<del> class SelectStatement < Arel::Nodes::Node
<add> class SelectStatement < Arel::Nodes::NodeExpression
<ide> attr_reader :cores
<ide> attr_accessor :limit, :orders, :lock, :offset, :with
<ide>
<ide><path>lib/arel/nodes/terminal.rb
<ide> # frozen_string_literal: true
<ide> module Arel
<ide> module Nodes
<del> class Distinct < Arel::Nodes::Node
<add> class Distinct < Arel::Nodes::NodeExpression
<ide> def hash
<ide> self.class.hash
<ide> end
<ide><path>lib/arel/nodes/true.rb
<ide> # frozen_string_literal: true
<ide> module Arel
<ide> module Nodes
<del> class True < Arel::Nodes::Node
<add> class True < Arel::Nodes::NodeExpression
<ide> def hash
<ide> self.class.hash
<ide> end
<ide><path>lib/arel/nodes/unary.rb
<ide> # frozen_string_literal: true
<ide> module Arel
<ide> module Nodes
<del> class Unary < Arel::Nodes::Node
<add> class Unary < Arel::Nodes::NodeExpression
<ide> attr_accessor :expr
<ide> alias :value :expr
<ide>
<ide><path>lib/arel/nodes/unary_operation.rb
<ide> module Arel
<ide> module Nodes
<ide>
<ide> class UnaryOperation < Unary
<del> include Arel::Expressions
<del> include Arel::Predications
<del> include Arel::OrderPredications
<del> include Arel::AliasPredication
<del> include Arel::Math
<del>
<ide> attr_reader :operator
<ide>
<ide> def initialize operator, operand
<ide> def initialize operand
<ide> end
<ide> end
<ide> end
<del>end
<ide>\ No newline at end of file
<add>end
<ide><path>test/test_nodes.rb
<ide> def test_every_arel_nodes_have_hash_eql_eqeq_from_same_class
<ide> node_descendants.unshift k unless k == self
<ide> end
<ide> node_descendants.delete(Arel::Nodes::Node)
<add> node_descendants.delete(Arel::Nodes::NodeExpression)
<ide>
<ide> bad_node_descendants = node_descendants.reject do |subnode|
<ide> eqeq_owner = subnode.instance_method(:==).owner | 15 |
Ruby | Ruby | convert compilerselector test to spec | ca4fba99c417437aca2efb36cc3c89e871d5f5a0 | <ide><path>Library/Homebrew/test/compiler_selector_spec.rb
<add>require "compilers"
<add>require "software_spec"
<add>
<add>describe CompilerSelector do
<add> subject { described_class.new(software_spec, versions, compilers) }
<add> let(:compilers) { [:clang, :gcc, :llvm, :gnu] }
<add> let(:software_spec) { SoftwareSpec.new }
<add> let(:cc) { :clang }
<add> let(:versions) do
<add> double(
<add> gcc_4_0_build_version: Version::NULL,
<add> gcc_build_version: Version.create("5666"),
<add> llvm_build_version: Version::NULL,
<add> clang_build_version: Version.create("425"),
<add> )
<add> end
<add>
<add> before(:each) do
<add> allow(versions).to receive(:non_apple_gcc_version) do |name|
<add> case name
<add> when "gcc-4.8" then Version.create("4.8.1")
<add> when "gcc-4.7" then Version.create("4.7.1")
<add> else Version::NULL
<add> end
<add> end
<add> end
<add>
<add> describe "#compiler" do
<add> it "raises an error if no matching compiler can be found" do
<add> software_spec.fails_with(:clang)
<add> software_spec.fails_with(:llvm)
<add> software_spec.fails_with(:gcc)
<add> software_spec.fails_with(gcc: "4.8")
<add> software_spec.fails_with(gcc: "4.7")
<add>
<add> expect { subject.compiler }.to raise_error(CompilerSelectionError)
<add> end
<add>
<add> it "defaults to cc" do
<add> expect(subject.compiler).to eq(cc)
<add> end
<add>
<add> it "returns gcc if it fails with clang" do
<add> software_spec.fails_with(:clang)
<add> expect(subject.compiler).to eq(:gcc)
<add> end
<add>
<add> it "returns clang if it fails with llvm" do
<add> software_spec.fails_with(:llvm)
<add> expect(subject.compiler).to eq(:clang)
<add> end
<add>
<add> it "returns clang if it fails with gcc" do
<add> software_spec.fails_with(:gcc)
<add> expect(subject.compiler).to eq(:clang)
<add> end
<add>
<add> it "returns clang if it fails with non-Apple gcc" do
<add> software_spec.fails_with(gcc: "4.8")
<add> expect(subject.compiler).to eq(:clang)
<add> end
<add>
<add> it "still returns gcc-4.8 if it fails with gcc without a specific version" do
<add> software_spec.fails_with(:clang)
<add> software_spec.fails_with(:gcc)
<add> expect(subject.compiler).to eq("gcc-4.8")
<add> end
<add>
<add> it "returns gcc if it fails with clang and llvm" do
<add> software_spec.fails_with(:clang)
<add> software_spec.fails_with(:llvm)
<add> expect(subject.compiler).to eq(:gcc)
<add> end
<add>
<add> it "returns clang if it fails with gcc and llvm" do
<add> software_spec.fails_with(:gcc)
<add> software_spec.fails_with(:llvm)
<add> expect(subject.compiler).to eq(:clang)
<add> end
<add>
<add> example "returns gcc if it fails with a specific gcc version" do
<add> software_spec.fails_with(:clang)
<add> software_spec.fails_with(gcc: "4.8")
<add> expect(subject.compiler).to eq(:gcc)
<add> end
<add>
<add> example "returns a lower version of gcc if it fails with the highest version" do
<add> software_spec.fails_with(:clang)
<add> software_spec.fails_with(:gcc)
<add> software_spec.fails_with(:llvm)
<add> software_spec.fails_with(gcc: "4.8")
<add> expect(subject.compiler).to eq("gcc-4.7")
<add> end
<add>
<add> it "prefers gcc" do
<add> software_spec.fails_with(:clang)
<add> software_spec.fails_with(:gcc)
<add> expect(subject.compiler).to eq("gcc-4.8")
<add> end
<add>
<add> it "raises an error when gcc is missing" do
<add> allow(versions).to receive(:gcc_build_version).and_return(Version::NULL)
<add>
<add> software_spec.fails_with(:clang)
<add> software_spec.fails_with(:llvm)
<add> software_spec.fails_with(gcc: "4.8")
<add> software_spec.fails_with(gcc: "4.7")
<add>
<add> expect { subject.compiler }.to raise_error(CompilerSelectionError)
<add> end
<add>
<add> it "raises an error when llvm and gcc are missing" do
<add> allow(versions).to receive(:gcc_build_version).and_return(Version::NULL)
<add>
<add> software_spec.fails_with(:clang)
<add> software_spec.fails_with(gcc: "4.8")
<add> software_spec.fails_with(gcc: "4.7")
<add>
<add> expect { subject.compiler }.to raise_error(CompilerSelectionError)
<add> end
<add> end
<add>end
<ide><path>Library/Homebrew/test/compiler_selector_test.rb
<del>require "testing_env"
<del>require "compilers"
<del>require "software_spec"
<del>
<del>class CompilerSelectorTests < Homebrew::TestCase
<del> class Double < SoftwareSpec
<del> def <<(cc)
<del> fails_with(cc)
<del> self
<del> end
<del> end
<del>
<del> class CompilerVersions
<del> attr_accessor :gcc_4_0_build_version, :gcc_build_version,
<del> :clang_build_version
<del>
<del> def initialize
<del> @gcc_4_0_build_version = Version::NULL
<del> @gcc_build_version = Version.create("5666")
<del> @llvm_build_version = Version::NULL
<del> @clang_build_version = Version.create("425")
<del> end
<del>
<del> def non_apple_gcc_version(name)
<del> case name
<del> when "gcc-4.8" then Version.create("4.8.1")
<del> when "gcc-4.7" then Version.create("4.7.1")
<del> else Version::NULL
<del> end
<del> end
<del> end
<del>
<del> def setup
<del> super
<del> @f = Double.new
<del> @cc = :clang
<del> @versions = CompilerVersions.new
<del> @selector = CompilerSelector.new(
<del> @f, @versions, [:clang, :gcc, :llvm, :gnu]
<del> )
<del> end
<del>
<del> def actual_cc
<del> @selector.compiler
<del> end
<del>
<del> def test_all_compiler_failures
<del> @f << :clang << :llvm << :gcc << { gcc: "4.8" } << { gcc: "4.7" }
<del> assert_raises(CompilerSelectionError) { actual_cc }
<del> end
<del>
<del> def test_no_compiler_failures
<del> assert_equal @cc, actual_cc
<del> end
<del>
<del> def test_fails_with_clang
<del> @f << :clang
<del> assert_equal :gcc, actual_cc
<del> end
<del>
<del> def test_fails_with_llvm
<del> @f << :llvm
<del> assert_equal :clang, actual_cc
<del> end
<del>
<del> def test_fails_with_gcc
<del> @f << :gcc
<del> assert_equal :clang, actual_cc
<del> end
<del>
<del> def test_fails_with_non_apple_gcc
<del> @f << { gcc: "4.8" }
<del> assert_equal :clang, actual_cc
<del> end
<del>
<del> def test_mixed_failures_1
<del> @f << :clang << :gcc
<del> assert_equal "gcc-4.8", actual_cc
<del> end
<del>
<del> def test_mixed_failures_2
<del> @f << :clang << :llvm
<del> assert_equal :gcc, actual_cc
<del> end
<del>
<del> def test_mixed_failures_3
<del> @f << :gcc << :llvm
<del> assert_equal :clang, actual_cc
<del> end
<del>
<del> def test_mixed_failures_4
<del> @f << :clang << { gcc: "4.8" }
<del> assert_equal :gcc, actual_cc
<del> end
<del>
<del> def test_mixed_failures_5
<del> @f << :clang << :gcc << :llvm << { gcc: "4.8" }
<del> assert_equal "gcc-4.7", actual_cc
<del> end
<del>
<del> def test_gcc_precedence
<del> @f << :clang << :gcc
<del> assert_equal "gcc-4.8", actual_cc
<del> end
<del>
<del> def test_missing_gcc
<del> @versions.gcc_build_version = Version::NULL
<del> @f << :clang << :llvm << { gcc: "4.8" } << { gcc: "4.7" }
<del> assert_raises(CompilerSelectionError) { actual_cc }
<del> end
<del>
<del> def test_missing_llvm_and_gcc
<del> @versions.gcc_build_version = Version::NULL
<del> @f << :clang << { gcc: "4.8" } << { gcc: "4.7" }
<del> assert_raises(CompilerSelectionError) { actual_cc }
<del> end
<del>end | 2 |
Python | Python | fix data type | bd2621583be21889aa21a763ce3ae3d8c69e4358 | <ide><path>src/transformers/modeling_utils.py
<ide> def get_extended_attention_mask(self, attention_mask: Tensor, input_shape: Tuple
<ide> seq_ids = torch.arange(seq_length, device=device)
<ide> causal_mask = seq_ids[None, None, :].repeat(batch_size, seq_length, 1) <= seq_ids[None, :, None]
<ide> # in case past_key_values are used we need to add a prefix ones mask to the causal mask
<add> # causal and attention masks must have same type with pytorch version < 1.3
<add> causal_mask = causal_mask.to(attention_mask.dtype)
<add>
<ide> if causal_mask.shape[1] < attention_mask.shape[1]:
<ide> prefix_seq_len = attention_mask.shape[1] - causal_mask.shape[1]
<ide> causal_mask = torch.cat(
<del> [torch.ones((batch_size, seq_length, prefix_seq_len), device=device), causal_mask], axis=-1
<add> [
<add> torch.ones(
<add> (batch_size, seq_length, prefix_seq_len), device=device, dtype=causal_mask.dtype
<add> ),
<add> causal_mask,
<add> ],
<add> axis=-1,
<ide> )
<del> # causal and attention masks must have same type with pytorch version < 1.3
<del> causal_mask = causal_mask.to(attention_mask.dtype)
<ide>
<ide> extended_attention_mask = causal_mask[:, None, :, :] * attention_mask[:, None, None, :]
<ide> else: | 1 |
Python | Python | add empty line | 32867f40629b3b28637215e72da8d0f902eddda4 | <ide><path>official/projects/longformer/longformer_encoder_test.py
<ide>
<ide> @keras_parameterized.run_all_keras_modes
<ide> class LongformerEncoderTest(keras_parameterized.TestCase):
<add>
<ide> @combinations.generate(combinations.combine(
<ide> attention_window=[32, 128], global_attention_size=[0, 1, 2]))
<ide> def test_encoder(self, attention_window, global_attention_size): | 1 |
Java | Java | use a timeout != 0 in invocablehandlermethodtests | 23e617160f196cd258ad36b2e908aeb58e50d340 | <ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/result/method/InvocableHandlerMethodTests.java
<ide> */
<ide> public class InvocableHandlerMethodTests {
<ide>
<add> private static final Duration TIMEOUT = Duration.ofSeconds(5);
<add>
<add>
<ide> private final MockServerWebExchange exchange = MockServerWebExchange.from(get("http://localhost:8080/path"));
<ide>
<ide> private final List<HandlerMethodArgumentResolver> resolvers = new ArrayList<>();
<ide> public void voidMonoMethodWithResponseArg() {
<ide> HandlerResult result = invokeForResult(new TestController(), method);
<ide>
<ide> assertThat(result).as("Expected no result (i.e. fully handled)").isNull();
<del> assertThat(this.exchange.getResponse().getBodyAsString().block(Duration.ZERO)).isEqualTo("body");
<add> assertThat(this.exchange.getResponse().getBodyAsString().block(TIMEOUT)).isEqualTo("body");
<ide> }
<ide>
<ide> @Test
<ide> public void voidMonoMethodWithExchangeArg() {
<ide> HandlerResult result = invokeForResult(new TestController(), method);
<ide>
<ide> assertThat(result).as("Expected no result (i.e. fully handled)").isNull();
<del> assertThat(this.exchange.getResponse().getBodyAsString().block(Duration.ZERO)).isEqualTo("body");
<add> assertThat(this.exchange.getResponse().getBodyAsString().block(TIMEOUT)).isEqualTo("body");
<ide> }
<ide>
<ide> @Test | 1 |
Javascript | Javascript | expose ecdh class | 26174fcfe1992f256b78f8053a1f2b02e545d4b1 | <ide><path>lib/crypto.js
<ide> const {
<ide> } = require('internal/crypto/util');
<ide> const Certificate = require('internal/crypto/certificate');
<ide>
<del>function createECDH(curve) {
<del> return new ECDH(curve);
<del>}
<del>
<ide> module.exports = exports = {
<ide> // Methods
<ide> _toBuf: toBuf,
<ide> module.exports = exports = {
<ide> createDecipheriv: Decipheriv,
<ide> createDiffieHellman: DiffieHellman,
<ide> createDiffieHellmanGroup: DiffieHellmanGroup,
<del> createECDH,
<add> createECDH: ECDH,
<ide> createHash: Hash,
<ide> createHmac: Hmac,
<ide> createSign: Sign,
<ide> module.exports = exports = {
<ide> Decipheriv,
<ide> DiffieHellman,
<ide> DiffieHellmanGroup,
<add> ECDH,
<ide> Hash,
<ide> Hmac,
<ide> Sign,
<ide><path>lib/internal/crypto/diffiehellman.js
<ide> DiffieHellman.prototype.setPrivateKey = function setPrivateKey(key, encoding) {
<ide>
<ide>
<ide> function ECDH(curve) {
<add> if (!(this instanceof ECDH))
<add> return new ECDH(curve);
<add>
<ide> if (typeof curve !== 'string')
<ide> throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'curve', 'string');
<ide>
<ide><path>test/parallel/test-crypto-classes.js
<ide> const TEST_CASES = {
<ide> 'Verify': ['RSA-SHA1'],
<ide> 'DiffieHellman': [1024],
<ide> 'DiffieHellmanGroup': ['modp5'],
<add> 'ECDH': ['prime256v1'],
<ide> 'Credentials': []
<ide> };
<ide> | 3 |
Text | Text | add ref docs for node label | 9594ac97ce0c6e0777716be2a35b47208d440e8e | <ide><path>docs/reference/commandline/node_update.md
<ide> Options:
<ide> --role string Role of the node (worker/manager)
<ide> ```
<ide>
<add>### Add label metadata to a node
<add>
<add>Add metadata to a swarm node using node labels. You can specify a node label as
<add>a key with an empty value:
<add>
<add>``` bash
<add>$ docker node update --label-add foo worker1
<add>```
<add>
<add>To add multiple labels to a node, pass the `--label-add` flag for each label:
<add>
<add>``` bash
<add>$ docker node update --label-add foo --label-add bar worker1
<add>```
<add>
<add>When you [create a service](service_create.md),
<add>you can use node labels as a constraint. A constraint limits the nodes where the
<add>scheduler deploys tasks for a service.
<add>
<add>For example, to add a `type` label to identify nodes where the scheduler should
<add>deploy message queue service tasks:
<add>
<add>``` bash
<add>$ docker node update --label-add type=queue worker1
<add>```
<add>
<add>The labels you set for nodes using `docker node update` apply only to the node
<add>entity within the swarm. Do not confuse them with the docker daemon labels for
<add>[dockerd]( ../../userguide/labels-custom-metadata.md#daemon-labels).
<add>
<add>For more information about labels, refer to [apply custom
<add>metadata](../../userguide/labels-custom-metadata.md).
<ide>
<ide> ## Related information
<ide>
<ide><path>docs/reference/commandline/service_create.md
<ide> $ docker service create \
<ide> ```
<ide>
<ide> For more information about labels, refer to [apply custom
<del>metadata](../../userguide/labels-custom-metadata.md)
<add>metadata](../../userguide/labels-custom-metadata.md).
<ide>
<ide> ### Set service mode
<ide>
<ide> follows:
<ide>
<ide> `engine.labels` apply to Docker Engine labels like operating system,
<ide> drivers, etc. Swarm administrators add `node.labels` for operational purposes by
<del>using the `docker node update` command.
<add>using the [`docker node update`](node_update.md) command.
<ide>
<ide> For example, the following limits tasks for the redis service to nodes where the
<ide> node type label equals queue: | 2 |
Python | Python | parse arguments from dict | 838dc06ff5a438159ac25f531d622e8f344476f5 | <ide><path>src/transformers/hf_argparser.py
<ide> def parse_json_file(self, json_file: str) -> Tuple[DataClass, ...]:
<ide> obj = dtype(**inputs)
<ide> outputs.append(obj)
<ide> return (*outputs,)
<add>
<add> def parse_dict(self, args: dict) -> Tuple[DataClass, ...]:
<add> """
<add> Alternative helper method that does not use `argparse` at all,
<add> instead uses a dict and populating the dataclass types.
<add> """
<add> outputs = []
<add> for dtype in self.dataclass_types:
<add> keys = {f.name for f in dataclasses.fields(dtype)}
<add> inputs = {k: v for k, v in args.items() if k in keys}
<add> obj = dtype(**inputs)
<add> outputs.append(obj)
<add> return (*outputs,)
<ide><path>tests/test_hf_argparser.py
<ide> def test_with_optional(self):
<ide> args = parser.parse_args("--foo 12 --bar 3.14 --baz 42 --ces a b c --des 1 2 3".split())
<ide> self.assertEqual(args, Namespace(foo=12, bar=3.14, baz="42", ces=["a", "b", "c"], des=[1, 2, 3]))
<ide>
<add> def test_parse_dict(self):
<add> parser = HfArgumentParser(BasicExample)
<add>
<add> args_dict = {
<add> "foo": 12,
<add> "bar": 3.14,
<add> "baz": "42",
<add> "flag": True,
<add> }
<add>
<add> parsed_args = parser.parse_dict(args_dict)[0]
<add> args = BasicExample(**args_dict)
<add> self.assertEqual(parsed_args, args)
<add>
<ide> def test_integration_training_args(self):
<ide> parser = HfArgumentParser(TrainingArguments)
<ide> self.assertIsNotNone(parser) | 2 |
Python | Python | fix postgresql failing on a test | a589fdff81ab36c57ff0a1003e60ee0dd55f3a88 | <ide><path>tests/modeltests/schema/tests.py
<ide> def test_creation_deletion(self):
<ide> DatabaseError,
<ide> lambda: list(Author.objects.all()),
<ide> )
<add> connection.rollback()
<ide>
<ide> @skipUnless(connection.features.supports_foreign_keys, "No FK support")
<ide> def test_fk(self): | 1 |
Javascript | Javascript | reslove urls with . and . | faa687b4be2cea71c545cc1bec631c164b608acd | <ide><path>lib/url.js
<ide> Url.prototype.resolveObject = function(relative) {
<ide> // then it must NOT get a trailing slash.
<ide> var last = srcPath.slice(-1)[0];
<ide> var hasTrailingSlash = (
<del> (result.host || relative.host) && (last === '.' || last === '..') ||
<del> last === '');
<add> (result.host || relative.host || srcPath.length > 1) &&
<add> (last === '.' || last === '..') || last === '');
<ide>
<ide> // strip single dots, resolve double dots to parent dir
<ide> // if the path tries to go above the root, `up` ends up > 0
<ide><path>test/parallel/test-url.js
<ide> var relativeTests = [
<ide> ['/foo/bar/baz/', 'quux/baz', '/foo/bar/baz/quux/baz'],
<ide> ['/foo/bar/baz', '../../../../../../../../quux/baz', '/quux/baz'],
<ide> ['/foo/bar/baz', '../../../../../../../quux/baz', '/quux/baz'],
<add> ['/foo', '.', '/'],
<add> ['/foo', '..', '/'],
<add> ['/foo/', '.', '/foo/'],
<add> ['/foo/', '..', '/'],
<add> ['/foo/bar', '.', '/foo/'],
<add> ['/foo/bar', '..', '/'],
<add> ['/foo/bar/', '.', '/foo/bar/'],
<add> ['/foo/bar/', '..', '/foo/'],
<ide> ['foo/bar', '../../../baz', '../../baz'],
<ide> ['foo/bar/', '../../../baz', '../baz'],
<ide> ['http://example.com/b//c//d;p?q#blarg', 'https:#hash2', 'https:///#hash2'], | 2 |
Javascript | Javascript | remove unused test case | 26a1916633e7e719b6bc2e39c60a7445aa163359 | <ide><path>test/configCases/parsing/harmony-reexport/webpack.config.js
<del>/** @type {import("../../../../").Configuration} */
<del>module.exports = {
<del> optimization: {
<del> usedExports: true,
<del> providedExports: true
<del> }
<del>}; | 1 |
Javascript | Javascript | reduce db calls, run in parallel | 750c9f1eabb7b6ab83e238f2eea5cd42ac17b80e | <ide><path>common/models/Access-Token.js
<ide> module.exports = AccessToken => {
<ide> AccessToken.findOne$ = Observable.fromNodeCallback(
<ide> AccessToken.findOne.bind(AccessToken)
<ide> );
<add> AccessToken.prototype.validate$ = Observable.fromNodeCallback(
<add> AccessToken.prototype.validate
<add> );
<add> AccessToken.prototype.destroy$ = Observable.fromNodeCallback(
<add> AccessToken.prototype.destroy
<add> );
<ide> });
<ide> };
<ide><path>common/models/user.js
<ide> module.exports = function(User) {
<ide> ctx.req.flash('error', {
<ide> msg: dedent`Oops, something went wrong, please try again later`
<ide> });
<add>
<add> const err = wrapHandledError(
<add> new Error('Theme is not valid.'),
<add> {
<add> Type: 'info',
<add> message: err.message
<add> }
<add> );
<ide> return ctx.res.redirect('/');
<ide> }
<ide>
<ide> module.exports = function(User) {
<ide> `);
<ide> }
<ide>
<del> // email verified will be false if the user instance has just been created
<del> const renderAuthEmail = this.emailVerified === false ?
<del> renderSignInEmail :
<del> renderSignUpEmail;
<del>
<ide> // create a temporary access token with ttl for 15 minutes
<del> return this.createAccessToken$({ ttl: 15 * 60 * 1000 })
<del> .flatMap(token => {
<del> const { id: loginToken } = token;
<del> const loginEmail = this.getEncodedEmail();
<del> const host = getServerFullURL();
<del> const mailOptions = {
<del> type: 'email',
<del> to: this.email,
<del> from: getEmailSender(),
<del> subject: 'freeCodeCamp - Authentication Request!',
<del> text: renderAuthEmail({
<del> host,
<del> loginEmail,
<del> loginToken
<del> })
<del> };
<del>
<del> return this.email.send$(mailOptions)
<del> .flatMap(() => {
<del> const emailAuthLinkTTL = token.created;
<del> return this.update$({
<del> emailAuthLinkTTL
<del> })
<del> .map(() => dedent`
<del> If you entered a valid email, a magic link is on its way.
<del> Please follow that link to sign in.
<del> `);
<del> });
<del> });
<add> return this.createAccessToken$({ ttl: 15 * 60 * 1000 });
<ide> })
<del> .catch(err => {
<del> if (err) { debug(err); }
<del> return dedent`
<del> Oops, something is not right, please try again later.
<del> `;
<del> });
<add> .flatMap(token => {
<add> // email verified will be false if the user instance
<add> // has just been created
<add> const renderAuthEmail = this.emailVerified === false ?
<add> renderSignInEmail :
<add> renderSignUpEmail;
<add> const { id: loginToken, created: emailAuthLinkTTL } = token;
<add> const loginEmail = this.getEncodedEmail();
<add> const host = getServerFullURL();
<add> const mailOptions = {
<add> type: 'email',
<add> to: this.email,
<add> from: getEmailSender(),
<add> subject: 'Login Requested - freeCodeCamp',
<add> text: renderAuthEmail({
<add> host,
<add> loginEmail,
<add> loginToken
<add> })
<add> };
<add>
<add> return Observable.combineLatest(
<add> this.email.send$(mailOptions),
<add> this.update$({ emailAuthLinkTTL })
<add> );
<add> })
<add> .map(() => dedent`
<add> If you entered a valid email, a magic link is on its way.
<add> Please follow that link to sign in.
<add> `);
<ide> };
<ide>
<ide> User.prototype.requestUpdateEmail = function requestUpdateEmail(
<ide><path>server/boot/authentication.js
<add>import _ from 'lodash';
<add>import { Observable } from 'rx';
<ide> import dedent from 'dedent';
<del>import debugFactory from 'debug';
<add>// import debugFactory from 'debug';
<add>import { isEmail } from 'validator';
<add>import { check, validationResults } from 'express-validator/check';
<add>
<add>import { ifUserRedirectTo } from '../utils/middleware';
<add>import {
<add> wrapHandledError,
<add> createValidatorErrorFormatter
<add>} from '../utils/create-handled-error.js';
<ide>
<ide> const isSignUpDisabled = !!process.env.DISABLE_SIGNUP;
<del>const debug = debugFactory('fcc:boot:auth');
<add>// const debug = debugFactory('fcc:boot:auth');
<ide>
<ide> module.exports = function enableAuthentication(app) {
<ide> // enable loopback access control authentication. see:
<ide> // loopback.io/doc/en/lb2/Authentication-authorization-and-permissions.html
<ide> app.enableAuth();
<add> const ifUserRedirect = ifUserRedirectTo();
<ide> const router = app.loopback.Router();
<ide> const api = app.loopback.Router();
<ide> const { AccessToken, User } = app.models;
<ide>
<del> router.get('/login', function(req, res) {
<del> res.redirect(301, '/signin');
<del> });
<del>
<del> router.get('/logout', function(req, res) {
<del> res.redirect(301, '/signout');
<del> });
<add> router.get('/login', (req, res) => res.redirect(301, '/signin'));
<add> router.get('/logout', (req, res) => res.redirect(301, '/signout'));
<ide>
<ide> function getEmailSignin(req, res) {
<del> if (req.user) {
<del> return res.redirect('/');
<del> }
<ide> if (isSignUpDisabled) {
<ide> return res.render('account/beta', {
<ide> title: 'New sign ups are disabled'
<ide> module.exports = function enableAuthentication(app) {
<ide> });
<ide> }
<ide>
<del> router.get('/signup', getEmailSignin);
<del> router.get('/signin', getEmailSignin);
<del> router.get('/email-signin', getEmailSignin);
<add> router.get('/signup', ifUserRedirect, getEmailSignin);
<add> router.get('/signin', ifUserRedirect, getEmailSignin);
<add> router.get('/email-signin', ifUserRedirect, getEmailSignin);
<ide>
<del> function signout(req, res) {
<add> router.get('/signout', (req, res) => {
<ide> req.logout();
<ide> res.redirect('/');
<del> }
<add> });
<ide>
<del> router.get('/signout', signout);
<ide>
<del> function getDepSignin(req, res) {
<del> if (req.user) {
<del> return res.redirect('/');
<del> }
<del> return res.render('account/deprecated-signin', {
<add> router.get(
<add> '/deprecated-signin',
<add> ifUserRedirect,
<add> (req, res) => res.render('account/deprecated-signin', {
<ide> title: 'Sign in to freeCodeCamp using a Deprecated Login'
<del> });
<del> }
<del>
<del> router.get('/deprecated-signin', getDepSignin);
<del>
<del> function invalidateAuthToken(req, res, next) {
<del> if (req.user) {
<del> return res.redirect('/');
<del> }
<del>
<del> if (!req.query || !req.query.email || !req.query.token) {
<del> req.flash('info', { msg: defaultErrorMsg });
<del> return res.redirect('/email-signin');
<del> }
<del>
<del> const authTokenId = req.query.token;
<del> const authEmailId = new Buffer(req.query.email, 'base64').toString();
<del>
<del> return AccessToken.findOne$({ where: {id: authTokenId} })
<del> .map(authToken => {
<del> if (!authToken) {
<del> req.flash('info', { msg: defaultErrorMsg });
<del> return res.redirect('/email-signin');
<del> }
<del>
<del> const userId = authToken.userId;
<del> return User.findById(userId, (err, user) => {
<del> if (err || !user || user.email !== authEmailId) {
<del> debug(err);
<del> req.flash('info', { msg: defaultErrorMsg });
<del> return res.redirect('/email-signin');
<del> }
<del> return authToken.validate((err, isValid) => {
<del> if (err) { throw err; }
<del> if (!isValid) {
<del> req.flash('info', { msg: [ 'Looks like the link you clicked has',
<del> 'expired, please request a fresh link, to sign in.'].join('')
<del> });
<del> return res.redirect('/email-signin');
<del> }
<del> return authToken.destroy((err) => {
<del> if (err) { debug(err); }
<del> next();
<del> });
<del> });
<del> });
<del> })
<del> .subscribe(
<del> () => {},
<del> next
<del> );
<del> }
<add> })
<add> );
<ide>
<ide> const defaultErrorMsg = dedent`
<ide> Oops, something is not right,
<ide> please request a fresh link to sign in / sign up.
<ide> `;
<ide>
<add> const passwordlessGetValidators = [
<add> check('email')
<add> .isBase64()
<add> .withMessage('email should be a base64 encoded string'),
<add> check('token')
<add> .exists()
<add> .withMessage('token should exist')
<add> // based on strongloop/loopback/common/models/access-token.js#L15
<add> .isLength({ min: 64, max: 64 })
<add> .withMessage('token is not the right length')
<add> ];
<add>
<ide> function getPasswordlessAuth(req, res, next) {
<del> if (req.user) {
<del> req.flash('info', {
<del> msg: 'Hey, looks like you’re already signed in.'
<del> });
<del> return res.redirect('/');
<add> const {
<add> query: {
<add> email: encodedEmail,
<add> token: authTokenId
<add> } = {}
<add> } = req;
<add> const validation = validationResults(req)
<add> .formatWith(createValidatorErrorFormatter('info', '/email-signup'));
<add>
<add> if (!validation.isEmpty()) {
<add> const errors = validation.array();
<add> return next(errors.pop());
<ide> }
<ide>
<del> if (!req.query || !req.query.email || !req.query.token) {
<del> req.flash('info', { msg: defaultErrorMsg });
<del> return res.redirect('/email-signin');
<add> const email = User.decodeEmail(encodedEmail);
<add> if (!isEmail(email)) {
<add> return next(wrapHandledError(
<add> new TypeError('decoded email is invalid'),
<add> {
<add> type: 'info',
<add> message: 'The email encoded in the link is incorrectly formatted',
<add> redirectTo: '/email-sign'
<add> }
<add> ));
<ide> }
<del>
<del> const email = new Buffer(req.query.email, 'base64').toString();
<del>
<del> return User.findOne$({ where: { email }})
<del> .map(user => {
<del>
<del> if (!user) {
<del> debug(`did not find a valid user with email: ${email}`);
<del> req.flash('info', { msg: defaultErrorMsg });
<del> return res.redirect('/email-signin');
<add> // first find
<add> return AccessToken.findOne$({ where: { id: authTokenId } })
<add> .flatMap(authToken => {
<add> if (authToken) {
<add> throw wrapHandledError(
<add> new Error(`no token found for id: ${authTokenId}`),
<add> {
<add> type: 'info',
<add> message: defaultErrorMsg,
<add> redirectTo: '/email-signin'
<add> }
<add> );
<ide> }
<del>
<add> // find user then validate and destroy email validation token
<add> // finally retun user instance
<add> return Observable.fromNodeCallback(authToken.user.bind(authToken))
<add> .flatMap(user => {
<add> if (!user) {
<add> throw wrapHandledError(
<add> new Error(`no user found for token: ${authTokenId}`),
<add> {
<add> type: 'info',
<add> message: defaultErrorMsg,
<add> redirectTo: '/email-signin'
<add> }
<add> );
<add> }
<add> if (user.email !== email) {
<add> throw wrapHandledError(
<add> new Error('user email does not match'),
<add> {
<add> type: 'info',
<add> message: defaultErrorMsg,
<add> redirectTo: '/email-signin'
<add> }
<add> );
<add> }
<add> return authToken.validate$()
<add> .map(isValid => {
<add> if (!isValid) {
<add> throw wrapHandledError(
<add> new Error('token is invalid'),
<add> {
<add> type: 'info',
<add> message: `
<add> Looks like the link you clicked has expired,
<add> please request a fresh link, to sign in.
<add> `,
<add> redirectTo: '/email-signin'
<add> }
<add> );
<add> }
<add> return authToken.destroy$();
<add> })
<add> .map(() => user);
<add> });
<add> })
<add> // at this point token has been validated and destroyed
<add> // update user and log them in
<add> .map(user => {
<ide> const emailVerified = true;
<ide> const emailAuthLinkTTL = null;
<ide> const emailVerifyTTL = null;
<del> user.update$({
<del> emailVerified, emailAuthLinkTTL, emailVerifyTTL
<add>
<add> const updateUser = user.update$({
<add> emailVerified,
<add> emailAuthLinkTTL,
<add> emailVerifyTTL
<ide> })
<del> .do((user) => {
<del> user.emailVerified = emailVerified;
<del> user.emailAuthLinkTTL = emailAuthLinkTTL;
<del> user.emailVerifyTTL = emailVerifyTTL;
<del> });
<add> .do((user) => {
<add> // update$ does not update in place
<add> // update user instance to reflect db
<add> user.emailVerified = emailVerified;
<add> user.emailAuthLinkTTL = emailAuthLinkTTL;
<add> user.emailVerifyTTL = emailVerifyTTL;
<add> });
<ide>
<del> return user.createAccessToken(
<del> { ttl: User.settings.ttl }, (err, accessToken) => {
<del> if (err) { throw err; }
<del>
<del> var config = {
<del> signed: !!req.signedCookies,
<del> maxAge: accessToken.ttl
<del> };
<del>
<del> if (accessToken && accessToken.id) {
<del> debug('setting cookies');
<del> res.cookie('access_token', accessToken.id, config);
<del> res.cookie('userId', accessToken.userId, config);
<del> }
<del>
<del> return req.logIn({
<del> id: accessToken.userId.toString() }, err => {
<del> if (err) { return next(err); }
<del>
<del> debug('user logged in');
<del>
<del> if (req.session && req.session.returnTo) {
<del> var redirectTo = req.session.returnTo;
<del> if (redirectTo === '/map-aside') {
<del> redirectTo = '/map';
<del> }
<del> return res.redirect(redirectTo);
<add> const createToken = user.createAccessToken()
<add> .do(accessToken => {
<add> const config = {
<add> signed: !!req.signedCookies,
<add> maxAge: accessToken.ttl
<add> };
<add> if (accessToken && accessToken.id) {
<add> res.cookie('access_token', accessToken.id, config);
<add> res.cookie('userId', accessToken.userId, config);
<ide> }
<del>
<del> req.flash('success', { msg:
<del> 'Success! You have signed in to your account. Happy Coding!'
<del> });
<del> return res.redirect('/');
<ide> });
<add>
<add> return Observable.combineLatest(
<add> updateUser,
<add> createToken,
<add> req.logIn(user),
<add> );
<add> })
<add> .do(() => {
<add> let redirectTo = '/';
<add>
<add> if (
<add> req.session &&
<add> req.session.returnTo
<add> ) {
<add> redirectTo = req.session.returnTo;
<add> }
<add>
<add> req.flash('success', { msg:
<add> 'Success! You have signed in to your account. Happy Coding!'
<ide> });
<del> })
<del> .subscribe(
<del> () => {},
<del> next
<del> );
<del> }
<ide>
<del> router.get('/passwordless-auth', invalidateAuthToken, getPasswordlessAuth);
<add> return res.redirect(redirectTo);
<add> })
<add> .subscribe(
<add> () => {},
<add> next
<add> );
<add> }
<ide>
<del> function postPasswordlessAuth(req, res) {
<del> if (req.user || !(req.body && req.body.email)) {
<del> return res.redirect('/');
<add> router.get(
<add> '/passwordless-auth',
<add> ifUserRedirect,
<add> passwordlessGetValidators,
<add> getPasswordlessAuth
<add> );
<add>
<add> const passwordlessPostValidators = [
<add> check('email')
<add> .isEmail()
<add> .withMessage('email is not a valid email address')
<add> ];
<add> function postPasswordlessAuth(req, res, next) {
<add> const { body: { email } = {} } = req;
<add> const validation = validationResults(req)
<add> .formatWith(createValidatorErrorFormatter('info', '/email-signup'));
<add> if (!validation.isEmpty()) {
<add> const errors = validation.array();
<add> return next(errors.pop());
<ide> }
<ide>
<del> return User.requestAuthEmail(req.body.email)
<del> .then(msg => {
<del> return res.status(200).send({ message: msg });
<del> })
<del> .catch(err => {
<del> debug(err);
<del> return res.status(200).send({ message: defaultErrorMsg });
<del> });
<add> return User.findOne$({ where: { email } })
<add> .flatMap(user => (
<add> // if no user found create new user and save to db
<add> user ? Observable.of(user) : User.create$({ email })
<add> ))
<add> .flatMap(user => user.requestAuthEmail())
<add> .do(msg => res.status(200).send({ message: msg }))
<add> .subscribe(_.noop, next);
<ide> }
<ide>
<del> api.post('/passwordless-auth', postPasswordlessAuth);
<add> api.post(
<add> '/passwordless-auth',
<add> ifUserRedirect,
<add> passwordlessPostValidators,
<add> postPasswordlessAuth
<add> );
<ide>
<ide> app.use('/:lang', router);
<ide> app.use(api);
<ide><path>server/boot/extend-request.js
<add>import _ from 'lodash';
<add>import http from 'http';
<add>import { Observable } from 'rx';
<add>import { login } from 'passport/lib/http/request';
<add>
<add>// make login polymorphic
<add>// if supplied callback it works as normal
<add>// if called without callback it returns an observable
<add>// login(user, options?, cb?) => Void|Observable
<add>function login$(...args) {
<add> if (_.isFunction(_.last(args))) {
<add> return login.apply(this, args);
<add> }
<add> return Observable.fromNodeCallback(login).apply(this, args);
<add>}
<add>
<add>module.exports = function extendRequest() {
<add> // see: jaredhanson/passport/blob/master/lib/framework/connect.js#L33
<add> http.IncomingMessage.prototype.login = login$;
<add> http.IncomingMessage.prototype.logIn = login$;
<add>};
<ide><path>server/utils/create-handled-error.js
<ide> export function wrapHandledError(err, {
<ide> err[_handledError] = { type, message, redirectTo };
<ide> return err;
<ide> }
<add>
<add>export const createValidatorErrorFormatter = (type, redirectTo) =>
<add> ({ msg }) => wrapHandledError(
<add> new Error(msg),
<add> {
<add> type,
<add> message: msg,
<add> redirectTo
<add> }
<add> );
<ide><path>server/utils/middleware.js
<ide> export function ifNotVerifiedRedirectToSettings(req, res, next) {
<ide> }
<ide> return next();
<ide> }
<add>
<add>export function ifUserRedirectTo(path = '/', status) {
<add> status = status === 302 ? 302 : 301;
<add> return (req, res, next) => {
<add> if (req.user) {
<add> return res.status(status).redirect(path);
<add> }
<add> return next();
<add> };
<add>} | 6 |
Text | Text | alphabetize error list | 14e98825a1e35f17b03aab22db52bc81e3a3ec94 | <ide><path>doc/api/errors.md
<ide> STDERR/STDOUT, and the data's length is longer than the `maxBuffer` option.
<ide> `Console` was instantiated without `stdout` stream, or `Console` has a
<ide> non-writable `stdout` or `stderr` stream.
<ide>
<del><a id="ERR_CONTEXT_NOT_INITIALIZED"></a>
<del>### `ERR_CONTEXT_NOT_INITIALIZED`
<add><a id="ERR_CONSTRUCT_CALL_INVALID"></a>
<add>### `ERR_CONSTRUCT_CALL_INVALID`
<add><!--
<add>added: v12.5.0
<add>-->
<ide>
<del>The vm context passed into the API is not yet initialized. This could happen
<del>when an error occurs (and is caught) during the creation of the
<del>context, for example, when the allocation fails or the maximum call stack
<del>size is reached when the context is created.
<add>A class constructor was called that is not callable.
<ide>
<ide> <a id="ERR_CONSTRUCT_CALL_REQUIRED"></a>
<ide> ### `ERR_CONSTRUCT_CALL_REQUIRED`
<ide>
<ide> A constructor for a class was called without `new`.
<ide>
<del><a id="ERR_CONSTRUCT_CALL_INVALID"></a>
<del>### `ERR_CONSTRUCT_CALL_INVALID`
<del><!--
<del>added: v12.5.0
<del>-->
<add><a id="ERR_CONTEXT_NOT_INITIALIZED"></a>
<add>### `ERR_CONTEXT_NOT_INITIALIZED`
<ide>
<del>A class constructor was called that is not callable.
<add>The vm context passed into the API is not yet initialized. This could happen
<add>when an error occurs (and is caught) during the creation of the
<add>context, for example, when the allocation fails or the maximum call stack
<add>size is reached when the context is created.
<ide>
<ide> <a id="ERR_CPU_USAGE"></a>
<ide> ### `ERR_CPU_USAGE`
<ide> allowed size for a `Buffer`.
<ide> An invalid symlink type was passed to the [`fs.symlink()`][] or
<ide> [`fs.symlinkSync()`][] methods.
<ide>
<del><a id="ERR_HTTP_REQUEST_TIMEOUT"></a>
<del>### `ERR_HTTP_REQUEST_TIMEOUT`
<del>
<del>The client has not sent the entire request within the allowed time.
<del>
<ide> <a id="ERR_HTTP_HEADERS_SENT"></a>
<ide> ### `ERR_HTTP_HEADERS_SENT`
<ide>
<ide> An invalid HTTP header value was specified.
<ide>
<ide> Status code was outside the regular status code range (100-999).
<ide>
<add><a id="ERR_HTTP_REQUEST_TIMEOUT"></a>
<add>### `ERR_HTTP_REQUEST_TIMEOUT`
<add>
<add>The client has not sent the entire request within the allowed time.
<add>
<ide> <a id="ERR_HTTP_SOCKET_ENCODING"></a>
<ide> ### `ERR_HTTP_SOCKET_ENCODING`
<ide>
<ide> A non-specific HTTP/2 error has occurred.
<ide> New HTTP/2 Streams may not be opened after the `Http2Session` has received a
<ide> `GOAWAY` frame from the connected peer.
<ide>
<add><a id="ERR_HTTP2_HEADER_SINGLE_VALUE"></a>
<add>### `ERR_HTTP2_HEADER_SINGLE_VALUE`
<add>
<add>Multiple values were provided for an HTTP/2 header field that was required to
<add>have only a single value.
<add>
<ide> <a id="ERR_HTTP2_HEADERS_AFTER_RESPOND"></a>
<ide> ### `ERR_HTTP2_HEADERS_AFTER_RESPOND`
<ide>
<ide> An additional headers was specified after an HTTP/2 response was initiated.
<ide>
<ide> An attempt was made to send multiple response headers.
<ide>
<del><a id="ERR_HTTP2_HEADER_SINGLE_VALUE"></a>
<del>### `ERR_HTTP2_HEADER_SINGLE_VALUE`
<del>
<del>Multiple values were provided for an HTTP/2 header field that was required to
<del>have only a single value.
<del>
<ide> <a id="ERR_HTTP2_INFO_STATUS_NOT_ALLOWED"></a>
<ide> ### `ERR_HTTP2_INFO_STATUS_NOT_ALLOWED`
<ide>
<ide> is set for the `Http2Stream`.
<ide> `http2.connect()` was passed a URL that uses any protocol other than `http:` or
<ide> `https:`.
<ide>
<del><a id="ERR_INTERNAL_ASSERTION"></a>
<del>### `ERR_INTERNAL_ASSERTION`
<del>
<del>There was a bug in Node.js or incorrect usage of Node.js internals.
<del>To fix the error, open an issue at <https://github.com/nodejs/node/issues>.
<del>
<ide> <a id="ERR_INCOMPATIBLE_OPTION_PAIR"></a>
<ide> ### `ERR_INCOMPATIBLE_OPTION_PAIR`
<ide>
<ide> before it was connected.
<ide> An API was called on the main thread that can only be used from
<ide> the worker thread.
<ide>
<add><a id="ERR_INTERNAL_ASSERTION"></a>
<add>### `ERR_INTERNAL_ASSERTION`
<add>
<add>There was a bug in Node.js or incorrect usage of Node.js internals.
<add>To fix the error, open an issue at <https://github.com/nodejs/node/issues>.
<add>
<ide> <a id="ERR_INVALID_ADDRESS_FAMILY"></a>
<ide> ### `ERR_INVALID_ADDRESS_FAMILY`
<ide>
<ide> strict compliance with the API specification (which in some cases may accept
<ide> For APIs that accept options objects, some options might be mandatory. This code
<ide> is thrown if a required option is missing.
<ide>
<add><a id="ERR_MISSING_PASSPHRASE"></a>
<add>### `ERR_MISSING_PASSPHRASE`
<add>
<add>An attempt was made to read an encrypted key without specifying a passphrase.
<add>
<add><a id="ERR_MISSING_PLATFORM_FOR_WORKER"></a>
<add>### `ERR_MISSING_PLATFORM_FOR_WORKER`
<add>
<add>The V8 platform used by this instance of Node.js does not support creating
<add>Workers. This is caused by lack of embedder support for Workers. In particular,
<add>this error will not occur with standard builds of Node.js.
<add>
<ide> <a id="ERR_MISSING_TRANSFERABLE_IN_TRANSFER_LIST"></a>
<ide> ### `ERR_MISSING_TRANSFERABLE_IN_TRANSFER_LIST`
<ide> <!-- YAML
<ide> In Node.js versions prior to REPLACEME, the error code being used here was
<ide> transferable object types has been expanded to cover more types than
<ide> `MessagePort`.
<ide>
<del><a id="ERR_MISSING_PASSPHRASE"></a>
<del>### `ERR_MISSING_PASSPHRASE`
<del>
<del>An attempt was made to read an encrypted key without specifying a passphrase.
<del>
<del><a id="ERR_MISSING_PLATFORM_FOR_WORKER"></a>
<del>### `ERR_MISSING_PLATFORM_FOR_WORKER`
<del>
<del>The V8 platform used by this instance of Node.js does not support creating
<del>Workers. This is caused by lack of embedder support for Workers. In particular,
<del>this error will not occur with standard builds of Node.js.
<del>
<ide> <a id="ERR_MODULE_NOT_FOUND"></a>
<ide> ### `ERR_MODULE_NOT_FOUND`
<ide>
<ide> A string was provided for a Subresource Integrity check, but was unable to be
<ide> parsed. Check the format of integrity attributes by looking at the
<ide> [Subresource Integrity specification][].
<ide>
<add><a id="ERR_STREAM_ALREADY_FINISHED"></a>
<add>### `ERR_STREAM_ALREADY_FINISHED`
<add>
<add>A stream method was called that cannot complete because the stream was
<add>finished.
<add>
<ide> <a id="ERR_STREAM_CANNOT_PIPE"></a>
<ide> ### `ERR_STREAM_CANNOT_PIPE`
<ide>
<ide> An attempt was made to call [`stream.pipe()`][] on a [`Writable`][] stream.
<ide> A stream method was called that cannot complete because the stream was
<ide> destroyed using `stream.destroy()`.
<ide>
<del><a id="ERR_STREAM_ALREADY_FINISHED"></a>
<del>### `ERR_STREAM_ALREADY_FINISHED`
<del>
<del>A stream method was called that cannot complete because the stream was
<del>finished.
<del>
<ide> <a id="ERR_STREAM_NULL_VALUES"></a>
<ide> ### `ERR_STREAM_NULL_VALUES`
<ide>
<ide> added: v13.3.0
<ide>
<ide> The context must be a `SecureContext`.
<ide>
<del><a id="ERR_TLS_INVALID_STATE"></a>
<del>### `ERR_TLS_INVALID_STATE`
<del><!-- YAML
<del>added:
<del> - v13.10.0
<del> - v12.17.0
<del>-->
<del>
<del>The TLS socket must be connected and securily established. Ensure the 'secure'
<del>event is emitted before continuing.
<del>
<ide> <a id="ERR_TLS_INVALID_PROTOCOL_METHOD"></a>
<ide> ### `ERR_TLS_INVALID_PROTOCOL_METHOD`
<ide>
<ide> disabled because it is insecure.
<ide>
<ide> Valid TLS protocol versions are `'TLSv1'`, `'TLSv1.1'`, or `'TLSv1.2'`.
<ide>
<add><a id="ERR_TLS_INVALID_STATE"></a>
<add>### `ERR_TLS_INVALID_STATE`
<add><!-- YAML
<add>added:
<add> - v13.10.0
<add> - v12.17.0
<add>-->
<add>
<add>The TLS socket must be connected and securily established. Ensure the 'secure'
<add>event is emitted before continuing.
<add>
<ide> <a id="ERR_TLS_PROTOCOL_VERSION_CONFLICT"></a>
<ide> ### `ERR_TLS_PROTOCOL_VERSION_CONFLICT`
<ide>
<ide> Attempting to set a TLS protocol `minVersion` or `maxVersion` conflicts with an
<ide> attempt to set the `secureProtocol` explicitly. Use one mechanism or the other.
<ide>
<add><a id="ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED"></a>
<add>### `ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED`
<add>
<add>Failed to set PSK identity hint. Hint may be too long.
<add>
<ide> <a id="ERR_TLS_RENEGOTIATION_DISABLED"></a>
<ide> ### `ERR_TLS_RENEGOTIATION_DISABLED`
<ide>
<ide> vector for denial-of-service attacks.
<ide> An attempt was made to issue Server Name Indication from a TLS server-side
<ide> socket, which is only valid from a client.
<ide>
<del><a id="ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED"></a>
<del>### `ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED`
<del>
<del>Failed to set PSK identity hint. Hint may be too long.
<del>
<ide> <a id="ERR_TRACE_EVENTS_CATEGORY_REQUIRED"></a>
<ide> ### `ERR_TRACE_EVENTS_CATEGORY_REQUIRED`
<ide> | 1 |
Javascript | Javascript | improve writable.write() performance | 43783b5b3fa0a0d477ae34aeb0405956fb534dc4 | <ide><path>lib/_stream_writable.js
<ide> Writable.prototype.pipe = function() {
<ide>
<ide> Writable.prototype.write = function(chunk, encoding, cb) {
<ide> const state = this._writableState;
<del> var ret = false;
<ide> const isBuf = !state.objectMode && Stream._isUint8Array(chunk);
<ide>
<ide> // Do not use Object.getPrototypeOf as it is slower since V8 7.3.
<ide> Writable.prototype.write = function(chunk, encoding, cb) {
<ide>
<ide> if (typeof encoding === 'function') {
<ide> cb = encoding;
<del> encoding = null;
<add> encoding = state.defaultEncoding;
<add> } else {
<add> if (!encoding)
<add> encoding = state.defaultEncoding;
<add> if (typeof cb !== 'function')
<add> cb = nop;
<ide> }
<ide>
<ide> if (isBuf)
<ide> encoding = 'buffer';
<del> else if (!encoding)
<del> encoding = state.defaultEncoding;
<del>
<del> if (typeof cb !== 'function')
<del> cb = nop;
<ide>
<ide> let err;
<ide> if (state.ending) {
<ide> Writable.prototype.write = function(chunk, encoding, cb) {
<ide> err = new ERR_STREAM_DESTROYED('write');
<ide> } else if (chunk === null) {
<ide> err = new ERR_STREAM_NULL_VALUES();
<del> } else if (!isBuf && typeof chunk !== 'string' && !state.objectMode) {
<del> err = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);
<ide> } else {
<del> state.pendingcb++;
<del> ret = writeOrBuffer(this, state, chunk, encoding, cb);
<del> }
<del>
<del> if (err) {
<del> process.nextTick(cb, err);
<del> errorOrDestroy(this, err, true);
<add> if (!isBuf && !state.objectMode) {
<add> if (typeof chunk !== 'string') {
<add> err = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);
<add> } else if (encoding !== 'buffer' && state.decodeStrings !== false) {
<add> chunk = Buffer.from(chunk, encoding);
<add> encoding = 'buffer';
<add> }
<add> }
<add> if (err === undefined) {
<add> state.pendingcb++;
<add> return writeOrBuffer(this, state, chunk, encoding, cb);
<add> }
<ide> }
<ide>
<del> return ret;
<add> process.nextTick(cb, err);
<add> errorOrDestroy(this, err, true);
<add> return false;
<ide> };
<ide>
<ide> Writable.prototype.cork = function() {
<ide> ObjectDefineProperty(Writable.prototype, 'writableCorked', {
<ide> // in the queue, and wait our turn. Otherwise, call _write
<ide> // If we return false, then we need a drain event, so set that flag.
<ide> function writeOrBuffer(stream, state, chunk, encoding, cb) {
<del> if (!state.objectMode &&
<del> state.decodeStrings !== false &&
<del> encoding !== 'buffer' &&
<del> typeof chunk === 'string') {
<del> chunk = Buffer.from(chunk, encoding);
<del> encoding = 'buffer';
<del> }
<ide> const len = state.objectMode ? 1 : chunk.length;
<ide>
<ide> state.length += len; | 1 |
PHP | PHP | use func_num_args(). | 74252d15d8c22be664934b251c52ff3c98147740 | <ide><path>src/Illuminate/View/Concerns/ManagesComponents.php
<ide> protected function componentData($name)
<ide> */
<ide> public function slot($name, $content = null)
<ide> {
<del> if (count(func_get_args()) === 2) {
<add> if (func_num_args() === 2) {
<ide> $this->slots[$this->currentComponent()][$name] = $content;
<ide> } else {
<ide> if (ob_start()) { | 1 |
Ruby | Ruby | fix another rack spec violation | 27902c7e96de6913c237c3b0487d4beeef848689 | <ide><path>actionpack/test/controller/new_base/middleware_test.rb
<ide> def setup
<ide>
<ide> test "middleware that is 'use'd is called as part of the Rack application" do
<ide> result = @app.call(env_for("/"))
<del> assert_equal ["Hello World"], result[2]
<add> assert_equal ["Hello World"], [].tap { |a| result[2].each { |x| a << x } }
<ide> assert_equal "Success", result[1]["Middleware-Test"]
<ide> end
<ide> | 1 |
Go | Go | add layer id to naivediffdriver untar timing log | 3b4df3d146c8c1fcc7a2916e4c88134c664de7af | <ide><path>daemon/graphdriver/fsdiff.go
<ide> func (gdw *NaiveDiffDriver) ApplyDiff(id, parent string, diff io.Reader) (size i
<ide> options := &archive.TarOptions{UIDMaps: gdw.uidMaps,
<ide> GIDMaps: gdw.gidMaps}
<ide> start := time.Now().UTC()
<del> logrus.Debug("Start untar layer")
<add> logrus.WithField("id", id).Debug("Start untar layer")
<ide> if size, err = ApplyUncompressedLayer(layerFs, diff, options); err != nil {
<ide> return
<ide> }
<del> logrus.Debugf("Untar time: %vs", time.Now().UTC().Sub(start).Seconds())
<add> logrus.WithField("id", id).Debugf("Untar time: %vs", time.Now().UTC().Sub(start).Seconds())
<ide>
<ide> return
<ide> } | 1 |
PHP | PHP | move optionparser initialization out of try block | fba17cffe969ab18ab5245bd97849d1ecd8a30e6 | <ide><path>lib/Cake/Console/Shell.php
<ide> public function runCommand($command, $argv) {
<ide> array_shift($argv);
<ide> }
<ide>
<add> $this->OptionParser = $this->getOptionParser();
<ide> try {
<del> $this->OptionParser = $this->getOptionParser();
<ide> list($this->params, $this->args) = $this->OptionParser->parse($argv, $command);
<ide> } catch (ConsoleException $e) {
<ide> $this->out($this->OptionParser->help($command)); | 1 |
Text | Text | add protocol option in http2.connect() | 470511ae781f152ac53a192c7bb0f395c972d200 | <ide><path>doc/api/http2.md
<ide> changes:
<ide> streams for the remote peer as if a `SETTINGS` frame had been received. Will
<ide> be overridden if the remote peer sets its own value for
<ide> `maxConcurrentStreams`. **Default:** `100`.
<add> * `protocol` {string} The protocol to connect with, if not set in the
<add> `authority`. Value may be either `'http:'` or `'https:'`. **Default:**
<add> `'https:'`
<ide> * `settings` {HTTP/2 Settings Object} The initial settings to send to the
<ide> remote peer upon connection.
<ide> * `createConnection` {Function} An optional callback that receives the `URL` | 1 |
PHP | PHP | add tests for issue #104 | 8cadac3ee551336e273984edd3e32317efb8898e | <ide><path>lib/Cake/Test/Case/Utility/Set2Test.php
<ide> public function testExtractAttributePattern() {
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide>
<add>/**
<add> * Test that uneven keys are handled correctly.
<add> *
<add> * @return void
<add> */
<add> public function testExtractUnevenKeys() {
<add> $data = array(
<add> 'Level1' => array(
<add> 'Level2' => array('test1', 'test2'),
<add> 'Level2bis' => array('test3', 'test4')
<add> )
<add> );
<add> $this->assertEquals(
<add> array('test1', 'test2'),
<add> Set2::extract($data, 'Level1.Level2')
<add> );
<add> $this->assertEquals(
<add> array('test3', 'test4'),
<add> Set2::extract($data, 'Level1.Level2bis')
<add> );
<add>
<add> $data = array(
<add> 'Level1' => array(
<add> 'Level2bis' => array(
<add> array('test3', 'test4'),
<add> array('test5', 'test6')
<add> )
<add> )
<add> );
<add> $expected = array(
<add> array('test3', 'test4'),
<add> array('test5', 'test6')
<add> );
<add> $this->assertEquals($expected, Set2::extract($data, 'Level1.Level2bis'));
<add>
<add> $data['Level1']['Level2'] = array('test1', 'test2');
<add> $this->assertEquals($expected, Set2::extract($data, 'Level1.Level2bis'));
<add> }
<add>
<ide> /**
<ide> * testSort method
<ide> *
<ide><path>lib/Cake/Utility/Set2.php
<ide> public static function combine(array $data, $keyPath, $valuePath = null, $groupP
<ide> /**
<ide> * Returns a formated series of values extracted from `$data`, using
<ide> * `$format` as the format and `$paths` as the values to extract.
<add> *
<add> * Usage:
<add> *
<add> * {{{
<add> * $result = Set::format($users, array('{n}.User.id', '{n}.User.name'), '%s : %s');
<add> * }}}
<add> *
<add> * The `$format` string can use any format options that `vsprintf()` and `sprintf()` do.
<ide> *
<ide> * @param array $data Source array from which to extract the data
<ide> * @param string $paths An array containing one or more Set2::extract()-style key paths | 2 |
Javascript | Javascript | remove redundant userheight | f19cfa30688ec4bf0df96728e80eed0a7bdc5747 | <ide><path>examples/js/vr/ViveController.js
<ide> THREE.ViveController = function ( id ) {
<ide> if ( pose.position !== null ) scope.position.fromArray( pose.position );
<ide> if ( pose.orientation !== null ) scope.quaternion.fromArray( pose.orientation );
<ide> scope.matrix.compose( scope.position, scope.quaternion, scope.scale );
<del> scope.matrix.multiplyMatrices( scope.standingMatrix, scope.matrix );
<add> scope.matrix.premultiply( scope.standingMatrix );
<ide> scope.matrixWorldNeedsUpdate = true;
<ide> scope.visible = true;
<ide>
<ide><path>src/renderers/webvr/WebVRManager.js
<ide> function WebVRManager( renderer ) {
<ide>
<ide> poseObject.position.fromArray( pose.position );
<ide>
<del> } else {
<del>
<del> poseObject.position.set( 0, scope.userHeight, 0 );
<del>
<del> }
<add> }
<ide>
<ide> if ( pose.orientation !== null ) {
<ide> | 2 |
Ruby | Ruby | optimize the common case | d5695001f1a7316ed1bb7886c1ff0b6aea95c944 | <ide><path>activesupport/lib/active_support/core_ext/string/output_safety.rb
<ide> module Util
<ide> JSON_ESCAPE_REGEXP = /[\u2028\u2029&><]/u
<ide>
<ide> # Following XML requirements: https://www.w3.org/TR/REC-xml/#NT-Name
<del> TAG_NAME_START_REGEXP_SET = "@:A-Z_a-z\u{C0}-\u{D6}\u{D8}-\u{F6}\u{F8}-\u{2FF}\u{370}-\u{37D}\u{37F}-\u{1FFF}" \
<add> TAG_NAME_START_CODEPOINTS = "@:A-Z_a-z\u{C0}-\u{D6}\u{D8}-\u{F6}\u{F8}-\u{2FF}\u{370}-\u{37D}\u{37F}-\u{1FFF}" \
<ide> "\u{200C}-\u{200D}\u{2070}-\u{218F}\u{2C00}-\u{2FEF}\u{3001}-\u{D7FF}\u{F900}-\u{FDCF}" \
<ide> "\u{FDF0}-\u{FFFD}\u{10000}-\u{EFFFF}"
<del> TAG_NAME_START_REGEXP = /[^#{TAG_NAME_START_REGEXP_SET}]/
<del> TAG_NAME_FOLLOWING_REGEXP = /[^#{TAG_NAME_START_REGEXP_SET}\-.0-9\u{B7}\u{0300}-\u{036F}\u{203F}-\u{2040}]/
<add> INVALID_TAG_NAME_START_REGEXP = /[^#{TAG_NAME_START_CODEPOINTS}]/
<add> TAG_NAME_FOLLOWING_CODEPOINTS = "#{TAG_NAME_START_CODEPOINTS}\\-.0-9\u{B7}\u{0300}-\u{036F}\u{203F}-\u{2040}"
<add> INVALID_TAG_NAME_FOLLOWING_REGEXP = /[^#{TAG_NAME_FOLLOWING_CODEPOINTS}]/
<add> SAFE_XML_TAG_NAME_REGEXP = /\A[#{TAG_NAME_START_CODEPOINTS}][#{TAG_NAME_FOLLOWING_CODEPOINTS}]*\z/
<ide> TAG_NAME_REPLACEMENT_CHAR = "_"
<ide>
<ide> # A utility method for escaping HTML tag characters.
<ide> def json_escape(s)
<ide> def xml_name_escape(name)
<ide> name = name.to_s
<ide> return "" if name.blank?
<add> return name if name.match?(SAFE_XML_TAG_NAME_REGEXP)
<ide>
<ide> starting_char = name[0]
<del> starting_char.gsub!(TAG_NAME_START_REGEXP, TAG_NAME_REPLACEMENT_CHAR)
<add> starting_char.gsub!(INVALID_TAG_NAME_START_REGEXP, TAG_NAME_REPLACEMENT_CHAR)
<ide>
<ide> return starting_char if name.size == 1
<ide>
<ide> following_chars = name[1..-1]
<del> following_chars.gsub!(TAG_NAME_FOLLOWING_REGEXP, TAG_NAME_REPLACEMENT_CHAR)
<add> following_chars.gsub!(INVALID_TAG_NAME_FOLLOWING_REGEXP, TAG_NAME_REPLACEMENT_CHAR)
<ide>
<ide> starting_char << following_chars
<ide> end
<ide><path>activesupport/test/core_ext/string_ext_test.rb
<ide> def to_s
<ide> unsafe_char = ">"
<ide> safe_char = "Á"
<ide> safe_char_after_start = "3"
<add> starting_with_dash = "-foo"
<ide>
<ide> assert_equal "_", ERB::Util.xml_name_escape(unsafe_char)
<ide> assert_equal "_#{safe_char}", ERB::Util.xml_name_escape(unsafe_char + safe_char)
<ide> def to_s
<ide> common_dangerous_chars = "&<>\"' %*+,/;=^|"
<ide> assert_equal "_" * common_dangerous_chars.size,
<ide> ERB::Util.xml_name_escape(common_dangerous_chars)
<add>
<add> assert_equal "_foo", ERB::Util.xml_name_escape(starting_with_dash)
<ide> end
<ide> end
<ide> | 2 |
Javascript | Javascript | expose api types | 80f67573a1e75aabd69202c75a3ab61e2f197e61 | <ide><path>lib/util/registerExternalSerializer.js
<ide> const {
<ide>
<ide> /** @typedef {import("../Dependency").RealDependencyLocation} RealDependencyLocation */
<ide> /** @typedef {import("../Dependency").SourcePosition} SourcePosition */
<del>/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
<del>/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
<add>/** @typedef {import("./serialization").ObjectDeserializerContext} ObjectDeserializerContext */
<add>/** @typedef {import("./serialization").ObjectSerializerContext} ObjectSerializerContext */
<ide>
<ide> const CURRENT_MODULE = "webpack/lib/util/registerExternalSerializer";
<ide>
<ide><path>lib/util/serialization.js
<ide> const FileMiddleware = require("../serialization/FileMiddleware");
<ide> const ObjectMiddleware = require("../serialization/ObjectMiddleware");
<ide> const Serializer = require("../serialization/Serializer");
<ide>
<add>/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
<add>/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
<add>
<ide> const { register, registerLoader, registerNotSerializable } = ObjectMiddleware;
<ide>
<ide> // Expose serialization API | 2 |
Text | Text | add docs index to readme.md | fa953bacd8930897dd0fe8b31b25d976bd51ba85 | <ide><path>README.md
<ide> through a more complete [tutorial](https://airflow.apache.org/docs/apache-airflo
<ide> For more information on Airflow Improvement Proposals (AIPs), visit
<ide> the [Airflow Wiki](https://cwiki.apache.org/confluence/display/AIRFLOW/Airflow+Improvements+Proposals).
<ide>
<del>Official Docker (container) images for Apache Airflow are described in [IMAGES.rst](https://github.com/apache/airflow/blob/main/IMAGES.rst).
<add>Documentation for dependent projects like provider packages, Docker image, Helm Chart, you'll find it in [the documentation index](https://airflow.apache.org/docs/).
<ide>
<ide> ## Installing from PyPI
<ide>
<ide> following the ASF Policy.
<ide>
<ide> Want to help build Apache Airflow? Check out our [contributing documentation](https://github.com/apache/airflow/blob/main/CONTRIBUTING.rst).
<ide>
<add>Official Docker (container) images for Apache Airflow are described in [IMAGES.rst](https://github.com/apache/airflow/blob/main/IMAGES.rst).
<add>
<ide> ## Who uses Apache Airflow?
<ide>
<ide> More than 400 organizations are using Apache Airflow | 1 |
Text | Text | add further reading section to bottom | a5175d125ababdcd1a82de0c148b2d4edeaf2228 | <ide><path>guide/english/javascript/es6/for-of/index.md
<ide> for (const para of paragraphs)
<ide> // We can add event listeners to each para here
<ide> }
<ide> ```
<add>
<add>#### More Information
<add>
<add>[ES6 In Depth: Iterators and the for-of loop](https://hacks.mozilla.org/2015/04/es6-in-depth-iterators-and-the-for-of-loop/) | 1 |
PHP | PHP | add withcookie() & getcookie() | 36b067cf9e5b7da5e579edd49002f8e3de251db0 | <ide><path>src/Network/Response.php
<ide> public function __toString()
<ide> * @param array|null $options Either null to get all cookies, string for a specific cookie
<ide> * or array to set cookie.
<ide> * @return mixed
<add> * @deprecated 3.4.0 Use getCookie() and withCookie() instead.
<ide> */
<ide> public function cookie($options = null)
<ide> {
<ide> public function cookie($options = null)
<ide> $this->_cookies[$options['name']] = $options;
<ide> }
<ide>
<add> /**
<add> * Create a new response with a cookie set.
<add> *
<add> * @param string $name The name of the cookie to set.
<add> * @param array|string $data Either a string value, or an array of cookie data.
<add> * @return static
<add> */
<add> public function withCookie($name, $data = '')
<add> {
<add> if (!is_array($data)) {
<add> $data = ['value' => $data];
<add> }
<add> $defaults = [
<add> 'value' => '',
<add> 'expire' => 0,
<add> 'path' => '/',
<add> 'domain' => '',
<add> 'secure' => false,
<add> 'httpOnly' => false
<add> ];
<add> $data += $defaults;
<add> $data['name'] = $name;
<add>
<add> $new = clone $this;
<add> $new->_cookies[$name] = $data;
<add>
<add> return $new;
<add> }
<add>
<add> /**
<add> * Read a single cookie from the response.
<add> *
<add> * This method provides read access to pending cookies. It will
<add> * not read the `Set-Cookie` header if set.
<add> *
<add> * @param string $name The cookie name you want to read.
<add> * @return array|null Either the cookie data or null
<add> */
<add> public function getCookie($name)
<add> {
<add> if (isset($this->_cookies[$name])) {
<add> return $this->_cookies[$name];
<add> }
<add>
<add> return null;
<add> }
<add>
<ide> /**
<ide> * Setup access for origin and methods on cross origin requests
<ide> *
<ide><path>tests/TestCase/Network/ResponseTest.php
<ide> public function testCookieSettings()
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide>
<add> /**
<add> * Test setting cookies with no value
<add> *
<add> * @return void
<add> */
<add> public function testWithCookieEmpty()
<add> {
<add> $response = new Response();
<add> $new = $response->withCookie('testing');
<add> $this->assertNull($response->getCookie('testing'), 'withCookie does not mutate');
<add>
<add> $expected = [
<add> 'name' => 'testing',
<add> 'value' => '',
<add> 'expire' => 0,
<add> 'path' => '/',
<add> 'domain' => '',
<add> 'secure' => false,
<add> 'httpOnly' => false];
<add> $result = $new->getCookie('testing');
<add> $this->assertEquals($expected, $result);
<add> }
<add>
<add> /**
<add> * Test setting cookies with scalar values
<add> *
<add> * @return void
<add> */
<add> public function testWithCookieScalar()
<add> {
<add> $response = new Response();
<add> $new = $response->withCookie('testing', 'abc123');
<add> $this->assertNull($response->getCookie('testing'), 'withCookie does not mutate');
<add> $this->assertEquals('abc123', $new->getCookie('testing')['value']);
<add>
<add> $new = $response->withCookie('testing', 99);
<add> $this->assertEquals(99, $new->getCookie('testing')['value']);
<add>
<add> $new = $response->withCookie('testing', false);
<add> $this->assertFalse($new->getCookie('testing')['value']);
<add>
<add> $new = $response->withCookie('testing', true);
<add> $this->assertTrue($new->getCookie('testing')['value']);
<add> }
<add>
<add> /**
<add> * Test withCookie() and array data.
<add> *
<add> * @return void
<add> */
<add> public function testWithCookieArray()
<add> {
<add> $response = new Response();
<add> $cookie = [
<add> 'name' => 'ignored key',
<add> 'value' => '[a,b,c]',
<add> 'expire' => 1000,
<add> 'path' => '/test',
<add> 'secure' => true
<add> ];
<add> $new = $response->withCookie('testing', $cookie);
<add> $this->assertNull($response->getCookie('testing'), 'withCookie does not mutate');
<add> $expected = [
<add> 'name' => 'testing',
<add> 'value' => '[a,b,c]',
<add> 'expire' => 1000,
<add> 'path' => '/test',
<add> 'domain' => '',
<add> 'secure' => true,
<add> 'httpOnly' => false
<add> ];
<add> $this->assertEquals($expected, $new->getCookie('testing'));
<add> }
<add>
<ide> /**
<ide> * Test CORS
<ide> * | 2 |
PHP | PHP | improve exception type | 7d4e9dd357dd3de56c652d9bb94ca72fad78a0d5 | <ide><path>src/Http/Middleware/CsrfProtectionMiddleware.php
<ide> use Cake\Http\Response;
<ide> use Cake\Utility\Hash;
<ide> use Cake\Utility\Security;
<add>use InvalidArgumentException;
<ide> use Psr\Http\Message\ResponseInterface;
<ide> use Psr\Http\Message\ServerRequestInterface;
<ide> use Psr\Http\Server\MiddlewareInterface;
<ide> public function process(ServerRequestInterface $request, RequestHandlerInterface
<ide> if (is_string($cookieData) && strlen($cookieData) > 0) {
<ide> try {
<ide> $request = $request->withAttribute('csrfToken', $this->saltToken($cookieData));
<del> } catch (RuntimeException $e) {
<add> } catch (InvalidArgumentException $e) {
<ide> $cookieData = null;
<ide> }
<ide> }
<ide> public function saltToken(string $token): string
<ide> }
<ide> $decoded = base64_decode($token, true);
<ide> if ($decoded === false) {
<del> throw new RuntimeException('Invalid token data.');
<add> throw new InvalidArgumentException('Invalid token data.');
<ide> }
<ide>
<ide> $length = strlen($decoded); | 1 |
Go | Go | add support for partial load | f946782316ea5fa635773587bd4c6da7ecf118b8 | <ide><path>image/tarexport/load.go
<ide> func (l *tarexporter) Load(inTar io.ReadCloser, outStream io.Writer) error {
<ide> if err != nil {
<ide> return err
<ide> }
<del> newLayer, err := l.loadLayer(layerPath, rootFS)
<add> r := rootFS
<add> r.Append(diffID)
<add> newLayer, err := l.ls.Get(r.ChainID())
<ide> if err != nil {
<del> return err
<add> newLayer, err = l.loadLayer(layerPath, rootFS)
<add> if err != nil {
<add> return err
<add> }
<ide> }
<ide> defer layer.ReleaseAndLog(l.ls, newLayer)
<ide> if expected, actual := diffID, newLayer.DiffID(); expected != actual { | 1 |
Python | Python | add support for temporal sample weights | 4922a67f09d5a54bcebc28cfe5baced9981bbeee | <ide><path>keras/models.py
<ide> def weighted(y_true, y_pred, weights, mask=None):
<ide> # to the number of unmasked samples.
<ide> score_array /= K.mean(mask)
<ide>
<del> # reduce score_array to 1D
<add> # reduce score_array to same ndim as weight array
<ide> ndim = K.ndim(score_array)
<del> for d in range(ndim-1):
<del> score_array = K.mean(score_array, axis=-1)
<add> weight_ndim = K.ndim(weights)
<add> score_array = K.mean(score_array, axis=list(range(weight_ndim, ndim)))
<ide>
<add> # apply sample weighting
<ide> if weights is not None:
<ide> score_array *= weights
<ide> return K.mean(score_array)
<ide> def standardize_weights(y, sample_weight=None, class_weight=None):
<ide> '''
<ide> '''
<ide> if sample_weight is not None:
<del> assert len(sample_weight) == len(y)
<del> return sample_weight.flatten()
<add> assert sample_weight.ndim <= y.ndim
<add> assert y.shape[:sample_weight.ndim] == sample_weight.shape
<add> return sample_weight
<ide> elif isinstance(class_weight, dict):
<ide> if len(y.shape) > 2:
<ide> raise Exception('class_weight not supported for '
<ide> def fit(self, X, y, batch_size=128, nb_epoch=100, verbose=1, callbacks=[],
<ide> class accuracy in the logs to stdout at each epoch.
<ide> class_weight: dictionary mapping classes to a weight value,
<ide> used for scaling the loss function (during training only).
<del> sample_weight: list or numpy array with 1:1 mapping to
<add> sample_weight: list or numpy array of weights for
<ide> the training samples, used for scaling the loss function
<del> (during training only).
<add> (during training only). You can either pass a flat (1D)
<add> Numpy array with the same length as the input samples
<add> (1:1 mapping between weights and samples),
<add> or in the case of temporal data,
<add> you can pass a 2D array with shape (samples, sequence_length),
<add> to apply a different weight to every timestep of every sample.
<ide> '''
<ide> if type(X) == list:
<ide> if len(set([len(a) for a in X] + [len(y)])) != 1: | 1 |
Text | Text | add "talks" to ecosystem.md | adf8b9a3b14ecc65eb1c30bf7b5840aff2797934 | <ide><path>docs/introduction/Ecosystem.md
<ide> On this page we will only feature a few of them that the Redux maintainers have
<ide> * [Handcrafting an Isomorphic Redux Application (With Love)](https://medium.com/@bananaoomarang/handcrafting-an-isomorphic-redux-application-with-love-40ada4468af4) — A guide to creating a universal app with data fetching and routing
<ide> * [Full-Stack Redux Tutorial](http://teropa.info/blog/2015/09/10/full-stack-redux-tutorial.html) — A comprehensive guide to test-first development with Redux, React, and Immutable
<ide>
<add>## Talks
<add>
<add>* [Live React: Hot Reloading and Time Travel](http://youtube.com/watch?v=xsSnOQynTHs) — See how constraints enforced by Redux make hot reloading with time travel easy
<add>* [Cleaning the Tar: Using React within the Firefox Developer Tools](https://www.youtube.com/watch?v=qUlRpybs7_c) — Learn how to gradually migrate existing MVC applications to Redux
<add>
<ide> ## Community Conventions
<ide>
<ide> * [Flux Standard Action](https://github.com/acdlite/flux-standard-action) — A human-friendly standard for Flux action objects | 1 |
Python | Python | add --text_column to run_summarization_no_trainer | 64232bc0df7e28f91bdad2b29fca1808089e3dfd | <ide><path>examples/pytorch/summarization/run_summarization_no_trainer.py
<ide> def parse_args():
<ide> default=None,
<ide> help="Pretrained tokenizer name or path if not the same as model_name",
<ide> )
<add> parser.add_argument(
<add> "--text_column",
<add> type=str,
<add> default=None,
<add> help="The name of the column in the datasets containing the full texts (for summarization).",
<add> )
<ide> parser.add_argument(
<ide> "--summary_column",
<ide> type=str,
<ide> def main():
<ide>
<ide> # Get the column names for input/target.
<ide> dataset_columns = summarization_name_mapping.get(args.dataset_name, None)
<del> text_column_name = dataset_columns[0] if dataset_columns is not None else column_names[0]
<del>
<del> padding = "max_length" if args.pad_to_max_length else False
<add> if args.text_column is None:
<add> text_column = dataset_columns[0] if dataset_columns is not None else column_names[0]
<add> else:
<add> text_column = args.text_column
<add> if text_column not in column_names:
<add> raise ValueError(
<add> f"--text_column' value '{args.text_column}' needs to be one of: {', '.join(column_names)}"
<add> )
<ide> if args.summary_column is None:
<ide> summary_column = dataset_columns[1] if dataset_columns is not None else column_names[1]
<ide> else:
<ide> def main():
<ide> padding = "max_length" if args.pad_to_max_length else False
<ide>
<ide> def preprocess_function(examples):
<del> inputs = examples[text_column_name]
<add> inputs = examples[text_column]
<ide> targets = examples[summary_column]
<ide> inputs = [prefix + inp for inp in inputs]
<ide> model_inputs = tokenizer(inputs, max_length=args.max_source_length, padding=padding, truncation=True) | 1 |
Javascript | Javascript | copy files from the react-native repo | f463b731ee5fce75ccf1df43d6174527016a0379 | <ide><path>src/renderers/native/ReactIOS/IOSDefaultEventPluginOrder.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> *
<add> * @providesModule IOSDefaultEventPluginOrder
<add> * @flow
<add> */
<add>'use strict';
<add>
<add>var IOSDefaultEventPluginOrder = [
<add> 'ResponderEventPlugin',
<add> 'IOSNativeBridgeEventPlugin'
<add>];
<add>
<add>module.exports = IOSDefaultEventPluginOrder;
<ide><path>src/renderers/native/ReactIOS/IOSNativeBridgeEventPlugin.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> *
<add> * @providesModule IOSNativeBridgeEventPlugin
<add> * @flow
<add> */
<add>'use strict';
<add>
<add>var EventPropagators = require('EventPropagators');
<add>var SyntheticEvent = require('SyntheticEvent');
<add>var UIManager = require('UIManager');
<add>
<add>var merge = require('merge');
<add>var warning = require('fbjs/lib/warning');
<add>
<add>var customBubblingEventTypes = UIManager.customBubblingEventTypes;
<add>var customDirectEventTypes = UIManager.customDirectEventTypes;
<add>
<add>var allTypesByEventName = {};
<add>
<add>for (var bubblingTypeName in customBubblingEventTypes) {
<add> allTypesByEventName[bubblingTypeName] = customBubblingEventTypes[bubblingTypeName];
<add>}
<add>
<add>for (var directTypeName in customDirectEventTypes) {
<add> warning(
<add> !customBubblingEventTypes[directTypeName],
<add> 'Event cannot be both direct and bubbling: %s',
<add> directTypeName
<add> );
<add> allTypesByEventName[directTypeName] = customDirectEventTypes[directTypeName];
<add>}
<add>
<add>var IOSNativeBridgeEventPlugin = {
<add>
<add> eventTypes: merge(customBubblingEventTypes, customDirectEventTypes),
<add>
<add> /**
<add> * @param {string} topLevelType Record from `EventConstants`.
<add> * @param {DOMEventTarget} topLevelTarget The listening component root node.
<add> * @param {string} topLevelTargetID ID of `topLevelTarget`.
<add> * @param {object} nativeEvent Native browser event.
<add> * @return {*} An accumulation of synthetic events.
<add> * @see {EventPluginHub.extractEvents}
<add> */
<add> extractEvents: function(
<add> topLevelType: string,
<add> topLevelTarget: EventTarget,
<add> topLevelTargetID: string,
<add> nativeEvent: Event
<add> ): ?Object {
<add> var bubbleDispatchConfig = customBubblingEventTypes[topLevelType];
<add> var directDispatchConfig = customDirectEventTypes[topLevelType];
<add> var event = SyntheticEvent.getPooled(
<add> bubbleDispatchConfig || directDispatchConfig,
<add> topLevelTargetID,
<add> nativeEvent
<add> );
<add> if (bubbleDispatchConfig) {
<add> EventPropagators.accumulateTwoPhaseDispatches(event);
<add> } else if (directDispatchConfig) {
<add> EventPropagators.accumulateDirectDispatches(event);
<add> } else {
<add> return null;
<add> }
<add> return event;
<add> }
<add>};
<add>
<add>module.exports = IOSNativeBridgeEventPlugin;
<ide><path>src/renderers/native/ReactIOS/NativeMethodsMixin.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> *
<add> * @providesModule NativeMethodsMixin
<add> * @flow
<add> */
<add>'use strict';
<add>
<add>var ReactNativeAttributePayload = require('ReactNativeAttributePayload');
<add>var TextInputState = require('TextInputState');
<add>var UIManager = require('UIManager');
<add>
<add>var findNodeHandle = require('findNodeHandle');
<add>var invariant = require('fbjs/lib/invariant');
<add>
<add>type MeasureOnSuccessCallback = (
<add> x: number,
<add> y: number,
<add> width: number,
<add> height: number,
<add> pageX: number,
<add> pageY: number
<add>) => void
<add>
<add>type MeasureInWindowOnSuccessCallback = (
<add> x: number,
<add> y: number,
<add> width: number,
<add> height: number,
<add>) => void
<add>
<add>type MeasureLayoutOnSuccessCallback = (
<add> left: number,
<add> top: number,
<add> width: number,
<add> height: number
<add>) => void
<add>
<add>function warnForStyleProps(props, validAttributes) {
<add> for (var key in validAttributes.style) {
<add> if (!(validAttributes[key] || props[key] === undefined)) {
<add> console.error(
<add> 'You are setting the style `{ ' + key + ': ... }` as a prop. You ' +
<add> 'should nest it in a style object. ' +
<add> 'E.g. `{ style: { ' + key + ': ... } }`'
<add> );
<add> }
<add> }
<add>}
<add>
<add>/**
<add> * `NativeMethodsMixin` provides methods to access the underlying native
<add> * component directly. This can be useful in cases when you want to focus
<add> * a view or measure its on-screen dimensions, for example.
<add> *
<add> * The methods described here are available on most of the default components
<add> * provided by React Native. Note, however, that they are *not* available on
<add> * composite components that aren't directly backed by a native view. This will
<add> * generally include most components that you define in your own app. For more
<add> * information, see [Direct
<add> * Manipulation](docs/direct-manipulation.html).
<add> */
<add>var NativeMethodsMixin = {
<add> /**
<add> * Determines the location on screen, width, and height of the given view and
<add> * returns the values via an async callback. If successful, the callback will
<add> * be called with the following arguments:
<add> *
<add> * - x
<add> * - y
<add> * - width
<add> * - height
<add> * - pageX
<add> * - pageY
<add> *
<add> * Note that these measurements are not available until after the rendering
<add> * has been completed in native. If you need the measurements as soon as
<add> * possible, consider using the [`onLayout`
<add> * prop](docs/view.html#onlayout) instead.
<add> */
<add> measure: function(callback: MeasureOnSuccessCallback) {
<add> UIManager.measure(
<add> findNodeHandle(this),
<add> mountSafeCallback(this, callback)
<add> );
<add> },
<add>
<add> /**
<add> * Determines the location of the given view in the window and returns the
<add> * values via an async callback. If the React root view is embedded in
<add> * another native view, this will give you the absolute coordinates. If
<add> * successful, the callback will be called with the following
<add> * arguments:
<add> *
<add> * - x
<add> * - y
<add> * - width
<add> * - height
<add> *
<add> * Note that these measurements are not available until after the rendering
<add> * has been completed in native.
<add> */
<add> measureInWindow: function(callback: MeasureInWindowOnSuccessCallback) {
<add> UIManager.measureInWindow(
<add> findNodeHandle(this),
<add> mountSafeCallback(this, callback)
<add> );
<add> },
<add>
<add> /**
<add> * Like [`measure()`](#measure), but measures the view relative an ancestor,
<add> * specified as `relativeToNativeNode`. This means that the returned x, y
<add> * are relative to the origin x, y of the ancestor view.
<add> *
<add> * As always, to obtain a native node handle for a component, you can use
<add> * `React.findNodeHandle(component)`.
<add> */
<add> measureLayout: function(
<add> relativeToNativeNode: number,
<add> onSuccess: MeasureLayoutOnSuccessCallback,
<add> onFail: () => void /* currently unused */
<add> ) {
<add> UIManager.measureLayout(
<add> findNodeHandle(this),
<add> relativeToNativeNode,
<add> mountSafeCallback(this, onFail),
<add> mountSafeCallback(this, onSuccess)
<add> );
<add> },
<add>
<add> /**
<add> * This function sends props straight to native. They will not participate in
<add> * future diff process - this means that if you do not include them in the
<add> * next render, they will remain active (see [Direct
<add> * Manipulation](docs/direct-manipulation.html)).
<add> */
<add> setNativeProps: function(nativeProps: Object) {
<add> if (__DEV__) {
<add> warnForStyleProps(nativeProps, this.viewConfig.validAttributes);
<add> }
<add>
<add> var updatePayload = ReactNativeAttributePayload.create(
<add> nativeProps,
<add> this.viewConfig.validAttributes
<add> );
<add>
<add> UIManager.updateView(
<add> findNodeHandle(this),
<add> this.viewConfig.uiViewClassName,
<add> updatePayload
<add> );
<add> },
<add>
<add> /**
<add> * Requests focus for the given input or view. The exact behavior triggered
<add> * will depend on the platform and type of view.
<add> */
<add> focus: function() {
<add> TextInputState.focusTextInput(findNodeHandle(this));
<add> },
<add>
<add> /**
<add> * Removes focus from an input or view. This is the opposite of `focus()`.
<add> */
<add> blur: function() {
<add> TextInputState.blurTextInput(findNodeHandle(this));
<add> }
<add>};
<add>
<add>function throwOnStylesProp(component, props) {
<add> if (props.styles !== undefined) {
<add> var owner = component._owner || null;
<add> var name = component.constructor.displayName;
<add> var msg = '`styles` is not a supported property of `' + name + '`, did ' +
<add> 'you mean `style` (singular)?';
<add> if (owner && owner.constructor && owner.constructor.displayName) {
<add> msg += '\n\nCheck the `' + owner.constructor.displayName + '` parent ' +
<add> ' component.';
<add> }
<add> throw new Error(msg);
<add> }
<add>}
<add>if (__DEV__) {
<add> // hide this from Flow since we can't define these properties outside of
<add> // __DEV__ without actually implementing them (setting them to undefined
<add> // isn't allowed by ReactClass)
<add> var NativeMethodsMixin_DEV = (NativeMethodsMixin: any);
<add> invariant(
<add> !NativeMethodsMixin_DEV.componentWillMount &&
<add> !NativeMethodsMixin_DEV.componentWillReceiveProps,
<add> 'Do not override existing functions.'
<add> );
<add> NativeMethodsMixin_DEV.componentWillMount = function () {
<add> throwOnStylesProp(this, this.props);
<add> };
<add> NativeMethodsMixin_DEV.componentWillReceiveProps = function (newProps) {
<add> throwOnStylesProp(this, newProps);
<add> };
<add>}
<add>
<add>/**
<add> * In the future, we should cleanup callbacks by cancelling them instead of
<add> * using this.
<add> */
<add>var mountSafeCallback = function(context: ReactComponent, callback: ?Function): any {
<add> return function() {
<add> if (!callback || (context.isMounted && !context.isMounted())) {
<add> return;
<add> }
<add> return callback.apply(context, arguments);
<add> };
<add>};
<add>
<add>module.exports = NativeMethodsMixin;
<ide><path>src/renderers/native/ReactIOS/YellowBox.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> *
<add> * @providesModule YellowBox
<add> * @flow
<add> */
<add>
<add>'use strict';
<add>
<add>const EventEmitter = require('EventEmitter');
<add>import type EmitterSubscription from 'EmitterSubscription';
<add>const Platform = require('Platform');
<add>const React = require('React');
<add>const StyleSheet = require('StyleSheet');
<add>
<add>const _warningEmitter = new EventEmitter();
<add>const _warningMap = new Map();
<add>
<add>/**
<add> * YellowBox renders warnings at the bottom of the app being developed.
<add> *
<add> * Warnings help guard against subtle yet significant issues that can impact the
<add> * quality of the app. This "in your face" style of warning allows developers to
<add> * notice and correct these issues as quickly as possible.
<add> *
<add> * By default, the warning box is enabled in `__DEV__`. Set the following flag
<add> * to disable it (and call `console.warn` to update any rendered <YellowBox>):
<add> *
<add> * console.disableYellowBox = true;
<add> * console.warn('YellowBox is disabled.');
<add> *
<add> * Warnings can be ignored programmatically by setting the array:
<add> *
<add> * console.ignoredYellowBox = ['Warning: ...'];
<add> *
<add> * Strings in `console.ignoredYellowBox` can be a prefix of the warning that
<add> * should be ignored.
<add> */
<add>
<add>if (__DEV__) {
<add> const {error, warn} = console;
<add> console.error = function() {
<add> error.apply(console, arguments);
<add> // Show yellow box for the `warning` module.
<add> if (typeof arguments[0] === 'string' &&
<add> arguments[0].startsWith('Warning: ')) {
<add> updateWarningMap.apply(null, arguments);
<add> }
<add> };
<add> console.warn = function() {
<add> warn.apply(console, arguments);
<add> updateWarningMap.apply(null, arguments);
<add> };
<add>}
<add>
<add>/**
<add> * Simple function for formatting strings.
<add> *
<add> * Replaces placeholders with values passed as extra arguments
<add> *
<add> * @param {string} format the base string
<add> * @param ...args the values to insert
<add> * @return {string} the replaced string
<add> */
<add>function sprintf(format, ...args) {
<add> var index = 0;
<add> return format.replace(/%s/g, match => args[index++]);
<add>}
<add>
<add>function updateWarningMap(format, ...args): void {
<add> const stringifySafe = require('stringifySafe');
<add>
<add> format = String(format);
<add> const argCount = (format.match(/%s/g) || []).length;
<add> const warning = [
<add> sprintf(format, ...args.slice(0, argCount)),
<add> ...args.slice(argCount).map(stringifySafe),
<add> ].join(' ');
<add>
<add> const count = _warningMap.has(warning) ? _warningMap.get(warning) : 0;
<add> _warningMap.set(warning, count + 1);
<add> _warningEmitter.emit('warning', _warningMap);
<add>}
<add>
<add>function isWarningIgnored(warning: string): boolean {
<add> return (
<add> Array.isArray(console.ignoredYellowBox) &&
<add> console.ignoredYellowBox.some(
<add> ignorePrefix => warning.startsWith(ignorePrefix)
<add> )
<add> );
<add>}
<add>
<add>const WarningRow = ({count, warning, onPress}) => {
<add> const Text = require('Text');
<add> const TouchableHighlight = require('TouchableHighlight');
<add> const View = require('View');
<add>
<add> const countText = count > 1 ?
<add> <Text style={styles.listRowCount}>{'(' + count + ') '}</Text> :
<add> null;
<add>
<add> return (
<add> <View style={styles.listRow}>
<add> <TouchableHighlight
<add> activeOpacity={0.5}
<add> onPress={onPress}
<add> style={styles.listRowContent}
<add> underlayColor="transparent">
<add> <Text style={styles.listRowText} numberOfLines={2}>
<add> {countText}
<add> {warning}
<add> </Text>
<add> </TouchableHighlight>
<add> </View>
<add> );
<add>};
<add>
<add>const WarningInspector = ({
<add> count,
<add> warning,
<add> onClose,
<add> onDismiss,
<add> onDismissAll,
<add>}) => {
<add> const ScrollView = require('ScrollView');
<add> const Text = require('Text');
<add> const TouchableHighlight = require('TouchableHighlight');
<add> const View = require('View');
<add>
<add> const countSentence =
<add> 'Warning encountered ' + count + ' time' + (count - 1 ? 's' : '') + '.';
<add>
<add> return (
<add> <TouchableHighlight
<add> activeOpacity={0.95}
<add> underlayColor={backgroundColor(0.8)}
<add> onPress={onClose}
<add> style={styles.inspector}>
<add> <View style={styles.inspectorContent}>
<add> <View style={styles.inspectorCount}>
<add> <Text style={styles.inspectorCountText}>{countSentence}</Text>
<add> </View>
<add> <ScrollView style={styles.inspectorWarning}>
<add> <Text style={styles.inspectorWarningText}>{warning}</Text>
<add> </ScrollView>
<add> <View style={styles.inspectorButtons}>
<add> <TouchableHighlight
<add> activeOpacity={0.5}
<add> onPress={onDismiss}
<add> style={styles.inspectorButton}
<add> underlayColor="transparent">
<add> <Text style={styles.inspectorButtonText}>
<add> Dismiss
<add> </Text>
<add> </TouchableHighlight>
<add> <TouchableHighlight
<add> activeOpacity={0.5}
<add> onPress={onDismissAll}
<add> style={styles.inspectorButton}
<add> underlayColor="transparent">
<add> <Text style={styles.inspectorButtonText}>
<add> Dismiss All
<add> </Text>
<add> </TouchableHighlight>
<add> </View>
<add> </View>
<add> </TouchableHighlight>
<add> );
<add>};
<add>
<add>class YellowBox extends React.Component {
<add> state: {
<add> inspecting: ?string;
<add> warningMap: Map;
<add> };
<add> _listener: ?EmitterSubscription;
<add>
<add> constructor(props: mixed, context: mixed) {
<add> super(props, context);
<add> this.state = {
<add> inspecting: null,
<add> warningMap: _warningMap,
<add> };
<add> this.dismissWarning = warning => {
<add> const {inspecting, warningMap} = this.state;
<add> if (warning) {
<add> warningMap.delete(warning);
<add> } else {
<add> warningMap.clear();
<add> }
<add> this.setState({
<add> inspecting: (warning && inspecting !== warning) ? inspecting : null,
<add> warningMap,
<add> });
<add> };
<add> }
<add>
<add> componentDidMount() {
<add> let scheduled = null;
<add> this._listener = _warningEmitter.addListener('warning', warningMap => {
<add> // Use `setImmediate` because warnings often happen during render, but
<add> // state cannot be set while rendering.
<add> scheduled = scheduled || setImmediate(() => {
<add> scheduled = null;
<add> this.setState({
<add> warningMap,
<add> });
<add> });
<add> });
<add> }
<add>
<add> componentWillUnmount() {
<add> if (this._listener) {
<add> this._listener.remove();
<add> }
<add> }
<add>
<add> render() {
<add> if (console.disableYellowBox || this.state.warningMap.size === 0) {
<add> return null;
<add> }
<add> const ScrollView = require('ScrollView');
<add> const View = require('View');
<add>
<add> const inspecting = this.state.inspecting;
<add> const inspector = inspecting !== null ?
<add> <WarningInspector
<add> count={this.state.warningMap.get(inspecting)}
<add> warning={inspecting}
<add> onClose={() => this.setState({inspecting: null})}
<add> onDismiss={() => this.dismissWarning(inspecting)}
<add> onDismissAll={() => this.dismissWarning(null)}
<add> /> :
<add> null;
<add>
<add> const rows = [];
<add> this.state.warningMap.forEach((count, warning) => {
<add> if (!isWarningIgnored(warning)) {
<add> rows.push(
<add> <WarningRow
<add> key={warning}
<add> count={count}
<add> warning={warning}
<add> onPress={() => this.setState({inspecting: warning})}
<add> onDismiss={() => this.dismissWarning(warning)}
<add> />
<add> );
<add> }
<add> });
<add>
<add> const listStyle = [
<add> styles.list,
<add> // Additional `0.4` so the 5th row can peek into view.
<add> {height: Math.min(rows.length, 4.4) * (rowGutter + rowHeight)},
<add> ];
<add> return (
<add> <View style={inspector ? styles.fullScreen : listStyle}>
<add> <ScrollView style={listStyle} scrollsToTop={false}>
<add> {rows}
<add> </ScrollView>
<add> {inspector}
<add> </View>
<add> );
<add> }
<add>}
<add>
<add>const backgroundColor = opacity => 'rgba(250, 186, 48, ' + opacity + ')';
<add>const textColor = 'white';
<add>const rowGutter = 1;
<add>const rowHeight = 46;
<add>
<add>var styles = StyleSheet.create({
<add> fullScreen: {
<add> backgroundColor: 'transparent',
<add> position: 'absolute',
<add> left: 0,
<add> right: 0,
<add> top: 0,
<add> bottom: 0,
<add> },
<add> inspector: {
<add> backgroundColor: backgroundColor(0.95),
<add> flex: 1,
<add> },
<add> inspectorContainer: {
<add> flex: 1,
<add> },
<add> inspectorButtons: {
<add> flexDirection: 'row',
<add> position: 'absolute',
<add> left: 0,
<add> right: 0,
<add> bottom: 0,
<add> },
<add> inspectorButton: {
<add> flex: 1,
<add> padding: 22,
<add> },
<add> inspectorButtonText: {
<add> color: textColor,
<add> fontSize: 14,
<add> opacity: 0.8,
<add> textAlign: 'center',
<add> },
<add> inspectorContent: {
<add> flex: 1,
<add> paddingTop: 5,
<add> },
<add> inspectorCount: {
<add> padding: 15,
<add> paddingBottom: 0,
<add> },
<add> inspectorCountText: {
<add> color: textColor,
<add> fontSize: 14,
<add> },
<add> inspectorWarning: {
<add> padding: 15,
<add> position: 'absolute',
<add> top: 39,
<add> bottom: 60,
<add> },
<add> inspectorWarningText: {
<add> color: textColor,
<add> fontSize: 16,
<add> fontWeight: '600',
<add> },
<add> list: {
<add> backgroundColor: 'transparent',
<add> position: 'absolute',
<add> left: 0,
<add> right: 0,
<add> bottom: 0,
<add> },
<add> listRow: {
<add> position: 'relative',
<add> backgroundColor: backgroundColor(0.95),
<add> flex: 1,
<add> height: rowHeight,
<add> marginTop: rowGutter,
<add> },
<add> listRowContent: {
<add> flex: 1,
<add> },
<add> listRowCount: {
<add> color: 'rgba(255, 255, 255, 0.5)',
<add> },
<add> listRowText: {
<add> color: textColor,
<add> position: 'absolute',
<add> left: 0,
<add> top: Platform.OS === 'android' ? 5 : 7,
<add> marginLeft: 15,
<add> marginRight: 15,
<add> },
<add>});
<add>
<add>module.exports = YellowBox;
<ide><path>src/renderers/native/ReactIOS/renderApplication.android.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> *
<add> * @providesModule renderApplication
<add> */
<add>
<add>'use strict';
<add>
<add>var Inspector = require('Inspector');
<add>var Portal = require('Portal');
<add>var RCTDeviceEventEmitter = require('RCTDeviceEventEmitter');
<add>var React = require('React');
<add>var StyleSheet = require('StyleSheet');
<add>var Subscribable = require('Subscribable');
<add>var View = require('View');
<add>
<add>var invariant = require('fbjs/lib/invariant');
<add>
<add>var YellowBox = __DEV__ ? require('YellowBox') : null;
<add>
<add>// require BackAndroid so it sets the default handler that exits the app if no listeners respond
<add>require('BackAndroid');
<add>
<add>var AppContainer = React.createClass({
<add> mixins: [Subscribable.Mixin],
<add>
<add> getInitialState: function() {
<add> return {
<add> enabled: __DEV__,
<add> inspectorVisible: false,
<add> rootNodeHandle: null,
<add> rootImportanceForAccessibility: 'auto',
<add> };
<add> },
<add>
<add> toggleElementInspector: function() {
<add> this.setState({
<add> inspectorVisible: !this.state.inspectorVisible,
<add> rootNodeHandle: React.findNodeHandle(this.refs.main),
<add> });
<add> },
<add>
<add> componentDidMount: function() {
<add> this.addListenerOn(
<add> RCTDeviceEventEmitter,
<add> 'toggleElementInspector',
<add> this.toggleElementInspector
<add> );
<add>
<add> this._unmounted = false;
<add> },
<add>
<add> renderInspector: function() {
<add> return this.state.inspectorVisible ?
<add> <Inspector
<add> rootTag={this.props.rootTag}
<add> inspectedViewTag={this.state.rootNodeHandle}
<add> /> :
<add> null;
<add> },
<add>
<add> componentWillUnmount: function() {
<add> this._unmounted = true;
<add> },
<add>
<add> setRootAccessibility: function(modalVisible) {
<add> if (this._unmounted) {
<add> return;
<add> }
<add>
<add> this.setState({
<add> rootImportanceForAccessibility: modalVisible ? 'no-hide-descendants' : 'auto',
<add> });
<add> },
<add>
<add> render: function() {
<add> var RootComponent = this.props.rootComponent;
<add> var appView =
<add> <View
<add> ref="main"
<add> collapsable={!this.state.inspectorVisible}
<add> style={styles.appContainer}>
<add> <RootComponent
<add> {...this.props.initialProps}
<add> rootTag={this.props.rootTag}
<add> importantForAccessibility={this.state.rootImportanceForAccessibility}/>
<add> <Portal
<add> onModalVisibilityChanged={this.setRootAccessibility}/>
<add> </View>;
<add> let yellowBox = null;
<add> if (__DEV__) {
<add> yellowBox = <YellowBox />;
<add> }
<add> return this.state.enabled ?
<add> <View style={styles.appContainer}>
<add> {appView}
<add> {yellowBox}
<add> {this.renderInspector()}
<add> </View> :
<add> appView;
<add> }
<add>});
<add>
<add>function renderApplication<D, P, S>(
<add> RootComponent: ReactClass<P>,
<add> initialProps: P,
<add> rootTag: any
<add>) {
<add> invariant(
<add> rootTag,
<add> 'Expect to have a valid rootTag, instead got ', rootTag
<add> );
<add> React.render(
<add> <AppContainer
<add> rootComponent={RootComponent}
<add> initialProps={initialProps}
<add> rootTag={rootTag} />,
<add> rootTag
<add> );
<add>}
<add>
<add>var styles = StyleSheet.create({
<add> // This is needed so the application covers the whole screen
<add> // and therefore the contents of the Portal are not clipped.
<add> appContainer: {
<add> position: 'absolute',
<add> left: 0,
<add> top: 0,
<add> right: 0,
<add> bottom: 0,
<add> },
<add>});
<add>
<add>module.exports = renderApplication;
<ide><path>src/renderers/native/ReactIOS/renderApplication.ios.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> *
<add> * @providesModule renderApplication
<add> * @noflow
<add> */
<add>
<add>'use strict';
<add>
<add>var RCTDeviceEventEmitter = require('RCTDeviceEventEmitter');
<add>var React = require('React');
<add>var StyleSheet = require('StyleSheet');
<add>var Subscribable = require('Subscribable');
<add>var View = require('View');
<add>
<add>var invariant = require('fbjs/lib/invariant');
<add>
<add>var Inspector = __DEV__ ? require('Inspector') : null;
<add>var YellowBox = __DEV__ ? require('YellowBox') : null;
<add>
<add>var AppContainer = React.createClass({
<add> mixins: [Subscribable.Mixin],
<add>
<add> getInitialState: function() {
<add> return { inspector: null };
<add> },
<add>
<add> toggleElementInspector: function() {
<add> var inspector = !__DEV__ || this.state.inspector
<add> ? null
<add> : <Inspector
<add> rootTag={this.props.rootTag}
<add> inspectedViewTag={React.findNodeHandle(this.refs.main)}
<add> />;
<add> this.setState({inspector});
<add> },
<add>
<add> componentDidMount: function() {
<add> this.addListenerOn(
<add> RCTDeviceEventEmitter,
<add> 'toggleElementInspector',
<add> this.toggleElementInspector
<add> );
<add> },
<add>
<add> render: function() {
<add> let yellowBox = null;
<add> if (__DEV__) {
<add> yellowBox = <YellowBox />;
<add> }
<add> return (
<add> <View style={styles.appContainer}>
<add> <View collapsible={false} style={styles.appContainer} ref="main">
<add> {this.props.children}
<add> </View>
<add> {yellowBox}
<add> {this.state.inspector}
<add> </View>
<add> );
<add> }
<add>});
<add>
<add>function renderApplication<D, P, S>(
<add> RootComponent: ReactClass<P>,
<add> initialProps: P,
<add> rootTag: any
<add>) {
<add> invariant(
<add> rootTag,
<add> 'Expect to have a valid rootTag, instead got ', rootTag
<add> );
<add> /* eslint-disable jsx-no-undef-with-namespace */
<add> React.render(
<add> <AppContainer rootTag={rootTag}>
<add> <RootComponent
<add> {...initialProps}
<add> rootTag={rootTag}
<add> />
<add> </AppContainer>,
<add> rootTag
<add> );
<add> /* eslint-enable jsx-no-undef-with-namespace */
<add>}
<add>
<add>var styles = StyleSheet.create({
<add> appContainer: {
<add> flex: 1,
<add> },
<add>});
<add>
<add>module.exports = renderApplication;
<ide><path>src/renderers/native/ReactIOS/requireNativeComponent.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> *
<add> * @providesModule requireNativeComponent
<add> * @flow
<add> */
<add>'use strict';
<add>
<add>var ReactNativeStyleAttributes = require('ReactNativeStyleAttributes');
<add>var UIManager = require('UIManager');
<add>var UnimplementedView = require('UnimplementedView');
<add>
<add>var createReactNativeComponentClass = require('createReactNativeComponentClass');
<add>
<add>var insetsDiffer = require('insetsDiffer');
<add>var pointsDiffer = require('pointsDiffer');
<add>var matricesDiffer = require('matricesDiffer');
<add>var processColor = require('processColor');
<add>var resolveAssetSource = require('resolveAssetSource');
<add>var sizesDiffer = require('sizesDiffer');
<add>var verifyPropTypes = require('verifyPropTypes');
<add>var warning = require('fbjs/lib/warning');
<add>
<add>/**
<add> * Used to create React components that directly wrap native component
<add> * implementations. Config information is extracted from data exported from the
<add> * UIManager module. You should also wrap the native component in a
<add> * hand-written component with full propTypes definitions and other
<add> * documentation - pass the hand-written component in as `componentInterface` to
<add> * verify all the native props are documented via `propTypes`.
<add> *
<add> * If some native props shouldn't be exposed in the wrapper interface, you can
<add> * pass null for `componentInterface` and call `verifyPropTypes` directly
<add> * with `nativePropsToIgnore`;
<add> *
<add> * Common types are lined up with the appropriate prop differs with
<add> * `TypeToDifferMap`. Non-scalar types not in the map default to `deepDiffer`.
<add> */
<add>import type { ComponentInterface } from 'verifyPropTypes';
<add>
<add>function requireNativeComponent(
<add> viewName: string,
<add> componentInterface?: ?ComponentInterface,
<add> extraConfig?: ?{nativeOnly?: Object},
<add>): Function {
<add> var viewConfig = UIManager[viewName];
<add> if (!viewConfig || !viewConfig.NativeProps) {
<add> warning(false, 'Native component for "%s" does not exist', viewName);
<add> return UnimplementedView;
<add> }
<add> var nativeProps = {
<add> ...UIManager.RCTView.NativeProps,
<add> ...viewConfig.NativeProps,
<add> };
<add> viewConfig.uiViewClassName = viewName;
<add> viewConfig.validAttributes = {};
<add> viewConfig.propTypes = componentInterface && componentInterface.propTypes;
<add> for (var key in nativeProps) {
<add> var useAttribute = false;
<add> var attribute = {};
<add>
<add> var differ = TypeToDifferMap[nativeProps[key]];
<add> if (differ) {
<add> attribute.diff = differ;
<add> useAttribute = true;
<add> }
<add>
<add> var processor = TypeToProcessorMap[nativeProps[key]];
<add> if (processor) {
<add> attribute.process = processor;
<add> useAttribute = true;
<add> }
<add>
<add> viewConfig.validAttributes[key] = useAttribute ? attribute : true;
<add> }
<add>
<add> // Unfortunately, the current set up puts the style properties on the top
<add> // level props object. We also need to add the nested form for API
<add> // compatibility. This allows these props on both the top level and the
<add> // nested style level. TODO: Move these to nested declarations on the
<add> // native side.
<add> viewConfig.validAttributes.style = ReactNativeStyleAttributes;
<add>
<add> if (__DEV__) {
<add> componentInterface && verifyPropTypes(
<add> componentInterface,
<add> viewConfig,
<add> extraConfig && extraConfig.nativeOnly
<add> );
<add> }
<add> return createReactNativeComponentClass(viewConfig);
<add>}
<add>
<add>var TypeToDifferMap = {
<add> // iOS Types
<add> CATransform3D: matricesDiffer,
<add> CGPoint: pointsDiffer,
<add> CGSize: sizesDiffer,
<add> UIEdgeInsets: insetsDiffer,
<add> // Android Types
<add> // (not yet implemented)
<add>};
<add>
<add>function processColorArray(colors: []): [] {
<add> return colors && colors.map(processColor);
<add>}
<add>
<add>var TypeToProcessorMap = {
<add> // iOS Types
<add> CGColor: processColor,
<add> CGColorArray: processColorArray,
<add> UIColor: processColor,
<add> UIColorArray: processColorArray,
<add> CGImage: resolveAssetSource,
<add> UIImage: resolveAssetSource,
<add> RCTImageSource: resolveAssetSource,
<add> // Android Types
<add> Color: processColor,
<add> ColorArray: processColorArray,
<add>};
<add>
<add>module.exports = requireNativeComponent;
<ide><path>src/renderers/native/ReactIOS/verifyPropTypes.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> *
<add> * @providesModule verifyPropTypes
<add> * @flow
<add> */
<add>'use strict';
<add>
<add>var ReactNativeStyleAttributes = require('ReactNativeStyleAttributes');
<add>
<add>export type ComponentInterface = ReactClass<any> | {
<add> name?: string;
<add> displayName?: string;
<add> propTypes: Object;
<add>};
<add>
<add>function verifyPropTypes(
<add> componentInterface: ComponentInterface,
<add> viewConfig: Object,
<add> nativePropsToIgnore?: ?Object
<add>) {
<add> if (!viewConfig) {
<add> return; // This happens for UnimplementedView.
<add> }
<add> var componentName = componentInterface.name ||
<add> componentInterface.displayName ||
<add> 'unknown';
<add> if (!componentInterface.propTypes) {
<add> throw new Error(
<add> '`' + componentName + '` has no propTypes defined`'
<add> );
<add> }
<add>
<add> var nativeProps = viewConfig.NativeProps;
<add> for (var prop in nativeProps) {
<add> if (!componentInterface.propTypes[prop] &&
<add> !ReactNativeStyleAttributes[prop] &&
<add> (!nativePropsToIgnore || !nativePropsToIgnore[prop])) {
<add> var message;
<add> if (componentInterface.propTypes.hasOwnProperty(prop)) {
<add> message = '`' + componentName + '` has incorrectly defined propType for native prop `' +
<add> viewConfig.uiViewClassName + '.' + prop + '` of native type `' + nativeProps[prop];
<add> } else {
<add> message = '`' + componentName + '` has no propType for native prop `' +
<add> viewConfig.uiViewClassName + '.' + prop + '` of native type `' +
<add> nativeProps[prop] + '`';
<add> };
<add> message += '\nIf you haven\'t changed this prop yourself, this usually means that ' +
<add> 'your versions of the native code and JavaScript code are out of sync. Updating both ' +
<add> 'should make this error go away.';
<add> throw new Error(message);
<add> }
<add> }
<add>}
<add>
<add>module.exports = verifyPropTypes;
<ide><path>src/renderers/native/ReactNative/React.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> *
<add> * @providesModule React
<add> * @flow
<add> */
<add>'use strict';
<add>
<add>module.exports = require('ReactNative');
<ide><path>src/renderers/native/ReactNative/ReactDOM.js
<add>/**
<add> * Copyright 2004-present Facebook. All Rights Reserved.
<add> *
<add> * @providesModule ReactDOM
<add> */
<add>
<add>'use strict';
<add>
<add>var ReactUpdates = require('ReactUpdates');
<add>
<add>// Temporary shim required for ReactTestUtils and Relay.
<add>var ReactDOM = {
<add> unstable_batchedUpdates: ReactUpdates.batchedUpdates,
<add>};
<add>
<add>module.exports = ReactDOM;
<ide><path>src/renderers/native/ReactNative/ReactNative.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> *
<add> * @providesModule ReactNative
<add> * @flow
<add> */
<add>'use strict';
<add>
<add>// Require ReactNativeDefaultInjection first for its side effects of setting up
<add>// the JS environment
<add>var ReactNativeDefaultInjection = require('ReactNativeDefaultInjection');
<add>
<add>var ReactChildren = require('ReactChildren');
<add>var ReactClass = require('ReactClass');
<add>var ReactComponent = require('ReactComponent');
<add>var ReactCurrentOwner = require('ReactCurrentOwner');
<add>var ReactElement = require('ReactElement');
<add>var ReactElementValidator = require('ReactElementValidator');
<add>var ReactInstanceHandles = require('ReactInstanceHandles');
<add>var ReactNativeMount = require('ReactNativeMount');
<add>var ReactPropTypes = require('ReactPropTypes');
<add>var ReactUpdates = require('ReactUpdates');
<add>
<add>var findNodeHandle = require('findNodeHandle');
<add>var invariant = require('fbjs/lib/invariant');
<add>var onlyChild = require('onlyChild');
<add>var warning = require('fbjs/lib/warning');
<add>
<add>ReactNativeDefaultInjection.inject();
<add>
<add>var createElement = ReactElement.createElement;
<add>var createFactory = ReactElement.createFactory;
<add>var cloneElement = ReactElement.cloneElement;
<add>
<add>if (__DEV__) {
<add> createElement = ReactElementValidator.createElement;
<add> createFactory = ReactElementValidator.createFactory;
<add> cloneElement = ReactElementValidator.cloneElement;
<add>}
<add>
<add>var resolveDefaultProps = function(element) {
<add> // Could be optimized, but not currently in heavy use.
<add> var defaultProps = element.type.defaultProps;
<add> var props = element.props;
<add> for (var propName in defaultProps) {
<add> if (props[propName] === undefined) {
<add> props[propName] = defaultProps[propName];
<add> }
<add> }
<add>};
<add>
<add>// Experimental optimized element creation
<add>var augmentElement = function(element: ReactElement): ReactElement {
<add> if (__DEV__) {
<add> invariant(
<add> false,
<add> 'This optimized path should never be used in DEV mode because ' +
<add> 'it does not provide validation. Check your JSX transform.'
<add> );
<add> }
<add> element._owner = ReactCurrentOwner.current;
<add> if (element.type.defaultProps) {
<add> resolveDefaultProps(element);
<add> }
<add> return element;
<add>};
<add>
<add>var render = function(
<add> element: ReactElement,
<add> mountInto: number,
<add> callback?: ?(() => void)
<add>): ?ReactComponent {
<add> return ReactNativeMount.renderComponent(element, mountInto, callback);
<add>};
<add>
<add>var ReactNative = {
<add> hasReactNativeInitialized: false,
<add> Children: {
<add> map: ReactChildren.map,
<add> forEach: ReactChildren.forEach,
<add> count: ReactChildren.count,
<add> toArray: ReactChildren.toArray,
<add> only: onlyChild
<add> },
<add> Component: ReactComponent,
<add> PropTypes: ReactPropTypes,
<add> createClass: ReactClass.createClass,
<add> createElement: createElement,
<add> createFactory: createFactory,
<add> cloneElement: cloneElement,
<add> _augmentElement: augmentElement,
<add> findNodeHandle: findNodeHandle,
<add> render: render,
<add> unmountComponentAtNode: ReactNativeMount.unmountComponentAtNode,
<add>
<add> /* eslint-disable camelcase */
<add> unstable_batchedUpdates: ReactUpdates.batchedUpdates,
<add> /* eslint-enable camelcase */
<add>
<add> // Hook for JSX spread, don't use this for anything else.
<add> __spread: Object.assign,
<add>
<add> unmountComponentAtNodeAndRemoveContainer: ReactNativeMount.unmountComponentAtNodeAndRemoveContainer,
<add> isValidClass: ReactElement.isValidFactory,
<add> isValidElement: ReactElement.isValidElement,
<add>
<add> // Deprecations (remove for 0.13)
<add> renderComponent: function(
<add> element: ReactElement,
<add> mountInto: number,
<add> callback?: ?(() => void)
<add> ): ?ReactComponent {
<add> warning('Use React.render instead of React.renderComponent');
<add> return ReactNative.render(element, mountInto, callback);
<add> },
<add>};
<add>
<add>// Inject the runtime into a devtools global hook regardless of browser.
<add>// Allows for debugging when the hook is injected on the page.
<add>/* globals __REACT_DEVTOOLS_GLOBAL_HOOK__ */
<add>if (
<add> typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
<add> typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject === 'function') {
<add> __REACT_DEVTOOLS_GLOBAL_HOOK__.inject({
<add> CurrentOwner: ReactCurrentOwner,
<add> InstanceHandles: ReactInstanceHandles,
<add> Mount: ReactNativeMount,
<add> Reconciler: require('ReactReconciler'),
<add> TextComponent: require('ReactNativeTextComponent'),
<add> });
<add>}
<add>
<add>module.exports = ReactNative;
<ide><path>src/renderers/native/ReactNative/ReactNativeAttributePayload.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> *
<add> * @providesModule ReactNativeAttributePayload
<add> * @flow
<add> */
<add>'use strict';
<add>
<add>var Platform = require('Platform');
<add>var ReactNativePropRegistry = require('ReactNativePropRegistry');
<add>
<add>var deepDiffer = require('deepDiffer');
<add>var flattenStyle = require('flattenStyle');
<add>
<add>var emptyObject = {};
<add>
<add>/**
<add> * Create a payload that contains all the updates between two sets of props.
<add> *
<add> * These helpers are all encapsulated into a single module, because they use
<add> * mutation as a performance optimization which leads to subtle shared
<add> * dependencies between the code paths. To avoid this mutable state leaking
<add> * across modules, I've kept them isolated to this module.
<add> */
<add>
<add>type AttributeDiffer = (prevProp: mixed, nextProp: mixed) => boolean;
<add>type AttributePreprocessor = (nextProp: mixed) => mixed;
<add>
<add>type CustomAttributeConfiguration =
<add> { diff: AttributeDiffer, process: AttributePreprocessor } |
<add> { diff: AttributeDiffer } |
<add> { process: AttributePreprocessor };
<add>
<add>type AttributeConfiguration =
<add> { [key: string]: (
<add> CustomAttributeConfiguration | AttributeConfiguration /*| boolean*/
<add> ) };
<add>
<add>type NestedNode = Array<NestedNode> | Object | number;
<add>
<add>// Tracks removed keys
<add>var removedKeys = null;
<add>var removedKeyCount = 0;
<add>
<add>function translateKey(propKey: string) : string {
<add> if (propKey === 'transform') {
<add> // We currently special case the key for `transform`. iOS uses the
<add> // transformMatrix name and Android uses the decomposedMatrix name.
<add> // TODO: We could unify these names and just use the name `transform`
<add> // all the time. Just need to update the native side.
<add> if (Platform.OS === 'android') {
<add> return 'decomposedMatrix';
<add> } else {
<add> return 'transformMatrix';
<add> }
<add> }
<add> return propKey;
<add>}
<add>
<add>function defaultDiffer(prevProp: mixed, nextProp: mixed) : boolean {
<add> if (typeof nextProp !== 'object' || nextProp === null) {
<add> // Scalars have already been checked for equality
<add> return true;
<add> } else {
<add> // For objects and arrays, the default diffing algorithm is a deep compare
<add> return deepDiffer(prevProp, nextProp);
<add> }
<add>}
<add>
<add>function resolveObject(idOrObject: number | Object) : Object {
<add> if (typeof idOrObject === 'number') {
<add> return ReactNativePropRegistry.getByID(idOrObject);
<add> }
<add> return idOrObject;
<add>}
<add>
<add>function restoreDeletedValuesInNestedArray(
<add> updatePayload: Object,
<add> node: NestedNode,
<add> validAttributes: AttributeConfiguration
<add>) {
<add> if (Array.isArray(node)) {
<add> var i = node.length;
<add> while (i-- && removedKeyCount > 0) {
<add> restoreDeletedValuesInNestedArray(
<add> updatePayload,
<add> node[i],
<add> validAttributes
<add> );
<add> }
<add> } else if (node && removedKeyCount > 0) {
<add> var obj = resolveObject(node);
<add> for (var propKey in removedKeys) {
<add> if (!removedKeys[propKey]) {
<add> continue;
<add> }
<add> var nextProp = obj[propKey];
<add> if (nextProp === undefined) {
<add> continue;
<add> }
<add>
<add> var attributeConfig = validAttributes[propKey];
<add> if (!attributeConfig) {
<add> continue; // not a valid native prop
<add> }
<add>
<add> if (typeof nextProp === 'function') {
<add> nextProp = true;
<add> }
<add> if (typeof nextProp === 'undefined') {
<add> nextProp = null;
<add> }
<add>
<add> if (typeof attributeConfig !== 'object') {
<add> // case: !Object is the default case
<add> updatePayload[propKey] = nextProp;
<add> } else if (typeof attributeConfig.diff === 'function' ||
<add> typeof attributeConfig.process === 'function') {
<add> // case: CustomAttributeConfiguration
<add> var nextValue = typeof attributeConfig.process === 'function' ?
<add> attributeConfig.process(nextProp) :
<add> nextProp;
<add> updatePayload[propKey] = nextValue;
<add> }
<add> removedKeys[propKey] = false;
<add> removedKeyCount--;
<add> }
<add> }
<add>}
<add>
<add>function diffNestedArrayProperty(
<add> updatePayload:? Object,
<add> prevArray: Array<NestedNode>,
<add> nextArray: Array<NestedNode>,
<add> validAttributes: AttributeConfiguration
<add>) : ?Object {
<add> var minLength = prevArray.length < nextArray.length ?
<add> prevArray.length :
<add> nextArray.length;
<add> var i;
<add> for (i = 0; i < minLength; i++) {
<add> // Diff any items in the array in the forward direction. Repeated keys
<add> // will be overwritten by later values.
<add> updatePayload = diffNestedProperty(
<add> updatePayload,
<add> prevArray[i],
<add> nextArray[i],
<add> validAttributes
<add> );
<add> }
<add> for (; i < prevArray.length; i++) {
<add> // Clear out all remaining properties.
<add> updatePayload = clearNestedProperty(
<add> updatePayload,
<add> prevArray[i],
<add> validAttributes
<add> );
<add> }
<add> for (; i < nextArray.length; i++) {
<add> // Add all remaining properties.
<add> updatePayload = addNestedProperty(
<add> updatePayload,
<add> nextArray[i],
<add> validAttributes
<add> );
<add> }
<add> return updatePayload;
<add>}
<add>
<add>function diffNestedProperty(
<add> updatePayload:? Object,
<add> prevProp: NestedNode,
<add> nextProp: NestedNode,
<add> validAttributes: AttributeConfiguration
<add>) : ?Object {
<add>
<add> if (!updatePayload && prevProp === nextProp) {
<add> // If no properties have been added, then we can bail out quickly on object
<add> // equality.
<add> return updatePayload;
<add> }
<add>
<add> if (!prevProp || !nextProp) {
<add> if (nextProp) {
<add> return addNestedProperty(
<add> updatePayload,
<add> nextProp,
<add> validAttributes
<add> );
<add> }
<add> if (prevProp) {
<add> return clearNestedProperty(
<add> updatePayload,
<add> prevProp,
<add> validAttributes
<add> );
<add> }
<add> return updatePayload;
<add> }
<add>
<add> if (!Array.isArray(prevProp) && !Array.isArray(nextProp)) {
<add> // Both are leaves, we can diff the leaves.
<add> return diffProperties(
<add> updatePayload,
<add> resolveObject(prevProp),
<add> resolveObject(nextProp),
<add> validAttributes
<add> );
<add> }
<add>
<add> if (Array.isArray(prevProp) && Array.isArray(nextProp)) {
<add> // Both are arrays, we can diff the arrays.
<add> return diffNestedArrayProperty(
<add> updatePayload,
<add> prevProp,
<add> nextProp,
<add> validAttributes
<add> );
<add> }
<add>
<add> if (Array.isArray(prevProp)) {
<add> return diffProperties(
<add> updatePayload,
<add> // $FlowFixMe - We know that this is always an object when the input is.
<add> flattenStyle(prevProp),
<add> // $FlowFixMe - We know that this isn't an array because of above flow.
<add> resolveObject(nextProp),
<add> validAttributes
<add> );
<add> }
<add>
<add> return diffProperties(
<add> updatePayload,
<add> resolveObject(prevProp),
<add> // $FlowFixMe - We know that this is always an object when the input is.
<add> flattenStyle(nextProp),
<add> validAttributes
<add> );
<add>}
<add>
<add>/**
<add> * addNestedProperty takes a single set of props and valid attribute
<add> * attribute configurations. It processes each prop and adds it to the
<add> * updatePayload.
<add> */
<add>function addNestedProperty(
<add> updatePayload:? Object,
<add> nextProp: NestedNode,
<add> validAttributes: AttributeConfiguration
<add>) {
<add> if (!nextProp) {
<add> return updatePayload;
<add> }
<add>
<add> if (!Array.isArray(nextProp)) {
<add> // Add each property of the leaf.
<add> return addProperties(
<add> updatePayload,
<add> resolveObject(nextProp),
<add> validAttributes
<add> );
<add> }
<add>
<add> for (var i = 0; i < nextProp.length; i++) {
<add> // Add all the properties of the array.
<add> updatePayload = addNestedProperty(
<add> updatePayload,
<add> nextProp[i],
<add> validAttributes
<add> );
<add> }
<add>
<add> return updatePayload;
<add>}
<add>
<add>/**
<add> * clearNestedProperty takes a single set of props and valid attributes. It
<add> * adds a null sentinel to the updatePayload, for each prop key.
<add> */
<add>function clearNestedProperty(
<add> updatePayload:? Object,
<add> prevProp: NestedNode,
<add> validAttributes: AttributeConfiguration
<add>) : ?Object {
<add> if (!prevProp) {
<add> return updatePayload;
<add> }
<add>
<add> if (!Array.isArray(prevProp)) {
<add> // Add each property of the leaf.
<add> return clearProperties(
<add> updatePayload,
<add> resolveObject(prevProp),
<add> validAttributes
<add> );
<add> }
<add>
<add> for (var i = 0; i < prevProp.length; i++) {
<add> // Add all the properties of the array.
<add> updatePayload = clearNestedProperty(
<add> updatePayload,
<add> prevProp[i],
<add> validAttributes
<add> );
<add> }
<add> return updatePayload;
<add>}
<add>
<add>/**
<add> * diffProperties takes two sets of props and a set of valid attributes
<add> * and write to updatePayload the values that changed or were deleted.
<add> * If no updatePayload is provided, a new one is created and returned if
<add> * anything changed.
<add> */
<add>function diffProperties(
<add> updatePayload: ?Object,
<add> prevProps: Object,
<add> nextProps: Object,
<add> validAttributes: AttributeConfiguration
<add>): ?Object {
<add> var attributeConfig : ?(CustomAttributeConfiguration | AttributeConfiguration);
<add> var nextProp;
<add> var prevProp;
<add> var altKey;
<add>
<add> for (var propKey in nextProps) {
<add> attributeConfig = validAttributes[propKey];
<add> if (!attributeConfig) {
<add> continue; // not a valid native prop
<add> }
<add>
<add> altKey = translateKey(propKey);
<add> if (!validAttributes[altKey]) {
<add> // If there is no config for the alternative, bail out. Helps ART.
<add> altKey = propKey;
<add> }
<add>
<add> prevProp = prevProps[propKey];
<add> nextProp = nextProps[propKey];
<add>
<add> // functions are converted to booleans as markers that the associated
<add> // events should be sent from native.
<add> if (typeof nextProp === 'function') {
<add> nextProp = (true : any);
<add> // If nextProp is not a function, then don't bother changing prevProp
<add> // since nextProp will win and go into the updatePayload regardless.
<add> if (typeof prevProp === 'function') {
<add> prevProp = (true : any);
<add> }
<add> }
<add>
<add> // An explicit value of undefined is treated as a null because it overrides
<add> // any other preceeding value.
<add> if (typeof nextProp === 'undefined') {
<add> nextProp = (null : any);
<add> if (typeof prevProp === 'undefined') {
<add> prevProp = (null : any);
<add> }
<add> }
<add>
<add> if (removedKeys) {
<add> removedKeys[propKey] = false;
<add> }
<add>
<add> if (updatePayload && updatePayload[altKey] !== undefined) {
<add> // Something else already triggered an update to this key because another
<add> // value diffed. Since we're now later in the nested arrays our value is
<add> // more important so we need to calculate it and override the existing
<add> // value. It doesn't matter if nothing changed, we'll set it anyway.
<add>
<add> // Pattern match on: attributeConfig
<add> if (typeof attributeConfig !== 'object') {
<add> // case: !Object is the default case
<add> updatePayload[altKey] = nextProp;
<add> } else if (typeof attributeConfig.diff === 'function' ||
<add> typeof attributeConfig.process === 'function') {
<add> // case: CustomAttributeConfiguration
<add> var nextValue = typeof attributeConfig.process === 'function' ?
<add> attributeConfig.process(nextProp) :
<add> nextProp;
<add> updatePayload[altKey] = nextValue;
<add> }
<add> continue;
<add> }
<add>
<add> if (prevProp === nextProp) {
<add> continue; // nothing changed
<add> }
<add>
<add> // Pattern match on: attributeConfig
<add> if (typeof attributeConfig !== 'object') {
<add> // case: !Object is the default case
<add> if (defaultDiffer(prevProp, nextProp)) {
<add> // a normal leaf has changed
<add> (updatePayload || (updatePayload = {}))[altKey] = nextProp;
<add> }
<add> } else if (typeof attributeConfig.diff === 'function' ||
<add> typeof attributeConfig.process === 'function') {
<add> // case: CustomAttributeConfiguration
<add> var shouldUpdate = prevProp === undefined || (
<add> typeof attributeConfig.diff === 'function' ?
<add> attributeConfig.diff(prevProp, nextProp) :
<add> defaultDiffer(prevProp, nextProp)
<add> );
<add> if (shouldUpdate) {
<add> var nextValue = typeof attributeConfig.process === 'function' ?
<add> attributeConfig.process(nextProp) :
<add> nextProp;
<add> (updatePayload || (updatePayload = {}))[altKey] = nextValue;
<add> }
<add> } else {
<add> // default: fallthrough case when nested properties are defined
<add> removedKeys = null;
<add> removedKeyCount = 0;
<add> updatePayload = diffNestedProperty(
<add> updatePayload,
<add> prevProp,
<add> nextProp,
<add> attributeConfig
<add> );
<add> if (removedKeyCount > 0 && updatePayload) {
<add> restoreDeletedValuesInNestedArray(
<add> updatePayload,
<add> nextProp,
<add> attributeConfig
<add> );
<add> removedKeys = null;
<add> }
<add> }
<add> }
<add>
<add> // Also iterate through all the previous props to catch any that have been
<add> // removed and make sure native gets the signal so it can reset them to the
<add> // default.
<add> for (var propKey in prevProps) {
<add> if (nextProps[propKey] !== undefined) {
<add> continue; // we've already covered this key in the previous pass
<add> }
<add> attributeConfig = validAttributes[propKey];
<add> if (!attributeConfig) {
<add> continue; // not a valid native prop
<add> }
<add>
<add> altKey = translateKey(propKey);
<add> if (!attributeConfig[altKey]) {
<add> // If there is no config for the alternative, bail out. Helps ART.
<add> altKey = propKey;
<add> }
<add>
<add> if (updatePayload && updatePayload[altKey] !== undefined) {
<add> // This was already updated to a diff result earlier.
<add> continue;
<add> }
<add>
<add> prevProp = prevProps[propKey];
<add> if (prevProp === undefined) {
<add> continue; // was already empty anyway
<add> }
<add> // Pattern match on: attributeConfig
<add> if (typeof attributeConfig !== 'object' ||
<add> typeof attributeConfig.diff === 'function' ||
<add> typeof attributeConfig.process === 'function') {
<add>
<add> // case: CustomAttributeConfiguration | !Object
<add> // Flag the leaf property for removal by sending a sentinel.
<add> (updatePayload || (updatePayload = {}))[altKey] = null;
<add> if (!removedKeys) {
<add> removedKeys = {};
<add> }
<add> if (!removedKeys[propKey]) {
<add> removedKeys[propKey] = true;
<add> removedKeyCount++;
<add> }
<add> } else {
<add> // default:
<add> // This is a nested attribute configuration where all the properties
<add> // were removed so we need to go through and clear out all of them.
<add> updatePayload = clearNestedProperty(
<add> updatePayload,
<add> prevProp,
<add> attributeConfig
<add> );
<add> }
<add> }
<add> return updatePayload;
<add>}
<add>
<add>/**
<add> * addProperties adds all the valid props to the payload after being processed.
<add> */
<add>function addProperties(
<add> updatePayload: ?Object,
<add> props: Object,
<add> validAttributes: AttributeConfiguration
<add>) : ?Object {
<add> // TODO: Fast path
<add> return diffProperties(updatePayload, emptyObject, props, validAttributes);
<add>}
<add>
<add>/**
<add> * clearProperties clears all the previous props by adding a null sentinel
<add> * to the payload for each valid key.
<add> */
<add>function clearProperties(
<add> updatePayload: ?Object,
<add> prevProps: Object,
<add> validAttributes: AttributeConfiguration
<add>) :? Object {
<add> // TODO: Fast path
<add> return diffProperties(updatePayload, prevProps, emptyObject, validAttributes);
<add>}
<add>
<add>var ReactNativeAttributePayload = {
<add>
<add> create: function(
<add> props: Object,
<add> validAttributes: AttributeConfiguration
<add> ) : ?Object {
<add> return addProperties(
<add> null, // updatePayload
<add> props,
<add> validAttributes
<add> );
<add> },
<add>
<add> diff: function(
<add> prevProps: Object,
<add> nextProps: Object,
<add> validAttributes: AttributeConfiguration
<add> ) : ?Object {
<add> return diffProperties(
<add> null, // updatePayload
<add> prevProps,
<add> nextProps,
<add> validAttributes
<add> );
<add> }
<add>
<add>};
<add>
<add>module.exports = ReactNativeAttributePayload;
<ide><path>src/renderers/native/ReactNative/ReactNativeBaseComponent.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> *
<add> * @providesModule ReactNativeBaseComponent
<add> * @flow
<add> */
<add>'use strict';
<add>
<add>var NativeMethodsMixin = require('NativeMethodsMixin');
<add>var ReactNativeAttributePayload = require('ReactNativeAttributePayload');
<add>var ReactNativeEventEmitter = require('ReactNativeEventEmitter');
<add>var ReactNativeTagHandles = require('ReactNativeTagHandles');
<add>var ReactMultiChild = require('ReactMultiChild');
<add>var UIManager = require('UIManager');
<add>
<add>var deepFreezeAndThrowOnMutationInDev = require('deepFreezeAndThrowOnMutationInDev');
<add>var invariant = require('fbjs/lib/invariant');
<add>var warning = require('fbjs/lib/warning');
<add>
<add>var registrationNames = ReactNativeEventEmitter.registrationNames;
<add>var putListener = ReactNativeEventEmitter.putListener;
<add>var deleteListener = ReactNativeEventEmitter.deleteListener;
<add>var deleteAllListeners = ReactNativeEventEmitter.deleteAllListeners;
<add>
<add>type ReactNativeBaseComponentViewConfig = {
<add> validAttributes: Object;
<add> uiViewClassName: string;
<add>}
<add>
<add>// require('UIManagerStatTracker').install(); // uncomment to enable
<add>
<add>/**
<add> * @constructor ReactNativeBaseComponent
<add> * @extends ReactComponent
<add> * @extends ReactMultiChild
<add> * @param {!object} UIKit View Configuration.
<add> */
<add>var ReactNativeBaseComponent = function(
<add> viewConfig: ReactNativeBaseComponentViewConfig
<add>) {
<add> this.viewConfig = viewConfig;
<add>};
<add>
<add>/**
<add> * Mixin for containers that contain UIViews. NOTE: markup is rendered markup
<add> * which is a `viewID` ... see the return value for `mountComponent` !
<add> */
<add>ReactNativeBaseComponent.Mixin = {
<add> getPublicInstance: function() {
<add> // TODO: This should probably use a composite wrapper
<add> return this;
<add> },
<add>
<add> construct: function(element) {
<add> this._currentElement = element;
<add> },
<add>
<add> unmountComponent: function() {
<add> deleteAllListeners(this._rootNodeID);
<add> this.unmountChildren();
<add> this._rootNodeID = null;
<add> },
<add>
<add> /**
<add> * Every native component is responsible for allocating its own `tag`, and
<add> * issuing the native `createView` command. But it is not responsible for
<add> * recording the fact that its own `rootNodeID` is associated with a
<add> * `nodeHandle`. Only the code that actually adds its `nodeHandle` (`tag`) as
<add> * a child of a container can confidently record that in
<add> * `ReactNativeTagHandles`.
<add> */
<add> initializeChildren: function(children, containerTag, transaction, context) {
<add> var mountImages = this.mountChildren(children, transaction, context);
<add> // In a well balanced tree, half of the nodes are in the bottom row and have
<add> // no children - let's avoid calling out to the native bridge for a large
<add> // portion of the children.
<add> if (mountImages.length) {
<add>
<add> // TODO: Pool these per platform view class. Reusing the `mountImages`
<add> // array would likely be a jit deopt.
<add> var createdTags = [];
<add> for (var i = 0, l = mountImages.length; i < l; i++) {
<add> var mountImage = mountImages[i];
<add> var childTag = mountImage.tag;
<add> var childID = mountImage.rootNodeID;
<add> warning(
<add> mountImage && mountImage.rootNodeID && mountImage.tag,
<add> 'Mount image returned does not have required data'
<add> );
<add> ReactNativeTagHandles.associateRootNodeIDWithMountedNodeHandle(
<add> childID,
<add> childTag
<add> );
<add> createdTags[i] = mountImage.tag;
<add> }
<add> UIManager.setChildren(containerTag, createdTags);
<add> }
<add> },
<add>
<add> /**
<add> * Updates the component's currently mounted representation.
<add> *
<add> * @param {object} nextElement
<add> * @param {ReactReconcileTransaction} transaction
<add> * @param {object} context
<add> * @internal
<add> */
<add> receiveComponent: function(nextElement, transaction, context) {
<add> var prevElement = this._currentElement;
<add> this._currentElement = nextElement;
<add>
<add> if (__DEV__) {
<add> for (var key in this.viewConfig.validAttributes) {
<add> if (nextElement.props.hasOwnProperty(key)) {
<add> deepFreezeAndThrowOnMutationInDev(nextElement.props[key]);
<add> }
<add> }
<add> }
<add>
<add> var updatePayload = ReactNativeAttributePayload.diff(
<add> prevElement.props,
<add> nextElement.props,
<add> this.viewConfig.validAttributes
<add> );
<add>
<add> if (updatePayload) {
<add> UIManager.updateView(
<add> ReactNativeTagHandles.mostRecentMountedNodeHandleForRootNodeID(this._rootNodeID),
<add> this.viewConfig.uiViewClassName,
<add> updatePayload
<add> );
<add> }
<add>
<add> this._reconcileListenersUponUpdate(
<add> prevElement.props,
<add> nextElement.props
<add> );
<add> this.updateChildren(nextElement.props.children, transaction, context);
<add> },
<add>
<add> /**
<add> * @param {object} initialProps Native component props.
<add> */
<add> _registerListenersUponCreation: function(initialProps) {
<add> for (var key in initialProps) {
<add> // NOTE: The check for `!props[key]`, is only possible because this method
<add> // registers listeners the *first* time a component is created.
<add> if (registrationNames[key] && initialProps[key]) {
<add> var listener = initialProps[key];
<add> putListener(this._rootNodeID, key, listener);
<add> }
<add> }
<add> },
<add>
<add> /**
<add> * Reconciles event listeners, adding or removing if necessary.
<add> * @param {object} prevProps Native component props including events.
<add> * @param {object} nextProps Next native component props including events.
<add> */
<add> _reconcileListenersUponUpdate: function(prevProps, nextProps) {
<add> for (var key in nextProps) {
<add> if (registrationNames[key] && (nextProps[key] !== prevProps[key])) {
<add> if (nextProps[key]) {
<add> putListener(this._rootNodeID, key, nextProps[key]);
<add> } else {
<add> deleteListener(this._rootNodeID, key);
<add> }
<add> }
<add> }
<add> },
<add>
<add> /**
<add> * @param {string} rootID Root ID of this subtree.
<add> * @param {Transaction} transaction For creating/updating.
<add> * @return {string} Unique iOS view tag.
<add> */
<add> mountComponent: function(rootID, transaction, context) {
<add> this._rootNodeID = rootID;
<add>
<add> var tag = ReactNativeTagHandles.allocateTag();
<add>
<add> if (__DEV__) {
<add> for (var key in this.viewConfig.validAttributes) {
<add> if (this._currentElement.props.hasOwnProperty(key)) {
<add> deepFreezeAndThrowOnMutationInDev(this._currentElement.props[key]);
<add> }
<add> }
<add> }
<add>
<add> var updatePayload = ReactNativeAttributePayload.create(
<add> this._currentElement.props,
<add> this.viewConfig.validAttributes
<add> );
<add>
<add> var nativeTopRootID = ReactNativeTagHandles.getNativeTopRootIDFromNodeID(rootID);
<add> if (nativeTopRootID == null) {
<add> invariant(
<add> false,
<add> 'nativeTopRootID not found for tag ' + tag + ' view type ' +
<add> this.viewConfig.uiViewClassName + ' with rootID ' + rootID);
<add> }
<add> UIManager.createView(
<add> tag,
<add> this.viewConfig.uiViewClassName,
<add> ReactNativeTagHandles.rootNodeIDToTag[nativeTopRootID],
<add> updatePayload
<add> );
<add>
<add> this._registerListenersUponCreation(this._currentElement.props);
<add> this.initializeChildren(
<add> this._currentElement.props.children,
<add> tag,
<add> transaction,
<add> context
<add> );
<add> return {
<add> rootNodeID: rootID,
<add> tag: tag
<add> };
<add> }
<add>};
<add>
<add>/**
<add> * Order of mixins is important. ReactNativeBaseComponent overrides methods in
<add> * ReactMultiChild.
<add> */
<add>Object.assign(
<add> ReactNativeBaseComponent.prototype,
<add> ReactMultiChild.Mixin,
<add> ReactNativeBaseComponent.Mixin,
<add> NativeMethodsMixin
<add>);
<add>
<add>module.exports = ReactNativeBaseComponent;
<ide><path>src/renderers/native/ReactNative/ReactNativeBaseComponentEnvironment.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> *
<add> * @providesModule ReactNativeComponentEnvironment
<add> * @flow
<add> */
<add>'use strict';
<add>
<add>var ReactNativeDOMIDOperations = require('ReactNativeDOMIDOperations');
<add>var ReactNativeReconcileTransaction = require('ReactNativeReconcileTransaction');
<add>
<add>var ReactNativeComponentEnvironment = {
<add>
<add> processChildrenUpdates: ReactNativeDOMIDOperations.dangerouslyProcessChildrenUpdates,
<add>
<add> replaceNodeWithMarkupByID: ReactNativeDOMIDOperations.dangerouslyReplaceNodeWithMarkupByID,
<add>
<add> /**
<add> * Nothing to do for UIKit bridge.
<add> *
<add> * @private
<add> */
<add> unmountIDFromEnvironment: function(/*rootNodeID*/) {
<add>
<add> },
<add>
<add> /**
<add> * @param {DOMElement} Element to clear.
<add> */
<add> clearNode: function(/*containerView*/) {
<add>
<add> },
<add>
<add> ReactReconcileTransaction: ReactNativeReconcileTransaction,
<add>};
<add>
<add>module.exports = ReactNativeComponentEnvironment;
<ide><path>src/renderers/native/ReactNative/ReactNativeDOMIDOperations.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> *
<add> * @providesModule ReactNativeDOMIDOperations
<add> * @flow
<add> */
<add>'use strict';
<add>
<add>var ReactNativeTagHandles = require('ReactNativeTagHandles');
<add>var ReactMultiChildUpdateTypes = require('ReactMultiChildUpdateTypes');
<add>var ReactPerf = require('ReactPerf');
<add>var UIManager = require('UIManager');
<add>
<add>/**
<add> * Updates a component's children by processing a series of updates.
<add> * For each of the update/create commands, the `fromIndex` refers to the index
<add> * that the item existed at *before* any of the updates are applied, and the
<add> * `toIndex` refers to the index after *all* of the updates are applied
<add> * (including deletes/moves). TODO: refactor so this can be shared with
<add> * DOMChildrenOperations.
<add> *
<add> * @param {array<object>} updates List of update configurations.
<add> * @param {array<string>} markup List of markup strings - in the case of React
<add> * IOS, the ids of new components assumed to be already created.
<add> */
<add>var dangerouslyProcessChildrenUpdates = function(childrenUpdates, markupList) {
<add> if (!childrenUpdates.length) {
<add> return;
<add> }
<add> var byContainerTag = {};
<add> // Group by parent ID - send them across the bridge in separate commands per
<add> // containerID.
<add> for (var i = 0; i < childrenUpdates.length; i++) {
<add> var update = childrenUpdates[i];
<add> var containerTag = ReactNativeTagHandles.mostRecentMountedNodeHandleForRootNodeID(update.parentID);
<add> var updates = byContainerTag[containerTag] || (byContainerTag[containerTag] = {});
<add> if (update.type === ReactMultiChildUpdateTypes.MOVE_EXISTING) {
<add> (updates.moveFromIndices || (updates.moveFromIndices = [])).push(update.fromIndex);
<add> (updates.moveToIndices || (updates.moveToIndices = [])).push(update.toIndex);
<add> } else if (update.type === ReactMultiChildUpdateTypes.REMOVE_NODE) {
<add> (updates.removeAtIndices || (updates.removeAtIndices = [])).push(update.fromIndex);
<add> } else if (update.type === ReactMultiChildUpdateTypes.INSERT_MARKUP) {
<add> var mountImage = markupList[update.markupIndex];
<add> var tag = mountImage.tag;
<add> var rootNodeID = mountImage.rootNodeID;
<add> ReactNativeTagHandles.associateRootNodeIDWithMountedNodeHandle(rootNodeID, tag);
<add> (updates.addAtIndices || (updates.addAtIndices = [])).push(update.toIndex);
<add> (updates.addChildTags || (updates.addChildTags = [])).push(tag);
<add> }
<add> }
<add> // Note this enumeration order will be different on V8! Move `byContainerTag`
<add> // to a sparse array as soon as we confirm there are not horrible perf
<add> // penalties.
<add> for (var updateParentTagString in byContainerTag) {
<add> var updateParentTagNumber = +updateParentTagString;
<add> var childUpdatesToSend = byContainerTag[updateParentTagNumber];
<add> UIManager.manageChildren(
<add> updateParentTagNumber,
<add> childUpdatesToSend.moveFromIndices,
<add> childUpdatesToSend.moveToIndices,
<add> childUpdatesToSend.addChildTags,
<add> childUpdatesToSend.addAtIndices,
<add> childUpdatesToSend.removeAtIndices
<add> );
<add> }
<add>};
<add>
<add>/**
<add> * Operations used to process updates to DOM nodes. This is made injectable via
<add> * `ReactComponent.DOMIDOperations`.
<add> */
<add>var ReactNativeDOMIDOperations = {
<add> dangerouslyProcessChildrenUpdates: ReactPerf.measure(
<add> // FIXME(frantic): #4441289 Hack to avoid modifying react-tools
<add> 'ReactDOMIDOperations',
<add> 'dangerouslyProcessChildrenUpdates',
<add> dangerouslyProcessChildrenUpdates
<add> ),
<add>
<add> /**
<add> * Replaces a view that exists in the document with markup.
<add> *
<add> * @param {string} id ID of child to be replaced.
<add> * @param {string} markup Mount image to replace child with id.
<add> */
<add> dangerouslyReplaceNodeWithMarkupByID: ReactPerf.measure(
<add> 'ReactDOMIDOperations',
<add> 'dangerouslyReplaceNodeWithMarkupByID',
<add> function(id, mountImage) {
<add> var oldTag = ReactNativeTagHandles.mostRecentMountedNodeHandleForRootNodeID(id);
<add> UIManager.replaceExistingNonRootView(oldTag, mountImage.tag);
<add> ReactNativeTagHandles.associateRootNodeIDWithMountedNodeHandle(id, mountImage.tag);
<add> }
<add> ),
<add>};
<add>
<add>module.exports = ReactNativeDOMIDOperations;
<ide><path>src/renderers/native/ReactNative/ReactNativeDefaultInjection.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> *
<add> * @providesModule ReactNativeDefaultInjection
<add> * @flow
<add> */
<add>'use strict';
<add>
<add>/**
<add> * Make sure essential globals are available and are patched correctly. Please don't remove this
<add> * line. Bundles created by react-packager `require` it before executing any application code. This
<add> * ensures it exists in the dependency graph and can be `require`d.
<add> */
<add>require('InitializeJavaScriptAppEngine');
<add>
<add>var EventPluginHub = require('EventPluginHub');
<add>var EventPluginUtils = require('EventPluginUtils');
<add>var IOSDefaultEventPluginOrder = require('IOSDefaultEventPluginOrder');
<add>var IOSNativeBridgeEventPlugin = require('IOSNativeBridgeEventPlugin');
<add>var NodeHandle = require('NodeHandle');
<add>var ReactElement = require('ReactElement');
<add>var ReactComponentEnvironment = require('ReactComponentEnvironment');
<add>var ReactDefaultBatchingStrategy = require('ReactDefaultBatchingStrategy');
<add>var ReactEmptyComponent = require('ReactEmptyComponent');
<add>var ReactInstanceHandles = require('ReactInstanceHandles');
<add>var ReactNativeComponentEnvironment = require('ReactNativeComponentEnvironment');
<add>var ReactNativeGlobalInteractionHandler = require('ReactNativeGlobalInteractionHandler');
<add>var ReactNativeGlobalResponderHandler = require('ReactNativeGlobalResponderHandler');
<add>var ReactNativeMount = require('ReactNativeMount');
<add>var ReactNativeTextComponent = require('ReactNativeTextComponent');
<add>var ReactNativeComponent = require('ReactNativeComponent');
<add>var ReactUpdates = require('ReactUpdates');
<add>var ResponderEventPlugin = require('ResponderEventPlugin');
<add>var UniversalWorkerNodeHandle = require('UniversalWorkerNodeHandle');
<add>
<add>var invariant = require('fbjs/lib/invariant');
<add>
<add>// Just to ensure this gets packaged, since its only caller is from Native.
<add>require('RCTEventEmitter');
<add>require('RCTLog');
<add>require('JSTimersExecution');
<add>
<add>function inject() {
<add> /**
<add> * Inject module for resolving DOM hierarchy and plugin ordering.
<add> */
<add> EventPluginHub.injection.injectEventPluginOrder(IOSDefaultEventPluginOrder);
<add> EventPluginHub.injection.injectInstanceHandle(ReactInstanceHandles);
<add>
<add> ResponderEventPlugin.injection.injectGlobalResponderHandler(
<add> ReactNativeGlobalResponderHandler
<add> );
<add>
<add> ResponderEventPlugin.injection.injectGlobalInteractionHandler(
<add> ReactNativeGlobalInteractionHandler
<add> );
<add>
<add> /**
<add> * Some important event plugins included by default (without having to require
<add> * them).
<add> */
<add> EventPluginHub.injection.injectEventPluginsByName({
<add> 'ResponderEventPlugin': ResponderEventPlugin,
<add> 'IOSNativeBridgeEventPlugin': IOSNativeBridgeEventPlugin
<add> });
<add>
<add> ReactUpdates.injection.injectReconcileTransaction(
<add> ReactNativeComponentEnvironment.ReactReconcileTransaction
<add> );
<add>
<add> ReactUpdates.injection.injectBatchingStrategy(
<add> ReactDefaultBatchingStrategy
<add> );
<add>
<add> ReactComponentEnvironment.injection.injectEnvironment(
<add> ReactNativeComponentEnvironment
<add> );
<add>
<add> var EmptyComponent = () => {
<add> // Can't import View at the top because it depends on React to make its composite
<add> var View = require('View');
<add> return ReactElement.createElement(View, {
<add> collapsable: true,
<add> style: { position: 'absolute' }
<add> });
<add> };
<add> ReactEmptyComponent.injection.injectEmptyComponent(EmptyComponent);
<add>
<add> EventPluginUtils.injection.injectMount(ReactNativeMount);
<add>
<add> ReactNativeComponent.injection.injectTextComponentClass(
<add> ReactNativeTextComponent
<add> );
<add> ReactNativeComponent.injection.injectGenericComponentClass(function(tag) {
<add> // Show a nicer error message for non-function tags
<add> var info = '';
<add> if (typeof tag === 'string' && /^[a-z]/.test(tag)) {
<add> info += ' Each component name should start with an uppercase letter.';
<add> }
<add> invariant(false, 'Expected a component class, got %s.%s', tag, info);
<add> });
<add>
<add> NodeHandle.injection.injectImplementation(UniversalWorkerNodeHandle);
<add>}
<add>
<add>module.exports = {
<add> inject: inject,
<add>};
<ide><path>src/renderers/native/ReactNative/ReactNativeEventEmitter.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> *
<add> * @providesModule ReactNativeEventEmitter
<add> * @flow
<add> */
<add>'use strict';
<add>
<add>var EventPluginHub = require('EventPluginHub');
<add>var ReactEventEmitterMixin = require('ReactEventEmitterMixin');
<add>var ReactNativeTagHandles = require('ReactNativeTagHandles');
<add>var NodeHandle = require('NodeHandle');
<add>var EventConstants = require('EventConstants');
<add>
<add>var merge = require('merge');
<add>var warning = require('fbjs/lib/warning');
<add>
<add>var topLevelTypes = EventConstants.topLevelTypes;
<add>
<add>/**
<add> * Version of `ReactBrowserEventEmitter` that works on the receiving side of a
<add> * serialized worker boundary.
<add> */
<add>
<add>// Shared default empty native event - conserve memory.
<add>var EMPTY_NATIVE_EVENT = {};
<add>
<add>/**
<add> * Selects a subsequence of `Touch`es, without destroying `touches`.
<add> *
<add> * @param {Array<Touch>} touches Deserialized touch objects.
<add> * @param {Array<number>} indices Indices by which to pull subsequence.
<add> * @return {Array<Touch>} Subsequence of touch objects.
<add> */
<add>var touchSubsequence = function(touches, indices) {
<add> var ret = [];
<add> for (var i = 0; i < indices.length; i++) {
<add> ret.push(touches[indices[i]]);
<add> }
<add> return ret;
<add>};
<add>
<add>/**
<add> * TODO: Pool all of this.
<add> *
<add> * Destroys `touches` by removing touch objects at indices `indices`. This is
<add> * to maintain compatibility with W3C touch "end" events, where the active
<add> * touches don't include the set that has just been "ended".
<add> *
<add> * @param {Array<Touch>} touches Deserialized touch objects.
<add> * @param {Array<number>} indices Indices to remove from `touches`.
<add> * @return {Array<Touch>} Subsequence of removed touch objects.
<add> */
<add>var removeTouchesAtIndices = function(
<add> touches: Array<Object>,
<add> indices: Array<number>
<add>): Array<Object> {
<add> var rippedOut = [];
<add> // use an unsafe downcast to alias to nullable elements,
<add> // so we can delete and then compact.
<add> var temp: Array<?Object> = (touches: Array<any>);
<add> for (var i = 0; i < indices.length; i++) {
<add> var index = indices[i];
<add> rippedOut.push(touches[index]);
<add> temp[index] = null;
<add> }
<add> var fillAt = 0;
<add> for (var j = 0; j < temp.length; j++) {
<add> var cur = temp[j];
<add> if (cur !== null) {
<add> temp[fillAt++] = cur;
<add> }
<add> }
<add> temp.length = fillAt;
<add> return rippedOut;
<add>};
<add>
<add>/**
<add> * `ReactNativeEventEmitter` is used to attach top-level event listeners. For example:
<add> *
<add> * ReactNativeEventEmitter.putListener('myID', 'onClick', myFunction);
<add> *
<add> * This would allocate a "registration" of `('onClick', myFunction)` on 'myID'.
<add> *
<add> * @internal
<add> */
<add>var ReactNativeEventEmitter = merge(ReactEventEmitterMixin, {
<add>
<add> registrationNames: EventPluginHub.registrationNameModules,
<add>
<add> putListener: EventPluginHub.putListener,
<add>
<add> getListener: EventPluginHub.getListener,
<add>
<add> deleteListener: EventPluginHub.deleteListener,
<add>
<add> deleteAllListeners: EventPluginHub.deleteAllListeners,
<add>
<add> /**
<add> * Internal version of `receiveEvent` in terms of normalized (non-tag)
<add> * `rootNodeID`.
<add> *
<add> * @see receiveEvent.
<add> *
<add> * @param {rootNodeID} rootNodeID React root node ID that event occurred on.
<add> * @param {TopLevelType} topLevelType Top level type of event.
<add> * @param {object} nativeEventParam Object passed from native.
<add> */
<add> _receiveRootNodeIDEvent: function(
<add> rootNodeID: ?string,
<add> topLevelType: string,
<add> nativeEventParam: Object
<add> ) {
<add> var nativeEvent = nativeEventParam || EMPTY_NATIVE_EVENT;
<add> ReactNativeEventEmitter.handleTopLevel(
<add> topLevelType,
<add> rootNodeID,
<add> rootNodeID,
<add> nativeEvent,
<add> nativeEvent.target
<add> );
<add> },
<add>
<add> /**
<add> * Publicly exposed method on module for native objc to invoke when a top
<add> * level event is extracted.
<add> * @param {rootNodeID} rootNodeID React root node ID that event occurred on.
<add> * @param {TopLevelType} topLevelType Top level type of event.
<add> * @param {object} nativeEventParam Object passed from native.
<add> */
<add> receiveEvent: function(
<add> tag: number,
<add> topLevelType: string,
<add> nativeEventParam: Object
<add> ) {
<add> var rootNodeID = ReactNativeTagHandles.tagToRootNodeID[tag];
<add> ReactNativeEventEmitter._receiveRootNodeIDEvent(
<add> rootNodeID,
<add> topLevelType,
<add> nativeEventParam
<add> );
<add> },
<add>
<add> /**
<add> * Simple multi-wrapper around `receiveEvent` that is intended to receive an
<add> * efficient representation of `Touch` objects, and other information that
<add> * can be used to construct W3C compliant `Event` and `Touch` lists.
<add> *
<add> * This may create dispatch behavior that differs than web touch handling. We
<add> * loop through each of the changed touches and receive it as a single event.
<add> * So two `touchStart`/`touchMove`s that occur simultaneously are received as
<add> * two separate touch event dispatches - when they arguably should be one.
<add> *
<add> * This implementation reuses the `Touch` objects themselves as the `Event`s
<add> * since we dispatch an event for each touch (though that might not be spec
<add> * compliant). The main purpose of reusing them is to save allocations.
<add> *
<add> * TODO: Dispatch multiple changed touches in one event. The bubble path
<add> * could be the first common ancestor of all the `changedTouches`.
<add> *
<add> * One difference between this behavior and W3C spec: cancelled touches will
<add> * not appear in `.touches`, or in any future `.touches`, though they may
<add> * still be "actively touching the surface".
<add> *
<add> * Web desktop polyfills only need to construct a fake touch event with
<add> * identifier 0, also abandoning traditional click handlers.
<add> */
<add> receiveTouches: function(
<add> eventTopLevelType: string,
<add> touches: Array<Object>,
<add> changedIndices: Array<number>
<add> ) {
<add> var changedTouches =
<add> eventTopLevelType === topLevelTypes.topTouchEnd ||
<add> eventTopLevelType === topLevelTypes.topTouchCancel ?
<add> removeTouchesAtIndices(touches, changedIndices) :
<add> touchSubsequence(touches, changedIndices);
<add>
<add> for (var jj = 0; jj < changedTouches.length; jj++) {
<add> var touch = changedTouches[jj];
<add> // Touch objects can fulfill the role of `DOM` `Event` objects if we set
<add> // the `changedTouches`/`touches`. This saves allocations.
<add> touch.changedTouches = changedTouches;
<add> touch.touches = touches;
<add> var nativeEvent = touch;
<add> var rootNodeID = null;
<add> var target = nativeEvent.target;
<add> if (target !== null && target !== undefined) {
<add> if (target < ReactNativeTagHandles.tagsStartAt) {
<add> if (__DEV__) {
<add> warning(
<add> false,
<add> 'A view is reporting that a touch occured on tag zero.'
<add> );
<add> }
<add> } else {
<add> rootNodeID = NodeHandle.getRootNodeID(target);
<add> }
<add> }
<add> ReactNativeEventEmitter._receiveRootNodeIDEvent(
<add> rootNodeID,
<add> eventTopLevelType,
<add> nativeEvent
<add> );
<add> }
<add> }
<add>});
<add>
<add>module.exports = ReactNativeEventEmitter;
<ide><path>src/renderers/native/ReactNative/ReactNativeGlobalInteractionHandler.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> *
<add> * @providesModule ReactNativeGlobalInteractionHandler
<add> * @flow
<add> */
<add>'use strict';
<add>
<add>var InteractionManager = require('InteractionManager');
<add>
<add>// Interaction handle is created/cleared when responder is granted or
<add>// released/terminated.
<add>var interactionHandle = null;
<add>
<add>var ReactNativeGlobalInteractionHandler = {
<add> onChange: function(numberActiveTouches: number) {
<add> if (numberActiveTouches === 0) {
<add> if (interactionHandle) {
<add> InteractionManager.clearInteractionHandle(interactionHandle);
<add> interactionHandle = null;
<add> }
<add> } else if (!interactionHandle) {
<add> interactionHandle = InteractionManager.createInteractionHandle();
<add> }
<add> }
<add>};
<add>
<add>module.exports = ReactNativeGlobalInteractionHandler;
<ide><path>src/renderers/native/ReactNative/ReactNativeGlobalResponderHandler.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> *
<add> * @providesModule ReactNativeGlobalResponderHandler
<add> * @flow
<add> */
<add>'use strict';
<add>
<add>var ReactNativeTagHandles = require('ReactNativeTagHandles');
<add>var UIManager = require('UIManager');
<add>
<add>var ReactNativeGlobalResponderHandler = {
<add> onChange: function(from: string, to: string, blockNativeResponder: boolean) {
<add> if (to !== null) {
<add> UIManager.setJSResponder(
<add> ReactNativeTagHandles.mostRecentMountedNodeHandleForRootNodeID(to),
<add> blockNativeResponder
<add> );
<add> } else {
<add> UIManager.clearJSResponder();
<add> }
<add> }
<add>};
<add>
<add>module.exports = ReactNativeGlobalResponderHandler;
<ide><path>src/renderers/native/ReactNative/ReactNativeMount.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> *
<add> * @providesModule ReactNativeMount
<add> * @flow
<add> */
<add>'use strict';
<add>
<add>var ReactElement = require('ReactElement');
<add>var ReactNativeTagHandles = require('ReactNativeTagHandles');
<add>var ReactPerf = require('ReactPerf');
<add>var ReactReconciler = require('ReactReconciler');
<add>var ReactUpdateQueue = require('ReactUpdateQueue');
<add>var ReactUpdates = require('ReactUpdates');
<add>var UIManager = require('UIManager');
<add>
<add>var emptyObject = require('fbjs/lib/emptyObject');
<add>var instantiateReactComponent = require('instantiateReactComponent');
<add>var shouldUpdateReactComponent = require('shouldUpdateReactComponent');
<add>
<add>function instanceNumberToChildRootID(rootNodeID, instanceNumber) {
<add> return rootNodeID + '[' + instanceNumber + ']';
<add>}
<add>
<add>/**
<add> * Temporary (?) hack so that we can store all top-level pending updates on
<add> * composites instead of having to worry about different types of components
<add> * here.
<add> */
<add>var TopLevelWrapper = function() {};
<add>TopLevelWrapper.prototype.isReactComponent = {};
<add>if (__DEV__) {
<add> TopLevelWrapper.displayName = 'TopLevelWrapper';
<add>}
<add>TopLevelWrapper.prototype.render = function() {
<add> // this.props is actually a ReactElement
<add> return this.props;
<add>};
<add>
<add>/**
<add> * Mounts this component and inserts it into the DOM.
<add> *
<add> * @param {ReactComponent} componentInstance The instance to mount.
<add> * @param {number} rootID ID of the root node.
<add> * @param {number} container container element to mount into.
<add> * @param {ReactReconcileTransaction} transaction
<add> */
<add>function mountComponentIntoNode(
<add> componentInstance,
<add> rootID,
<add> container,
<add> transaction) {
<add> var markup = ReactReconciler.mountComponent(
<add> componentInstance, rootID, transaction, emptyObject
<add> );
<add> componentInstance._renderedComponent._topLevelWrapper = componentInstance;
<add> ReactNativeMount._mountImageIntoNode(markup, container);
<add>}
<add>
<add>/**
<add> * Batched mount.
<add> *
<add> * @param {ReactComponent} componentInstance The instance to mount.
<add> * @param {number} rootID ID of the root node.
<add> * @param {number} container container element to mount into.
<add> */
<add>function batchedMountComponentIntoNode(
<add> componentInstance,
<add> rootID,
<add> container) {
<add> var transaction = ReactUpdates.ReactReconcileTransaction.getPooled();
<add> transaction.perform(
<add> mountComponentIntoNode,
<add> null,
<add> componentInstance,
<add> rootID,
<add> container,
<add> transaction
<add> );
<add> ReactUpdates.ReactReconcileTransaction.release(transaction);
<add>}
<add>
<add>/**
<add> * As soon as `ReactMount` is refactored to not rely on the DOM, we can share
<add> * code between the two. For now, we'll hard code the ID logic.
<add> */
<add>var ReactNativeMount = {
<add> instanceCount: 0,
<add>
<add> _instancesByContainerID: {},
<add>
<add> // these two functions are needed by React Devtools
<add> findNodeHandle: require('findNodeHandle'),
<add> nativeTagToRootNodeID: function (nativeTag: number): string {
<add> return ReactNativeTagHandles.tagToRootNodeID[nativeTag];
<add> },
<add>
<add> /**
<add> * @param {ReactComponent} instance Instance to render.
<add> * @param {containerTag} containerView Handle to native view tag
<add> */
<add> renderComponent: function(
<add> nextElement: ReactElement,
<add> containerTag: number,
<add> callback?: ?(() => void)
<add> ): ?ReactComponent {
<add> var nextWrappedElement = new ReactElement(
<add> TopLevelWrapper,
<add> null,
<add> null,
<add> null,
<add> null,
<add> null,
<add> nextElement
<add> );
<add>
<add> var topRootNodeID = ReactNativeTagHandles.tagToRootNodeID[containerTag];
<add> if (topRootNodeID) {
<add> var prevComponent = ReactNativeMount._instancesByContainerID[topRootNodeID];
<add> if (prevComponent) {
<add> var prevWrappedElement = prevComponent._currentElement;
<add> var prevElement = prevWrappedElement.props;
<add> if (shouldUpdateReactComponent(prevElement, nextElement)) {
<add> ReactUpdateQueue.enqueueElementInternal(prevComponent, nextWrappedElement);
<add> if (callback) {
<add> ReactUpdateQueue.enqueueCallbackInternal(prevComponent, callback);
<add> }
<add> return prevComponent;
<add> } else {
<add> ReactNativeMount.unmountComponentAtNode(containerTag);
<add> }
<add> }
<add> }
<add>
<add> if (!ReactNativeTagHandles.reactTagIsNativeTopRootID(containerTag)) {
<add> console.error('You cannot render into anything but a top root');
<add> return;
<add> }
<add>
<add> var topRootNodeID = ReactNativeTagHandles.allocateRootNodeIDForTag(containerTag);
<add> ReactNativeTagHandles.associateRootNodeIDWithMountedNodeHandle(
<add> topRootNodeID,
<add> containerTag
<add> );
<add>
<add> var instance = instantiateReactComponent(nextWrappedElement);
<add> ReactNativeMount._instancesByContainerID[topRootNodeID] = instance;
<add>
<add> var childRootNodeID = instanceNumberToChildRootID(
<add> topRootNodeID,
<add> ReactNativeMount.instanceCount++
<add> );
<add>
<add> // The initial render is synchronous but any updates that happen during
<add> // rendering, in componentWillMount or componentDidMount, will be batched
<add> // according to the current batching strategy.
<add>
<add> ReactUpdates.batchedUpdates(
<add> batchedMountComponentIntoNode,
<add> instance,
<add> childRootNodeID,
<add> topRootNodeID
<add> );
<add> var component = instance.getPublicInstance();
<add> if (callback) {
<add> callback.call(component);
<add> }
<add> return component;
<add> },
<add>
<add> /**
<add> * @param {View} view View tree image.
<add> * @param {number} containerViewID View to insert sub-view into.
<add> */
<add> _mountImageIntoNode: ReactPerf.measure(
<add> // FIXME(frantic): #4441289 Hack to avoid modifying react-tools
<add> 'ReactComponentBrowserEnvironment',
<add> 'mountImageIntoNode',
<add> function(mountImage, containerID) {
<add> // Since we now know that the `mountImage` has been mounted, we can
<add> // mark it as such.
<add> ReactNativeTagHandles.associateRootNodeIDWithMountedNodeHandle(
<add> mountImage.rootNodeID,
<add> mountImage.tag
<add> );
<add> UIManager.setChildren(
<add> ReactNativeTagHandles.mostRecentMountedNodeHandleForRootNodeID(containerID),
<add> [mountImage.tag]
<add> );
<add> }
<add> ),
<add>
<add> /**
<add> * Standard unmounting of the component that is rendered into `containerID`,
<add> * but will also execute a command to remove the actual container view
<add> * itself. This is useful when a client is cleaning up a React tree, and also
<add> * knows that the container will no longer be needed. When executing
<add> * asynchronously, it's easier to just have this method be the one that calls
<add> * for removal of the view.
<add> */
<add> unmountComponentAtNodeAndRemoveContainer: function(
<add> containerTag: number
<add> ) {
<add> ReactNativeMount.unmountComponentAtNode(containerTag);
<add> // call back into native to remove all of the subviews from this container
<add> UIManager.removeRootView(containerTag);
<add> },
<add>
<add> /**
<add> * Unmount component at container ID by iterating through each child component
<add> * that has been rendered and unmounting it. There should just be one child
<add> * component at this time.
<add> */
<add> unmountComponentAtNode: function(containerTag: number): boolean {
<add> if (!ReactNativeTagHandles.reactTagIsNativeTopRootID(containerTag)) {
<add> console.error('You cannot render into anything but a top root');
<add> return false;
<add> }
<add>
<add> var containerID = ReactNativeTagHandles.tagToRootNodeID[containerTag];
<add> var instance = ReactNativeMount._instancesByContainerID[containerID];
<add> if (!instance) {
<add> return false;
<add> }
<add> ReactNativeMount.unmountComponentFromNode(instance, containerID);
<add> delete ReactNativeMount._instancesByContainerID[containerID];
<add> return true;
<add> },
<add>
<add> /**
<add> * Unmounts a component and sends messages back to iOS to remove its subviews.
<add> *
<add> * @param {ReactComponent} instance React component instance.
<add> * @param {string} containerID ID of container we're removing from.
<add> * @final
<add> * @internal
<add> * @see {ReactNativeMount.unmountComponentAtNode}
<add> */
<add> unmountComponentFromNode: function(
<add> instance: ReactComponent,
<add> containerID: string
<add> ) {
<add> // Call back into native to remove all of the subviews from this container
<add> ReactReconciler.unmountComponent(instance);
<add> var containerTag =
<add> ReactNativeTagHandles.mostRecentMountedNodeHandleForRootNodeID(containerID);
<add> UIManager.removeSubviewsFromContainerWithID(containerTag);
<add> },
<add>
<add> getNode: function(rootNodeID: string): number {
<add> return ReactNativeTagHandles.rootNodeIDToTag[rootNodeID];
<add> },
<add>
<add> getID: function(nativeTag: number): string {
<add> return ReactNativeTagHandles.tagToRootNodeID[nativeTag];
<add> }
<add>};
<add>
<add>ReactNativeMount.renderComponent = ReactPerf.measure(
<add> 'ReactMount',
<add> '_renderNewRootComponent',
<add> ReactNativeMount.renderComponent
<add>);
<add>
<add>module.exports = ReactNativeMount;
<ide><path>src/renderers/native/ReactNative/ReactNativePropRegistry.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> *
<add> * @providesModule ReactNativePropRegistry
<add> * @flow
<add> */
<add>'use strict';
<add>
<add>var objects = {};
<add>var uniqueID = 1;
<add>var emptyObject = {};
<add>
<add>class ReactNativePropRegistry {
<add> static register(object: Object): number {
<add> var id = ++uniqueID;
<add> if (__DEV__) {
<add> Object.freeze(object);
<add> }
<add> objects[id] = object;
<add> return id;
<add> }
<add>
<add> static getByID(id: number): Object {
<add> if (!id) {
<add> // Used in the style={[condition && id]} pattern,
<add> // we want it to be a no-op when the value is false or null
<add> return emptyObject;
<add> }
<add>
<add> var object = objects[id];
<add> if (!object) {
<add> console.warn('Invalid style with id `' + id + '`. Skipping ...');
<add> return emptyObject;
<add> }
<add> return object;
<add> }
<add>}
<add>
<add>module.exports = ReactNativePropRegistry;
<ide><path>src/renderers/native/ReactNative/ReactNativeReconcileTransaction.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> *
<add> * @providesModule ReactNativeReconcileTransaction
<add> * @flow
<add> */
<add>'use strict';
<add>
<add>var CallbackQueue = require('CallbackQueue');
<add>var PooledClass = require('PooledClass');
<add>var Transaction = require('Transaction');
<add>
<add>/**
<add> * Provides a `CallbackQueue` queue for collecting `onDOMReady` callbacks during
<add> * the performing of the transaction.
<add> */
<add>var ON_DOM_READY_QUEUEING = {
<add> /**
<add> * Initializes the internal `onDOMReady` queue.
<add> */
<add> initialize: function() {
<add> this.reactMountReady.reset();
<add> },
<add>
<add> /**
<add> * After DOM is flushed, invoke all registered `onDOMReady` callbacks.
<add> */
<add> close: function() {
<add> this.reactMountReady.notifyAll();
<add> }
<add>};
<add>
<add>/**
<add> * Executed within the scope of the `Transaction` instance. Consider these as
<add> * being member methods, but with an implied ordering while being isolated from
<add> * each other.
<add> */
<add>var TRANSACTION_WRAPPERS = [ON_DOM_READY_QUEUEING];
<add>
<add>/**
<add> * Currently:
<add> * - The order that these are listed in the transaction is critical:
<add> * - Suppresses events.
<add> * - Restores selection range.
<add> *
<add> * Future:
<add> * - Restore document/overflow scroll positions that were unintentionally
<add> * modified via DOM insertions above the top viewport boundary.
<add> * - Implement/integrate with customized constraint based layout system and keep
<add> * track of which dimensions must be remeasured.
<add> *
<add> * @class ReactNativeReconcileTransaction
<add> */
<add>function ReactNativeReconcileTransaction() {
<add> this.reinitializeTransaction();
<add> this.reactMountReady = CallbackQueue.getPooled(null);
<add>}
<add>
<add>var Mixin = {
<add> /**
<add> * @see Transaction
<add> * @abstract
<add> * @final
<add> * @return {array<object>} List of operation wrap procedures.
<add> * TODO: convert to array<TransactionWrapper>
<add> */
<add> getTransactionWrappers: function() {
<add> return TRANSACTION_WRAPPERS;
<add> },
<add>
<add> /**
<add> * @return {object} The queue to collect `onDOMReady` callbacks with.
<add> * TODO: convert to ReactMountReady
<add> */
<add> getReactMountReady: function() {
<add> return this.reactMountReady;
<add> },
<add>
<add> /**
<add> * `PooledClass` looks for this, and will invoke this before allowing this
<add> * instance to be reused.
<add> */
<add> destructor: function() {
<add> CallbackQueue.release(this.reactMountReady);
<add> this.reactMountReady = null;
<add> }
<add>};
<add>
<add>Object.assign(
<add> ReactNativeReconcileTransaction.prototype,
<add> Transaction.Mixin,
<add> ReactNativeReconcileTransaction,
<add> Mixin
<add>);
<add>
<add>PooledClass.addPoolingTo(ReactNativeReconcileTransaction);
<add>
<add>module.exports = ReactNativeReconcileTransaction;
<ide><path>src/renderers/native/ReactNative/ReactNativeTagHandles.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> *
<add> * @providesModule ReactNativeTagHandles
<add> * @flow
<add> */
<add>'use strict';
<add>
<add>var invariant = require('fbjs/lib/invariant');
<add>var warning = require('fbjs/lib/warning');
<add>
<add>/**
<add> * Keeps track of allocating and associating native "tags" which are numeric,
<add> * unique view IDs. All the native tags are negative numbers, to avoid
<add> * collisions, but in the JS we keep track of them as positive integers to store
<add> * them effectively in Arrays. So we must refer to them as "inverses" of the
<add> * native tags (that are * normally negative).
<add> *
<add> * It *must* be the case that every `rootNodeID` always maps to the exact same
<add> * `tag` forever. The easiest way to accomplish this is to never delete
<add> * anything from this table.
<add> * Why: Because `dangerouslyReplaceNodeWithMarkupByID` relies on being able to
<add> * unmount a component with a `rootNodeID`, then mount a new one in its place,
<add> */
<add>var INITIAL_TAG_COUNT = 1;
<add>var NATIVE_TOP_ROOT_ID_SEPARATOR = '{TOP_LEVEL}';
<add>var ReactNativeTagHandles = {
<add> tagsStartAt: INITIAL_TAG_COUNT,
<add> tagCount: INITIAL_TAG_COUNT,
<add>
<add> allocateTag: function(): number {
<add> // Skip over root IDs as those are reserved for native
<add> while (this.reactTagIsNativeTopRootID(ReactNativeTagHandles.tagCount)) {
<add> ReactNativeTagHandles.tagCount++;
<add> }
<add> var tag = ReactNativeTagHandles.tagCount;
<add> ReactNativeTagHandles.tagCount++;
<add> return tag;
<add> },
<add>
<add> /**
<add> * This associates the *last* observed *native* mounting between `rootNodeID`
<add> * and some `tag`. This association doesn't imply that `rootNodeID` is still
<add> * natively mounted as `tag`. The only reason why we don't clear the
<add> * association when the `rootNodeID` is unmounted, is that we don't have a
<add> * convenient time to disassociate them (otherwise we would).
<add> * `unmountComponent` isn't the correct time because that doesn't imply that
<add> * the native node has been natively unmounted.
<add> */
<add> associateRootNodeIDWithMountedNodeHandle: function(
<add> rootNodeID: ?string,
<add> tag: ?number
<add> ) {
<add> warning(rootNodeID && tag, 'Root node or tag is null when associating');
<add> if (rootNodeID && tag) {
<add> ReactNativeTagHandles.tagToRootNodeID[tag] = rootNodeID;
<add> ReactNativeTagHandles.rootNodeIDToTag[rootNodeID] = tag;
<add> }
<add> },
<add>
<add> allocateRootNodeIDForTag: function(tag: number): string {
<add> invariant(
<add> this.reactTagIsNativeTopRootID(tag),
<add> 'Expect a native root tag, instead got ', tag
<add> );
<add> return '.r[' + tag + ']' + NATIVE_TOP_ROOT_ID_SEPARATOR;
<add> },
<add>
<add> reactTagIsNativeTopRootID: function(reactTag: number): bool {
<add> // We reserve all tags that are 1 mod 10 for native root views
<add> return reactTag % 10 === 1;
<add> },
<add>
<add> getNativeTopRootIDFromNodeID: function(nodeID: ?string): ?string {
<add> if (!nodeID) {
<add> return null;
<add> }
<add> var index = nodeID.indexOf(NATIVE_TOP_ROOT_ID_SEPARATOR);
<add> if (index === -1) {
<add> return null;
<add> }
<add> return nodeID.substr(0, index + NATIVE_TOP_ROOT_ID_SEPARATOR.length);
<add> },
<add>
<add> /**
<add> * Returns the native `nodeHandle` (`tag`) that was most recently *natively*
<add> * mounted at the `rootNodeID`. Just because a React component has been
<add> * mounted, that doesn't mean that its native node has been mounted. The
<add> * native node is mounted when we actually make the call to insert the
<add> * `nodeHandle` (`tag`) into the native hierarchy.
<add> *
<add> * @param {string} rootNodeID Root node ID to find most recently mounted tag
<add> * for. Again, this doesn't imply that it is still currently mounted.
<add> * @return {number} Tag ID of native view for most recent mounting of
<add> * `rootNodeID`.
<add> */
<add> mostRecentMountedNodeHandleForRootNodeID: function(
<add> rootNodeID: string
<add> ): number {
<add> return ReactNativeTagHandles.rootNodeIDToTag[rootNodeID];
<add> },
<add>
<add> tagToRootNodeID: ([] : Array<string>),
<add>
<add> rootNodeIDToTag: ({} : {[key: string]: number})
<add>};
<add>
<add>module.exports = ReactNativeTagHandles;
<ide><path>src/renderers/native/ReactNative/ReactNativeTextComponent.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> *
<add> * @providesModule ReactNativeTextComponent
<add> */
<add>
<add>'use strict';
<add>
<add>var ReactNativeTagHandles = require('ReactNativeTagHandles');
<add>var UIManager = require('UIManager');
<add>
<add>var invariant = require('fbjs/lib/invariant');
<add>
<add>var ReactNativeTextComponent = function(props) {
<add> // This constructor and its argument is currently used by mocks.
<add>};
<add>
<add>Object.assign(ReactNativeTextComponent.prototype, {
<add>
<add> construct: function(text) {
<add> // This is really a ReactText (ReactNode), not a ReactElement
<add> this._currentElement = text;
<add> this._stringText = '' + text;
<add> this._rootNodeID = null;
<add> },
<add>
<add> mountComponent: function(rootID, transaction, context) {
<add> invariant(
<add> context.isInAParentText,
<add> 'RawText "' + this._stringText + '" must be wrapped in an explicit ' +
<add> '<Text> component.'
<add> );
<add> this._rootNodeID = rootID;
<add> var tag = ReactNativeTagHandles.allocateTag();
<add> var nativeTopRootID = ReactNativeTagHandles.getNativeTopRootIDFromNodeID(rootID);
<add> UIManager.createView(
<add> tag,
<add> 'RCTRawText',
<add> nativeTopRootID ? ReactNativeTagHandles.rootNodeIDToTag[nativeTopRootID] : null,
<add> {text: this._stringText}
<add> );
<add> return {
<add> rootNodeID: rootID,
<add> tag: tag,
<add> };
<add> },
<add>
<add> receiveComponent: function(nextText, transaction, context) {
<add> if (nextText !== this._currentElement) {
<add> this._currentElement = nextText;
<add> var nextStringText = '' + nextText;
<add> if (nextStringText !== this._stringText) {
<add> this._stringText = nextStringText;
<add> UIManager.updateView(
<add> ReactNativeTagHandles.mostRecentMountedNodeHandleForRootNodeID(
<add> this._rootNodeID
<add> ),
<add> 'RCTRawText',
<add> {text: this._stringText}
<add> );
<add> }
<add> }
<add> },
<add>
<add> unmountComponent: function() {
<add> this._currentElement = null;
<add> this._stringText = null;
<add> this._rootNodeID = null;
<add> }
<add>
<add>});
<add>
<add>module.exports = ReactNativeTextComponent;
<ide><path>src/renderers/native/ReactNative/UIManagerStatTracker.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> *
<add> * @providesModule UIManagerStatTracker
<add> * @flow
<add> */
<add>'use strict';
<add>
<add>var UIManager = require('UIManager');
<add>
<add>var installed = false;
<add>var UIManagerStatTracker = {
<add> install: function() {
<add> if (installed) {
<add> return;
<add> }
<add> installed = true;
<add> var statLogHandle;
<add> var stats = {};
<add> function printStats() {
<add> console.log({UIManagerStatTracker: stats});
<add> statLogHandle = null;
<add> }
<add> function incStat(key: string, increment: number) {
<add> stats[key] = (stats[key] || 0) + increment;
<add> if (!statLogHandle) {
<add> statLogHandle = setImmediate(printStats);
<add> }
<add> }
<add> var createViewOrig = UIManager.createView;
<add> UIManager.createView = function(tag, className, rootTag, props) {
<add> incStat('createView', 1);
<add> incStat('setProp', Object.keys(props || []).length);
<add> createViewOrig(tag, className, rootTag, props);
<add> };
<add> var updateViewOrig = UIManager.updateView;
<add> UIManager.updateView = function(tag, className, props) {
<add> incStat('updateView', 1);
<add> incStat('setProp', Object.keys(props || []).length);
<add> updateViewOrig(tag, className, props);
<add> };
<add> var manageChildrenOrig = UIManager.manageChildren;
<add> UIManager.manageChildren = function(tag, moveFrom, moveTo, addTags, addIndices, remove) {
<add> incStat('manageChildren', 1);
<add> incStat('move', Object.keys(moveFrom || []).length);
<add> incStat('remove', Object.keys(remove || []).length);
<add> manageChildrenOrig(tag, moveFrom, moveTo, addTags, addIndices, remove);
<add> };
<add> },
<add>};
<add>
<add>module.exports = UIManagerStatTracker;
<ide><path>src/renderers/native/ReactNative/__tests__/ReactNativeAttributePayload-test.js
<add>/**
<add> * Copyright (c) 2013-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> *
<add> */
<add>'use strict';
<add>
<add>jest.dontMock('ReactNativeAttributePayload');
<add>jest.dontMock('ReactNativePropRegistry');
<add>jest.dontMock('deepDiffer');
<add>jest.dontMock('flattenStyle');
<add>
<add>var ReactNativeAttributePayload = require('ReactNativeAttributePayload');
<add>var ReactNativePropRegistry = require('ReactNativePropRegistry');
<add>
<add>var diff = ReactNativeAttributePayload.diff;
<add>
<add>describe('ReactNativeAttributePayload', function() {
<add>
<add> it('should work with simple example', () => {
<add> expect(diff(
<add> {a: 1, c: 3},
<add> {b: 2, c: 3},
<add> {a: true, b: true}
<add> )).toEqual({a: null, b: 2});
<add> });
<add>
<add> it('should skip fields that are equal', () => {
<add> expect(diff(
<add> {a: 1, b: 'two', c: true, d: false, e: undefined, f: 0},
<add> {a: 1, b: 'two', c: true, d: false, e: undefined, f: 0},
<add> {a: true, b: true, c: true, d: true, e: true, f: true}
<add> )).toEqual(null);
<add> });
<add>
<add> it('should remove fields', () => {
<add> expect(diff(
<add> {a: 1},
<add> {},
<add> {a: true}
<add> )).toEqual({a: null});
<add> });
<add>
<add> it('should remove fields that are set to undefined', () => {
<add> expect(diff(
<add> {a: 1},
<add> {a: undefined},
<add> {a: true}
<add> )).toEqual({a: null});
<add> });
<add>
<add> it('should ignore invalid fields', () => {
<add> expect(diff(
<add> {a: 1},
<add> {b: 2},
<add> {}
<add> )).toEqual(null);
<add> });
<add>
<add> it('should use the diff attribute', () => {
<add> var diffA = jest.genMockFunction().mockImpl((a, b) => true);
<add> var diffB = jest.genMockFunction().mockImpl((a, b) => false);
<add> expect(diff(
<add> {a: [1], b: [3]},
<add> {a: [2], b: [4]},
<add> {a: {diff: diffA}, b: {diff: diffB}}
<add> )).toEqual({a: [2]});
<add> expect(diffA).toBeCalledWith([1], [2]);
<add> expect(diffB).toBeCalledWith([3], [4]);
<add> });
<add>
<add> it('should not use the diff attribute on addition/removal', () => {
<add> var diffA = jest.genMockFunction();
<add> var diffB = jest.genMockFunction();
<add> expect(diff(
<add> {a: [1]},
<add> {b: [2]},
<add> {a: {diff: diffA}, b: {diff: diffB}}
<add> )).toEqual({a: null, b: [2]});
<add> expect(diffA).not.toBeCalled();
<add> expect(diffB).not.toBeCalled();
<add> });
<add>
<add> it('should do deep diffs of Objects by default', () => {
<add> expect(diff(
<add> {a: [1], b: {k: [3,4]}, c: {k: [4,4]} },
<add> {a: [2], b: {k: [3,4]}, c: {k: [4,5]} },
<add> {a: true, b: true, c: true}
<add> )).toEqual({a: [2], c: {k: [4,5]}});
<add> });
<add>
<add> it('should work with undefined styles', () => {
<add> expect(diff(
<add> { style: { a: '#ffffff', b: 1 } },
<add> { style: undefined },
<add> { style: { b: true } }
<add> )).toEqual({ b: null });
<add> expect(diff(
<add> { style: undefined },
<add> { style: { a: '#ffffff', b: 1 } },
<add> { style: { b: true } }
<add> )).toEqual({ b: 1 });
<add> expect(diff(
<add> { style: undefined },
<add> { style: undefined },
<add> { style: { b: true } }
<add> )).toEqual(null);
<add> });
<add>
<add> it('should work with empty styles', () => {
<add> expect(diff(
<add> {a: 1, c: 3},
<add> {},
<add> {a: true, b: true}
<add> )).toEqual({a: null});
<add> expect(diff(
<add> {},
<add> {a: 1, c: 3},
<add> {a: true, b: true}
<add> )).toEqual({a: 1});
<add> expect(diff(
<add> {},
<add> {},
<add> {a: true, b: true}
<add> )).toEqual(null);
<add> });
<add>
<add> it('should flatten nested styles and predefined styles', () => {
<add> var validStyleAttribute = { someStyle: { foo: true, bar: true } };
<add>
<add> expect(diff(
<add> {},
<add> { someStyle: [{ foo: 1 }, { bar: 2 }]},
<add> validStyleAttribute
<add> )).toEqual({ foo: 1, bar: 2 });
<add>
<add> expect(diff(
<add> { someStyle: [{ foo: 1 }, { bar: 2 }]},
<add> {},
<add> validStyleAttribute
<add> )).toEqual({ foo: null, bar: null });
<add>
<add> var barStyle = ReactNativePropRegistry.register({
<add> bar: 3,
<add> });
<add>
<add> expect(diff(
<add> {},
<add> { someStyle: [[{ foo: 1 }, { foo: 2 }], barStyle]},
<add> validStyleAttribute
<add> )).toEqual({ foo: 2, bar: 3 });
<add> });
<add>
<add> it('should reset a value to a previous if it is removed', () => {
<add> var validStyleAttribute = { someStyle: { foo: true, bar: true } };
<add>
<add> expect(diff(
<add> { someStyle: [{ foo: 1 }, { foo: 3 }]},
<add> { someStyle: [{ foo: 1 }, { bar: 2 }]},
<add> validStyleAttribute
<add> )).toEqual({ foo: 1, bar: 2 });
<add> });
<add>
<add> it('should not clear removed props if they are still in another slot', () => {
<add> var validStyleAttribute = { someStyle: { foo: true, bar: true } };
<add>
<add> expect(diff(
<add> { someStyle: [{}, { foo: 3, bar: 2 }]},
<add> { someStyle: [{ foo: 3 }, { bar: 2 }]},
<add> validStyleAttribute
<add> )).toEqual({ foo: 3 }); // this should ideally be null. heuristic tradeoff.
<add>
<add> expect(diff(
<add> { someStyle: [{}, { foo: 3, bar: 2 }]},
<add> { someStyle: [{ foo: 1, bar: 1 }, { bar: 2 }]},
<add> validStyleAttribute
<add> )).toEqual({ bar: 2, foo: 1 });
<add> });
<add>
<add> it('should clear a prop if a later style is explicit null/undefined', () => {
<add> var validStyleAttribute = { someStyle: { foo: true, bar: true } };
<add> expect(diff(
<add> { someStyle: [{}, { foo: 3, bar: 2 }]},
<add> { someStyle: [{ foo: 1 }, { bar: 2, foo: null }]},
<add> validStyleAttribute
<add> )).toEqual({ foo: null });
<add>
<add> expect(diff(
<add> { someStyle: [{ foo: 3 }, { foo: null, bar: 2 }]},
<add> { someStyle: [{ foo: null }, { bar: 2 }]},
<add> validStyleAttribute
<add> )).toEqual({ foo: null });
<add>
<add> expect(diff(
<add> { someStyle: [{ foo: 1 }, { foo: null }]},
<add> { someStyle: [{ foo: 2 }, { foo: null }]},
<add> validStyleAttribute
<add> )).toEqual({ foo: null }); // this should ideally be null. heuristic.
<add>
<add> // Test the same case with object equality because an early bailout doesn't
<add> // work in this case.
<add> var fooObj = { foo: 3 };
<add> expect(diff(
<add> { someStyle: [{ foo: 1 }, fooObj]},
<add> { someStyle: [{ foo: 2 }, fooObj]},
<add> validStyleAttribute
<add> )).toEqual({ foo: 3 }); // this should ideally be null. heuristic.
<add>
<add> expect(diff(
<add> { someStyle: [{ foo: 1 }, { foo: 3 }]},
<add> { someStyle: [{ foo: 2 }, { foo: undefined }]},
<add> validStyleAttribute
<add> )).toEqual({ foo: null }); // this should ideally be null. heuristic.
<add> });
<add>
<add> // Function properties are just markers to native that events should be sent.
<add> it('should convert functions to booleans', () => {
<add> // Note that if the property changes from one function to another, we don't
<add> // need to send an update.
<add> expect(diff(
<add> {a: function() { return 1; }, b: function() { return 2; }, c: 3},
<add> {b: function() { return 9; }, c: function() { return 3; }, },
<add> {a: true, b: true, c: true}
<add> )).toEqual({a: null, c: true});
<add> });
<add>
<add> });
<ide><path>src/renderers/native/ReactNative/createReactNativeComponentClass.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> *
<add> * @providesModule createReactNativeComponentClass
<add> * @flow
<add> */
<add>
<add>'use strict';
<add>
<add>var ReactNativeBaseComponent = require('ReactNativeBaseComponent');
<add>
<add>// See also ReactNativeBaseComponent
<add>type ReactNativeBaseComponentViewConfig = {
<add> validAttributes: Object;
<add> uiViewClassName: string;
<add> propTypes?: Object,
<add>}
<add>
<add>/**
<add> * @param {string} config iOS View configuration.
<add> * @private
<add> */
<add>var createReactNativeComponentClass = function(
<add> viewConfig: ReactNativeBaseComponentViewConfig
<add>): ReactClass<any> {
<add> var Constructor = function(element) {
<add> this._currentElement = element;
<add>
<add> this._rootNodeID = null;
<add> this._renderedChildren = null;
<add> };
<add> Constructor.displayName = viewConfig.uiViewClassName;
<add> Constructor.viewConfig = viewConfig;
<add> Constructor.propTypes = viewConfig.propTypes;
<add> Constructor.prototype = new ReactNativeBaseComponent(viewConfig);
<add> Constructor.prototype.constructor = Constructor;
<add>
<add> return ((Constructor: any): ReactClass);
<add>};
<add>
<add>module.exports = createReactNativeComponentClass;
<ide><path>src/renderers/native/ReactNative/findNodeHandle.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> *
<add> * @providesModule findNodeHandle
<add> * @flow
<add> */
<add>
<add>'use strict';
<add>
<add>var ReactCurrentOwner = require('ReactCurrentOwner');
<add>var ReactInstanceMap = require('ReactInstanceMap');
<add>var ReactNativeTagHandles = require('ReactNativeTagHandles');
<add>
<add>var invariant = require('fbjs/lib/invariant');
<add>var warning = require('fbjs/lib/warning');
<add>
<add>/**
<add> * ReactNative vs ReactWeb
<add> * -----------------------
<add> * React treats some pieces of data opaquely. This means that the information
<add> * is first class (it can be passed around), but cannot be inspected. This
<add> * allows us to build infrastructure that reasons about resources, without
<add> * making assumptions about the nature of those resources, and this allows that
<add> * infra to be shared across multiple platforms, where the resources are very
<add> * different. General infra (such as `ReactMultiChild`) reasons opaquely about
<add> * the data, but platform specific code (such as `ReactNativeBaseComponent`) can
<add> * make assumptions about the data.
<add> *
<add> *
<add> * `rootNodeID`, uniquely identifies a position in the generated native view
<add> * tree. Many layers of composite components (created with `React.createClass`)
<add> * can all share the same `rootNodeID`.
<add> *
<add> * `nodeHandle`: A sufficiently unambiguous way to refer to a lower level
<add> * resource (dom node, native view etc). The `rootNodeID` is sufficient for web
<add> * `nodeHandle`s, because the position in a tree is always enough to uniquely
<add> * identify a DOM node (we never have nodes in some bank outside of the
<add> * document). The same would be true for `ReactNative`, but we must maintain a
<add> * mapping that we can send efficiently serializable
<add> * strings across native boundaries.
<add> *
<add> * Opaque name TodaysWebReact FutureWebWorkerReact ReactNative
<add> * ----------------------------------------------------------------------------
<add> * nodeHandle N/A rootNodeID tag
<add> */
<add>
<add>function findNodeHandle(componentOrHandle: any): ?number {
<add> if (__DEV__) {
<add> var owner = ReactCurrentOwner.current;
<add> if (owner !== null) {
<add> warning(
<add> owner._warnedAboutRefsInRender,
<add> '%s is accessing findNodeHandle inside its render(). ' +
<add> 'render() should be a pure function of props and state. It should ' +
<add> 'never access something that requires stale data from the previous ' +
<add> 'render, such as refs. Move this logic to componentDidMount and ' +
<add> 'componentDidUpdate instead.',
<add> owner.getName() || 'A component'
<add> );
<add> owner._warnedAboutRefsInRender = true;
<add> }
<add> }
<add> if (componentOrHandle == null) {
<add> return null;
<add> }
<add> if (typeof componentOrHandle === 'number') {
<add> // Already a node handle
<add> return componentOrHandle;
<add> }
<add>
<add> var component = componentOrHandle;
<add>
<add> // TODO (balpert): Wrap iOS native components in a composite wrapper, then
<add> // ReactInstanceMap.get here will always succeed for mounted components
<add> var internalInstance = ReactInstanceMap.get(component);
<add> if (internalInstance) {
<add> return ReactNativeTagHandles.rootNodeIDToTag[internalInstance._rootNodeID];
<add> } else {
<add> var rootNodeID = component._rootNodeID;
<add> if (rootNodeID) {
<add> return ReactNativeTagHandles.rootNodeIDToTag[rootNodeID];
<add> } else {
<add> invariant(
<add> (
<add> // Native
<add> typeof component === 'object' &&
<add> '_rootNodeID' in component
<add> ) || (
<add> // Composite
<add> component.render != null &&
<add> typeof component.render === 'function'
<add> ),
<add> 'findNodeHandle(...): Argument is not a component ' +
<add> '(type: %s, keys: %s)',
<add> typeof component,
<add> Object.keys(component)
<add> );
<add> invariant(
<add> false,
<add> 'findNodeHandle(...): Unable to find node handle for unmounted ' +
<add> 'component.'
<add> );
<add> }
<add> }
<add>}
<add>
<add>module.exports = findNodeHandle;
<ide><path>src/renderers/native/vendor/react/browser/eventPlugins/PanResponder.js
<add>/**
<add> * @providesModule PanResponder
<add> */
<add>
<add>"use strict";
<add>
<add>var TouchHistoryMath = require('TouchHistoryMath');
<add>
<add>var currentCentroidXOfTouchesChangedAfter =
<add> TouchHistoryMath.currentCentroidXOfTouchesChangedAfter;
<add>var currentCentroidYOfTouchesChangedAfter =
<add> TouchHistoryMath.currentCentroidYOfTouchesChangedAfter;
<add>var previousCentroidXOfTouchesChangedAfter =
<add> TouchHistoryMath.previousCentroidXOfTouchesChangedAfter;
<add>var previousCentroidYOfTouchesChangedAfter =
<add> TouchHistoryMath.previousCentroidYOfTouchesChangedAfter;
<add>var currentCentroidX = TouchHistoryMath.currentCentroidX;
<add>var currentCentroidY = TouchHistoryMath.currentCentroidY;
<add>
<add>/**
<add> * `PanResponder` reconciles several touches into a single gesture. It makes
<add> * single-touch gestures resilient to extra touches, and can be used to
<add> * recognize simple multi-touch gestures.
<add> *
<add> * It provides a predictable wrapper of the responder handlers provided by the
<add> * [gesture responder system](docs/gesture-responder-system.html).
<add> * For each handler, it provides a new `gestureState` object alongside the
<add> * native event object:
<add> *
<add> * ```
<add> * onPanResponderMove: (event, gestureState) => {}
<add> * ```
<add> *
<add> * A native event is a synthetic touch event with the following form:
<add> *
<add> * - `nativeEvent`
<add> * + `changedTouches` - Array of all touch events that have changed since the last event
<add> * + `identifier` - The ID of the touch
<add> * + `locationX` - The X position of the touch, relative to the element
<add> * + `locationY` - The Y position of the touch, relative to the element
<add> * + `pageX` - The X position of the touch, relative to the root element
<add> * + `pageY` - The Y position of the touch, relative to the root element
<add> * + `target` - The node id of the element receiving the touch event
<add> * + `timestamp` - A time identifier for the touch, useful for velocity calculation
<add> * + `touches` - Array of all current touches on the screen
<add> *
<add> * A `gestureState` object has the following:
<add> *
<add> * - `stateID` - ID of the gestureState- persisted as long as there at least
<add> * one touch on screen
<add> * - `moveX` - the latest screen coordinates of the recently-moved touch
<add> * - `moveY` - the latest screen coordinates of the recently-moved touch
<add> * - `x0` - the screen coordinates of the responder grant
<add> * - `y0` - the screen coordinates of the responder grant
<add> * - `dx` - accumulated distance of the gesture since the touch started
<add> * - `dy` - accumulated distance of the gesture since the touch started
<add> * - `vx` - current velocity of the gesture
<add> * - `vy` - current velocity of the gesture
<add> * - `numberActiveTouches` - Number of touches currently on screen
<add> *
<add> * ### Basic Usage
<add> *
<add> * ```
<add> * componentWillMount: function() {
<add> * this._panResponder = PanResponder.create({
<add> * // Ask to be the responder:
<add> * onStartShouldSetPanResponder: (evt, gestureState) => true,
<add> * onStartShouldSetPanResponderCapture: (evt, gestureState) => true,
<add> * onMoveShouldSetPanResponder: (evt, gestureState) => true,
<add> * onMoveShouldSetPanResponderCapture: (evt, gestureState) => true,
<add> *
<add> * onPanResponderGrant: (evt, gestureState) => {
<add> * // The guesture has started. Show visual feedback so the user knows
<add> * // what is happening!
<add> *
<add> * // gestureState.{x,y}0 will be set to zero now
<add> * },
<add> * onPanResponderMove: (evt, gestureState) => {
<add> * // The most recent move distance is gestureState.move{X,Y}
<add> *
<add> * // The accumulated gesture distance since becoming responder is
<add> * // gestureState.d{x,y}
<add> * },
<add> * onPanResponderTerminationRequest: (evt, gestureState) => true,
<add> * onPanResponderRelease: (evt, gestureState) => {
<add> * // The user has released all touches while this view is the
<add> * // responder. This typically means a gesture has succeeded
<add> * },
<add> * onPanResponderTerminate: (evt, gestureState) => {
<add> * // Another component has become the responder, so this gesture
<add> * // should be cancelled
<add> * },
<add> * onShouldBlockNativeResponder: (evt, gestureState) => {
<add> * // Returns whether this component should block native components from becoming the JS
<add> * // responder. Returns true by default. Is currently only supported on android.
<add> * return true;
<add> * },
<add> * });
<add> * },
<add> *
<add> * render: function() {
<add> * return (
<add> * <View {...this._panResponder.panHandlers} />
<add> * );
<add> * },
<add> *
<add> * ```
<add> *
<add> * ### Working Example
<add> *
<add> * To see it in action, try the
<add> * [PanResponder example in UIExplorer](https://github.com/facebook/react-native/blob/master/Examples/UIExplorer/PanResponderExample.js)
<add> */
<add>
<add>var PanResponder = {
<add>
<add> /**
<add> *
<add> * A graphical explanation of the touch data flow:
<add> *
<add> * +----------------------------+ +--------------------------------+
<add> * | ResponderTouchHistoryStore | |TouchHistoryMath |
<add> * +----------------------------+ +----------+---------------------+
<add> * |Global store of touchHistory| |Allocation-less math util |
<add> * |including activeness, start | |on touch history (centroids |
<add> * |position, prev/cur position.| |and multitouch movement etc) |
<add> * | | | |
<add> * +----^-----------------------+ +----^---------------------------+
<add> * | |
<add> * | (records relevant history |
<add> * | of touches relevant for |
<add> * | implementing higher level |
<add> * | gestures) |
<add> * | |
<add> * +----+-----------------------+ +----|---------------------------+
<add> * | ResponderEventPlugin | | | Your App/Component |
<add> * +----------------------------+ +----|---------------------------+
<add> * |Negotiates which view gets | Low level | | High level |
<add> * |onResponderMove events. | events w/ | +-+-------+ events w/ |
<add> * |Also records history into | touchHistory| | Pan | multitouch + |
<add> * |ResponderTouchHistoryStore. +---------------->Responder+-----> accumulative|
<add> * +----------------------------+ attached to | | | distance and |
<add> * each event | +---------+ velocity. |
<add> * | |
<add> * | |
<add> * +--------------------------------+
<add> *
<add> *
<add> *
<add> * Gesture that calculates cumulative movement over time in a way that just
<add> * "does the right thing" for multiple touches. The "right thing" is very
<add> * nuanced. When moving two touches in opposite directions, the cumulative
<add> * distance is zero in each dimension. When two touches move in parallel five
<add> * pixels in the same direction, the cumulative distance is five, not ten. If
<add> * two touches start, one moves five in a direction, then stops and the other
<add> * touch moves fives in the same direction, the cumulative distance is ten.
<add> *
<add> * This logic requires a kind of processing of time "clusters" of touch events
<add> * so that two touch moves that essentially occur in parallel but move every
<add> * other frame respectively, are considered part of the same movement.
<add> *
<add> * Explanation of some of the non-obvious fields:
<add> *
<add> * - moveX/moveY: If no move event has been observed, then `(moveX, moveY)` is
<add> * invalid. If a move event has been observed, `(moveX, moveY)` is the
<add> * centroid of the most recently moved "cluster" of active touches.
<add> * (Currently all move have the same timeStamp, but later we should add some
<add> * threshold for what is considered to be "moving"). If a palm is
<add> * accidentally counted as a touch, but a finger is moving greatly, the palm
<add> * will move slightly, but we only want to count the single moving touch.
<add> * - x0/y0: Centroid location (non-cumulative) at the time of becoming
<add> * responder.
<add> * - dx/dy: Cumulative touch distance - not the same thing as sum of each touch
<add> * distance. Accounts for touch moves that are clustered together in time,
<add> * moving the same direction. Only valid when currently responder (otherwise,
<add> * it only represents the drag distance below the threshold).
<add> * - vx/vy: Velocity.
<add> */
<add>
<add> _initializeGestureState: function(gestureState) {
<add> gestureState.moveX = 0;
<add> gestureState.moveY = 0;
<add> gestureState.x0 = 0;
<add> gestureState.y0 = 0;
<add> gestureState.dx = 0;
<add> gestureState.dy = 0;
<add> gestureState.vx = 0;
<add> gestureState.vy = 0;
<add> gestureState.numberActiveTouches = 0;
<add> // All `gestureState` accounts for timeStamps up until:
<add> gestureState._accountsForMovesUpTo = 0;
<add> },
<add>
<add> /**
<add> * This is nuanced and is necessary. It is incorrect to continuously take all
<add> * active *and* recently moved touches, find the centroid, and track how that
<add> * result changes over time. Instead, we must take all recently moved
<add> * touches, and calculate how the centroid has changed just for those
<add> * recently moved touches, and append that change to an accumulator. This is
<add> * to (at least) handle the case where the user is moving three fingers, and
<add> * then one of the fingers stops but the other two continue.
<add> *
<add> * This is very different than taking all of the recently moved touches and
<add> * storing their centroid as `dx/dy`. For correctness, we must *accumulate
<add> * changes* in the centroid of recently moved touches.
<add> *
<add> * There is also some nuance with how we handle multiple moved touches in a
<add> * single event. With the way `ReactNativeEventEmitter` dispatches touches as
<add> * individual events, multiple touches generate two 'move' events, each of
<add> * them triggering `onResponderMove`. But with the way `PanResponder` works,
<add> * all of the gesture inference is performed on the first dispatch, since it
<add> * looks at all of the touches (even the ones for which there hasn't been a
<add> * native dispatch yet). Therefore, `PanResponder` does not call
<add> * `onResponderMove` passed the first dispatch. This diverges from the
<add> * typical responder callback pattern (without using `PanResponder`), but
<add> * avoids more dispatches than necessary.
<add> */
<add> _updateGestureStateOnMove: function(gestureState, touchHistory) {
<add> gestureState.numberActiveTouches = touchHistory.numberActiveTouches;
<add> gestureState.moveX = currentCentroidXOfTouchesChangedAfter(
<add> touchHistory,
<add> gestureState._accountsForMovesUpTo
<add> );
<add> gestureState.moveY = currentCentroidYOfTouchesChangedAfter(
<add> touchHistory,
<add> gestureState._accountsForMovesUpTo
<add> );
<add> var movedAfter = gestureState._accountsForMovesUpTo;
<add> var prevX = previousCentroidXOfTouchesChangedAfter(touchHistory, movedAfter);
<add> var x = currentCentroidXOfTouchesChangedAfter(touchHistory, movedAfter);
<add> var prevY = previousCentroidYOfTouchesChangedAfter(touchHistory, movedAfter);
<add> var y = currentCentroidYOfTouchesChangedAfter(touchHistory, movedAfter);
<add> var nextDX = gestureState.dx + (x - prevX);
<add> var nextDY = gestureState.dy + (y - prevY);
<add>
<add> // TODO: This must be filtered intelligently.
<add> var dt =
<add> (touchHistory.mostRecentTimeStamp - gestureState._accountsForMovesUpTo);
<add> gestureState.vx = (nextDX - gestureState.dx) / dt;
<add> gestureState.vy = (nextDY - gestureState.dy) / dt;
<add>
<add> gestureState.dx = nextDX;
<add> gestureState.dy = nextDY;
<add> gestureState._accountsForMovesUpTo = touchHistory.mostRecentTimeStamp;
<add> },
<add>
<add> /**
<add> * @param {object} config Enhanced versions of all of the responder callbacks
<add> * that provide not only the typical `ResponderSyntheticEvent`, but also the
<add> * `PanResponder` gesture state. Simply replace the word `Responder` with
<add> * `PanResponder` in each of the typical `onResponder*` callbacks. For
<add> * example, the `config` object would look like:
<add> *
<add> * - `onMoveShouldSetPanResponder: (e, gestureState) => {...}`
<add> * - `onMoveShouldSetPanResponderCapture: (e, gestureState) => {...}`
<add> * - `onStartShouldSetPanResponder: (e, gestureState) => {...}`
<add> * - `onStartShouldSetPanResponderCapture: (e, gestureState) => {...}`
<add> * - `onPanResponderReject: (e, gestureState) => {...}`
<add> * - `onPanResponderGrant: (e, gestureState) => {...}`
<add> * - `onPanResponderStart: (e, gestureState) => {...}`
<add> * - `onPanResponderEnd: (e, gestureState) => {...}`
<add> * - `onPanResponderRelease: (e, gestureState) => {...}`
<add> * - `onPanResponderMove: (e, gestureState) => {...}`
<add> * - `onPanResponderTerminate: (e, gestureState) => {...}`
<add> * - `onPanResponderTerminationRequest: (e, gestureState) => {...}`
<add> * - `onShouldBlockNativeResponder: (e, gestureState) => {...}`
<add> *
<add> * In general, for events that have capture equivalents, we update the
<add> * gestureState once in the capture phase and can use it in the bubble phase
<add> * as well.
<add> *
<add> * Be careful with onStartShould* callbacks. They only reflect updated
<add> * `gestureState` for start/end events that bubble/capture to the Node.
<add> * Once the node is the responder, you can rely on every start/end event
<add> * being processed by the gesture and `gestureState` being updated
<add> * accordingly. (numberActiveTouches) may not be totally accurate unless you
<add> * are the responder.
<add> */
<add> create: function(config) {
<add> var gestureState = {
<add> // Useful for debugging
<add> stateID: Math.random(),
<add> };
<add> PanResponder._initializeGestureState(gestureState);
<add> var panHandlers = {
<add> onStartShouldSetResponder: function(e) {
<add> return config.onStartShouldSetPanResponder === undefined ? false :
<add> config.onStartShouldSetPanResponder(e, gestureState);
<add> },
<add> onMoveShouldSetResponder: function(e) {
<add> return config.onMoveShouldSetPanResponder === undefined ? false :
<add> config.onMoveShouldSetPanResponder(e, gestureState);
<add> },
<add> onStartShouldSetResponderCapture: function(e) {
<add> // TODO: Actually, we should reinitialize the state any time
<add> // touches.length increases from 0 active to > 0 active.
<add> if (e.nativeEvent.touches.length === 1) {
<add> PanResponder._initializeGestureState(gestureState);
<add> }
<add> gestureState.numberActiveTouches = e.touchHistory.numberActiveTouches;
<add> return config.onStartShouldSetPanResponderCapture !== undefined ?
<add> config.onStartShouldSetPanResponderCapture(e, gestureState) : false;
<add> },
<add>
<add> onMoveShouldSetResponderCapture: function(e) {
<add> var touchHistory = e.touchHistory;
<add> // Responder system incorrectly dispatches should* to current responder
<add> // Filter out any touch moves past the first one - we would have
<add> // already processed multi-touch geometry during the first event.
<add> if (gestureState._accountsForMovesUpTo === touchHistory.mostRecentTimeStamp) {
<add> return false;
<add> }
<add> PanResponder._updateGestureStateOnMove(gestureState, touchHistory);
<add> return config.onMoveShouldSetPanResponderCapture ?
<add> config.onMoveShouldSetPanResponderCapture(e, gestureState) : false;
<add> },
<add>
<add> onResponderGrant: function(e) {
<add> gestureState.x0 = currentCentroidX(e.touchHistory);
<add> gestureState.y0 = currentCentroidY(e.touchHistory);
<add> gestureState.dx = 0;
<add> gestureState.dy = 0;
<add> config.onPanResponderGrant && config.onPanResponderGrant(e, gestureState);
<add> // TODO: t7467124 investigate if this can be removed
<add> return config.onShouldBlockNativeResponder === undefined ? true :
<add> config.onShouldBlockNativeResponder();
<add> },
<add>
<add> onResponderReject: function(e) {
<add> config.onPanResponderReject && config.onPanResponderReject(e, gestureState);
<add> },
<add>
<add> onResponderRelease: function(e) {
<add> config.onPanResponderRelease && config.onPanResponderRelease(e, gestureState);
<add> PanResponder._initializeGestureState(gestureState);
<add> },
<add>
<add> onResponderStart: function(e) {
<add> var touchHistory = e.touchHistory;
<add> gestureState.numberActiveTouches = touchHistory.numberActiveTouches;
<add> config.onPanResponderStart && config.onPanResponderStart(e, gestureState);
<add> },
<add>
<add> onResponderMove: function(e) {
<add> var touchHistory = e.touchHistory;
<add> // Guard against the dispatch of two touch moves when there are two
<add> // simultaneously changed touches.
<add> if (gestureState._accountsForMovesUpTo === touchHistory.mostRecentTimeStamp) {
<add> return;
<add> }
<add> // Filter out any touch moves past the first one - we would have
<add> // already processed multi-touch geometry during the first event.
<add> PanResponder._updateGestureStateOnMove(gestureState, touchHistory);
<add> config.onPanResponderMove && config.onPanResponderMove(e, gestureState);
<add> },
<add>
<add> onResponderEnd: function(e) {
<add> var touchHistory = e.touchHistory;
<add> gestureState.numberActiveTouches = touchHistory.numberActiveTouches;
<add> config.onPanResponderEnd && config.onPanResponderEnd(e, gestureState);
<add> },
<add>
<add> onResponderTerminate: function(e) {
<add> config.onPanResponderTerminate &&
<add> config.onPanResponderTerminate(e, gestureState);
<add> PanResponder._initializeGestureState(gestureState);
<add> },
<add>
<add> onResponderTerminationRequest: function(e) {
<add> return config.onPanResponderTerminationRequest === undefined ? true :
<add> config.onPanResponderTerminationRequest(e, gestureState);
<add> },
<add> };
<add> return {panHandlers: panHandlers};
<add> },
<add>};
<add>
<add>module.exports = PanResponder;
<ide><path>src/renderers/native/vendor/react/browser/eventPlugins/TouchHistoryMath.js
<add>/**
<add> * @providesModule TouchHistoryMath
<add> */
<add>
<add>"use strict";
<add>
<add>var TouchHistoryMath = {
<add> /**
<add> * This code is optimized and not intended to look beautiful. This allows
<add> * computing of touch centroids that have moved after `touchesChangedAfter`
<add> * timeStamp. You can compute the current centroid involving all touches
<add> * moves after `touchesChangedAfter`, or you can compute the previous
<add> * centroid of all touches that were moved after `touchesChangedAfter`.
<add> *
<add> * @param {TouchHistoryMath} touchHistory Standard Responder touch track
<add> * data.
<add> * @param {number} touchesChangedAfter timeStamp after which moved touches
<add> * are considered "actively moving" - not just "active".
<add> * @param {boolean} isXAxis Consider `x` dimension vs. `y` dimension.
<add> * @param {boolean} ofCurrent Compute current centroid for actively moving
<add> * touches vs. previous centroid of now actively moving touches.
<add> * @return {number} value of centroid in specified dimension.
<add> */
<add> centroidDimension: function(touchHistory, touchesChangedAfter, isXAxis, ofCurrent) {
<add> var touchBank = touchHistory.touchBank;
<add> var total = 0;
<add> var count = 0;
<add>
<add> var oneTouchData = touchHistory.numberActiveTouches === 1 ?
<add> touchHistory.touchBank[touchHistory.indexOfSingleActiveTouch] : null;
<add>
<add> if (oneTouchData !== null) {
<add> if (oneTouchData.touchActive && oneTouchData.currentTimeStamp > touchesChangedAfter) {
<add> total += ofCurrent && isXAxis ? oneTouchData.currentPageX :
<add> ofCurrent && !isXAxis ? oneTouchData.currentPageY :
<add> !ofCurrent && isXAxis ? oneTouchData.previousPageX :
<add> oneTouchData.previousPageY;
<add> count = 1;
<add> }
<add> } else {
<add> for (var i = 0; i < touchBank.length; i++) {
<add> var touchTrack = touchBank[i];
<add> if (touchTrack !== null &&
<add> touchTrack !== undefined &&
<add> touchTrack.touchActive &&
<add> touchTrack.currentTimeStamp >= touchesChangedAfter) {
<add> var toAdd; // Yuck, program temporarily in invalid state.
<add> if (ofCurrent && isXAxis) {
<add> toAdd = touchTrack.currentPageX;
<add> } else if (ofCurrent && !isXAxis) {
<add> toAdd = touchTrack.currentPageY;
<add> } else if (!ofCurrent && isXAxis) {
<add> toAdd = touchTrack.previousPageX;
<add> } else {
<add> toAdd = touchTrack.previousPageY;
<add> }
<add> total += toAdd;
<add> count++;
<add> }
<add> }
<add> }
<add> return count > 0 ? total / count : TouchHistoryMath.noCentroid;
<add> },
<add>
<add> currentCentroidXOfTouchesChangedAfter: function(touchHistory, touchesChangedAfter) {
<add> return TouchHistoryMath.centroidDimension(
<add> touchHistory,
<add> touchesChangedAfter,
<add> true, // isXAxis
<add> true // ofCurrent
<add> );
<add> },
<add>
<add> currentCentroidYOfTouchesChangedAfter: function(touchHistory, touchesChangedAfter) {
<add> return TouchHistoryMath.centroidDimension(
<add> touchHistory,
<add> touchesChangedAfter,
<add> false, // isXAxis
<add> true // ofCurrent
<add> );
<add> },
<add>
<add> previousCentroidXOfTouchesChangedAfter: function(touchHistory, touchesChangedAfter) {
<add> return TouchHistoryMath.centroidDimension(
<add> touchHistory,
<add> touchesChangedAfter,
<add> true, // isXAxis
<add> false // ofCurrent
<add> );
<add> },
<add>
<add> previousCentroidYOfTouchesChangedAfter: function(touchHistory, touchesChangedAfter) {
<add> return TouchHistoryMath.centroidDimension(
<add> touchHistory,
<add> touchesChangedAfter,
<add> false, // isXAxis
<add> false // ofCurrent
<add> );
<add> },
<add>
<add> currentCentroidX: function(touchHistory) {
<add> return TouchHistoryMath.centroidDimension(
<add> touchHistory,
<add> 0, // touchesChangedAfter
<add> true, // isXAxis
<add> true // ofCurrent
<add> );
<add> },
<add>
<add> currentCentroidY: function(touchHistory) {
<add> return TouchHistoryMath.centroidDimension(
<add> touchHistory,
<add> 0, // touchesChangedAfter
<add> false, // isXAxis
<add> true // ofCurrent
<add> );
<add> },
<add>
<add> noCentroid: -1,
<add>};
<add>
<add>module.exports = TouchHistoryMath;
<ide><path>src/renderers/native/vendor/react/core/clamp.js
<add>/**
<add> * @generated SignedSource<<ec51291ea6059cf23faa74f8644d17b1>>
<add> *
<add> * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
<add> * !! This file is a check-in of a static_upstream project! !!
<add> * !! !!
<add> * !! You should not modify this file directly. Instead: !!
<add> * !! 1) Use `fjs use-upstream` to temporarily replace this with !!
<add> * !! the latest version from upstream. !!
<add> * !! 2) Make your changes, test them, etc. !!
<add> * !! 3) Use `fjs push-upstream` to copy your changes back to !!
<add> * !! static_upstream. !!
<add> * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
<add> *
<add> * @providesModule clamp
<add> * @typechecks
<add> */
<add>
<add> /**
<add> * @param {number} value
<add> * @param {number} min
<add> * @param {number} max
<add> * @return {number}
<add> */
<add>function clamp(min, value, max) {
<add> if (value < min) {
<add> return min;
<add> }
<add> if (value > max) {
<add> return max;
<add> }
<add> return value;
<add>}
<add>
<add>module.exports = clamp;
<ide><path>src/renderers/native/vendor/react/platform/NodeHandle.js
<add>/**
<add> * @providesModule NodeHandle
<add> */
<add>
<add> /**
<add> * A "handle" is a serializable representation of the underlying platform's
<add> * native node abstraction. This allows reasoning about nodes behind a thread
<add> * (worker) boundary. On some platforms (DOM main thread) the node handle *is*
<add> * an actual DOM node - `NodeHandle` (and potentially other libraries)
<add> * abstract away those differences so you can write code that doesn't depend
<add> * on whether or not you are running in a worker. For example, you could write
<add> * application code:
<add> *
<add> *
<add> * SomeLibrary.measureNodeHandle(myNodeHandle, cb)
<add> *
<add> * Where `measureNodeHandle` knows how to handle actual DOM nodes if running
<add> * in a worker thread, and knows how to handle numeric IDs if running in a
<add> * worker thread.
<add> *
<add> * The only other requirement of a platform/environment is that it always be
<add> * possible to extract the React rootNodeID in a blocking manner (see
<add> * `getRootNodeID`).
<add> *
<add> * +------------------+ +------------------+ +------------------+
<add> * | | | | | |
<add> * | ReactJS | | YourUtilities | | Animation Utils |
<add> * | | | | | |
<add> * +------------------+ +------------------+ +------------------+
<add> *
<add> * +------------------------------------------------------------+
<add> * | Async Platform Independent Node Interface |
<add> * +------------------------------------------------------------+
<add> * | |
<add> * | NodeIterface: |
<add> * | -measure(nodeHandle, cb) |
<add> * | -setProperties(nodeHandle, cb) |
<add> * | -manageChildren(nodeHandle, nodeHandles, cb) |
<add> * | ... |
<add> * | |
<add> * | Note: This may be a simplification. We could break up much |
<add> * | of this functionality into several smaller libraries, each |
<add> * | one requiring a . |
<add> * +------------------------------------------------------------+
<add> *
<add> * +------------------------------------------------------------+
<add> * | Platform Implementations |
<add> * | ----------------------------------------- |
<add> * | React Canvas | React DOM Worker | React DOM main |
<add> * +------------------------------------------------------------+
<add> * | | | |
<add> * |-measure(..) |-measure(..) |-measure(..) |
<add> * |-setProperties(..) |-setProperties(..) |-setProperties(..) |
<add> * |-manageChildren(..)|-manageChildren(..) |-manageChildren(..)|
<add> * | ... | ... | ... |
<add> * +-----------------------------o------------------------------+
<add> * | Worker simply ^
<add> * | marshals commands |
<add> * | to Web DOM thread. |
<add> * +---------------------+
<add> */
<add>var NodeHandle = {
<add> /**
<add> * Injection
<add> */
<add> injection: {
<add> injectImplementation: function(Impl) {
<add> NodeHandle._Implementation = Impl;
<add> }
<add> },
<add>
<add> _Implementation: null,
<add>
<add> /**
<add> * @param {NodeHandle} nodeHandle The handle to the low level resource.
<add> * @return {string} React root node ID.
<add> */
<add> getRootNodeID: function(nodeHandle) {
<add> return NodeHandle._Implementation.getRootNodeID(nodeHandle);
<add> }
<add>};
<add>
<add>module.exports = NodeHandle;
<ide><path>src/renderers/native/vendor/react/platformImplementations/universal/worker/UniversalWorkerNodeHandle.js
<add>/**
<add> * @providesModule UniversalWorkerNodeHandle
<add> */
<add>
<add>var ReactNativeTagHandles = require('ReactNativeTagHandles');
<add>
<add>var invariant = require('fbjs/lib/invariant');
<add>
<add>var UniversalWorkerNodeHandle = {
<add> getRootNodeID: function(nodeHandle) {
<add> invariant(
<add> nodeHandle !== undefined && nodeHandle !== null && nodeHandle !== 0,
<add> 'No node handle defined'
<add> );
<add> return ReactNativeTagHandles.tagToRootNodeID[nodeHandle];
<add> }
<add>};
<add>
<add>module.exports = UniversalWorkerNodeHandle;
<ide><path>src/renderers/native/vendor/react/vendor/core/ExecutionEnvironment.android.js
<add>/**
<add> * Copyright 2013-2014 Facebook, Inc.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> *
<add> * @providesModule ExecutionEnvironment
<add> *
<add> * NB: This is a temporary override that has not yet been merged upstream. It is NOT actually part
<add> * of react-core (yet)
<add> *
<add> * Stubs SignedSource<<7afee88a05412d0c4eef54817419648e>>
<add> */
<add>
<add>/*jslint evil: true */
<add>
<add>"use strict";
<add>
<add>var canUseDOM = false;
<add>
<add>/**
<add> * Simple, lightweight module assisting with the detection and context of
<add> * Worker. Helps avoid circular dependencies and allows code to reason about
<add> * whether or not they are in a Worker, even if they never include the main
<add> * `ReactWorker` dependency.
<add> */
<add>var ExecutionEnvironment = {
<add>
<add> canUseDOM: canUseDOM,
<add>
<add> canUseWorkers: typeof Worker !== 'undefined',
<add>
<add> canUseEventListeners:
<add> canUseDOM && !!(window.addEventListener || window.attachEvent),
<add>
<add> canUseViewport: canUseDOM && !!window.screen,
<add>
<add> isInWorker: !canUseDOM // For now, this is true - might change in the future.
<add>
<add>};
<add>
<add>module.exports = ExecutionEnvironment;
<ide><path>src/renderers/native/vendor/react/vendor/core/ExecutionEnvironment.ios.js
<add>/**
<add> * Copyright 2013-2014 Facebook, Inc.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> *
<add> * @providesModule ExecutionEnvironment
<add> *
<add> * Stubs SignedSource<<7afee88a05412d0c4eef54817419648e>>
<add> */
<add>
<add>/*jslint evil: true */
<add>
<add>"use strict";
<add>
<add>var canUseDOM = false;
<add>
<add>/**
<add> * Simple, lightweight module assisting with the detection and context of
<add> * Worker. Helps avoid circular dependencies and allows code to reason about
<add> * whether or not they are in a Worker, even if they never include the main
<add> * `ReactWorker` dependency.
<add> */
<add>var ExecutionEnvironment = {
<add>
<add> canUseDOM: canUseDOM,
<add>
<add> canUseWorkers: typeof Worker !== 'undefined',
<add>
<add> canUseEventListeners:
<add> canUseDOM && !!(window.addEventListener || window.attachEvent),
<add>
<add> canUseViewport: canUseDOM && !!window.screen,
<add>
<add> isInWorker: !canUseDOM // For now, this is true - might change in the future.
<add>
<add>};
<add>
<add>module.exports = ExecutionEnvironment; | 35 |
PHP | PHP | add assertions for error codes to routes shell | 7c76081fd1710c82e80732bb3c233fe2c7867e56 | <ide><path>tests/TestCase/Shell/RoutesShellTest.php
<ide> */
<ide> namespace Cake\Test\TestCase\Shell;
<ide>
<add>use Cake\Console\Shell;
<ide> use Cake\Routing\Router;
<ide> use Cake\Shell\RoutesShell;
<ide> use Cake\TestSuite\ConsoleIntegrationTestCase;
<ide> public function tearDown()
<ide> Router::reload();
<ide> }
<ide>
<del> /**
<del> * Check that a row of cells exists in the output.
<del> *
<del> * @param array $row The row of cells to check
<del> * @return void
<del> */
<del> protected function assertOutputContainsRow(array $row)
<del> {
<del> $row = array_map(function ($cell) {
<del> return preg_quote($cell, '/');
<del> }, $row);
<del> $cells = implode('\s+\|\s+', $row);
<del> $pattern = '/' . $cells . '/';
<del> $this->assertOutputRegexp($pattern);
<del> }
<del>
<ide> /**
<ide> * Test checking an non-existing route.
<ide> *
<ide> protected function assertOutputContainsRow(array $row)
<ide> public function testMain()
<ide> {
<ide> $this->exec('routes');
<add> $this->assertExitCode(Shell::CODE_SUCCESS);
<ide> $this->assertOutputContainsRow([
<ide> '<info>Route name</info>',
<ide> '<info>URI template</info>',
<ide> public function testMain()
<ide> public function testCheck()
<ide> {
<ide> $this->exec('routes check /articles/check');
<add> $this->assertExitCode(Shell::CODE_SUCCESS);
<ide> $this->assertOutputContainsRow([
<ide> '<info>Route name</info>',
<ide> '<info>URI template</info>',
<ide> public function testCheck()
<ide> public function testCheckWithNamedRoute()
<ide> {
<ide> $this->exec('routes check /tests/index');
<add> $this->assertExitCode(Shell::CODE_SUCCESS);
<ide> $this->assertOutputContainsRow([
<ide> '<info>Route name</info>',
<ide> '<info>URI template</info>',
<ide> public function testCheckWithNamedRoute()
<ide> public function testCheckNotFound()
<ide> {
<ide> $this->exec('routes check /nope');
<add> $this->assertExitCode(Shell::CODE_ERROR);
<ide> $this->assertErrorContains('did not match');
<ide> }
<ide>
<ide> public function testCheckNotFound()
<ide> public function testGenerateNoPassArgs()
<ide> {
<ide> $this->exec('routes generate controller:Articles action:index');
<add> $this->assertExitCode(Shell::CODE_SUCCESS);
<ide> $this->assertOutputContains('> /articles/index');
<ide> $this->assertErrorEmpty();
<ide> }
<ide> public function testGenerateNoPassArgs()
<ide> public function testGeneratePassedArguments()
<ide> {
<ide> $this->exec('routes generate controller:Articles action:view 2 3');
<add> $this->assertExitCode(Shell::CODE_SUCCESS);
<ide> $this->assertOutputContains('> /articles/view/2/3');
<ide> $this->assertErrorEmpty();
<ide> }
<ide> public function testGeneratePassedArguments()
<ide> public function testGenerateBoolParams()
<ide> {
<ide> $this->exec('routes generate controller:Articles action:index _ssl:true _host:example.com');
<add> $this->assertExitCode(Shell::CODE_SUCCESS);
<ide> $this->assertOutputContains('> https://example.com/articles/index');
<ide> }
<ide>
<ide> public function testGenerateBoolParams()
<ide> public function testGenerateMissing()
<ide> {
<ide> $this->exec('routes generate controller:Derp');
<add> $this->assertExitCode(Shell::CODE_ERROR);
<ide> $this->assertErrorContains('do not match');
<ide> }
<ide> } | 1 |
Ruby | Ruby | add ability to run system tests via capybara | 0862cf1bbffe0a3c82e311804244a8cb715332a6 | <ide><path>actionpack/lib/system_test_case.rb
<add>require 'system_testing/base'
<add>
<ide> module Rails
<ide> class SystemTestCase < ActiveSupport::TestCase
<ide> include Rails.application.routes.url_helpers
<add> include SystemTesting::Base
<ide> end
<ide> end
<ide><path>actionpack/lib/system_testing/base.rb
<add>require 'system_testing/test_helper'
<add>require 'system_testing/driver_adapter'
<add>
<add>module SystemTesting
<add> module Base
<add> include TestHelper
<add> include DriverAdapter
<add> end
<add>end
<ide><path>actionpack/lib/system_testing/driver_adapter.rb
<add>require 'system_testing/driver_adapters'
<add>
<add>module SystemTesting
<add> module DriverAdapter
<add> extend ActiveSupport::Concern
<add>
<add> included do
<add> self.driver_adapter = :capybara_rack_test_driver
<add> end
<add>
<add> module ClassMethods
<add> def driver_adapter=(driver_name_or_class)
<add> driver = DriverAdapters.lookup(driver_name_or_class).new
<add> driver.call
<add> end
<add> end
<add> end
<add>end
<ide><path>actionpack/lib/system_testing/driver_adapters.rb
<add>module SystemTesting
<add> module DriverAdapters
<add> extend ActiveSupport::Autoload
<add>
<add> autoload :CapybaraRackTestDriver
<add>
<add> class << self
<add> def lookup(name)
<add> const_get(name.to_s.camelize)
<add> end
<add> end
<add> end
<add>end
<ide><path>actionpack/lib/system_testing/driver_adapters/capybara_rack_test_driver.rb
<add>module SystemTesting
<add> module DriverAdapters
<add> class CapybaraRackTestDriver
<add> attr_reader :useragent
<add>
<add> def initialize(useragent: 'Capybara')
<add> @useragent = useragent
<add> end
<add>
<add> def call
<add> registration
<add> end
<add>
<add> private
<add> def registration
<add> Capybara.register_driver :rack_test do |app|
<add> Capybara::RackTest::Driver.new(app, headers: {
<add> 'HTTP_USER_AGENT' => @useragent
<add> })
<add> end
<add> end
<add> end
<add> end
<add>end
<ide><path>actionpack/lib/system_testing/test_helper.rb
<add>require 'capybara/rails'
<add>
<add>module SystemTesting
<add> module TestHelper
<add> include Capybara::DSL
<add>
<add> def after_teardown
<add> Capybara.reset_sessions!
<add> super
<add> end
<add> end
<add>end | 6 |
Javascript | Javascript | remove accidental white space | 5e64b96df5b674a9d83ba1bb76d6cf35329c0e08 | <ide><path>src/math/Sphere.js
<ide> Object.assign( Sphere.prototype, {
<ide> return box.intersectsSphere( this );
<ide>
<ide> },
<del>
<add>
<ide> intersectsPlane: function ( plane ) {
<ide>
<ide> return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
<ide>
<ide> },
<ide>
<del>
<ide> clampPoint: function ( point, optionalTarget ) {
<ide>
<ide> var deltaLengthSq = this.center.distanceToSquared( point ); | 1 |
Text | Text | add havan to companies list | 1070435e851ac11b144459801024fb69631ec040 | <ide><path>README.md
<ide> Currently **officially** using Airflow:
<ide> 1. [Handshake](https://joinhandshake.com/) [[@mhickman](https://github.com/mhickman)]
<ide> 1. [Handy](http://www.handy.com/careers/73115?gh_jid=73115&gh_src=o5qcxn) [[@marcintustin](https://github.com/marcintustin) / [@mtustin-handy](https://github.com/mtustin-handy)]
<ide> 1. [happn](https://www.happn.com) [[@PierreCORBEL](https://github.com/PierreCORBEL)]
<add>1. [HAVAN](https://www.havan.com.br) [[@botbiz](https://github.com/botbiz)]
<ide> 1. [HBC Digital](http://tech.hbc.com) [[@tmccartan](https://github.com/tmccartan) & [@dmateusp](https://github.com/dmateusp)]
<ide> 1. [HBO](http://www.hbo.com/)[[@yiwang](https://github.com/yiwang)]
<ide> 1. [Healthjump](http://www.healthjump.com/) [[@miscbits](https://github.com/miscbits)] | 1 |
PHP | PHP | fix an error in collection->random() | 5211c68bbaa791223e3c782c28984c3dc6165136 | <ide><path>src/Illuminate/Support/Collection.php
<ide> public function put($key, $value)
<ide> */
<ide> public function random($amount = 1)
<ide> {
<add> if (!count($this->items)) {
<add> return null;
<add> }
<add>
<ide> $keys = array_rand($this->items, $amount);
<ide>
<ide> return is_array($keys) ? array_intersect_key($this->items, array_flip($keys)) : $this->items[$keys]; | 1 |
Ruby | Ruby | add missing comma | 13f08a2bd4ff3aec13423fa5bb62b6ef08ffa0c4 | <ide><path>Library/Homebrew/cmd/update-report.rb
<ide> def migrate_legacy_repository_if_necessary
<ide> end
<ide>
<ide> unremovable_paths = []
<del> extra_remove_paths = [".git", "Library/Locks", "Library/Taps", "Caskroom"
<add> extra_remove_paths = [".git", "Library/Locks", "Library/Taps", "Caskroom",
<ide> "Library/Homebrew/cask", "Library/Homebrew/test"]
<ide> (repo_files + extra_remove_paths).each do |file|
<ide> path = Pathname.new "#{HOMEBREW_REPOSITORY}/#{file}" | 1 |
Python | Python | improve optimizer tests | 69e19b1e03492c54179bf98ea3cab7c7d032cf2b | <ide><path>tests/keras/test_optimizers.py
<ide> def _test_optimizer(optimizer, target=0.9):
<ide> history = model.fit(X_train, y_train, nb_epoch=12, batch_size=16,
<ide> validation_data=(X_test, y_test),
<ide> show_accuracy=True, verbose=2)
<del> return history.history['val_acc'][-1] > target
<add> config = optimizer.get_config()
<add> assert type(config) == dict
<add> assert history.history['val_acc'][-1] > target
<ide>
<ide>
<ide> def test_sgd():
<ide> sgd = SGD(lr=0.01, momentum=0.9, nesterov=True)
<del> assert(_test_optimizer(sgd))
<add> _test_optimizer(sgd)
<ide>
<ide>
<ide> def test_rmsprop():
<del> assert(_test_optimizer(RMSprop()))
<add> _test_optimizer(RMSprop())
<ide>
<ide>
<ide> def test_adagrad():
<del> assert(_test_optimizer(Adagrad()))
<add> _test_optimizer(Adagrad())
<ide>
<ide>
<ide> def test_adadelta():
<del> assert(_test_optimizer(Adadelta()))
<add> _test_optimizer(Adadelta())
<ide>
<ide>
<ide> def test_adam():
<del> assert(_test_optimizer(Adam()))
<add> _test_optimizer(Adam())
<ide>
<ide>
<ide> def test_adamax():
<del> assert(_test_optimizer(Adamax()))
<add> _test_optimizer(Adamax())
<ide>
<ide>
<ide> if __name__ == '__main__': | 1 |
Ruby | Ruby | fix broken to_ary expectation | 2841a14f4b26e093e88cdb6d84c82d120f53ca46 | <ide><path>activesupport/test/caching_test.rb
<ide> def test_mem_cache_fragment_cache_store_with_given_mem_cache
<ide>
<ide> def test_mem_cache_fragment_cache_store_with_given_mem_cache_like_object
<ide> MemCache.expects(:new).never
<del> store = ActiveSupport::Cache.lookup_store :mem_cache_store, stub("memcache", :get => true)
<add> memcache = Object.new
<add> def memcache.get() true end
<add> store = ActiveSupport::Cache.lookup_store :mem_cache_store, memcache
<ide> assert_kind_of(ActiveSupport::Cache::MemCacheStore, store)
<ide> end
<ide> | 1 |
PHP | PHP | improve internal documentation of benchmark class | 3ba3089208dece7255c88b0c4272d62d5a5dad96 | <ide><path>system/benchmark.php
<ide> class Benchmark {
<ide>
<ide> /**
<del> * Benchmark starting times.
<add> * All of the benchmark starting times.
<ide> *
<ide> * @var array
<ide> */
<ide> class Benchmark {
<ide> /**
<ide> * Start a benchmark.
<ide> *
<add> * After starting a benchmark, the elapsed time in milliseconds can be
<add> * retrieved using the "check" method.
<add> *
<add> * <code>
<add> * Benchmark::start('name');
<add> * </code>
<add> *
<ide> * @param string $name
<ide> * @return void
<add> * @see check
<ide> */
<ide> public static function start($name)
<ide> {
<ide> public static function start($name)
<ide> /**
<ide> * Get the elapsed time in milliseconds since starting a benchmark.
<ide> *
<add> * <code>
<add> * echo Benchmark::check('name');
<add> * </code>
<add> *
<ide> * @param string $name
<ide> * @return float
<add> * @see start
<ide> */
<ide> public static function check($name)
<ide> { | 1 |
Python | Python | fix linter warning | e6f77f8d71eaa68708fde8e7c0a7aebf79a9d1c7 | <ide><path>libcloud/compute/drivers/packet.py
<ide> def _to_size(self, data):
<ide> name = "%s - %s RAM" % (data.get('name'), ram)
<ide> price = data['pricing'].get('hour')
<ide> return NodeSize(id=data['slug'], name=name,
<del> ram=int(ram.replace('GB', ''))*1024, disk=disk,
<add> ram=int(ram.replace('GB', '')) * 1024, disk=disk,
<ide> bandwidth=0, price=price, extra=extra, driver=self)
<ide>
<ide> def _to_key_pairs(self, data): | 1 |
Javascript | Javascript | remove dom window uri check | f524eaefe24e08415fa7c8c88bd39bdfce4bd009 | <ide><path>extensions/firefox/components/PdfStreamConverter.js
<ide> PdfStreamConverter.prototype = {
<ide> // We get the DOM window here instead of before the request since it
<ide> // may have changed during a redirect.
<ide> var domWindow = getDOMWindow(channel);
<del> // Double check the url is still the correct one.
<del> if (domWindow.document.documentURIObject.equals(aRequest.URI)) {
<del> var actions;
<del> if (rangeRequest) {
<del> // We are going to be issuing range requests, so cancel the
<del> // original request
<del> aRequest.resume();
<del> aRequest.cancel(Cr.NS_BINDING_ABORTED);
<del> actions = new RangedChromeActions(domWindow,
<del> contentDispositionFilename, aRequest);
<del> } else {
<del> actions = new StandardChromeActions(
<del> domWindow, contentDispositionFilename, dataListener);
<del> }
<del> var requestListener = new RequestListener(actions);
<del> domWindow.addEventListener(PDFJS_EVENT_ID, function(event) {
<del> requestListener.receive(event);
<del> }, false, true);
<del> if (actions.supportsIntegratedFind()) {
<del> var chromeWindow = getChromeWindow(domWindow);
<del> var findEventManager = new FindEventManager(chromeWindow.gFindBar,
<del> domWindow,
<del> chromeWindow);
<del> findEventManager.bind();
<del> }
<add> var actions;
<add> if (rangeRequest) {
<add> // We are going to be issuing range requests, so cancel the
<add> // original request
<add> aRequest.resume();
<add> aRequest.cancel(Cr.NS_BINDING_ABORTED);
<add> actions = new RangedChromeActions(domWindow,
<add> contentDispositionFilename, aRequest);
<ide> } else {
<del> log('Dom window url did not match request url.');
<add> actions = new StandardChromeActions(
<add> domWindow, contentDispositionFilename, dataListener);
<add> }
<add> var requestListener = new RequestListener(actions);
<add> domWindow.addEventListener(PDFJS_EVENT_ID, function(event) {
<add> requestListener.receive(event);
<add> }, false, true);
<add> if (actions.supportsIntegratedFind()) {
<add> var chromeWindow = getChromeWindow(domWindow);
<add> var findEventManager = new FindEventManager(chromeWindow.gFindBar,
<add> domWindow,
<add> chromeWindow);
<add> findEventManager.bind();
<ide> }
<ide> listener.onStopRequest(aRequest, context, statusCode);
<ide> } | 1 |
Ruby | Ruby | add note to railtie docs to use unique filenames | de7bc3188160f6ceb943b30a0f8603c4b447a7d3 | <ide><path>railties/lib/rails/railtie.rb
<ide> module Rails
<ide> # end
<ide> # end
<ide> #
<add> # Since filenames on the load path are shared across gems, be sure that files you load
<add> # through a railtie have unique names.
<add> #
<ide> # == Application and Engine
<ide> #
<ide> # An engine is nothing more than a railtie with some initializers already set. And since | 1 |
Ruby | Ruby | add the 2.1.x series as a recognized gnupg version | 7058c089a6c38681d1d84cfec9f40f499a3cf885 | <ide><path>Library/Homebrew/gpg.rb
<ide> def self.find_gpg(executable)
<ide> which_all(executable).detect do |gpg|
<ide> gpg_short_version = Utils.popen_read(gpg, "--version")[/\d\.\d/, 0]
<ide> next unless gpg_short_version
<del> Version.create(gpg_short_version.to_s) == Version.create("2.0")
<add> gpg_version = Version.create(gpg_short_version.to_s)
<add> gpg_version == Version.create("2.0") ||
<add> gpg_version == Version.create("2.1")
<ide> end
<ide> end
<ide> | 1 |
Ruby | Ruby | fix artifact number | d304c84f2aa264ca60eaeb3d7848f88198ff1c8c | <ide><path>Library/Homebrew/test/utils/github_spec.rb
<ide> url = described_class.get_artifact_url(
<ide> described_class.get_workflow_run("Homebrew", "homebrew-core", 79751, artifact_name: "bottles"),
<ide> )
<del> expect(url).to eq("https://api.github.com/repos/Homebrew/homebrew-core/actions/artifacts/69422207/zip")
<add> expect(url).to eq("https://api.github.com/repos/Homebrew/homebrew-core/actions/artifacts/70494047/zip")
<ide> end
<ide> end
<ide> | 1 |
Javascript | Javascript | add missing babel helper | fd360ca8181f0812a20fd718fefcfb0ddd4befe7 | <ide><path>packages/external-helpers/lib/external-helpers.js
<ide> export function possibleConstructorReturn(self, call) {
<ide> }
<ide> return assertThisInitialized(self);
<ide> }
<add>
<add>export function objectDestructuringEmpty(obj) {
<add> if (DEBUG && (obj === null || obj === undefined)) {
<add> throw new TypeError('Cannot destructure undefined');
<add> }
<add>} | 1 |
Ruby | Ruby | show the formula origin for non core-formula | 4d17d4c8dbef49a9ed9fd174ed2ac2f8a7b4e9a6 | <ide><path>Library/Homebrew/cmd/gist-logs.rb
<ide> def gistify_logs f
<ide> Homebrew.dump_verbose_config(s)
<ide> files["config.out"] = { :content => s.string }
<ide> files["doctor.out"] = { :content => `brew doctor 2>&1` }
<add> unless f.core_formula?
<add> tap = <<-EOS.undent
<add> Formula: #{f.name}
<add> Tap: #{f.tap}
<add> Path: #{f.path}
<add> EOS
<add> files["tap.out"] = { :content => tap }
<add> end
<ide>
<ide> url = create_gist(files)
<ide> | 1 |
Python | Python | clarify the use of past in gpt2 and ctrl | d409aca32632718afbcd098de2bb11b9b71b7df1 | <ide><path>transformers/modeling_ctrl.py
<ide> def _init_weights(self, module):
<ide> **past**:
<ide> list of ``torch.FloatTensor`` (one for each layer):
<ide> that contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model
<del> (see `past` output below). Can be used to speed up sequential decoding.
<add> (see `past` output below). Can be used to speed up sequential decoding. The token ids which have their past given to this model
<add> should not be passed as input ids as they have already been computed.
<ide> **attention_mask**: (`optional`) ``torch.FloatTensor`` of shape ``(batch_size, sequence_length)``:
<ide> Mask to avoid performing attention on padding token indices.
<ide> Mask values selected in ``[0, 1]``:
<ide> class CTRLModel(CTRLPreTrainedModel):
<ide> **past**:
<ide> list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:
<ide> that contains pre-computed hidden-states (key and values in the attention blocks).
<del> Can be used (see `past` input) to speed up sequential decoding.
<add> Can be used (see `past` input) to speed up sequential decoding. The token ids which have their past given to this model
<add> should not be passed as input ids as they have already been computed.
<ide> **hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``)
<ide> list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings)
<ide> of shape ``(batch_size, sequence_length, hidden_size)``:
<ide> class CTRLLMHeadModel(CTRLPreTrainedModel):
<ide> **past**:
<ide> list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:
<ide> that contains pre-computed hidden-states (key and values in the attention blocks).
<del> Can be used (see `past` input) to speed up sequential decoding.
<add> Can be used (see `past` input) to speed up sequential decoding. The token ids which have their past given to this model
<add> should not be passed as input ids as they have already been computed.
<ide> **hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``)
<ide> list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings)
<ide> of shape ``(batch_size, sequence_length, hidden_size)``:
<ide><path>transformers/modeling_gpt2.py
<ide> def _init_weights(self, module):
<ide> **past**:
<ide> list of ``torch.FloatTensor`` (one for each layer):
<ide> that contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model
<del> (see `past` output below). Can be used to speed up sequential decoding.
<add> (see `past` output below). Can be used to speed up sequential decoding. The token ids which have their past given to this model
<add> should not be passed as input ids as they have already been computed.
<ide> **attention_mask**: (`optional`) ``torch.FloatTensor`` of shape ``(batch_size, sequence_length)``:
<ide> Mask to avoid performing attention on padding token indices.
<ide> Mask values selected in ``[0, 1]``:
<ide> class GPT2Model(GPT2PreTrainedModel):
<ide> **past**:
<ide> list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:
<ide> that contains pre-computed hidden-states (key and values in the attention blocks).
<del> Can be used (see `past` input) to speed up sequential decoding.
<add> Can be used (see `past` input) to speed up sequential decoding. The token ids which have their past given to this model
<add> should not be passed as input ids as they have already been computed.
<ide> **hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``)
<ide> list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings)
<ide> of shape ``(batch_size, sequence_length, hidden_size)``:
<ide> class GPT2LMHeadModel(GPT2PreTrainedModel):
<ide> **past**:
<ide> list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:
<ide> that contains pre-computed hidden-states (key and values in the attention blocks).
<del> Can be used (see `past` input) to speed up sequential decoding.
<add> Can be used (see `past` input) to speed up sequential decoding. The token ids which have their past given to this model
<add> should not be passed as input ids as they have already been computed.
<ide> **hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``)
<ide> list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings)
<ide> of shape ``(batch_size, sequence_length, hidden_size)``:
<ide> class GPT2DoubleHeadsModel(GPT2PreTrainedModel):
<ide> **past**:
<ide> list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:
<ide> that contains pre-computed hidden-states (key and values in the attention blocks).
<del> Can be used (see `past` input) to speed up sequential decoding.
<add> Can be used (see `past` input) to speed up sequential decoding. The token ids which have their past given to this model
<add> should not be passed as input ids as they have already been computed.
<ide> **hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``)
<ide> list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings)
<ide> of shape ``(batch_size, sequence_length, hidden_size)``: | 2 |
Go | Go | fix typo in error-message | 5f699a465dd428d6285080ca07cb4a6634952744 | <ide><path>daemon/create.go
<ide> func (daemon *Daemon) ContainerCreate(job *engine.Job) engine.Status {
<ide> config.MemorySwap = -1
<ide> }
<ide> if config.Memory > 0 && config.MemorySwap > 0 && config.MemorySwap < config.Memory {
<del> return job.Errorf("Minimum memoryswap limit should larger than memory limit, see usage.\n")
<add> return job.Errorf("Minimum memoryswap limit should be larger than memory limit, see usage.\n")
<ide> }
<ide>
<ide> var hostConfig *runconfig.HostConfig | 1 |
Python | Python | add a new bar class to display bar in curse ui | 63ab6b0e0ae88ee05c410c91f9014c4aa457e3e6 | <ide><path>glances/outputs/glances_bars.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>"""Manage bars for Glances output."""
<add>
<add># Import system lib
<add>from math import modf
<add>
<add># Global vars
<add>curses_bars = [" ", "▏", "▎", "▍", "▌", "▋", "▊", "▉", "█"]
<add>
<add>
<add>class Bar(object):
<add> """Manage bar (progression or status)
<add>
<add> import sys
<add> import time
<add> b = Bar(10)
<add> for p in range(0, 100):
<add> b.set_percent(p)
<add> print("\r%s" % b),
<add> time.sleep(0.1)
<add> sys.stdout.flush()
<add>
<add> """
<add>
<add> def __init__(self, size):
<add> # Bar size
<add> self.__size = size
<add> # Bar current percent
<add> self.__percent = 0
<add>
<add> def get_size(self):
<add> return self.__size
<add>
<add> def set_size(self, size):
<add> self.__size = size
<add> return self.__size
<add>
<add> def get_percent(self):
<add> return self.__percent
<add>
<add> def set_percent(self, percent):
<add> assert percent >= 0
<add> assert percent <= 100
<add> self.__percent = percent
<add> return self.__percent
<add>
<add> def __str__(self):
<add> """Return the bars"""
<add> frac, whole = modf(self.get_size() * self.get_percent() / 100.0)
<add> ret = curses_bars[8] * int(whole)
<add> if frac > 0:
<add> ret += curses_bars[int(frac * 8)]
<add> whole += 1
<add> ret += '_' * int(self.get_size() - whole)
<add> return ret | 1 |
Ruby | Ruby | implement more of @reitermarkus's comments | a2730c8618ebb512cf00318af6d4987dbee1efe5 | <ide><path>Library/Homebrew/test/cask/cli/upgrade_spec.rb
<ide> describe Hbc::CLI::Upgrade, :cask do
<ide> it_behaves_like "a command that handles invalid options"
<ide>
<del> shared_context "Proper Casks" do
<add> context "successful upgrade" do
<ide> let(:installed) {
<ide> [
<ide> "outdated/local-caffeine",
<ide>
<ide> allow_any_instance_of(described_class).to receive(:verbose?).and_return(true)
<ide> end
<del> end
<del>
<del> shared_context "Casks that will fail upon upgrade" do
<del> let(:installed) {
<del> [
<del> "outdated/bad-checksum",
<del> "outdated/will-fail-if-upgraded",
<del> ]
<del> }
<del>
<del> before(:example) do
<del> installed.each { |cask| Hbc::CLI::Install.run(cask) }
<ide>
<del> allow_any_instance_of(described_class).to receive(:verbose?).and_return(true)
<add> describe 'without --greedy it ignores the Casks with "version latest" or "auto_updates true"' do
<add> it "updates all the installed Casks when no token is provided" do
<add> local_caffeine = Hbc::CaskLoader.load("local-caffeine")
<add> local_caffeine_path = Hbc.appdir.join("Caffeine.app")
<add> local_transmission = Hbc::CaskLoader.load("local-transmission")
<add> local_transmission_path = Hbc.appdir.join("Transmission.app")
<add>
<add> expect(local_caffeine).to be_installed
<add> expect(local_caffeine_path).to be_a_directory
<add> expect(local_caffeine.versions).to include("1.2.2")
<add>
<add> expect(local_transmission).to be_installed
<add> expect(local_transmission_path).to be_a_directory
<add> expect(local_transmission.versions).to include("2.60")
<add>
<add> described_class.run
<add>
<add> expect(local_caffeine).to be_installed
<add> expect(local_caffeine_path).to be_a_directory
<add> expect(local_caffeine.versions).to include("1.2.3")
<add>
<add> expect(local_transmission).to be_installed
<add> expect(local_transmission_path).to be_a_directory
<add> expect(local_transmission.versions).to include("2.61")
<add> end
<add>
<add> it "updates only the Casks specified in the command line" do
<add> local_caffeine = Hbc::CaskLoader.load("local-caffeine")
<add> local_caffeine_path = Hbc.appdir.join("Caffeine.app")
<add> local_transmission = Hbc::CaskLoader.load("local-transmission")
<add> local_transmission_path = Hbc.appdir.join("Transmission.app")
<add>
<add> expect(local_caffeine).to be_installed
<add> expect(local_caffeine_path).to be_a_directory
<add> expect(local_caffeine.versions).to include("1.2.2")
<add>
<add> expect(local_transmission).to be_installed
<add> expect(local_transmission_path).to be_a_directory
<add> expect(local_transmission.versions).to include("2.60")
<add>
<add> described_class.run("local-caffeine")
<add>
<add> expect(local_caffeine).to be_installed
<add> expect(local_caffeine_path).to be_a_directory
<add> expect(local_caffeine.versions).to include("1.2.3")
<add>
<add> expect(local_transmission).to be_installed
<add> expect(local_transmission_path).to be_a_directory
<add> expect(local_transmission.versions).to include("2.60")
<add> end
<add>
<add> it 'updates "auto_updates" and "latest" Casks when their tokens are provided in the command line' do
<add> local_caffeine = Hbc::CaskLoader.load("local-caffeine")
<add> local_caffeine_path = Hbc.appdir.join("Caffeine.app")
<add> auto_updates = Hbc::CaskLoader.load("auto-updates")
<add> auto_updates_path = Hbc.appdir.join("MyFancyApp.app")
<add>
<add> expect(local_caffeine).to be_installed
<add> expect(local_caffeine_path).to be_a_directory
<add> expect(local_caffeine.versions).to include("1.2.2")
<add>
<add> expect(auto_updates).to be_installed
<add> expect(auto_updates_path).to be_a_directory
<add> expect(auto_updates.versions).to include("2.57")
<add>
<add> described_class.run("local-caffeine", "auto-updates")
<add>
<add> expect(local_caffeine).to be_installed
<add> expect(local_caffeine_path).to be_a_directory
<add> expect(local_caffeine.versions).to include("1.2.3")
<add>
<add> expect(auto_updates).to be_installed
<add> expect(auto_updates_path).to be_a_directory
<add> expect(auto_updates.versions).to include("2.61")
<add> end
<ide> end
<del> end
<del>
<del> describe 'without --greedy it ignores the Casks with "version latest" or "auto_updates true"' do
<del> include_context "Proper Casks"
<ide>
<del> it "and updates all the installed Casks when no token is provided" do
<del> local_caffeine = Hbc::CaskLoader.load("local-caffeine")
<del> local_caffeine_route = Hbc.appdir.join("Caffeine.app")
<del> local_transmission = Hbc::CaskLoader.load("local-transmission")
<del> local_transmission_route = Hbc.appdir.join("Transmission.app")
<add> describe "with --greedy it checks additional Casks" do
<add> it 'includes the Casks with "auto_updates true" or "version latest" with --greedy' do
<add> local_caffeine = Hbc::CaskLoader.load("local-caffeine")
<add> local_caffeine_path = Hbc.appdir.join("Caffeine.app")
<add> auto_updates = Hbc::CaskLoader.load("auto-updates")
<add> auto_updates_path = Hbc.appdir.join("MyFancyApp.app")
<add> local_transmission = Hbc::CaskLoader.load("local-transmission")
<add> local_transmission_path = Hbc.appdir.join("Transmission.app")
<ide>
<del> expect(local_caffeine).to be_installed
<del> expect(local_caffeine_route).to be_a_directory
<del> expect(local_caffeine.versions).to include("1.2.2")
<add> expect(local_caffeine).to be_installed
<add> expect(local_caffeine_path).to be_a_directory
<add> expect(local_caffeine.versions).to include("1.2.2")
<ide>
<del> expect(local_transmission).to be_installed
<del> expect(local_transmission_route).to be_a_directory
<del> expect(local_transmission.versions).to include("2.60")
<add> expect(auto_updates).to be_installed
<add> expect(auto_updates_path).to be_a_directory
<add> expect(auto_updates.versions).to include("2.57")
<ide>
<del> described_class.run
<add> expect(local_transmission).to be_installed
<add> expect(local_transmission_path).to be_a_directory
<add> expect(local_transmission.versions).to include("2.60")
<ide>
<del> expect(local_caffeine).to be_installed
<del> expect(local_caffeine_route).to be_a_directory
<del> expect(local_caffeine.versions).to include("1.2.3")
<add> described_class.run("--greedy")
<ide>
<del> expect(local_transmission).to be_installed
<del> expect(local_transmission_route).to be_a_directory
<del> expect(local_transmission.versions).to include("2.61")
<del> end
<del>
<del> it "and updates only the Casks specified in the command line" do
<del> local_caffeine = Hbc::CaskLoader.load("local-caffeine")
<del> local_caffeine_route = Hbc.appdir.join("Caffeine.app")
<del> local_transmission = Hbc::CaskLoader.load("local-transmission")
<del> local_transmission_route = Hbc.appdir.join("Transmission.app")
<add> expect(local_caffeine).to be_installed
<add> expect(local_caffeine_path).to be_a_directory
<add> expect(local_caffeine.versions).to include("1.2.3")
<ide>
<del> expect(local_caffeine).to be_installed
<del> expect(local_caffeine_route).to be_a_directory
<del> expect(local_caffeine.versions).to include("1.2.2")
<add> expect(auto_updates).to be_installed
<add> expect(auto_updates_path).to be_a_directory
<add> expect(auto_updates.versions).to include("2.61")
<ide>
<del> expect(local_transmission).to be_installed
<del> expect(local_transmission_route).to be_a_directory
<del> expect(local_transmission.versions).to include("2.60")
<add> expect(local_transmission).to be_installed
<add> expect(local_transmission_path).to be_a_directory
<add> expect(local_transmission.versions).to include("2.61")
<add> end
<ide>
<del> described_class.run("local-caffeine")
<add> it 'does not include the Casks with "auto_updates true" when the version did not change' do
<add> cask = Hbc::CaskLoader.load("auto-updates")
<add> cask_path = Hbc.appdir.join("MyFancyApp.app")
<ide>
<del> expect(local_caffeine).to be_installed
<del> expect(local_caffeine_route).to be_a_directory
<del> expect(local_caffeine.versions).to include("1.2.3")
<add> expect(cask).to be_installed
<add> expect(cask_path).to be_a_directory
<add> expect(cask.versions).to include("2.57")
<ide>
<del> expect(local_transmission).to be_installed
<del> expect(local_transmission_route).to be_a_directory
<del> expect(local_transmission.versions).to include("2.60")
<del> end
<add> described_class.run("auto-updates", "--greedy")
<ide>
<del> it 'updates "auto_updates" and "latest" Casks when their tokens are provided in the command line' do
<del> local_caffeine = Hbc::CaskLoader.load("local-caffeine")
<del> local_caffeine_route = Hbc.appdir.join("Caffeine.app")
<del> auto_updates = Hbc::CaskLoader.load("auto-updates")
<del> auto_updates_path = Hbc.appdir.join("MyFancyApp.app")
<add> expect(cask).to be_installed
<add> expect(cask_path).to be_a_directory
<add> expect(cask.versions).to include("2.61")
<ide>
<del> expect(local_caffeine).to be_installed
<del> expect(local_caffeine_route).to be_a_directory
<del> expect(local_caffeine.versions).to include("1.2.2")
<add> described_class.run("auto-updates", "--greedy")
<ide>
<del> expect(auto_updates).to be_installed
<del> expect(auto_updates_path).to be_a_directory
<del> expect(auto_updates.versions).to include("2.57")
<del>
<del> described_class.run("local-caffeine", "auto-updates")
<del>
<del> expect(local_caffeine).to be_installed
<del> expect(local_caffeine_route).to be_a_directory
<del> expect(local_caffeine.versions).to include("1.2.3")
<del>
<del> expect(auto_updates).to be_installed
<del> expect(auto_updates_path).to be_a_directory
<del> expect(auto_updates.versions).to include("2.61")
<add> expect(cask).to be_installed
<add> expect(cask_path).to be_a_directory
<add> expect(cask.versions).to include("2.61")
<add> end
<ide> end
<ide> end
<ide>
<del> describe "with --greedy it checks additional Casks" do
<del> include_context "Proper Casks"
<del>
<del> it 'includes the Casks with "auto_updates true" or "version latest" with --greedy' do
<del> local_caffeine = Hbc::CaskLoader.load("local-caffeine")
<del> local_caffeine_route = Hbc.appdir.join("Caffeine.app")
<del> auto_updates = Hbc::CaskLoader.load("auto-updates")
<del> auto_updates_path = Hbc.appdir.join("MyFancyApp.app")
<del> local_transmission = Hbc::CaskLoader.load("local-transmission")
<del> local_transmission_route = Hbc.appdir.join("Transmission.app")
<del>
<del> expect(local_caffeine).to be_installed
<del> expect(local_caffeine_route).to be_a_directory
<del> expect(local_caffeine.versions).to include("1.2.2")
<del>
<del> expect(auto_updates).to be_installed
<del> expect(auto_updates_path).to be_a_directory
<del> expect(auto_updates.versions).to include("2.57")
<del>
<del> expect(local_transmission).to be_installed
<del> expect(local_transmission_route).to be_a_directory
<del> expect(local_transmission.versions).to include("2.60")
<del>
<del> described_class.run("--greedy")
<del>
<del> expect(local_caffeine).to be_installed
<del> expect(local_caffeine_route).to be_a_directory
<del> expect(local_caffeine.versions).to include("1.2.3")
<del>
<del> expect(auto_updates).to be_installed
<del> expect(auto_updates_path).to be_a_directory
<del> expect(auto_updates.versions).to include("2.61")
<del>
<del> expect(local_transmission).to be_installed
<del> expect(local_transmission_route).to be_a_directory
<del> expect(local_transmission.versions).to include("2.61")
<del> end
<del>
<del> it 'does not include the Casks with "auto_updates true" when the version did not change' do
<del> auto_updates = Hbc::CaskLoader.load("auto-updates")
<del> auto_updates_path = Hbc.appdir.join("MyFancyApp.app")
<del>
<del> expect(auto_updates).to be_installed
<del> expect(auto_updates_path).to be_a_directory
<del> expect(auto_updates.versions).to include("2.57")
<del>
<del> described_class.run("auto-updates", "--greedy")
<del>
<del> expect(auto_updates).to be_installed
<del> expect(auto_updates_path).to be_a_directory
<del> expect(auto_updates.versions).to include("2.61")
<add> context "failed upgrade" do
<add> let(:installed) {
<add> [
<add> "outdated/bad-checksum",
<add> "outdated/will-fail-if-upgraded",
<add> ]
<add> }
<ide>
<del> described_class.run("auto-updates", "--greedy")
<add> before(:example) do
<add> installed.each { |cask| Hbc::CLI::Install.run(cask) }
<ide>
<del> expect(auto_updates).to be_installed
<del> expect(auto_updates_path).to be_a_directory
<del> expect(auto_updates.versions).to include("2.61")
<add> allow_any_instance_of(described_class).to receive(:verbose?).and_return(true)
<ide> end
<del> end
<del>
<del> describe "handles borked upgrades" do
<del> include_context "Casks that will fail upon upgrade"
<ide>
<ide> output_reverted = Regexp.new <<~EOS
<ide> Warning: Reverting upgrade for Cask .*
<ide> expect(will_fail_if_upgraded.staged_path).to_not exist
<ide> end
<ide>
<del> it "by not restoring the old Cask if the upgrade failed pre-install" do
<add> it "does not restore the old Cask if the upgrade failed pre-install" do
<ide> bad_checksum = Hbc::CaskLoader.load("bad-checksum")
<ide> bad_checksum_path = Hbc.appdir.join("Caffeine.app")
<ide> | 1 |
Python | Python | fix regression test #771 on 64 bits architecture | 87d85a0dbd8ec019a233ed921cd7cd2d9e6234c4 | <ide><path>numpy/core/tests/test_regression.py
<ide> def test_copy_detection_corner_case2(self, level=rlevel):
<ide> """Ticket #771: strides are not set correctly when reshaping 0-sized
<ide> arrays"""
<ide> b = np.indices((0,3,4)).T.reshape(-1,3)
<del> assert_equal(b.strides, (12, 4))
<add> assert_equal(b.strides, (3 * b.itemsize, b.itemsize))
<ide>
<ide> def test_object_array_refcounting(self, level=rlevel):
<ide> """Ticket #633""" | 1 |
Ruby | Ruby | raise error if unsupported charset for mysql | c4867b88f6eed16230a90077b82ad02293ea45b3 | <ide><path>activerecord/lib/active_record/tasks/mysql_database_tasks.rb
<ide> def create
<ide> end
<ide> establish_connection configuration
<ide> else
<del> $stderr.puts error.inspect
<del> $stderr.puts "Couldn't create database for #{configuration.inspect}, #{creation_options.inspect}"
<del> $stderr.puts "(If you set the charset manually, make sure you have a matching collation)" if configuration["encoding"]
<add> raise
<ide> end
<ide> end
<ide>
<ide><path>activerecord/test/cases/tasks/mysql_rake_test.rb
<ide> def test_connection_established_as_normal_user
<ide> ActiveRecord::Tasks::DatabaseTasks.create @configuration
<ide> end
<ide>
<del> def test_sends_output_to_stderr_when_other_errors
<add> def test_raises_error_when_other_errors
<ide> @error.stubs(:errno).returns(42)
<ide>
<del> $stderr.expects(:puts).at_least_once.returns(nil)
<del>
<del> ActiveRecord::Tasks::DatabaseTasks.create @configuration
<add> assert_raises(Mysql2::Error) do
<add> ActiveRecord::Tasks::DatabaseTasks.create @configuration
<add> end
<ide> end
<ide>
<ide> private | 2 |
PHP | PHP | fix regression caused by pr | 9b857d090f0301852ea2d200a12debde4a5172de | <ide><path>src/Core/ObjectRegistry.php
<ide> abstract class ObjectRegistry
<ide> */
<ide> public function load($objectName, $config = [])
<ide> {
<del> if (empty($config) && !isset($this->_loaded[$objectName])) {
<del> list(, $name) = pluginSplit($objectName);
<del> } else {
<add> if (is_array($config) && isset($config['className'])) {
<ide> $name = $objectName;
<add> $objectName = $config['className'];
<add> } else {
<add> list(, $name) = pluginSplit($objectName);
<ide> }
<ide>
<ide> $loaded = isset($this->_loaded[$name]);
<ide> public function load($objectName, $config = [])
<ide> return $this->_loaded[$name];
<ide> }
<ide>
<del> if (is_array($config) && isset($config['className'])) {
<del> $objectName = $config['className'];
<del> }
<ide> $className = $this->_resolveClassName($objectName);
<ide> if (!$className || (is_string($className) && !class_exists($className))) {
<ide> list($plugin, $objectName) = pluginSplit($objectName);
<ide><path>tests/TestCase/ORM/BehaviorRegistryTest.php
<ide> public function testLoadPlugin()
<ide> {
<ide> Plugin::load('TestPlugin');
<ide> $result = $this->Behaviors->load('TestPlugin.PersisterOne');
<del> $this->assertInstanceOf('TestPlugin\Model\Behavior\PersisterOneBehavior', $result);
<add>
<add> $expected = 'TestPlugin\Model\Behavior\PersisterOneBehavior';
<add> $this->assertInstanceOf($expected, $result);
<add> $this->assertInstanceOf($expected, $this->Behaviors->PersisterOne);
<add>
<add> $this->Behaviors->unload('PersisterOne');
<add>
<add> $result = $this->Behaviors->load('TestPlugin.PersisterOne', ['foo' => 'bar']);
<add> $this->assertInstanceOf($expected, $result);
<add> $this->assertInstanceOf($expected, $this->Behaviors->PersisterOne);
<ide> }
<ide>
<ide> /** | 2 |
Javascript | Javascript | convert `fontfaceobject` to an es6 class | caf90ff6eeb902ebb93848aea8c248928157ec24 | <ide><path>src/display/font_loader.js
<ide> if (typeof PDFJSDev === 'undefined' || !PDFJSDev.test('MOZCENTRAL || CHROME')) {
<ide> });
<ide> }
<ide>
<del>var IsEvalSupportedCached = {
<add>const IsEvalSupportedCached = {
<ide> get value() {
<ide> return shadow(this, 'value', isEvalSupported());
<ide> },
<ide> };
<ide>
<del>var FontFaceObject = (function FontFaceObjectClosure() {
<del> function FontFaceObject(translatedData, { isEvalSupported = true,
<del> disableFontFace = false,
<del> ignoreErrors = false,
<del> onUnsupportedFeature = null,
<del> fontRegistry = null, }) {
<add>class FontFaceObject {
<add> constructor(translatedData, { isEvalSupported = true,
<add> disableFontFace = false,
<add> ignoreErrors = false,
<add> onUnsupportedFeature = null,
<add> fontRegistry = null, }) {
<ide> this.compiledGlyphs = Object.create(null);
<ide> // importing translated data
<del> for (var i in translatedData) {
<add> for (let i in translatedData) {
<ide> this[i] = translatedData[i];
<ide> }
<ide> this.isEvalSupported = isEvalSupported !== false;
<ide> var FontFaceObject = (function FontFaceObjectClosure() {
<ide> this._onUnsupportedFeature = onUnsupportedFeature;
<ide> this.fontRegistry = fontRegistry;
<ide> }
<del> FontFaceObject.prototype = {
<del> createNativeFontFace: function FontFaceObject_createNativeFontFace() {
<del> if (typeof PDFJSDev !== 'undefined' && PDFJSDev.test('MOZCENTRAL')) {
<del> throw new Error('Not implemented: createNativeFontFace');
<del> }
<del>
<del> if (!this.data || this.disableFontFace) {
<del> return null;
<del> }
<ide>
<del> var nativeFontFace = new FontFace(this.loadedName, this.data, {});
<add> createNativeFontFace() {
<add> if (!this.data || this.disableFontFace) {
<add> return null;
<add> }
<add> const nativeFontFace = new FontFace(this.loadedName, this.data, {});
<ide>
<del> if (this.fontRegistry) {
<del> this.fontRegistry.registerFont(this);
<del> }
<del> return nativeFontFace;
<del> },
<add> if (this.fontRegistry) {
<add> this.fontRegistry.registerFont(this);
<add> }
<add> return nativeFontFace;
<add> }
<ide>
<del> createFontFaceRule: function FontFaceObject_createFontFaceRule() {
<del> if (!this.data || this.disableFontFace) {
<del> return null;
<del> }
<add> createFontFaceRule() {
<add> if (!this.data || this.disableFontFace) {
<add> return null;
<add> }
<add> const data = bytesToString(new Uint8Array(this.data));
<add> // Add the @font-face rule to the document.
<add> const url = `url(data:${this.mimetype};base64,${btoa(data)});`;
<add> const rule = `@font-face {font-family:"${this.loadedName}";src:${url}}`;
<ide>
<del> var data = bytesToString(new Uint8Array(this.data));
<del> var fontName = this.loadedName;
<add> if (this.fontRegistry) {
<add> this.fontRegistry.registerFont(this, url);
<add> }
<add> return rule;
<add> }
<ide>
<del> // Add the font-face rule to the document
<del> var url = ('url(data:' + this.mimetype + ';base64,' + btoa(data) + ');');
<del> var rule = '@font-face { font-family:"' + fontName + '";src:' + url + '}';
<add> getPathGenerator(objs, character) {
<add> if (this.compiledGlyphs[character] !== undefined) {
<add> return this.compiledGlyphs[character];
<add> }
<ide>
<del> if (this.fontRegistry) {
<del> this.fontRegistry.registerFont(this, url);
<add> let cmds, current;
<add> try {
<add> cmds = objs.get(this.loadedName + '_path_' + character);
<add> } catch (ex) {
<add> if (!this.ignoreErrors) {
<add> throw ex;
<ide> }
<del>
<del> return rule;
<del> },
<del>
<del> getPathGenerator(objs, character) {
<del> if (this.compiledGlyphs[character] !== undefined) {
<del> return this.compiledGlyphs[character];
<add> if (this._onUnsupportedFeature) {
<add> this._onUnsupportedFeature({ featureId: UNSUPPORTED_FEATURES.font, });
<ide> }
<add> warn(`getPathGenerator - ignoring character: "${ex}".`);
<ide>
<del> let cmds, current;
<del> try {
<del> cmds = objs.get(this.loadedName + '_path_' + character);
<del> } catch (ex) {
<del> if (!this.ignoreErrors) {
<del> throw ex;
<del> }
<del> if (this._onUnsupportedFeature) {
<del> this._onUnsupportedFeature({ featureId: UNSUPPORTED_FEATURES.font, });
<del> }
<del> warn(`getPathGenerator - ignoring character: "${ex}".`);
<add> return this.compiledGlyphs[character] = function(c, size) {
<add> // No-op function, to allow rendering to continue.
<add> };
<add> }
<ide>
<del> return this.compiledGlyphs[character] = function(c, size) {
<del> // No-op function, to allow rendering to continue.
<del> };
<del> }
<add> // If we can, compile cmds into JS for MAXIMUM SPEED...
<add> if (this.isEvalSupported && IsEvalSupportedCached.value) {
<add> let args, js = '';
<add> for (let i = 0, ii = cmds.length; i < ii; i++) {
<add> current = cmds[i];
<ide>
<del> // If we can, compile cmds into JS for MAXIMUM SPEED...
<del> if (this.isEvalSupported && IsEvalSupportedCached.value) {
<del> let args, js = '';
<del> for (let i = 0, ii = cmds.length; i < ii; i++) {
<del> current = cmds[i];
<del>
<del> if (current.args !== undefined) {
<del> args = current.args.join(',');
<del> } else {
<del> args = '';
<del> }
<del> js += 'c.' + current.cmd + '(' + args + ');\n';
<add> if (current.args !== undefined) {
<add> args = current.args.join(',');
<add> } else {
<add> args = '';
<ide> }
<del> // eslint-disable-next-line no-new-func
<del> return this.compiledGlyphs[character] = new Function('c', 'size', js);
<add> js += 'c.' + current.cmd + '(' + args + ');\n';
<ide> }
<del> // ... but fall back on using Function.prototype.apply() if we're
<del> // blocked from using eval() for whatever reason (like CSP policies).
<del> return this.compiledGlyphs[character] = function(c, size) {
<del> for (let i = 0, ii = cmds.length; i < ii; i++) {
<del> current = cmds[i];
<del>
<del> if (current.cmd === 'scale') {
<del> current.args = [size, -size];
<del> }
<del> c[current.cmd].apply(c, current.args);
<add> // eslint-disable-next-line no-new-func
<add> return this.compiledGlyphs[character] = new Function('c', 'size', js);
<add> }
<add> // ... but fall back on using Function.prototype.apply() if we're
<add> // blocked from using eval() for whatever reason (like CSP policies).
<add> return this.compiledGlyphs[character] = function(c, size) {
<add> for (let i = 0, ii = cmds.length; i < ii; i++) {
<add> current = cmds[i];
<add>
<add> if (current.cmd === 'scale') {
<add> current.args = [size, -size];
<ide> }
<del> };
<del> },
<del> };
<del>
<del> return FontFaceObject;
<del>})();
<add> c[current.cmd].apply(c, current.args);
<add> }
<add> };
<add> }
<add>}
<ide>
<ide> export {
<ide> FontFaceObject, | 1 |
Text | Text | update changelog.md for 1.6.0-beta.1 | b7163c5970ebde48d304cb301ae112337427ca47 | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<del>### Ember 1.5.0-beta.4 (March 10, 2014)
<del>
<add>### Ember 1.6.0-beta.1 (March 31, 2014)
<add>
<add>* [BUGFIX] Add `which` attribute to event triggered by keyEvent test helper.
<add>* [Performance] Improve cache lookup throughput.
<add>* [FEATURE ember-routing-add-model-option]
<add>* [FEATURE ember-runtime-test-friendly-promises]
<add>* [FEATURE ember-metal-computed-empty-array]
<add>
<add>### Ember 1.5.0 (March 29, 2014)
<add>
<add>* [BUGFIX beta] Move reduceComputed instanceMetas into object's meta.
<add>* [BUGFIX beta] Total invalidation of arrayComputed by non-array dependencies should be synchronous.
<add>* [BUGFIX] run.bind keeps the arguments from the callback.
<add>* [BUGFIX] Do not attach new listeners on each setupForTesting call.
<add>* [BUGFIX] Ember.copy now supports Date.
<add>* [BUGFIX] Add `which` attribute to event triggered by test helper.
<add>* [BUGFIX beta] The `each` helper checks that the metamorph tags have the same parent.
<ide> * Allow Ember Inspector to access models with custom resolver.
<ide> * [BUGFIX] Allow components with layoutName specified by parent class to specify templateName.
<ide> * [BUGFIX] Don't raise error when a destroyed array is assigned to ArrayProxy.
<ide> * [BUGFIX] Use better ajax events for ember-testing counters.
<ide> * [BUGFIX] Move AJAX listeners into Ember.setupForTesting.
<del>
<del>### Ember 1.5.0-beta.3 (March 1, 2014)
<del>
<ide> * [BUGFIX] PromiseProxyMixin reset isFulfilled and isRejected.
<ide> * Use documentElement instead of body for ember-extension detection.
<ide> * Many documentation updates.
<del>
<del>### Ember 1.5.0-beta.2 (February 23, 2014)
<del>
<ide> * [SECURITY] Ensure that `ember-routing-auto-location` cannot be forced to redirect to another domain.
<ide> * [BUGFIX beta] Handle ES6 transpiler errors.
<ide> * [BUGFIX beta] Ensure namespaces are cleaned up.
<ide> * Many documentation updates.
<del>
<del>### Ember 1.5.0-beta.1 (February 14, 2014)
<del>
<ide> * [FEATURE ember-handlebars-log-primitives]
<ide> * [FEATURE ember-testing-routing-helpers]
<ide> * [FEATURE ember-testing-triggerEvent-helper] | 1 |
Javascript | Javascript | fix typo in panresponder documentation | f7aeefa521d74d7caba3ed4909780baa6f7bf83c | <ide><path>Libraries/vendor/react/browser/eventPlugins/PanResponder.js
<ide> var currentCentroidY = TouchHistoryMath.currentCentroidY;
<ide> * // The accumulated gesture distance since becoming responder is
<ide> * // gestureState.d{x,y}
<ide> * },
<del> * onResponderTerminationRequest: (evt, gestureState) => true,
<add> * onPanResponderTerminationRequest: (evt, gestureState) => true,
<ide> * onPanResponderRelease: (evt, gestureState) => {
<ide> * // The user has released all touches while this view is the
<ide> * // responder. This typically means a gesture has succeeded | 1 |
Java | Java | change sseevent#mimetype to sseevent#mediatype | 3fe87ee22551ea8f0176de84b5cd9cae488aa9db | <ide><path>spring-web-reactive/src/main/java/org/springframework/http/codec/SseEventEncoder.java
<ide> import org.springframework.core.io.buffer.DataBuffer;
<ide> import org.springframework.core.io.buffer.DataBufferFactory;
<ide> import org.springframework.core.io.buffer.FlushingDataBuffer;
<add>import org.springframework.http.MediaType;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.util.MimeType;
<ide> import org.springframework.web.reactive.sse.SseEvent;
<ide> public Flux<DataBuffer> encode(Publisher<?> inputStream, DataBufferFactory buffe
<ide>
<ide> Object data = event.getData();
<ide> Flux<DataBuffer> dataBuffer = Flux.empty();
<del> MimeType mimeType = (event.getMimeType() == null ?
<del> new MimeType("*") : event.getMimeType());
<add> MediaType mediaType = (event.getMediaType() == null ?
<add> MediaType.ALL : event.getMediaType());
<ide> if (data != null) {
<ide> sb.append("data:");
<ide> if (data instanceof String) {
<ide> public Flux<DataBuffer> encode(Publisher<?> inputStream, DataBufferFactory buffe
<ide> else {
<ide> Optional<Encoder<?>> encoder = dataEncoders
<ide> .stream()
<del> .filter(e -> e.canEncode(ResolvableType.forClass(data.getClass()), mimeType))
<add> .filter(e -> e.canEncode(ResolvableType.forClass(data.getClass()), mediaType))
<ide> .findFirst();
<ide>
<ide> if (encoder.isPresent()) {
<ide> dataBuffer = ((Encoder<Object>)encoder.get())
<ide> .encode(Mono.just(data), bufferFactory,
<del> ResolvableType.forClass(data.getClass()), mimeType)
<add> ResolvableType.forClass(data.getClass()), mediaType)
<ide> .concatWith(encodeString("\n", bufferFactory));
<ide> }
<ide> else {
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/sse/SseEvent.java
<ide>
<ide> package org.springframework.web.reactive.sse;
<ide>
<add>import org.springframework.http.MediaType;
<ide> import org.springframework.http.codec.SseEventEncoder;
<del>import org.springframework.util.MimeType;
<ide>
<ide> /**
<ide> * Represent a Server-Sent Event.
<ide> *
<ide> * @author Sebastien Deleuze
<ide> * @see SseEventEncoder
<del> * @see <a href="https://www.w3.org/TR/eventsource/">Server-Sent Events W3C recommandation</a>
<add> * @see <a href="https://www.w3.org/TR/eventsource/">Server-Sent Events W3C recommendation</a>
<ide> */
<ide> public class SseEvent {
<ide>
<ide> public class SseEvent {
<ide>
<ide> private Object data;
<ide>
<del> private MimeType mimeType;
<add> private MediaType mediaType;
<ide>
<ide> private Long reconnectTime;
<ide>
<ide> public SseEvent(Object data) {
<ide> /**
<ide> * Create an instance with the provided {@code data} and {@code mediaType}.
<ide> */
<del> public SseEvent(Object data, MimeType mimeType) {
<add> public SseEvent(Object data, MediaType mediaType) {
<ide> this.data = data;
<del> this.mimeType = mimeType;
<add> this.mediaType = mediaType;
<ide> }
<ide>
<ide> /**
<ide> public String getName() {
<ide> * - Turn multiline line {@code String} to multiple {@code data} fields
<ide> * - Serialize other {@code Object} as JSON
<ide> *
<del> * @see #setMimeType(MimeType)
<add> * @see #setMediaType(MediaType)
<ide> */
<ide> public void setData(Object data) {
<ide> this.data = data;
<ide> public Object getData() {
<ide> }
<ide>
<ide> /**
<del> * Set the {@link MimeType} used to serialize the {@code data}.
<add> * Set the {@link MediaType} used to serialize the {@code data}.
<ide> * {@link SseEventEncoder} should be configured with the relevant encoder to be
<ide> * able to serialize it.
<ide> */
<del> public void setMimeType(MimeType mimeType) {
<del> this.mimeType = mimeType;
<add> public void setMediaType(MediaType mediaType) {
<add> this.mediaType = mediaType;
<ide> }
<ide>
<ide> /**
<del> * @see #setMimeType(MimeType)
<add> * @see #setMediaType(MediaType)
<ide> */
<del> public MimeType getMimeType() {
<del> return mimeType;
<add> public MediaType getMediaType() {
<add> return this.mediaType;
<ide> }
<ide>
<ide> /** | 2 |
Javascript | Javascript | set 'readable' flag on readable streams | 53fa66d9f79b4ba593f071334d58fda766fa5be3 | <ide><path>lib/_stream_readable.js
<ide> function Readable(options) {
<ide> return new Readable(options);
<ide>
<ide> this._readableState = new ReadableState(options, this);
<add>
<add> // legacy
<add> this.readable = true;
<add>
<ide> Stream.apply(this);
<ide> }
<ide> | 1 |
Go | Go | add api version to `docker version` | b246fc33ae4f05b5084fed8fc9f1034e36d87d78 | <ide><path>api/client/commands.go
<ide> func (cli *DockerCli) CmdVersion(args ...string) error {
<ide> if dockerversion.VERSION != "" {
<ide> fmt.Fprintf(cli.out, "Client version: %s\n", dockerversion.VERSION)
<ide> }
<add> fmt.Fprintf(cli.out, "Client API version: %s\n", api.APIVERSION)
<ide> fmt.Fprintf(cli.out, "Go version (client): %s\n", goruntime.Version())
<ide> if dockerversion.GITCOMMIT != "" {
<ide> fmt.Fprintf(cli.out, "Git commit (client): %s\n", dockerversion.GITCOMMIT)
<ide> func (cli *DockerCli) CmdVersion(args ...string) error {
<ide> }
<ide> out.Close()
<ide> fmt.Fprintf(cli.out, "Server version: %s\n", remoteVersion.Get("Version"))
<add> if apiVersion := remoteVersion.Get("ApiVersion"); apiVersion != "" {
<add> fmt.Fprintf(cli.out, "Server API version: %s\n", apiVersion)
<add> }
<ide> fmt.Fprintf(cli.out, "Git commit (server): %s\n", remoteVersion.Get("GitCommit"))
<ide> fmt.Fprintf(cli.out, "Go version (server): %s\n", remoteVersion.Get("GoVersion"))
<ide> release := utils.GetReleaseVersion()
<ide><path>integration-cli/docker_cli_version_test.go
<ide> func TestVersionEnsureSucceeds(t *testing.T) {
<ide> t.Fatal("failed to execute docker version")
<ide> }
<ide>
<del> stringsToCheck := []string{"Client version:", "Go version (client):", "Git commit (client):", "Server version:", "Git commit (server):", "Go version (server):", "Last stable version:"}
<add> stringsToCheck := []string{
<add> "Client version:",
<add> "Client API version:",
<add> "Go version (client):",
<add> "Git commit (client):",
<add> "Server version:",
<add> "Server API version:",
<add> "Git commit (server):",
<add> "Go version (server):",
<add> "Last stable version:",
<add> }
<ide>
<ide> for _, linePrefix := range stringsToCheck {
<ide> if !strings.Contains(out, linePrefix) {
<ide><path>server/server.go
<ide> package server
<ide> import (
<ide> "encoding/json"
<ide> "fmt"
<add> "github.com/dotcloud/docker/api"
<ide> "github.com/dotcloud/docker/archive"
<ide> "github.com/dotcloud/docker/daemonconfig"
<ide> "github.com/dotcloud/docker/dockerversion"
<ide> func (srv *Server) DockerInfo(job *engine.Job) engine.Status {
<ide> func (srv *Server) DockerVersion(job *engine.Job) engine.Status {
<ide> v := &engine.Env{}
<ide> v.Set("Version", dockerversion.VERSION)
<add> v.Set("ApiVersion", api.APIVERSION)
<ide> v.Set("GitCommit", dockerversion.GITCOMMIT)
<ide> v.Set("GoVersion", goruntime.Version())
<ide> v.Set("Os", goruntime.GOOS) | 3 |
Javascript | Javascript | return null when no initfragment is required | 55b73a54afd2cb7c78b55e7102c6b24409c0d391 | <ide><path>lib/dependencies/CachedConstDependency.js
<ide> CachedConstDependency.Template = class CachedConstDependencyTemplate {
<ide> source.replace(dep.range[0], dep.range[1] - 1, dep.identifier);
<ide> }
<ide>
<del> getInitFragments(dep, source, runtime) {
<add> getInitFragments(dependency, source, runtimeTemplate, dependencyTemplates) {
<ide> return [
<ide> new InitFragment(
<del> `var ${dep.identifier} = ${dep.expression};\n`,
<add> `var ${dependency.identifier} = ${dependency.expression};\n`,
<ide> 1,
<del> `const ${dep.identifier}`
<add> `const ${dependency.identifier}`
<ide> )
<ide> ];
<ide> }
<ide><path>lib/dependencies/HarmonyExportImportedSpecifierDependency.js
<ide> HarmonyExportImportedSpecifierDependency.Template = class HarmonyExportImportedS
<ide> new InitFragment(this.getContent(dependency), dependency.sourceOrder)
<ide> );
<ide> } else {
<del> return [];
<add> return null;
<ide> }
<ide> }
<ide>
<ide><path>lib/dependencies/HarmonyImportDependency.js
<ide> HarmonyImportDependency.Template = class HarmonyImportDependencyTemplate extends
<ide>
<ide> const key = dependency._module || dependency.request;
<ide> if (!key || sourceInfo.emittedImports.get(key)) {
<del> return [];
<add> return null;
<ide> }
<ide>
<ide> sourceInfo.emittedImports.set(key, true);
<ide><path>lib/dependencies/HarmonyImportSideEffectDependency.js
<ide> class HarmonyImportSideEffectDependency extends HarmonyImportDependency {
<ide> HarmonyImportSideEffectDependency.Template = class HarmonyImportSideEffectDependencyTemplate extends HarmonyImportDependency.Template {
<ide> getInitFragments(dependency, source, runtimeTemplate, dependencyTemplates) {
<ide> if (dependency._module && dependency._module.factoryMeta.sideEffectFree) {
<del> return [];
<add> return null;
<ide> } else {
<ide> return super.getInitFragments(
<ide> dependency,
<ide><path>lib/optimize/ConcatenatedModule.js
<ide> class HarmonyImportSpecifierDependencyConcatenatedTemplate extends DependencyTem
<ide> this.modulesMap = modulesMap;
<ide> }
<ide>
<del> getInitFragments(dep, source, runtimeTemplate, dependencyTemplates) {
<del> const module = dep._module;
<add> getInitFragments(dependency, source, runtimeTemplate, dependencyTemplates) {
<add> const module = dependency._module;
<ide> const info = this.modulesMap.get(module);
<ide> if (!info) {
<ide> return this.originalTemplate.getInitFragments(
<del> dep,
<add> dependency,
<ide> source,
<ide> runtimeTemplate,
<ide> dependencyTemplates
<ide> class HarmonyImportSideEffectDependencyConcatenatedTemplate extends DependencyTe
<ide> this.modulesMap = modulesMap;
<ide> }
<ide>
<del> getInitFragments(dep, source, runtime, dependencyTemplates) {
<del> const module = dep._module;
<add> getInitFragments(dependency, source, runtimeTemplate, dependencyTemplates) {
<add> const module = dependency._module;
<ide> const info = this.modulesMap.get(module);
<ide> if (!info) {
<ide> return this.originalTemplate.getInitFragments(
<del> dep,
<add> dependency,
<ide> source,
<del> runtime,
<add> runtimeTemplate,
<ide> dependencyTemplates
<ide> );
<ide> } else {
<ide> class HarmonyExportSpecifierDependencyConcatenatedTemplate extends DependencyTem
<ide> this.rootModule = rootModule;
<ide> }
<ide>
<del> getInitFragments(dep, source, runtime, dependencyTemplates) {
<del> if (dep.originModule === this.rootModule) {
<add> getInitFragments(dependency, source, runtimeTemplate, dependencyTemplates) {
<add> if (dependency.originModule === this.rootModule) {
<ide> return this.originalTemplate.getInitFragments(
<del> dep,
<add> dependency,
<ide> source,
<del> runtime,
<add> runtimeTemplate,
<ide> dependencyTemplates
<ide> );
<ide> } else {
<ide> class HarmonyExportImportedSpecifierDependencyConcatenatedTemplate extends Depen
<ide> });
<ide> }
<ide>
<del> getInitFragments(dep, source, runtime, dependencyTemplates) {
<del> const module = dep._module;
<add> getInitFragments(dependency, source, runtimeTemplate, dependencyTemplates) {
<add> const module = dependency._module;
<ide> const info = this.modulesMap.get(module);
<ide> if (!info) {
<ide> return this.originalTemplate.getInitFragments(
<del> dep,
<add> dependency,
<ide> source,
<del> runtime,
<add> runtimeTemplate,
<ide> dependencyTemplates
<ide> );
<ide> } else { | 5 |
Javascript | Javascript | allow accessing siblings by ref | 2bc2b52eaa7f541dd3ad30ede41e2a8dba74d9c8 | <ide><path>src/core/ReactComponent.js
<ide> var ReactComponent = {
<ide> */
<ide> isOwnedBy: function(owner) {
<ide> return this.props[OWNER] === owner;
<add> },
<add>
<add> /**
<add> * Gets another component, that shares the same owner as this one, by ref.
<add> *
<add> * @param {string} ref of a sibling Component.
<add> * @return {?ReactComponent} the actual sibling Component.
<add> * @final
<add> * @internal
<add> */
<add> getSiblingByRef: function(ref) {
<add> var owner = this.props[OWNER];
<add> if (!owner || !owner.refs) {
<add> return null;
<add> }
<add> return owner.refs[ref];
<ide> }
<ide>
<ide> } | 1 |
Go | Go | fix container unmount networkmounts | 04f99a6ca8232e43169b9a0706e435c551c798a3 | <ide><path>daemon/container_linux.go
<ide> func (container *Container) DisableLink(name string) {
<ide> }
<ide>
<ide> func (container *Container) UnmountVolumes(forceSyscall bool) error {
<del> for _, m := range container.MountPoints {
<del> dest, err := container.GetResourcePath(m.Destination)
<add> var volumeMounts []mountPoint
<add>
<add> for _, mntPoint := range container.MountPoints {
<add> dest, err := container.GetResourcePath(mntPoint.Destination)
<add> if err != nil {
<add> return err
<add> }
<add>
<add> volumeMounts = append(volumeMounts, mountPoint{Destination: dest, Volume: mntPoint.Volume})
<add> }
<add>
<add> for _, mnt := range container.networkMounts() {
<add> dest, err := container.GetResourcePath(mnt.Destination)
<ide> if err != nil {
<ide> return err
<ide> }
<ide>
<add> volumeMounts = append(volumeMounts, mountPoint{Destination: dest})
<add> }
<add>
<add> for _, volumeMount := range volumeMounts {
<ide> if forceSyscall {
<del> syscall.Unmount(dest, 0)
<add> syscall.Unmount(volumeMount.Destination, 0)
<ide> }
<ide>
<del> if m.Volume != nil {
<del> if err := m.Volume.Unmount(); err != nil {
<add> if volumeMount.Volume != nil {
<add> if err := volumeMount.Volume.Unmount(); err != nil {
<ide> return err
<ide> }
<ide> }
<ide> }
<add>
<ide> return nil
<ide> }
<ide><path>daemon/volumes.go
<ide> import (
<ide> "path/filepath"
<ide> "strings"
<ide>
<del> "github.com/docker/docker/daemon/execdriver"
<ide> "github.com/docker/docker/pkg/chrootarchive"
<ide> "github.com/docker/docker/runconfig"
<ide> "github.com/docker/docker/volume"
<ide> func validMountMode(mode string) bool {
<ide> return validModes[mode]
<ide> }
<ide>
<del>func (container *Container) specialMounts() []execdriver.Mount {
<del> var mounts []execdriver.Mount
<del> if container.ResolvConfPath != "" {
<del> mounts = append(mounts, execdriver.Mount{Source: container.ResolvConfPath, Destination: "/etc/resolv.conf", Writable: !container.hostConfig.ReadonlyRootfs, Private: true})
<del> }
<del> if container.HostnamePath != "" {
<del> mounts = append(mounts, execdriver.Mount{Source: container.HostnamePath, Destination: "/etc/hostname", Writable: !container.hostConfig.ReadonlyRootfs, Private: true})
<del> }
<del> if container.HostsPath != "" {
<del> mounts = append(mounts, execdriver.Mount{Source: container.HostsPath, Destination: "/etc/hosts", Writable: !container.hostConfig.ReadonlyRootfs, Private: true})
<del> }
<del> return mounts
<del>}
<del>
<ide> func copyExistingContents(source, destination string) error {
<ide> volList, err := ioutil.ReadDir(source)
<ide> if err != nil {
<ide><path>integration-cli/docker_cli_cp_test.go
<ide> func (s *DockerSuite) TestCpNameHasColon(c *check.C) {
<ide> c.Fatalf("Wrong content in copied file %q, should be %q", content, "lololol\n")
<ide> }
<ide> }
<add>
<add>func (s *DockerSuite) TestCopyAndRestart(c *check.C) {
<add> expectedMsg := "hello"
<add> out, err := exec.Command(dockerBinary, "run", "-d", "busybox", "echo", expectedMsg).CombinedOutput()
<add> if err != nil {
<add> c.Fatal(string(out), err)
<add> }
<add> id := strings.TrimSpace(string(out))
<add>
<add> if out, err = exec.Command(dockerBinary, "wait", id).CombinedOutput(); err != nil {
<add> c.Fatalf("unable to wait for container: %s", err)
<add> }
<add>
<add> status := strings.TrimSpace(string(out))
<add> if status != "0" {
<add> c.Fatalf("container exited with status %s", status)
<add> }
<add>
<add> tmpDir, err := ioutil.TempDir("", "test-docker-restart-after-copy-")
<add> if err != nil {
<add> c.Fatalf("unable to make temporary directory: %s", err)
<add> }
<add> defer os.RemoveAll(tmpDir)
<add>
<add> if _, err = exec.Command(dockerBinary, "cp", fmt.Sprintf("%s:/etc/issue", id), tmpDir).CombinedOutput(); err != nil {
<add> c.Fatalf("unable to copy from busybox container: %s", err)
<add> }
<add>
<add> if out, err = exec.Command(dockerBinary, "start", "-a", id).CombinedOutput(); err != nil {
<add> c.Fatalf("unable to start busybox container after copy: %s - %s", err, out)
<add> }
<add>
<add> msg := strings.TrimSpace(string(out))
<add> if msg != expectedMsg {
<add> c.Fatalf("expected %q but got %q", expectedMsg, msg)
<add> }
<add>} | 3 |
Javascript | Javascript | add tests for parts of `/settings` page | 625b12c4f267210ca82e399c575c4bd594d6ab67 | <ide><path>cypress/integration/settings/settings.js
<add>/* global cy expect */
<add>
<add>describe('Settings', () => {
<add> beforeEach(() => {
<add> cy.visit('/');
<add> cy.contains("Get started (it's free)").click({ force: true });
<add> cy.visit('/settings');
<add> });
<add>
<add> describe('The `Sign me out of freeCodeCamp` button works properly', () => {
<add> it('Should get rendered properly', () => {
<add> cy.contains('Sign me out of freeCodeCamp')
<add> .should('be.visible')
<add> // We are checking for classes here to check for proper styling
<add> // This will be replaces with Percy in the future
<add> .should('have.class', 'btn-invert btn btn-lg btn-primary btn-block');
<add> });
<add>
<add> it('Should take to the landing page when clicked', () => {
<add> cy.contains('Sign me out of freeCodeCamp').click({ force: true });
<add> cy.location().should(loc => {
<add> expect(loc.pathname).to.eq('/');
<add> });
<add> });
<add> });
<add>});
<ide><path>cypress/integration/settings/username-change.js
<add>/* global cy */
<add>
<add>describe('Username input field', () => {
<add> beforeEach(() => {
<add> cy.visit('/');
<add> cy.contains("Get started (it's free)").click({ force: true });
<add> cy.visit('/settings');
<add>
<add> // Setting aliases here
<add> cy.get('input[name=username-settings]').as('usernameInput');
<add> cy.get('form#usernameSettings').as('usernameForm');
<add> });
<add>
<add> it('Should be possible to type', () => {
<add> cy.get('@usernameInput')
<add> .clear({ force: true })
<add> .type('twaha', { force: true })
<add> .should('have.attr', 'value', 'twaha');
<add> });
<add>
<add> it('Should show message when validating name', () => {
<add> cy.get('@usernameInput')
<add> .clear({ force: true })
<add> .type('twaha', { force: true });
<add>
<add> cy.contains('Validating username...')
<add> .should('have.attr', 'role', 'alert')
<add> // We are checking for classes here to check for proper styling
<add> // This will be replaced with Percy in the future
<add> .should('have.class', 'alert alert-info');
<add> });
<add>
<add> it('Should show username is available if it is', () => {
<add> cy.get('@usernameInput')
<add> .clear({ force: true })
<add> .type('brad', { force: true });
<add>
<add> cy.contains('Username is available.')
<add> .should('be.visible')
<add> .should('have.attr', 'role', 'alert')
<add> // We are checking for classes here to check for proper styling
<add> // This will be replaced with Percy in the future
<add> .should('have.class', 'alert alert-success');
<add> });
<add>
<add> it('Should info message if username is available', () => {
<add> cy.get('@usernameInput')
<add> .clear({ force: true })
<add> .type('mrugesh', { force: true });
<add>
<add> cy.contains(
<add> 'Please note, changing your username will also change ' +
<add> 'the URL to your profile and your certifications.'
<add> )
<add> .should('be.visible')
<add> .should('have.attr', 'role', 'alert')
<add> // We are checking for classes here to check for proper styling
<add> // This will be replaced with Percy in the future
<add> .should('have.class', 'alert alert-info');
<add> });
<add>
<add> // eslint-disable-next-line
<add> it('Should be able to click the `Save` button if username is avalable', () => {
<add> cy.get('@usernameInput')
<add> .clear({ force: true })
<add> .type('oliver', { force: true });
<add>
<add> cy.get('@usernameForm').within(() => {
<add> cy.contains('Save').should('not.be.disabled');
<add> });
<add> });
<add>
<add> it('Should show username is unavailable if it is', () => {
<add> cy.get('@usernameInput')
<add> .clear({ force: true })
<add> .type('twaha', { force: true });
<add>
<add> cy.contains('Username not available.')
<add> .should('be.visible')
<add> .should('have.attr', 'role', 'alert')
<add> // We are checking for classes here to check for proper styling
<add> // This will be replaced with Percy in the future
<add> .should('have.class', 'alert alert-warning');
<add> });
<add>
<add> // eslint-disable-next-line
<add> it('Should not be possible to click the `Save` button if username is unavailable', () => {
<add> cy.get('@usernameInput')
<add> .clear({ force: true })
<add> .type('twaha', { force: true });
<add>
<add> cy.contains('Username is available.').should('not.be.visible');
<add> cy.contains('Username not available.').should('not.be.visible');
<add> cy.contains(
<add> 'Please note, changing your username will also change ' +
<add> 'the URL to your profile and your certifications.'
<add> ).should('not.be.visible');
<add>
<add> cy.get('@usernameForm')
<add> .contains('Save')
<add> .should('be.disabled');
<add> });
<add>
<add> it('Should not show anything if user types their current name', () => {
<add> cy.get('@usernameInput')
<add> .clear({ force: true })
<add> .type('developmentuser', { force: true });
<add>
<add> cy.get('@usernameForm')
<add> .contains('Save')
<add> .should('be.disabled');
<add> });
<add>
<add> // eslint-disable-next-line max-len
<add> it('Should not be possible to click the `Save` button if user types their current name', () => {
<add> cy.get('@usernameInput')
<add> .clear({ force: true })
<add> .type('developmentuser', { force: true });
<add>
<add> cy.get('@usernameForm')
<add> .contains('Save')
<add> .should('be.disabled');
<add> });
<add>
<add> it('Should show warning if username includes invalid character', () => {
<add> cy.get('@usernameInput')
<add> .clear({ force: true })
<add> .type('Quincy Larson', { force: true });
<add>
<add> cy.contains('Username contains invalid characters.')
<add> .should('be.visible')
<add> .should('have.attr', 'role', 'alert')
<add> // We are checking for classes here to check for proper styling
<add> // This will be replaced with Percy in the future
<add> .should('have.class', 'alert alert-danger');
<add> });
<add>
<add> // eslint-disable-next-line max-len
<add> it('Should not be able to click the `Save` button if username includes invalid character', () => {
<add> cy.get('@usernameInput')
<add> .clear({ force: true })
<add> .type('Quincy Larson', { force: true });
<add>
<add> cy.get('@usernameForm')
<add> .contains('Save')
<add> .should('be.disabled');
<add> });
<add>
<add> it('Should change username if `Save` button is clicked', () => {
<add> cy.get('@usernameInput')
<add> .clear({ force: true })
<add> .type('quincy', { force: true });
<add>
<add> cy.contains('Username is available.');
<add>
<add> cy.get('@usernameForm')
<add> .contains('Save')
<add> .click({ force: true });
<add> cy.contains('Account Settings for quincy').should('be.visible');
<add>
<add> cy.resetUsername();
<add> });
<add>
<add> it('Should show flash message showing username has been updated', () => {
<add> cy.get('@usernameInput')
<add> .clear({ force: true })
<add> .type('nhcarrigan', { force: true });
<add> cy.contains('Username is available.');
<add> cy.get('@usernameInput').type('{enter}', { force: true, release: false });
<add>
<add> cy.contains('We have updated your username to nhcarrigan')
<add> .should('be.visible')
<add> // We are checking for classes here to check for proper styling
<add> // This will be replaced with Percy in the future
<add> .should(
<add> 'have.class',
<add> 'flash-message alert alert-success alert-dismissable'
<add> );
<add>
<add> cy.resetUsername();
<add> });
<add>
<add> it('Should be able to close the shown flash message', () => {
<add> cy.get('@usernameInput')
<add> .clear({ force: true })
<add> .type('bjorno', { force: true });
<add> cy.contains('Username is available.');
<add> cy.get('@usernameInput').type('{enter}', { force: true, release: false });
<add>
<add> cy.contains('We have updated your username to bjorno').within(() => {
<add> cy.get('button').click();
<add> });
<add>
<add> cy.contains('We have updated your username to bjorno').should(
<add> 'not.be.visible'
<add> );
<add>
<add> cy.resetUsername();
<add> });
<add>
<add> it('Should change username if enter is pressed', () => {
<add> cy.get('@usernameInput')
<add> .clear({ force: true })
<add> .type('symbol', { force: true });
<add> cy.contains('Username is available.');
<add>
<add> cy.get('@usernameInput').type('{enter}', { force: true, release: false });
<add>
<add> cy.contains('Account Settings for symbol').should('be.visible');
<add>
<add> cy.resetUsername();
<add> });
<add>});
<ide><path>cypress/support/commands.js
<ide> Cypress.Commands.add('login', () => {
<ide> cy.visit('/');
<ide> cy.contains("Get started (it's free)").click({ force: true });
<ide> });
<add>
<add>Cypress.Commands.add('resetUsername', () => {
<add> cy.login();
<add> cy.visit('/settings');
<add>
<add> cy.get('@usernameInput')
<add> .clear({ force: true })
<add> .type('developmentuser', { force: true });
<add>
<add> cy.contains('Username is available.');
<add>
<add> cy.get('@usernameInput').type('{enter}', { force: true, release: false });
<add>
<add> cy.contains('Account Settings for developmentuser').should('be.visible');
<add>});
<ide><path>tools/scripts/seed/seedAuthUser.js
<ide> const envVariables = process.argv;
<ide> const log = debug('fcc:tools:seedLocalAuthUser');
<ide> const { MONGOHQ_URL } = process.env;
<ide>
<del>const defaulUserImage = require('../../../config/misc').defaulUserImage;
<add>const defaultUserImage = require('../../../config/misc').defaultUserImage;
<ide>
<ide> function handleError(err, client) {
<ide> if (err) {
<ide> function handleError(err, client) {
<ide> }
<ide> }
<ide>
<del>MongoClient.connect(MONGOHQ_URL, { useNewUrlParser: true }, function(
<del> err,
<del> client
<del>) {
<add>MongoClient.connect(MONGOHQ_URL, { useNewUrlParser: true }, (err, client) => {
<ide> handleError(err, client);
<ide>
<ide> log('Connected successfully to mongo');
<ide>
<ide> const db = client.db('freecodecamp');
<ide> const user = db.collection('user');
<ide>
<del> user.deleteOne({ _id: ObjectId('5bd30e0f1caf6ac3ddddddb5') }, err => {
<del> handleError(err, client);
<add> user.deleteMany(
<add> {
<add> _id: {
<add> $in: [
<add> ObjectId('5bd30e0f1caf6ac3ddddddb5'),
<add> ObjectId('5bd30e0f1caf6ac3ddddddb9')
<add> ]
<add> }
<add> },
<add> err => {
<add> handleError(err, client);
<ide>
<del> try {
<del> user.insertOne({
<del> _id: ObjectId('5bd30e0f1caf6ac3ddddddb5'),
<del> email: 'foo@bar.com',
<del> emailVerified: true,
<del> progressTimestamps: [],
<del> isBanned: false,
<del> isCheater: false,
<del> username: 'developmentuser',
<del> about: '',
<del> name: 'Development User',
<del> location: '',
<del> picture: defaulUserImage,
<del> acceptedPrivacyTerms: true,
<del> sendQuincyEmail: false,
<del> currentChallengeId: '',
<del> isHonest: false,
<del> isFrontEndCert: false,
<del> isDataVisCert: false,
<del> isBackEndCert: false,
<del> isFullStackCert: false,
<del> isRespWebDesignCert: false,
<del> is2018DataVisCert: false,
<del> isFrontEndLibsCert: false,
<del> isJsAlgoDataStructCert: false,
<del> isApisMicroservicesCert: false,
<del> isInfosecQaCert: false,
<del> isQaCertV7: false,
<del> isInfosecCertV7: false,
<del> is2018FullStackCert: false,
<del> isSciCompPyCertV7: false,
<del> isDataAnalysisPyCertV7: false,
<del> isMachineLearningPyCertV7: false,
<del> completedChallenges: [],
<del> portfolio: [],
<del> yearsTopContributor: envVariables.includes('--top-contributor')
<del> ? ['2017', '2018', '2019']
<del> : [],
<del> rand: 0.6126749173148205,
<del> theme: 'default',
<del> profileUI: {
<del> isLocked: true,
<del> showAbout: false,
<del> showCerts: false,
<del> showDonation: false,
<del> showHeatMap: false,
<del> showLocation: false,
<del> showName: false,
<del> showPoints: false,
<del> showPortfolio: false,
<del> showTimeLine: false
<del> },
<del> badges: {
<del> coreTeam: []
<del> },
<del> isDonating: envVariables.includes('--donor'),
<del> emailAuthLinkTTL: null,
<del> emailVerifyTTL: null
<del> });
<del> } catch (e) {
<del> handleError(e, client);
<del> } finally {
<del> log('local auth user seed complete');
<del> client.close();
<add> try {
<add> user.insertOne({
<add> _id: ObjectId('5bd30e0f1caf6ac3ddddddb5'),
<add> email: 'foo@bar.com',
<add> emailVerified: true,
<add> progressTimestamps: [],
<add> isBanned: false,
<add> isCheater: false,
<add> username: 'developmentuser',
<add> about: '',
<add> name: 'Development User',
<add> location: '',
<add> picture: defaultUserImage,
<add> acceptedPrivacyTerms: true,
<add> sendQuincyEmail: false,
<add> currentChallengeId: '',
<add> isHonest: false,
<add> isFrontEndCert: false,
<add> isDataVisCert: false,
<add> isBackEndCert: false,
<add> isFullStackCert: false,
<add> isRespWebDesignCert: false,
<add> is2018DataVisCert: false,
<add> isFrontEndLibsCert: false,
<add> isJsAlgoDataStructCert: false,
<add> isApisMicroservicesCert: false,
<add> isInfosecQaCert: false,
<add> isQaCertV7: false,
<add> isInfosecCertV7: false,
<add> is2018FullStackCert: false,
<add> isSciCompPyCertV7: false,
<add> isDataAnalysisPyCertV7: false,
<add> isMachineLearningPyCertV7: false,
<add> completedChallenges: [],
<add> portfolio: [],
<add> yearsTopContributor: envVariables.includes('--top-contributor')
<add> ? ['2017', '2018', '2019']
<add> : [],
<add> rand: 0.6126749173148205,
<add> theme: 'default',
<add> profileUI: {
<add> isLocked: true,
<add> showAbout: false,
<add> showCerts: false,
<add> showDonation: false,
<add> showHeatMap: false,
<add> showLocation: false,
<add> showName: false,
<add> showPoints: false,
<add> showPortfolio: false,
<add> showTimeLine: false
<add> },
<add> badges: {
<add> coreTeam: []
<add> },
<add> isDonating: envVariables.includes('--donor'),
<add> emailAuthLinkTTL: null,
<add> emailVerifyTTL: null
<add> });
<add>
<add> user.insertOne({
<add> _id: ObjectId('5bd30e0f1caf6ac3ddddddb9'),
<add> email: 'bar@bar.com',
<add> emailVerified: true,
<add> progressTimestamps: [],
<add> isBanned: false,
<add> isCheater: false,
<add> username: 'twaha',
<add> about: '',
<add> name: 'Development User',
<add> location: '',
<add> picture: defaultUserImage,
<add> acceptedPrivacyTerms: true,
<add> sendQuincyEmail: false,
<add> currentChallengeId: '',
<add> isHonest: false,
<add> isFrontEndCert: false,
<add> isDataVisCert: false,
<add> isBackEndCert: false,
<add> isFullStackCert: false,
<add> isRespWebDesignCert: false,
<add> is2018DataVisCert: false,
<add> isFrontEndLibsCert: false,
<add> isJsAlgoDataStructCert: false,
<add> isApisMicroservicesCert: false,
<add> isInfosecQaCert: false,
<add> isQaCertV7: false,
<add> isInfosecCertV7: false,
<add> is2018FullStackCert: false,
<add> isSciCompPyCertV7: false,
<add> isDataAnalysisPyCertV7: false,
<add> isMachineLearningPyCertV7: false,
<add> completedChallenges: [],
<add> portfolio: [],
<add> yearsTopContributor: [],
<add> rand: 0.6126749173148205,
<add> theme: 'default',
<add> profileUI: {
<add> isLocked: true,
<add> showAbout: false,
<add> showCerts: false,
<add> showDonation: false,
<add> showHeatMap: false,
<add> showLocation: false,
<add> showName: false,
<add> showPoints: false,
<add> showPortfolio: false,
<add> showTimeLine: false
<add> },
<add> badges: {
<add> coreTeam: []
<add> },
<add> isDonating: false,
<add> emailAuthLinkTTL: null,
<add> emailVerifyTTL: null
<add> });
<add> } catch (e) {
<add> handleError(e, client);
<add> } finally {
<add> log('local auth user seed complete');
<add> client.close();
<add> }
<ide> }
<del> });
<add> );
<ide> }); | 4 |
Javascript | Javascript | hide legacy full stack cert on portfolio | 08e968079ce23bee98784f39a420f5a72aef9da8 | <ide><path>client/src/components/profile/components/Certifications.js
<ide> const mapStateToProps = (state, props) =>
<ide> }
<ide> ],
<ide> legacyCerts: [
<del> {
<del> show: isFullStackCert,
<del> title: 'Full Stack Certification',
<del> showURL: 'legacy-full-stack'
<del> },
<ide> {
<ide> show: isFrontEndCert,
<ide> title: 'Front End Certification', | 1 |
PHP | PHP | add escape false to paginationhelper | 51b141543cb446f39d50b1764527177feb32281a | <ide><path>src/View/Helper/PaginatorHelper.php
<ide> public function sort($key, $title = null, array $options = [])
<ide> /**
<ide> * Merges passed URL options with current pagination state to generate a pagination URL.
<ide> *
<add> * ### Options:
<add> *
<add> * - `escape`: If false, the URL will be returned unescaped, do only use if it is manually
<add> * escaped afterwards before being displayed.
<add> * - `fullBase`: If true, the full base URL will be prepended to the result
<add> *
<ide> * @param array $options Pagination/URL options array
<ide> * @param string|null $model Which model to paginate on
<del> * @param bool $full If true, the full base URL will be prepended to the result
<add> * @param bool $full If true, the full base URL will be prepended to the result @deprecated Use $options and `fullBase`.
<ide> * @return string By default, returns a full pagination URL string for use in non-standard contexts (i.e. JavaScript)
<ide> * @link http://book.cakephp.org/3.0/en/views/helpers/paginator.html#generating-pagination-urls
<ide> */
<ide> public function generateUrl(array $options = [], $model = null, $full = false)
<ide> {
<ide> $paging = $this->params($model);
<ide> $paging += ['page' => null, 'sort' => null, 'direction' => null, 'limit' => null];
<add>
<add> $defaults = [
<add> 'escape' => true,
<add> 'fullBase' => $full
<add> ];
<add> $options += $defaults;
<add>
<ide> $url = [
<ide> 'page' => $paging['page'],
<ide> 'limit' => $paging['limit'],
<ide> public function generateUrl(array $options = [], $model = null, $full = false)
<ide> }
<ide> }
<ide>
<del> return $this->Url->build($url, $full);
<add> return $this->Url->build($url, $options);
<ide> }
<ide>
<ide> /** | 1 |
PHP | PHP | add more test coverage for commandrunner | a7f9372c2ae135c7003807d4634bf58d689e73e1 | <ide><path>src/Console/CommandRunner.php
<ide> namespace Cake\Console;
<ide>
<ide> use Cake\Console\CommandCollection;
<add>use Cake\Console\ConsoleIo;
<add>use Cake\Console\Exception\StopException;
<add>use Cake\Console\Shell;
<ide> use Cake\Http\BaseApplication;
<ide> use RuntimeException;
<ide>
<ide> public function __construct(BaseApplication $app, $root = 'cake')
<ide> * Run the command contained in $argv.
<ide> *
<ide> * @param array $argv The arguments from the CLI environment.
<add> * @param \Cake\Console\ConsoleIo $io The ConsoleIo instance. Used primarily for testing.
<ide> * @return int The exit code of the command.
<ide> * @throws \RuntimeException
<ide> */
<del> public function run(array $argv)
<add> public function run(array $argv, ConsoleIo $io = null)
<ide> {
<ide> $this->app->bootstrap();
<ide>
<ide> public function run(array $argv)
<ide> "Unknown root command{$command}. Was expecting `{$this->root}`."
<ide> );
<ide> }
<del> // Remove the root command
<add> $io = $io ?: new ConsoleIo();
<add>
<add> // Remove the root executable segment
<ide> array_shift($argv);
<ide>
<del> $shell = $this->getShell($commands, $argv);
<add> $shell = $this->getShell($io, $commands, $argv);
<add>
<add> // Remove the command name segment
<add> array_shift($argv);
<add> try {
<add> $shell->initialize();
<add> $result = $shell->runCommand($argv, true);
<add> } catch (StopException $e) {
<add> return $e->getCode();
<add> }
<add>
<add> if ($result === null || $result === true) {
<add> return Shell::CODE_SUCCESS;
<add> }
<add> if (is_int($result)) {
<add> return $result;
<add> }
<add>
<add> return Shell::CODE_ERROR;
<ide> }
<ide>
<ide> /**
<ide> * Get the shell instance for the argv list.
<ide> *
<ide> * @return \Cake\Console\Shell
<ide> */
<del> protected function getShell(CommandCollection $commands, array $argv)
<add> protected function getShell(ConsoleIo $io, CommandCollection $commands, array $argv)
<ide> {
<ide> $command = array_shift($argv);
<ide> if (!$commands->has($command)) {
<ide> protected function getShell(CommandCollection $commands, array $argv)
<ide> " Run `{$this->root} --help` to get the list of valid commands."
<ide> );
<ide> }
<add> $classOrInstance = $commands->get($command);
<add> if (is_string($classOrInstance)) {
<add> return new $classOrInstance($io);
<add> }
<add> return $classOrInstance;
<ide> }
<ide> }
<ide><path>tests/TestCase/Console/CommandRunnerTest.php
<ide>
<ide> use Cake\Console\CommandCollection;
<ide> use Cake\Console\CommandRunner;
<add>use Cake\Console\ConsoleIo;
<add>use Cake\Console\Shell;
<ide> use Cake\Core\Configure;
<ide> use Cake\Http\BaseApplication;
<ide> use Cake\TestSuite\TestCase;
<add>use Cake\TestSuite\Stub\ConsoleOutput;
<ide>
<ide> /**
<ide> * Test case for the CommandCollection
<ide> public function testRunVersionShortOption()
<ide> {
<ide> $this->markTestIncomplete();
<ide> }
<add>
<add> /**
<add> * Test running a valid command
<add> *
<add> * @return void
<add> */
<add> public function testRunValidCommand()
<add> {
<add> $app = $this->getMockBuilder(BaseApplication::class)
<add> ->setMethods(['middleware', 'bootstrap'])
<add> ->setConstructorArgs([$this->config])
<add> ->getMock();
<add>
<add> $output = new ConsoleOutput();
<add>
<add> $runner = new CommandRunner($app, 'cake');
<add> $result = $runner->run(['cake', 'routes'], $this->getMockIo($output));
<add> $this->assertSame(Shell::CODE_SUCCESS, $result);
<add>
<add> $contents = implode("\n", $output->messages());
<add> $this->assertContains('URI template', $contents);
<add> $this->assertContains('Welcome to CakePHP', $contents);
<add> }
<add>
<add> /**
<add> * Test running a valid raising an error
<add> *
<add> * @return void
<add> */
<add> public function testRunValidCommandWithAbort()
<add> {
<add> $app = $this->getMockBuilder(BaseApplication::class)
<add> ->setMethods(['middleware', 'bootstrap', 'console'])
<add> ->setConstructorArgs([$this->config])
<add> ->getMock();
<add>
<add> $commands = new CommandCollection(['failure' => 'TestApp\Shell\SampleShell']);
<add> $app->method('console')->will($this->returnValue($commands));
<add>
<add> $output = new ConsoleOutput();
<add>
<add> $runner = new CommandRunner($app, 'cake');
<add> $result = $runner->run(['cake', 'failure', 'with_abort'], $this->getMockIo($output));
<add> $this->assertSame(Shell::CODE_ERROR, $result);
<add> }
<add>
<add> /**
<add> * Test returning a non-zero value
<add> *
<add> * @return void
<add> */
<add> public function testRunValidCommandReturnInteger()
<add> {
<add> $app = $this->getMockBuilder(BaseApplication::class)
<add> ->setMethods(['middleware', 'bootstrap', 'console'])
<add> ->setConstructorArgs([$this->config])
<add> ->getMock();
<add>
<add> $commands = new CommandCollection(['failure' => 'TestApp\Shell\SampleShell']);
<add> $app->method('console')->will($this->returnValue($commands));
<add>
<add> $output = new ConsoleOutput();
<add>
<add> $runner = new CommandRunner($app, 'cake');
<add> $result = $runner->run(['cake', 'failure', 'returnValue'], $this->getMockIo($output));
<add> $this->assertSame(99, $result);
<add> }
<add>
<add> protected function getMockIo($output)
<add> {
<add> $io = $this->getMockBuilder(ConsoleIo::class)
<add> ->setConstructorArgs([$output, $output, null, null])
<add> ->setMethods(['in'])
<add> ->getMock();
<add>
<add> return $io;
<add> }
<ide> }
<ide><path>tests/test_app/TestApp/Shell/SampleShell.php
<ide> public function derp()
<ide> {
<ide> $this->out('This is the example method called from TestPlugin.SampleShell');
<ide> }
<add>
<add> public function withAbort()
<add> {
<add> $this->abort('Bad things');
<add> }
<add>
<add> public function returnValue()
<add> {
<add> return 99;
<add> }
<ide> } | 3 |
Text | Text | use branch 4.x instead of master | 9d3743887df6f8fa8ab3c023541d68b6c93b0251 | <ide><path>README.md
<ide> <a href="LICENSE" target="_blank">
<ide> <img alt="Software License" src="https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square">
<ide> </a>
<del> <img alt="Build Status" src="https://github.com/cakephp/cakephp/actions/workflows/ci.yml/badge.svg?branch=master">
<del> <a href="https://codecov.io/gh/cakephp/cakephp/branch/master" target="_blank">
<add> <img alt="Build Status" src="https://github.com/cakephp/cakephp/actions/workflows/ci.yml/badge.svg?branch=4.x">
<add> <a href="https://codecov.io/gh/cakephp/cakephp/branch/4.x" target="_blank">
<ide> <img alt="Coverage Status" src="https://img.shields.io/codecov/c/github/cakephp/cakephp?style=flat-square">
<ide> </a>
<ide> <a href="https://squizlabs.github.io/PHP_CodeSniffer/analysis/cakephp/cakephp/" target="_blank"> | 1 |
Ruby | Ruby | activate env extensions | 809a52a6a3e8b0899aa2697f767b8dcc22210bd8 | <ide><path>Library/Homebrew/cmd/--env.rb
<ide> def __env
<ide> if superenv?
<ide> ENV.deps = ARGV.formulae.map(&:name) unless ARGV.named.empty?
<ide> end
<add>
<ide> ENV.setup_build_environment
<ide> ENV.universal_binary if ARGV.build_universal?
<ide> if $stdout.tty?
<ide><path>Library/Homebrew/cmd/audit.rb
<ide> def audit
<ide> formula_count = 0
<ide> problem_count = 0
<ide>
<add> ENV.activate_extensions!
<ide> ENV.setup_build_environment
<ide>
<ide> ff = if ARGV.named.empty? | 2 |
Javascript | Javascript | fix unterminated statements | 66eeb3bca39b491110ef2143336b3e75eae5f396 | <ide><path>resources/js/app.js
<ide> window.Vue = require('vue');
<ide> * Eg. ./components/ExampleComponent.vue -> <example-component></example-component>
<ide> */
<ide>
<del>// const files = require.context('./', true, /\.vue$/i)
<del>// files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default))
<add>// const files = require.context('./', true, /\.vue$/i);
<add>// files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default));
<ide>
<ide> Vue.component('example-component', require('./components/ExampleComponent.vue').default);
<ide> | 1 |
Ruby | Ruby | reduce string allocations in read/write_attribute | ffc9ed3d3b59dd76cfe3fc1ff6913bd1d2aaf462 | <ide><path>activerecord/lib/active_record/attribute_methods/read.rb
<ide> def #{temp_method_name}
<ide> # it has been typecast (for example, "2004-12-12" in a date column is cast
<ide> # to a date object, like Date.new(2004, 12, 12)).
<ide> def read_attribute(attr_name, &block)
<del> name = if self.class.attribute_alias?(attr_name)
<del> self.class.attribute_alias(attr_name).to_s
<del> else
<del> attr_name.to_s
<add> name = attr_name.to_s
<add> if self.class.attribute_alias?(name)
<add> name = self.class.attribute_alias(name)
<ide> end
<ide>
<ide> primary_key = self.class.primary_key
<ide><path>activerecord/lib/active_record/attribute_methods/write.rb
<ide> def #{temp_method_name}(value)
<ide> # specified +value+. Empty strings for Integer and Float columns are
<ide> # turned into +nil+.
<ide> def write_attribute(attr_name, value)
<del> name = if self.class.attribute_alias?(attr_name)
<del> self.class.attribute_alias(attr_name).to_s
<del> else
<del> attr_name.to_s
<add> name = attr_name.to_s
<add> if self.class.attribute_alias?(name)
<add> name = self.class.attribute_alias(name)
<ide> end
<ide>
<ide> primary_key = self.class.primary_key | 2 |
Text | Text | make minor adjustments | 38a39143d2d5dbff0421ca3448ada2ebe21144e4 | <ide><path>BUILDING.md
<ide> When modifying only the JS layer in `lib`, it is possible to externally load it
<ide> without modifying the executable:
<ide>
<ide> ```console
<del>$ ./configure --node-builtin-modules-path $(pwd)
<add>$ ./configure --node-builtin-modules-path "$(pwd)"
<ide> ```
<ide>
<ide> The resulting binary won't include any JS files and will try to load them from
<ide><path>doc/api/async_context.md
<ide> class DBQuery extends AsyncResource {
<ide> }
<ide> ```
<ide>
<del>### Static method: `AsyncResource.bind(fn[, type, [thisArg]])`
<add>### Static method: `AsyncResource.bind(fn[, type[, thisArg]])`
<ide>
<ide> <!-- YAML
<ide> added:
<ide><path>doc/api/buffer.md
<ide> added:
<ide>
<ide> The total size of the `Blob` in bytes.
<ide>
<del>### `blob.slice([start, [end, [type]]])`
<add>### `blob.slice([start[, end[, type]]])`
<ide>
<ide> <!-- YAML
<ide> added:
<ide><path>doc/api/corepack.md
<ide> successfully retrieved.
<ide> When running outside of an existing project (for example when running
<ide> `yarn init`), Corepack will by default use predefined versions roughly
<ide> corresponding to the latest stable releases from each tool. Those versions can
<del>be overriden by running the [`corepack prepare`][] command along with the
<add>be overridden by running the [`corepack prepare`][] command along with the
<ide> package manager version you wish to set:
<ide>
<ide> ```bash
<ide><path>doc/api/crypto.md
<ide> is currently in use. Setting to true requires a FIPS build of Node.js.
<ide> This property is deprecated. Please use `crypto.setFips()` and
<ide> `crypto.getFips()` instead.
<ide>
<del>### `crypto.checkPrime(candidate[, options, [callback]])`
<add>### `crypto.checkPrime(candidate[, options[, callback]])`
<ide>
<ide> <!-- YAML
<ide> added: v15.8.0
<ide><path>doc/api/fs.md
<ide> changes:
<ide> added: v10.0.0
<ide> -->
<ide>
<del>* Returns: {Promise} Fufills with `undefined` upon success.
<add>* Returns: {Promise} Fulfills with `undefined` upon success.
<ide>
<ide> Request that all data for the open file descriptor is flushed to the storage
<ide> device. The specific implementation is operating system and device specific.
<ide><path>doc/api/https.md
<ide> const options = {
<ide> return err;
<ide> }
<ide>
<del> // Pin the public key, similar to HPKP pin-sha25 pinning
<add> // Pin the public key, similar to HPKP pin-sha256 pinning
<ide> const pubkey256 = 'pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU=';
<ide> if (sha256(cert.pubkey) !== pubkey256) {
<ide> const msg = 'Certificate verification error: ' +
<ide><path>doc/api/stream.md
<ide> result from the calculation on the previous element. It returns a promise for
<ide> the final value of the reduction.
<ide>
<ide> The reducer function iterates the stream element-by-element which means that
<del>there is no `concurrency` parameter or parallism. To perform a `reduce`
<add>there is no `concurrency` parameter or parallelism. To perform a `reduce`
<ide> concurrently, it can be chained to the [`readable.map`][] method.
<ide>
<ide> If no `initial` value is supplied the first chunk of the stream is used as the
<ide><path>doc/contributing/collaborator-guide.md
<ide> files also qualify as affecting the `node` binary:
<ide> * `configure`
<ide> * `configure.py`
<ide> * `Makefile`
<del>* `vcbuilt.bat`
<add>* `vcbuild.bat`
<ide>
<ide> </details>
<ide>
<ide><path>doc/contributing/commit-queue.md
<ide> work for more complex pull requests. These are the currently known limitations
<ide> of the commit queue:
<ide>
<ide> 1. All commits in a pull request must either be following commit message
<del> guidelines or be a valid [`fixup!`](https://git-scm.com/docs/git-commit#Documentation/git-commit.txt---fixupltcommitgt)
<add> guidelines or be a valid [`fixup!`](https://git-scm.com/docs/git-commit#Documentation/git-commit.txt---fixupamendrewordltcommitgt)
<ide> commit that will be correctly handled by the [`--autosquash`](https://git-scm.com/docs/git-rebase#Documentation/git-rebase.txt---autosquash)
<ide> option
<ide> 2. A CI must've ran and succeeded since the last change on the PR
<ide><path>doc/contributing/maintaining-shared-library-support.md
<ide> Currently, shared library support has only been tested on:
<ide>
<ide> ## Building with shared library option
<ide>
<del>On non-Windows platoforms, Node.js is built with the shared library
<add>On non-Windows platforms, Node.js is built with the shared library
<ide> option by adding `--shared` to the configure step. On Windows
<del>platofrms Node.js is built with the shared library option by
<add>platforms Node.js is built with the shared library option by
<ide> adding `dll` to the vcbuild command line.
<ide>
<ide> Once built there are two key components:
<ide><path>doc/contributing/writing-and-running-benchmarks.md
<ide> Supported options keys are:
<ide> [git-for-windows]: https://git-scm.com/download/win
<ide> [nghttp2.org]: https://nghttp2.org
<ide> [node-benchmark-compare]: https://github.com/targos/node-benchmark-compare
<del>[t-test]: https://en.wikipedia.org/wiki/Student%27s_t-test#Equal_or_unequal_sample_sizes.2C_unequal_variances
<add>[t-test]: https://en.wikipedia.org/wiki/Student%27s_t-test#Equal_or_unequal_sample_sizes%2C_unequal_variances_%28sX1_%3E_2sX2_or_sX2_%3E_2sX1%29
<ide> [wrk]: https://github.com/wg/wrk | 12 |
Go | Go | fix fedora tty with apparmor | 6104f9f9495678549ef8fc5aa716a3cc893add8f | <ide><path>graph.go
<ide> func setupInitLayer(initLayer string) error {
<ide> "/etc/resolv.conf": "file",
<ide> "/etc/hosts": "file",
<ide> "/etc/hostname": "file",
<add> "/dev/console": "file",
<ide> // "var/run": "dir",
<ide> // "var/lock": "dir",
<ide> } { | 1 |
Text | Text | fix heading level in errors.md | 6562942461e6307480bb0873447708ecc996e490 | <ide><path>doc/api/errors.md
<ide> added properties.
<ide>
<ide> ### Class: SystemError
<ide>
<del>### error.info
<add>#### error.info
<ide>
<ide> `SystemError` instances may have an additional `info` property whose
<ide> value is an object with additional details about the error conditions. | 1 |
PHP | PHP | change method to only return true/false | 69e63b11a4ebe4edab1b55708ea13bc204c8e173 | <ide><path>lib/Cake/Test/Case/View/Helper/FormHelperTest.php
<ide> class Contact extends CakeTestModel {
<ide> 'imrequired' => array('rule' => array('between', 5, 30), 'allowEmpty' => false),
<ide> 'imrequiredonupdate' => array('notEmpty' => array('rule' => 'alphaNumeric', 'on' => 'update')),
<ide> 'imrequiredoncreate' => array('required' => array('rule' => 'alphaNumeric', 'on' => 'create')),
<del> 'imrequiredonboth' => array('required' => array('rule' => 'alphaNumeric')),
<add> 'imrequiredonboth' => array(
<add> 'required' => array('rule' => 'alphaNumeric', 'allowEmpty' => true),
<add> 'check' => array('rule' => 'alphaNumeric')
<add> ),
<ide> 'string_required' => 'notEmpty',
<ide> 'imalsorequired' => array('rule' => 'alphaNumeric', 'allowEmpty' => false),
<ide> 'imrequiredtoo' => array('rule' => 'notEmpty'),
<ide> 'required_one' => array('required' => array('rule' => array('notEmpty'))),
<ide> 'imnotrequired' => array('required' => false, 'rule' => 'alphaNumeric', 'allowEmpty' => true),
<ide> 'imalsonotrequired' => array(
<del> 'alpha' => array('rule' => 'alphaNumeric','allowEmpty' => true),
<del> 'between' => array('rule' => array('between', 5, 30)),
<add> 'alpha' => array('rule' => 'alphaNumeric', 'allowEmpty' => true),
<add> 'between' => array('rule' => array('between', 5, 30), 'allowEmpty' => true),
<ide> ),
<ide> 'imnotrequiredeither' => array('required' => true, 'rule' => array('between', 5, 30), 'allowEmpty' => true),
<ide> );
<ide><path>lib/Cake/View/Helper/FormHelper.php
<ide> protected function _isRequiredField($validateProperties) {
<ide> }
<ide>
<ide> foreach ($validateProperties as $rule => $validateProp) {
<del> $parse = $this->_parseRuleRequired($validateProp);
<del> if ($parse === false) {
<del> return false;
<del> } elseif ($parse == null){
<add> $isRequired = $this->_isRequiredRule($validateProp);
<add> if ($isRequired === false) {
<ide> continue;
<ide> }
<ide> $rule = isset($validateProp['rule']) ? $validateProp['rule'] : false;
<ide> protected function _isRequiredField($validateProperties) {
<ide> return $required;
<ide> }
<ide>
<add>/**
<add> * Checks if the field is required by the 'on' key in validation properties.
<add> * If no 'on' key is present in validation props, this method returns true.
<add> *
<add> * @param array $validateProp
<add> * @return mixed. Boolean for required
<add> */
<add> protected function _isRequiredRule($validateProp) {
<add> if (isset($validateProp['on'])) {
<add> if (
<add> ($validateProp['on'] == 'create' && $this->requestType != 'post') ||
<add> ($validateProp['on'] == 'update' && $this->requestType != 'put')
<add> ) {
<add> return false;
<add> }
<add> }
<add> if (
<add> isset($validateProp['allowEmpty']) &&
<add> $validateProp['allowEmpty'] === true
<add> ) {
<add> return false;
<add> }
<add> if (isset($validateProp['required']) && empty($validateProp['required'])) {
<add> return false;
<add> }
<add> return true;
<add> }
<add>
<ide> /**
<ide> * Returns false if given form field described by the current entity has no errors.
<ide> * Otherwise it returns the validation message
<ide> protected function _initInputField($field, $options = array()) {
<ide> return $result;
<ide> }
<ide>
<del>/**
<del> * Checks if the field is required by the 'on' key in validation properties.
<del> * If no 'on' key is present in validation props, this method returns true.
<del> *
<del> * @param array $validateProp
<del> * @return mixed. Boolean for required, null if create/update does not match
<del> */
<del> protected function _parseRuleRequired($validateProp) {
<del> if (isset($validateProp['on'])) {
<del> if (
<del> ($validateProp['on'] == 'create' && $this->requestType != 'post') ||
<del> ($validateProp['on'] == 'update' && $this->requestType != 'put')
<del> ) {
<del> return null;
<del> }
<del> }
<del> if (isset($validateProp['allowEmpty']) && $validateProp['allowEmpty'] === true) {
<del> return false;
<del> }
<del> return true;
<del> }
<del>
<ide> } | 2 |
Python | Python | fix mypy in | 25164bb6380ae760bed5fe3efc5f2fc3ec5c38a1 | <ide><path>backtracking/all_combinations.py
<ide> numbers out of 1 ... n. We use backtracking to solve this problem.
<ide> Time complexity: O(C(n,k)) which is O(n choose k) = O((n!/(k! * (n - k)!)))
<ide> """
<add>from typing import List
<ide>
<ide>
<del>def generate_all_combinations(n: int, k: int) -> [[int]]:
<add>def generate_all_combinations(n: int, k: int) -> List[List[int]]:
<ide> """
<ide> >>> generate_all_combinations(n=4, k=2)
<ide> [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
<ide> """
<ide>
<del> result = []
<add> result: List[List[int]] = []
<ide> create_all_state(1, n, k, [], result)
<ide> return result
<ide>
<ide> def create_all_state(
<ide> increment: int,
<ide> total_number: int,
<ide> level: int,
<del> current_list: [int],
<del> total_list: [int],
<add> current_list: List[int],
<add> total_list: List[List[int]],
<ide> ) -> None:
<ide> if level == 0:
<ide> total_list.append(current_list[:])
<ide> def create_all_state(
<ide> current_list.pop()
<ide>
<ide>
<del>def print_all_state(total_list: [int]) -> None:
<add>def print_all_state(total_list: List[List[int]]) -> None:
<ide> for i in total_list:
<ide> print(*i)
<ide>
<ide><path>backtracking/all_permutations.py
<ide> Time complexity: O(n! * n),
<ide> where n denotes the length of the given sequence.
<ide> """
<add>from typing import List, Union
<ide>
<ide>
<del>def generate_all_permutations(sequence: [int]) -> None:
<add>def generate_all_permutations(sequence: List[Union[int, str]]) -> None:
<ide> create_state_space_tree(sequence, [], 0, [0 for i in range(len(sequence))])
<ide>
<ide>
<ide> def create_state_space_tree(
<del> sequence: [int], current_sequence: [int], index: int, index_used: int
<add> sequence: List[Union[int, str]],
<add> current_sequence: List[Union[int, str]],
<add> index: int,
<add> index_used: List[int],
<ide> ) -> None:
<ide> """
<ide> Creates a state space tree to iterate through each branch using DFS.
<ide> def create_state_space_tree(
<ide> sequence = list(map(int, input().split()))
<ide> """
<ide>
<del>sequence = [3, 1, 2, 4]
<add>sequence: List[Union[int, str]] = [3, 1, 2, 4]
<ide> generate_all_permutations(sequence)
<ide>
<del>sequence = ["A", "B", "C"]
<del>generate_all_permutations(sequence)
<add>sequence_2: List[Union[int, str]] = ["A", "B", "C"]
<add>generate_all_permutations(sequence_2)
<ide><path>backtracking/n_queens.py
<ide> diagonal lines.
<ide>
<ide> """
<add>from typing import List
<add>
<ide> solution = []
<ide>
<ide>
<del>def isSafe(board: [[int]], row: int, column: int) -> bool:
<add>def isSafe(board: List[List[int]], row: int, column: int) -> bool:
<ide> """
<ide> This function returns a boolean value True if it is safe to place a queen there
<ide> considering the current state of the board.
<ide> def isSafe(board: [[int]], row: int, column: int) -> bool:
<ide> return True
<ide>
<ide>
<del>def solve(board: [[int]], row: int) -> bool:
<add>def solve(board: List[List[int]], row: int) -> bool:
<ide> """
<ide> It creates a state space tree and calls the safe function until it receives a
<ide> False Boolean and terminates that branch and backtracks to the next
<ide> def solve(board: [[int]], row: int) -> bool:
<ide> solution.append(board)
<ide> printboard(board)
<ide> print()
<del> return
<add> return True
<ide> for i in range(len(board)):
<ide> """
<ide> For every row it iterates through each column to check if it is feasible to
<ide> def solve(board: [[int]], row: int) -> bool:
<ide> return False
<ide>
<ide>
<del>def printboard(board: [[int]]) -> None:
<add>def printboard(board: List[List[int]]) -> None:
<ide> """
<ide> Prints the boards that have a successful combination.
<ide> """
<ide><path>backtracking/rat_in_maze.py
<del>def solve_maze(maze: [[int]]) -> bool:
<add>from typing import List
<add>
<add>
<add>def solve_maze(maze: List[List[int]]) -> bool:
<ide> """
<ide> This method solves the "rat in maze" problem.
<ide> In this problem we have some n by n matrix, a start point and an end point.
<ide> def solve_maze(maze: [[int]]) -> bool:
<ide> return solved
<ide>
<ide>
<del>def run_maze(maze: [[int]], i: int, j: int, solutions: [[int]]) -> bool:
<add>def run_maze(maze: List[List[int]], i: int, j: int, solutions: List[List[int]]) -> bool:
<ide> """
<ide> This method is recursive starting from (i, j) and going in one of four directions:
<ide> up, down, left, right.
<ide> def run_maze(maze: [[int]], i: int, j: int, solutions: [[int]]) -> bool:
<ide>
<ide> solutions[i][j] = 0
<ide> return False
<add> return False
<ide>
<ide>
<ide> if __name__ == "__main__":
<ide><path>backtracking/sum_of_subsets.py
<ide> Summation of the chosen numbers must be equal to given number M and one number
<ide> can be used only once.
<ide> """
<add>from typing import List
<ide>
<ide>
<del>def generate_sum_of_subsets_soln(nums: [int], max_sum: [int]) -> [int]:
<del> result = []
<del> path = []
<add>def generate_sum_of_subsets_soln(nums: List[int], max_sum: int) -> List[List[int]]:
<add> result: List[List[int]] = []
<add> path: List[int] = []
<ide> num_index = 0
<ide> remaining_nums_sum = sum(nums)
<ide> create_state_space_tree(nums, max_sum, num_index, path, result, remaining_nums_sum)
<ide> return result
<ide>
<ide>
<ide> def create_state_space_tree(
<del> nums: [int],
<add> nums: List[int],
<ide> max_sum: int,
<ide> num_index: int,
<del> path: [int],
<del> result: [int],
<add> path: List[int],
<add> result: List[List[int]],
<ide> remaining_nums_sum: int,
<ide> ) -> None:
<ide> """ | 5 |
Go | Go | add unit test for rebasearchiveentries | 82eb9002e928f06ff694c618887bbc7d61f4b8e0 | <ide><path>pkg/archive/archive_unix_test.go
<ide> func TestTarWithHardLink(t *testing.T) {
<ide> }
<ide> }
<ide>
<add>func TestTarWithHardLinkAndRebase(t *testing.T) {
<add> tmpDir, err := ioutil.TempDir("", "docker-test-tar-hardlink-rebase")
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> defer os.RemoveAll(tmpDir)
<add>
<add> origin := filepath.Join(tmpDir, "origin")
<add> if err := os.Mkdir(origin, 0700); err != nil {
<add> t.Fatal(err)
<add> }
<add> if err := ioutil.WriteFile(filepath.Join(origin, "1"), []byte("hello world"), 0700); err != nil {
<add> t.Fatal(err)
<add> }
<add> if err := os.Link(filepath.Join(origin, "1"), filepath.Join(origin, "2")); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> var i1, i2 uint64
<add> if i1, err = getNlink(filepath.Join(origin, "1")); err != nil {
<add> t.Fatal(err)
<add> }
<add> // sanity check that we can hardlink
<add> if i1 != 2 {
<add> t.Skipf("skipping since hardlinks don't work here; expected 2 links, got %d", i1)
<add> }
<add>
<add> dest := filepath.Join(tmpDir, "dest")
<add>
<add> bRdr, err := TarResourceRebase(origin, "origin")
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> dstDir, srcBase := SplitPathDirEntry(origin)
<add> _, dstBase := SplitPathDirEntry(dest)
<add> content := RebaseArchiveEntries(bRdr, srcBase, dstBase)
<add> err = Untar(content, dstDir, &TarOptions{Compression: Uncompressed, NoLchown: true, NoOverwriteDirNonDir: true})
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> if i1, err = getInode(filepath.Join(dest, "1")); err != nil {
<add> t.Fatal(err)
<add> }
<add> if i2, err = getInode(filepath.Join(dest, "2")); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> if i1 != i2 {
<add> t.Errorf("expected matching inodes, but got %d and %d", i1, i2)
<add> }
<add>}
<add>
<ide> func getNlink(path string) (uint64, error) {
<ide> stat, err := os.Stat(path)
<ide> if err != nil { | 1 |
Javascript | Javascript | fix some bugs | 122d168b51b92dd0b682c69a2acb14e97a5c4b91 | <ide><path>fonts.js
<ide> CFF.prototype = {
<ide> var data =
<ide> "\x8b\x14" + // defaultWidth
<ide> "\x8b\x15" + // nominalWidth
<del> self.encodeNumber(properties.stdHW) + "\x0a" + // StdHW
<del> self.encodeNumber(properties.stdVW) + "\x0b"; // StdVW
<add> self.encodeNumber(properties.stdHW || 0) + "\x0a" + // StdHW
<add> self.encodeNumber(properties.stdVW || 0) + "\x0b"; // StdVW
<ide>
<ide> var stemH = properties.stemSnapH;
<ide> for (var i = 0; i < stemH.length; i++)
<ide><path>pdf.js
<ide> var CanvasGraphics = (function() {
<ide> this.ctx.translate(this.current.x, -1 * this.current.y);
<ide>
<ide> var font = Fonts.lookup(this.current.fontName);
<del> if (font)
<add> if (font && font.properties.textMatrix)
<ide> this.ctx.transform.apply(this.ctx, font.properties.textMatrix);
<ide>
<ide> this.ctx.fillText(text, 0, 0);
<ide><path>test/driver.js
<ide> function snapshotCurrentPage(gfx, page, task, failure) {
<ide> }
<ide>
<ide> sendTaskResult(canvas.toDataURL("image/png"), task, failure);
<del> log("done"+ (failure ? " (failed!)" : "") +"\n");
<add> log("done"+ (failure ? " (failed!: "+ failure +")" : "") +"\n");
<ide>
<ide> // Set up the next request
<ide> backoff = (inFlightRequests > 0) ? inFlightRequests * 10 : 0; | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.