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
add ability to reference casks from brew uninstall
90c26dadc7ec5021716fc0674b4b8b8dd8965293
<ide><path>Library/Homebrew/cask/cmd/uninstall.rb <ide> def initialize(*) <ide> <ide> def run <ide> casks.each do |cask| <del> odebug "Uninstalling Cask #{cask}" <add> uninstall_cask cask, binaries?, verbose?, force? <add> end <add> end <ide> <del> raise CaskNotInstalledError, cask unless cask.installed? || force? <add> def self.uninstall_cask(cask, binaries, verbose, force) <add> odebug "Uninstalling Cask #{cask}" <ide> <del> if cask.installed? && !cask.installed_caskfile.nil? <del> # use the same cask file that was used for installation, if possible <del> cask = CaskLoader.load(cask.installed_caskfile) if cask.installed_caskfile.exist? <del> end <add> raise CaskNotInstalledError, cask unless cask.installed? || force <ide> <del> Installer.new(cask, binaries: binaries?, verbose: verbose?, force: force?).uninstall <add> if cask.installed? && !cask.installed_caskfile.nil? <add> # use the same cask file that was used for installation, if possible <add> cask = CaskLoader.load(cask.installed_caskfile) if cask.installed_caskfile.exist? <add> end <ide> <del> next if (versions = cask.versions).empty? <add> Installer.new(cask, binaries: binaries, verbose: verbose, force: force).uninstall <ide> <del> puts <<~EOS <del> #{cask} #{versions.to_sentence} #{"is".pluralize(versions.count)} still installed. <del> Remove #{(versions.count == 1) ? "it" : "them all"} with `brew cask uninstall --force #{cask}`. <del> EOS <del> end <add> return if (versions = cask.versions).empty? <add> <add> puts <<~EOS <add> #{cask} #{versions.to_sentence} #{"is".pluralize(versions.count)} still installed. <add> Remove #{(versions.count == 1) ? "it" : "them all"} with `brew cask uninstall --force #{cask}`. <add> EOS <ide> end <ide> <ide> def self.help <ide><path>Library/Homebrew/cmd/uninstall.rb <ide> require "diagnostic" <ide> require "migrator" <ide> require "cli/parser" <add>require "cask/all" <add>require "cask/cmd" <add>require "cask/cask_loader" <ide> <ide> module Homebrew <ide> module_function <ide> def uninstall_args <ide> def uninstall <ide> uninstall_args.parse <ide> <del> kegs_by_rack = if args.force? <del> Hash[args.named.map do |name| <add> if args.force? <add> possible_casks = [] <add> kegs_by_rack = Hash[args.named.map do |name| <ide> rack = Formulary.to_rack(name) <del> next unless rack.directory? <add> <add> unless rack.directory? <add> possible_casks << name <add> next <add> end <ide> <ide> [rack, rack.subdirs.map { |d| Keg.new(d) }] <ide> end] <ide> else <del> args.kegs.group_by(&:rack) <add> kegs_, possible_casks = args.kegs_and_unknowns <add> kegs_by_rack = kegs_.group_by(&:rack) <ide> end <ide> <ide> handle_unsatisfied_dependents(kegs_by_rack) <ide> def uninstall <ide> end <ide> end <ide> end <add> <add> possible_casks.each do |name| <add> cask = Cask::CaskLoader.load name <add> Cask::Cmd::Uninstall.uninstall_cask(cask, true, args.verbose, args.force?) <add> rescue Cask::CaskUnavailableError <add> ofail "No installed keg or cask with the name \"#{name}\"" <add> end <ide> rescue MultipleVersionsInstalledError => e <ide> ofail e <ide> puts "Run `brew uninstall --force #{e.name}` to remove all versions."
2
Ruby
Ruby
fix missing formula reference
fd343c0578e4a8f6c7b5d33c3dfce85bf1c0305f
<ide><path>Library/Homebrew/cmd/info.rb <ide> def print_info <ide> args.named.each_with_index do |f, i| <ide> puts unless i.zero? <ide> begin <del> Formulary.factory(f) <add> formula = Formulary.factory(f) <ide> if args.analytics? <ide> Utils::Analytics.formula_output(formula) <ide> else
1
Ruby
Ruby
improve fault tolerance for redis cache store
bd54991d20aa30a76815ce80912c8122a2e4ffd3
<ide><path>activesupport/lib/active_support/cache/redis_cache_store.rb <ide> def delete_matched(matcher, options = nil) <ide> # Failsafe: Raises errors. <ide> def increment(name, amount = 1, options = nil) <ide> instrument :increment, name, amount: amount do <del> redis.with { |c| c.incrby normalize_key(name, options), amount } <add> failsafe :increment do <add> redis.with { |c| c.incrby normalize_key(name, options), amount } <add> end <ide> end <ide> end <ide> <ide> def increment(name, amount = 1, options = nil) <ide> # Failsafe: Raises errors. <ide> def decrement(name, amount = 1, options = nil) <ide> instrument :decrement, name, amount: amount do <del> redis.with { |c| c.decrby normalize_key(name, options), amount } <add> failsafe :decrement do <add> redis.with { |c| c.decrby normalize_key(name, options), amount } <add> end <ide> end <ide> end <ide> <ide> def read_multi_mget(*names) <ide> options = merged_options(options) <ide> <ide> keys = names.map { |name| normalize_key(name, options) } <del> values = redis.with { |c| c.mget(*keys) } <add> <add> values = failsafe(:read_multi_mget, returning: {}) do <add> redis.with { |c| c.mget(*keys) } <add> end <ide> <ide> names.zip(values).each_with_object({}) do |(name, value), results| <ide> if value <ide> def write_entry(key, entry, unless_exist: false, raw: false, expires_in: nil, ra <ide> expires_in += 5.minutes <ide> end <ide> <del> failsafe :write_entry do <add> failsafe :write_entry, returning: false do <ide> if unless_exist || expires_in <ide> modifiers = {} <ide> modifiers[:nx] = unless_exist <ide><path>activesupport/test/cache/behaviors.rb <ide> require_relative "behaviors/cache_store_version_behavior" <ide> require_relative "behaviors/connection_pool_behavior" <ide> require_relative "behaviors/encoded_key_cache_behavior" <add>require_relative "behaviors/failure_safety_behavior" <ide> require_relative "behaviors/local_cache_behavior" <ide><path>activesupport/test/cache/behaviors/failure_safety_behavior.rb <add># frozen_string_literal: true <add> <add>module FailureSafetyBehavior <add> def test_fetch_read_failure_returns_nil <add> @cache.write("foo", "bar") <add> <add> emulating_unavailability do |cache| <add> assert_nil cache.fetch("foo") <add> end <add> end <add> <add> def test_fetch_read_failure_does_not_attempt_to_write <add> end <add> <add> def test_read_failure_returns_nil <add> @cache.write("foo", "bar") <add> <add> emulating_unavailability do |cache| <add> assert_nil cache.read("foo") <add> end <add> end <add> <add> def test_read_multi_failure_returns_empty_hash <add> @cache.write_multi("foo" => "bar", "baz" => "quux") <add> <add> emulating_unavailability do |cache| <add> assert_equal Hash.new, cache.read_multi("foo", "baz") <add> end <add> end <add> <add> def test_write_failure_returns_false <add> emulating_unavailability do |cache| <add> assert_equal false, cache.write("foo", "bar") <add> end <add> end <add> <add> def test_write_multi_failure_not_raises <add> emulating_unavailability do |cache| <add> assert_nothing_raised do <add> cache.write_multi("foo" => "bar", "baz" => "quux") <add> end <add> end <add> end <add> <add> def test_fetch_multi_failure_returns_fallback_results <add> @cache.write_multi("foo" => "bar", "baz" => "quux") <add> <add> emulating_unavailability do |cache| <add> fetched = cache.fetch_multi("foo", "baz") { |k| "unavailable" } <add> assert_equal Hash["foo" => "unavailable", "baz" => "unavailable"], fetched <add> end <add> end <add> <add> def test_delete_failure_returns_false <add> @cache.write("foo", "bar") <add> <add> emulating_unavailability do |cache| <add> assert_equal false, cache.delete("foo") <add> end <add> end <add> <add> def test_exist_failure_returns_false <add> @cache.write("foo", "bar") <add> <add> emulating_unavailability do |cache| <add> assert !cache.exist?("foo") <add> end <add> end <add> <add> def test_increment_failure_returns_nil <add> @cache.write("foo", 1, raw: true) <add> <add> emulating_unavailability do |cache| <add> assert_nil cache.increment("foo") <add> end <add> end <add> <add> def test_decrement_failure_returns_nil <add> @cache.write("foo", 1, raw: true) <add> <add> emulating_unavailability do |cache| <add> assert_nil cache.decrement("foo") <add> end <add> end <add> <add> def test_clear_failure_returns_nil <add> emulating_unavailability do |cache| <add> assert_nil cache.clear <add> end <add> end <add>end <ide><path>activesupport/test/cache/stores/mem_cache_store_test.rb <ide> def get(key, options = {}) <ide> end <ide> end <ide> <add>class UnavailableDalliServer < Dalli::Server <add> def alive? <add> false <add> end <add>end <add> <ide> class MemCacheStoreTest < ActiveSupport::TestCase <ide> begin <ide> ss = Dalli::Client.new("localhost:11211").stats <ide> def setup <ide> include EncodedKeyCacheBehavior <ide> include AutoloadingCacheBehavior <ide> include ConnectionPoolBehavior <add> include FailureSafetyBehavior <ide> <ide> def test_raw_values <ide> cache = ActiveSupport::Cache.lookup_store(:mem_cache_store, raw: true) <ide> def emulating_latency <ide> Dalli.send(:remove_const, :Client) <ide> Dalli.const_set(:Client, old_client) <ide> end <add> <add> def emulating_unavailability <add> old_server = Dalli.send(:remove_const, :Server) <add> Dalli.const_set(:Server, UnavailableDalliServer) <add> <add> yield ActiveSupport::Cache::MemCacheStore.new <add> ensure <add> Dalli.send(:remove_const, :Server) <add> Dalli.const_set(:Server, old_server) <add> end <ide> end <ide><path>activesupport/test/cache/stores/redis_cache_store_test.rb <ide> class KeyEncodingSafetyTest < StoreTest <ide> class StoreAPITest < StoreTest <ide> end <ide> <del> class FailureSafetyTest < StoreTest <del> test "fetch read failure returns nil" do <add> class UnavailableRedisClient < Redis::Client <add> def ensure_connected <add> raise Redis::BaseConnectionError <ide> end <add> end <ide> <del> test "fetch read failure does not attempt to write" do <del> end <add> class FailureSafetyTest < StoreTest <add> include FailureSafetyBehavior <ide> <del> test "write failure returns nil" do <del> end <add> private <add> <add> def emulating_unavailability <add> old_client = Redis.send(:remove_const, :Client) <add> Redis.const_set(:Client, UnavailableRedisClient) <add> <add> yield ActiveSupport::Cache::RedisCacheStore.new <add> ensure <add> Redis.send(:remove_const, :Client) <add> Redis.const_set(:Client, old_client) <add> end <ide> end <ide> <ide> class DeleteMatchedTest < StoreTest
5
Javascript
Javascript
support windows for snapshot
e6864e4ac6b47b0cfecedf7be564a409db63aa4c
<ide><path>test/Errors.test.js <ide> const fs = require("fs"); <ide> const webpack = require(".."); <ide> const prettyFormat = require("pretty-format"); <ide> <del>const CWD_PATTERN = new RegExp(`${process.cwd()}`.replace(/\/|\\/, "/"), "gm"); <add>const CWD_PATTERN = new RegExp(process.cwd().replace(/\\/g, "/"), "gm"); <ide> const ERROR_STACK_PATTERN = /(?:\n\s+at[^()]+\(?.*\)?)+/gm; <ide> <ide> function cleanError(err) { <ide> const prettyFormatOptions = { <ide> return typeof val === "string"; <ide> }, <ide> print(val) { <del> return `"${val.replace(/\n/gm, "\\n").replace(/"/gm, '\\"')}"`; <add> return `"${val <add> .replace(/\\/gm, "/") <add> .replace(/"/gm, '\\"') <add> .replace(/\n/gm, "\\n") <add> }"`; <ide> } <del> }, <del> // { <del> // test(val) { <del> // return typeof val === "object" && typeof val.loc !== "undefined"; <del> // }, <del> // print(val) { <del> // return `"${val.replace(/\n/gm, "\\n").replace(/"/gm, '\\"')}"`; <del> // } <del> // } <add> } <ide> ] <ide> }; <ide> <ide> expect.addSnapshotSerializer({ <ide> <ide> const defaults = { <ide> options: { <del> context: path.resolve(__dirname, "fixtures/errors"), <add> context: path.resolve(__dirname, "fixtures", "errors"), <ide> mode: "none", <ide> devtool: false, <ide> optimization: { <ide> Object { <ide> }); <ide> <ide> const isCasePreservedFilesystem = fs.existsSync( <del> path.resolve(__dirname, "fixtures/errors/FILE.js") <add> path.resolve(__dirname, "fixtures", "errors", "FILE.js") <ide> ); <ide> if (isCasePreservedFilesystem) { <ide> it("should emit warning for case-preserved disk", async () => {
1
PHP
PHP
fix failing test
28372576223c5063bcd1fefe01190c14575780ab
<ide><path>src/Http/Response.php <ide> public function getType(): string <ide> * @param string $contentType Either a file extension which will be mapped to a mime-type or a concrete mime-type. <ide> * @return static <ide> */ <del> public function withType(string $contentType): ResponseInterface <add> public function withType(string $contentType): self <ide> { <ide> $mappedType = $this->resolveType($contentType); <ide> $new = clone $this; <ide><path>src/Http/ServerRequest.php <ide> public function clientIp(): string <ide> $ipaddr = $this->getEnv('REMOTE_ADDR'); <ide> } <ide> <del> return trim($ipaddr); <add> return trim((string)$ipaddr); <ide> } <ide> <ide> /** <ide><path>src/Shell/Task/LoadTask.php <ide> protected function modifyApplication(string $app, string $plugin, string $option <ide> $append = "\n \$this->addPlugin('%s', [%s]);\n"; <ide> $insert = str_replace(', []', '', sprintf($append, $plugin, $options)); <ide> <del> if (!preg_match('/function bootstrap\(\)/m', $contents)) { <add> if (!preg_match('/function bootstrap\(\)(?:\s*)\:(?:\s*)void/m', $contents)) { <ide> $this->abort('Your Application class does not have a bootstrap() method. Please add one.'); <ide> } else { <del> $contents = preg_replace('/(function bootstrap\(\)(?:\s+)\{)/m', '$1' . $insert, $contents); <add> $contents = preg_replace('/(function bootstrap\(\)(?:\s*)\:(?:\s*)void(?:\s+)\{)/m', '$1' . $insert, $contents); <ide> } <ide> $file->write($contents); <ide> <ide><path>tests/TestCase/Controller/Component/RequestHandlerComponentTest.php <ide> public function testPrefers(): void <ide> $this->assertEquals('html', $this->RequestHandler->prefers()); <ide> $this->assertFalse($this->RequestHandler->prefers('rss')); <ide> <del> $this->Controller->setRequest($this->request->withEnv('HTTP_ACCEPT', null)); <add> $this->Controller->setRequest($this->request->withEnv('HTTP_ACCEPT', '')); <ide> $this->RequestHandler->ext = 'json'; <ide> $this->assertFalse($this->RequestHandler->prefers('xml')); <ide> }
4
Javascript
Javascript
prefer module over global for isempty
3309e21d01ec1e1d06104659b973636c8074f24f
<ide><path>packages/ember-routing/lib/system/route.js <ide> import { <ide> calculateCacheKey <ide> } from 'ember-routing/utils'; <ide> import { getOwner } from 'container/owner'; <del> <add>import isEmpty from 'ember-metal/is_empty'; <ide> var slice = Array.prototype.slice; <ide> <ide> function K() { return this; } <ide> var Route = EmberObject.extend(ActionHandler, Evented, { <ide> assert('The name in the given arguments is undefined', arguments.length > 0 ? !isNone(arguments[0]) : true); <ide> <ide> var namePassed = typeof _name === 'string' && !!_name; <del> var isDefaultRender = arguments.length === 0 || Ember.isEmpty(arguments[0]); <add> var isDefaultRender = arguments.length === 0 || isEmpty(arguments[0]); <ide> var name; <ide> <ide> if (typeof _name === 'object' && !options) {
1
Ruby
Ruby
omit the default limit for float columns
7ff3bc125373c76e58f46463f6cff6dac15b15dd
<ide><path>activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb <ide> class AbstractMysqlAdapter < AbstractAdapter <ide> string: { name: "varchar", limit: 255 }, <ide> text: { name: "text", limit: 65535 }, <ide> integer: { name: "int", limit: 4 }, <del> float: { name: "float" }, <add> float: { name: "float", limit: 24 }, <ide> decimal: { name: "decimal" }, <ide> datetime: { name: "datetime" }, <ide> timestamp: { name: "timestamp" }, <ide><path>activerecord/test/cases/adapters/mysql2/unsigned_type_test.rb <ide> class UnsignedType < ActiveRecord::Base <ide> schema = dump_table_schema "unsigned_types" <ide> assert_match %r{t\.integer\s+"unsigned_integer",\s+unsigned: true$}, schema <ide> assert_match %r{t\.bigint\s+"unsigned_bigint",\s+unsigned: true$}, schema <del> assert_match %r{t\.float\s+"unsigned_float",\s+limit: 24,\s+unsigned: true$}, schema <add> assert_match %r{t\.float\s+"unsigned_float",\s+unsigned: true$}, schema <ide> assert_match %r{t\.decimal\s+"unsigned_decimal",\s+precision: 10,\s+scale: 2,\s+unsigned: true$}, schema <ide> end <ide> end <ide><path>activerecord/test/cases/schema_dumper_test.rb <ide> def test_schema_dump_should_honor_nonstandard_primary_keys <ide> end <ide> <ide> def test_schema_dump_should_use_false_as_default <del> output = standard_dump <add> output = dump_table_schema "booleans" <ide> assert_match %r{t\.boolean\s+"has_fun",.+default: false}, output <ide> end <ide> <ide> def test_schema_dump_does_not_include_limit_for_text_field <del> output = standard_dump <add> output = dump_table_schema "admin_users" <ide> assert_match %r{t\.text\s+"params"$}, output <ide> end <ide> <ide> def test_schema_dump_does_not_include_limit_for_binary_field <del> output = standard_dump <add> output = dump_table_schema "binaries" <ide> assert_match %r{t\.binary\s+"data"$}, output <ide> end <ide> <add> def test_schema_dump_does_not_include_limit_for_float_field <add> output = dump_table_schema "numeric_data" <add> assert_match %r{t\.float\s+"temperature"$}, output <add> end <add> <ide> if current_adapter?(:Mysql2Adapter) <ide> def test_schema_dump_includes_length_for_mysql_binary_fields <ide> output = standard_dump
3
Ruby
Ruby
use deep_dup in the deep_transform_keys tests
b0ebdf3e744baa935c0d9325780121e7fcac9d9a
<ide><path>activesupport/test/core_ext/hash_ext_test.rb <ide> def test_transform_keys <ide> assert_equal @upcase_strings, @mixed.transform_keys{ |key| key.to_s.upcase } <ide> end <ide> <add> def test_transform_keys_not_mutates <add> transformed_hash = @mixed.dup <add> transformed_hash.transform_keys{ |key| key.to_s.upcase } <add> assert_equal @mixed, transformed_hash <add> end <add> <ide> def test_deep_transform_keys <ide> assert_equal @nested_upcase_strings, @nested_symbols.deep_transform_keys{ |key| key.to_s.upcase } <ide> assert_equal @nested_upcase_strings, @nested_strings.deep_transform_keys{ |key| key.to_s.upcase } <ide> assert_equal @nested_upcase_strings, @nested_mixed.deep_transform_keys{ |key| key.to_s.upcase } <ide> end <ide> <add> def test_deep_transform_keys_not_mutates <add> transformed_hash = @nested_mixed.deep_dup <add> transformed_hash.deep_transform_keys{ |key| key.to_s.upcase } <add> assert_equal @nested_mixed, transformed_hash <add> end <add> <ide> def test_transform_keys! <ide> assert_equal @upcase_strings, @symbols.dup.transform_keys!{ |key| key.to_s.upcase } <ide> assert_equal @upcase_strings, @strings.dup.transform_keys!{ |key| key.to_s.upcase } <ide> assert_equal @upcase_strings, @mixed.dup.transform_keys!{ |key| key.to_s.upcase } <ide> end <ide> <add> def test_transform_keys_with_bang_mutates <add> transformed_hash = @mixed.dup <add> transformed_hash.transform_keys!{ |key| key.to_s.upcase } <add> assert_equal @upcase_strings, transformed_hash <add> assert_equal @mixed, { :a => 1, "b" => 2 } <add> end <add> <ide> def test_deep_transform_keys! <del> assert_equal @nested_upcase_strings, @nested_symbols.deep_transform_keys!{ |key| key.to_s.upcase } <del> assert_equal @nested_upcase_strings, @nested_strings.deep_transform_keys!{ |key| key.to_s.upcase } <del> assert_equal @nested_upcase_strings, @nested_mixed.deep_transform_keys!{ |key| key.to_s.upcase } <del> end <add> assert_equal @nested_upcase_strings, @nested_symbols.deep_dup.deep_transform_keys!{ |key| key.to_s.upcase } <add> assert_equal @nested_upcase_strings, @nested_strings.deep_dup.deep_transform_keys!{ |key| key.to_s.upcase } <add> assert_equal @nested_upcase_strings, @nested_mixed.deep_dup.deep_transform_keys!{ |key| key.to_s.upcase } <add> end <add> <add> def test_deep_transform_keys_with_bang_mutates <add> transformed_hash = @nested_mixed.deep_dup <add> transformed_hash.deep_transform_keys!{ |key| key.to_s.upcase } <add> assert_equal @nested_upcase_strings, transformed_hash <add> assert_equal @nested_mixed, { 'a' => { :b => { 'c' => 3 } } } <add> end <ide> <ide> def test_symbolize_keys <ide> assert_equal @symbols, @symbols.symbolize_keys <ide> assert_equal @symbols, @strings.symbolize_keys <ide> assert_equal @symbols, @mixed.symbolize_keys <ide> end <ide> <add> def test_symbolize_keys_not_mutates <add> transformed_hash = @mixed.dup <add> transformed_hash.symbolize_keys <add> assert_equal @mixed, transformed_hash <add> end <add> <ide> def test_deep_symbolize_keys <ide> assert_equal @nested_symbols, @nested_symbols.deep_symbolize_keys <ide> assert_equal @nested_symbols, @nested_strings.deep_symbolize_keys <ide> assert_equal @nested_symbols, @nested_mixed.deep_symbolize_keys <ide> end <ide> <add> def test_deep_symbolize_keys_not_mutates <add> transformed_hash = @nested_mixed.deep_dup <add> transformed_hash.deep_symbolize_keys <add> assert_equal @nested_mixed, transformed_hash <add> end <add> <ide> def test_symbolize_keys! <ide> assert_equal @symbols, @symbols.dup.symbolize_keys! <ide> assert_equal @symbols, @strings.dup.symbolize_keys! <ide> assert_equal @symbols, @mixed.dup.symbolize_keys! <ide> end <ide> <add> def test_symbolize_keys_with_bang_mutates <add> transformed_hash = @mixed.dup <add> transformed_hash.deep_symbolize_keys! <add> assert_equal @symbols, transformed_hash <add> assert_equal @mixed, { :a => 1, "b" => 2 } <add> end <add> <ide> def test_deep_symbolize_keys! <del> assert_equal @nested_symbols, @nested_symbols.dup.deep_symbolize_keys! <del> assert_equal @nested_symbols, @nested_strings.dup.deep_symbolize_keys! <del> assert_equal @nested_symbols, @nested_mixed.dup.deep_symbolize_keys! <add> assert_equal @nested_symbols, @nested_symbols.deep_dup.deep_symbolize_keys! <add> assert_equal @nested_symbols, @nested_strings.deep_dup.deep_symbolize_keys! <add> assert_equal @nested_symbols, @nested_mixed.deep_dup.deep_symbolize_keys! <add> end <add> <add> def test_deep_symbolize_keys_with_bang_mutates <add> transformed_hash = @nested_mixed.deep_dup <add> transformed_hash.deep_symbolize_keys! <add> assert_equal @nested_symbols, transformed_hash <add> assert_equal @nested_mixed, { 'a' => { :b => { 'c' => 3 } } } <ide> end <ide> <ide> def test_symbolize_keys_preserves_keys_that_cant_be_symbolized <ide> def test_symbolize_keys_preserves_keys_that_cant_be_symbolized <ide> <ide> def test_deep_symbolize_keys_preserves_keys_that_cant_be_symbolized <ide> assert_equal @nested_illegal_symbols, @nested_illegal_symbols.deep_symbolize_keys <del> assert_equal @nested_illegal_symbols, @nested_illegal_symbols.dup.deep_symbolize_keys! <add> assert_equal @nested_illegal_symbols, @nested_illegal_symbols.deep_dup.deep_symbolize_keys! <ide> end <ide> <ide> def test_symbolize_keys_preserves_fixnum_keys <ide> def test_symbolize_keys_preserves_fixnum_keys <ide> <ide> def test_deep_symbolize_keys_preserves_fixnum_keys <ide> assert_equal @nested_fixnums, @nested_fixnums.deep_symbolize_keys <del> assert_equal @nested_fixnums, @nested_fixnums.dup.deep_symbolize_keys! <add> assert_equal @nested_fixnums, @nested_fixnums.deep_dup.deep_symbolize_keys! <ide> end <ide> <ide> def test_stringify_keys <ide> def test_stringify_keys <ide> assert_equal @strings, @mixed.stringify_keys <ide> end <ide> <add> def test_stringify_keys_not_mutates <add> transformed_hash = @mixed.dup <add> transformed_hash.stringify_keys <add> assert_equal @mixed, transformed_hash <add> end <add> <ide> def test_deep_stringify_keys <ide> assert_equal @nested_strings, @nested_symbols.deep_stringify_keys <ide> assert_equal @nested_strings, @nested_strings.deep_stringify_keys <ide> assert_equal @nested_strings, @nested_mixed.deep_stringify_keys <ide> end <ide> <add> def test_deep_stringify_keys_not_mutates <add> transformed_hash = @nested_mixed.deep_dup <add> transformed_hash.deep_stringify_keys <add> assert_equal @nested_mixed, transformed_hash <add> end <add> <ide> def test_stringify_keys! <ide> assert_equal @strings, @symbols.dup.stringify_keys! <ide> assert_equal @strings, @strings.dup.stringify_keys! <ide> assert_equal @strings, @mixed.dup.stringify_keys! <ide> end <ide> <add> def test_stringify_keys_with_bang_mutates <add> transformed_hash = @mixed.dup <add> transformed_hash.stringify_keys! <add> assert_equal @strings, transformed_hash <add> assert_equal @mixed, { :a => 1, "b" => 2 } <add> end <add> <ide> def test_deep_stringify_keys! <del> assert_equal @nested_strings, @nested_symbols.dup.deep_stringify_keys! <del> assert_equal @nested_strings, @nested_strings.dup.deep_stringify_keys! <del> assert_equal @nested_strings, @nested_mixed.dup.deep_stringify_keys! <add> assert_equal @nested_strings, @nested_symbols.deep_dup.deep_stringify_keys! <add> assert_equal @nested_strings, @nested_strings.deep_dup.deep_stringify_keys! <add> assert_equal @nested_strings, @nested_mixed.deep_dup.deep_stringify_keys! <add> end <add> <add> def test_deep_stringify_keys_with_bang_mutates <add> transformed_hash = @nested_mixed.deep_dup <add> transformed_hash.deep_stringify_keys! <add> assert_equal @nested_strings, transformed_hash <add> assert_equal @nested_mixed, { 'a' => { :b => { 'c' => 3 } } } <ide> end <ide> <ide> def test_symbolize_keys_for_hash_with_indifferent_access <ide> def test_symbolize_keys_bang_for_hash_with_indifferent_access <ide> end <ide> <ide> def test_deep_symbolize_keys_bang_for_hash_with_indifferent_access <del> assert_raise(NoMethodError) { @nested_symbols.with_indifferent_access.dup.deep_symbolize_keys! } <del> assert_raise(NoMethodError) { @nested_strings.with_indifferent_access.dup.deep_symbolize_keys! } <del> assert_raise(NoMethodError) { @nested_mixed.with_indifferent_access.dup.deep_symbolize_keys! } <add> assert_raise(NoMethodError) { @nested_symbols.with_indifferent_access.deep_dup.deep_symbolize_keys! } <add> assert_raise(NoMethodError) { @nested_strings.with_indifferent_access.deep_dup.deep_symbolize_keys! } <add> assert_raise(NoMethodError) { @nested_mixed.with_indifferent_access.deep_dup.deep_symbolize_keys! } <ide> end <ide> <ide> def test_symbolize_keys_preserves_keys_that_cant_be_symbolized_for_hash_with_indifferent_access <ide> def test_symbolize_keys_preserves_keys_that_cant_be_symbolized_for_hash_with_ind <ide> <ide> def test_deep_symbolize_keys_preserves_keys_that_cant_be_symbolized_for_hash_with_indifferent_access <ide> assert_equal @nested_illegal_symbols, @nested_illegal_symbols.with_indifferent_access.deep_symbolize_keys <del> assert_raise(NoMethodError) { @nested_illegal_symbols.with_indifferent_access.dup.deep_symbolize_keys! } <add> assert_raise(NoMethodError) { @nested_illegal_symbols.with_indifferent_access.deep_dup.deep_symbolize_keys! } <ide> end <ide> <ide> def test_symbolize_keys_preserves_fixnum_keys_for_hash_with_indifferent_access <ide> def test_symbolize_keys_preserves_fixnum_keys_for_hash_with_indifferent_access <ide> <ide> def test_deep_symbolize_keys_preserves_fixnum_keys_for_hash_with_indifferent_access <ide> assert_equal @nested_fixnums, @nested_fixnums.with_indifferent_access.deep_symbolize_keys <del> assert_raise(NoMethodError) { @nested_fixnums.with_indifferent_access.dup.deep_symbolize_keys! } <add> assert_raise(NoMethodError) { @nested_fixnums.with_indifferent_access.deep_dup.deep_symbolize_keys! } <ide> end <ide> <ide> def test_stringify_keys_for_hash_with_indifferent_access <ide> def test_stringify_keys_bang_for_hash_with_indifferent_access <ide> <ide> def test_deep_stringify_keys_bang_for_hash_with_indifferent_access <ide> assert_instance_of ActiveSupport::HashWithIndifferentAccess, @nested_symbols.with_indifferent_access.dup.deep_stringify_keys! <del> assert_equal @nested_strings, @nested_symbols.with_indifferent_access.dup.deep_stringify_keys! <del> assert_equal @nested_strings, @nested_strings.with_indifferent_access.dup.deep_stringify_keys! <del> assert_equal @nested_strings, @nested_mixed.with_indifferent_access.dup.deep_stringify_keys! <add> assert_equal @nested_strings, @nested_symbols.with_indifferent_access.deep_dup.deep_stringify_keys! <add> assert_equal @nested_strings, @nested_strings.with_indifferent_access.deep_dup.deep_stringify_keys! <add> assert_equal @nested_strings, @nested_mixed.with_indifferent_access.deep_dup.deep_stringify_keys! <ide> end <ide> <ide> def test_nested_under_indifferent_access
1
Text
Text
add documentation for core layers
25ad4000f9eadde485a293e29f0c081b736251db
<ide><path>README.md <ide> model.add(Activation('relu')) <ide> model.add(MaxPooling2D(poolsize=(2, 2))) <ide> model.add(Dropout(0.25)) <ide> <del>model.add(Flatten(64*8*8)) <add>model.add(Flatten()) <ide> model.add(Dense(64*8*8, 256)) <ide> model.add(Activation('relu')) <ide> model.add(Dropout(0.5)) <ide> model.add(Convolution2D(128, 128, 3, 3)) <ide> model.add(Activation('relu')) <ide> model.add(MaxPooling2D(poolsize=(2, 2))) <ide> <del>model.add(Flatten(128*4*4)) <add>model.add(Flatten()) <ide> model.add(Dense(128*4*4, 256)) <ide> model.add(Activation('relu')) <ide> model.add(Dropout(0.5)) <ide><path>docs/sources/activations.md <ide> model.add(Activation(tanh)) <ide> <ide> ## On Advanced Activations <ide> <del>Activations that are more complex than a simple Theano function (eg. learnable activations, configurable activations, etc.) are available as [Advanced Activation layers](/layers/advanced_activations), and can be found in the module `keras.layers.advanced_activations`. These include PReLU and LeakyReLU. <ide>\ No newline at end of file <add>Activations that are more complex than a simple Theano function (eg. learnable activations, configurable activations, etc.) are available as [Advanced Activation layers](layers/advanced_activations.md), and can be found in the module `keras.layers.advanced_activations`. These include PReLU and LeakyReLU. <ide>\ No newline at end of file <ide><path>docs/sources/examples.md <ide> model.add(Activation('relu')) <ide> model.add(MaxPooling2D(poolsize=(2, 2))) <ide> model.add(Dropout(0.25)) <ide> <del>model.add(Flatten(64*8*8)) <add>model.add(Flatten()) <ide> model.add(Dense(64*8*8, 256)) <ide> model.add(Activation('relu')) <ide> model.add(Dropout(0.5)) <ide> model.add(Convolution2D(128, 128, 3, 3)) <ide> model.add(Activation('relu')) <ide> model.add(MaxPooling2D(poolsize=(2, 2))) <ide> <del>model.add(Flatten(128*4*4)) <add>model.add(Flatten()) <ide> model.add(Dense(128*4*4, 256)) <ide> model.add(Activation('relu')) <ide> model.add(Dropout(0.5)) <ide><path>docs/sources/layers/core.md <del># Core <del> <ide> ## Base class <ide> <ide> ```python <ide> keras.layers.core.Layer() <ide> <ide> __Methods__: <ide> <add>```python <add>connect(self, previous_layer) <add>``` <add> <add>- Connect the input of the current layer to the output of the argument layer. <add> <add>- __Returns__: None. <add> <add>- __Arguments__: <add> - __previous_layer__: Layer object. <add> <add> <add> <add>```python <add>output(self, train) <add>``` <add> <add>- Get the output of the layer. <add> <add>- __Returns__: Theano tensor. <add> <add>- __Arguments__: <add> - __train__: Boolean. Specifies whether output is computed in training mode or in testing mode, which can change the logic, for instance in there are any `Dropout` layers in the network. <add> <add> <add> <add>```python <add>get_input(self, train) <add>``` <add> <add>- Get the input of the layer. <add> <add>- __Returns__: Theano tensor. <add> <add>- __Arguments__: <add> - __train__: Boolean. Specifies whether output is computed in training mode or in testing mode, which can change the logic, for instance in there are any `Dropout` layers in the network. <add> <add> <add> <add>```python <add>get_weights(self) <add>``` <add> <add>- Get the weights of the parameters of the layer. <add> <add>- __Returns__: List of numpy arrays (one per layer parameter). <add> <add> <add> <add>```python <add>set_weights(self, weights) <add>``` <add> <add>- Set the weights of the parameters of the layer. <ide> <del>## Core layers <add>- __Arguments__: <add> - __weights__: List of numpy arrays (one per layer parameter). Should be in the same order as what `get_weights(self)` returns. <ide> <del>### Dense <add> <add> <add>--- <add> <add>## Dense <ide> ```python <ide> keras.layers.core.Dense(input_dim, output_dim, init='uniform', activation='linear', weights=None) <ide> ``` <del>__Arguments__: <ide> <del>__Methods__: <add>- Standard 1D fully-connect layer. <add> <add>- __Input shape__: `(nb_samples, input_dim)`. <add> <add>- __Arguments__: <add> <add> - __input_dim__: int >= 0. <add> - __output_dim__: int >= 0. <add> - __init__: name of initialization function for the weights of the layer (see: [initializations](../initializations.md)), or alternatively, Theano function to use for weights initialization. This parameter is only relevant if you don't pass a `weights` argument. <add> - __activation__: name of activation function to use (see: [activations](../activations.md)), or alternatively, elementwise Theano function. If you don't specify anything, no activation is applied (ie. "linear" activation: a(x) = x). <add> - __weights__: list of numpy arrays to set as initial weights. The list should have 1 element, of shape `(input_dim, output_dim)`. <add> <add> <add>--- <ide> <del>### Activation <add>## Activation <ide> ```python <ide> keras.layers.core.Activation(activation) <ide> ``` <del>__Arguments__: <add>- Apply an activation function to the input. <ide> <del>__Methods__: <add>- __Input shape__: This layer does not assume a specific input shape. As a result, it cannot be used as the first layer in a model. <add> <add>- __Arguments__: <add> <add> - __activation__: name of activation function to use (see: [activations](../activations.md)), or alternatively, elementwise Theano function. <add> <add> <add>--- <ide> <del>### Dropout <add>## Dropout <ide> ```python <ide> keras.layers.core.Dropout(p) <ide> ``` <del>__Arguments__: <add>- Apply dropout to the input. Dropout consists in randomly setting a fraction `p` of input units to 0 at each update during training time, which helps prevent overfitting. Reference: [Dropout: A Simple Way to Prevent Neural Networks from Overfitting](http://www.cs.toronto.edu/~rsalakhu/papers/srivastava14a.pdf) <add> <add>- __Input shape__: This layer does not assume a specific input shape. As a result, it cannot be used as the first layer in a model. <add> <add>- __Arguments__: <add> <add> - __p__: float (0 <= p < 1). Fraction of the input that gets dropped out at training time. <ide> <del>__Methods__: <ide> <del>### Reshape <add>--- <add> <add>## Reshape <ide> ```python <ide> keras.layers.core.Reshape(*dims) <ide> ``` <del>__Arguments__: <ide> <del>__Methods__: <add>- Reshape the input to a new shape containing the same number of units. <add> <add>- __Input shape__: This layer does not assume a specific input shape. As a result, it cannot be used as the first layer in a model. <add> <add>- __Arguments__: <add> <add> - *dims: integers. Dimensions of the new shape. <ide> <del>### Flatten <add>- __Example__: <ide> ```python <del>keras.layers.core.Flatten(size) <add># input shape: (nb_samples, 10) <add>model.add(Dense(10, 100)) # output shape: (nb_samples, 100) <add>model.add(Reshape(10, 10)) # output shape: (nb_samples, 10, 10) <ide> ``` <del>__Arguments__: <ide> <del>__Methods__: <add>--- <ide> <del>### RepeatVector <add>## Flatten <add>```python <add>keras.layers.core.Flatten() <add>``` <add> <add>- Convert a nD input to 1D. <add>- __Input shape__: (nb_samples, *). This layer cannot be used as the first layer in a model. <add> <add>--- <add> <add>## RepeatVector <ide> ```python <ide> keras.layers.core.RepeatVector(n) <ide> ``` <del>__Arguments__: <ide> <del>__Methods__: <add>- Repeat the 1D input n times. Dimensions of input are assumed to be (nb_samples, dim). Output will have the shape (nb_samples, n, dim). <add> <add>- __Input shape__: This layer does not assume a specific input shape. As a result, it cannot be used as the first layer in a model. <ide> <add>- __Arguments__: <add> - __n__: int. <add> <add>- __Example__: <add> <add>```python <add># input shape: (nb_samples, 10) <add>model.add(Dense(10, 100)) # output shape: (nb_samples, 100) <add>model.add(Repeat(2)) # output shape: (nb_samples, 2, 10) <add>``` <ide> <ide><path>docs/sources/optimizers.md <ide> You can either instantiate an optimizer before passing it to `model.compile()` , <ide> model.compile(loss='mean_squared_error', optimizer='sgd') <ide> ``` <ide> <add>--- <add> <ide> ## Base class <ide> <ide> ```python <ide> All optimizers descended from this class support the following keyword arguments <ide> <ide> Note: this is base class for building optimizers, not an actual optimizer that can be used for training models. <ide> <add>--- <add> <ide> ## SGD <ide> <ide> ```python <ide> keras.optimizers.SGD(lr=0.01, momentum=0., decay=0., nesterov=False) <ide> ``` <ide> [[source](https://github.com/fchollet/keras/blob/master/keras/optimizers.py)] <ide> <add>__Arguments__: <add> <ide> - __lr__: float >= 0. Learning rate. <ide> - __momentum__: float >= 0. Parameter updates momentum. <ide> - __decay__: float >= 0. Learning rate decay over each update. <ide> - __nesterov__: boolean. Whether to apply Nesterov momentum. <ide> <add>--- <add> <ide> ## Adagrad <ide> <ide> ```python <ide> keras.optimizers.Adagrad(lr=0.01, epsilon=1e-6) <ide> <ide> It is recommended to leave the parameters of this optimizer at their default values. <ide> <add>__Arguments__: <add> <ide> - __lr__: float >= 0. Learning rate. <ide> - __epsilon__: float >= 0. <ide> <add>--- <ide> <ide> ## Adadelta <ide> <ide> keras.optimizers.Adadelta(lr=1.0, rho=0.95, epsilon=1e-6) <ide> <ide> It is recommended to leave the parameters of this optimizer at their default values. <ide> <add>__Arguments__: <add> <ide> - __lr__: float >= 0. Learning rate. It is recommended to leave it at the default value. <ide> - __rho__: float >= 0. <ide> - __epsilon__: float >= 0. Fuzz factor. <ide> <ide> For more info, see *"Adadelta: an adaptive learning rate method"* by Matthew Zeiler. <ide> <add>--- <add> <ide> ## RMSprop <ide> <ide> ```python <ide> keras.optimizers.RMSprop(lr=0.001, rho=0.9, epsilon=1e-6) <ide> <ide> It is recommended to leave the parameters of this optimizer at their default values. <ide> <add>__Arguments__: <add> <ide> - __lr__: float >= 0. Learning rate. <ide> - __rho__: float >= 0. <ide> - __epsilon__: float >= 0. Fuzz factor. <ide>\ No newline at end of file
5
Javascript
Javascript
introduce nganimateswap directive
78297d252de7c80f73ecf9e291ed71bd52578361
<ide><path>angularFiles.js <ide> var angularFiles = { <ide> 'src/ngAnimate/animateQueue.js', <ide> 'src/ngAnimate/animateRunner.js', <ide> 'src/ngAnimate/animation.js', <add> 'src/ngAnimate/ngAnimateSwap.js', <ide> 'src/ngAnimate/module.js' <ide> ], <ide> 'ngCookies': [ <ide><path>src/ngAnimate/module.js <ide> <ide> /* global angularAnimateModule: true, <ide> <add> ngAnimateSwapDirective, <ide> $$AnimateAsyncRunFactory, <ide> $$rAFSchedulerFactory, <ide> $$AnimateChildrenDirective, <ide> * Click here {@link ng.$animate to learn more about animations with `$animate`}. <ide> */ <ide> angular.module('ngAnimate', []) <add> .directive('ngAnimateSwap', ngAnimateSwapDirective) <add> <ide> .directive('ngAnimateChildren', $$AnimateChildrenDirective) <ide> .factory('$$rAFScheduler', $$rAFSchedulerFactory) <ide> <ide><path>src/ngAnimate/ngAnimateSwap.js <add>'use strict'; <add> <add>/** <add> * @ngdoc directive <add> * @name ngAnimateSwap <add> * @restrict A <add> * @scope <add> * <add> * @description <add> * <add> * ngAnimateSwap is a animation-oriented directive that allows for the container to <add> * be removed and entered in whenever the associated expression changes. A <add> * common usecase for this directive is a rotating banner component which <add> * contains one image being present at a time. When the active image changes <add> * then the old image will perform a `leave` animation and the new element <add> * will be inserted via an `enter` animation. <add> * <add> * @example <add> * <example name="ngAnimateSwap-directive" module="ngAnimateSwapExample" <add> * deps="angular-animate.js" <add> * animations="true" fixBase="true"> <add> * <file name="index.html"> <add> * <div class="container" ng-controller="AppCtrl"> <add> * <div ng-animate-swap="number" class="cell swap-animation" ng-class="colorClass(number)"> <add> * {{ number }} <add> * </div> <add> * </div> <add> * </file> <add> * <file name="script.js"> <add> * angular.module('ngAnimateSwapExample', ['ngAnimate']) <add> * .controller('AppCtrl', ['$scope', '$interval', function($scope, $interval) { <add> * $scope.number = 0; <add> * $interval(function() { <add> * $scope.number++; <add> * }, 1000); <add> * <add> * var colors = ['red','blue','green','yellow','orange']; <add> * $scope.colorClass = function(number) { <add> * return colors[number % colors.length]; <add> * }; <add> * }]); <add> * </file> <add> * <file name="animations.css"> <add> * .container { <add> * height:250px; <add> * width:250px; <add> * position:relative; <add> * overflow:hidden; <add> * border:2px solid black; <add> * } <add> * .container .cell { <add> * font-size:150px; <add> * text-align:center; <add> * line-height:250px; <add> * position:absolute; <add> * top:0; <add> * left:0; <add> * right:0; <add> * border-bottom:2px solid black; <add> * } <add> * .swap-animation.ng-enter, .swap-animation.ng-leave { <add> * transition:0.5s linear all; <add> * } <add> * .swap-animation.ng-enter { <add> * top:-250px; <add> * } <add> * .swap-animation.ng-enter-active { <add> * top:0px; <add> * } <add> * .swap-animation.ng-leave { <add> * top:0px; <add> * } <add> * .swap-animation.ng-leave-active { <add> * top:250px; <add> * } <add> * .red { background:red; } <add> * .green { background:green; } <add> * .blue { background:blue; } <add> * .yellow { background:yellow; } <add> * .orange { background:orange; } <add> * </file> <add> * </example> <add> */ <add>var ngAnimateSwapDirective = ['$animate', '$rootScope', function($animate, $rootScope) { <add> return { <add> restrict: 'A', <add> transclude: 'element', <add> terminal: true, <add> priority: 600, // we use 600 here to ensure that the directive is caught before others <add> link: function(scope, $element, attrs, ctrl, $transclude) { <add> var previousElement, previousScope; <add> scope.$watchCollection(attrs.ngAnimateSwap || attrs['for'], function(value) { <add> if (previousElement) { <add> $animate.leave(previousElement); <add> } <add> if (previousScope) { <add> previousScope.$destroy(); <add> previousScope = null; <add> } <add> if (value || value === 0) { <add> previousScope = scope.$new(); <add> $transclude(previousScope, function(element) { <add> previousElement = element; <add> $animate.enter(element, null, $element); <add> }); <add> } <add> }); <add> } <add> }; <add>}]; <ide><path>test/ngAnimate/ngAnimateSwapSpec.js <add>'use strict'; <add> <add>describe("ngAnimateSwap", function() { <add> <add> beforeEach(module('ngAnimate')); <add> beforeEach(module('ngAnimateMock')); <add> <add> var element; <add> afterEach(function() { <add> dealoc(element); <add> }); <add> <add> var $rootScope, $compile, $animate; <add> beforeEach(inject(function(_$rootScope_, _$animate_, _$compile_) { <add> $rootScope = _$rootScope_; <add> $animate = _$animate_; <add> $compile = _$compile_; <add> <add> $animate.enabled(false); <add> })); <add> <add> <add> it('should render a new container when the expression changes', inject(function() { <add> element = $compile('<div><div ng-animate-swap="exp">{{ exp }}</div></div>')($rootScope); <add> $rootScope.$digest(); <add> <add> var first = element.find('div')[0]; <add> expect(first).toBeFalsy(); <add> <add> $rootScope.exp = 'yes'; <add> $rootScope.$digest(); <add> <add> var second = element.find('div')[0]; <add> expect(second.textContent).toBe('yes'); <add> <add> $rootScope.exp = 'super'; <add> $rootScope.$digest(); <add> <add> var third = element.find('div')[0]; <add> expect(third.textContent).toBe('super'); <add> expect(third).not.toEqual(second); <add> expect(second.parentNode).toBeFalsy(); <add> })); <add> <add> it('should render a new container only when the expression property changes', inject(function() { <add> element = $compile('<div><div ng-animate-swap="exp.prop">{{ exp.value }}</div></div>')($rootScope); <add> $rootScope.exp = { <add> prop: 'hello', <add> value: 'world' <add> }; <add> $rootScope.$digest(); <add> <add> var one = element.find('div')[0]; <add> expect(one.textContent).toBe('world'); <add> <add> $rootScope.exp.value = 'planet'; <add> $rootScope.$digest(); <add> <add> var two = element.find('div')[0]; <add> expect(two.textContent).toBe('planet'); <add> expect(two).toBe(one); <add> <add> $rootScope.exp.prop = 'goodbye'; <add> $rootScope.$digest(); <add> <add> var three = element.find('div')[0]; <add> expect(three.textContent).toBe('planet'); <add> expect(three).not.toBe(two); <add> })); <add> <add> it('should watch the expression as a collection', inject(function() { <add> element = $compile('<div><div ng-animate-swap="exp">{{ exp.a }} {{ exp.b }} {{ exp.c }}</div></div>')($rootScope); <add> $rootScope.exp = { <add> a: 1, <add> b: 2 <add> }; <add> $rootScope.$digest(); <add> <add> var one = element.find('div')[0]; <add> expect(one.textContent.trim()).toBe('1 2'); <add> <add> $rootScope.exp.a++; <add> $rootScope.$digest(); <add> <add> var two = element.find('div')[0]; <add> expect(two.textContent.trim()).toBe('2 2'); <add> expect(two).not.toEqual(one); <add> <add> $rootScope.exp.c = 3; <add> $rootScope.$digest(); <add> <add> var three = element.find('div')[0]; <add> expect(three.textContent.trim()).toBe('2 2 3'); <add> expect(three).not.toEqual(two); <add> <add> $rootScope.exp = { c: 4 }; <add> $rootScope.$digest(); <add> <add> var four = element.find('div')[0]; <add> expect(four.textContent.trim()).toBe('4'); <add> expect(four).not.toEqual(three); <add> })); <add> <add> they('should consider $prop as a falsy value', [false, undefined, null], function(value) { <add> inject(function() { <add> element = $compile('<div><div ng-animate-swap="value">{{ value }}</div></div>')($rootScope); <add> $rootScope.value = true; <add> $rootScope.$digest(); <add> <add> var one = element.find('div')[0]; <add> expect(one).toBeTruthy(); <add> <add> $rootScope.value = value; <add> $rootScope.$digest(); <add> <add> var two = element.find('div')[0]; <add> expect(two).toBeFalsy(); <add> }); <add> }); <add> <add> it('should consider "0" as a truthy value', inject(function() { <add> element = $compile('<div><div ng-animate-swap="value">{{ value }}</div></div>')($rootScope); <add> $rootScope.$digest(); <add> <add> var one = element.find('div')[0]; <add> expect(one).toBeFalsy(); <add> <add> $rootScope.value = 0; <add> $rootScope.$digest(); <add> <add> var two = element.find('div')[0]; <add> expect(two).toBeTruthy(); <add> })); <add> <add> <add> describe("animations", function() { <add> it('should trigger a leave animation followed by an enter animation upon swap', <add> inject(function() { <add> <add> element = $compile('<div><div ng-animate-swap="exp">{{ exp }}</div></div>')($rootScope); <add> $rootScope.exp = 1; <add> $rootScope.$digest(); <add> <add> var first = $animate.queue.shift(); <add> expect(first.event).toBe('enter'); <add> expect($animate.queue.length).toBe(0); <add> <add> $rootScope.exp = 2; <add> $rootScope.$digest(); <add> <add> var second = $animate.queue.shift(); <add> expect(second.event).toBe('leave'); <add> <add> var third = $animate.queue.shift(); <add> expect(third.event).toBe('enter'); <add> expect($animate.queue.length).toBe(0); <add> <add> $rootScope.exp = false; <add> $rootScope.$digest(); <add> <add> var forth = $animate.queue.shift(); <add> expect(forth.event).toBe('leave'); <add> expect($animate.queue.length).toBe(0); <add> })); <add> }); <add>});
4
Text
Text
remove snippet that is not recommended.
b9b35d406cd95e1cfeff03e7e5e4640db39eb300
<ide><path>docs/api-reference/next.config.js/custom-webpack-config.md <ide> In order to extend our usage of `webpack`, you can define a function that extend <ide> ```js <ide> module.exports = { <ide> webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => { <del> // Note: we provide webpack above so you should not `require` it <del> // Perform customizations to webpack config <del> config.plugins.push(new webpack.IgnorePlugin(/\/__tests__\//)) <del> <ide> // Important: return the modified config <ide> return config <ide> },
1
Python
Python
fix bug when checking for existence of a variable
93d2a1626d4da4ae372f5c5edb47a12afc388d33
<ide><path>airflow/models/variable.py <ide> def update( <ide> """ <ide> cls.check_for_write_conflict(key) <ide> <del> if cls.get_variable_from_secrets(key) is None: <add> if cls.get_variable_from_secrets(key=key) is None: <ide> raise KeyError(f'Variable {key} does not exist') <ide> <ide> obj = session.query(cls).filter(cls.key == key).first() <ide> def rotate_fernet_key(self): <ide> if self._val and self.is_encrypted: <ide> self._val = fernet.rotate(self._val.encode('utf-8')).decode() <ide> <add> @staticmethod <ide> def check_for_write_conflict(key: str) -> None: <ide> """ <ide> Logs a warning if a variable exists outside of the metastore. <ide><path>tests/secrets/test_local_filesystem.py <ide> import pytest <ide> from parameterized import parameterized <ide> <add>from airflow.configuration import ensure_secrets_loaded <ide> from airflow.exceptions import AirflowException, AirflowFileParseException, ConnectionNotUnique <add>from airflow.models import Variable <ide> from airflow.secrets import local_filesystem <ide> from airflow.secrets.local_filesystem import LocalFilesystemBackend <add>from tests.test_utils.config import conf_vars <ide> <ide> <ide> @contextmanager <ide> def test_should_read_variable(self): <ide> assert "VAL_A" == backend.get_variable("KEY_A") <ide> assert backend.get_variable("KEY_B") is None <ide> <add> @conf_vars( <add> { <add> ( <add> "secrets", <add> "backend", <add> ): "airflow.secrets.local_filesystem.LocalFilesystemBackend", <add> ("secrets", "backend_kwargs"): '{"variables_file_path": "var.env"}', <add> } <add> ) <add> def test_load_secret_backend_LocalFilesystemBackend(self): <add> with mock_local_file("KEY_A=VAL_A"): <add> backends = ensure_secrets_loaded() <add> <add> backend_classes = [backend.__class__.__name__ for backend in backends] <add> assert 'LocalFilesystemBackend' in backend_classes <add> assert Variable.get("KEY_A") == "VAL_A" <add> <ide> def test_should_read_connection(self): <ide> with NamedTemporaryFile(suffix=".env") as tmp_file: <ide> tmp_file.write(b"CONN_A=mysql://host_a") <ide> tmp_file.flush() <ide> backend = LocalFilesystemBackend(connections_file_path=tmp_file.name) <del> assert ["mysql://host_a"] == [conn.get_uri() for conn in backend.get_connections("CONN_A")] <add> assert "mysql://host_a" == backend.get_connection("CONN_A").get_uri() <ide> assert backend.get_variable("CONN_B") is None <ide> <ide> def test_files_are_optional(self): <ide> backend = LocalFilesystemBackend() <del> assert [] == backend.get_connections("CONN_A") <add> assert None is backend.get_connection("CONN_A") <ide> assert backend.get_variable("VAR_A") is None <ide><path>tests/secrets/test_secrets.py <ide> def test_get_variable_first_try(self, mock_env_get, mock_meta_get): <ide> Test if Variable is present in Environment Variable, it does not look for it in <ide> Metastore DB <ide> """ <del> mock_env_get.return_value = [["something"]] # returns nonempty list <add> mock_env_get.return_value = "something" <ide> Variable.get_variable_from_secrets("fake_var_key") <ide> mock_env_get.assert_called_once_with(key="fake_var_key") <del> mock_meta_get.not_called() <add> mock_meta_get.assert_not_called() <ide> <ide> def test_backend_fallback_to_default_var(self): <ide> """ <ide> def test_backend_fallback_to_default_var(self): <ide> """ <ide> variable_value = Variable.get(key="test_var", default_var="new") <ide> assert "new" == variable_value <add> <add> @conf_vars( <add> { <add> ( <add> "secrets", <add> "backend", <add> ): "airflow.providers.amazon.aws.secrets.systems_manager.SystemsManagerParameterStoreBackend", <add> ("secrets", "backend_kwargs"): '{"variables_prefix": "/airflow", "profile_name": null}', <add> } <add> ) <add> @mock.patch.dict( <add> 'os.environ', <add> { <add> 'AIRFLOW_VAR_MYVAR': 'a_venv_value', <add> }, <add> ) <add> @mock.patch("airflow.secrets.metastore.MetastoreBackend.get_variable") <add> @mock.patch( <add> "airflow.providers.amazon.aws.secrets.systems_manager." <add> "SystemsManagerParameterStoreBackend.get_variable" <add> ) <add> def test_backend_variable_order(self, mock_secret_get, mock_meta_get): <add> backends = ensure_secrets_loaded() <add> backend_classes = [backend.__class__.__name__ for backend in backends] <add> assert 'SystemsManagerParameterStoreBackend' in backend_classes <add> <add> mock_secret_get.return_value = None <add> mock_meta_get.return_value = None <add> <add> assert "a_venv_value" == Variable.get(key="MYVAR") <add> mock_secret_get.assert_called_with(key="MYVAR") <add> mock_meta_get.assert_not_called() <add> <add> mock_secret_get.return_value = None <add> mock_meta_get.return_value = "a_metastore_value" <add> assert "a_metastore_value" == Variable.get(key="not_myvar") <add> mock_meta_get.assert_called_once_with(key="not_myvar") <add> <add> mock_secret_get.return_value = "a_secret_value" <add> assert "a_secret_value" == Variable.get(key="not_myvar")
3
Go
Go
remove unnecessary cmdwithargs
c0d2f7b33869cf749efcbab003bdb9bd2f665cec
<ide><path>integration-cli/daemon.go <ide> func (d *Daemon) getBaseDeviceSize(c *check.C) int64 { <ide> <ide> // Cmd will execute a docker CLI command against this Daemon. <ide> // Example: d.Cmd("version") will run docker -H unix://path/to/unix.sock version <del>func (d *Daemon) Cmd(name string, arg ...string) (string, error) { <del> args := []string{"--host", d.sock(), name} <del> args = append(args, arg...) <del> c := exec.Command(dockerBinary, args...) <add>func (d *Daemon) Cmd(args ...string) (string, error) { <add> c := exec.Command(dockerBinary, d.prependHostArg(args)...) <ide> b, err := c.CombinedOutput() <ide> return string(b), err <ide> } <ide> <del>// CmdWithArgs will execute a docker CLI command against a daemon with the <del>// given additional arguments <del>func (d *Daemon) CmdWithArgs(daemonArgs []string, name string, arg ...string) (string, error) { <del> args := append(daemonArgs, name) <del> args = append(args, arg...) <del> c := exec.Command(dockerBinary, args...) <del> b, err := c.CombinedOutput() <del> return string(b), err <add>func (d *Daemon) prependHostArg(args []string) []string { <add> for _, arg := range args { <add> if arg == "--host" || arg == "-H" { <add> return args <add> } <add> } <add> return append([]string{"--host", d.sock()}, args...) <ide> } <ide> <ide> // SockRequest executes a socket request on a daemon and returns statuscode and output. <ide><path>integration-cli/daemon_swarm_hack.go <ide> func (s *DockerSwarmSuite) getDaemon(c *check.C, nodeID string) *SwarmDaemon { <ide> } <ide> <ide> // nodeCmd executes a command on a given node via the normal docker socket <del>func (s *DockerSwarmSuite) nodeCmd(c *check.C, id, cmd string, args ...string) (string, error) { <del> return s.getDaemon(c, id).Cmd(cmd, args...) <add>func (s *DockerSwarmSuite) nodeCmd(c *check.C, id string, args ...string) (string, error) { <add> return s.getDaemon(c, id).Cmd(args...) <ide> } <ide><path>integration-cli/docker_cli_daemon_test.go <ide> func (s *DockerDaemonSuite) TestDaemonICCPing(c *check.C) { <ide> <ide> // But, Pinging external or a Host interface must succeed <ide> pingCmd := fmt.Sprintf("ping -c 1 %s -W 1", ip.String()) <del> runArgs := []string{"--rm", "busybox", "sh", "-c", pingCmd} <del> _, err = d.Cmd("run", runArgs...) <add> runArgs := []string{"run", "--rm", "busybox", "sh", "-c", pingCmd} <add> _, err = d.Cmd(runArgs...) <ide> c.Assert(err, check.IsNil) <ide> } <ide> <ide> func (s *DockerDaemonSuite) TestHttpsInfo(c *check.C) { <ide> c.Fatalf("Could not start daemon with busybox: %v", err) <ide> } <ide> <del> daemonArgs := []string{"--host", testDaemonHTTPSAddr, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/client-cert.pem", "--tlskey", "fixtures/https/client-key.pem"} <del> out, err := s.d.CmdWithArgs(daemonArgs, "info") <add> args := []string{ <add> "--host", testDaemonHTTPSAddr, <add> "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", <add> "--tlscert", "fixtures/https/client-cert.pem", <add> "--tlskey", "fixtures/https/client-key.pem", <add> "info", <add> } <add> out, err := s.d.Cmd(args...) <ide> if err != nil { <ide> c.Fatalf("Error Occurred: %s and output: %s", err, out) <ide> } <ide> func (s *DockerDaemonSuite) TestHttpsRun(c *check.C) { <ide> c.Fatalf("Could not start daemon with busybox: %v", err) <ide> } <ide> <del> daemonArgs := []string{"--host", testDaemonHTTPSAddr, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/client-cert.pem", "--tlskey", "fixtures/https/client-key.pem"} <del> out, err := s.d.CmdWithArgs(daemonArgs, "run", "busybox", "echo", "TLS response") <add> args := []string{ <add> "--host", testDaemonHTTPSAddr, <add> "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", <add> "--tlscert", "fixtures/https/client-cert.pem", <add> "--tlskey", "fixtures/https/client-key.pem", <add> "run", "busybox", "echo", "TLS response", <add> } <add> out, err := s.d.Cmd(args...) <ide> if err != nil { <ide> c.Fatalf("Error Occurred: %s and output: %s", err, out) <ide> } <ide> func (s *DockerDaemonSuite) TestHttpsInfoRogueCert(c *check.C) { <ide> c.Fatalf("Could not start daemon with busybox: %v", err) <ide> } <ide> <del> daemonArgs := []string{"--host", testDaemonHTTPSAddr, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/client-rogue-cert.pem", "--tlskey", "fixtures/https/client-rogue-key.pem"} <del> out, err := s.d.CmdWithArgs(daemonArgs, "info") <add> args := []string{ <add> "--host", testDaemonHTTPSAddr, <add> "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", <add> "--tlscert", "fixtures/https/client-rogue-cert.pem", <add> "--tlskey", "fixtures/https/client-rogue-key.pem", <add> "info", <add> } <add> out, err := s.d.Cmd(args...) <ide> if err == nil || !strings.Contains(out, errBadCertificate) { <ide> c.Fatalf("Expected err: %s, got instead: %s and output: %s", errBadCertificate, err, out) <ide> } <ide> func (s *DockerDaemonSuite) TestHttpsInfoRogueServerCert(c *check.C) { <ide> c.Fatalf("Could not start daemon with busybox: %v", err) <ide> } <ide> <del> daemonArgs := []string{"--host", testDaemonRogueHTTPSAddr, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/client-rogue-cert.pem", "--tlskey", "fixtures/https/client-rogue-key.pem"} <del> out, err := s.d.CmdWithArgs(daemonArgs, "info") <add> args := []string{ <add> "--host", testDaemonRogueHTTPSAddr, <add> "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", <add> "--tlscert", "fixtures/https/client-rogue-cert.pem", <add> "--tlskey", "fixtures/https/client-rogue-key.pem", <add> "info", <add> } <add> out, err := s.d.Cmd(args...) <ide> if err == nil || !strings.Contains(out, errCaUnknown) { <ide> c.Fatalf("Expected err: %s, got instead: %s and output: %s", errCaUnknown, err, out) <ide> } <ide> func (s *DockerDaemonSuite) TestDaemonRestartContainerLinksRestart(c *check.C) { <ide> parent2Args = append([]string{"run", "-d"}, parent2Args...) <ide> parent2Args = append(parent2Args, []string{"--name=parent2", "--restart=always", "busybox", "top"}...) <ide> <del> _, err = d.Cmd(parent1Args[0], parent1Args[1:]...) <add> _, err = d.Cmd(parent1Args...) <ide> c.Assert(err, check.IsNil) <del> _, err = d.Cmd(parent2Args[0], parent2Args[1:]...) <add> _, err = d.Cmd(parent2Args...) <ide> c.Assert(err, check.IsNil) <ide> <ide> err = d.Stop() <ide><path>integration-cli/docker_cli_service_update_test.go <ide> func (s *DockerSwarmSuite) TestServiceUpdatePort(c *check.C) { <ide> d := s.AddDaemon(c, true, true) <ide> <ide> serviceName := "TestServiceUpdatePort" <del> serviceArgs := append([]string{"create", "--name", serviceName, "-p", "8080:8081", defaultSleepImage}, defaultSleepCommand...) <add> serviceArgs := append([]string{"service", "create", "--name", serviceName, "-p", "8080:8081", defaultSleepImage}, defaultSleepCommand...) <ide> <ide> // Create a service with a port mapping of 8080:8081. <del> out, err := d.Cmd("service", serviceArgs...) <add> out, err := d.Cmd(serviceArgs...) <ide> c.Assert(err, checker.IsNil) <ide> waitAndAssert(c, defaultReconciliationTimeout, d.checkActiveContainerCount, checker.Equals, 1) <ide> <ide><path>integration-cli/docker_cli_stack_test.go <ide> import ( <ide> func (s *DockerSwarmSuite) TestStackRemove(c *check.C) { <ide> d := s.AddDaemon(c, true, true) <ide> <del> stackArgs := append([]string{"remove", "UNKNOWN_STACK"}) <add> stackArgs := append([]string{"stack", "remove", "UNKNOWN_STACK"}) <ide> <del> out, err := d.Cmd("stack", stackArgs...) <add> out, err := d.Cmd(stackArgs...) <ide> c.Assert(err, checker.IsNil) <ide> c.Assert(out, check.Equals, "Nothing found in stack: UNKNOWN_STACK\n") <ide> } <ide> <ide> func (s *DockerSwarmSuite) TestStackTasks(c *check.C) { <ide> d := s.AddDaemon(c, true, true) <ide> <del> stackArgs := append([]string{"ps", "UNKNOWN_STACK"}) <add> stackArgs := append([]string{"stack", "ps", "UNKNOWN_STACK"}) <ide> <del> out, err := d.Cmd("stack", stackArgs...) <add> out, err := d.Cmd(stackArgs...) <ide> c.Assert(err, checker.IsNil) <ide> c.Assert(out, check.Equals, "Nothing found in stack: UNKNOWN_STACK\n") <ide> } <ide> <ide> func (s *DockerSwarmSuite) TestStackServices(c *check.C) { <ide> d := s.AddDaemon(c, true, true) <ide> <del> stackArgs := append([]string{"services", "UNKNOWN_STACK"}) <add> stackArgs := append([]string{"stack", "services", "UNKNOWN_STACK"}) <ide> <del> out, err := d.Cmd("stack", stackArgs...) <add> out, err := d.Cmd(stackArgs...) <ide> c.Assert(err, checker.IsNil) <ide> c.Assert(out, check.Equals, "Nothing found in stack: UNKNOWN_STACK\n") <ide> } <ide><path>integration-cli/docker_hub_pull_suite_test.go <ide> func (s *DockerHubPullSuite) SetUpTest(c *check.C) { <ide> func (s *DockerHubPullSuite) TearDownTest(c *check.C) { <ide> out := s.Cmd(c, "images", "-aq") <ide> images := strings.Split(out, "\n") <del> images = append([]string{"-f"}, images...) <del> s.d.Cmd("rmi", images...) <add> images = append([]string{"rmi", "-f"}, images...) <add> s.d.Cmd(images...) <ide> s.ds.TearDownTest(c) <ide> } <ide>
6
Mixed
Text
fix i.e. typos in markdown and ruby
6cf394c236d7a3ab067c8c408e5437afb1d75232
<ide><path>activerecord/CHANGELOG.md <ide> <ide> * Add option to run `default_scope` on all queries. <ide> <del> Previously, a `default_scope` would only run on select or insert queries. In some cases, like non-Rails tenant sharding solutions, it may be desirable to run `default_scope` on all queries in order to ensure queries are including a foreign key for the shard (ie `blog_id`). <add> Previously, a `default_scope` would only run on select or insert queries. In some cases, like non-Rails tenant sharding solutions, it may be desirable to run `default_scope` on all queries in order to ensure queries are including a foreign key for the shard (i.e. `blog_id`). <ide> <ide> Now applications can add an option to run on all queries including select, insert, delete, and update by adding an `all_queries` option to the default scope definition. <ide> <ide><path>activerecord/lib/active_record/database_configurations/url_config.rb <ide> class DatabaseConfigurations <ide> # <ide> # ==== Options <ide> # <del> # * <tt>:env_name</tt> - The Rails environment, ie "development". <add> # * <tt>:env_name</tt> - The Rails environment, i.e. "development". <ide> # * <tt>:name</tt> - The db config name. In a standard two-tier <ide> # database configuration this will default to "primary". In a multiple <ide> # database three-tier database configuration this corresponds to the name <ide><path>guides/source/active_record_multiple_databases.md <ide> the handler. Call `connection_handler.all_connection_pools` to use this. In most <ide> you'll want writing or reading pools with `connection_handler.connection_pool_list(:writing)` or <ide> `connection_handler.connection_pool_list(:reading)`. <ide> * If you turn off `legacy_connection_handling` in your application, any method that's unsupported <del>will raise an error (ie `connection_handlers=`). <add>will raise an error (i.e. `connection_handlers=`). <ide> <ide> ## Granular Database Connection Switching <ide> <ide><path>guides/source/api_app.md <ide> The following middlewares, used for session management, are excluded from API ap <ide> The trick to adding these back in is that, by default, they are passed `session_options` <ide> when added (including the session key), so you can't just add a `session_store.rb` initializer, add <ide> `use ActionDispatch::Session::CookieStore` and have sessions functioning as usual. (To be clear: sessions <del>may work, but your session options will be ignored - i.e the session key will default to `_session_id`) <add>may work, but your session options will be ignored - i.e. the session key will default to `_session_id`) <ide> <ide> Instead of the initializer, you'll have to set the relevant options somewhere before your middleware is <ide> built (like `config/application.rb`) and pass them to your preferred middleware, like this:
4
PHP
PHP
add postgres support for collation() on columns
9775c6079e27441d20b2fca4c08c145c8c2286ba
<ide><path>src/Illuminate/Database/Schema/ColumnDefinition.php <ide> * @method ColumnDefinition autoIncrement() Set INTEGER columns as auto-increment (primary key) <ide> * @method ColumnDefinition change() Change the column <ide> * @method ColumnDefinition charset(string $charset) Specify a character set for the column (MySQL) <del> * @method ColumnDefinition collation(string $collation) Specify a collation for the column (MySQL/SQL Server) <add> * @method ColumnDefinition collation(string $collation) Specify a collation for the column (MySQL/PostgreSQL/SQL Server) <ide> * @method ColumnDefinition comment(string $comment) Add a comment to the column (MySQL) <ide> * @method ColumnDefinition default(mixed $value) Specify a "default" value for the column <ide> * @method ColumnDefinition first() Place the column "first" in the table (MySQL) <ide><path>src/Illuminate/Database/Schema/Grammars/PostgresGrammar.php <ide> class PostgresGrammar extends Grammar <ide> * <ide> * @var array <ide> */ <del> protected $modifiers = ['Increment', 'Nullable', 'Default']; <add> protected $modifiers = ['Collate', 'Increment', 'Nullable', 'Default']; <ide> <ide> /** <ide> * The columns available as serials. <ide> private function formatPostGisType(string $type) <ide> return "geography($type, 4326)"; <ide> } <ide> <add> /** <add> * Get the SQL for a collation column modifier. <add> * <add> * @param \Illuminate\Database\Schema\Blueprint $blueprint <add> * @param \Illuminate\Support\Fluent $column <add> * @return string|null <add> */ <add> protected function modifyCollate(Blueprint $blueprint, Fluent $column) <add> { <add> if (! is_null($column->collation)) { <add> return ' collate '.$this->wrapValue($column->collation); <add> } <add> } <add> <ide> /** <ide> * Get the SQL for a nullable column modifier. <ide> * <ide><path>tests/Database/DatabasePostgresSchemaGrammarTest.php <ide> public function testBasicCreateTable() <ide> $blueprint->create(); <ide> $blueprint->increments('id'); <ide> $blueprint->string('email'); <add> $blueprint->string('name')->collation('nb_NO.utf8'); <ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); <ide> <ide> $this->assertCount(1, $statements); <del> $this->assertEquals('create table "users" ("id" serial primary key not null, "email" varchar(255) not null)', $statements[0]); <add> $this->assertEquals('create table "users" ("id" serial primary key not null, "email" varchar(255) not null, "name" varchar(255) collate "nb_NO.utf8" not null)', $statements[0]); <ide> <ide> $blueprint = new Blueprint('users'); <ide> $blueprint->increments('id');
3
Java
Java
fix a nodes crash when removing children
e5c81e1c1bebd0cd6bcc9ac2ed453eec353312f8
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/FlatUIImplementation.java <ide> import javax.annotation.Nullable; <ide> <ide> import java.util.ArrayList; <add>import java.util.Arrays; <ide> import java.util.List; <ide> <ide> import com.facebook.infer.annotation.Assertions; <ide> private void removeChildren( <ide> int moveFromIndex = mMoveProxy.size() - 1; <ide> int moveFromChildIndex = (moveFromIndex == -1) ? -1 : mMoveProxy.getMoveFrom(moveFromIndex); <ide> <add> int numToRemove = removeFrom == null ? 0 : removeFrom.size(); <add> int[] indicesToRemove = new int[numToRemove]; <add> if (numToRemove > 0) { <add> Assertions.assertNotNull(removeFrom); <add> for (int i = 0; i < numToRemove; i++) { <add> int indexToRemove = removeFrom.getInt(i); <add> indicesToRemove[i] = indexToRemove; <add> } <add> } <add> <add> // this isn't guaranteed to be sorted actually <add> Arrays.sort(indicesToRemove); <add> <ide> int removeFromIndex; <ide> int removeFromChildIndex; <ide> if (removeFrom == null) { <ide> removeFromIndex = -1; <ide> removeFromChildIndex = -1; <ide> } else { <del> removeFromIndex = removeFrom.size() - 1; <del> removeFromChildIndex = removeFrom.getInt(removeFromIndex); <add> removeFromIndex = indicesToRemove.length - 1; <add> removeFromChildIndex = indicesToRemove[removeFromIndex]; <ide> } <ide> <ide> // both moveFrom and removeFrom are already sorted, but combined order is not sorted. Use <ide> private void removeChildren( <ide> prevIndex = removeFromChildIndex; <ide> <ide> --removeFromIndex; <del> removeFromChildIndex = (removeFromIndex == -1) ? -1 : removeFrom.getInt(removeFromIndex); <add> removeFromChildIndex = (removeFromIndex == -1) ? -1 : indicesToRemove[removeFromIndex]; <ide> } else { <ide> // moveFromChildIndex == removeFromChildIndex can only be if both are equal to -1 <ide> // which means that we exhausted both arrays, and all children are removed.
1
Python
Python
add no_cuda args in extract_features
27ee0fff3ce5f9d1c1169061d49200745ea3ba4e
<ide><path>examples/extract_features.py <ide> def main(): <ide> type=int, <ide> default=-1, <ide> help = "local_rank for distributed training on gpus") <add> parser.add_argument("--no_cuda", <add> default=False, <add> action='store_true', <add> help="Whether not to use CUDA when available") <ide> <ide> args = parser.parse_args() <ide>
1
PHP
PHP
add haserror and error to entitycontext
d7d94e774bde40b4bd2d92fad01186ced3daa8e6
<ide><path>src/View/Form/EntityContext.php <ide> public function attributes($field) { <ide> return array_intersect_key($column, $whitelist); <ide> } <ide> <add>/** <add> * Check whether or not a field has an error attached to it <add> * <add> * @param string $field A dot separated path to check errors on. <add> * @return boolean Returns true if the errors for the field are not empty. <add> */ <ide> public function hasError($field) { <add> $parts = explode('.', $field); <add> list($entity, $prop) = $this->_getEntity($parts); <add> if (!$entity) { <add> return false; <add> } <add> $errors = $entity->errors(array_pop($parts)); <add> return !empty($errors); <ide> } <ide> <add> <add>/** <add> * Get the errors for a given field <add> * <add> * @param string $field A dot separated path to check errors on. <add> * @return array|null Either an array of errors. Null will be returned when the <add> * field path is undefined or there is no error. <add> */ <ide> public function error($field) { <add> $parts = explode('.', $field); <add> list($entity, $prop) = $this->_getEntity($parts); <add> if (!$entity) { <add> return false; <add> } <add> return $entity->errors(array_pop($parts)); <ide> } <ide> <ide> } <ide><path>tests/TestCase/View/Form/EntityContextTest.php <ide> public function testAttributes() { <ide> $this->assertEquals($expected, $context->attributes('user.rating')); <ide> } <ide> <add>/** <add> * Test hasError <add> * <add> * @return void <add> */ <add> public function testHasError() { <add> $this->_setupTables(); <add> <add> $row = new Entity([ <add> 'title' => 'My title', <add> 'user' => new Entity(['username' => 'Mark']), <add> ]); <add> $row->errors('title', []); <add> $row->errors('body', 'Gotta have one'); <add> $row->errors('user_id', ['Required field']); <add> $context = new EntityContext($this->request, [ <add> 'entity' => $row, <add> 'table' => 'Articles', <add> ]); <add> <add> $this->assertFalse($context->hasError('title')); <add> $this->assertFalse($context->hasError('nope')); <add> $this->assertTrue($context->hasError('body')); <add> $this->assertTrue($context->hasError('user_id')); <add> } <add> <add>/** <add> * Test hasError on associated records <add> * <add> * @return void <add> */ <add> public function testHasErrorAssociated() { <add> $this->_setupTables(); <add> <add> $row = new Entity([ <add> 'title' => 'My title', <add> 'user' => new Entity(['username' => 'Mark']), <add> ]); <add> $row->errors('title', []); <add> $row->errors('body', 'Gotta have one'); <add> $row->user->errors('username', ['Required']); <add> $context = new EntityContext($this->request, [ <add> 'entity' => $row, <add> 'table' => 'Articles', <add> ]); <add> <add> $this->assertTrue($context->hasError('user.username')); <add> $this->assertFalse($context->hasError('user.nope')); <add> $this->assertFalse($context->hasError('no.nope')); <add> } <add> <add>/** <add> * Test error <add> * <add> * @return void <add> */ <add> public function testError() { <add> $this->_setupTables(); <add> <add> $row = new Entity([ <add> 'title' => 'My title', <add> 'user' => new Entity(['username' => 'Mark']), <add> ]); <add> $row->errors('title', []); <add> $row->errors('body', 'Gotta have one'); <add> $row->errors('user_id', ['Required field']); <add> <add> $row->user->errors('username', ['Required']); <add> <add> $context = new EntityContext($this->request, [ <add> 'entity' => $row, <add> 'table' => 'Articles', <add> ]); <add> <add> $this->assertEquals([], $context->error('title')); <add> <add> $expected = ['Gotta have one']; <add> $this->assertEquals($expected, $context->error('body')); <add> <add> $expected = ['Required']; <add> $this->assertEquals($expected, $context->error('user.username')); <add> } <add> <ide> /** <ide> * Setup tables for tests. <ide> *
2
Javascript
Javascript
add uiexplorer example of swipeablelistview
7971cca4f05109c4420edbaeb4d205217aeb83dc
<ide><path>Examples/UIExplorer/js/SwipeableListViewExample.js <add>/** <add> * The examples provided by Facebook are for non-commercial testing and <add> * evaluation purposes only. <add> * <add> * Facebook reserves all rights not expressly granted. <add> * <add> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS <add> * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, <add> * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL <add> * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN <add> * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN <add> * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. <add> * <add> * @flow <add> */ <add>'use strict'; <add> <add>var React = require('react'); <add>var ReactNative = require('react-native'); <add>var { <add> Image, <add> SwipeableListView, <add> TouchableHighlight, <add> StyleSheet, <add> RecyclerViewBackedScrollView, <add> Text, <add> View, <add> Alert, <add>} = ReactNative; <add> <add>var UIExplorerPage = require('./UIExplorerPage'); <add> <add>var SwipeableListViewSimpleExample = React.createClass({ <add> statics: { <add> title: '<SwipeableListView>', <add> description: 'Performant, scrollable, swipeable list of data.' <add> }, <add> <add> getInitialState: function() { <add> var ds = SwipeableListView.getNewDataSource(); <add> return { <add> dataSource: ds.cloneWithRowsAndSections(...this._genDataSource({})), <add> }; <add> }, <add> <add> _pressData: ({}: {[key: number]: boolean}), <add> <add> componentWillMount: function() { <add> this._pressData = {}; <add> }, <add> <add> render: function() { <add> return ( <add> <UIExplorerPage <add> title={this.props.navigator ? null : '<SwipeableListView>'} <add> noSpacer={true} <add> noScroll={true}> <add> <SwipeableListView <add> dataSource={this.state.dataSource} <add> maxSwipeDistance={100} <add> renderQuickActions={(rowData: Object, sectionID: string, rowID: string) => { <add> return (<View style={styles.actionsContainer}> <add> <TouchableHighlight onPress={() => { <add> Alert.alert('Tips', 'You could do something with this row: ' + rowData.text); <add> }}> <add> <Text>Remove</Text> <add> </TouchableHighlight> <add> </View>); <add> }} <add> renderRow={this._renderRow} <add> renderScrollComponent={props => <RecyclerViewBackedScrollView {...props} />} <add> renderSeparator={this._renderSeperator} <add> /> <add> </UIExplorerPage> <add> ); <add> }, <add> <add> _renderRow: function(rowData: Object, sectionID: number, rowID: number, highlightRow: (sectionID: number, rowID: number) => void) { <add> var rowHash = Math.abs(hashCode(rowData.id)); <add> var imgSource = THUMB_URLS[rowHash % THUMB_URLS.length]; <add> return ( <add> <TouchableHighlight onPress={() => {}}> <add> <View> <add> <View style={styles.row}> <add> <Image style={styles.thumb} source={imgSource} /> <add> <Text style={styles.text}> <add> {rowData.id + ' - ' + LOREM_IPSUM.substr(0, rowHash % 301 + 10)} <add> </Text> <add> </View> <add> </View> <add> </TouchableHighlight> <add> ); <add> }, <add> <add> _genDataSource: function(pressData: {[key: number]: boolean}): Array<any> { <add> var dataBlob = {}; <add> var sectionIDs = ['Section 0']; <add> var rowIDs = [[]]; <add> /** <add> * dataBlob example below: <add> { <add> 'Section 0': { <add> 'Row 0': { <add> id: '0', <add> text: 'row 0 text' <add> }, <add> 'Row 1': { <add> id: '1', <add> text: 'row 1 text' <add> } <add> } <add> } <add> */ <add> // only one section in this example <add> dataBlob['Section 0'] = {}; <add> for (var ii = 0; ii < 100; ii++) { <add> var pressedText = pressData[ii] ? ' (pressed)' : ''; <add> dataBlob[sectionIDs[0]]['Row ' + ii] = {id: 'Row ' + ii, text: 'Row ' + ii + pressedText}; <add> rowIDs[0].push('Row ' + ii); <add> } <add> return [dataBlob, sectionIDs, rowIDs]; <add> }, <add> <add> _renderSeperator: function(sectionID: number, rowID: number, adjacentRowHighlighted: bool) { <add> return ( <add> <View <add> key={`${sectionID}-${rowID}`} <add> style={{ <add> height: adjacentRowHighlighted ? 4 : 1, <add> backgroundColor: adjacentRowHighlighted ? '#3B5998' : '#CCCCCC', <add> }} <add> /> <add> ); <add> } <add>}); <add> <add>var THUMB_URLS = [ <add> require('./Thumbnails/like.png'), <add> require('./Thumbnails/dislike.png'), <add> require('./Thumbnails/call.png'), <add> require('./Thumbnails/fist.png'), <add> require('./Thumbnails/bandaged.png'), <add> require('./Thumbnails/flowers.png'), <add> require('./Thumbnails/heart.png'), <add> require('./Thumbnails/liking.png'), <add> require('./Thumbnails/party.png'), <add> require('./Thumbnails/poke.png'), <add> require('./Thumbnails/superlike.png'), <add> require('./Thumbnails/victory.png'), <add> ]; <add>var LOREM_IPSUM = 'Lorem ipsum dolor sit amet, ius ad pertinax oportere accommodare, an vix civibus corrumpit referrentur. Te nam case ludus inciderint, te mea facilisi adipiscing. Sea id integre luptatum. In tota sale consequuntur nec. Erat ocurreret mei ei. Eu paulo sapientem vulputate est, vel an accusam intellegam interesset. Nam eu stet pericula reprimique, ea vim illud modus, putant invidunt reprehendunt ne qui.'; <add> <add>/* eslint no-bitwise: 0 */ <add>var hashCode = function(str) { <add> var hash = 15; <add> for (var ii = str.length - 1; ii >= 0; ii--) { <add> hash = ((hash << 5) - hash) + str.charCodeAt(ii); <add> } <add> return hash; <add>}; <add> <add>var styles = StyleSheet.create({ <add> row: { <add> flexDirection: 'row', <add> justifyContent: 'center', <add> padding: 10, <add> backgroundColor: '#F6F6F6', <add> }, <add> thumb: { <add> width: 64, <add> height: 64, <add> }, <add> text: { <add> flex: 1, <add> }, <add> actionsContainer: { <add> flex: 1, <add> flexDirection: 'row', <add> justifyContent: 'flex-end', <add> alignItems: 'center', <add> }, <add>}); <add> <add>module.exports = SwipeableListViewSimpleExample; <ide><path>Examples/UIExplorer/js/UIExplorerList.android.js <ide> var ComponentExamples: Array<UIExplorerExample> = [ <ide> key: 'StatusBarExample', <ide> module: require('./StatusBarExample'), <ide> }, <add> { <add> key: 'SwipeableListViewExample', <add> module: require('./SwipeableListViewExample') <add> }, <ide> { <ide> key: 'SwitchExample', <ide> module: require('./SwitchExample'), <ide><path>Examples/UIExplorer/js/UIExplorerList.ios.js <ide> const ComponentExamples: Array<UIExplorerExample> = [ <ide> key: 'StatusBarExample', <ide> module: require('./StatusBarExample'), <ide> }, <add> { <add> key: 'SwipeableListViewExample', <add> module: require('./SwipeableListViewExample') <add> }, <ide> { <ide> key: 'SwitchExample', <ide> module: require('./SwitchExample'),
3
Javascript
Javascript
fix invalid assertion
ffedc10ea3c11ff17040175b28d3bbe3bfda24a3
<ide><path>packages/ember-views/tests/views/select_test.js <ide> QUnit.test("XSS: does not escape label value when it is a SafeString", function( <ide> append(); <ide> <ide> equal(select.$('option').length, 2, "Should have two options"); <del> equal(select.$('option[value=1] b').length, 1, "Should have child elements"); <add> equal(select.$('option[value=1] p').length, 1, "Should have child elements"); <ide> <ide> // IE 8 adds whitespace <ide> equal(trim(select.$().text()), "YehudaTom", "Options should have content");
1
Go
Go
add platform to image store
6c336849876c2117381618b577f1b24f1fb85571
<ide><path>daemon/daemon.go <ide> func NewDaemon(config *config.Config, registryService registry.Service, containe <ide> return nil, err <ide> } <ide> <del> d.imageStore, err = image.NewImageStore(ifs, d.layerStore) <add> // TODO LCOW @jhowardmsft. For now assume it's the runtime OS. This will be modified <add> // as the stores are split in a follow-up commit. <add> d.imageStore, err = image.NewImageStore(ifs, runtime.GOOS, d.layerStore) <ide> if err != nil { <ide> return nil, err <ide> } <ide><path>image/image.go <ide> func (img *Image) RunConfig() *container.Config { <ide> return img.Config <ide> } <ide> <add>// Platform returns the image's operating system. If not populated, defaults to the host runtime OS. <add>func (img *Image) Platform() string { <add> os := img.OS <add> if os == "" { <add> os = runtime.GOOS <add> } <add> return os <add>} <add> <ide> // MarshalJSON serializes the image to JSON. It sorts the top-level keys so <ide> // that JSON that's been manipulated by a push/pull cycle with a legacy <ide> // registry won't end up with a different key order. <ide><path>image/store.go <ide> type store struct { <ide> images map[ID]*imageMeta <ide> fs StoreBackend <ide> digestSet *digestset.Set <add> platform string <ide> } <ide> <ide> // NewImageStore returns new store object for given layer store <del>func NewImageStore(fs StoreBackend, ls LayerGetReleaser) (Store, error) { <add>func NewImageStore(fs StoreBackend, platform string, ls LayerGetReleaser) (Store, error) { <ide> is := &store{ <ide> ls: ls, <ide> images: make(map[ID]*imageMeta), <ide> fs: fs, <ide> digestSet: digestset.NewSet(), <add> platform: platform, <ide> } <ide> <ide> // load all current images and retain layers <ide><path>image/store_test.go <ide> package image <ide> <ide> import ( <add> "runtime" <ide> "testing" <ide> <ide> "github.com/docker/docker/layer" <ide> func TestRestore(t *testing.T) { <ide> err = fs.SetMetadata(id2, "parent", []byte(id1)) <ide> assert.NoError(t, err) <ide> <del> is, err := NewImageStore(fs, &mockLayerGetReleaser{}) <add> is, err := NewImageStore(fs, runtime.GOOS, &mockLayerGetReleaser{}) <ide> assert.NoError(t, err) <ide> <ide> assert.Len(t, is.Map(), 2) <ide> func TestParentReset(t *testing.T) { <ide> func defaultImageStore(t *testing.T) (Store, func()) { <ide> fsBackend, cleanup := defaultFSStoreBackend(t) <ide> <del> store, err := NewImageStore(fsBackend, &mockLayerGetReleaser{}) <add> store, err := NewImageStore(fsBackend, runtime.GOOS, &mockLayerGetReleaser{}) <ide> assert.NoError(t, err) <ide> <ide> return store, cleanup <ide><path>migrate/v1/migratev1_test.go <ide> func TestMigrateContainers(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> <del> is, err := image.NewImageStore(ifs, ls) <add> is, err := image.NewImageStore(ifs, runtime.GOOS, ls) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide> func TestMigrateImages(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> <del> is, err := image.NewImageStore(ifs, ls) <add> is, err := image.NewImageStore(ifs, runtime.GOOS, ls) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide> <del> ms, err := metadata.NewFSMetadataStore(filepath.Join(tmpdir, "distribution")) <add> ms, err := metadata.NewFSMetadataStore(filepath.Join(tmpdir, "distribution"), runtime.GOOS) <ide> if err != nil { <ide> t.Fatal(err) <ide> }
5
PHP
PHP
fix another skipped test for select()
e68618a3cd2f3f92d9e4f54219e1fddb8cfff7a0
<ide><path>tests/TestCase/View/Helper/FormHelperTest.php <ide> public function testSelectRequired() { <ide> * @return void <ide> */ <ide> public function testNestedSelect() { <del> $this->markTestIncomplete('Need to revisit once models work again.'); <ide> $result = $this->Form->select( <ide> 'Model.field', <ide> array(1 => 'One', 2 => 'Two', 'Three' => array( <ide> 3 => 'Three', 4 => 'Four', 5 => 'Five' <ide> )), array('empty' => false) <ide> ); <ide> $expected = array( <del> 'select' => array('name' => 'Model[field]', <del> 'id' => 'ModelField'), <del> array('option' => array('value' => 1)), <del> 'One', <del> '/option', <del> array('option' => array('value' => 2)), <del> 'Two', <del> '/option', <del> array('optgroup' => array('label' => 'Three')), <del> array('option' => array('value' => 4)), <del> 'Four', <del> '/option', <del> array('option' => array('value' => 5)), <del> 'Five', <del> '/option', <del> '/optgroup', <del> '/select' <del> ); <del> $this->assertTags($result, $expected); <del> <del> $result = $this->Form->select( <del> 'Model.field', <del> array(1 => 'One', 2 => 'Two', 'Three' => array(3 => 'Three', 4 => 'Four')), <del> array('showParents' => true, 'empty' => false) <del> ); <del> <del> $expected = array( <del> 'select' => array('name' => 'Model[field]', 'id' => 'ModelField'), <del> array('option' => array('value' => 1)), <del> 'One', <add> 'select' => array('name' => 'Model[field]'), <add> array('option' => array('value' => 1)), <add> 'One', <add> '/option', <add> array('option' => array('value' => 2)), <add> 'Two', <add> '/option', <add> array('optgroup' => array('label' => 'Three')), <add> array('option' => array('value' => 3)), <add> 'Three', <ide> '/option', <del> array('option' => array('value' => 2)), <del> 'Two', <add> array('option' => array('value' => 4)), <add> 'Four', <ide> '/option', <del> array('optgroup' => array('label' => 'Three')), <del> array('option' => array('value' => 3)), <del> 'Three', <del> '/option', <del> array('option' => array('value' => 4)), <del> 'Four', <del> '/option', <del> '/optgroup', <add> array('option' => array('value' => 5)), <add> 'Five', <add> '/option', <add> '/optgroup', <ide> '/select' <ide> ); <ide> $this->assertTags($result, $expected);
1
Python
Python
fix impossible location condition
048d31835c5ce7c7a5a0248d29267b2796d1fb04
<ide><path>libcloud/compute/drivers/azure_arm.py <ide> def ex_list_publishers(self, location=None): <ide> :rtype: ``list`` <ide> """ <ide> <del> if location is None and self.default_location: <del> location = self.default_location <del> else: <del> raise ValueError("location is required.") <add> if location is None: <add> if self.default_location: <add> location = self.default_location <add> else: <add> raise ValueError("location is required.") <ide> <ide> action = "/subscriptions/%s/providers/Microsoft.Compute/" \ <ide> "locations/%s/publishers" \
1
Javascript
Javascript
add benchmark on async_hooks enabled http server
bf7265ffc699a621c70bb1767204dc5c0e61b6dc
<ide><path>benchmark/async_hooks/http-server.js <add>'use strict'; <add>const common = require('../common.js'); <add> <add>const bench = common.createBenchmark(main, { <add> asyncHooks: ['init', 'before', 'after', 'all', 'disabled', 'none'], <add> connections: [50, 500] <add>}); <add> <add>function main({ asyncHooks, connections }) { <add> if (asyncHooks !== 'none') { <add> let hooks = { <add> init() {}, <add> before() {}, <add> after() {}, <add> destroy() {}, <add> promiseResolve() {} <add> }; <add> if (asyncHooks !== 'all' || asyncHooks !== 'disabled') { <add> hooks = { <add> [asyncHooks]: () => {} <add> }; <add> } <add> const hook = require('async_hooks').createHook(hooks); <add> if (asyncHooks !== 'disabled') { <add> hook.enable(); <add> } <add> } <add> const server = require('../fixtures/simple-http-server.js') <add> .listen(common.PORT) <add> .on('listening', () => { <add> const path = '/buffer/4/4/normal/1'; <add> <add> bench.http({ <add> connections, <add> path, <add> }, () => { <add> server.close(); <add> }); <add> }); <add>} <ide><path>test/benchmark/test-benchmark-async-hooks.js <ide> const runBenchmark = require('../common/benchmark'); <ide> <ide> runBenchmark('async_hooks', <ide> [ <add> 'asyncHooks=all', <add> 'connections=50', <ide> 'method=trackingDisabled', <ide> 'n=10' <ide> ],
2
PHP
PHP
fix docblock indentation in basics.php
94d9c5a9ea0608949631e3561c23089bdef79e1c
<ide><path>src/basics.php <ide> use Cake\Core\Configure; <ide> use Cake\Error\Debugger; <ide> <del>/** <del> * Basic defines for timing functions. <del> */ <add> /** <add> * Basic defines for timing functions. <add> */ <ide> define('SECOND', 1); <ide> define('MINUTE', 60); <ide> define('HOUR', 3600);
1
PHP
PHP
fix $_files parsing
45725b870dfff5a5d82fabd8079fe6ccd355d46e
<ide><path>src/Network/Request.php <ide> protected static function _base() { <ide> protected function _processFiles($post, $files) { <ide> if (is_array($files)) { <ide> foreach ($files as $key => $data) { <del> if (!is_numeric($key)) { <del> $this->_processFileData($post, '', $data, $key); <del> } else { <add> if (isset($data['tmp_name']) && is_string($data['tmp_name'])) { <ide> $post[$key] = $data; <add> } else { <add> $post[$key] = $this->_processFileData([], $data); <ide> } <ide> } <ide> } <ide> protected function _processFiles($post, $files) { <ide> <ide> /** <ide> * Recursively walks the FILES array restructuring the data <del> * into something sane and useable. <add> * into something sane and usable. <ide> * <del> * @param array &$post The post data having files inserted into <add> * @param array $data The data being built <add> * @param array $post The post data being traversed <ide> * @param string $path The dot separated path to insert $data into. <del> * @param array $data The data to traverse/insert. <del> * @param string $field The terminal field name, which is the top level key in $_FILES. <add> * @param string $field The terminal field in the path. This is one of the <add> * $_FILES properties e.g. name, tmp_name, size, error <ide> * @return void <ide> */ <del> protected function _processFileData(&$post, $path, $data, $field) { <del> foreach ($data as $key => $fields) { <del> $newPath = $key; <del> if (!empty($path)) { <del> $newPath = $path . '.' . $key; <add> protected function _processFileData($data, $post, $path = '', $field = '') { <add> foreach ($post as $key => $fields) { <add> $newField = $field; <add> if ($path === '' && $newField === '') { <add> $newField = $key; <add> } <add> if ($field === $newField) { <add> $path .= '.' . $key; <ide> } <ide> if (is_array($fields)) { <del> $this->_processFileData($post, $newPath, $fields, $field); <add> $data = $this->_processFileData($data, $fields, $path, $newField); <ide> } else { <del> if (strpos($newPath, '.') === false) { <del> $newPath = $field . '.' . $key; <del> } else { <del> $newPath .= '.' . $field; <del> } <del> $post = Hash::insert($post, $newPath, $fields); <add> $path = trim($path . '.' . $field, '.'); <add> $data = Hash::insert($data, $path, $fields); <ide> } <ide> } <add> return $data; <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Network/RequestTest.php <ide> public function testPutParsingJSON() { <ide> } <ide> <ide> /** <del> * Test parsing of FILES array <add> * Test processing files with `file` field names. <ide> * <ide> * @return void <ide> */ <del> public function testFilesParsing() { <del> $files = array( <del> 'name' => array( <del> 'File' => array( <del> array('data' => 'cake_sqlserver_patch.patch'), <del> array('data' => 'controller.diff'), <del> array('data' => ''), <del> array('data' => ''), <del> ), <del> 'Post' => array('attachment' => 'jquery-1.2.1.js'), <del> ), <del> 'type' => array( <del> 'File' => array( <del> array('data' => ''), <del> array('data' => ''), <del> array('data' => ''), <del> array('data' => ''), <del> ), <del> 'Post' => array('attachment' => 'application/x-javascript'), <del> ), <del> 'tmp_name' => array( <del> 'File' => array( <del> array('data' => '/private/var/tmp/phpy05Ywj'), <del> array('data' => '/private/var/tmp/php7MBztY'), <del> array('data' => ''), <del> array('data' => ''), <del> ), <del> 'Post' => array('attachment' => '/private/var/tmp/phpEwlrIo'), <del> ), <del> 'error' => array( <del> 'File' => array( <del> array('data' => 0), <del> array('data' => 0), <del> array('data' => 4), <del> array('data' => 4) <del> ), <del> 'Post' => array('attachment' => 0) <del> ), <del> 'size' => array( <del> 'File' => array( <del> array('data' => 6271), <del> array('data' => 350), <del> array('data' => 0), <del> array('data' => 0), <del> ), <del> 'Post' => array('attachment' => 80469) <del> ), <del> ); <del> <add> public function testProcessFilesNested() { <add> $files = [ <add> 'image_main' => [ <add> 'name' => ['file' => 'born on.txt'], <add> 'type' => ['file' => 'text/plain'], <add> 'tmp_name' => ['file' => '/private/var/tmp/php'], <add> 'error' => ['file' => 0], <add> 'size' => ['file' => 17178] <add> ], <add> 0 => [ <add> 'name' => ['image' => 'scratch.text'], <add> 'type' => ['image' => 'text/plain'], <add> 'tmp_name' => ['image' => '/private/var/tmp/phpChIZPb'], <add> 'error' => ['image' => 0], <add> 'size' => ['image' => 1490] <add> ], <add> 'pictures' => [ <add> 'name' => [ <add> 0 => ['file' => 'a-file.png'] <add> ], <add> 'type' => [ <add> 0 => ['file' => 'image/png'] <add> ], <add> 'tmp_name' => [ <add> 0 => ['file' => '/tmp/file123'] <add> ], <add> 'error' => [ <add> 0 => ['file' => '0'] <add> ], <add> 'size' => [ <add> 0 => ['file' => 17188] <add> ], <add> ] <add> ]; <ide> $request = new Request(compact('files')); <del> $expected = array( <del> 'File' => array( <del> array( <del> 'data' => array( <del> 'name' => 'cake_sqlserver_patch.patch', <del> 'type' => '', <del> 'tmp_name' => '/private/var/tmp/phpy05Ywj', <del> 'error' => 0, <del> 'size' => 6271, <del> ) <del> ), <del> array( <del> 'data' => array( <del> 'name' => 'controller.diff', <del> 'type' => '', <del> 'tmp_name' => '/private/var/tmp/php7MBztY', <del> 'error' => 0, <del> 'size' => 350, <del> ) <del> ), <del> array( <del> 'data' => array( <del> 'name' => '', <del> 'type' => '', <del> 'tmp_name' => '', <del> 'error' => 4, <del> 'size' => 0, <del> ) <del> ), <del> array( <del> 'data' => array( <del> 'name' => '', <del> 'type' => '', <del> 'tmp_name' => '', <del> 'error' => 4, <del> 'size' => 0, <del> ) <del> ), <del> ), <del> 'Post' => array( <del> 'attachment' => array( <del> 'name' => 'jquery-1.2.1.js', <del> 'type' => 'application/x-javascript', <del> 'tmp_name' => '/private/var/tmp/phpEwlrIo', <add> $expected = [ <add> 'image_main' => [ <add> 'file' => [ <add> 'name' => 'born on.txt', <add> 'type' => 'text/plain', <add> 'tmp_name' => '/private/var/tmp/php', <ide> 'error' => 0, <del> 'size' => 80469, <del> ) <del> ) <del> ); <del> $this->assertEquals($expected, $request->data); <del> <del> $files = array( <del> 'name' => array( <del> 'Document' => array( <del> 1 => array( <del> 'birth_cert' => 'born on.txt', <del> 'passport' => 'passport.txt', <del> 'drivers_license' => 'ugly pic.jpg' <del> ), <del> 2 => array( <del> 'birth_cert' => 'aunt betty.txt', <del> 'passport' => 'betty-passport.txt', <del> 'drivers_license' => 'betty-photo.jpg' <del> ), <del> ), <del> ), <del> 'type' => array( <del> 'Document' => array( <del> 1 => array( <del> 'birth_cert' => 'application/octet-stream', <del> 'passport' => 'application/octet-stream', <del> 'drivers_license' => 'application/octet-stream', <del> ), <del> 2 => array( <del> 'birth_cert' => 'application/octet-stream', <del> 'passport' => 'application/octet-stream', <del> 'drivers_license' => 'application/octet-stream', <del> ) <del> ) <del> ), <del> 'tmp_name' => array( <del> 'Document' => array( <del> 1 => array( <del> 'birth_cert' => '/private/var/tmp/phpbsUWfH', <del> 'passport' => '/private/var/tmp/php7f5zLt', <del> 'drivers_license' => '/private/var/tmp/phpMXpZgT', <del> ), <del> 2 => array( <del> 'birth_cert' => '/private/var/tmp/php5kHZt0', <del> 'passport' => '/private/var/tmp/phpnYkOuM', <del> 'drivers_license' => '/private/var/tmp/php9Rq0P3', <del> ) <del> ) <del> ), <del> 'error' => array( <del> 'Document' => array( <del> 1 => array( <del> 'birth_cert' => 0, <del> 'passport' => 0, <del> 'drivers_license' => 0, <del> ), <del> 2 => array( <del> 'birth_cert' => 0, <del> 'passport' => 0, <del> 'drivers_license' => 0, <del> ) <del> ) <del> ), <del> 'size' => array( <del> 'Document' => array( <del> 1 => array( <del> 'birth_cert' => 123, <del> 'passport' => 458, <del> 'drivers_license' => 875, <del> ), <del> 2 => array( <del> 'birth_cert' => 876, <del> 'passport' => 976, <del> 'drivers_license' => 9783, <del> ) <del> ) <del> ) <del> ); <del> <del> $request = new Request(compact('files')); <del> $expected = array( <del> 'Document' => array( <del> 1 => array( <del> 'birth_cert' => array( <del> 'name' => 'born on.txt', <del> 'tmp_name' => '/private/var/tmp/phpbsUWfH', <del> 'error' => 0, <del> 'size' => 123, <del> 'type' => 'application/octet-stream', <del> ), <del> 'passport' => array( <del> 'name' => 'passport.txt', <del> 'tmp_name' => '/private/var/tmp/php7f5zLt', <del> 'error' => 0, <del> 'size' => 458, <del> 'type' => 'application/octet-stream', <del> ), <del> 'drivers_license' => array( <del> 'name' => 'ugly pic.jpg', <del> 'tmp_name' => '/private/var/tmp/phpMXpZgT', <del> 'error' => 0, <del> 'size' => 875, <del> 'type' => 'application/octet-stream', <del> ), <del> ), <del> 2 => array( <del> 'birth_cert' => array( <del> 'name' => 'aunt betty.txt', <del> 'tmp_name' => '/private/var/tmp/php5kHZt0', <del> 'error' => 0, <del> 'size' => 876, <del> 'type' => 'application/octet-stream', <del> ), <del> 'passport' => array( <del> 'name' => 'betty-passport.txt', <del> 'tmp_name' => '/private/var/tmp/phpnYkOuM', <del> 'error' => 0, <del> 'size' => 976, <del> 'type' => 'application/octet-stream', <del> ), <del> 'drivers_license' => array( <del> 'name' => 'betty-photo.jpg', <del> 'tmp_name' => '/private/var/tmp/php9Rq0P3', <del> 'error' => 0, <del> 'size' => 9783, <del> 'type' => 'application/octet-stream', <del> ), <del> ), <del> ) <del> ); <add> 'size' => 17178, <add> ] <add> ], <add> 'pictures' => [ <add> 0 => [ <add> 'file' => [ <add> 'name' => 'a-file.png', <add> 'type' => 'image/png', <add> 'tmp_name' => '/tmp/file123', <add> 'error' => '0', <add> 'size' => 17188, <add> ] <add> ] <add> ], <add> 0 => [ <add> 'image' => [ <add> 'name' => 'scratch.text', <add> 'type' => 'text/plain', <add> 'tmp_name' => '/private/var/tmp/phpChIZPb', <add> 'error' => 0, <add> 'size' => 1490 <add> ] <add> ] <add> ]; <ide> $this->assertEquals($expected, $request->data); <ide> } <ide>
2
Go
Go
simplify containerfs type
95824f2b5f44cd90096c865b093ed9a68342377a
<ide><path>builder/builder-next/adapters/snapshot/snapshot.go <ide> func (s *snapshotter) Mounts(ctx context.Context, key string) (snapshot.Mountabl <ide> return nil, nil, err <ide> } <ide> return []mount.Mount{{ <del> Source: rootfs.Path(), <add> Source: string(rootfs), <ide> Type: "bind", <ide> Options: []string{"rbind"}, <ide> }}, func() error { <ide> func (s *snapshotter) Mounts(ctx context.Context, key string) (snapshot.Mountabl <ide> return nil, nil, err <ide> } <ide> return []mount.Mount{{ <del> Source: rootfs.Path(), <add> Source: string(rootfs), <ide> Type: "bind", <ide> Options: []string{"rbind"}, <ide> }}, func() error { <ide><path>builder/dockerfile/copy.go <ide> type copyInfo struct { <ide> } <ide> <ide> func (c copyInfo) fullPath() (string, error) { <del> return containerfs.ResolveScopedPath(c.root.Path(), c.path) <add> return containerfs.ResolveScopedPath(string(c.root), c.path) <ide> } <ide> <ide> func newCopyInfoFromSource(source builder.Source, path string, hash string) copyInfo { <ide> func (o *copier) getCopyInfoForSourcePath(orig, dest string) ([]copyInfo, error) <ide> } <ide> path = unnamedFilename <ide> } <del> o.tmpPaths = append(o.tmpPaths, remote.Root().Path()) <add> o.tmpPaths = append(o.tmpPaths, string(remote.Root())) <ide> <ide> hash, err := remote.Hash(path) <ide> ci := newCopyInfoFromSource(remote, path, hash) <ide> func (o *copier) calcCopyInfo(origPath string, allowWildcards bool) ([]copyInfo, <ide> <ide> o.source, err = remotecontext.NewLazySource(rwLayer.Root()) <ide> if err != nil { <del> return nil, errors.Wrapf(err, "failed to create context for copy from %s", rwLayer.Root().Path()) <add> return nil, errors.Wrapf(err, "failed to create context for copy from %s", string(rwLayer.Root())) <ide> } <ide> } <ide> <ide> func (o *copier) storeInPathCache(im *imageMount, path string, hash string) { <ide> func (o *copier) copyWithWildcards(origPath string) ([]copyInfo, error) { <ide> root := o.source.Root() <ide> var copyInfos []copyInfo <del> if err := filepath.Walk(root.Path(), func(path string, info os.FileInfo, err error) error { <add> if err := filepath.Walk(string(root), func(path string, info os.FileInfo, err error) error { <ide> if err != nil { <ide> return err <ide> } <ide><path>builder/dockerfile/internals.go <ide> func (b *Builder) performCopy(req dispatchRequest, inst copyInstruction) error { <ide> // translated (if necessary because of user namespaces), and replace <ide> // the root pair with the chown pair for copy operations <ide> if inst.chownStr != "" { <del> identity, err = parseChownFlag(b, state, inst.chownStr, destInfo.root.Path(), b.idMapping) <add> identity, err = parseChownFlag(b, state, inst.chownStr, string(destInfo.root), b.idMapping) <ide> if err != nil { <ide> if b.options.Platform != "windows" { <ide> return errors.Wrapf(err, "unable to convert uid/gid chown string to host mapping") <ide><path>builder/dockerfile/internals_test.go <ide> func TestDeepCopyRunConfig(t *testing.T) { <ide> type MockRWLayer struct{} <ide> <ide> func (l *MockRWLayer) Release() error { return nil } <del>func (l *MockRWLayer) Root() containerfs.ContainerFS { return nil } <add>func (l *MockRWLayer) Root() containerfs.ContainerFS { return "" } <ide> func (l *MockRWLayer) Commit() (builder.ROLayer, error) { <ide> return &MockROLayer{ <ide> diffID: layer.DiffID(digest.Digest("sha256:1234")), <ide><path>builder/dockerfile/mockbackend_test.go <ide> func (l *mockRWLayer) Commit() (builder.ROLayer, error) { <ide> } <ide> <ide> func (l *mockRWLayer) Root() containerfs.ContainerFS { <del> return nil <add> return "" <ide> } <ide><path>builder/remotecontext/archive.go <ide> type archiveContext struct { <ide> } <ide> <ide> func (c *archiveContext) Close() error { <del> return os.RemoveAll(c.root.Path()) <add> return os.RemoveAll(string(c.root)) <ide> } <ide> <ide> func convertPathError(err error, cleanpath string) error { <ide> func (c *archiveContext) Hash(path string) (string, error) { <ide> return "", err <ide> } <ide> <del> rel, err := filepath.Rel(c.root.Path(), fullpath) <add> rel, err := filepath.Rel(string(c.root), fullpath) <ide> if err != nil { <ide> return "", convertPathError(err, cleanpath) <ide> } <ide> func (c *archiveContext) Hash(path string) (string, error) { <ide> <ide> func normalize(path string, root containerfs.ContainerFS) (cleanPath, fullPath string, err error) { <ide> cleanPath = filepath.Clean(string(filepath.Separator) + path)[1:] <del> fullPath, err = containerfs.ResolveScopedPath(root.Path(), path) <add> fullPath, err = containerfs.ResolveScopedPath(string(root), path) <ide> if err != nil { <ide> return "", "", errors.Wrapf(err, "forbidden path outside the build context: %s (%s)", path, cleanPath) <ide> } <ide><path>builder/remotecontext/detect.go <ide> func StatAt(remote builder.Source, path string) (os.FileInfo, error) { <ide> <ide> // FullPath is a helper for getting a full path for a path from a source <ide> func FullPath(remote builder.Source, path string) (string, error) { <del> fullPath, err := containerfs.ResolveScopedPath(remote.Root().Path(), path) <add> fullPath, err := containerfs.ResolveScopedPath(string(remote.Root()), path) <ide> if err != nil { <ide> if runtime.GOOS == "windows" { <ide> return "", fmt.Errorf("failed to resolve scoped path %s (%s): %s. Possible cause is a forbidden path outside the build context", path, fullPath, err) <ide><path>builder/remotecontext/detect_test.go <ide> func (r *stubRemote) Close() error { <ide> return errors.New("not implemented") <ide> } <ide> func (r *stubRemote) Remove(p string) error { <del> return os.Remove(filepath.Join(r.root.Path(), p)) <add> return os.Remove(filepath.Join(string(r.root), p)) <ide> } <ide><path>builder/remotecontext/lazycontext.go <ide> func (c *lazySource) Hash(path string) (string, error) { <ide> } <ide> <ide> func (c *lazySource) prepareHash(relPath string, fi os.FileInfo) (string, error) { <del> p := filepath.Join(c.root.Path(), relPath) <add> p := filepath.Join(string(c.root), relPath) <ide> h, err := NewFileHash(p, relPath, fi) <ide> if err != nil { <ide> return "", errors.Wrapf(err, "failed to create hash for %s", relPath) <ide> func (c *lazySource) prepareHash(relPath string, fi os.FileInfo) (string, error) <ide> func Rel(basepath containerfs.ContainerFS, targpath string) (string, error) { <ide> // filepath.Rel can't handle UUID paths in windows <ide> if runtime.GOOS == "windows" { <del> pfx := basepath.Path() + `\` <add> pfx := string(basepath) + `\` <ide> if strings.HasPrefix(targpath, pfx) { <ide> p := strings.TrimPrefix(targpath, pfx) <ide> if p == "" { <ide> func Rel(basepath containerfs.ContainerFS, targpath string) (string, error) { <ide> return p, nil <ide> } <ide> } <del> return filepath.Rel(basepath.Path(), targpath) <add> return filepath.Rel(string(basepath), targpath) <ide> } <ide><path>builder/remotecontext/tarsum.go <ide> func (cs *CachableSource) Scan() error { <ide> return err <ide> } <ide> txn := iradix.New().Txn() <del> err = filepath.Walk(cs.root.Path(), func(path string, info os.FileInfo, err error) error { <add> err = filepath.Walk(string(cs.root), func(path string, info os.FileInfo, err error) error { <ide> if err != nil { <ide> return errors.Wrapf(err, "failed to walk %s", path) <ide> } <ide><path>builder/remotecontext/tarsum_test.go <ide> func TestCloseRootDirectory(t *testing.T) { <ide> t.Fatalf("Error while executing Close: %s", err) <ide> } <ide> <del> _, err = os.Stat(src.Root().Path()) <add> _, err = os.Stat(string(src.Root())) <ide> <ide> if !errors.Is(err, os.ErrNotExist) { <ide> t.Fatal("Directory should not exist at this point") <ide> func TestRemoveDirectory(t *testing.T) { <ide> <ide> src := makeTestArchiveContext(t, contextDir) <ide> <del> _, err = os.Stat(filepath.Join(src.Root().Path(), relativePath)) <add> _, err = os.Stat(filepath.Join(string(src.Root()), relativePath)) <ide> if err != nil { <ide> t.Fatalf("Statting %s shouldn't fail: %+v", relativePath, err) <ide> } <ide> func TestRemoveDirectory(t *testing.T) { <ide> t.Fatalf("Error when executing Remove: %s", err) <ide> } <ide> <del> _, err = os.Stat(filepath.Join(src.Root().Path(), relativePath)) <add> _, err = os.Stat(filepath.Join(string(src.Root()), relativePath)) <ide> if !errors.Is(err, os.ErrNotExist) { <ide> t.Fatalf("Directory should not exist at this point: %+v ", err) <ide> } <ide><path>container/archive.go <ide> import ( <ide> // the absolute path to the resource relative to the container's rootfs, and <ide> // an error if the path points to outside the container's rootfs. <ide> func (container *Container) ResolvePath(path string) (resolvedPath, absPath string, err error) { <del> if container.BaseFS == nil { <del> return "", "", errors.New("ResolvePath: BaseFS of container " + container.ID + " is unexpectedly nil") <add> if container.BaseFS == "" { <add> return "", "", errors.New("ResolvePath: BaseFS of container " + container.ID + " is unexpectedly empty") <ide> } <ide> // Check if a drive letter supplied, it must be the system drive. No-op except on Windows <ide> path, err = system.CheckSystemDriveAndRemoveDriveLetter(path) <ide> func (container *Container) ResolvePath(path string) (resolvedPath, absPath stri <ide> // resolved to a path on the host corresponding to the given absolute path <ide> // inside the container. <ide> func (container *Container) StatPath(resolvedPath, absPath string) (stat *types.ContainerPathStat, err error) { <del> if container.BaseFS == nil { <del> return nil, errors.New("StatPath: BaseFS of container " + container.ID + " is unexpectedly nil") <add> if container.BaseFS == "" { <add> return nil, errors.New("StatPath: BaseFS of container " + container.ID + " is unexpectedly empty") <ide> } <del> driver := container.BaseFS <ide> <ide> lstat, err := os.Lstat(resolvedPath) <ide> if err != nil { <ide> func (container *Container) StatPath(resolvedPath, absPath string) (stat *types. <ide> return nil, err <ide> } <ide> <del> linkTarget, err = filepath.Rel(driver.Path(), hostPath) <add> linkTarget, err = filepath.Rel(string(container.BaseFS), hostPath) <ide> if err != nil { <ide> return nil, err <ide> } <ide><path>container/container.go <ide> func (container *Container) SetupWorkingDirectory(rootIdentity idtools.Identity) <ide> // symlinking to a different path) between using this method and using the <ide> // path. See symlink.FollowSymlinkInScope for more details. <ide> func (container *Container) GetResourcePath(path string) (string, error) { <del> if container.BaseFS == nil { <del> return "", errors.New("GetResourcePath: BaseFS of container " + container.ID + " is unexpectedly nil") <add> if container.BaseFS == "" { <add> return "", errors.New("GetResourcePath: BaseFS of container " + container.ID + " is unexpectedly empty") <ide> } <ide> // IMPORTANT - These are paths on the OS where the daemon is running, hence <ide> // any filepath operations must be done in an OS agnostic way. <del> r, e := containerfs.ResolveScopedPath(container.BaseFS.Path(), containerfs.CleanScopedPath(path)) <add> r, e := containerfs.ResolveScopedPath(string(container.BaseFS), containerfs.CleanScopedPath(path)) <ide> <ide> // Log this here on the daemon side as there's otherwise no indication apart <ide> // from the error being propagated all the way back to the client. This makes <ide> // debugging significantly easier and clearly indicates the error comes from the daemon. <ide> if e != nil { <del> logrus.Errorf("Failed to ResolveScopedPath BaseFS %s path %s %s\n", container.BaseFS.Path(), path, e) <add> logrus.Errorf("Failed to ResolveScopedPath BaseFS %s path %s %s\n", string(container.BaseFS), path, e) <ide> } <ide> return r, e <ide> } <ide><path>daemon/archive.go <ide> func (daemon *Daemon) containerArchivePath(container *container.Container, path <ide> } <ide> opts := archive.TarResourceRebaseOpts(sourceBase, filepath.Base(absPath)) <ide> <del> data, err := archivePath(driver, sourceDir, opts, container.BaseFS.Path()) <add> data, err := archivePath(driver, sourceDir, opts, string(container.BaseFS)) <ide> if err != nil { <ide> return nil, nil, err <ide> } <ide> func (daemon *Daemon) containerExtractToDir(container *container.Container, path <ide> // a volume file path. <ide> var baseRel string <ide> if strings.HasPrefix(resolvedPath, `\\?\Volume{`) { <del> if strings.HasPrefix(resolvedPath, driver.Path()) { <del> baseRel = resolvedPath[len(driver.Path()):] <add> if strings.HasPrefix(resolvedPath, string(driver)) { <add> baseRel = resolvedPath[len(string(driver)):] <ide> if baseRel[:1] == `\` { <ide> baseRel = baseRel[1:] <ide> } <ide> } <ide> } else { <del> baseRel, err = filepath.Rel(driver.Path(), resolvedPath) <add> baseRel, err = filepath.Rel(string(driver), resolvedPath) <ide> } <ide> if err != nil { <ide> return err <ide> func (daemon *Daemon) containerExtractToDir(container *container.Container, path <ide> } <ide> } <ide> <del> if err := extractArchive(driver, content, resolvedPath, options, container.BaseFS.Path()); err != nil { <add> if err := extractArchive(driver, content, resolvedPath, options, string(container.BaseFS)); err != nil { <ide> return err <ide> } <ide> <ide> func (daemon *Daemon) containerCopy(container *container.Container, resource str <ide> archv, err := archivePath(driver, basePath, &archive.TarOptions{ <ide> Compression: archive.Uncompressed, <ide> IncludeFiles: filter, <del> }, container.BaseFS.Path()) <add> }, string(container.BaseFS)) <ide> if err != nil { <ide> return nil, err <ide> } <ide><path>daemon/daemon.go <ide> func (daemon *Daemon) Mount(container *container.Container) error { <ide> } <ide> logrus.WithField("container", container.ID).Debugf("container mounted via layerStore: %v", dir) <ide> <del> if container.BaseFS != nil && container.BaseFS.Path() != dir.Path() { <add> if container.BaseFS != "" && container.BaseFS != dir { <ide> // The mount path reported by the graph driver should always be trusted on Windows, since the <ide> // volume path for a given mounted layer may change over time. This should only be an error <ide> // on non-Windows operating systems. <ide><path>daemon/export.go <ide> func (daemon *Daemon) containerExport(container *container.Container) (arch io.R <ide> return nil, err <ide> } <ide> <del> archv, err := archivePath(basefs, basefs.Path(), &archive.TarOptions{ <add> archv, err := archivePath(basefs, string(basefs), &archive.TarOptions{ <ide> Compression: archive.Uncompressed, <ide> IDMap: daemon.idMapping, <del> }, basefs.Path()) <add> }, string(basefs)) <ide> if err != nil { <ide> rwlayer.Unmount() <ide> return nil, err <ide><path>daemon/graphdriver/aufs/aufs.go <ide> func (a *Driver) Get(id, mountLabel string) (containerfs.ContainerFS, error) { <ide> defer a.locker.Unlock(id) <ide> parents, err := a.getParentLayerPaths(id) <ide> if err != nil && !os.IsNotExist(err) { <del> return nil, err <add> return "", err <ide> } <ide> <ide> a.pathCacheLock.Lock() <ide> func (a *Driver) Get(id, mountLabel string) (containerfs.ContainerFS, error) { <ide> // just return the diff path to the data <ide> if len(parents) > 0 { <ide> if err := a.mount(id, m, mountLabel, parents); err != nil { <del> return nil, err <add> return "", err <ide> } <ide> } <ide> <ide><path>daemon/graphdriver/aufs/aufs_test.go <ide> func driverGet(d *Driver, id string, mntLabel string) (string, error) { <ide> if err != nil { <ide> return "", err <ide> } <del> return mnt.Path(), nil <add> return string(mnt), nil <ide> } <ide> <ide> func newDriver(t testing.TB) *Driver { <ide> func TestGetWithoutParent(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> expected := path.Join(tmp, "diff", "1") <del> if diffPath.Path() != expected { <add> if string(diffPath) != expected { <ide> t.Fatalf("Expected path %s got %s", expected, diffPath) <ide> } <ide> } <ide> func TestMountWithParent(t *testing.T) { <ide> if err != nil { <ide> t.Fatal(err) <ide> } <del> if mntPath == nil { <del> t.Fatal("mntPath should not be nil") <add> if mntPath == "" { <add> t.Fatal("mntPath should not be empty") <ide> } <ide> <ide> expected := path.Join(tmp, "mnt", "2") <del> if mntPath.Path() != expected { <del> t.Fatalf("Expected %s got %s", expected, mntPath.Path()) <add> if string(mntPath) != expected { <add> t.Fatalf("Expected %s got %s", expected, string(mntPath)) <ide> } <ide> } <ide> <ide> func TestRemoveMountedDir(t *testing.T) { <ide> if err != nil { <ide> t.Fatal(err) <ide> } <del> if mntPath == nil { <del> t.Fatal("mntPath should not be nil") <add> if mntPath == "" { <add> t.Fatal("mntPath should not be empty") <ide> } <ide> <ide> mounted, err := d.mounted(d.pathCache["2"]) <ide><path>daemon/graphdriver/btrfs/btrfs.go <ide> func (d *Driver) Get(id, mountLabel string) (containerfs.ContainerFS, error) { <ide> dir := d.subvolumesDirID(id) <ide> st, err := os.Stat(dir) <ide> if err != nil { <del> return nil, err <add> return "", err <ide> } <ide> <ide> if !st.IsDir() { <del> return nil, fmt.Errorf("%s: not a directory", dir) <add> return "", fmt.Errorf("%s: not a directory", dir) <ide> } <ide> <ide> if quota, err := os.ReadFile(d.quotasDirID(id)); err == nil { <ide> if size, err := strconv.ParseUint(string(quota), 10, 64); err == nil && size >= d.options.minSpace { <ide> if err := d.enableQuota(); err != nil { <del> return nil, err <add> return "", err <ide> } <ide> if err := subvolLimitQgroup(dir, size); err != nil { <del> return nil, err <add> return "", err <ide> } <ide> } <ide> } <ide><path>daemon/graphdriver/btrfs/btrfs_test.go <ide> func TestBtrfsSubvolDelete(t *testing.T) { <ide> } <ide> defer d.Put("test") <ide> <del> dir := dirFS.Path() <add> dir := string(dirFS) <ide> <ide> if err := subvolCreate(dir, "subvoltest"); err != nil { <ide> t.Fatal(err) <ide><path>daemon/graphdriver/devmapper/driver.go <ide> func (d *Driver) Get(id, mountLabel string) (containerfs.ContainerFS, error) { <ide> // Create the target directories if they don't exist <ide> if err := idtools.MkdirAllAndChown(path.Join(d.home, "mnt"), 0755, root); err != nil { <ide> d.ctr.Decrement(mp) <del> return nil, err <add> return "", err <ide> } <ide> if err := idtools.MkdirAndChown(mp, 0755, root); err != nil && !os.IsExist(err) { <ide> d.ctr.Decrement(mp) <del> return nil, err <add> return "", err <ide> } <ide> <ide> // Mount the device <ide> if err := d.DeviceSet.MountDevice(id, mp, mountLabel); err != nil { <ide> d.ctr.Decrement(mp) <del> return nil, err <add> return "", err <ide> } <ide> <ide> if err := idtools.MkdirAllAndChown(rootFs, 0755, root); err != nil { <ide> d.ctr.Decrement(mp) <ide> d.DeviceSet.UnmountDevice(id, mp) <del> return nil, err <add> return "", err <ide> } <ide> <ide> idFile := path.Join(mp, "id") <ide> func (d *Driver) Get(id, mountLabel string) (containerfs.ContainerFS, error) { <ide> if err := os.WriteFile(idFile, []byte(id), 0600); err != nil { <ide> d.ctr.Decrement(mp) <ide> d.DeviceSet.UnmountDevice(id, mp) <del> return nil, err <add> return "", err <ide> } <ide> } <ide> <ide><path>daemon/graphdriver/fsdiff.go <ide> func (gdw *NaiveDiffDriver) Diff(id, parent string) (arch io.ReadCloser, err err <ide> if err != nil { <ide> return nil, err <ide> } <del> layerFs := layerRootFs.Path() <add> layerFs := string(layerRootFs) <ide> <ide> defer func() { <ide> if err != nil { <ide> func (gdw *NaiveDiffDriver) Diff(id, parent string) (arch io.ReadCloser, err err <ide> } <ide> defer driver.Put(parent) <ide> <del> parentFs := parentRootFs.Path() <add> parentFs := string(parentRootFs) <ide> <ide> changes, err := archive.ChangesDirs(layerFs, parentFs) <ide> if err != nil { <ide> func (gdw *NaiveDiffDriver) Changes(id, parent string) ([]archive.Change, error) <ide> } <ide> defer driver.Put(id) <ide> <del> layerFs := layerRootFs.Path() <add> layerFs := string(layerRootFs) <ide> parentFs := "" <ide> <ide> if parent != "" { <ide> func (gdw *NaiveDiffDriver) Changes(id, parent string) ([]archive.Change, error) <ide> return nil, err <ide> } <ide> defer driver.Put(parent) <del> parentFs = parentRootFs.Path() <add> parentFs = string(parentRootFs) <ide> } <ide> <ide> return archive.ChangesDirs(layerFs, parentFs) <ide> func (gdw *NaiveDiffDriver) ApplyDiff(id, parent string, diff io.Reader) (size i <ide> } <ide> defer driver.Put(id) <ide> <del> layerFs := layerRootFs.Path() <add> layerFs := string(layerRootFs) <ide> options := &archive.TarOptions{IDMap: gdw.idMap} <ide> start := time.Now().UTC() <ide> logrus.WithField("id", id).Debug("Start untar layer") <ide> func (gdw *NaiveDiffDriver) DiffSize(id, parent string) (size int64, err error) <ide> } <ide> defer driver.Put(id) <ide> <del> return archive.ChangesSize(layerFs.Path(), changes), nil <add> return archive.ChangesSize(string(layerFs), changes), nil <ide> } <ide><path>daemon/graphdriver/fuse-overlayfs/fuseoverlayfs.go <ide> func (d *Driver) Get(id, mountLabel string) (_ containerfs.ContainerFS, retErr e <ide> defer d.locker.Unlock(id) <ide> dir := d.dir(id) <ide> if _, err := os.Stat(dir); err != nil { <del> return nil, err <add> return "", err <ide> } <ide> <ide> diffDir := path.Join(dir, diffDirName) <ide> func (d *Driver) Get(id, mountLabel string) (_ containerfs.ContainerFS, retErr e <ide> if os.IsNotExist(err) { <ide> return containerfs.NewLocalContainerFS(diffDir), nil <ide> } <del> return nil, err <add> return "", err <ide> } <ide> <ide> mergedDir := path.Join(dir, mergedDirName) <ide> func (d *Driver) Get(id, mountLabel string) (_ containerfs.ContainerFS, retErr e <ide> if _, err := os.Stat(path.Join(dir, "committed")); err == nil { <ide> readonly = true <ide> } else if !os.IsNotExist(err) { <del> return nil, err <add> return "", err <ide> } <ide> <ide> var opts string <ide> func (d *Driver) Get(id, mountLabel string) (_ containerfs.ContainerFS, retErr e <ide> mountTarget := mergedDir <ide> <ide> if err := idtools.MkdirAndChown(mergedDir, 0700, d.idMap.RootPair()); err != nil { <del> return nil, err <add> return "", err <ide> } <ide> <ide> mountProgram := exec.Command(binary, "-o", mountData, mountTarget) <ide> func (d *Driver) Get(id, mountLabel string) (_ containerfs.ContainerFS, retErr e <ide> if output == "" { <ide> output = "<stderr empty>" <ide> } <del> return nil, errors.Wrapf(err, "using mount program %s: %s", binary, output) <add> return "", errors.Wrapf(err, "using mount program %s: %s", binary, output) <ide> } <ide> <ide> return containerfs.NewLocalContainerFS(mergedDir), nil <ide><path>daemon/graphdriver/graphtest/graphbench_unix.go <ide> func DriverBenchDeepLayerRead(b *testing.B, layerCount int, drivername string, d <ide> for i := 0; i < b.N; i++ { <ide> <ide> // Read content <del> c, err := os.ReadFile(filepath.Join(root.Path(), "testfile.txt")) <add> c, err := os.ReadFile(filepath.Join(string(root), "testfile.txt")) <ide> if err != nil { <ide> b.Fatal(err) <ide> } <ide><path>daemon/graphdriver/graphtest/graphtest_unix.go <ide> func DriverTestCreateEmpty(t testing.TB, drivername string, driverOptions ...str <ide> dir, err := driver.Get("empty", "") <ide> assert.NilError(t, err) <ide> <del> verifyFile(t, dir.Path(), 0755|os.ModeDir, 0, 0) <add> verifyFile(t, string(dir), 0755|os.ModeDir, 0, 0) <ide> <ide> // Verify that the directory is empty <del> fis, err := readDir(dir.Path()) <add> fis, err := readDir(string(dir)) <ide> assert.NilError(t, err) <ide> assert.Check(t, is.Len(fis, 0)) <ide> <ide> func DriverTestSetQuota(t *testing.T, drivername string, required bool) { <ide> quota := uint64(50 * units.MiB) <ide> <ide> // Try to write a file smaller than quota, and ensure it works <del> err = writeRandomFile(path.Join(mountPath.Path(), "smallfile"), quota/2) <add> err = writeRandomFile(path.Join(string(mountPath), "smallfile"), quota/2) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <del> defer os.Remove(path.Join(mountPath.Path(), "smallfile")) <add> defer os.Remove(path.Join(string(mountPath), "smallfile")) <ide> <ide> // Try to write a file bigger than quota. We've already filled up half the quota, so hitting the limit should be easy <del> err = writeRandomFile(path.Join(mountPath.Path(), "bigfile"), quota) <add> err = writeRandomFile(path.Join(string(mountPath), "bigfile"), quota) <ide> if err == nil { <ide> t.Fatalf("expected write to fail(), instead had success") <ide> } <ide> if pathError, ok := err.(*os.PathError); ok && pathError.Err != unix.EDQUOT && pathError.Err != unix.ENOSPC { <del> os.Remove(path.Join(mountPath.Path(), "bigfile")) <add> os.Remove(path.Join(string(mountPath), "bigfile")) <ide> t.Fatalf("expect write() to fail with %v or %v, got %v", unix.EDQUOT, unix.ENOSPC, pathError.Err) <ide> } <ide> } <ide><path>daemon/graphdriver/graphtest/testutil.go <ide> func addFiles(drv graphdriver.Driver, layer string, seed int64) error { <ide> } <ide> defer drv.Put(layer) <ide> <del> if err := os.WriteFile(filepath.Join(root.Path(), "file-a"), randomContent(64, seed), 0755); err != nil { <add> if err := os.WriteFile(filepath.Join(string(root), "file-a"), randomContent(64, seed), 0755); err != nil { <ide> return err <ide> } <del> if err := os.MkdirAll(filepath.Join(root.Path(), "dir-b"), 0755); err != nil { <add> if err := os.MkdirAll(filepath.Join(string(root), "dir-b"), 0755); err != nil { <ide> return err <ide> } <del> if err := os.WriteFile(filepath.Join(root.Path(), "dir-b", "file-b"), randomContent(128, seed+1), 0755); err != nil { <add> if err := os.WriteFile(filepath.Join(string(root), "dir-b", "file-b"), randomContent(128, seed+1), 0755); err != nil { <ide> return err <ide> } <ide> <del> return os.WriteFile(filepath.Join(root.Path(), "file-c"), randomContent(128*128, seed+2), 0755) <add> return os.WriteFile(filepath.Join(string(root), "file-c"), randomContent(128*128, seed+2), 0755) <ide> } <ide> <ide> func checkFile(drv graphdriver.Driver, layer, filename string, content []byte) error { <ide> func checkFile(drv graphdriver.Driver, layer, filename string, content []byte) e <ide> } <ide> defer drv.Put(layer) <ide> <del> fileContent, err := os.ReadFile(filepath.Join(root.Path(), filename)) <add> fileContent, err := os.ReadFile(filepath.Join(string(root), filename)) <ide> if err != nil { <ide> return err <ide> } <ide> func addFile(drv graphdriver.Driver, layer, filename string, content []byte) err <ide> } <ide> defer drv.Put(layer) <ide> <del> return os.WriteFile(filepath.Join(root.Path(), filename), content, 0755) <add> return os.WriteFile(filepath.Join(string(root), filename), content, 0755) <ide> } <ide> <ide> func addDirectory(drv graphdriver.Driver, layer, dir string) error { <ide> func addDirectory(drv graphdriver.Driver, layer, dir string) error { <ide> } <ide> defer drv.Put(layer) <ide> <del> return os.MkdirAll(filepath.Join(root.Path(), dir), 0755) <add> return os.MkdirAll(filepath.Join(string(root), dir), 0755) <ide> } <ide> <ide> func removeAll(drv graphdriver.Driver, layer string, names ...string) error { <ide> func removeAll(drv graphdriver.Driver, layer string, names ...string) error { <ide> defer drv.Put(layer) <ide> <ide> for _, filename := range names { <del> if err := os.RemoveAll(filepath.Join(root.Path(), filename)); err != nil { <add> if err := os.RemoveAll(filepath.Join(string(root), filename)); err != nil { <ide> return err <ide> } <ide> } <ide> func checkFileRemoved(drv graphdriver.Driver, layer, filename string) error { <ide> } <ide> defer drv.Put(layer) <ide> <del> if _, err := os.Stat(filepath.Join(root.Path(), filename)); err == nil { <del> return fmt.Errorf("file still exists: %s", filepath.Join(root.Path(), filename)) <add> if _, err := os.Stat(filepath.Join(string(root), filename)); err == nil { <add> return fmt.Errorf("file still exists: %s", filepath.Join(string(root), filename)) <ide> } else if !os.IsNotExist(err) { <ide> return err <ide> } <ide> func addManyFiles(drv graphdriver.Driver, layer string, count int, seed int64) e <ide> defer drv.Put(layer) <ide> <ide> for i := 0; i < count; i += 100 { <del> dir := filepath.Join(root.Path(), fmt.Sprintf("directory-%d", i)) <add> dir := filepath.Join(string(root), fmt.Sprintf("directory-%d", i)) <ide> if err := os.MkdirAll(dir, 0755); err != nil { <ide> return err <ide> } <ide> func changeManyFiles(drv graphdriver.Driver, layer string, count int, seed int64 <ide> var changes []archive.Change <ide> for i := 0; i < count; i += 100 { <ide> archiveRoot := fmt.Sprintf("/directory-%d", i) <del> if err := os.MkdirAll(filepath.Join(root.Path(), archiveRoot), 0755); err != nil { <add> if err := os.MkdirAll(filepath.Join(string(root), archiveRoot), 0755); err != nil { <ide> return nil, err <ide> } <ide> for j := 0; i+j < count && j < 100; j++ { <ide> func changeManyFiles(drv graphdriver.Driver, layer string, count int, seed int64 <ide> case 0: <ide> change.Path = filepath.Join(archiveRoot, fmt.Sprintf("file-%d", i+j)) <ide> change.Kind = archive.ChangeModify <del> if err := os.WriteFile(filepath.Join(root.Path(), change.Path), randomContent(64, seed+int64(i+j)), 0755); err != nil { <add> if err := os.WriteFile(filepath.Join(string(root), change.Path), randomContent(64, seed+int64(i+j)), 0755); err != nil { <ide> return nil, err <ide> } <ide> // Add file <ide> case 1: <ide> change.Path = filepath.Join(archiveRoot, fmt.Sprintf("file-%d-%d", seed, i+j)) <ide> change.Kind = archive.ChangeAdd <del> if err := os.WriteFile(filepath.Join(root.Path(), change.Path), randomContent(64, seed+int64(i+j)), 0755); err != nil { <add> if err := os.WriteFile(filepath.Join(string(root), change.Path), randomContent(64, seed+int64(i+j)), 0755); err != nil { <ide> return nil, err <ide> } <ide> // Remove file <ide> case 2: <ide> change.Path = filepath.Join(archiveRoot, fmt.Sprintf("file-%d", i+j)) <ide> change.Kind = archive.ChangeDelete <del> if err := os.Remove(filepath.Join(root.Path(), change.Path)); err != nil { <add> if err := os.Remove(filepath.Join(string(root), change.Path)); err != nil { <ide> return nil, err <ide> } <ide> } <ide> func checkManyFiles(drv graphdriver.Driver, layer string, count int, seed int64) <ide> defer drv.Put(layer) <ide> <ide> for i := 0; i < count; i += 100 { <del> dir := filepath.Join(root.Path(), fmt.Sprintf("directory-%d", i)) <add> dir := filepath.Join(string(root), fmt.Sprintf("directory-%d", i)) <ide> for j := 0; i+j < count && j < 100; j++ { <ide> file := filepath.Join(dir, fmt.Sprintf("file-%d", i+j)) <ide> fileContent, err := os.ReadFile(file) <ide> func addLayerFiles(drv graphdriver.Driver, layer, parent string, i int) error { <ide> } <ide> defer drv.Put(layer) <ide> <del> if err := os.WriteFile(filepath.Join(root.Path(), "top-id"), []byte(layer), 0755); err != nil { <add> if err := os.WriteFile(filepath.Join(string(root), "top-id"), []byte(layer), 0755); err != nil { <ide> return err <ide> } <del> layerDir := filepath.Join(root.Path(), fmt.Sprintf("layer-%d", i)) <add> layerDir := filepath.Join(string(root), fmt.Sprintf("layer-%d", i)) <ide> if err := os.MkdirAll(layerDir, 0755); err != nil { <ide> return err <ide> } <ide> func checkManyLayers(drv graphdriver.Driver, layer string, count int) error { <ide> } <ide> defer drv.Put(layer) <ide> <del> layerIDBytes, err := os.ReadFile(filepath.Join(root.Path(), "top-id")) <add> layerIDBytes, err := os.ReadFile(filepath.Join(string(root), "top-id")) <ide> if err != nil { <ide> return err <ide> } <ide> func checkManyLayers(drv graphdriver.Driver, layer string, count int) error { <ide> } <ide> <ide> for i := count; i > 0; i-- { <del> layerDir := filepath.Join(root.Path(), fmt.Sprintf("layer-%d", i)) <add> layerDir := filepath.Join(string(root), fmt.Sprintf("layer-%d", i)) <ide> <ide> thisLayerIDBytes, err := os.ReadFile(filepath.Join(layerDir, "layer-id")) <ide> if err != nil { <ide><path>daemon/graphdriver/graphtest/testutil_unix.go <ide> func createBase(t testing.TB, driver graphdriver.Driver, name string) { <ide> assert.NilError(t, err) <ide> defer driver.Put(name) <ide> <del> subdir := filepath.Join(dirFS.Path(), "a subdir") <add> subdir := filepath.Join(string(dirFS), "a subdir") <ide> assert.NilError(t, os.Mkdir(subdir, 0705|os.ModeSticky)) <ide> assert.NilError(t, contdriver.LocalDriver.Lchown(subdir, 1, 2)) <ide> <del> file := filepath.Join(dirFS.Path(), "a file") <add> file := filepath.Join(string(dirFS), "a file") <ide> err = os.WriteFile(file, []byte("Some data"), 0222|os.ModeSetuid) <ide> assert.NilError(t, err) <ide> } <ide> func verifyBase(t testing.TB, driver graphdriver.Driver, name string) { <ide> assert.NilError(t, err) <ide> defer driver.Put(name) <ide> <del> subdir := filepath.Join(dirFS.Path(), "a subdir") <add> subdir := filepath.Join(string(dirFS), "a subdir") <ide> verifyFile(t, subdir, 0705|os.ModeDir|os.ModeSticky, 1, 2) <ide> <del> file := filepath.Join(dirFS.Path(), "a file") <add> file := filepath.Join(string(dirFS), "a file") <ide> verifyFile(t, file, 0222|os.ModeSetuid, 0, 0) <ide> <del> files, err := readDir(dirFS.Path()) <add> files, err := readDir(string(dirFS)) <ide> assert.NilError(t, err) <ide> assert.Check(t, is.Len(files, 2)) <ide> } <ide><path>daemon/graphdriver/overlay/overlay.go <ide> func (d *Driver) Get(id, mountLabel string) (_ containerfs.ContainerFS, err erro <ide> defer d.locker.Unlock(id) <ide> dir := d.dir(id) <ide> if _, err := os.Stat(dir); err != nil { <del> return nil, err <add> return "", err <ide> } <ide> // If id has a root, just return it <ide> rootDir := path.Join(dir, "root") <ide> func (d *Driver) Get(id, mountLabel string) (_ containerfs.ContainerFS, err erro <ide> }() <ide> lowerID, err := os.ReadFile(path.Join(dir, "lower-id")) <ide> if err != nil { <del> return nil, err <add> return "", err <ide> } <ide> root := d.idMap.RootPair() <ide> if err := idtools.MkdirAndChown(mergedDir, 0700, root); err != nil { <del> return nil, err <add> return "", err <ide> } <ide> var ( <ide> lowerDir = path.Join(d.dir(string(lowerID)), "root") <ide> func (d *Driver) Get(id, mountLabel string) (_ containerfs.ContainerFS, err erro <ide> opts = fmt.Sprintf("lowerdir=%s,upperdir=%s,workdir=%s", lowerDir, upperDir, workDir) <ide> ) <ide> if err := unix.Mount("overlay", mergedDir, "overlay", 0, label.FormatMountLabel(opts, mountLabel)); err != nil { <del> return nil, fmt.Errorf("error creating overlay mount to %s: %v", mergedDir, err) <add> return "", fmt.Errorf("error creating overlay mount to %s: %v", mergedDir, err) <ide> } <ide> // chown "workdir/work" to the remapped root UID/GID. Overlay fs inside a <ide> // user namespace requires this to move a directory from lower to upper. <ide> if err := root.Chown(path.Join(workDir, "work")); err != nil { <del> return nil, err <add> return "", err <ide> } <ide> return containerfs.NewLocalContainerFS(mergedDir), nil <ide> } <ide><path>daemon/graphdriver/overlay2/overlay.go <ide> func (d *Driver) Get(id, mountLabel string) (_ containerfs.ContainerFS, retErr e <ide> defer d.locker.Unlock(id) <ide> dir := d.dir(id) <ide> if _, err := os.Stat(dir); err != nil { <del> return nil, err <add> return "", err <ide> } <ide> <ide> diffDir := path.Join(dir, diffDirName) <ide> func (d *Driver) Get(id, mountLabel string) (_ containerfs.ContainerFS, retErr e <ide> if os.IsNotExist(err) { <ide> return containerfs.NewLocalContainerFS(diffDir), nil <ide> } <del> return nil, err <add> return "", err <ide> } <ide> <ide> mergedDir := path.Join(dir, mergedDirName) <ide> func (d *Driver) Get(id, mountLabel string) (_ containerfs.ContainerFS, retErr e <ide> if _, err := os.Stat(path.Join(dir, "committed")); err == nil { <ide> readonly = true <ide> } else if !os.IsNotExist(err) { <del> return nil, err <add> return "", err <ide> } <ide> <ide> var opts string <ide> func (d *Driver) Get(id, mountLabel string) (_ containerfs.ContainerFS, retErr e <ide> <ide> root := d.idMap.RootPair() <ide> if err := idtools.MkdirAndChown(mergedDir, 0700, root); err != nil { <del> return nil, err <add> return "", err <ide> } <ide> <ide> pageSize := unix.Getpagesize() <ide> func (d *Driver) Get(id, mountLabel string) (_ containerfs.ContainerFS, retErr e <ide> } <ide> mountData = label.FormatMountLabel(opts, mountLabel) <ide> if len(mountData) > pageSize-1 { <del> return nil, fmt.Errorf("cannot mount layer, mount label too large %d", len(mountData)) <add> return "", fmt.Errorf("cannot mount layer, mount label too large %d", len(mountData)) <ide> } <ide> <ide> mount = func(source string, target string, mType string, flags uintptr, label string) error { <ide> func (d *Driver) Get(id, mountLabel string) (_ containerfs.ContainerFS, retErr e <ide> } <ide> <ide> if err := mount("overlay", mountTarget, "overlay", 0, mountData); err != nil { <del> return nil, fmt.Errorf("error creating overlay mount to %s: %v", mergedDir, err) <add> return "", fmt.Errorf("error creating overlay mount to %s: %v", mergedDir, err) <ide> } <ide> <ide> if !readonly { <ide> // chown "workdir/work" to the remapped root UID/GID. Overlay fs inside a <ide> // user namespace requires this to move a directory from lower to upper. <ide> if err := root.Chown(path.Join(workDir, workDirName)); err != nil { <del> return nil, err <add> return "", err <ide> } <ide> } <ide> <ide><path>daemon/graphdriver/proxy.go <ide> func (d *graphDriverProxy) Get(id, mountLabel string) (containerfs.ContainerFS, <ide> } <ide> var ret graphDriverResponse <ide> if err := d.client.Call("GraphDriver.Get", args, &ret); err != nil { <del> return nil, err <add> return "", err <ide> } <ide> var err error <ide> if ret.Err != "" { <ide><path>daemon/graphdriver/vfs/driver.go <ide> func (d *Driver) create(id, parent string, size uint64) error { <ide> if err != nil { <ide> return fmt.Errorf("%s: %s", parent, err) <ide> } <del> return CopyDir(parentDir.Path(), dir) <add> return CopyDir(string(parentDir), dir) <ide> } <ide> <ide> func (d *Driver) dir(id string) string { <ide> func (d *Driver) Remove(id string) error { <ide> func (d *Driver) Get(id, mountLabel string) (containerfs.ContainerFS, error) { <ide> dir := d.dir(id) <ide> if st, err := os.Stat(dir); err != nil { <del> return nil, err <add> return "", err <ide> } else if !st.IsDir() { <del> return nil, fmt.Errorf("%s: not a directory", dir) <add> return "", fmt.Errorf("%s: not a directory", dir) <ide> } <ide> return containerfs.NewLocalContainerFS(dir), nil <ide> } <ide><path>daemon/graphdriver/windows/windows.go <ide> func (d *Driver) Get(id, mountLabel string) (containerfs.ContainerFS, error) { <ide> <ide> rID, err := d.resolveID(id) <ide> if err != nil { <del> return nil, err <add> return "", err <ide> } <ide> if count := d.ctr.Increment(rID); count > 1 { <ide> return containerfs.NewLocalContainerFS(d.cache[rID]), nil <ide> func (d *Driver) Get(id, mountLabel string) (containerfs.ContainerFS, error) { <ide> layerChain, err := d.getLayerChain(rID) <ide> if err != nil { <ide> d.ctr.Decrement(rID) <del> return nil, err <add> return "", err <ide> } <ide> <ide> if err := hcsshim.ActivateLayer(d.info, rID); err != nil { <ide> d.ctr.Decrement(rID) <del> return nil, err <add> return "", err <ide> } <ide> if err := hcsshim.PrepareLayer(d.info, rID, layerChain); err != nil { <ide> d.ctr.Decrement(rID) <ide> if err2 := hcsshim.DeactivateLayer(d.info, rID); err2 != nil { <ide> logrus.Warnf("Failed to Deactivate %s: %s", id, err) <ide> } <del> return nil, err <add> return "", err <ide> } <ide> <ide> mountPath, err := hcsshim.GetLayerMountPath(d.info, rID) <ide> func (d *Driver) Get(id, mountLabel string) (containerfs.ContainerFS, error) { <ide> if err2 := hcsshim.DeactivateLayer(d.info, rID); err2 != nil { <ide> logrus.Warnf("Failed to Deactivate %s: %s", id, err) <ide> } <del> return nil, err <add> return "", err <ide> } <ide> d.cacheMu.Lock() <ide> d.cache[rID] = mountPath <ide> func (d *Driver) DiffSize(id, parent string) (size int64, err error) { <ide> } <ide> defer d.Put(id) <ide> <del> return archive.ChangesSize(layerFs.Path(), changes), nil <add> return archive.ChangesSize(string(layerFs), changes), nil <ide> } <ide> <ide> // GetMetadata returns custom driver information. <ide><path>daemon/graphdriver/zfs/zfs.go <ide> func (d *Driver) Get(id, mountLabel string) (_ containerfs.ContainerFS, retErr e <ide> root := d.idMap.RootPair() <ide> // Create the target directories if they don't exist <ide> if err := idtools.MkdirAllAndChown(mountpoint, 0755, root); err != nil { <del> return nil, err <add> return "", err <ide> } <ide> <ide> if err := mount.Mount(filesystem, mountpoint, "zfs", options); err != nil { <del> return nil, errors.Wrap(err, "error creating zfs mount") <add> return "", errors.Wrap(err, "error creating zfs mount") <ide> } <ide> <ide> // this could be our first mount after creation of the filesystem, and the root dir may still have root <ide> // permissions instead of the remapped root uid:gid (if user namespaces are enabled): <ide> if err := root.Chown(mountpoint); err != nil { <del> return nil, fmt.Errorf("error modifying zfs mountpoint (%s) directory ownership: %v", mountpoint, err) <add> return "", fmt.Errorf("error modifying zfs mountpoint (%s) directory ownership: %v", mountpoint, err) <ide> } <ide> <ide> return containerfs.NewLocalContainerFS(mountpoint), nil <ide><path>daemon/images/image_builder.go <ide> func (l *rwLayer) Release() error { <ide> return nil <ide> } <ide> <del> if l.fs != nil { <add> if l.fs != "" { <ide> if err := l.rwLayer.Unmount(); err != nil { <ide> return errors.Wrap(err, "failed to unmount RWLayer") <ide> } <del> l.fs = nil <add> l.fs = "" <ide> } <ide> <ide> metadata, err := l.layerStore.ReleaseRWLayer(l.rwLayer) <ide><path>daemon/initlayer/setup_unix.go <ide> import ( <ide> // the container from unwanted side-effects on the rw layer. <ide> func Setup(initLayerFs containerfs.ContainerFS, rootIdentity idtools.Identity) error { <ide> // Since all paths are local to the container, we can just extract initLayerFs.Path() <del> initLayer := initLayerFs.Path() <add> initLayer := string(initLayerFs) <ide> <ide> for pth, typ := range map[string]string{ <ide> "/dev/pts": "dir", <ide><path>daemon/oci_linux.go <ide> func sysctlExists(s string) bool { <ide> // WithCommonOptions sets common docker options <ide> func WithCommonOptions(daemon *Daemon, c *container.Container) coci.SpecOpts { <ide> return func(ctx context.Context, _ coci.Client, _ *containers.Container, s *coci.Spec) error { <del> if c.BaseFS == nil && !daemon.UsesSnapshotter() { <del> return errors.New("populateCommonSpec: BaseFS of container " + c.ID + " is unexpectedly nil") <add> if c.BaseFS == "" && !daemon.UsesSnapshotter() { <add> return errors.New("populateCommonSpec: BaseFS of container " + c.ID + " is unexpectedly empty") <ide> } <ide> linkedEnv, err := daemon.setupLinkedContainers(c) <ide> if err != nil { <ide> return err <ide> } <ide> if !daemon.UsesSnapshotter() { <ide> s.Root = &specs.Root{ <del> Path: c.BaseFS.Path(), <add> Path: string(c.BaseFS), <ide> Readonly: c.HostConfig.ReadonlyRootfs, <ide> } <ide> } <ide><path>daemon/oci_windows.go <ide> func (daemon *Daemon) createSpecWindowsFields(c *container.Container, s *specs.S <ide> } <ide> s.Root.Readonly = false // Windows does not support a read-only root filesystem <ide> if !isHyperV { <del> if c.BaseFS == nil { <del> return errors.New("createSpecWindowsFields: BaseFS of container " + c.ID + " is unexpectedly nil") <add> if c.BaseFS == "" { <add> return errors.New("createSpecWindowsFields: BaseFS of container " + c.ID + " is unexpectedly empty") <ide> } <ide> <del> s.Root.Path = c.BaseFS.Path() // This is not set for Hyper-V containers <add> s.Root.Path = string(c.BaseFS) // This is not set for Hyper-V containers <ide> if !strings.HasSuffix(s.Root.Path, `\`) { <ide> s.Root.Path = s.Root.Path + `\` // Ensure a correctly formatted volume GUID path \\?\Volume{GUID}\ <ide> } <ide><path>daemon/start.go <ide> func (daemon *Daemon) Cleanup(container *container.Container) { <ide> daemon.unregisterExecCommand(container, eConfig) <ide> } <ide> <del> if container.BaseFS != nil && container.BaseFS.Path() != "" { <add> if container.BaseFS != "" { <ide> if err := container.UnmountVolumes(daemon.LogVolumeEvent); err != nil { <ide> logrus.Warnf("%s cleanup: Failed to umount volumes: %v", container.ID, err) <ide> } <ide><path>integration/plugin/graphdriver/external_test.go <ide> func setupPlugin(t *testing.T, ec map[string]*graphEventsCounter, ext string, mu <ide> respond(w, err) <ide> return <ide> } <del> respond(w, &graphDriverResponse{Dir: dir.Path()}) <add> respond(w, &graphDriverResponse{Dir: string(dir)}) <ide> }) <ide> <ide> mux.HandleFunc("/GraphDriver.Put", func(w http.ResponseWriter, r *http.Request) { <ide><path>layer/layer_store.go <ide> func (n *naiveDiffPathDriver) DiffGetter(id string) (graphdriver.FileGetCloser, <ide> if err != nil { <ide> return nil, err <ide> } <del> return &fileGetPutter{storage.NewPathFileGetter(p.Path()), n.Driver, id}, nil <add> return &fileGetPutter{storage.NewPathFileGetter(string(p)), n.Driver, id}, nil <ide> } <ide><path>layer/layer_test.go <ide> func newTestFile(name string, content []byte, perm os.FileMode) FileApplier { <ide> } <ide> <ide> func (tf *testFile) ApplyFile(root containerfs.ContainerFS) error { <del> fullPath := filepath.Join(root.Path(), tf.name) <add> fullPath := filepath.Join(string(root), tf.name) <ide> if err := os.MkdirAll(filepath.Dir(fullPath), 0755); err != nil { <ide> return err <ide> } <ide> func TestMountAndRegister(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> <del> b, err := os.ReadFile(filepath.Join(path2.Path(), "testfile.txt")) <add> b, err := os.ReadFile(filepath.Join(string(path2), "testfile.txt")) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide> func TestStoreRestore(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> <del> if err := os.WriteFile(filepath.Join(pathFS.Path(), "testfile.txt"), []byte("nothing here"), 0644); err != nil { <add> if err := os.WriteFile(filepath.Join(string(pathFS), "testfile.txt"), []byte("nothing here"), 0644); err != nil { <ide> t.Fatal(err) <ide> } <ide> <ide> func TestStoreRestore(t *testing.T) { <ide> <ide> if mountPath, err := m2.Mount(""); err != nil { <ide> t.Fatal(err) <del> } else if pathFS.Path() != mountPath.Path() { <del> t.Fatalf("Unexpected path %s, expected %s", mountPath.Path(), pathFS.Path()) <add> } else if string(pathFS) != string(mountPath) { <add> t.Fatalf("Unexpected path %s, expected %s", string(mountPath), string(pathFS)) <ide> } <ide> <ide> if mountPath, err := m2.Mount(""); err != nil { <ide> t.Fatal(err) <del> } else if pathFS.Path() != mountPath.Path() { <del> t.Fatalf("Unexpected path %s, expected %s", mountPath.Path(), pathFS.Path()) <add> } else if string(pathFS) != string(mountPath) { <add> t.Fatalf("Unexpected path %s, expected %s", string(mountPath), string(pathFS)) <ide> } <ide> if err := m2.Unmount(); err != nil { <ide> t.Fatal(err) <ide> } <ide> <del> b, err := os.ReadFile(filepath.Join(pathFS.Path(), "testfile.txt")) <add> b, err := os.ReadFile(filepath.Join(string(pathFS), "testfile.txt")) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide><path>layer/layer_windows.go <ide> func GetLayerPath(s Store, layer ChainID) (string, error) { <ide> return "", err <ide> } <ide> <del> return path.Path(), nil <add> return string(path), nil <ide> } <ide> <ide> func (ls *layerStore) mountID(name string) string { <ide><path>layer/mount_test.go <ide> func TestMountInit(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> <del> fi, err := os.Stat(filepath.Join(pathFS.Path(), "testfile.txt")) <add> fi, err := os.Stat(filepath.Join(string(pathFS), "testfile.txt")) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide> <del> f, err := os.Open(filepath.Join(pathFS.Path(), "testfile.txt")) <add> f, err := os.Open(filepath.Join(string(pathFS), "testfile.txt")) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide> func TestMountSize(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> <del> if err := os.WriteFile(filepath.Join(pathFS.Path(), "file2"), content2, 0755); err != nil { <add> if err := os.WriteFile(filepath.Join(string(pathFS), "file2"), content2, 0755); err != nil { <ide> t.Fatal(err) <ide> } <ide> <ide> func TestMountChanges(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> <del> if err := driver.LocalDriver.Lchmod(filepath.Join(pathFS.Path(), "testfile1.txt"), 0755); err != nil { <add> if err := driver.LocalDriver.Lchmod(filepath.Join(string(pathFS), "testfile1.txt"), 0755); err != nil { <ide> t.Fatal(err) <ide> } <ide> <del> if err := os.WriteFile(filepath.Join(pathFS.Path(), "testfile1.txt"), []byte("mount data!"), 0755); err != nil { <add> if err := os.WriteFile(filepath.Join(string(pathFS), "testfile1.txt"), []byte("mount data!"), 0755); err != nil { <ide> t.Fatal(err) <ide> } <ide> <del> if err := os.Remove(filepath.Join(pathFS.Path(), "testfile2.txt")); err != nil { <add> if err := os.Remove(filepath.Join(string(pathFS), "testfile2.txt")); err != nil { <ide> t.Fatal(err) <ide> } <ide> <del> if err := driver.LocalDriver.Lchmod(filepath.Join(pathFS.Path(), "testfile3.txt"), 0755); err != nil { <add> if err := driver.LocalDriver.Lchmod(filepath.Join(string(pathFS), "testfile3.txt"), 0755); err != nil { <ide> t.Fatal(err) <ide> } <ide> <del> if err := os.WriteFile(filepath.Join(pathFS.Path(), "testfile4.txt"), []byte("mount data!"), 0644); err != nil { <add> if err := os.WriteFile(filepath.Join(string(pathFS), "testfile4.txt"), []byte("mount data!"), 0644); err != nil { <ide> t.Fatal(err) <ide> } <ide> <ide> func TestMountApply(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> <del> f, err := os.Open(filepath.Join(pathFS.Path(), "newfile.txt")) <add> f, err := os.Open(filepath.Join(string(pathFS), "newfile.txt")) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide><path>pkg/containerfs/containerfs.go <ide> import ( <ide> ) <ide> <ide> // ContainerFS is that represents a root file system <del>type ContainerFS interface { <del> // Path returns the path to the root. Note that this may not exist <del> // on the local system, so the continuity operations must be used <del> Path() string <del>} <add>type ContainerFS string <ide> <ide> // NewLocalContainerFS is a helper function to implement daemon's Mount interface <ide> // when the graphdriver mount point is a local path on the machine. <ide> func NewLocalContainerFS(path string) ContainerFS { <del> return &local{ <del> path: path, <del> } <del>} <del> <del>type local struct { <del> path string <del>} <del> <del>func (l *local) Path() string { <del> return l.path <add> return ContainerFS(path) <ide> } <ide> <ide> // ResolveScopedPath evaluates the given path scoped to the root.
44
Ruby
Ruby
delegate more path methods
346621dd5b7ef93fb658f89b9427841cb17a2824
<ide><path>Library/Homebrew/service.rb <ide> def environment_variables(variables = {}) <ide> end <ide> end <ide> <del> delegate [:bin, :var, :etc, :opt_bin, :opt_sbin, :opt_prefix] => :@formula <add> delegate [:bin, :etc, :libexec, :opt_bin, :opt_libexec, :opt_pkgshare, :opt_prefix, :opt_sbin, :var] => :@formula <ide> <ide> sig { returns(String) } <ide> def std_service_path_env
1
Javascript
Javascript
use regular timeout times for armv8
668449ad1442645c0657a75d190bd791d0a59532
<ide><path>test/common.js <ide> exports.platformTimeout = function(ms) { <ide> if (process.arch !== 'arm') <ide> return ms; <ide> <del> if (process.config.variables.arm_version === '6') <add> const armv = process.config.variables.arm_version; <add> <add> if (armv === '6') <ide> return 7 * ms; // ARMv6 <ide> <del> return 2 * ms; // ARMv7 and up. <add> if (armv === '7') <add> return 2 * ms; // ARMv7 <add> <add> return ms; // ARMv8+ <ide> }; <ide> <ide> var knownGlobals = [setTimeout,
1
Text
Text
update some more docs for package split
0faf4b752f43a18598dcac3541dda257a2a656af
<ide><path>docs/docs/10-addons.md <ide> prev: tooling-integration.html <ide> next: animation.html <ide> --- <ide> <del>`React.addons` is where we park some useful utilities for building React apps. **These should be considered experimental** but will eventually be rolled into core or a blessed utilities library: <add>The React add-ons are a collection of useful utility modules for building React apps. **These should be considered experimental** and tend to change more often than the core. <ide> <ide> - [`TransitionGroup` and `CSSTransitionGroup`](animation.html), for dealing with animations and transitions that are usually not simple to implement, such as before a component's removal. <ide> - [`LinkedStateMixin`](two-way-binding-helpers.html), to simplify the coordination between user's form input data and the component's state. <ide> The add-ons below are in the development (unminified) version of React only: <ide> - [`TestUtils`](test-utils.html), simple helpers for writing test cases (unminified build only). <ide> - [`Perf`](perf.html), for measuring performance and giving you hint where to optimize. <ide> <del>To get the add-ons, use `react-with-addons.js` (and its minified counterpart) rather than the common `react.js`. <del> <del>When using the react package from npm, simply `require('react/addons')` instead of `require('react')` to get React with all of the add-ons. <add>To get the add-ons, install them individually from npm (e.g., `npm install react-addons-pure-render-mixin`). We don't support using the addons if you're not using npm. <ide><path>docs/docs/10.1-animation.md <ide> React provides a `ReactTransitionGroup` addon component as a low-level API for a <ide> `ReactCSSTransitionGroup` is the interface to `ReactTransitions`. This is a simple element that wraps all of the components you are interested in animating. Here's an example where we fade list items in and out. <ide> <ide> ```javascript{28-30} <del>var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup; <add>var ReactCSSTransitionGroup = require('react-addons-css-transition-group'); <ide> <ide> var TodoList = React.createClass({ <ide> getInitialState: function() { <ide> In order for it to apply transitions to its children, the `ReactCSSTransitionGro <ide> In the example above, we rendered a list of items into `ReactCSSTransitionGroup`. However, the children of `ReactCSSTransitionGroup` can also be one or zero items. This makes it possible to animate a single element entering or leaving. Similarly, you can animate a new element replacing the current element. For example, we can implement a simple image carousel like this: <ide> <ide> ```javascript{10-12} <del>var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup; <add>var ReactCSSTransitionGroup = require('react-addons-css-transition-group'); <ide> <ide> var ImageCarousel = React.createClass({ <ide> propTypes: { <ide> You can disable animating `enter` or `leave` animations if you want. For example <ide> <ide> ## Low-level API: `ReactTransitionGroup` <ide> <del>`ReactTransitionGroup` is the basis for animations. It is accessible as `React.addons.TransitionGroup`. When children are declaratively added or removed from it (as in the example above) special lifecycle hooks are called on them. <add>`ReactTransitionGroup` is the basis for animations. It is accessible from `require('react-addons-transition-group')`. When children are declaratively added or removed from it (as in the example above) special lifecycle hooks are called on them. <ide> <ide> ### `componentWillAppear(callback)` <ide> <ide> By default `ReactTransitionGroup` renders as a `span`. You can change this behav <ide> </ReactTransitionGroup> <ide> ``` <ide> <del>Every DOM component that React can render is available for use. However, `component` does not need to be a DOM component. It can be any React component you want; even ones you've written yourself! <del> <del>> Note: <del>> <del>> Prior to v0.12, when using DOM components, the `component` prop needed to be a reference to `React.DOM.*`. Since the component is simply passed to `React.createElement`, it must now be a string. Composite components must pass the factory. <add>Every DOM component that React can render is available for use. However, `component` does not need to be a DOM component. It can be any React component you want; even ones you've written yourself! Just write `component={List}` and your component will receive `this.props.children`. <ide> <ide> Any additional, user-defined, properties will become properties of the rendered component. For example, here's how you would render a `<ul>` with CSS class: <ide> <ide><path>docs/docs/10.2-form-input-binding-sugar.md <ide> var NoLink = React.createClass({ <ide> This works really well and it's very clear how data is flowing, however, with a lot of form fields it could get a bit verbose. Let's use `ReactLink` to save us some typing: <ide> <ide> ```javascript{2,7} <add>var LinkedStateMixin = require('react-addons-linked-state-mixin'); <add> <ide> var WithLink = React.createClass({ <del> mixins: [React.addons.LinkedStateMixin], <add> mixins: [LinkedStateMixin], <ide> getInitialState: function() { <ide> return {message: 'Hello!'}; <ide> }, <ide> As you can see, `ReactLink` objects are very simple objects that just have a `va <ide> ### ReactLink Without valueLink <ide> <ide> ```javascript <add>var LinkedStateMixin = require('react-addons-linked-state-mixin'); <add> <ide> var WithoutLink = React.createClass({ <del> mixins: [React.addons.LinkedStateMixin], <add> mixins: [LinkedStateMixin], <ide> getInitialState: function() { <ide> return {message: 'Hello!'}; <ide> }, <ide><path>docs/docs/10.3-class-name-manipulation.md <ide> next: test-utils.html <ide> <ide> > NOTE: <ide> > <del>> This module now exists independently at [JedWatson/classnames](https://github.com/JedWatson/classnames) and is React-agnostic. The add-on here will thus be removed in the future. <del> <del>`classSet()` is a neat utility for easily manipulating the DOM `class` string. <del> <del>Here's a common scenario and its solution without `classSet()`: <del> <del>```javascript <del>// inside some `<Message />` React component <del>render: function() { <del> var classString = 'message'; <del> if (this.props.isImportant) { <del> classString += ' message-important'; <del> } <del> if (this.props.isRead) { <del> classString += ' message-read'; <del> } <del> // 'message message-important message-read' <del> return <div className={classString}>Great, I'll be there.</div>; <del>} <del>``` <del> <del>This can quickly get tedious, as assigning class name strings can be hard to read and error-prone. `classSet()` solves this problem: <del> <del>```javascript <del>render: function() { <del> var cx = React.addons.classSet; <del> var classes = cx({ <del> 'message': true, <del> 'message-important': this.props.isImportant, <del> 'message-read': this.props.isRead <del> }); <del> // same final string, but much cleaner <del> return <div className={classes}>Great, I'll be there.</div>; <del>} <del>``` <del> <del>When using `classSet()`, pass an object with keys of the CSS class names you might or might not need. Truthy values will result in the key being a part of the resulting string. <del> <del>`classSet()` also lets you pass class names in as arguments that are then concatenated for you: <del> <del>```javascript <del>render: function() { <del> var cx = React.addons.classSet; <del> var importantModifier = 'message-important'; <del> var readModifier = 'message-read'; <del> var classes = cx('message', importantModifier, readModifier); <del> // Final string is 'message message-important message-read' <del> return <div className={classes}>Great, I'll be there.</div>; <del>} <del>``` <del> <del>No more hacky string concatenations! <add>> This module has been deprecated; use [JedWatson/classnames](https://github.com/JedWatson/classnames) instead. <ide><path>docs/docs/10.4-test-utils.md <ide> prev: two-way-binding-helpers.html <ide> next: clone-with-props.html <ide> --- <ide> <del>`React.addons.TestUtils` makes it easy to test React components in the testing framework of your choice (we use [Jest](https://facebook.github.io/jest/)). <add>`ReactTestUtils` makes it easy to test React components in the testing framework of your choice (we use [Jest](https://facebook.github.io/jest/)). <add> <add>``` <add>var ReactTestUtils = require('react-addons-test-utils'); <add>``` <ide> <ide> ### Simulate <ide> <ide> Simulate an event dispatch on a DOM node with optional `eventData` event data. * <ide> <ide> ```javascript <ide> var node = ReactDOM.findDOMNode(this.refs.button); <del>React.addons.TestUtils.Simulate.click(node); <add>ReactTestUtils.Simulate.click(node); <ide> ``` <ide> <ide> **Changing the value of an input field and then pressing ENTER** <ide> <ide> ```javascript <ide> var node = ReactDOM.findDOMNode(this.refs.input); <ide> node.value = 'giraffe' <del>React.addons.TestUtils.Simulate.change(node); <del>React.addons.TestUtils.Simulate.keyDown(node, {key: "Enter", keyCode: 13, which: 13}); <add>ReactTestUtils.Simulate.change(node); <add>ReactTestUtils.Simulate.keyDown(node, {key: "Enter", keyCode: 13, which: 13}); <ide> ``` <ide> <ide> *note that you will have to provide any event property that you're using in your component (e.g. keyCode, which, etc...) as React is not creating any of these for you* <ide><path>docs/docs/10.5-clone-with-props.md <ide> next: create-fragment.html <ide> In rare situations, you may want to create a copy of a React element with different props from those of the original element. One example is cloning the elements passed into `this.props.children` and rendering them with different props: <ide> <ide> ```js <add>var cloneWithProps = require('react-addons-clone-with-props'); <add> <ide> var _makeBlue = function(element) { <del> return React.addons.cloneWithProps(element, {style: {color: 'blue'}}); <add> return cloneWithProps(element, {style: {color: 'blue'}}); <ide> }; <ide> <ide> var Blue = React.createClass({ <ide><path>docs/docs/10.6-create-fragment.md <ide> var Swapper = React.createClass({ <ide> <ide> The children will unmount and remount as you change the `swapped` prop because there aren't any keys marked on the two sets of children. <ide> <del>To solve this problem, you can use `React.addons.createFragment` to give keys to the sets of children. <add>To solve this problem, you can use the `createFragment` add-on to give keys to the sets of children. <ide> <del>#### `ReactFragment React.addons.createFragment(object children)` <add>#### `Array<ReactNode> createFragment(object children)` <ide> <ide> Instead of creating arrays, we write: <ide> <ide> ```js <add>var createFragment = require('react-addons-create-fragment'); <add> <ide> if (this.props.swapped) { <del> children = React.addons.createFragment({ <add> children = createFragment({ <ide> right: this.props.rightChildren, <ide> left: this.props.leftChildren <ide> }); <ide> } else { <del> children = React.addons.createFragment({ <add> children = createFragment({ <ide> left: this.props.leftChildren, <ide> right: this.props.rightChildren <ide> }); <ide><path>docs/docs/10.7-update.md <ide> While this is fairly performant (since it only makes a shallow copy of `log n` o <ide> `update()` provides simple syntactic sugar around this pattern to make writing this code easier. This code becomes: <ide> <ide> ```js <del>var newData = React.addons.update(myData, { <add>var update = require('react-addons-update'); <add> <add>var newData = update(myData, { <ide> x: {y: {z: {$set: 7}}}, <ide> a: {b: {$push: [9]}} <ide> }); <ide><path>docs/docs/10.9-perf.md <ide> React is usually quite fast out of the box. However, in situations where you nee <ide> <ide> In addition to giving you an overview of your app's overall performance, ReactPerf is a profiling tool that tells you exactly where you need to put these hooks. <ide> <add>## General API <add> <add>The `Perf` object documented here is exposed as `require('react-addons-perf')` and can be used with React in development mode only. You should not include this bundle when building your app for production. <add> <ide> > Note: <ide> > <ide> > The dev build of React is slower than the prod build, due to all the extra logic for providing, for example, React's friendly console warnings (stripped away in the prod build). Therefore, the profiler only serves to indicate the _relatively_ expensive parts of your app. <ide> <del>## General API <del> <del>The `Perf` object documented here is exposed as `React.addons.Perf` when using the `react-with-addons.js` build in development mode. <del> <ide> ### `Perf.start()` and `Perf.stop()` <ide> Start/stop the measurement. The React operations in-between are recorded for analyses below. Operations that took an insignificant amount of time are ignored. <ide> <ide><path>docs/docs/getting-started.md <ide> The easiest way to start hacking on React is using the following JSFiddle Hello <ide> * **[React JSFiddle](https://jsfiddle.net/reactjs/69z2wepo/)** <ide> * [React JSFiddle without JSX](https://jsfiddle.net/reactjs/5vjqabv3/) <ide> <del>## Starter Kit <add>## Using React from npm <ide> <del>Download the starter kit to get started. <add>We recommend using React with a CommonJS module system like [browserify](http://browserify.org/) or [webpack](https://webpack.github.io/). Use the [`react`](https://www.npmjs.com/package/react) and [`react-dom`](https://www.npmjs.com/package/react-dom) npm packages. <add> <add>```js <add>// main.js <add>var React = require('react'); <add>var ReactDOM = require('react-dom'); <add> <add>ReactDOM.render( <add> <h1>Hello, world!</h1>, <add> document.getElementById('example') <add>); <add>``` <add> <add>To install React DOM and build your bundle after installing browserify: <add> <add>```sh <add>$ npm install --save react react-dom <add>$ browserify -t babelify main.js -o bundle.js <add>``` <add> <add>## Quick Start Without npm <add> <add>If you're not ready to use npm yet, you can download the starter kit which includes prebuilt copies of React and React DOM. <ide> <ide> <div class="buttons-unit downloads"> <ide> <a href="/react/downloads/react-{{site.react_version}}.zip" class="button"> <ide> In the root directory of the starter kit, create a `helloworld.html` with the fo <ide> <meta charset="UTF-8" /> <ide> <title>Hello React!</title> <ide> <script src="build/react.js"></script> <add> <script src="build/react-dom.js"></script> <ide> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script> <ide> </head> <ide> <body> <ide> ReactDOM.render( <ide> <ide> Update your HTML file as below: <ide> <del>```html{7,11} <add>```html{8,12} <ide> <!DOCTYPE html> <ide> <html> <ide> <head> <ide> <meta charset="UTF-8" /> <ide> <title>Hello React!</title> <ide> <script src="build/react.js"></script> <add> <script src="build/react-dom.js"></script> <ide> <!-- No need for Babel! --> <ide> </head> <ide> <body> <ide> Update your HTML file as below: <ide> </html> <ide> ``` <ide> <del>## Want CommonJS? <del> <del>If you want to use React with [browserify](http://browserify.org/), [webpack](https://webpack.github.io/), or another CommonJS-compatible module system, just use the [`react` npm package](https://www.npmjs.com/package/react). In addition, the `jsx` build tool can be integrated into most packaging systems (not just CommonJS) quite easily. <del> <ide> ## Next Steps <ide> <ide> Check out [the tutorial](/react/docs/tutorial.html) and the other examples in the starter kit's `examples` directory to learn more. <ide><path>docs/docs/ref-01-top-level-api.md <ide> the type argument can be either an html tag name string (eg. 'div', 'span', etc) <ide> `ReactClass`. <ide> <ide> <add>### React.isValidElement <add> <add>```javascript <add>boolean isValidElement(* object) <add>``` <add> <add>Verifies the object is a ReactElement. <add> <add> <add>### React.DOM <add> <add>`React.DOM` provides convenience wrappers around `React.createElement` for DOM components. These should only be used when not using JSX. For example, `React.DOM.div(null, 'Hello World!')` <add> <add> <add>### React.PropTypes <add> <add>`React.PropTypes` includes types that can be used with a component's `propTypes` object to validate props being passed to your components. For more information about `propTypes`, see [Reusable Components](/react/docs/reusable-components.html). <add> <add> <add>### React.Children <add> <add>`React.Children` provides utilities for dealing with the `this.props.children` opaque data structure. <add> <add>#### React.Children.map <add> <add>```javascript <add>object React.Children.map(object children, function fn [, object thisArg]) <add>``` <add> <add>Invoke `fn` on every immediate child contained within `children` with `this` set to `thisArg`. If `children` is a nested object or array it will be traversed: `fn` will never be passed the container objects. If children is `null` or `undefined` returns `null` or `undefined` rather than an empty object. <add> <add>#### React.Children.forEach <add> <add>```javascript <add>React.Children.forEach(object children, function fn [, object thisArg]) <add>``` <add> <add>Like `React.Children.map()` but does not return an object. <add> <add>#### React.Children.count <add> <add>```javascript <add>number React.Children.count(object children) <add>``` <add> <add>Return the total number of components in `children`, equal to the number of times that a callback passed to `map` or `forEach` would be invoked. <add> <add>#### React.Children.only <add> <add>```javascript <add>object React.Children.only(object children) <add>``` <add> <add>Return the only child in `children`. Throws otherwise. <add> <add>## ReactDOM <add> <add>The `react-dom` package provides DOM-specific methods that can be used at the top level of your app and as an escape hatch to get outside of the React model if you need to. <add> <ide> ### ReactDOM.render <ide> <ide> ```javascript <ide> boolean unmountComponentAtNode(DOMElement container) <ide> Remove a mounted React component from the DOM and clean up its event handlers and state. If no component was mounted in the container, calling this function does nothing. Returns `true` if a component was unmounted and `false` if there was no component to unmount. <ide> <ide> <del>### ReactDOM.renderToString <del> <del>```javascript <del>string renderToString(ReactElement element) <del>``` <del> <del>Render a ReactElement to its initial HTML. This should only be used on the server. React will return an HTML string. You can use this method to generate HTML on the server and send the markup down on the initial request for faster page loads and to allow search engines to crawl your pages for SEO purposes. <del> <del>If you call `ReactDOM.render()` on a node that already has this server-rendered markup, React will preserve it and only attach event handlers, allowing you to have a very performant first-load experience. <del> <del> <del>### ReactDOM.renderToStaticMarkup <del> <del>```javascript <del>string renderToStaticMarkup(ReactElement element) <del>``` <del> <del>Similar to `renderToString`, except this doesn't create extra DOM attributes such as `data-react-id`, that React uses internally. This is useful if you want to use React as a simple static page generator, as stripping away the extra attributes can save lots of bytes. <del> <del> <del>### ReactDOM.isValidElement <del> <del>```javascript <del>boolean isValidElement(* object) <del>``` <del> <del>Verifies the object is a ReactElement. <del> <del> <ide> ### ReactDOM.findDOMNode <ide> <ide> ```javascript <ide> If this component has been mounted into the DOM, this returns the corresponding <ide> > <ide> > `findDOMNode()` only works on mounted components (that is, components that have been placed in the DOM). If you try to call this on a component that has not been mounted yet (like calling `findDOMNode()` in `render()` on a component that has yet to be created) an exception will be thrown. <ide> <del>### React.DOM <del> <del>`React.DOM` provides convenience wrappers around `React.createElement` for DOM components. These should only be used when not using JSX. For example, `React.DOM.div(null, 'Hello World!')` <add>## ReactDOMServer <ide> <add>The `react-dom/server` package allows you to render your components on the server. <ide> <del>### React.PropTypes <del> <del>`React.PropTypes` includes types that can be used with a component's `propTypes` object to validate props being passed to your components. For more information about `propTypes`, see [Reusable Components](/react/docs/reusable-components.html). <del> <del> <del>### React.Children <del> <del>`React.Children` provides utilities for dealing with the `this.props.children` opaque data structure. <del> <del>#### React.Children.map <add>### ReactDOMServer.renderToString <ide> <ide> ```javascript <del>object React.Children.map(object children, function fn [, object thisArg]) <del>``` <del> <del>Invoke `fn` on every immediate child contained within `children` with `this` set to `thisArg`. If `children` is a nested object or array it will be traversed: `fn` will never be passed the container objects. If children is `null` or `undefined` returns `null` or `undefined` rather than an empty object. <del> <del>#### React.Children.forEach <del> <del>```javascript <del>React.Children.forEach(object children, function fn [, object thisArg]) <add>string renderToString(ReactElement element) <ide> ``` <ide> <del>Like `React.Children.map()` but does not return an object. <del> <del>#### React.Children.count <add>Render a ReactElement to its initial HTML. This should only be used on the server. React will return an HTML string. You can use this method to generate HTML on the server and send the markup down on the initial request for faster page loads and to allow search engines to crawl your pages for SEO purposes. <ide> <del>```javascript <del>number React.Children.count(object children) <del>``` <add>If you call `ReactDOM.render()` on a node that already has this server-rendered markup, React will preserve it and only attach event handlers, allowing you to have a very performant first-load experience. <ide> <del>Return the total number of components in `children`, equal to the number of times that a callback passed to `map` or `forEach` would be invoked. <ide> <del>#### React.Children.only <add>### ReactDOMServer.renderToStaticMarkup <ide> <ide> ```javascript <del>object React.Children.only(object children) <add>string renderToStaticMarkup(ReactElement element) <ide> ``` <ide> <del>Return the only child in `children`. Throws otherwise. <add>Similar to `renderToString`, except this doesn't create extra DOM attributes such as `data-react-id`, that React uses internally. This is useful if you want to use React as a simple static page generator, as stripping away the extra attributes can save lots of bytes. <ide><path>docs/docs/tutorial.md <ide> For this tutorial, we're going to make it as easy as possible. Included in the s <ide> <meta charset="utf-8" /> <ide> <title>React Tutorial</title> <ide> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/{{site.react_version}}/react.js"></script> <add> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/{{site.react_version}}/react-dom.js"></script> <ide> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script> <ide> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ide> </head> <ide> You do not have to return basic HTML. You can return a tree of components that y <ide> <ide> `ReactDOM.render()` instantiates the root component, starts the framework, and injects the markup into a raw DOM element, provided as the second argument. <ide> <add>The `ReactDOM` module exposes DOM-specific methods, while `React` has the core tools shared by React on different platforms (e.g., [React Native](http://facebook.github.io/react-native/)). <add> <ide> ## Composing components <ide> <ide> Let's build skeletons for `CommentList` and `CommentForm` which will, again, be simple `<div>`s. Add these two components to your file, keeping the existing `CommentBox` declaration and `ReactDOM.render` call: <ide> Markdown is a simple way to format your text inline. For example, surrounding te <ide> <ide> First, add the third-party library **marked** to your application. This is a JavaScript library which takes Markdown text and converts it to raw HTML. This requires a script tag in your head (which we have already included in the React playground): <ide> <del>```html{8} <add>```html{9} <ide> <!-- index.html --> <ide> <head> <ide> <meta charset="utf-8" /> <ide> <title>React Tutorial</title> <ide> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/{{site.react_version}}/react.js"></script> <add> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/{{site.react_version}}/react-dom.js"></script> <ide> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script> <ide> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ide> <script src="https://cdnjs.cloudflare.com/ajax/libs/marked/0.3.2/marked.min.js"></script>
12
Javascript
Javascript
fix a race condition or two in net.js
4681e34c1e74e96f3027e88523dadf6b27a611c3
<ide><path>lib/net.js <ide> function initStream (self) { <ide> //debug('bytesRead ' + bytesRead + '\n'); <ide> <ide> if (bytesRead === 0) { <add> // EOF <ide> self.readable = false; <ide> self._readWatcher.stop(); <ide> <add> if (!self.writable) self.destroy(); <add> // Note: 'close' not emitted until nextTick. <add> <ide> if (self._events && self._events['end']) self.emit('end'); <ide> if (self.onend) self.onend(); <del> <del> if (!self.writable) self.destroy(); <ide> } else if (bytesRead > 0) { <ide> <ide> timeout.active(self); <ide> exports.createConnection = function (port, host) { <ide> <ide> Object.defineProperty(Stream.prototype, 'readyState', { <ide> get: function () { <del> if (this._resolving) { <add> if (this._connecting) { <ide> return 'opening'; <ide> } else if (this.readable && this.writable) { <add> assert(typeof this.fd == 'number'); <ide> return 'open'; <ide> } else if (this.readable && !this.writable){ <add> assert(typeof this.fd == 'number'); <ide> return 'readOnly'; <ide> } else if (!this.readable && this.writable){ <add> assert(typeof this.fd == 'number'); <ide> return 'writeOnly'; <ide> } else { <add> assert(typeof this.fd != 'number'); <ide> return 'closed'; <ide> } <ide> } <ide> function doConnect (socket, port, host) { <ide> // socketError() if there isn't an error, we're connected. AFAIK this a <ide> // platform independent way determining when a non-blocking connection <ide> // is established, but I have only seen it documented in the Linux <del> // Manual Page connect(2) under the error code EINPROGRESS. <add> // Manual Page connect(2) under the error code EINPROGRESS. <ide> socket._writeWatcher.set(socket.fd, false, true); <ide> socket._writeWatcher.start(); <ide> socket._writeWatcher.callback = function () { <ide> var errno = socketError(socket.fd); <ide> if (errno == 0) { <ide> // connection established <add> socket._connecting = false; <ide> socket.resume(); <del> socket.readable = true; <del> socket.writable = true; <add> socket.readable = socket.writable = true; <ide> socket._writeWatcher.callback = _doFlush; <ide> socket.emit('connect'); <ide> } else if (errno != EINPROGRESS) { <ide> Stream.prototype.connect = function () { <ide> <ide> timeout.active(socket); <ide> <del> var port = parseInt(arguments[0]); <add> self._connecting = true; // set false in doConnect <ide> <del> if (port >= 0) { <del> //debug('new fd = ' + self.fd); <del> // TODO dns resolution on arguments[1] <add> if (parseInt(arguments[0]) >= 0) { <add> // TCP <ide> var port = arguments[0]; <del> self._resolving = true; <ide> dns.lookup(arguments[1], function (err, ip, addressType) { <ide> if (err) { <ide> self.emit('error', err); <ide> } else { <ide> self.type = addressType == 4 ? 'tcp4' : 'tcp6'; <ide> self.fd = socket(self.type); <del> self._resolving = false; <ide> doConnect(self, port, ip); <ide> } <ide> }); <ide> } else { <add> // UNIX <ide> self.fd = socket('unix'); <ide> self.type = 'unix'; <del> // TODO check if sockfile exists? <ide> doConnect(self, arguments[0]); <ide> } <ide> }; <ide> Stream.prototype.destroy = function (exception) { <ide> // but lots of code assumes this._writeQueue is always an array. <ide> this._writeQueue = []; <ide> <add> this.readable = this.writable = false; <add> <ide> if (this._writeWatcher) { <ide> this._writeWatcher.stop(); <ide> ioWatchers.free(this._writeWatcher);
1
Python
Python
fix export for multiple materials per mesh
4f29dbb180772ae44d8d97544113709e226eeb87
<ide><path>utils/exporters/blender/addons/io_three/exporter/api/object.py <ide> def cast_shadow(obj): <ide> ret = None <ide> return ret <ide> elif obj.type == MESH: <del> mat = material(obj) <del> if mat: <del> return data.materials[mat].use_cast_shadows <del> else: <del> return False <add> mats = material(obj) <add> if mats: <add> for m in mats: <add> if data.materials[m].use_cast_shadows: <add> return True <add> return False <ide> <ide> <ide> @_object <ide> def material(obj): <ide> <ide> """ <ide> logger.debug('object.material(%s)', obj) <add> <ide> try: <del> return obj.material_slots[0].name <add> matName = obj.material_slots[0].name # manthrax: Make this throw an error on an empty material array, resulting in non-material <add> return [o.name for o in obj.material_slots] <ide> except IndexError: <ide> pass <ide> <ide> def receive_shadow(obj): <ide> <ide> """ <ide> if obj.type == MESH: <del> mat = material(obj) <del> if mat: <del> return data.materials[mat].use_shadows <del> else: <del> return False <add> mats = material(obj) <add> if mats: <add> for m in mats: <add> if data.materials[m].use_shadows: <add> return True <add> return False <ide> <del>AXIS_CONVERSION = axis_conversion(to_forward='Z', to_up='Y').to_4x4() <add># manthrax: TODO: Would like to evaluate wether this axis conversion stuff is still neccesary AXIS_CONVERSION = mathutils.Matrix() <add>AXIS_CONVERSION = axis_conversion(to_forward='Z', to_up='Y').to_4x4() <ide> <ide> @_object <ide> def matrix(obj, options): <ide><path>utils/exporters/blender/addons/io_three/exporter/object.py <ide> def _node_setup(self): <ide> <ide> if self.options.get(constants.MATERIALS): <ide> logger.info("Parsing materials for %s", self.node) <del> material_name = api.object.material(self.node) <del> if material_name: <del> logger.info("Material found %s", material_name) <del> material_inst = self.scene.material(material_name) <del> self[constants.MATERIAL] = material_inst[constants.UUID] <add> <add> <add> material_names = api.object.material(self.node) #manthrax: changes for multimaterial start here <add> if material_names: <add> logger.info("Got material names for this object:",material_names); <add> materialArray = [self.scene.material(objname)[constants.UUID] for objname in material_names] <add> if len(materialArray) == 0: # If no materials.. dont export a material entry <add> materialArray = None <add> elif len(materialArray) == 1: # If only one material, export material UUID singly, not as array <add> materialArray = materialArray[0] <add> # else export array of material uuids <add> self[constants.MATERIAL] = materialArray <add> logger.info("materials:",self[constants.MATERIAL]); <ide> else: <del> logger.info("%s has no materials", self.node) <add> logger.info("%s has no materials", self.node) #manthrax: end multimaterial <ide> <ide> # TODO (abelnation): handle Area lights <ide> casts_shadow = (constants.MESH,
2
Go
Go
remove daemon dependency on api packages
f4106b46db47524b4f38abeee48137d42e3fe4eb
<ide><path>api/server/router/network/backend.go <ide> type Backend interface { <ide> DeleteNetwork(networkID string) error <ide> NetworksPrune(ctx context.Context, pruneFilters filters.Args) (*types.NetworksPruneReport, error) <ide> } <add> <add>// ClusterBackend is all the methods that need to be implemented <add>// to provide cluster network specific functionality. <add>type ClusterBackend interface { <add> GetNetworks() ([]types.NetworkResource, error) <add> GetNetwork(name string) (types.NetworkResource, error) <add> GetNetworksByName(name string) ([]types.NetworkResource, error) <add> CreateNetwork(nc types.NetworkCreateRequest) (string, error) <add> RemoveNetwork(name string) error <add>} <ide><path>api/server/router/network/network.go <ide> package network // import "github.com/docker/docker/api/server/router/network" <ide> <ide> import ( <ide> "github.com/docker/docker/api/server/router" <del> "github.com/docker/docker/daemon/cluster" <ide> ) <ide> <ide> // networkRouter is a router to talk with the network controller <ide> type networkRouter struct { <ide> backend Backend <del> cluster *cluster.Cluster <add> cluster ClusterBackend <ide> routes []router.Route <ide> } <ide> <ide> // NewRouter initializes a new network router <del>func NewRouter(b Backend, c *cluster.Cluster) router.Router { <add>func NewRouter(b Backend, c ClusterBackend) router.Router { <ide> r := &networkRouter{ <ide> backend: b, <ide> cluster: c, <ide><path>api/server/router/system/backend.go <ide> import ( <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/api/types/events" <ide> "github.com/docker/docker/api/types/filters" <add> "github.com/docker/docker/api/types/swarm" <ide> "golang.org/x/net/context" <ide> ) <ide> <ide> type Backend interface { <ide> UnsubscribeFromEvents(chan interface{}) <ide> AuthenticateToRegistry(ctx context.Context, authConfig *types.AuthConfig) (string, string, error) <ide> } <add> <add>// ClusterBackend is all the methods that need to be implemented <add>// to provide cluster system specific functionality. <add>type ClusterBackend interface { <add> Info() swarm.Info <add>} <ide><path>api/server/router/system/system.go <ide> package system // import "github.com/docker/docker/api/server/router/system" <ide> import ( <ide> "github.com/docker/docker/api/server/router" <ide> "github.com/docker/docker/builder/fscache" <del> "github.com/docker/docker/daemon/cluster" <ide> ) <ide> <ide> // systemRouter provides information about the Docker system overall. <ide> // It gathers information about host, daemon and container events. <ide> type systemRouter struct { <ide> backend Backend <del> cluster *cluster.Cluster <add> cluster ClusterBackend <ide> routes []router.Route <ide> builder *fscache.FSCache <ide> } <ide> <ide> // NewRouter initializes a new system router <del>func NewRouter(b Backend, c *cluster.Cluster, fscache *fscache.FSCache) router.Router { <add>func NewRouter(b Backend, c ClusterBackend, fscache *fscache.FSCache) router.Router { <ide> r := &systemRouter{ <ide> backend: b, <ide> cluster: c,
4
Text
Text
fix broken wikipedia link
deeeaef6d2f49edb4eda0cfbab7f585a3eb520be
<ide><path>guides/source/i18n.md <ide> If you found this guide useful, please consider recommending its authors on [wor <ide> Footnotes <ide> --------- <ide> <del>[^1]: Or, to quote [Wikipedia](http://en.wikipedia.org/wiki/Internationalization_and_localization:) _"Internationalization is the process of designing a software application so that it can be adapted to various languages and regions without engineering changes. Localization is the process of adapting software for a specific region or language by adding locale-specific components and translating text."_ <add>[^1]: Or, to quote [Wikipedia](http://en.wikipedia.org/wiki/Internationalization_and_localization): _"Internationalization is the process of designing a software application so that it can be adapted to various languages and regions without engineering changes. Localization is the process of adapting software for a specific region or language by adding locale-specific components and translating text."_ <ide> <ide> [^2]: Other backends might allow or require to use other formats, e.g. a GetText backend might allow to read GetText files. <ide>
1
Javascript
Javascript
attempt #5 to fix format
87a778288ee3a34846b19cd01cabc82df97f8425
<ide><path>test/lang/ms-my.js <ide> exports["lang:ms-my"] = { <ide> ['m mm', '25 25'], <ide> ['s ss', '50 50'], <ide> ['a A', 'petang petang'], <del> ['h\\a\\ri ke DDDo t\\a\\hun ini', 'hari ke 45 tahun ini'], <add> ['\\h\\a\\ri ke DDDo t\\a\\hun ini', 'hari ke 45 tahun ini'], <ide> ['L', '14/02/2010'], <ide> ['LL', '14 Februari 2010'], <del> ['LLL', '14 Februari 2010 pukul 15:25'], <del> ['LLLL', 'Ahad, Februari 14 2010 15:25'], <add> ['LLL', '14 Februari 2010 pukul 15.25'], <add> ['LLLL', 'Ahad, Februari 14 2010 15.25'], <ide> ['l', '14/2/2010'], <ide> ['ll', '14 Feb 2010'], <del> ['lll', '14 Feb 2010 pukul 3:25'], <del> ['llll', 'Ahd, 14 Feb 2010 pukul 15:25'] <add> ['lll', '14 Feb 2010 pukul 15.25'], <add> ['llll', 'Ahd, 14 Feb 2010 pukul 15.25'] <ide> ], <ide> b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), <ide> i; <ide> exports["lang:ms-my"] = { <ide> <ide> var a = moment().hours(2).minutes(0).seconds(0); <ide> <del> test.equal(moment(a).calendar(), "Hari ini pukul 2:00", "hari ini pada waktu yang sama"); <del> test.equal(moment(a).add({ m: 25 }).calendar(), "Hari ini pukul 2:25", "Sekarang tambah 25 minit"); <del> test.equal(moment(a).add({ h: 1 }).calendar(), "Hari ini pukul 3:00", "Sekarang tambah 1 jam"); <del> test.equal(moment(a).add({ d: 1 }).calendar(), "Esok pada pukul 2:00", "esok pada waktu yang sama"); <del> test.equal(moment(a).subtract({ h: 1 }).calendar(), "Hari ini pukul 1:00", "Sekarang tolak 1 jam"); <del> test.equal(moment(a).subtract({ d: 1 }).calendar(), "Kelmarin pukul 2:00", "kelmarin pada waktu yang sama"); <add> test.equal(moment(a).calendar(), "Hari ini pukul 02.00", "hari ini pada waktu yang sama"); <add> test.equal(moment(a).add({ m: 25 }).calendar(), "Hari ini pukul 02.25", "Sekarang tambah 25 minit"); <add> test.equal(moment(a).add({ h: 1 }).calendar(), "Hari ini pukul 03.00", "Sekarang tambah 1 jam"); <add> test.equal(moment(a).add({ d: 1 }).calendar(), "Esok pukul 02.00", "esok pada waktu yang sama"); <add> test.equal(moment(a).subtract({ h: 1 }).calendar(), "Hari ini pukul 01.00", "Sekarang tolak 1 jam"); <add> test.equal(moment(a).subtract({ d: 1 }).calendar(), "Kelmarin pukul 02.00", "kelmarin pada waktu yang sama"); <ide> <ide> test.done(); <ide> },
1
Python
Python
return attention mask in int32
5c14fceac0a275a47b2f097333b6e36fbe300000
<ide><path>src/transformers/models/speech_to_text/feature_extraction_speech_to_text.py <ide> def __call__( <ide> <ide> attention_mask = padded_inputs.get("attention_mask") <ide> if attention_mask is not None: <del> padded_inputs["attention_mask"] = [np.asarray(array, dtype=np.bool) for array in attention_mask] <add> padded_inputs["attention_mask"] = [np.asarray(array, dtype=np.int32) for array in attention_mask] <ide> <ide> # Utterance-level cepstral mean and variance normalization <ide> if self.do_ceptral_normalize: <ide> attention_mask = ( <del> np.array(attention_mask, dtype=np.bool) <add> np.array(attention_mask, dtype=np.int32) <ide> if self._get_padding_strategies(padding, max_length=max_length) is not PaddingStrategy.DO_NOT_PAD <ide> else None <ide> ) <ide><path>src/transformers/models/wav2vec2/feature_extraction_wav2vec2.py <ide> def zero_mean_unit_var_norm( <ide> Every array in the list is normalized to have zero mean and unit variance <ide> """ <ide> if attention_mask is not None: <del> attention_mask = np.array(attention_mask, np.bool) <add> attention_mask = np.array(attention_mask, np.int32) <ide> normed_input_values = [] <ide> <ide> for vector, length in zip(input_values, attention_mask.sum(-1)): <ide> def __call__( <ide> # convert attention_mask to correct format <ide> attention_mask = padded_inputs.get("attention_mask") <ide> if attention_mask is not None: <del> padded_inputs["attention_mask"] = [np.asarray(array, dtype=np.bool) for array in attention_mask] <add> padded_inputs["attention_mask"] = [np.asarray(array, dtype=np.int32) for array in attention_mask] <ide> <ide> # zero-mean and unit-variance normalization <ide> if self.do_normalize:
2
Javascript
Javascript
fix tga parsing bug of horizontal origin
318c4ccfe77a2ac6541145f7491a95d5f37105ae
<ide><path>examples/js/loaders/TGALoader.js <ide> THREE.TGALoader.prototype._parser = function ( buffer ) { <ide> x_start = 0; <ide> x_step = 1; <ide> x_end = width; <del> y_start = 0; <del> y_step = 1; <del> y_end = height; <add> y_start = height - 1; <add> y_step = -1; <add> y_end = -1; <ide> break; <ide> <ide> case TGA_ORIGIN_BL: <ide> x_start = 0; <ide> x_step = 1; <ide> x_end = width; <del> y_start = height - 1; <del> y_step = - 1; <del> y_end = - 1; <add> y_start = 0; <add> y_step = 1; <add> y_end = height; <ide> break; <ide> <ide> case TGA_ORIGIN_UR: <ide> x_start = width - 1; <ide> x_step = - 1; <ide> x_end = - 1; <del> y_start = 0; <del> y_step = 1; <del> y_end = height; <add> y_start = height - 1; <add> y_step = -1; <add> y_end = -1; <ide> break; <ide> <ide> case TGA_ORIGIN_BR: <ide> x_start = width - 1; <ide> x_step = - 1; <ide> x_end = - 1; <del> y_start = height - 1; <del> y_step = - 1; <del> y_end = - 1; <add> y_start = 0; <add> y_step = 1; <add> y_end = height; <ide> break; <ide> <ide> }
1
Javascript
Javascript
add missing tests for ember.dag
4011c54de066748eca84c47c6bb5fb8548c61847
<ide><path>packages/ember-application/tests/system/dag_test.js <add>import DAG from "ember-application/system/dag"; <add>import EmberError from "ember-metal/error"; <add> <add>QUnit.module("Ember.DAG"); <add> <add>test("detects circular dependencies when added", function(){ <add> var graph = new DAG(); <add> graph.addEdges("eat omelette", 1); <add> graph.addEdges("buy eggs", 2) ; <add> graph.addEdges("fry omelette", 3, "eat omelette", "shake eggs"); <add> graph.addEdges("shake eggs", 4, undefined, "buy eggs"); <add> graph.addEdges("buy oil", 5, "fry omelette"); <add> graph.addEdges("warm oil", 6, "fry omelette", "buy oil"); <add> graph.addEdges("prepare salad", 7); <add> graph.addEdges("prepare the table", 8, "eat omelette"); <add> graph.addEdges("clear the table", 9, undefined, "eat omelette"); <add> graph.addEdges("say grace", 10, "eat omelette", "prepare the table"); <add> <add> raises(function(){ <add> graph.addEdges("imposible", 11, "shake eggs", "eat omelette"); <add> }, EmberError, "raises an error when a circular dependency is added"); <add>}); <add> <add>test("#topsort iterates over the edges respecting precedence order", function(){ <add> var graph = new DAG(), <add> names = [], <add> index = 0; <add> <add> graph.addEdges("eat omelette", 1); <add> graph.addEdges("buy eggs", 2) ; <add> graph.addEdges("fry omelette", 3, "eat omelette", "shake eggs"); <add> graph.addEdges("shake eggs", 4, undefined, "buy eggs"); <add> graph.addEdges("buy oil", 5, "fry omelette"); <add> graph.addEdges("warm oil", 6, "fry omelette", "buy oil"); <add> graph.addEdges("prepare salad", 7); <add> graph.addEdges("prepare the table", 8, "eat omelette"); <add> graph.addEdges("clear the table", 9, undefined, "eat omelette"); <add> graph.addEdges("say grace", 10, "eat omelette", "prepare the table"); <add> <add> <add> graph.topsort(function(vertex, path){ <add> names[index] = vertex.name; <add> index++; <add> }); <add> <add> ok(names.indexOf("buy eggs") < names.indexOf("shake eggs"), "you need eggs to shake them"); <add> ok(names.indexOf("buy oil") < names.indexOf("warm oil"), "you need oil to warm it"); <add> ok(names.indexOf("eat omelette") < names.indexOf("clear the table"), "you clear the table after eat"); <add> ok(names.indexOf("fry omelette") < names.indexOf("eat omelette"), "cook before eat"); <add> ok(names.indexOf("shake eggs") < names.indexOf("fry omelette"), "shake before put into the pan"); <add> ok(names.indexOf("prepare salad") > -1, "we don't know when we prepare the salad, but we do"); <add>}); <add> <add>test("#addEdged supports both strings and arrays to specify precedences", function(){ <add> var graph = new DAG(), <add> names = [], <add> index = 0; <add> <add> graph.addEdges("eat omelette", 1); <add> graph.addEdges("buy eggs", 2) ; <add> graph.addEdges("fry omelette", 3, "eat omelette", "shake eggs"); <add> graph.addEdges("shake eggs", 4, undefined, "buy eggs"); <add> graph.addEdges("buy oil", 5, ["fry omelette", "shake eggs", "prepare the table"], ["warm oil"]); <add> graph.addEdges("prepare the table", 5, undefined, ["fry omelette"]); <add> <add> graph.topsort(function(vertex, path){ <add> names[index] = vertex.name; <add> index++; <add> }); <add> <add> deepEqual(names, ["buy eggs", "warm oil", "buy oil", "shake eggs", "fry omelette", "eat omelette", "prepare the table"]); <add>}); <add>
1
Ruby
Ruby
use correct variable in `secure_compare!`
971cd757eaeb6da34a256b35457749d067073c03
<ide><path>activesupport/lib/active_support/secure_compare_rotator.rb <ide> def initialize(value, **_options) <ide> @value = value <ide> end <ide> <del> def secure_compare!(other_value, on_rotation: @rotation) <add> def secure_compare!(other_value, on_rotation: @on_rotation) <ide> secure_compare(@value, other_value) || <ide> run_rotations(on_rotation) { |wrapper| wrapper.secure_compare!(other_value) } || <ide> raise(InvalidMatch) <ide><path>activesupport/test/secure_compare_rotator_test.rb <ide> class SecureCompareRotatorTest < ActiveSupport::TestCase <ide> assert_equal(true, wrapper.secure_compare!("and_another_one", on_rotation: -> { @witness = true })) <ide> end <ide> end <add> <add> test "#secure_compare! calls the on_rotation proc that given in constructor" do <add> @witness = nil <add> <add> wrapper = ActiveSupport::SecureCompareRotator.new("old_secret", on_rotation: -> { @witness = true }) <add> wrapper.rotate("new_secret") <add> wrapper.rotate("another_secret") <add> wrapper.rotate("and_another_one") <add> <add> assert_changes(:@witness, from: nil, to: true) do <add> assert_equal(true, wrapper.secure_compare!("and_another_one")) <add> end <add> end <ide> end
2
PHP
PHP
use accessor instead of property
fc94940ae9e6b14e9a75eb428b41f01fb7b27c3e
<ide><path>src/View/Cell.php <ide> public function render($template = null) <ide> $className = explode('\\', get_class($this)); <ide> $className = array_pop($className); <ide> $name = substr($className, 0, strrpos($className, 'Cell')); <del> $this->_view->subDir = 'Cell' . DS . $name; <add> $this->_view->viewPath('Cell' . DS . $name); <ide> <ide> try { <ide> return $this->_view->render($template);
1
Javascript
Javascript
add plugin test for event order
c6a855cf744cd2b5f591d9a959eeae5e5c5a15ff
<ide><path>test/unit/plugins.js <ide> test('Plugin should overwrite plugin of same name', function(){ <ide> player2.dispose(); <ide> }); <ide> <add> <add>test('Plugins should get events in registration order', function() { <add> var order = []; <add> var expectedOrder = []; <add> var pluginName = 'orderPlugin'; <add> var i = 0; <add> var name; <add> var player = PlayerTest.makePlayer({}); <add> <add> for (; i < 3; i++ ) { <add> name = pluginName + i; <add> expectedOrder.push(name); <add> (function (name) { <add> vjs.plugin(name, function (opts) { <add> this.on('test', function (event) { <add> order.push(name) <add> }); <add> }); <add> player[name]({}); <add> })(name); <add> } <add> <add> vjs.plugin("testerPlugin", function (opts) { <add> this.trigger('test'); <add> }); <add> <add> player['testerPlugin']({}); <add> <add> deepEqual(order, expectedOrder, "plugins should receive events in order of initialization") <add> player.dispose(); <add>});
1
Text
Text
fix a typo in contributing.md
cce360c7b0136f91fdce6e15ec7fb83eb14153f2
<ide><path>CONTRIBUTING.md <ide> the contributors guide. <ide> <p> <ide> Register for the Docker Community Slack at <ide> <a href="https://community.docker.com/registrations/groups/4316" target="_blank">https://community.docker.com/registrations/groups/4316</a>. <del> We use the #moby-project channel for general discussion, and there are seperate channels for other Moby projects such as #containerd. <add> We use the #moby-project channel for general discussion, and there are separate channels for other Moby projects such as #containerd. <ide> Archives are available at <a href="https://dockercommunity.slackarchive.io/" target="_blank">https://dockercommunity.slackarchive.io/</a>. <ide> </p> <ide> </td>
1
Text
Text
update react installation guide to make it shorter
789746aaca237849b4f81c68245dd31bb76af302
<ide><path>guide/english/react/installation/index.md <ide> --- <ide> title: Installation <ide> --- <add> <ide> ## Installing React <del>### Creating a new React project <del>You could just embed the React library in your webpage like so<sup>2</sup>: <add>There are several different methods to get started with using React<sup>1</sup>. It will depend on the web application size, complexity, and environment to determine the exact approach that is best for you. <add> <add>For a quick and easy method of adding React to your website you could just embed the React library in your website using a `<script>` tag. <ide> ```html <del><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.0.0/cjs/react.production.min.js"></script> <add><script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script> <add><script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script> <ide> ``` <ide> <del>Smart programmers want to take the more practical and productive way: [Create React App](https://github.com/facebookincubator/create-react-app) <add>However, with the above approach, you may feel limited in how far you can take React. This is where the use of toolchain is the preferred approach, with the more practical and productive [Create React App](https://github.com/facebookincubator/create-react-app): <add> <ide> ```bash <ide> npx create-react-app my-app <del> <ide> cd my-app <ide> npm start <ide> ``` <ide> <del>Another option is using the package `npx` which doesn't require you to install the package `create-react-app` before using it. So you can use it without installing it which is helpful for the future not to have too many packages installed on your machine <del>``` <add>This will set up your development environment so that you can use the latest JavaScript features, provide a great developer experience, and optimize your application for production. <add> <add>Another option is using the package `npx` which doesn't require you to install the package `create-react-app` before using it. So you can use it without installing it which is helpful for the future not to have too many packages installed on your machine. <add> <add>```bash <ide> npm install -g npx <ide> npx create-react-app my-app <ide> ``` <ide> <del>This will set up your development environment so that you can use the latest JavaScript features, provide a nice developer experience, and optimize your app for production. <add>- `npm start` will start up a development server which allows live reloading. <ide> <del>`npm start` will start up a development server which allows live reloading<sup>3</sup>. <add>- After you finish your project and are ready to deploy your application to production, you can just use `npm run build` to create an optimized build of your app in the `build` folder. <ide> <del>After you finish your project and are ready to deploy your App to production, you can just use <del>`npm run build` <del>to create an optimized build of your app in the `build`folder. <ide> <del>#### Useful links <del>[Create React App repository](https://github.com/facebookincubator/create-react-app#create-react-app-) <add>You can find more toolchains which support server-rendered website or static content-oriented website at [Create a New React App](https://reactjs.org/docs/create-a-new-react-app.html). <add> <ide> <ide> #### Sources <ide> [1. The React tutorial on installing](https://reactjs.org/docs/installation.html) <ide> <del>[2. Link to the React minimal JavaScript library on cdnjs.org](https://cdnjs.com/libraries/react) <del> <del>[3. npm start command](https://docs.npmjs.com/cli/start) <add>#### More Information <add>- [Getting Started - React Official Site](https://reactjs.org/docs/getting-started.html) <add>- [Create React App repository](https://github.com/facebookincubator/create-react-app#create-react-app-) <add>- [npm start command](https://docs.npmjs.com/cli/start)
1
Javascript
Javascript
strip any leading /private/
28326b3674b183fc425c7c220152fc92069f7d65
<ide><path>src/git-repository-async.js <ide> export default class GitRepositoryAsync { <ide> return _path <ide> } <ide> <add> // Depending on where the paths come from, they may have a '/private/' <add> // prefix. Standardize by stripping that out. <add> _path = _path.replace(/^\/private\//, '/') <add> workingDirectory = workingDirectory.replace(/^\/private\//, '/') <add> <ide> if (process.platform === 'win32') { <ide> _path = _path.replace(/\\/g, '/') <ide> } else {
1
Text
Text
improve spanish translations
c0f9eb66f80c8d5fa654a7375b7618ca08e20ff8
<ide><path>guide/spanish/react/component/index.md <ide> localeTitle: React - Componentes <ide> --- <ide> ## React - Componentes <ide> <del>Los componentes son reutilizables en react.js. Puede inyectar valor en los accesorios como se indica a continuación: <add>Los componentes son reutilizables en react.js. Puedes inyectar valores en props como se indica a continuación: <ide> <ide> ```jsx <ide> function Welcome(props) { <ide> function Welcome(props) { <ide> ); <ide> ``` <ide> <del>`name="Faisal Arkan"` le dará valor en `{props.name}` de la `function Welcome(props)` y devolverá el componente que haya dado un valor por `name="Faisal Arkan"` , luego de que reaccione se convertirá el elemento en html. <add>El valor `name="Faisal Arkan"` se asignará en `{props.name}` de la `function Welcome(props)` y devolverá el componente `<h1>Hello, Faisal Arkan</h1>` el cual esta guardado en la constante `element`. Ahora el componente puede renderizarse a través de la llamada a `ReactDOM.render(element, document.getElemenyById('root'));`. <add>En este caso, `document.getElemenyById('root')` indica el elemento en el cual se va a renderizar el componente. <ide> <ide> ### Otras formas de declarar componentes. <ide> <ide> Hay muchas formas de declarar componentes al usar React.js, pero hay dos tipos de componentes, componentes **_sin_** **_estado_** y componentes con **_estado_** . <ide> <ide> ### Con estado <ide> <del>#### Clase de componentes de clase <add>#### Componentes de tipo clase <ide> <ide> ```jsx <ide> class Cat extends React.Component { <ide> const Cat = props => <ide> <p>{props.color}</p> <ide> </div>; <ide> <del>``` <ide>\ No newline at end of file <add>```
1
Text
Text
remove flash messages view helper
491aebc63a0be3780b73e5bab1a875e0d44a94ad
<ide><path>README.md <ide> Features <ide> - **Local Authentication** using Email and Password <ide> - **OAuth 1.0a Authentication** via Twitter <ide> - **OAuth 2.0 Authentication** via Facebook, Google or GitHub <del>- Sweet Error and Success flash notifications with animations by *animate.css* <add>- Awesome flash notifications with animations by *animate.css* <ide> - MVC Project Structure <ide> - LESS stylesheets (auto-compiled via Express middleware) <ide> - Bootstrap 3 + Flat UI + iOS7 Theme <ide> Obtaining API Keys <ide> - **Authorized redirect URI**: http://localhost:3000/auth/google/callback <ide> - Copy and paste *Client ID* and *Client secret* keys into `config/secrets.js` <ide> <del>> **Note**: When you ready to deploy to production don't forget to add <add>>:exclamation: **Note**: When you ready to deploy to production don't forget to add <ide> > your new url to Authorized Javascript origins and Authorized redirect URI, <ide> > e.g. `http://my-awesome-app.herokuapp.com` and `http://my-awesome-app.herokuapp.com/auth/google/callback` respectively. <ide> <ide> Project Structure <ide> | Name | Description | <ide> | ------------- |:-------------:| <ide> | **config**/passport.js | Passport Local and OAuth strategies + Passport middleware. | <del>| **config**/secrets.js | Your API keys, tokens, passwords and database URL. | <del>| **controllers**/api.js | Controller for /api route and all api examples. | <del>| **controllers**/contact.js | Controller for contact form. | <del>| **controllers**/home.js | Controller for home page (index). <del>| **controllers**/user.js | Controller for user account management page. | <del>| **models**/User.js | Mongoose schema and model for User. | <del>| **public/*** | Static assets, i.e. fonts, css, js, img. | <del>| **views/account/*** | Templates relating to user account. | <del>| **views/api/*** | Templates relating to API Examples. | <del>| **views**/layout.jade | Base template. | <del>| **views**/home.jade | Home page template. | <add>| **config**/secrets.js | Your API keys, tokens, passwords and database URL. | <add>| **controllers**/api.js | Controller for /api route and all api examples. | <add>| **controllers**/contact.js | Controller for contact form. | <add>| **controllers**/home.js | Controller for home page (index). | <add>| **controllers**/user.js | Controller for user account management page. | <add>| **models**/User.js | Mongoose schema and model for User. | <add>| **public/*** | Static assets, i.e. fonts, css, js, img. | <add>| **views/account/*** | Templates relating to user account. | <add>| **views/api/*** | Templates relating to API Examples. | <add>| **views/partials**/flash.jade | Error, info and success notifications. | <add>| **views/partials**/navigation.jade | Navbar partial template. | <add>| **views/partials**/footer.jade | Footer partial template. | <add>| **views**/layout.jade | Base template. | <add>| **views**/home.jade | Home page template. | <ide> <ide> <ide> :exclamation: **Note:** There is no difference how you name or structure your views. You could place all your templates in a top-level `views` directory without having a nested folder structure, if that makes things easier for you. Just don't forget to update `extends ../layout` and corresponding `res.render()` method in controllers. For smaller apps, I find having a flat folder structure to be easier to work with. <ide> I specifically avoided client-side MV* frameworks in this project to keep things <ide> There is a big shift in the way you develop apps with Ember, Backbone, Angular <ide> as opposed to server-side frameworks like Express, Flask, Rails, Django. Not only <ide> would you need to know how to use Express in this case, but also the client-side framework of your choice, <del>which in itself is not a trivial task. It's best if you use a boilerplate of choice for your particular <add>which in itself is not a trivial task. And then there is a whole different process <add>for authentication with single page applications. It's best if you use a boilerplate of choice for your particular <ide> client-side framework and just grab the pieces you need from the Hackathon Starter. <ide> <ide> TODO
1
Java
Java
improve example in javadoc for httpentity
b3eb1a2ad725ab4e8c9af7e1fe51840fa01289d0
<ide><path>spring-web/src/main/java/org/springframework/http/HttpEntity.java <ide> * <pre class="code"> <ide> * HttpHeaders headers = new HttpHeaders(); <ide> * headers.setContentType(MediaType.TEXT_PLAIN); <del> * HttpEntity&lt;String&gt; entity = new HttpEntity&lt;String&gt;(helloWorld, headers); <add> * HttpEntity&lt;String&gt; entity = new HttpEntity&lt;String&gt;("helloWorld", headers); <ide> * URI location = template.postForLocation("https://example.com", entity); <ide> * </pre> <ide> * or
1
Java
Java
fix javadoc description of share()
03295a2b2c7049273d2b3c366439661b830c3ac2
<ide><path>src/main/java/rx/Observable.java <ide> public final Observable<T> serialize() { <ide> <ide> /** <ide> * Returns a new {@link Observable} that multicasts (shares) the original {@link Observable}. As long as <del> * there is more than one {@link Subscriber} this {@link Observable} will be subscribed and emitting data. <add> * there is at least one {@link Subscriber} this {@link Observable} will be subscribed and emitting data. <ide> * When all subscribers have unsubscribed it will unsubscribe from the source {@link Observable}. <ide> * <p> <ide> * This is an alias for {@link #publish()}.{@link ConnectableObservable#refCount()}.
1
Text
Text
remove links to contributor covenant coc
d81e2a23b9f45927e73a60a2f7eb194ed195e9ab
<ide><path>CONTRIBUTING.md <ide> These are just guidelines, not rules, use your best judgment and feel free to pr <ide> <ide> ### Code of Conduct <ide> <del>This project adheres to the [Contributor Covenant 1.3](http://contributor-covenant.org/version/1/3/0) (see [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md)). <add>This project adheres to the Contributor Covenant [code of conduct](CODE_OF_CONDUCT.md). <ide> By participating, you are expected to uphold this code. <ide> Please report unacceptable behavior to [atom@github.com](mailto:atom@github.com). <ide> <ide><path>README.md <ide> Visit [atom.io](https://atom.io) to learn more or visit the [Atom forum](https:/ <ide> Follow [@AtomEditor](https://twitter.com/atomeditor) on Twitter for important <ide> announcements. <ide> <del>This project adheres to the [Contributor Covenant 1.3](http://contributor-covenant.org/version/1/3/0) (see [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md)). <add>This project adheres to the Contributor Covenant [code of conduct](CODE_OF_CONDUCT.md). <ide> By participating, you are expected to uphold this code. Please report unacceptable behavior to atom@github.com. <ide> <ide> ## Documentation
2
Javascript
Javascript
fix missing dispatch argument
4d0d97b0f414ea7d9b8c1cd87a2ac3450dda61b6
<ide><path>examples/universal/common/containers/App.js <ide> const mapStateToProps = (state) => ({ <ide> counter: state.counter <ide> }) <ide> <del>const mapDispatchToProps = () => { <add>const mapDispatchToProps = (dispatch) => { <ide> return bindActionCreators(CounterActions, dispatch) <ide> } <ide>
1
Ruby
Ruby
sanitize argv options
fe3b69d388ca4a5b3a0d9493b688e40ee28dc1c8
<ide><path>Library/Homebrew/cmd/test.rb <ide> def test <ide> #{f.path} <ide> ].concat(ARGV.options_only) <ide> <add> if f.head? <add> args << "--HEAD" <add> elsif f.devel? <add> args << "--devel" <add> end <add> <ide> if Sandbox.available? && ARGV.sandbox? <ide> if Sandbox.auto_disable? <ide> Sandbox.print_autodisable_warning
1
Javascript
Javascript
fix z-index of yellowbox
407973ab27212616cdfac4509875beb6d20c1222
<ide><path>Libraries/ReactNative/YellowBox.js <ide> var styles = StyleSheet.create({ <ide> right: 0, <ide> top: 0, <ide> bottom: 0, <add> elevation: Number.MAX_VALUE <ide> }, <ide> inspector: { <ide> backgroundColor: backgroundColor(0.95), <ide> flex: 1, <ide> paddingTop: 5, <add> elevation: Number.MAX_VALUE <ide> }, <ide> inspectorButtons: { <ide> flexDirection: 'row', <ide> var styles = StyleSheet.create({ <ide> left: 0, <ide> right: 0, <ide> bottom: 0, <add> elevation: Number.MAX_VALUE <ide> }, <ide> listRow: { <ide> position: 'relative',
1
Text
Text
fix typos in text
51077f1dfddef4e17a0f63694f4f1f07758db31b
<ide><path>guide/english/vim/macros/index.md <ide> Recording macros is a way to make some repetitive tasks automatically in VIM. <ide> <ide> ### Recording Macros <ide> <del>Macros use one of the VIM registers to be storage, each register is indentify by a letter `a` to `z`. <add>Macros use one of the VIM registers to be storage, each register is identified by a letter `a` to `z`. <ide> <ide> To start a Macro, in Normal Mode, press: <ide> <ide> q<REGISTER LETTER> <ide> ``` <ide> Example: `qq` starts a macro in the register `q`, `qs` starts the macro in the register `s` <ide> <del>At this point you will see in VIM bottom line `recording @q`, this means everything you type now will be register in the macro. <add>At this point you will see in VIM bottom line `recording @q`, this means everything you type now will be registered in the macro. <ide> <del>To stop record the macro, press `<ESC>` to go back to NORMAL mode, and `q` to quit the macro. <add>To stop recording the macro, press `<ESC>` to go back to NORMAL mode, and `q` to quit the macro. <ide> <ide> To execute the macro you record, press `@` and the register `q`. <ide> <del>#### The complete process look like this: <add>#### The complete process looks like this: <ide> - `qq` -> start record the macro in register `q` <del>- `...` -> the serie of commands you want to record <add>- `...` -> the series of commands you want to record <ide> - `<ESC>q` -> go back to NORMAL mode and quit the macro record <ide> - `@q` -> execute the macro, starting from the line you current are <ide> - `@@` -> execute the macro again
1
Java
Java
reinstate removal of jsessionid from lookup path
eb11c6fa233092506d360fb46d40d489107efd5f
<ide><path>spring-web/src/main/java/org/springframework/web/util/UrlPathHelper.java <ide> protected String determineEncoding(HttpServletRequest request) { <ide> * @return the updated URI string <ide> */ <ide> public String removeSemicolonContent(String requestUri) { <del> return (this.removeSemicolonContent ? removeSemicolonContentInternal(requestUri) : requestUri); <add> return (this.removeSemicolonContent ? <add> removeSemicolonContentInternal(requestUri) : removeJsessionid(requestUri)); <ide> } <ide> <ide> private String removeSemicolonContentInternal(String requestUri) { <ide> private String removeSemicolonContentInternal(String requestUri) { <ide> return requestUri; <ide> } <ide> <add> private String removeJsessionid(String requestUri) { <add> String key = ";jsessionid="; <add> int index = requestUri.toLowerCase().indexOf(key); <add> if (index == -1) { <add> return requestUri; <add> } <add> String start = requestUri.substring(0, index); <add> for (int i = key.length(); i < requestUri.length(); i++) { <add> char c = requestUri.charAt(i); <add> if (c == ';' || c == '/') { <add> return start + requestUri.substring(i); <add> } <add> } <add> return start; <add> } <add> <ide> /** <ide> * Decode the given URI path variables via {@link #decodeRequestString} unless <ide> * {@link #setUrlDecode} is set to {@code true} in which case it is assumed <ide> private boolean shouldRemoveTrailingServletPathSlash(HttpServletRequest request) <ide> * <li>{@code defaultEncoding=}{@link WebUtils#DEFAULT_CHARACTER_ENCODING} <ide> * </ul> <ide> */ <del> public static final UrlPathHelper rawPathInstance = new UrlPathHelper(); <add> public static final UrlPathHelper rawPathInstance = new UrlPathHelper() { <add> <add> @Override <add> public String removeSemicolonContent(String requestUri) { <add> return requestUri; <add> } <add> }; <ide> <ide> static { <ide> rawPathInstance.setAlwaysUseFullPath(true); <ide><path>spring-web/src/test/java/org/springframework/web/util/UrlPathHelperTests.java <ide> public void getRequestKeepSemicolonContent() { <ide> assertThat(helper.getRequestUri(request)).isEqualTo("/foo;a=b;c=d"); <ide> <ide> request.setRequestURI("/foo;jsessionid=c0o7fszeb1"); <del> assertThat(helper.getRequestUri(request)).isEqualTo("/foo;jsessionid=c0o7fszeb1"); <add> assertThat(helper.getRequestUri(request)).isEqualTo("/foo"); <ide> } <ide> <ide> @Test <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessorTests.java <ide> public void addContentDispositionHeader() throws Exception { <ide> assertContentDisposition(processor, true, "/hello.json;a=b;setup.dataless", "unknown ext in path params"); <ide> assertContentDisposition(processor, true, "/hello.dataless;a=b;setup.json", "unknown ext in filename"); <ide> assertContentDisposition(processor, false, "/hello.json;a=b;setup.json", "safe extensions"); <add> assertContentDisposition(processor, true, "/hello.json;jsessionid=foo.bar", "jsessionid shouldn't cause issue"); <ide> <ide> // encoded dot <ide> assertContentDisposition(processor, true, "/hello%2Edataless;a=b;setup.json", "encoded dot in filename"); <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/UriTemplateServletAnnotationControllerHandlerMethodTests.java <ide> /* <del> * Copyright 2002-2019 the original author or authors. <add> * Copyright 2002-2020 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public void simple() throws Exception { <ide> assertThat(response.getContentAsString()).isEqualTo("test-42-7"); <ide> } <ide> <add> @Test // gh-25864 <add> public void literalMappingWithPathParams() throws Exception { <add> initServletWithControllers(MultipleUriTemplateController.class); <add> <add> MockHttpServletRequest request = new MockHttpServletRequest("GET", "/data"); <add> MockHttpServletResponse response = new MockHttpServletResponse(); <add> getServlet().service(request, response); <add> assertThat(response.getStatus()).isEqualTo(200); <add> assertThat(response.getContentAsString()).isEqualTo("test"); <add> <add> request = new MockHttpServletRequest("GET", "/data;foo=bar"); <add> response = new MockHttpServletResponse(); <add> getServlet().service(request, response); <add> assertThat(response.getStatus()).isEqualTo(404); <add> <add> request = new MockHttpServletRequest("GET", "/data;jsessionid=123"); <add> response = new MockHttpServletResponse(); <add> getServlet().service(request, response); <add> assertThat(response.getStatus()).isEqualTo(200); <add> assertThat(response.getContentAsString()).isEqualTo("test"); <add> } <add> <ide> @Test <ide> public void multiple() throws Exception { <ide> initServletWithControllers(MultipleUriTemplateController.class); <ide> public void handle(@PathVariable("hotel") String hotel, <ide> writer.write("test-" + hotel + "-q" + qHotel + "-" + booking + "-" + other + "-q" + qOther); <ide> } <ide> <add> @RequestMapping("/data") <add> void handleWithLiteralMapping(Writer writer) throws IOException { <add> writer.write("test"); <add> } <ide> } <ide> <ide> @Controller
4
Go
Go
add build test for absolute symlink
134f8e6b474d07e12712e0f2d55b901246e6482e
<ide><path>integration-cli/docker_cli_build_test.go <ide> func TestBuildCopyDisallowRemote(t *testing.T) { <ide> logDone("build - copy - disallow copy from remote") <ide> } <ide> <add>func TestBuildAddBadLinks(t *testing.T) { <add> const ( <add> dockerfile = ` <add> FROM scratch <add> ADD links.tar / <add> ADD foo.txt /symlink/ <add> ` <add> targetFile = "foo.txt" <add> ) <add> var ( <add> name = "test-link-absolute" <add> ) <add> defer deleteImages(name) <add> ctx, err := fakeContext(dockerfile, nil) <add> if err != nil { <add> t.Fatal(err) <add> } <add> defer ctx.Close() <add> <add> tempDir, err := ioutil.TempDir("", "test-link-absolute-temp-") <add> if err != nil { <add> t.Fatalf("failed to create temporary directory: %s", tempDir) <add> } <add> defer os.RemoveAll(tempDir) <add> <add> symlinkTarget := fmt.Sprintf("/../../../../../../../../../../../..%s", tempDir) <add> tarPath := filepath.Join(ctx.Dir, "links.tar") <add> nonExistingFile := filepath.Join(tempDir, targetFile) <add> fooPath := filepath.Join(ctx.Dir, targetFile) <add> <add> tarOut, err := os.Create(tarPath) <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> tarWriter := tar.NewWriter(tarOut) <add> <add> header := &tar.Header{ <add> Name: "symlink", <add> Typeflag: tar.TypeSymlink, <add> Linkname: symlinkTarget, <add> Mode: 0755, <add> Uid: 0, <add> Gid: 0, <add> } <add> <add> err = tarWriter.WriteHeader(header) <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> tarWriter.Close() <add> tarOut.Close() <add> <add> foo, err := os.Create(fooPath) <add> if err != nil { <add> t.Fatal(err) <add> } <add> defer foo.Close() <add> <add> if _, err := foo.WriteString("test"); err != nil { <add> t.Fatal(err) <add> } <add> <add> if _, err := buildImageFromContext(name, ctx, true); err != nil { <add> t.Fatal(err) <add> } <add> <add> if _, err := os.Stat(nonExistingFile); err == nil || err != nil && !os.IsNotExist(err) { <add> t.Fatalf("%s shouldn't have been written and it shouldn't exist", nonExistingFile) <add> } <add> <add> logDone("build - ADD must add files in container") <add>} <add> <ide> // Issue #5270 - ensure we throw a better error than "unexpected EOF" <ide> // when we can't access files in the context. <ide> func TestBuildWithInaccessibleFilesInContext(t *testing.T) {
1
Python
Python
add arg cache_enabled
3dcff62578799ac92e62d2deccf55b5a54f9ecb9
<ide><path>keras/layers/core.py <ide> class Layer(object): <ide> def __init__(self, **kwargs): <ide> allowed_kwargs = {'input_shape', <ide> 'trainable', <del> 'batch_input_shape'} <add> 'batch_input_shape', <add> 'cache_enabled'} <ide> for kwarg in kwargs: <ide> assert kwarg in allowed_kwargs, "Keyword argument not understood: " + kwarg <ide> if 'input_shape' in kwargs: <ide> def __init__(self, **kwargs): <ide> self._trainable = kwargs['trainable'] <ide> if not hasattr(self, 'params'): <ide> self.params = [] <add> self.cache_enabled = True <add> if 'cache_enabled' in kwargs: <add> self.cache_enabled = kwargs['cache_enabled'] <ide> <del> def __call__(self, X, mask=None, train=False): <del> # set temporary input and mask <del> tmp_input = self.get_input <del> tmp_mask = None <del> if hasattr(self, 'get_input_mask'): <del> tmp_mask = self.get_input_mask <del> self.get_input_mask = lambda _: mask <add> def __call__(self, X, train=False): <add> # set temporary input <add> tmp = self.get_input <ide> self.get_input = lambda _: X <ide> Y = self.get_output(train=train) <del> # return input and mask to what it was <del> self.get_input = tmp_input <del> if hasattr(self, 'get_input_mask'): <del> self.get_input_mask = tmp_mask <add> # return input to what it was <add> self.get_input = tmp <ide> return Y <ide> <ide> def set_previous(self, layer, connection_map={}): <ide> def get_input(self, train=False): <ide> if hasattr(self, 'previous'): <ide> # to avoid redundant computations, <ide> # layer outputs are cached when possible. <del> if hasattr(self, 'layer_cache'): <add> if hasattr(self, 'layer_cache') and self.cache_enabled: <ide> previous_layer_id = '%s_%s' % (id(self.previous), train) <ide> if previous_layer_id in self.layer_cache: <ide> return self.layer_cache[previous_layer_id] <ide> previous_output = self.previous.get_output(train=train) <del> if hasattr(self, 'layer_cache'): <add> if hasattr(self, 'layer_cache') and self.cache_enabled: <ide> previous_layer_id = '%s_%s' % (id(self.previous), train) <ide> self.layer_cache[previous_layer_id] = previous_output <ide> return previous_output <ide> def get_config(self): <ide> config['input_shape'] = self._input_shape[1:] <ide> if hasattr(self, '_trainable'): <ide> config['trainable'] = self._trainable <add> config['cache_enabled'] = self.cache_enabled <ide> return config <ide> <ide> def get_params(self):
1
Python
Python
add new oauth2 tests
8809c46ab5d2a09d5a956ccffcb2ae2db95c5c1b
<ide><path>rest_framework/tests/authentication.py <ide> def _create_authorization_header(self, token=None): <ide> def _client_credentials_params(self): <ide> return {'client_id': self.CLIENT_ID, 'client_secret': self.CLIENT_SECRET} <ide> <add> @unittest.skipUnless(oauth2_provider, 'django-oauth2-provider not installed') <add> def test_get_form_with_wrong_authorization_header_token_type_failing(self): <add> """Ensure that a wrong token type lead to the correct HTTP error status code""" <add> auth = "Wrong token-type-obsviously" <add> response = self.csrf_client.get('/oauth2-test/', {}, HTTP_AUTHORIZATION=auth) <add> self.assertEqual(response.status_code, 401) <add> params = self._client_credentials_params() <add> response = self.csrf_client.get('/oauth2-test/', params, HTTP_AUTHORIZATION=auth) <add> self.assertEqual(response.status_code, 401) <add> <add> @unittest.skipUnless(oauth2_provider, 'django-oauth2-provider not installed') <add> def test_get_form_with_wrong_authorization_header_token_format_failing(self): <add> """Ensure that a wrong token format lead to the correct HTTP error status code""" <add> auth = "Bearer wrong token format" <add> response = self.csrf_client.get('/oauth2-test/', {}, HTTP_AUTHORIZATION=auth) <add> self.assertEqual(response.status_code, 401) <add> params = self._client_credentials_params() <add> response = self.csrf_client.get('/oauth2-test/', params, HTTP_AUTHORIZATION=auth) <add> self.assertEqual(response.status_code, 401) <add> <add> @unittest.skipUnless(oauth2_provider, 'django-oauth2-provider not installed') <add> def test_get_form_with_wrong_authorization_header_token_failing(self): <add> """Ensure that a wrong token lead to the correct HTTP error status code""" <add> auth = "Bearer wrong-token" <add> response = self.csrf_client.get('/oauth2-test/', {}, HTTP_AUTHORIZATION=auth) <add> self.assertEqual(response.status_code, 401) <add> params = self._client_credentials_params() <add> response = self.csrf_client.get('/oauth2-test/', params, HTTP_AUTHORIZATION=auth) <add> self.assertEqual(response.status_code, 401) <add> <ide> @unittest.skipUnless(oauth2_provider, 'django-oauth2-provider not installed') <ide> def test_get_form_with_wrong_client_data_failing_auth(self): <ide> """Ensure GETing form over OAuth with incorrect client credentials fails"""
1
Go
Go
fix unclosed file-handles in tests
553b0edb4c44bdddfad36524ba2b39c8c3b58ddd
<ide><path>daemon/graphdriver/driver_test.go <ide> func TestIsEmptyDir(t *testing.T) { <ide> d = filepath.Join(tmp, "dir-with-empty-file") <ide> err = os.Mkdir(d, 0755) <ide> assert.NilError(t, err) <del> _, err = os.CreateTemp(d, "file") <add> f, err := os.CreateTemp(d, "file") <ide> assert.NilError(t, err) <add> defer f.Close() <ide> empty = isEmptyDir(d) <ide> assert.Check(t, !empty) <ide> } <ide><path>daemon/trustkey_test.go <ide> func TestLoadOrCreateTrustKeyInvalidKeyFile(t *testing.T) { <ide> <ide> tmpKeyFile, err := os.CreateTemp(tmpKeyFolderPath, "keyfile") <ide> assert.NilError(t, err) <add> defer tmpKeyFile.Close() <ide> <ide> _, err = loadOrCreateTrustKey(tmpKeyFile.Name()) <ide> assert.Check(t, is.ErrorContains(err, "Error loading key file")) <ide><path>pkg/directory/directory_test.go <ide> func TestSizeEmptyFile(t *testing.T) { <ide> if file, err = os.CreateTemp(dir, "file"); err != nil { <ide> t.Fatalf("failed to create file: %s", err) <ide> } <add> defer file.Close() <ide> <ide> var size int64 <ide> if size, _ = Size(context.Background(), file.Name()); size != 0 { <ide> func TestSizeNonemptyFile(t *testing.T) { <ide> if file, err = os.CreateTemp(dir, "file"); err != nil { <ide> t.Fatalf("failed to create file: %s", err) <ide> } <add> defer file.Close() <ide> <ide> d := []byte{97, 98, 99, 100, 101} <ide> file.Write(d) <ide> func TestSizeFileAndNestedDirectoryEmpty(t *testing.T) { <ide> if file, err = os.CreateTemp(dir, "file"); err != nil { <ide> t.Fatalf("failed to create file: %s", err) <ide> } <add> defer file.Close() <ide> <ide> d := []byte{100, 111, 99, 107, 101, 114} <ide> file.Write(d) <ide> func TestSizeFileAndNestedDirectoryNonempty(t *testing.T) { <ide> if file, err = os.CreateTemp(dir, "file"); err != nil { <ide> t.Fatalf("failed to create file: %s", err) <ide> } <add> defer file.Close() <ide> <ide> data := []byte{100, 111, 99, 107, 101, 114} <ide> file.Write(data) <ide> func TestSizeFileAndNestedDirectoryNonempty(t *testing.T) { <ide> if nestedFile, err = os.CreateTemp(dirNested, "file"); err != nil { <ide> t.Fatalf("failed to create file in nested directory: %s", err) <ide> } <add> defer nestedFile.Close() <ide> <ide> nestedData := []byte{100, 111, 99, 107, 101, 114} <ide> nestedFile.Write(nestedData) <ide><path>volume/service/db_test.go <ide> func TestSetGetMeta(t *testing.T) { <ide> assert.NilError(t, err) <ide> <ide> store := &VolumeStore{db: db} <add> defer store.Shutdown() <ide> <ide> _, err = store.getMeta("test") <ide> assert.Assert(t, is.ErrorContains(err, "")) <ide><path>volume/service/restore_test.go <ide> func TestRestore(t *testing.T) { <ide> <ide> s, err = NewStore(dir, drivers) <ide> assert.NilError(t, err) <add> defer s.Shutdown() <ide> <ide> v, err := s.Get(ctx, "test1") <ide> assert.NilError(t, err) <ide><path>volume/service/store_test.go <ide> func TestList(t *testing.T) { <ide> if err != nil { <ide> t.Fatal(err) <ide> } <add> defer s.Shutdown() <ide> ls, _, err = s.Find(ctx, nil) <ide> if err != nil { <ide> t.Fatal(err)
6
Javascript
Javascript
use correct arg name in assert benchmark
967d80594c7ab736ea7374f6b6a2cf75d782410a
<ide><path>test/parallel/test-benchmark-assert.js <ide> require('../common'); <ide> const runBenchmark = require('../common/benchmark'); <ide> <ide> runBenchmark( <del> 'assert', ['len=1', 'method=', 'n=1', 'prim=null', 'size=1', 'type=Int8Array'] <add> 'assert', <add> [ <add> 'len=1', <add> 'method=', <add> 'n=1', <add> 'primitive=null', <add> 'size=1', <add> 'type=Int8Array' <add> ] <ide> );
1
Ruby
Ruby
remove incorrect comment
6197eae3d4eefd621c857773020c0c2a05e1674b
<ide><path>Library/Homebrew/mach.rb <ide> def mach_data <ide> end <ide> mach_data <ide> rescue <del> # read() will raise if it sees EOF, which should only happen if the <del> # file is < 8 bytes. Otherwise, we raise if the file is not a Mach-O <del> # binary. In both cases, we want to return an empty array. <ide> [] <ide> end <ide> end
1
Go
Go
address more todos
3fea79bfd835960e3f6c9972305e350ee2e256b2
<ide><path>daemon/daemon.go <ide> import ( <ide> "github.com/docker/docker/pkg/graphdb" <ide> "github.com/docker/docker/pkg/ioutils" <ide> "github.com/docker/docker/pkg/namesgenerator" <add> "github.com/docker/docker/pkg/nat" <ide> "github.com/docker/docker/pkg/stringid" <ide> "github.com/docker/docker/pkg/sysinfo" <ide> "github.com/docker/docker/pkg/system" <ide> func getDefaultRouteMtu() (int, error) { <ide> } <ide> return 0, errNoDefaultRoute <ide> } <add> <add>// verifyContainerSettings performs validation of the hostconfig and config <add>// structures. <add>func (daemon *Daemon) verifyContainerSettings(hostConfig *runconfig.HostConfig, config *runconfig.Config) ([]string, error) { <add> <add> // First perform verification of settings common across all platforms. <add> if config != nil { <add> if config.WorkingDir != "" && !filepath.IsAbs(config.WorkingDir) { <add> return nil, fmt.Errorf("The working directory '%s' is invalid. It needs to be an absolute path.", config.WorkingDir) <add> } <add> } <add> <add> if hostConfig == nil { <add> return nil, nil <add> } <add> <add> for port := range hostConfig.PortBindings { <add> _, portStr := nat.SplitProtoPort(string(port)) <add> if _, err := nat.ParsePort(portStr); err != nil { <add> return nil, fmt.Errorf("Invalid port specification: %q", portStr) <add> } <add> for _, pb := range hostConfig.PortBindings[port] { <add> _, err := nat.NewPort(nat.SplitProtoPort(pb.HostPort)) <add> if err != nil { <add> return nil, fmt.Errorf("Invalid port specification: %q", pb.HostPort) <add> } <add> } <add> } <add> <add> // Now do platform-specific verification <add> return verifyPlatformContainerSettings(daemon, hostConfig, config) <add>} <ide><path>daemon/daemon_unix.go <ide> import ( <ide> "github.com/docker/docker/daemon/graphdriver" <ide> "github.com/docker/docker/pkg/archive" <ide> "github.com/docker/docker/pkg/fileutils" <del> "github.com/docker/docker/pkg/nat" <ide> "github.com/docker/docker/pkg/parsers" <ide> "github.com/docker/docker/pkg/parsers/kernel" <ide> "github.com/docker/docker/pkg/system" <ide> func checkKernel() error { <ide> return nil <ide> } <ide> <add>// adaptContainerSettings is called during container creation to modify any <add>// settings necessary in the HostConfig structure. <ide> func (daemon *Daemon) adaptContainerSettings(hostConfig *runconfig.HostConfig) { <ide> if hostConfig == nil { <ide> return <ide> func (daemon *Daemon) adaptContainerSettings(hostConfig *runconfig.HostConfig) { <ide> } <ide> } <ide> <del>func (daemon *Daemon) verifyContainerSettings(hostConfig *runconfig.HostConfig, config *runconfig.Config) ([]string, error) { <add>// verifyPlatformContainerSettings performs platform-specific validation of the <add>// hostconfig and config structures. <add>func verifyPlatformContainerSettings(daemon *Daemon, hostConfig *runconfig.HostConfig, config *runconfig.Config) ([]string, error) { <ide> var warnings []string <ide> <del> if config != nil { <del> // The check for a valid workdir path is made on the server rather than in the <del> // client. This is because we don't know the type of path (Linux or Windows) <del> // to validate on the client. <del> if config.WorkingDir != "" && !filepath.IsAbs(config.WorkingDir) { <del> return warnings, fmt.Errorf("The working directory '%s' is invalid. It needs to be an absolute path.", config.WorkingDir) <del> } <del> } <del> <del> if hostConfig == nil { <del> return warnings, nil <del> } <del> <del> for port := range hostConfig.PortBindings { <del> _, portStr := nat.SplitProtoPort(string(port)) <del> if _, err := nat.ParsePort(portStr); err != nil { <del> return warnings, fmt.Errorf("Invalid port specification: %q", portStr) <del> } <del> for _, pb := range hostConfig.PortBindings[port] { <del> _, err := nat.NewPort(nat.SplitProtoPort(pb.HostPort)) <del> if err != nil { <del> return warnings, fmt.Errorf("Invalid port specification: %q", pb.HostPort) <del> } <del> } <del> } <ide> if hostConfig.LxcConf.Len() > 0 && !strings.Contains(daemon.ExecutionDriver().Name(), "lxc") { <ide> return warnings, fmt.Errorf("Cannot use --lxc-conf with execdriver: %s", daemon.ExecutionDriver().Name()) <ide> } <ide><path>daemon/daemon_windows.go <ide> func checkKernel() error { <ide> return nil <ide> } <ide> <add>// adaptContainerSettings is called during container creation to modify any <add>// settings necessary in the HostConfig structure. <ide> func (daemon *Daemon) adaptContainerSettings(hostConfig *runconfig.HostConfig) { <del> // TODO Windows. <ide> } <ide> <del>func (daemon *Daemon) verifyContainerSettings(hostConfig *runconfig.HostConfig, config *runconfig.Config) ([]string, error) { <del> // TODO Windows. Verifications TBC <add>// verifyPlatformContainerSettings performs platform-specific validation of the <add>// hostconfig and config structures. <add>func verifyPlatformContainerSettings(daemon *Daemon, hostConfig *runconfig.HostConfig, config *runconfig.Config) ([]string, error) { <ide> return nil, nil <ide> } <ide>
3
Ruby
Ruby
fix railties tests in master
14c175c5727467e708ccbfaac1ae98c8f817b37d
<ide><path>railties/test/isolation/abstract_unit.rb <ide> module Generation <ide> # Build an application by invoking the generator and going through the whole stack. <ide> def build_app(options = {}) <ide> @prev_rails_env = ENV['RAILS_ENV'] <del> ENV['RAILS_ENV'] = 'development' <add> ENV['RAILS_ENV'] = 'development' <add> ENV['RAILS_SECRET_KEY_BASE'] ||= SecureRandom.hex(16) <ide> <ide> FileUtils.rm_rf(app_path) <ide> FileUtils.cp_r(app_template_path, app_path)
1
Java
Java
reuse mock request from the tcf in spring mvc test
bf06bf33abbf0d3169ae6465757808cf3bc9e4ab
<ide><path>spring-test/src/main/java/org/springframework/test/context/web/ServletTestExecutionListener.java <ide> /* <del> * Copyright 2002-2014 the original author or authors. <add> * Copyright 2002-2015 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; <ide> import org.springframework.util.Assert; <ide> import org.springframework.web.context.WebApplicationContext; <add>import org.springframework.web.context.request.RequestAttributes; <ide> import org.springframework.web.context.request.RequestContextHolder; <ide> import org.springframework.web.context.request.ServletWebRequest; <ide> <ide> public class ServletTestExecutionListener extends AbstractTestExecutionListener <ide> public static final String POPULATED_REQUEST_CONTEXT_HOLDER_ATTRIBUTE = Conventions.getQualifiedAttributeName( <ide> ServletTestExecutionListener.class, "populatedRequestContextHolder"); <ide> <add> /** <add> * Attribute name for a request attribute which indicates that the <add> * {@link MockHttpServletRequest} stored in the {@link RequestAttributes} <add> * in Spring Web's {@link RequestContextHolder} was created by the TestContext <add> * framework. <add> * <add> * <p>Permissible values include {@link Boolean#TRUE} and {@link Boolean#FALSE}. <add> * @since 4.2 <add> */ <add> public static final String CREATED_BY_THE_TESTCONTEXT_FRAMEWORK = Conventions.getQualifiedAttributeName( <add> ServletTestExecutionListener.class, "createdByTheTestContextFramework"); <add> <ide> private static final Log logger = LogFactory.getLog(ServletTestExecutionListener.class); <ide> <ide> <ide> private void setUpRequestContextIfNecessary(TestContext testContext) { <ide> <ide> MockServletContext mockServletContext = (MockServletContext) servletContext; <ide> MockHttpServletRequest request = new MockHttpServletRequest(mockServletContext); <add> request.setAttribute(CREATED_BY_THE_TESTCONTEXT_FRAMEWORK, Boolean.TRUE); <ide> MockHttpServletResponse response = new MockHttpServletResponse(); <ide> ServletWebRequest servletWebRequest = new ServletWebRequest(request, response); <ide> <ide><path>spring-test/src/main/java/org/springframework/test/web/servlet/MockMvc.java <ide> import org.springframework.mock.web.MockHttpServletRequest; <ide> import org.springframework.mock.web.MockHttpServletResponse; <ide> import org.springframework.util.Assert; <add>import org.springframework.web.context.request.RequestAttributes; <ide> import org.springframework.web.context.request.RequestContextHolder; <ide> import org.springframework.web.context.request.ServletRequestAttributes; <ide> <ide> public ResultActions perform(RequestBuilder requestBuilder) throws Exception { <ide> <ide> // [SPR-13217] Simulate RequestContextFilter to ensure that RequestAttributes are <ide> // populated before filters are invoked. <add> RequestAttributes previousAttributes = RequestContextHolder.getRequestAttributes(); <ide> RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request, response)); <ide> <ide> MockFilterChain filterChain = new MockFilterChain(this.servlet, this.filters); <ide> filterChain.doFilter(request, response); <ide> <ide> applyDefaultResultActions(mvcResult); <ide> <add> RequestContextHolder.setRequestAttributes(previousAttributes); <add> <ide> return new ResultActions() { <ide> <ide> @Override <ide><path>spring-test/src/main/java/org/springframework/test/web/servlet/request/MockHttpServletRequestBuilder.java <ide> /* <del> * Copyright 2002-2014 the original author or authors. <add> * Copyright 2002-2015 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import javax.servlet.ServletContext; <ide> import javax.servlet.ServletRequest; <ide> import javax.servlet.http.Cookie; <add>import javax.servlet.http.HttpServletRequest; <ide> <ide> import org.springframework.beans.Mergeable; <ide> import org.springframework.beans.factory.NoSuchBeanDefinitionException; <ide> import org.springframework.mock.web.MockHttpServletRequest; <ide> import org.springframework.mock.web.MockHttpServletResponse; <ide> import org.springframework.mock.web.MockHttpSession; <add>import org.springframework.test.context.web.ServletTestExecutionListener; <ide> import org.springframework.test.web.servlet.MockMvc; <ide> import org.springframework.util.Assert; <ide> import org.springframework.util.LinkedMultiValueMap; <ide> import org.springframework.util.StringUtils; <ide> import org.springframework.web.bind.annotation.ValueConstants; <ide> import org.springframework.web.context.WebApplicationContext; <add>import org.springframework.web.context.request.RequestAttributes; <add>import org.springframework.web.context.request.RequestContextHolder; <add>import org.springframework.web.context.request.ServletRequestAttributes; <ide> import org.springframework.web.context.support.WebApplicationContextUtils; <ide> import org.springframework.web.servlet.DispatcherServlet; <ide> import org.springframework.web.servlet.FlashMap; <ide> * <ide> * @author Rossen Stoyanchev <ide> * @author Arjen Poutsma <add> * @author Sam Brannen <ide> * @since 3.2 <ide> */ <ide> public class MockHttpServletRequestBuilder <ide> public final MockHttpServletRequest buildRequest(ServletContext servletContext) <ide> } <ide> <ide> /** <del> * Create a new {@link MockHttpServletRequest} based on the given <del> * {@link ServletContext}. Can be overridden in subclasses. <add> * Create a {@link MockHttpServletRequest}. <add> * <p>If an instance of {@code MockHttpServletRequest} that was created <add> * by the <em>Spring TestContext Framework</em> is available via the <add> * {@link RequestAttributes} bound to the current thread in <add> * {@link RequestContextHolder}, this method simply returns that instance. <add> * <p>Otherwise, this method creates a new {@code MockHttpServletRequest} <add> * based on the supplied {@link ServletContext}. <add> * <p>Can be overridden in subclasses. <add> * @see RequestContextHolder#getRequestAttributes() <add> * @see ServletRequestAttributes <add> * @see ServletTestExecutionListener#CREATED_BY_THE_TESTCONTEXT_FRAMEWORK <ide> */ <ide> protected MockHttpServletRequest createServletRequest(ServletContext servletContext) { <add> RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); <add> if (requestAttributes instanceof ServletRequestAttributes) { <add> HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest(); <add> if (request instanceof MockHttpServletRequest) { <add> MockHttpServletRequest mockRequest = (MockHttpServletRequest) request; <add> Object createdByTcf = mockRequest.getAttribute(ServletTestExecutionListener.CREATED_BY_THE_TESTCONTEXT_FRAMEWORK); <add> if (Boolean.TRUE.equals(createdByTcf)) { <add> return mockRequest; <add> } <add> } <add> } <add> <ide> return new MockHttpServletRequest(servletContext); <ide> } <ide> <ide><path>spring-test/src/main/java/org/springframework/test/web/servlet/request/MockMultipartHttpServletRequestBuilder.java <ide> /* <del> * Copyright 2002-2014 the original author or authors. <add> * Copyright 2002-2015 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public Object merge(Object parent) { <ide> return this; <ide> } <ide> <add> /** <add> * Create a new {@link MockMultipartHttpServletRequest} based on the <add> * supplied {@code ServletContext} and the {@code MockMultipartFiles} <add> * added to this builder. <add> * <p>Can be overridden in subclasses. <add> */ <ide> @Override <ide> protected final MockHttpServletRequest createServletRequest(ServletContext servletContext) { <ide> MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest(servletContext); <ide><path>spring-test/src/main/java/org/springframework/test/web/servlet/request/MockMvcRequestBuilders.java <ide> * See the License for the specific language governing permissions and <ide> * limitations under the License. <ide> */ <add> <ide> package org.springframework.test.web.servlet.request; <ide> <ide> import java.net.URI; <ide> import javax.servlet.ServletContext; <ide> <ide> import org.springframework.http.HttpMethod; <ide> import org.springframework.mock.web.MockHttpServletRequest; <add>import org.springframework.mock.web.MockMultipartHttpServletRequest; <ide> import org.springframework.test.web.servlet.MvcResult; <ide> import org.springframework.test.web.servlet.RequestBuilder; <ide> <ide> /** <del> * Static factory methods for {@link RequestBuilder}s. <add> * Static factory methods for {@link RequestBuilder RequestBuilders}. <add> * <add> * <h3>Integration with the Spring TestContext Framework</h3> <add> * <p>Methods in this class will reuse a <add> * {@link org.springframework.mock.web.MockServletContext MockServletContext} <add> * that was created by the Spring TestContext Framework. <add> * <add> * <p>Methods in this class that return a {@link MockHttpServletRequestBuilder} <add> * will reuse a {@link MockHttpServletRequest} that was created by the Spring <add> * TestContext Framework. <ide> * <del> * <p><strong>Eclipse users:</strong> Consider adding this class as a Java <del> * editor favorite. To navigate, open the Preferences and type "favorites". <add> * <h3>Eclipse Users</h3> <add> * <p>Consider adding this class as a Java editor favorite. To navigate to <add> * this setting, open the Preferences and type "favorites". <ide> * <ide> * @author Arjen Poutsma <ide> * @author Rossen Stoyanchev <ide> * @author Greg Turnquist <ide> * @author Sebastien Deleuze <add> * @author Sam Brannen <ide> * @since 3.2 <ide> */ <ide> public abstract class MockMvcRequestBuilders { <ide> public static MockHttpServletRequestBuilder request(HttpMethod httpMethod, URI u <ide> } <ide> <ide> /** <del> * Create a {@link MockHttpServletRequestBuilder} for a multipart request. <add> * Create a {@link MockMultipartHttpServletRequestBuilder} for a multipart request. <add> * <p>In contrast to methods in this class that return a <add> * {@link MockHttpServletRequestBuilder}, the builder returned by this <add> * method will always create a new {@link MockMultipartHttpServletRequest} <add> * that is <em>not</em> associated with a mock request created by the <add> * Spring TestContext Framework. <ide> * @param urlTemplate a URL template; the resulting URL will be encoded <ide> * @param urlVariables zero or more URL variables <ide> */ <ide> public static MockMultipartHttpServletRequestBuilder fileUpload(String urlTempla <ide> } <ide> <ide> /** <del> * Create a {@link MockHttpServletRequestBuilder} for a multipart request. <add> * Create a {@link MockMultipartHttpServletRequestBuilder} for a multipart request. <add> * <p>In contrast to methods in this class that return a <add> * {@link MockHttpServletRequestBuilder}, the builder returned by this <add> * method will always create a new {@link MockMultipartHttpServletRequest} <add> * that is <em>not</em> associated with a mock request created by the <add> * Spring TestContext Framework. <ide> * @param uri the URL <ide> * @since 4.0.3 <ide> */ <ide><path>spring-test/src/test/java/org/springframework/test/web/servlet/samples/spr/CustomRequestAttributesRequestContextHolderTests.java <add>/* <add> * Copyright 2002-2015 the original author or authors. <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> <add>package org.springframework.test.web.servlet.samples.spr; <add> <add>import javax.servlet.ServletContext; <add>import javax.servlet.ServletRequest; <add>import javax.servlet.http.HttpServletRequest; <add> <add>import org.junit.After; <add>import org.junit.Before; <add>import org.junit.Test; <add> <add>import org.springframework.context.annotation.AnnotatedBeanDefinitionReader; <add>import org.springframework.context.annotation.Bean; <add>import org.springframework.context.annotation.Configuration; <add>import org.springframework.mock.web.MockHttpServletRequest; <add>import org.springframework.mock.web.MockHttpServletResponse; <add>import org.springframework.mock.web.MockServletContext; <add>import org.springframework.test.context.web.ServletTestExecutionListener; <add>import org.springframework.test.web.servlet.MockMvc; <add>import org.springframework.web.bind.annotation.RequestMapping; <add>import org.springframework.web.bind.annotation.RestController; <add>import org.springframework.web.context.request.RequestAttributes; <add>import org.springframework.web.context.request.RequestContextHolder; <add>import org.springframework.web.context.request.ServletRequestAttributes; <add>import org.springframework.web.context.request.ServletWebRequest; <add>import org.springframework.web.context.support.GenericWebApplicationContext; <add>import org.springframework.web.servlet.config.annotation.EnableWebMvc; <add>import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; <add> <add>import static org.hamcrest.CoreMatchers.*; <add>import static org.junit.Assert.*; <add>import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; <add>import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; <add>import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*; <add> <add>/** <add> * Integration tests for SPR-13211 which verify that a custom mock request <add> * (i.e., one not created by {@link ServletTestExecutionListener}) is not <add> * reused by MockMvc. <add> * <add> * @author Sam Brannen <add> * @since 4.2 <add> * @see RequestContextHolderTests <add> */ <add>public class CustomRequestAttributesRequestContextHolderTests { <add> <add> private static final String FROM_CUSTOM_MOCK = "fromCustomMock"; <add> private static final String FROM_MVC_TEST_DEFAULT = "fromSpringMvcTestDefault"; <add> private static final String FROM_MVC_TEST_MOCK = "fromSpringMvcTestMock"; <add> <add> private final GenericWebApplicationContext wac = new GenericWebApplicationContext(); <add> <add> private MockMvc mockMvc; <add> <add> <add> @Before <add> public void setUp() { <add> ServletContext servletContext = new MockServletContext(); <add> MockHttpServletRequest mockRequest = new MockHttpServletRequest(servletContext); <add> mockRequest.setAttribute(FROM_CUSTOM_MOCK, FROM_CUSTOM_MOCK); <add> RequestContextHolder.setRequestAttributes(new ServletWebRequest(mockRequest, new MockHttpServletResponse())); <add> <add> this.wac.setServletContext(servletContext); <add> new AnnotatedBeanDefinitionReader(this.wac).register(WebConfig.class); <add> this.wac.refresh(); <add> <add> this.mockMvc = webAppContextSetup(this.wac) <add> .defaultRequest(get("/").requestAttr(FROM_MVC_TEST_DEFAULT, FROM_MVC_TEST_DEFAULT)) <add> .alwaysExpect(status().isOk()) <add> .build(); <add> } <add> <add> @Test <add> public void singletonController() throws Exception { <add> this.mockMvc.perform(get("/singletonController").requestAttr(FROM_MVC_TEST_MOCK, FROM_MVC_TEST_MOCK)); <add> } <add> <add> @After <add> public void verifyCustomRequestAttributesAreRestored() { <add> RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); <add> assertThat(requestAttributes, instanceOf(ServletRequestAttributes.class)); <add> HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest(); <add> <add> assertThat(request.getAttribute(FROM_CUSTOM_MOCK), is(FROM_CUSTOM_MOCK)); <add> assertThat(request.getAttribute(FROM_MVC_TEST_DEFAULT), is(nullValue())); <add> assertThat(request.getAttribute(FROM_MVC_TEST_MOCK), is(nullValue())); <add> <add> RequestContextHolder.resetRequestAttributes(); <add> this.wac.close(); <add> } <add> <add> <add> // ------------------------------------------------------------------- <add> <add> @Configuration <add> @EnableWebMvc <add> static class WebConfig extends WebMvcConfigurerAdapter { <add> <add> @Bean <add> public SingletonController singletonController() { <add> return new SingletonController(); <add> } <add> } <add> <add> @RestController <add> private static class SingletonController { <add> <add> @RequestMapping("/singletonController") <add> public void handle() { <add> assertRequestAttributes(); <add> } <add> } <add> <add> private static void assertRequestAttributes() { <add> RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); <add> assertThat(requestAttributes, instanceOf(ServletRequestAttributes.class)); <add> assertRequestAttributes(((ServletRequestAttributes) requestAttributes).getRequest()); <add> } <add> <add> private static void assertRequestAttributes(ServletRequest request) { <add> assertThat(request.getAttribute(FROM_CUSTOM_MOCK), is(nullValue())); <add> assertThat(request.getAttribute(FROM_MVC_TEST_DEFAULT), is(FROM_MVC_TEST_DEFAULT)); <add> assertThat(request.getAttribute(FROM_MVC_TEST_MOCK), is(FROM_MVC_TEST_MOCK)); <add> } <add> <add>} <ide><path>spring-test/src/test/java/org/springframework/test/web/servlet/samples/spr/RequestContextHolderTests.java <ide> import javax.servlet.ServletRequest; <ide> import javax.servlet.ServletResponse; <ide> <add>import org.junit.After; <ide> import org.junit.Before; <ide> import org.junit.Test; <ide> import org.junit.runner.RunWith; <ide> import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*; <ide> <ide> /** <del> * Tests for SPR-10025 (access to request attributes via RequestContextHolder), <del> * SPR-13217 (Populate RequestAttributes before invoking Filters in MockMvc), <del> * and SPR-13211 (re-use of mock request from the TestContext framework). <add> * Integration tests for the following use cases. <add> * <ul> <add> * <li>SPR-10025: Access to request attributes via RequestContextHolder</li> <add> * <li>SPR-13217: Populate RequestAttributes before invoking Filters in MockMvc</li> <add> * <li>SPR-13211: Reuse of mock request from the TestContext framework</li> <add> * </ul> <ide> * <ide> * @author Rossen Stoyanchev <ide> * @author Sam Brannen <add> * @see CustomRequestAttributesRequestContextHolderTests <ide> */ <ide> @RunWith(SpringJUnit4ClassRunner.class) <ide> @WebAppConfiguration <ide> public void sessionScopedService() throws Exception { <ide> this.mockMvc.perform(get("/sessionScopedService").requestAttr(FROM_MVC_TEST_MOCK, FROM_MVC_TEST_MOCK)); <ide> } <ide> <add> @After <add> public void verifyRestoredRequestAttributes() { <add> assertRequestAttributes(); <add> } <add> <ide> <ide> // ------------------------------------------------------------------- <ide> <ide> private static void assertRequestAttributes() { <ide> } <ide> <ide> private static void assertRequestAttributes(ServletRequest request) { <del> // TODO [SPR-13211] Assert that FROM_TCF_MOCK is FROM_TCF_MOCK, instead of NULL. <del> assertThat(request.getAttribute(FROM_TCF_MOCK), is(nullValue())); <add> assertThat(request.getAttribute(FROM_TCF_MOCK), is(FROM_TCF_MOCK)); <ide> assertThat(request.getAttribute(FROM_MVC_TEST_DEFAULT), is(FROM_MVC_TEST_DEFAULT)); <ide> assertThat(request.getAttribute(FROM_MVC_TEST_MOCK), is(FROM_MVC_TEST_MOCK)); <ide> assertThat(request.getAttribute(FROM_REQUEST_FILTER), is(FROM_REQUEST_FILTER));
7
Java
Java
add support for rxjava 2 maybe type
2075932780b9801c22222ddd2016ed63f360c894
<ide><path>spring-core/src/main/java/org/springframework/core/ReactiveAdapterRegistry.java <ide> <ide> import io.reactivex.BackpressureStrategy; <ide> import io.reactivex.Flowable; <add>import io.reactivex.Maybe; <ide> import org.reactivestreams.Publisher; <ide> import reactor.core.publisher.Flux; <ide> import reactor.core.publisher.Mono; <ide> * registered via {@link #registerFluxAdapter} and {@link #registerMonoAdapter}. <ide> * <ide> * @author Rossen Stoyanchev <add> * @author Sebastien Deleuze <ide> * @since 5.0 <ide> */ <ide> public class ReactiveAdapterRegistry { <ide> public void register(ReactiveAdapterRegistry registry) { <ide> source -> Flowable.fromPublisher(source).toObservable().singleElement().toSingle(), <ide> new ReactiveAdapter.Descriptor(false, false, false) <ide> ); <add> registry.registerMonoAdapter(Maybe.class, <add> source -> Mono.from(((Maybe<?>) source).toFlowable()), <add> source -> Flowable.fromPublisher(source).toObservable().singleElement(), <add> new ReactiveAdapter.Descriptor(false, true, false) <add> ); <ide> registry.registerMonoAdapter(io.reactivex.Completable.class, <ide> source -> Mono.from(((io.reactivex.Completable) source).toFlowable()), <ide> source -> Flowable.fromPublisher(source).toObservable().ignoreElements(), <ide><path>spring-core/src/test/java/org/springframework/core/convert/support/ReactiveAdapterRegistryTests.java <ide> import java.util.concurrent.CompletableFuture; <ide> <ide> import io.reactivex.Flowable; <add>import io.reactivex.Maybe; <ide> import org.junit.Before; <ide> import org.junit.Test; <ide> import org.reactivestreams.Publisher; <ide> public void getDefaultAdapters() throws Exception { <ide> testFluxAdapter(Flowable.class); <ide> testFluxAdapter(io.reactivex.Observable.class); <ide> testMonoAdapter(io.reactivex.Single.class); <add> testMonoAdapter(Maybe.class); <ide> testMonoAdapter(io.reactivex.Completable.class); <ide> } <ide> <ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/result/method/annotation/HttpEntityArgumentResolverTests.java <ide> <ide> import io.reactivex.BackpressureStrategy; <ide> import io.reactivex.Flowable; <add>import io.reactivex.Maybe; <ide> import org.junit.Before; <ide> import org.junit.Test; <ide> import reactor.core.publisher.Flux; <ide> public void supports() throws Exception { <ide> testSupports(httpEntityType(forClassWithGenerics(Mono.class, String.class))); <ide> testSupports(httpEntityType(forClassWithGenerics(Single.class, String.class))); <ide> testSupports(httpEntityType(forClassWithGenerics(io.reactivex.Single.class, String.class))); <add> testSupports(httpEntityType(forClassWithGenerics(Maybe.class, String.class))); <ide> testSupports(httpEntityType(forClassWithGenerics(CompletableFuture.class, String.class))); <ide> testSupports(httpEntityType(forClassWithGenerics(Flux.class, String.class))); <ide> testSupports(httpEntityType(forClassWithGenerics(Observable.class, String.class))); <ide> public void emptyBodyWithRxJava2Single() throws Exception { <ide> .verify(entity.getBody().toFlowable()); <ide> } <ide> <add> @Test <add> public void emptyBodyWithRxJava2Maybe() throws Exception { <add> ResolvableType type = httpEntityType(forClassWithGenerics(Maybe.class, String.class)); <add> HttpEntity<Maybe<String>> entity = resolveValueWithEmptyBody(type); <add> <add> ScriptedSubscriber <add> .create().expectNextCount(0) <add> .expectComplete() <add> .verify(entity.getBody().toFlowable()); <add> } <add> <ide> @Test <ide> public void emptyBodyWithObservable() throws Exception { <ide> ResolvableType type = httpEntityType(forClassWithGenerics(Observable.class, String.class)); <ide> public void httpEntityWithRxJava2SingleBody() throws Exception { <ide> assertEquals("line1", httpEntity.getBody().blockingGet()); <ide> } <ide> <add> @Test <add> public void httpEntityWithRxJava2MaybeBody() throws Exception { <add> String body = "line1"; <add> ResolvableType type = httpEntityType(forClassWithGenerics(Maybe.class, String.class)); <add> HttpEntity<Maybe<String>> httpEntity = resolveValue(type, body); <add> <add> assertEquals(this.request.getHeaders(), httpEntity.getHeaders()); <add> assertEquals("line1", httpEntity.getBody().blockingGet()); <add> } <add> <ide> @Test <ide> public void httpEntityWithCompletableFutureBody() throws Exception { <ide> String body = "line1"; <ide> void handle( <ide> HttpEntity<Mono<String>> monoBody, <ide> HttpEntity<Flux<String>> fluxBody, <ide> HttpEntity<Single<String>> singleBody, <del> HttpEntity<io.reactivex.Single<String>> xJava2SingleBody, <add> HttpEntity<io.reactivex.Single<String>> rxJava2SingleBody, <add> HttpEntity<Maybe<String>> rxJava2MaybeBody, <ide> HttpEntity<Observable<String>> observableBody, <ide> HttpEntity<io.reactivex.Observable<String>> rxJava2ObservableBody, <ide> HttpEntity<Flowable<String>> flowableBody, <ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/result/method/annotation/MessageReaderArgumentResolverTests.java <ide> import javax.xml.bind.annotation.XmlRootElement; <ide> <ide> import io.reactivex.Flowable; <add>import io.reactivex.Maybe; <ide> import org.junit.Before; <ide> import org.junit.Test; <ide> import reactor.core.publisher.Flux; <ide> public void rxJava2SingleTestBean() throws Exception { <ide> assertEquals(new TestBean("f1", "b1"), single.blockingGet()); <ide> } <ide> <add> @Test <add> public void rxJava2MaybeTestBean() throws Exception { <add> String body = "{\"bar\":\"b1\",\"foo\":\"f1\"}"; <add> ResolvableType type = forClassWithGenerics(Maybe.class, TestBean.class); <add> MethodParameter param = this.testMethod.resolveParam(type); <add> Maybe<TestBean> maybe = resolveValue(param, body); <add> <add> assertEquals(new TestBean("f1", "b1"), maybe.blockingGet()); <add> } <add> <ide> @Test <ide> public void observableTestBean() throws Exception { <ide> String body = "[{\"bar\":\"b1\",\"foo\":\"f1\"},{\"bar\":\"b2\",\"foo\":\"f2\"}]"; <ide> private void handle( <ide> @Validated Flux<TestBean> fluxTestBean, <ide> Single<TestBean> singleTestBean, <ide> io.reactivex.Single<TestBean> rxJava2SingleTestBean, <add> Maybe<TestBean> rxJava2MaybeTestBean, <ide> Observable<TestBean> observableTestBean, <ide> io.reactivex.Observable<TestBean> rxJava2ObservableTestBean, <ide> Flowable<TestBean> flowableTestBean, <ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestBodyArgumentResolverTests.java <ide> import java.util.concurrent.CompletableFuture; <ide> import java.util.function.Predicate; <ide> <add>import io.reactivex.Maybe; <ide> import org.junit.Before; <ide> import org.junit.Test; <ide> import reactor.core.publisher.Flux; <ide> import reactor.core.publisher.Mono; <ide> import reactor.test.subscriber.ScriptedSubscriber; <del>import rx.Completable; <ide> import rx.Observable; <ide> import rx.RxReactiveStreams; <ide> import rx.Single; <ide> public void emptyBodyWithSingle() throws Exception { <ide> .verify(RxReactiveStreams.toPublisher(single)); <ide> } <ide> <add> @Test <add> public void emptyBodyWithMaybe() throws Exception { <add> ResolvableType type = forClassWithGenerics(Maybe.class, String.class); <add> <add> Maybe<String> maybe = resolveValueWithEmptyBody(type, true); <add> ScriptedSubscriber.<String>create().expectNextCount(0) <add> .expectError(ServerWebInputException.class) <add> .verify(maybe.toFlowable()); <add> <add> maybe = resolveValueWithEmptyBody(type, false); <add> ScriptedSubscriber.<String>create().expectNextCount(0) <add> .expectComplete() <add> .verify(maybe.toFlowable()); <add> } <add> <ide> @Test <ide> public void emptyBodyWithObservable() throws Exception { <ide> ResolvableType type = forClassWithGenerics(Observable.class, String.class); <ide> void handle( <ide> @RequestBody Flux<String> flux, <ide> @RequestBody Single<String> single, <ide> @RequestBody io.reactivex.Single<String> rxJava2Single, <add> @RequestBody Maybe<String> rxJava2Maybe, <ide> @RequestBody Observable<String> obs, <ide> @RequestBody io.reactivex.Observable<String> rxjava2Obs, <ide> @RequestBody CompletableFuture<String> future, <ide> void handle( <ide> @RequestBody(required = false) Flux<String> fluxNotRequired, <ide> @RequestBody(required = false) Single<String> singleNotRequired, <ide> @RequestBody(required = false) io.reactivex.Single<String> rxJava2SingleNotRequired, <add> @RequestBody(required = false) Maybe<String> rxJava2MaybeNotRequired, <ide> @RequestBody(required = false) Observable<String> obsNotRequired, <ide> @RequestBody(required = false) io.reactivex.Observable<String> rxjava2ObsNotRequired, <ide> @RequestBody(required = false) CompletableFuture<String> futureNotRequired, <ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingMessageConversionIntegrationTests.java <ide> import javax.xml.bind.annotation.XmlRootElement; <ide> <ide> import io.reactivex.Flowable; <add>import io.reactivex.Maybe; <ide> import org.junit.Test; <ide> import org.reactivestreams.Publisher; <ide> import reactor.core.publisher.Flux; <ide> public void personTransformWithRxJava2Single() throws Exception { <ide> JSON, Person.class).getBody()); <ide> } <ide> <add> @Test <add> public void personTransformWithRxJava2Maybe() throws Exception { <add> assertEquals(new Person("ROBERT"), <add> performPost("/person-transform/rxjava2-maybe", JSON, new Person("Robert"), <add> JSON, Person.class).getBody()); <add> } <add> <ide> @Test <ide> public void personTransformWithPublisher() throws Exception { <ide> List<?> req = asList(new Person("Robert"), new Person("Marie")); <ide> public io.reactivex.Single<Person> transformRxJava2Single(@RequestBody io.reacti <ide> return personFuture.map(person -> new Person(person.getName().toUpperCase())); <ide> } <ide> <add> @PostMapping("/rxjava2-maybe") <add> public Maybe<Person> transformRxJava2Maybe(@RequestBody Maybe<Person> personFuture) { <add> return personFuture.map(person -> new Person(person.getName().toUpperCase())); <add> } <add> <ide> @PostMapping("/publisher") <ide> public Publisher<Person> transformPublisher(@RequestBody Publisher<Person> persons) { <ide> return Flux
6
Text
Text
add help command for conda.
9a64e1f1e65e1751f9ec4380b1065425ebe91ae2
<ide><path>guide/english/python/anaconda/index.md <ide> letter of the option. So ``--name`` and ``-n`` are the same, and <ide> <ide> For full usage of each command, including abbreviations, see <ide> [Command reference](https://conda.io/docs/commands.html). <add>You can also type ``conda`` or ``conda help`` to access the list of commands and help text for each command available. <ide> <ide> <ide> ### Sources
1
Ruby
Ruby
tweak a test so the queries match
fc0b62597f9c34bd028fd91457b8865eea42cc2d
<ide><path>activerecord/test/cases/relations_test.rb <ide> def test_only <ide> assert_equal Post.where(author_id: 1).to_a, author_posts.to_a <ide> <ide> all_posts = relation.only(:limit) <del> assert_equal Post.limit(1).to_a.first, all_posts.first <add> assert_equal Post.limit(1).to_a, all_posts.to_a <ide> end <ide> <ide> def test_anonymous_extension
1
Go
Go
fix network feature detection on first start
b241e2008e50f2d8e045642d6fd511a1af9bb52b
<ide><path>daemon/daemon.go <ide> func NewDaemon(ctx context.Context, config *config.Config, pluginStore *plugin.S <ide> return nil, err <ide> } <ide> <del> sysInfo := d.RawSysInfo() <del> for _, w := range sysInfo.Warnings { <del> logrus.Warn(w) <del> } <ide> // Check if Devices cgroup is mounted, it is hard requirement for container security, <ide> // on Linux. <del> if runtime.GOOS == "linux" && !sysInfo.CgroupDevicesEnabled && !userns.RunningInUserNS() { <add> // <add> // Important: we call getSysInfo() directly here, without storing the results, <add> // as networking has not yet been set up, so we only have partial system info <add> // at this point. <add> // <add> // TODO(thaJeztah) add a utility to only collect the CgroupDevicesEnabled information <add> if runtime.GOOS == "linux" && !userns.RunningInUserNS() && !getSysInfo(d).CgroupDevicesEnabled { <ide> return nil, errors.New("Devices cgroup isn't mounted") <ide> } <ide> <ide> func NewDaemon(ctx context.Context, config *config.Config, pluginStore *plugin.S <ide> close(d.startupDone) <ide> <ide> info := d.SystemInfo() <add> for _, w := range info.Warnings { <add> logrus.Warn(w) <add> } <ide> <ide> engineInfo.WithValues( <ide> dockerversion.Version, <ide> func (daemon *Daemon) RawSysInfo() *sysinfo.SysInfo { <ide> // We check if sysInfo is not set here, to allow some test to <ide> // override the actual sysInfo. <ide> if daemon.sysInfo == nil { <del> daemon.loadSysInfo() <add> daemon.sysInfo = getSysInfo(daemon) <ide> } <ide> }) <ide> <ide><path>daemon/daemon_unix.go <ide> func (daemon *Daemon) setupSeccompProfile() error { <ide> return nil <ide> } <ide> <del>func (daemon *Daemon) loadSysInfo() { <add>func getSysInfo(daemon *Daemon) *sysinfo.SysInfo { <ide> var siOpts []sysinfo.Opt <ide> if daemon.getCgroupDriver() == cgroupSystemdDriver { <ide> if euid := os.Getenv("ROOTLESSKIT_PARENT_EUID"); euid != "" { <ide> siOpts = append(siOpts, sysinfo.WithCgroup2GroupPath("/user.slice/user-"+euid+".slice")) <ide> } <ide> } <del> daemon.sysInfo = sysinfo.New(siOpts...) <add> return sysinfo.New(siOpts...) <ide> } <ide> <ide> func (daemon *Daemon) initLibcontainerd(ctx context.Context) error { <ide><path>daemon/daemon_unsupported.go <ide> const platformSupported = false <ide> func setupResolvConf(config *config.Config) { <ide> } <ide> <del>func (daemon *Daemon) loadSysInfo() { <del> daemon.sysInfo = sysinfo.New() <add>func getSysInfo(daemon *Daemon) *sysinfo.SysInfo { <add> return sysinfo.New() <ide> } <ide><path>daemon/daemon_windows.go <ide> func (daemon *Daemon) loadRuntimes() error { <ide> <ide> func setupResolvConf(config *config.Config) {} <ide> <del>func (daemon *Daemon) loadSysInfo() { <del> daemon.sysInfo = sysinfo.New() <add>func getSysInfo(daemon *Daemon) *sysinfo.SysInfo { <add> return sysinfo.New() <ide> } <ide> <ide> func (daemon *Daemon) initLibcontainerd(ctx context.Context) error {
4
Python
Python
convert objectives to keras backend
6ffa18e3905ac8dac016111063db4bbacbc788c7
<ide><path>keras/objectives.py <ide> from __future__ import absolute_import <del>import theano <del>import theano.tensor as T <ide> import numpy as np <del> <del> <del>if theano.config.floatX == 'float64': <del> epsilon = 1.0e-9 <del>else: <del> epsilon = 1.0e-7 <add>from . import backend as K <ide> <ide> <ide> def mean_squared_error(y_true, y_pred): <del> return T.sqr(y_pred - y_true).mean(axis=-1) <add> return K.mean(K.square(y_pred - y_true), axis=-1) <ide> <ide> <ide> def root_mean_squared_error(y_true, y_pred): <del> return T.sqrt(T.sqr(y_pred - y_true).mean(axis=-1)) <add> return K.mean(K.square(K.square(y_pred - y_true), axis=-1)) <ide> <ide> <ide> def mean_absolute_error(y_true, y_pred): <del> return T.abs_(y_pred - y_true).mean(axis=-1) <add> return K.mean(K.abs(y_pred - y_true), axis=-1) <ide> <ide> <ide> def mean_absolute_percentage_error(y_true, y_pred): <del> return T.abs_((y_true - y_pred) / T.clip(T.abs_(y_true), epsilon, np.inf)).mean(axis=-1) * 100. <add> diff = K.abs((y_true - y_pred) / K.clip(K.abs(y_true), K._EPSILON, np.inf)) <add> return 100. * K.mean(diff, axis=-1) <ide> <ide> <ide> def mean_squared_logarithmic_error(y_true, y_pred): <del> return T.sqr(T.log(T.clip(y_pred, epsilon, np.inf) + 1.) - T.log(T.clip(y_true, epsilon, np.inf) + 1.)).mean(axis=-1) <add> first_log = K.log(K.clip(y_pred, K._EPSILON, np.inf) + 1.) <add> second_log = K.log(K.clip(y_true, K._EPSILON, np.inf) + 1.) <add> return K.mean(K.square(first_log - second_log), axis=-1) <ide> <ide> <ide> def squared_hinge(y_true, y_pred): <del> return T.sqr(T.maximum(1. - y_true * y_pred, 0.)).mean(axis=-1) <add> return K.mean(K.square(K.maximum(1. - y_true * y_pred, 0.)), axis=-1) <ide> <ide> <ide> def hinge(y_true, y_pred): <del> return T.maximum(1. - y_true * y_pred, 0.).mean(axis=-1) <add> return K.mean(K.maximum(1. - y_true * y_pred, 0.), axis=-1) <ide> <ide> <ide> def categorical_crossentropy(y_true, y_pred): <ide> '''Expects a binary class matrix instead of a vector of scalar classes <ide> ''' <del> y_pred = T.clip(y_pred, epsilon, 1.0 - epsilon) <del> # scale preds so that the class probas of each sample sum to 1 <del> y_pred /= y_pred.sum(axis=-1, keepdims=True) <del> cce = T.nnet.categorical_crossentropy(y_pred, y_true) <del> return cce <add> return K.mean(K.categorical_crossentropy(y_pred, y_true), axis=-1) <ide> <ide> <ide> def binary_crossentropy(y_true, y_pred): <del> y_pred = T.clip(y_pred, epsilon, 1.0 - epsilon) <del> bce = T.nnet.binary_crossentropy(y_pred, y_true).mean(axis=-1) <del> return bce <add> return K.mean(K.binary_crossentropy(y_pred, y_true), axis=-1) <ide> <ide> <ide> def poisson_loss(y_true, y_pred): <del> return T.mean(y_pred - y_true * T.log(y_pred + epsilon), axis=-1) <add> return K.mean(y_pred - y_true * K.log(y_pred + K._EPSILON), axis=-1) <ide> <ide> # aliases <ide> mse = MSE = mean_squared_error
1
Python
Python
return serverid for backups in rackspace driver
b1d65c57f9855aae8507cab81ed466dfaace60e7
<ide><path>libcloud/drivers/rackspace.py <ide> def to_images(self, object): <ide> def _to_image(self, el): <ide> i = NodeImage(id=el.get('id'), <ide> name=el.get('name'), <del> driver=self.connection.driver) <add> driver=self.connection.driver, <add> extra = { 'serverId' : el.get('serverId') }) <ide> return i <ide><path>test/test_rackspace.py <ide> def test_list_sizes(self): <ide> <ide> def test_list_images(self): <ide> ret = self.driver.list_images() <add> self.assertEqual(ret[10].extra['serverId'], None) <add> self.assertEqual(ret[11].extra['serverId'], '91221') <ide> <ide> def test_create_node(self): <ide> image = NodeImage(id=11, name='Ubuntu 8.10 (intrepid)', driver=self.driver) <ide> def _v1_0_slug_flavors_detail(self, method, url, body, headers): <ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK]) <ide> <ide> def _v1_0_slug_images_detail(self, method, url, body, headers): <del> body = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?><images xmlns="http://docs.rackspacecloud.com/servers/api/v1.0"><image status="ACTIVE" created="2009-07-20T09:14:37-05:00" updated="2009-07-20T09:14:37-05:00" name="CentOS 5.2" id="2"/><image status="ACTIVE" created="2009-07-20T09:14:37-05:00" updated="2009-07-20T09:14:37-05:00" name="Gentoo 2008.0" id="3"/><image status="ACTIVE" created="2009-07-20T09:14:37-05:00" updated="2009-07-20T09:14:37-05:00" name="Debian 5.0 (lenny)" id="4"/><image status="ACTIVE" created="2009-07-20T09:14:37-05:00" updated="2009-07-20T09:14:37-05:00" name="Fedora 10 (Cambridge)" id="5"/><image status="ACTIVE" created="2009-07-20T09:14:37-05:00" updated="2009-07-20T09:14:37-05:00" name="CentOS 5.3" id="7"/><image status="ACTIVE" created="2009-07-20T09:14:37-05:00" updated="2009-07-20T09:14:37-05:00" name="Ubuntu 9.04 (jaunty)" id="8"/><image status="ACTIVE" created="2009-07-20T09:14:37-05:00" updated="2009-07-20T09:14:37-05:00" name="Arch 2009.02" id="9"/><image status="ACTIVE" created="2009-07-20T09:14:37-05:00" updated="2009-07-20T09:14:37-05:00" name="Ubuntu 8.04.2 LTS (hardy)" id="10"/><image status="ACTIVE" created="2009-07-20T09:14:37-05:00" updated="2009-07-20T09:14:37-05:00" name="Ubuntu 8.10 (intrepid)" id="11"/><image status="ACTIVE" created="2009-07-20T09:14:37-05:00" updated="2009-07-20T09:14:37-05:00" name="Red Hat EL 5.3" id="12"/><image status="ACTIVE" created="2009-07-20T09:14:37-05:00" updated="2009-07-20T09:14:37-05:00" name="Fedora 11 (Leonidas)" id="13"/></images>""" <add> body = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?><images xmlns="http://docs.rackspacecloud.com/servers/api/v1.0"><image status="ACTIVE" created="2009-07-20T09:14:37-05:00" updated="2009-07-20T09:14:37-05:00" name="CentOS 5.2" id="2"/><image status="ACTIVE" created="2009-07-20T09:14:37-05:00" updated="2009-07-20T09:14:37-05:00" name="Gentoo 2008.0" id="3"/><image status="ACTIVE" created="2009-07-20T09:14:37-05:00" updated="2009-07-20T09:14:37-05:00" name="Debian 5.0 (lenny)" id="4"/><image status="ACTIVE" created="2009-07-20T09:14:37-05:00" updated="2009-07-20T09:14:37-05:00" name="Fedora 10 (Cambridge)" id="5"/><image status="ACTIVE" created="2009-07-20T09:14:37-05:00" updated="2009-07-20T09:14:37-05:00" name="CentOS 5.3" id="7"/><image status="ACTIVE" created="2009-07-20T09:14:37-05:00" updated="2009-07-20T09:14:37-05:00" name="Ubuntu 9.04 (jaunty)" id="8"/><image status="ACTIVE" created="2009-07-20T09:14:37-05:00" updated="2009-07-20T09:14:37-05:00" name="Arch 2009.02" id="9"/><image status="ACTIVE" created="2009-07-20T09:14:37-05:00" updated="2009-07-20T09:14:37-05:00" name="Ubuntu 8.04.2 LTS (hardy)" id="10"/><image status="ACTIVE" created="2009-07-20T09:14:37-05:00" updated="2009-07-20T09:14:37-05:00" name="Ubuntu 8.10 (intrepid)" id="11"/><image status="ACTIVE" created="2009-07-20T09:14:37-05:00" updated="2009-07-20T09:14:37-05:00" name="Red Hat EL 5.3" id="12"/><image status="ACTIVE" created="2009-07-20T09:14:37-05:00" updated="2009-07-20T09:14:37-05:00" name="Fedora 11 (Leonidas)" id="13"/><image status="ACTIVE" progress="100" created="2009-11-29T20:22:09-06:00" updated="2009-11-29T20:24:08-06:00" serverId="91221" name="daily" id="191234"/></images>""" <ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK]) <ide> <ide> def _v1_0_slug_servers(self, method, url, body, headers):
2
Javascript
Javascript
fix all warnings for missing keys
e4fe55708972c0b09674e99b4841830339620196
<ide><path>Examples/UIExplorer/AnimatedExample.js <ide> exports.examples = [ <ide> {['Composite', 'Easing', 'Animations!'].map( <ide> (text, ii) => ( <ide> <Animated.View <add> key={text} <ide> style={[styles.content, { <ide> left: this.anims[ii] <ide> }]}> <ide><path>Examples/UIExplorer/AsyncStorageExample.js <ide> var BasicStorageExample = React.createClass({ <ide> </Text> <ide> <Text>{' '}</Text> <ide> <Text>Messages:</Text> <del> {this.state.messages.map((m) => <Text>{m}</Text>)} <add> {this.state.messages.map((m) => <Text key={m}>{m}</Text>)} <ide> </View> <ide> ); <ide> }, <ide><path>Examples/UIExplorer/CameraRollExample.ios.js <ide> var CameraRollExample = React.createClass({ <ide> var location = asset.node.location.longitude ? <ide> JSON.stringify(asset.node.location) : 'Unknown location'; <ide> return ( <del> <TouchableOpacity onPress={ this.loadAsset.bind( this, asset ) }> <del> <View key={asset} style={styles.row}> <add> <TouchableOpacity key={asset} onPress={ this.loadAsset.bind( this, asset ) }> <add> <View style={styles.row}> <ide> <Image <ide> source={asset.node.image} <ide> style={imageStyle} <ide><path>Examples/UIExplorer/PullToRefreshViewAndroidExample.android.js <ide> const PullToRefreshViewAndroidExample = React.createClass({ <ide> }, <ide> <ide> render() { <del> const rows = this.state.rowData.map((row) => { <del> return <Row data={row} onClick={this._onClick}/>; <add> const rows = this.state.rowData.map((row, ii) => { <add> return <Row key={ii} data={row} onClick={this._onClick}/>; <ide> }); <ide> return ( <ide> <PullToRefreshViewAndroid <ide><path>Examples/UIExplorer/StatusBarIOSExample.js <ide> exports.examples = [{ <ide> return ( <ide> <View> <ide> {['default', 'light-content'].map((style) => <del> <TouchableHighlight style={styles.wrapper} <add> <TouchableHighlight key={style} style={styles.wrapper} <ide> onPress={() => StatusBarIOS.setStyle(style)}> <ide> <View style={styles.button}> <ide> <Text>setStyle('{style}')</Text> <ide> exports.examples = [{ <ide> return ( <ide> <View> <ide> {['default', 'light-content'].map((style) => <del> <TouchableHighlight style={styles.wrapper} <add> <TouchableHighlight key={style} style={styles.wrapper} <ide> onPress={() => StatusBarIOS.setStyle(style, true)}> <ide> <View style={styles.button}> <ide> <Text>setStyle('{style}', true)</Text> <ide> exports.examples = [{ <ide> return ( <ide> <View> <ide> {['none', 'fade', 'slide'].map((animation) => <del> <View> <add> <View key={animation}> <ide> <TouchableHighlight style={styles.wrapper} <ide> onPress={() => StatusBarIOS.setHidden(true, animation)}> <ide> <View style={styles.button}> <ide><path>Examples/UIExplorer/TextInputExample.ios.js <ide> class TokenizedTextExample extends React.Component { <ide> //highlight hashtags <ide> parts = parts.map((text) => { <ide> if (/^#/.test(text)) { <del> return <Text style={styles.hashtag}>{text}</Text>; <add> return <Text key={text} style={styles.hashtag}>{text}</Text>; <ide> } else { <ide> return text; <ide> } <ide><path>Examples/UIExplorer/TimerExample.js <ide> exports.examples = [ <ide> } <ide> return ( <ide> <View> <del> {timer} <add> {this.state.showTimer && this._renderTimer()} <ide> <UIExplorerButton onPress={this._toggleTimer}> <del> {toggleText} <add> {this.state.showTimer ? 'Unmount timer' : 'Mount new timer'} <add> </UIExplorerButton> <add> </View> <add> ); <add> }, <add> <add> _renderTimer: function() { <add> return ( <add> <View> <add> <TimerTester ref="interval" dt={25} type="setInterval" /> <add> <UIExplorerButton onPress={() => this.refs.interval.clear() }> <add> Clear interval <ide> </UIExplorerButton> <ide> </View> <ide> );
7
PHP
PHP
fix more typehints
1db4772be8a0b73cda7d5173df112064505d1ee1
<ide><path>src/Database/Schema/TableSchema.php <ide> public function defaultValues(): array <ide> * {@inheritDoc} <ide> * @throws \Cake\Database\Exception <ide> */ <del> public function addIndex(string $name, $attrs): TableSchemaInterface <add> public function addIndex(string $name, $attrs) <ide> { <ide> if (is_string($attrs)) { <ide> $attrs = ['type' => $attrs]; <ide> public function primaryKey(): array <ide> * {@inheritDoc} <ide> * @throws \Cake\Database\Exception <ide> */ <del> public function addConstraint(string $name, $attrs): TableSchemaInterface <add> public function addConstraint(string $name, $attrs) <ide> { <ide> if (is_string($attrs)) { <ide> $attrs = ['type' => $attrs]; <ide> public function addConstraint(string $name, $attrs): TableSchemaInterface <ide> /** <ide> * @inheritDoc <ide> */ <del> public function dropConstraint(string $name): TableSchemaInterface <add> public function dropConstraint(string $name) <ide> { <ide> if (isset($this->_constraints[$name])) { <ide> unset($this->_constraints[$name]); <ide><path>src/Database/Schema/TableSchemaInterface.php <ide> public function primaryKey(): array; <ide> * @param string $name The name of the index. <ide> * @param array|string $attrs The attributes for the index. <ide> * If string it will be used as `type`. <del> * @return self <add> * @return $this <ide> */ <del> public function addIndex(string $name, $attrs): self; <add> public function addIndex(string $name, $attrs); <ide> <ide> /** <ide> * Read information about an index based on name. <ide> public function indexes(): array; <ide> * @param string $name The name of the constraint. <ide> * @param array|string $attrs The attributes for the constraint. <ide> * If string it will be used as `type`. <del> * @return self <add> * @return $this <ide> */ <del> public function addConstraint(string $name, $attrs): self; <add> public function addConstraint(string $name, $attrs); <ide> <ide> /** <ide> * Read information about a constraint based on name. <ide> public function getConstraint(string $name): ?array; <ide> * Remove a constraint. <ide> * <ide> * @param string $name Name of the constraint to remove <del> * @return self <add> * @return $this <ide> */ <del> public function dropConstraint(string $name): self; <add> public function dropConstraint(string $name); <ide> <ide> /** <ide> * Get the names of all the constraints in the table. <ide><path>src/Datasource/Paginator.php <ide> class Paginator implements PaginatorInterface <ide> * @return \Cake\Datasource\ResultSetInterface Query results <ide> * @throws \Cake\Datasource\Exception\PageOutOfBoundsException <ide> */ <del> public function paginate(object $object, array $params = [], array $settings = []) <add> public function paginate(object $object, array $params = [], array $settings = []): ResultSetInterface <ide> { <ide> $query = null; <ide> if ($object instanceof QueryInterface) { <ide><path>src/Datasource/PaginatorInterface.php <ide> interface PaginatorInterface <ide> * to paginate. <ide> * @param array $params Request params <ide> * @param array $settings The settings/configuration used for pagination. <del> * @return \Cake\Datasource\ResultSetInterface|array Query results <add> * @return \Cake\Datasource\ResultSetInterface Query results <ide> */ <del> public function paginate(object $object, array $params = [], array $settings = []); <add> public function paginate(object $object, array $params = [], array $settings = []): ResultSetInterface; <ide> <ide> /** <ide> * Get paging params after pagination operation. <ide><path>src/Datasource/QueryCacher.php <ide> protected function _resolveKey(object $query): string <ide> /** <ide> * Get the cache engine. <ide> * <del> * @return \Cake\Cache\CacheEngine <add> * @return \Cake\Cache\CacheEngineInterface&\Psr\SimpleCache\CacheInterface <ide> */ <del> protected function _resolveCacher(): CacheEngine <add> protected function _resolveCacher() <ide> { <ide> if (is_string($this->_config)) { <ide> return Cache::pool($this->_config); <ide><path>src/Datasource/QueryTrait.php <ide> trait QueryTrait <ide> * <ide> * When set, query execution will be bypassed. <ide> * <del> * @var \Cake\Datasource\ResultSetInterface|null <add> * @var iterable|null <ide> * @see \Cake\Datasource\QueryTrait::setResult() <ide> */ <ide> protected $_results; <ide> public function getRepository(): RepositoryInterface <ide> * <ide> * This method is most useful when combined with results stored in a persistent cache. <ide> * <del> * @param \Cake\Datasource\ResultSetInterface $results The results this query should return. <add> * @param iterable $results The results this query should return. <ide> * @return $this <ide> */ <del> public function setResult(ResultSetInterface $results) <add> public function setResult(iterable $results) <ide> { <ide> $this->_results = $results; <ide>
6
Javascript
Javascript
remove var in rntester
2648f47a4edd38433f48f56267f8ab0794404e67
<ide><path>RNTester/js/TextInputExample.android.js <ide> <ide> 'use strict'; <ide> <del>var React = require('react'); <del>var ReactNative = require('react-native'); <del>var {Text, TextInput, View, StyleSheet, Slider, Switch} = ReactNative; <add>const React = require('react'); <add>const ReactNative = require('react-native'); <add>const {Text, TextInput, View, StyleSheet, Slider, Switch} = ReactNative; <ide> <ide> class TextEventsExample extends React.Component<{}, $FlowFixMeState> { <ide> state = { <ide> class RewriteExample extends React.Component<$FlowFixMeProps, $FlowFixMeState> { <ide> this.state = {text: ''}; <ide> } <ide> render() { <del> var limit = 20; <del> var remainder = limit - this.state.text.length; <del> var remainderColor = remainder > 5 ? 'blue' : 'red'; <add> const limit = 20; <add> const remainder = limit - this.state.text.length; <add> const remainderColor = remainder > 5 ? 'blue' : 'red'; <ide> return ( <ide> /* $FlowFixMe(>=0.78.0 site=react_native_android_fb) This issue was found <ide> * when making Flow check .android.js files. */ <ide> class SelectionExample extends React.Component< <ide> } <ide> <ide> getRandomPosition() { <del> var length = this.state.value.length; <add> const length = this.state.value.length; <ide> return Math.round(Math.random() * length); <ide> } <ide> <ide> class SelectionExample extends React.Component< <ide> } <ide> <ide> selectRandom() { <del> var positions = [this.getRandomPosition(), this.getRandomPosition()].sort(); <add> const positions = [ <add> this.getRandomPosition(), <add> this.getRandomPosition(), <add> ].sort(); <ide> this.select(...positions); <ide> } <ide> <ide> class SelectionExample extends React.Component< <ide> } <ide> <ide> render() { <del> var length = this.state.value.length; <add> const length = this.state.value.length; <ide> <ide> return ( <ide> <View> <ide> class AutogrowingTextInputExample extends React.Component<{}> { <ide> render() { <ide> /* $FlowFixMe(>=0.78.0 site=react_native_android_fb) This issue was found <ide> * when making Flow check .android.js files. */ <del> var {style, multiline, ...props} = this.props; <add> const {style, multiline, ...props} = this.props; <ide> return ( <ide> <View> <ide> <Text>Width:</Text> <ide> class AutogrowingTextInputExample extends React.Component<{}> { <ide> } <ide> } <ide> <del>var styles = StyleSheet.create({ <add>const styles = StyleSheet.create({ <ide> multiline: { <ide> height: 60, <ide> fontSize: 16, <ide> exports.examples = [ <ide> { <ide> title: 'Auto-capitalize', <ide> render: function() { <del> var autoCapitalizeTypes = ['none', 'sentences', 'words', 'characters']; <del> var examples = autoCapitalizeTypes.map(type => { <add> const autoCapitalizeTypes = ['none', 'sentences', 'words', 'characters']; <add> const examples = autoCapitalizeTypes.map(type => { <ide> return ( <ide> <TextInput <ide> key={type} <ide> exports.examples = [ <ide> { <ide> title: 'Keyboard types', <ide> render: function() { <del> var keyboardTypes = ['default', 'email-address', 'numeric', 'phone-pad']; <del> var examples = keyboardTypes.map(type => { <add> const keyboardTypes = [ <add> 'default', <add> 'email-address', <add> 'numeric', <add> 'phone-pad', <add> ]; <add> const examples = keyboardTypes.map(type => { <ide> return ( <ide> <TextInput <ide> key={type} <ide> exports.examples = [ <ide> { <ide> title: 'Return key', <ide> render: function() { <del> var returnKeyTypes = [ <add> const returnKeyTypes = [ <ide> 'none', <ide> 'go', <ide> 'search', <ide> exports.examples = [ <ide> 'previous', <ide> 'next', <ide> ]; <del> var returnKeyLabels = ['Compile', 'React Native']; <del> var examples = returnKeyTypes.map(type => { <add> const returnKeyLabels = ['Compile', 'React Native']; <add> const examples = returnKeyTypes.map(type => { <ide> return ( <ide> <TextInput <ide> key={type} <ide> exports.examples = [ <ide> /> <ide> ); <ide> }); <del> var types = returnKeyLabels.map(type => { <add> const types = returnKeyLabels.map(type => { <ide> return ( <ide> <TextInput <ide> key={type} <ide><path>RNTester/js/TextInputExample.ios.js <ide> <ide> const Button = require('Button'); <ide> const InputAccessoryView = require('InputAccessoryView'); <del>var React = require('react'); <del>var ReactNative = require('react-native'); <del>var {Text, TextInput, View, StyleSheet, Slider, Switch} = ReactNative; <add>const React = require('react'); <add>const ReactNative = require('react-native'); <add>const {Text, TextInput, View, StyleSheet, Slider, Switch} = ReactNative; <ide> <ide> class WithLabel extends React.Component<$FlowFixMeProps> { <ide> render() { <ide> class RewriteExample extends React.Component<$FlowFixMeProps, any> { <ide> this.state = {text: ''}; <ide> } <ide> render() { <del> var limit = 20; <del> var remainder = limit - this.state.text.length; <del> var remainderColor = remainder > 5 ? 'blue' : 'red'; <add> const limit = 20; <add> const remainder = limit - this.state.text.length; <add> const remainderColor = remainder > 5 ? 'blue' : 'red'; <ide> return ( <ide> <View style={styles.rewriteContainer}> <ide> <TextInput <ide> class SelectionExample extends React.Component< <ide> } <ide> <ide> getRandomPosition() { <del> var length = this.state.value.length; <add> const length = this.state.value.length; <ide> return Math.round(Math.random() * length); <ide> } <ide> <ide> class SelectionExample extends React.Component< <ide> } <ide> <ide> selectRandom() { <del> var positions = [this.getRandomPosition(), this.getRandomPosition()].sort( <add> const positions = [this.getRandomPosition(), this.getRandomPosition()].sort( <ide> (a, b) => a - b, <ide> ); <ide> this.select(...positions); <ide> class SelectionExample extends React.Component< <ide> } <ide> <ide> render() { <del> var length = this.state.value.length; <add> const length = this.state.value.length; <ide> <ide> return ( <ide> <View> <ide> class AutogrowingTextInputExample extends React.Component< <ide> } <ide> <ide> render() { <del> var {style, multiline, ...props} = this.props; <add> const {style, multiline, ...props} = this.props; <ide> return ( <ide> <View> <ide> <Text>Width:</Text> <ide> class AutogrowingTextInputExample extends React.Component< <ide> } <ide> } <ide> <del>var styles = StyleSheet.create({ <add>const styles = StyleSheet.create({ <ide> page: { <ide> paddingBottom: 300, <ide> }, <ide> exports.examples = [ <ide> { <ide> title: 'Keyboard types', <ide> render: function() { <del> var keyboardTypes = [ <add> const keyboardTypes = [ <ide> 'default', <ide> 'ascii-capable', <ide> 'numbers-and-punctuation', <ide> exports.examples = [ <ide> 'web-search', <ide> 'numeric', <ide> ]; <del> var examples = keyboardTypes.map(type => { <add> const examples = keyboardTypes.map(type => { <ide> return ( <ide> <WithLabel key={type} label={type}> <ide> <TextInput keyboardType={type} style={styles.default} /> <ide> exports.examples = [ <ide> { <ide> title: 'Keyboard appearance', <ide> render: function() { <del> var keyboardAppearance = ['default', 'light', 'dark']; <del> var examples = keyboardAppearance.map(type => { <add> const keyboardAppearance = ['default', 'light', 'dark']; <add> const examples = keyboardAppearance.map(type => { <ide> return ( <ide> <WithLabel key={type} label={type}> <ide> <TextInput keyboardAppearance={type} style={styles.default} /> <ide> exports.examples = [ <ide> { <ide> title: 'Return key types', <ide> render: function() { <del> var returnKeyTypes = [ <add> const returnKeyTypes = [ <ide> 'default', <ide> 'go', <ide> 'google', <ide> exports.examples = [ <ide> 'done', <ide> 'emergency-call', <ide> ]; <del> var examples = returnKeyTypes.map(type => { <add> const examples = returnKeyTypes.map(type => { <ide> return ( <ide> <WithLabel key={type} label={type}> <ide> <TextInput returnKeyType={type} style={styles.default} /> <ide><path>RNTester/js/TimePickerAndroidExample.js <ide> <ide> 'use strict'; <ide> <del>var React = require('react'); <del>var ReactNative = require('react-native'); <del>var { <add>const React = require('react'); <add>const ReactNative = require('react-native'); <add>const { <ide> TimePickerAndroid, <ide> StyleSheet, <ide> Text, <ide> TouchableWithoutFeedback, <ide> } = ReactNative; <ide> <del>var RNTesterBlock = require('./RNTesterBlock'); <del>var RNTesterPage = require('./RNTesterPage'); <add>const RNTesterBlock = require('./RNTesterBlock'); <add>const RNTesterPage = require('./RNTesterPage'); <ide> <ide> class TimePickerAndroidExample extends React.Component { <ide> static title = 'TimePickerAndroid'; <ide> class TimePickerAndroidExample extends React.Component { <ide> showPicker = async (stateKey, options) => { <ide> try { <ide> const {action, minute, hour} = await TimePickerAndroid.open(options); <del> var newState = {}; <add> const newState = {}; <ide> if (action === TimePickerAndroid.timeSetAction) { <ide> newState[stateKey + 'Text'] = _formatTime(hour, minute); <ide> newState[stateKey + 'Hour'] = hour; <ide> function _formatTime(hour, minute) { <ide> return hour + ':' + (minute < 10 ? '0' + minute : minute); <ide> } <ide> <del>var styles = StyleSheet.create({ <add>const styles = StyleSheet.create({ <ide> text: { <ide> color: 'black', <ide> }, <ide><path>RNTester/js/TimerExample.js <ide> <ide> 'use strict'; <ide> <del>var React = require('react'); <del>var ReactNative = require('react-native'); <del>var {AlertIOS, Platform, ToastAndroid, Text, View} = ReactNative; <del>var RNTesterButton = require('./RNTesterButton'); <del>var performanceNow = require('fbjs/lib/performanceNow'); <add>const React = require('react'); <add>const ReactNative = require('react-native'); <add>const {AlertIOS, Platform, ToastAndroid, Text, View} = ReactNative; <add>const RNTesterButton = require('./RNTesterButton'); <add>const performanceNow = require('fbjs/lib/performanceNow'); <ide> <ide> function burnCPU(milliseconds) { <ide> const start = performanceNow(); <ide> class TimerTester extends React.Component<TimerTesterProps> { <ide> _timerFn: ?() => any = null; <ide> <ide> render() { <del> var args = 'fn' + (this.props.dt !== undefined ? ', ' + this.props.dt : ''); <add> const args = <add> 'fn' + (this.props.dt !== undefined ? ', ' + this.props.dt : ''); <ide> return ( <ide> <RNTesterButton onPress={this._run}> <ide> Measure: {this.props.type}({args}) - {this._ii || 0} <ide> class TimerTester extends React.Component<TimerTesterProps> { <ide> <ide> _run = () => { <ide> if (!this._start) { <del> var d = new Date(); <add> const d = new Date(); <ide> this._start = d.getTime(); <ide> this._iters = 100; <ide> this._ii = 0; <ide> class TimerTester extends React.Component<TimerTesterProps> { <ide> } <ide> } <ide> if (this._ii >= this._iters && this._intervalId == null) { <del> var d = new Date(); <del> var e = d.getTime() - this._start; <del> var msg = <add> const d = new Date(); <add> const e = d.getTime() - this._start; <add> const msg = <ide> 'Finished ' + <ide> this._ii + <ide> ' ' + <ide><path>RNTester/js/ToastAndroidExample.android.js <ide> <ide> 'use strict'; <ide> <del>var React = require('react'); <del>var ReactNative = require('react-native'); <del>var {StyleSheet, Text, ToastAndroid, TouchableWithoutFeedback} = ReactNative; <add>const React = require('react'); <add>const ReactNative = require('react-native'); <add>const {StyleSheet, Text, ToastAndroid, TouchableWithoutFeedback} = ReactNative; <ide> <del>var RNTesterBlock = require('RNTesterBlock'); <del>var RNTesterPage = require('RNTesterPage'); <add>const RNTesterBlock = require('RNTesterBlock'); <add>const RNTesterPage = require('RNTesterPage'); <ide> <ide> class ToastExample extends React.Component<{}, $FlowFixMeState> { <ide> static title = 'Toast Example'; <ide> class ToastExample extends React.Component<{}, $FlowFixMeState> { <ide> } <ide> } <ide> <del>var styles = StyleSheet.create({ <add>const styles = StyleSheet.create({ <ide> text: { <ide> color: 'black', <ide> }, <ide><path>RNTester/js/ToolbarAndroidExample.android.js <ide> <ide> 'use strict'; <ide> <del>var React = require('react'); <del>var ReactNative = require('react-native'); <add>const React = require('react'); <add>const ReactNative = require('react-native'); <ide> <del>var nativeImageSource = require('nativeImageSource'); <del>var {StyleSheet, Text, View} = ReactNative; <del>var RNTesterBlock = require('./RNTesterBlock'); <del>var RNTesterPage = require('./RNTesterPage'); <add>const nativeImageSource = require('nativeImageSource'); <add>const {StyleSheet, Text, View} = ReactNative; <add>const RNTesterBlock = require('./RNTesterBlock'); <add>const RNTesterPage = require('./RNTesterPage'); <ide> <del>var Switch = require('Switch'); <del>var ToolbarAndroid = require('ToolbarAndroid'); <add>const Switch = require('Switch'); <add>const ToolbarAndroid = require('ToolbarAndroid'); <ide> <ide> class ToolbarAndroidExample extends React.Component<{}, $FlowFixMeState> { <ide> static title = '<ToolbarAndroid>'; <ide> class ToolbarAndroidExample extends React.Component<{}, $FlowFixMeState> { <ide> }; <ide> } <ide> <del>var toolbarActions = [ <add>const toolbarActions = [ <ide> { <ide> title: 'Create', <ide> icon: nativeImageSource({ <ide> var toolbarActions = [ <ide> }, <ide> ]; <ide> <del>var styles = StyleSheet.create({ <add>const styles = StyleSheet.create({ <ide> toolbar: { <ide> backgroundColor: '#e9eaed', <ide> height: 56, <ide><path>RNTester/js/TouchableExample.js <ide> <ide> 'use strict'; <ide> <del>var React = require('react'); <del>var ReactNative = require('react-native'); <del>var { <add>const React = require('react'); <add>const ReactNative = require('react-native'); <add>const { <ide> Animated, <ide> Image, <ide> StyleSheet, <ide> class TouchableWithoutFeedbackBox extends React.Component<{}, $FlowFixMeState> { <ide> }; <ide> <ide> render() { <del> var textLog = ''; <add> let textLog = ''; <ide> if (this.state.timesPressed > 1) { <ide> textLog = this.state.timesPressed + 'x TouchableWithoutFeedback onPress'; <ide> } else if (this.state.timesPressed > 0) { <ide> class TextOnPressBox extends React.Component<{}, $FlowFixMeState> { <ide> }; <ide> <ide> render() { <del> var textLog = ''; <add> let textLog = ''; <ide> if (this.state.timesPressed > 1) { <ide> textLog = this.state.timesPressed + 'x text onPress'; <ide> } else if (this.state.timesPressed > 0) { <ide> class TouchableFeedbackEvents extends React.Component<{}, $FlowFixMeState> { <ide> } <ide> <ide> _appendEvent = eventName => { <del> var limit = 6; <del> var eventLog = this.state.eventLog.slice(0, limit - 1); <add> const limit = 6; <add> const eventLog = this.state.eventLog.slice(0, limit - 1); <ide> eventLog.unshift(eventName); <ide> this.setState({eventLog}); <ide> }; <ide> class TouchableDelayEvents extends React.Component<{}, $FlowFixMeState> { <ide> } <ide> <ide> _appendEvent = eventName => { <del> var limit = 6; <del> var eventLog = this.state.eventLog.slice(0, limit - 1); <add> const limit = 6; <add> const eventLog = this.state.eventLog.slice(0, limit - 1); <ide> eventLog.unshift(eventName); <ide> this.setState({eventLog}); <ide> }; <ide> class TouchableHitSlop extends React.Component<{}, $FlowFixMeState> { <ide> }; <ide> <ide> render() { <del> var log = ''; <add> let log = ''; <ide> if (this.state.timesPressed > 1) { <ide> log = this.state.timesPressed + 'x onPress'; <ide> } else if (this.state.timesPressed > 0) { <ide> class TouchableDisabled extends React.Component<{}> { <ide> } <ide> } <ide> <del>var heartImage = {uri: 'https://pbs.twimg.com/media/BlXBfT3CQAA6cVZ.png:small'}; <add>const heartImage = { <add> uri: 'https://pbs.twimg.com/media/BlXBfT3CQAA6cVZ.png:small', <add>}; <ide> <del>var styles = StyleSheet.create({ <add>const styles = StyleSheet.create({ <ide> row: { <ide> justifyContent: 'center', <ide> flexDirection: 'row', <ide><path>RNTester/js/TransformExample.js <ide> <ide> 'use strict'; <ide> <del>var React = require('react'); <del>var ReactNative = require('react-native'); <del>var {Animated, StyleSheet, Text, View} = ReactNative; <add>const React = require('react'); <add>const ReactNative = require('react-native'); <add>const {Animated, StyleSheet, Text, View} = ReactNative; <ide> <ide> class Flip extends React.Component<{}, $FlowFixMeState> { <ide> state = { <ide> class Flip extends React.Component<{}, $FlowFixMeState> { <ide> } <ide> } <ide> <del>var styles = StyleSheet.create({ <add>const styles = StyleSheet.create({ <ide> container: { <ide> height: 500, <ide> }, <ide><path>RNTester/js/TransparentHitTestExample.js <ide> <ide> 'use strict'; <ide> <del>var React = require('react'); <del>var ReactNative = require('react-native'); <del>var {Text, View, TouchableOpacity} = ReactNative; <add>const React = require('react'); <add>const ReactNative = require('react-native'); <add>const {Text, View, TouchableOpacity} = ReactNative; <ide> <ide> class TransparentHitTestExample extends React.Component<{}> { <ide> render() {
9
Ruby
Ruby
allow multiple unsatisfied fatal requirements
8c8701f26893f0b0cf9d54c4a6e56657af2d25e8
<ide><path>Library/Homebrew/build.rb <ide> end <ide> <ide> def install f <del> f.external_deps.each { |dep| dep.modify_build_environment } <add> f.requirements.each { |dep| dep.modify_build_environment } <ide> <ide> f.recursive_deps.uniq.each do |dep| <ide> dep = Formula.factory dep <ide><path>Library/Homebrew/dependencies.rb <ide> class DependencyCollector <ide> :chicken, :jruby, :lua, :node, :perl, :python, :rbx, :ruby <ide> ].freeze <ide> <del> attr_reader :deps, :external_deps <add> attr_reader :deps, :requirements <ide> <ide> def initialize <ide> @deps = Dependencies.new <del> @external_deps = Set.new <add> @requirements = Set.new <ide> end <ide> <ide> def add spec <ide> def add spec <ide> # dependency needed for the current platform. <ide> return if dep.nil? <ide> # Add dep to the correct bucket <del> (dep.is_a?(Requirement) ? @external_deps : @deps) << dep <add> (dep.is_a?(Requirement) ? @requirements : @deps) << dep <ide> end <ide> <ide> private <ide><path>Library/Homebrew/exceptions.rb <ide> def message <ide> end <ide> end <ide> <del>class UnsatisfiedRequirement < Homebrew::InstallationError <del> attr :dep <del> <del> def initialize formula, dep <del> @dep = dep <del> super formula, "An unsatisfied requirement failed this build." <add>class UnsatisfiedRequirements < Homebrew::InstallationError <add> attr :reqs <add> <add> def initialize formula, reqs <add> @reqs = reqs <add> message = (reqs.length == 1) \ <add> ? "An unsatisfied requirement failed this build." \ <add> : "Unsatisifed requirements failed this build." <add> super formula, message <ide> end <ide> end <ide> <ide><path>Library/Homebrew/formula.rb <ide> def self.path name <ide> HOMEBREW_REPOSITORY+"Library/Formula/#{name.downcase}.rb" <ide> end <ide> <del> def deps; self.class.dependencies.deps; end <del> def external_deps; self.class.dependencies.external_deps; end <add> def deps; self.class.dependencies.deps; end <add> def requirements; self.class.dependencies.requirements; end <ide> <ide> # deps are in an installable order <ide> # which means if a depends on b then b will be ordered before a in this list <ide><path>Library/Homebrew/formula_installer.rb <ide> def check_install_sanity <ide> <ide> f.recursive_deps.each do |dep| <ide> if dep.installed? and not dep.keg_only? and not dep.linked_keg.directory? <del> raise CannotInstallFormulaError, "You must `brew link #{dep}' before #{f} can be installed" <add> raise CannotInstallFormulaError, <add> "You must `brew link #{dep}' before #{f} can be installed" <ide> end <ide> end unless ignore_deps <ide> <ide> def install <ide> EOS <ide> end <ide> <del> f.external_deps.each do |dep| <del> unless dep.satisfied? <del> puts dep.message <del> if dep.fatal? and not ignore_deps <del> raise UnsatisfiedRequirement.new(f, dep) <add> # Build up a list of unsatisifed fatal requirements <add> first_message = true <add> unsatisfied_fatals = [] <add> f.requirements.each do |req| <add> unless req.satisfied? <add> # Newline between multiple messages <add> puts unless first_message <add> puts req.message <add> first_message = false <add> if req.fatal? and not ignore_deps <add> unsatisfied_fatals << req <ide> end <ide> end <ide> end <ide> <add> unless unsatisfied_fatals.empty? <add> raise UnsatisfiedRequirements.new(f, unsatisfied_fatals) <add> end <add> <ide> unless ignore_deps <ide> needed_deps = f.recursive_deps.reject{ |d| d.installed? } <ide> unless needed_deps.empty? <ide><path>Library/Homebrew/test/test_external_deps.rb <ide> def check_deps_fail specs <ide> end <ide> <ide> # Should have found a dep <del> assert d.external_deps.size == 1 <add> assert d.requirements.size == 1 <ide> <del> d.external_deps do |dep| <add> d.requirements do |req| <ide> assert !d.satisfied? <ide> end <ide> end <ide> def check_deps_pass specs <ide> end <ide> <ide> # Should have found a dep <del> assert d.external_deps.size == 1 <add> assert d.requirements.size == 1 <ide> <del> d.external_deps do |dep| <add> d.requirements do |req| <ide> assert d.satisfied? <ide> end <ide> end
6
Javascript
Javascript
fix the font inspector
45e3db77f235bbae038ebb8f19738cc394b4d28d
<ide><path>src/debugger.js <ide> var FontInspector = (function FontInspectorClosure() { <ide> var fonts; <ide> var panelWidth = 300; <ide> var active = false; <add> var fontAttribute = 'data-font-name'; <ide> function removeSelection() { <del> var divs = document.getElementsByTagName('div'); <add> var divs = document.querySelectorAll('div[' + fontAttribute + ']'); <ide> for (var i = 0; i < divs.length; ++i) { <del> var div = divs[i], style = div.getAttribute('style'); <del> if (!style || style.indexOf('pdfFont') < 0) continue; <del> var m = /(pdfFont\d+)/.exec(style); <del> div.dataset.fontName = ''; <add> var div = divs[i]; <ide> div.className = ''; <ide> } <ide> } <ide> function resetSelection() { <del> var divs = document.getElementsByTagName('div'); <add> var divs = document.querySelectorAll('div[' + fontAttribute + ']'); <ide> for (var i = 0; i < divs.length; ++i) { <del> var div = divs[i], style = div.getAttribute('style'); <del> if (!style || style.indexOf('pdfFont') < 0) continue; <del> var m = /(pdfFont\d+)/.exec(style); <del> div.dataset.fontName = m[1]; <add> var div = divs[i]; <ide> div.className = 'debuggerHideText'; <ide> } <ide> } <ide> function selectFont(fontName, show) { <del> var divs = document.getElementsByTagName('div'); <add> var divs = document.querySelectorAll('div[' + fontAttribute + '=' + <add> fontName + ']'); <ide> for (var i = 0; i < divs.length; ++i) { <del> var div = divs[i], style = div.getAttribute('style'); <del> if (div.dataset.fontName != fontName) continue; <add> var div = divs[i]; <ide> div.className = show ? 'debuggerShowText' : 'debuggerHideText'; <ide> } <ide> } <ide> var FontInspector = (function FontInspectorClosure() { <ide> document.body.addEventListener('click', textLayerClick, true); <ide> resetSelection(); <ide> } else { <del> document.body.removeEventListener('click', textLayerClick); <add> document.body.removeEventListener('click', textLayerClick, true); <ide> removeSelection(); <ide> } <ide> }, <ide><path>web/viewer.js <ide> var TextLayerBuilder = function textLayerBuilder(textLayerDiv) { <ide> // vScale and hScale already contain the scaling to pixel units <ide> var fontHeight = fontSize * text.geom.vScale; <ide> textDiv.dataset.canvasWidth = text.canvasWidth * text.geom.hScale; <add> textDiv.dataset.fontName = fontName; <ide> <ide> textDiv.style.fontSize = fontHeight + 'px'; <ide> textDiv.style.left = text.geom.x + 'px';
2
Python
Python
add more info on dry-run cli option
4de5089fd2edfe6fe6fc6a96df8de504d673b60a
<ide><path>airflow/cli/cli_parser.py <ide> def positive_int(value): <ide> type=parsedate) <ide> ARG_DRY_RUN = Arg( <ide> ("-n", "--dry-run"), <del> help="Perform a dry run", <add> help="Perform a dry run for each task. Only renders Template Fields for each task, nothing else", <ide> action="store_true") <ide> ARG_PID = Arg( <ide> ("--pid",),
1
Text
Text
fix locale title
3c0cf31b4cf14ac2a751acbaa794d1c39534b689
<ide><path>guide/portuguese/react/what-are-react-props/index.md <del>--- <del>title: React TypeChecking with PropTypes <del>localeTitle: Validação de Tipo em React com PropTypes <del>--- <del>## React PropTypes <del> <del>Estes servem como um método de validação de tipo (type checking) à medida que um aplicativo tende a crescer, com isso uma base muito grande de bugs tende a ser corrigida com o uso desse recurso. <del> <del>## Como obter PropTypes <del> <del>Começando com o React versão 15.5, esse recurso foi movido para um pacote separado chamado prop-types. <del> <del>Para usá-lo, é necessário que ele seja adicionado ao projeto como uma dependência, emitindo o seguinte comando em um terminal: <del> <del>```sh <del>npm install --save prop-types <del>``` <del> <del>Depois disso, toda uma gama de validadores de tipo podem ser usados para garantir que os dados que o desenvolvedor receberá realmente sejam válidos. Quando um valor inválido é fornecido, haverá um aviso aparecendo no console do JavaScript. <del> <del>Observe que, por motivos de desempenho, os propTypes definidos são verificados apenas no modo de desenvolvimento. <del> <del>Também, ao contrário do estado do componente, que pode ser manipulado conforme necessário, essas propriedades (props) são somente leitura. <del> <del>Seu valor não pode ser alterado pelo componente. <del> <del>## Proptypes disponíveis <del> <del>Abaixo está um exemplo de código com os diferentes validadores fornecidos pelo pacote e como injetá-los no componente. <del> <del>```javascript <del>import PropTypes from 'prop-types'; <del> class MyComponent extends Component{ <del> constructor(props){ <del> super(props); <del> } <del> render(){ <del> return ( <del> ... <del> ); <del> } <del> } <del> <del> MyComponent.propTypes = { <del> // A prop that is a specific JS primitive. By default, these <del> // are all optional. <del> optionalArray: PropTypes.array, <del> optionalBool: PropTypes.bool, <del> optionalFunc: PropTypes.func, <del> optionalNumber: PropTypes.number, <del> optionalObject: PropTypes.object, <del> optionalString: PropTypes.string, <del> optionalSymbol: PropTypes.symbol, <del> <del> // Anything that can be rendered: numbers, strings, elements or an array <del> // (or fragment) containing these types. <del> optionalNode: PropTypes.node, <del> <del> // A React element as a PropType <del> optionalElement: PropTypes.element, <del> <del> // Declaring that a prop is an instance of a class. This uses <del> // JS's instanceof operator. <del> optionalMessage: PropTypes.instanceOf(AnotherComponent), <del> <del> // You can ensure that your prop is limited to specific values by treating <del> // it as an enum. <del> optionalEnum: PropTypes.oneOf(['News', 'Photos']), <del> <del> // An object that could be one of many types <del> optionalUnion: PropTypes.oneOfType([ <del> PropTypes.string, <del> PropTypes.number, <del> PropTypes.instanceOf(AnotherComponent) <del> ]), <del> <del> // An array of a certain type <del> optionalArrayOf: PropTypes.arrayOf(PropTypes.number), <del> <del> // An object with property values of a certain type <del> optionalObjectOf: PropTypes.objectOf(PropTypes.number), <del> <del> // An object taking on a particular shape <del> optionalObjectWithShape: PropTypes.shape({ <del> color: PropTypes.string, <del> fontSize: PropTypes.number <del> }), <del> <del> // You can chain any of the above with `isRequired` to make sure a warning <del> // is shown if the prop isn't provided. <del> requiredFunc: PropTypes.func.isRequired, <del> <del> // A value of any data type <del> requiredAny: PropTypes.any.isRequired, <del> }; <del>``` <del> <del>## Configurando Valores Padrão <del> <del>Como parte deste recurso, também é possível definir valores padrão para qualquer componente definido durante o desenvolvimento. <del> <del>Eles garantem que o propore tenha um valor, mesmo que não especificado pelo componente pai. <del> <del>O código abaixo ilustra como usar essa funcionalidade. <del> <del>```javascript <del>import React,{Component} from 'react'; <del> import PropTypes from 'prop-types'; <del> class MyComponent extends Component{ <del> constructor(props){ <del> super(props); <del> } <del> render(){ <del> return ( <del> <h3>Hello, {this.props.name}</h3> <del> ); <del> } <del> } <del> MyComponent.defaultProps = { <del> name: 'Stranger' <del> }; <del>``` <del> <del>Para obter mais informações sobre PropTypes e outros documentos no React. <del> <del>Vá para o [site oficial](https://reactjs.org/) e leia os documentos ou o [Github Repo](https://github.com/facebook/react/) <add>--- <add>title: React TypeChecking with PropTypes <add>localeTitle: Verificação de Tipo em React com PropTypes <add>--- <add>## React PropTypes <add> <add>Estes servem como um método de typechecking (verificação de tipo) à medida que um aplicativo tende a crescer, com isso uma base muito grande de bugs tende a ser corrigida com o uso desse recurso. <add> <add>## Como obter PropTypes <add> <add>Começando com o React versão 15.5, esse recurso foi movido para um pacote separado chamado prop-types. <add> <add>Para usá-lo, é necessário que ele seja adicionado ao projeto como uma dependência, emitindo o seguinte comando em um console. <add> <add>```sh <add>npm install --save prop-types <add>``` <add> <add>Depois disso, toda uma gama de validadores que podem ser usados ​​para garantir que os dados que o desenvolvedor receberá realmente sejam válidos. Quando um valor inválido é fornecido, haverá um aviso aparecendo no console do JavaScript. <add> <add>Observe que, por motivos de desempenho, os propTypes definidos são verificados apenas no modo de desenvolvimento. <add> <add>Também, ao contrário do estado do componente, que pode ser manipulado conforme necessário, esses suportes são somente leitura. <add> <add>Seu valor não pode ser alterado pelo componente. <add> <add>## Proptypes disponíveis <add> <add>Abaixo está um exemplo de código com os diferentes validadores fornecidos pelo pacote e como injetá-los no componente. <add> <add>```javascript <add>import PropTypes from 'prop-types'; <add> class MyComponent extends Component{ <add> constructor(props){ <add> super(props); <add> } <add> render(){ <add> return ( <add> ... <add> ); <add> } <add> } <add> <add> MyComponent.propTypes = { <add> // A prop that is a specific JS primitive. By default, these <add> // are all optional. <add> optionalArray: PropTypes.array, <add> optionalBool: PropTypes.bool, <add> optionalFunc: PropTypes.func, <add> optionalNumber: PropTypes.number, <add> optionalObject: PropTypes.object, <add> optionalString: PropTypes.string, <add> optionalSymbol: PropTypes.symbol, <add> <add> // Anything that can be rendered: numbers, strings, elements or an array <add> // (or fragment) containing these types. <add> optionalNode: PropTypes.node, <add> <add> // A React element as a PropType <add> optionalElement: PropTypes.element, <add> <add> // Declaring that a prop is an instance of a class. This uses <add> // JS's instanceof operator. <add> optionalMessage: PropTypes.instanceOf(AnotherComponent), <add> <add> // You can ensure that your prop is limited to specific values by treating <add> // it as an enum. <add> optionalEnum: PropTypes.oneOf(['News', 'Photos']), <add> <add> // An object that could be one of many types <add> optionalUnion: PropTypes.oneOfType([ <add> PropTypes.string, <add> PropTypes.number, <add> PropTypes.instanceOf(AnotherComponent) <add> ]), <add> <add> // An array of a certain type <add> optionalArrayOf: PropTypes.arrayOf(PropTypes.number), <add> <add> // An object with property values of a certain type <add> optionalObjectOf: PropTypes.objectOf(PropTypes.number), <add> <add> // An object taking on a particular shape <add> optionalObjectWithShape: PropTypes.shape({ <add> color: PropTypes.string, <add> fontSize: PropTypes.number <add> }), <add> <add> // You can chain any of the above with `isRequired` to make sure a warning <add> // is shown if the prop isn't provided. <add> requiredFunc: PropTypes.func.isRequired, <add> <add> // A value of any data type <add> requiredAny: PropTypes.any.isRequired, <add> }; <add>``` <add> <add>## Configurando Valores Padrão <add> <add>Como parte deste recurso, também é possível definir valores padrão para qualquer componente definido durante o desenvolvimento. <add> <add>Eles garantem que o propore tenha um valor, mesmo que não especificado pelo componente pai. <add> <add>O código abaixo ilustra como usar essa funcionalidade. <add> <add>```javascript <add>import React,{Component} from 'react'; <add> import PropTypes from 'prop-types'; <add> class MyComponent extends Component{ <add> constructor(props){ <add> super(props); <add> } <add> render(){ <add> return ( <add> <h3>Hello, {this.props.name}</h3> <add> ); <add> } <add> } <add> MyComponent.defaultProps = { <add> name: 'Stranger' <add> }; <add>``` <add> <add>Para obter mais informações sobre PropTypes e outros documentos no React. <add> <add>Vá para o [site oficial](https://reactjs.org/) e leia os documentos ou o [Github Repo](https://github.com/facebook/react/)
1
Javascript
Javascript
fix crash when exporting type of existing variable
b9a03ce197865ec333c3dccfc7a4dcf1206b9064
<ide><path>packages/react-native-codegen/src/parsers/flow/utils.js <ide> function getTypes(ast: $FlowFixMe): TypeDeclarationMap { <ide> return ast.body.reduce((types, node) => { <ide> if (node.type === 'ExportNamedDeclaration' && node.exportKind === 'type') { <ide> if ( <del> node.declaration.type === 'TypeAlias' || <del> node.declaration.type === 'InterfaceDeclaration' <add> node.declaration != null && <add> (node.declaration.type === 'TypeAlias' || <add> node.declaration.type === 'InterfaceDeclaration') <ide> ) { <ide> types[node.declaration.id.name] = node.declaration; <ide> }
1
Go
Go
suggest login on pull denial
8d9f51ea55c8c9373d20bcc7561ca34c59aaf8c2
<ide><path>api/server/httputils/errors.go <ide> func GetHTTPErrorStatusCode(err error) int { <ide> {"this node", http.StatusServiceUnavailable}, <ide> {"needs to be unlocked", http.StatusServiceUnavailable}, <ide> {"certificates have expired", http.StatusServiceUnavailable}, <add> {"repository does not exist", http.StatusNotFound}, <ide> } { <ide> if strings.Contains(errStr, status.keyword) { <ide> statusCode = status.code <ide><path>distribution/errors.go <ide> func TranslatePullError(err error, ref reference.Named) error { <ide> switch v.Code { <ide> case errcode.ErrorCodeDenied: <ide> // ErrorCodeDenied is used when access to the repository was denied <del> newErr = errors.Errorf("repository %s not found: does not exist or no pull access", reference.FamiliarName(ref)) <add> newErr = errors.Errorf("pull access denied for %s, repository does not exist or may require 'docker login'", reference.FamiliarName(ref)) <ide> case v2.ErrorCodeManifestUnknown: <ide> newErr = errors.Errorf("manifest for %s not found", reference.FamiliarString(ref)) <ide> case v2.ErrorCodeNameUnknown: <ide><path>integration-cli/docker_cli_pull_test.go <ide> func (s *DockerHubPullSuite) TestPullNonExistingImage(c *check.C) { <ide> for record := range recordChan { <ide> if len(record.option) == 0 { <ide> c.Assert(record.err, checker.NotNil, check.Commentf("expected non-zero exit status when pulling non-existing image: %s", record.out)) <del> c.Assert(record.out, checker.Contains, fmt.Sprintf("repository %s not found: does not exist or no pull access", record.e.repo), check.Commentf("expected image not found error messages")) <add> c.Assert(record.out, checker.Contains, fmt.Sprintf("pull access denied for %s, repository does not exist or may require 'docker login'", record.e.repo), check.Commentf("expected image not found error messages")) <ide> } else { <ide> // pull -a on a nonexistent registry should fall back as well <ide> c.Assert(record.err, checker.NotNil, check.Commentf("expected non-zero exit status when pulling non-existing image: %s", record.out)) <del> c.Assert(record.out, checker.Contains, fmt.Sprintf("repository %s not found", record.e.repo), check.Commentf("expected image not found error messages")) <add> c.Assert(record.out, checker.Contains, fmt.Sprintf("pull access denied for %s, repository does not exist or may require 'docker login'", record.e.repo), check.Commentf("expected image not found error messages")) <ide> c.Assert(record.out, checker.Not(checker.Contains), "unauthorized", check.Commentf(`message should not contain "unauthorized"`)) <ide> } <ide> }
3
Text
Text
update code examples for spanish translation
e24a2d9fdbf44bafbad4dddf569cb108a31517bc
<ide><path>curriculum/challenges/spanish/03-front-end-libraries/sass/nest-css-with-sass.spanish.md <ide> localeTitle: Nest CSS con Sass <ide> --- <ide> <ide> ## Description <del><section id="description"> Sass permite <code>nesting</code> reglas CSS, que es una forma útil de organizar una hoja de estilo. Normalmente, cada elemento está enfocado en una línea diferente para diseñarlo, así: <blockquote> nav { <br> color de fondo: rojo; <br> } <br><br> nav ul { <br> estilo de lista: ninguno; <br> } <br><br> nav ul li { <br> pantalla: bloque en línea; <br> } </blockquote> Para un proyecto grande, el archivo CSS tendrá muchas líneas y reglas. Aquí es donde el <code>nesting</code> puede ayudar a organizar su código al colocar reglas de estilo secundarias dentro de los elementos principales respectivos: <blockquote> nav { <br> color de fondo: rojo; <br><br> ul { <br> estilo de lista: ninguno; <br><br> li { <br> pantalla: bloque en línea; <br> } <br> } <br> } <br></blockquote></section> <add><section id="description"> <add>Sass permite anidamiento (<code>nesting</code>) de reglas CSS, que es una forma útil de organizar una hoja de estilo. Normalmente, cada elemento se escribe en una línea diferente para darle estilo así: <add> <add>```html <add>nav { <add> background-color: red; <add>} <add> <add>nav ul { <add> list-style: none; <add>} <add> <add>nav ul li { <add> display: inline-block; <add>} <add>``` <add> <add>Para un proyecto grande, el archivo CSS tendrá muchas líneas y reglas. Aquí es donde el <code>nesting</code> puede ayudar a organizar su código al colocar reglas de estilo secundarias dentro de los respectivos elementos principales: <add> <add>```html <add>nav { <add> background-color: red; <add> ul { <add> list-style: none; <add> li { <add> display: inline-block; <add> } <add> } <add>} <add>``` <add></section> <ide> <ide> ## Instructions <ide> <section id="instructions"> Use la técnica de <code>nesting</code> que se muestra arriba para reorganizar las reglas de CSS para ambos elementos del elemento <code>.blog-post</code> . Para propósitos de prueba, el <code>h1</code> debe venir antes del elemento <code>p</code> . </section>
1
PHP
PHP
fix time api docs
a7cb1bab8f4bd39558170fbcf3ab620afbc0e8f6
<ide><path>src/Utility/Time.php <ide> public function __toString() { <ide> * Get list of timezone identifiers <ide> * <ide> * @param int|string $filter A regex to filter identifer <del> * Or one of DateTimeZone class constants <add> * Or one of DateTimeZone class constants <ide> * @param string $country A two-letter ISO 3166-1 compatible country code. <del> * This option is only used when $filter is set to DateTimeZone::PER_COUNTRY <add> * This option is only used when $filter is set to DateTimeZone::PER_COUNTRY <ide> * @param bool $group If true (default value) groups the identifiers list by primary region <ide> * @return array List of timezone identifiers <ide> * @since 2.2
1
Text
Text
add v3.7.0-beta.2 to changelog
ac1df67a7100a1169ad5e0e6ad1ec23bb0d28017
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <add>### v3.7.0-beta.2 (December 17, 2018) <add> <add>- [#17328](https://github.com/emberjs/ember.js/pull/17328) [BUGFIX] Ensure that delayed transition retrys work <add>- [#17374](https://github.com/emberjs/ember.js/pull/17374) [BUGFIX] Fix cyclic references on Array.prototype <add> <ide> ### v3.7.0-beta.1 (December 6, 2018) <ide> <ide> - [#17254](https://github.com/emberjs/ember.js/pull/17254) [BREAKING] Explicitly drop support for Node 4
1
Ruby
Ruby
remove unused require
bb6d369f891963f8ed6ec3eeaaba3066c438aaee
<ide><path>railties/lib/rails/generators/named_base.rb <ide> # frozen_string_literal: true <ide> <del>require "active_support/core_ext/module/introspection" <ide> require "rails/generators/base" <ide> require "rails/generators/generated_attribute" <ide>
1
Ruby
Ruby
recognize os x 10.9 and xcode 5.0
15626b38cacd6151b9b215a421c433c9fcea8893
<ide><path>Library/Homebrew/macos.rb <ide> def prefer_64_bit? <ide> "4.6" => { :llvm_build => 2336, :clang => "4.2", :clang_build => 425 }, <ide> "4.6.1" => { :llvm_build => 2336, :clang => "4.2", :clang_build => 425 }, <ide> "4.6.2" => { :llvm_build => 2336, :clang => "4.2", :clang_build => 425 }, <add> "5.0" => { :clang => "5.0", :clang_build => 500 }, <ide> } <ide> <ide> def compilers_standard? <ide><path>Library/Homebrew/os/mac/xcode.rb <ide> def latest_version <ide> when 10.5 then "3.1.4" <ide> when 10.6 then "3.2.6" <ide> when 10.7, 10.8 then "4.6.2" <add> when 10.9 then "5.0" <ide> else <ide> # Default to newest known version of Xcode for unreleased OSX versions. <del> if MacOS.version > 10.8 <del> "4.6.2" <add> if MacOS.version > 10.9 <add> "5.0" <ide> else <ide> raise "Mac OS X '#{MacOS.version}' is invalid" <ide> end <ide> def uncached_version <ide> when 40 then "4.4" <ide> when 41 then "4.5" <ide> when 42 then "4.6" <add> when 50 then "5.0" <ide> else "4.6" <ide> end <ide> end
2
Ruby
Ruby
emit single pair of parens for union and union all
63dd8d8e12edb25d8d5bac324aacb1caf05bbe22
<ide><path>activerecord/lib/arel/visitors/mysql.rb <ide> module Arel # :nodoc: all <ide> module Visitors <ide> class MySQL < Arel::Visitors::ToSql <ide> private <del> def visit_Arel_Nodes_Union(o, collector, suppress_parens = false) <del> unless suppress_parens <del> collector << "( " <del> end <del> <del> case o.left <del> when Arel::Nodes::Union <del> visit_Arel_Nodes_Union o.left, collector, true <del> else <del> visit o.left, collector <del> end <del> <del> collector << " UNION " <del> <del> case o.right <del> when Arel::Nodes::Union <del> visit_Arel_Nodes_Union o.right, collector, true <del> else <del> visit o.right, collector <del> end <del> <del> if suppress_parens <del> collector <del> else <del> collector << " )" <del> end <del> end <del> <ide> def visit_Arel_Nodes_Bin(o, collector) <ide> collector << "BINARY " <ide> visit o.expr, collector <ide><path>activerecord/lib/arel/visitors/to_sql.rb <ide> def visit_Arel_Nodes_WithRecursive(o, collector) <ide> end <ide> <ide> def visit_Arel_Nodes_Union(o, collector) <del> collector << "( " <del> infix_value(o, collector, " UNION ") << " )" <add> infix_value_with_paren(o, collector, " UNION ") <ide> end <ide> <ide> def visit_Arel_Nodes_UnionAll(o, collector) <del> collector << "( " <del> infix_value(o, collector, " UNION ALL ") << " )" <add> infix_value_with_paren(o, collector, " UNION ALL ") <ide> end <ide> <ide> def visit_Arel_Nodes_Intersect(o, collector) <ide> def infix_value(o, collector, value) <ide> visit o.right, collector <ide> end <ide> <add> def infix_value_with_paren(o, collector, value, suppress_parens = false) <add> collector << '( ' unless suppress_parens <add> collector = if o.left.class == o.class <add> infix_value_with_paren(o.left, collector, value, true) <add> else <add> visit o.left, collector <add> end <add> collector << value <add> collector = if o.right.class == o.class <add> infix_value_with_paren(o.right, collector, value, true) <add> else <add> visit o.right, collector <add> end <add> collector << ' )' unless suppress_parens <add> collector <add> end <add> <ide> def aggregate(name, o, collector) <ide> collector << "#{name}(" <ide> if o.distinct <ide><path>activerecord/test/cases/arel/visitors/mysql_test.rb <ide> def compile(node) <ide> @visitor.accept(node, Collectors::SQLString.new).value <ide> end <ide> <del> it "squashes parenthesis on multiple unions" do <del> subnode = Nodes::Union.new Arel.sql("left"), Arel.sql("right") <del> node = Nodes::Union.new subnode, Arel.sql("topright") <del> assert_equal 1, compile(node).scan("(").length <del> <del> subnode = Nodes::Union.new Arel.sql("left"), Arel.sql("right") <del> node = Nodes::Union.new Arel.sql("topleft"), subnode <del> assert_equal 1, compile(node).scan("(").length <del> end <del> <ide> ### <ide> # :'( <ide> # http://dev.mysql.com/doc/refman/5.0/en/select.html#id3482214 <ide><path>activerecord/test/cases/arel/visitors/to_sql_test.rb <ide> def dispatch <ide> end <ide> end <ide> <add> describe "Nodes::Union" do <add> it "squashes parenthesis on multiple unions" do <add> subnode = Nodes::Union.new Arel.sql("left"), Arel.sql("right") <add> node = Nodes::Union.new subnode, Arel.sql("topright") <add> assert_equal("( left UNION right UNION topright )", compile(node)) <add> subnode = Nodes::Union.new Arel.sql("left"), Arel.sql("right") <add> node = Nodes::Union.new Arel.sql("topleft"), subnode <add> assert_equal("( topleft UNION left UNION right )", compile(node)) <add> end <add> end <add> <add> describe "Nodes::UnionAll" do <add> it "squashes parenthesis on multiple union alls" do <add> subnode = Nodes::UnionAll.new Arel.sql("left"), Arel.sql("right") <add> node = Nodes::UnionAll.new subnode, Arel.sql("topright") <add> assert_equal("( left UNION ALL right UNION ALL topright )", compile(node)) <add> subnode = Nodes::UnionAll.new Arel.sql("left"), Arel.sql("right") <add> node = Nodes::UnionAll.new Arel.sql("topleft"), subnode <add> assert_equal("( topleft UNION ALL left UNION ALL right )", compile(node)) <add> end <add> end <add> <ide> describe "Nodes::NotIn" do <ide> it "should know how to visit" do <ide> node = @attr.not_in [1, 2, 3]
4
PHP
PHP
simplify error message and test
94e52ff18238842633b05f63a4faa04b77809f45
<ide><path>src/ORM/Query.php <ide> public function autoFields($value = null) { <ide> } <ide> <ide> /** <del> * Get the first result from the executing query or raist an exception. <add> * Get the first result from the executing query or raise an exception. <ide> * <ide> * @throws \Cake\ORM\RecordNotFoundException When there is no first record. <ide> * @return mixed The first result from the ResultSet. <ide> public function firstOrFail() { <ide> if ($entity) { <ide> return $entity; <ide> } <del> $binder = new ValueBinder(); <del> $conditions = $this->clause('where'); <del> <ide> throw new RecordNotFoundException(sprintf( <del> 'Record not found in table "%s" for conditions "%s"', <del> $this->repository()->table(), <del> $conditions->sql($binder) <add> 'Record not found in table "%s"', <add> $this->repository()->table() <ide> )); <ide> } <ide> <ide><path>tests/TestCase/ORM/TableTest.php <ide> public function testGetWithCache($options, $cacheKey, $cacheConfig) { <ide> * Tests that get() will throw an exception if the record was not found <ide> * <ide> * @expectedException \Cake\ORM\Exception\RecordNotFoundException <del> * @expectedExceptionMessage Record not found in table "articles" for conditions "articles.id = :c0" <add> * @expectedExceptionMessage Record not found in table "articles" <ide> * @return void <ide> */ <ide> public function testGetNotFoundException() {
2
PHP
PHP
pass request into route closures
a045496684c92a46d46b9d8b8aed690346a5c336
<ide><path>application/routes.php <ide> | <ide> */ <ide> <del> 'GET /' => function() <add> 'GET /' => function($request) <ide> { <ide> return View::make('home.index'); <ide> }, <ide><path>laravel/routing/handler.php <ide> protected function find_route_closure(Route $route) <ide> */ <ide> protected function handle_closure(Route $route, Closure $closure) <ide> { <add> array_unshift($route->parameters, $this->request); <add> <ide> $response = call_user_func_array($closure, $route->parameters); <ide> <ide> if (is_array($response))
2
Text
Text
fix failing static check in master
4bacc1950faff7c915bbaeffec404113c5d589c4
<ide><path>INTHEWILD.md <ide> Currently, **officially** using Airflow: <ide> 1. [Akamas](https://akamas.io) [[@GiovanniPaoloGibilisco](https://github.com/GiovanniPaoloGibilisco), [@lucacavazzana](https://github.com/lucacavazzana)] <ide> 1. [Alan](https://alan.eu) [[@charles-go](https://github.com/charles-go)] <ide> 1. [AloPeyk](https://alopeyk.com) [[@blcksrx](https://github.com/blcksrx), [@AloPeyk](https://github.com/AloPeyk)] <del>1. [Altafino](https://altafino.com) [[@altafino](https://github.com/altafino)] <ide> 1. [AltX](https://www.getaltx.com/about) [[@pedromduarte](https://github.com/pedromduarte)] <add>1. [Altafino](https://altafino.com) [[@altafino](https://github.com/altafino)] <ide> 1. [American Family Insurance](https://www.amfam.com/about) [[@di1eep](https://github.com/di1eep)] <ide> 1. [Apigee](https://apigee.com) [[@btallman](https://github.com/btallman)] <ide> 1. [Arquivei](https://www.arquivei.com.br/) [[@arquivei](https://github.com/arquivei)]
1
Javascript
Javascript
fix lint errors for examples/shopping-cart/
348651b21fa7a0c32921ad5f1f13053b442db3ad
<ide><path>examples/shopping-cart/actions/index.js <del>import shop from '../api/shop'; <del>import * as types from '../constants/ActionTypes'; <add>import shop from '../api/shop' <add>import * as types from '../constants/ActionTypes' <ide> <ide> function receiveProducts(products) { <ide> return { <ide> type: types.RECEIVE_PRODUCTS, <ide> products: products <del> }; <add> } <ide> } <ide> <ide> export function getAllProducts() { <ide> return dispatch => { <ide> shop.getProducts(products => { <del> dispatch(receiveProducts(products)); <del> }); <del> }; <add> dispatch(receiveProducts(products)) <add> }) <add> } <ide> } <ide> <ide> function addToCartUnsafe(productId) { <ide> return { <ide> type: types.ADD_TO_CART, <ide> productId <del> }; <add> } <ide> } <ide> <ide> export function addToCart(productId) { <ide> return (dispatch, getState) => { <ide> if (getState().products.byId[productId].inventory > 0) { <del> dispatch(addToCartUnsafe(productId)); <add> dispatch(addToCartUnsafe(productId)) <ide> } <del> }; <add> } <ide> } <ide> <ide> export function checkout(products) { <ide> return (dispatch, getState) => { <del> const cart = getState().cart; <add> const cart = getState().cart <ide> <ide> dispatch({ <ide> type: types.CHECKOUT_REQUEST <del> }); <add> }) <ide> shop.buyProducts(products, () => { <ide> dispatch({ <ide> type: types.CHECKOUT_SUCCESS, <ide> cart <del> }); <add> }) <ide> // Replace the line above with line below to rollback on failure: <del> // dispatch({ type: types.CHECKOUT_FAILURE, cart }); <del> }); <del> }; <add> // dispatch({ type: types.CHECKOUT_FAILURE, cart }) <add> }) <add> } <ide> } <ide><path>examples/shopping-cart/api/shop.js <ide> /** <ide> * Mocking client-server processing <ide> */ <del>import _products from './products.json'; <add>import _products from './products.json' <ide> <del>const TIMEOUT = 100; <add>const TIMEOUT = 100 <ide> <ide> export default { <ide> getProducts(cb, timeout) { <del> setTimeout(() => cb(_products), timeout || TIMEOUT); <add> setTimeout(() => cb(_products), timeout || TIMEOUT) <ide> }, <ide> <ide> buyProducts(payload, cb, timeout) { <del> setTimeout(() => cb(), timeout || TIMEOUT); <add> setTimeout(() => cb(), timeout || TIMEOUT) <ide> } <del>}; <add>} <ide><path>examples/shopping-cart/components/Cart.js <del>import React, { Component, PropTypes } from 'react'; <del>import Product from './Product'; <add>import React, { Component, PropTypes } from 'react' <add>import Product from './Product' <ide> <ide> export default class Cart extends Component { <ide> render() { <del> const { products, total, onCheckoutClicked } = this.props; <add> const { products, total, onCheckoutClicked } = this.props <ide> <del> const hasProducts = products.length > 0; <add> const hasProducts = products.length > 0 <ide> const nodes = !hasProducts ? <ide> <div>Please add some products to cart.</div> : <ide> products.map(product => <ide> export default class Cart extends Component { <ide> price={product.price} <ide> quantity={product.quantity} <ide> key={product.id}/> <del> ); <add> ) <ide> <ide> return ( <ide> <div> <ide> <h3>Your Cart</h3> <ide> <div>{nodes}</div> <del> <p>Total: &euro;{total}</p> <add> <p>Total: &euro{total}</p> <ide> <button onClick={onCheckoutClicked} <ide> disabled={hasProducts ? '' : 'disabled'}> <ide> Checkout <ide> </button> <ide> </div> <del> ); <add> ) <ide> } <ide> } <ide> <ide> Cart.propTypes = { <ide> products: PropTypes.array, <ide> total: PropTypes.string, <ide> onCheckoutClicked: PropTypes.func <del>}; <add>} <ide><path>examples/shopping-cart/components/Product.js <del>import React, { Component, PropTypes } from 'react'; <add>import React, { Component, PropTypes } from 'react' <ide> <ide> export default class Product extends Component { <ide> render() { <del> const { price, quantity, title } = this.props; <del> return <div> {title} - &euro;{price} {quantity ? `x ${quantity}` : null} </div>; <add> const { price, quantity, title } = this.props <add> return <div> {title} - &euro{price} {quantity ? `x ${quantity}` : null} </div> <ide> } <ide> } <ide> <ide> Product.propTypes = { <ide> price: PropTypes.number, <ide> quantity: PropTypes.number, <ide> title: PropTypes.string <del>}; <add>} <ide><path>examples/shopping-cart/components/ProductItem.js <del>import React, { Component, PropTypes } from 'react'; <del>import Product from './Product'; <add>import React, { Component, PropTypes } from 'react' <add>import Product from './Product' <ide> <ide> export default class ProductItem extends Component { <ide> render() { <del> const { product } = this.props; <add> const { product } = this.props <ide> <ide> return ( <ide> <div> <ide> export default class ProductItem extends Component { <ide> {product.inventory > 0 ? 'Add to cart' : 'Sold Out'} <ide> </button> <ide> </div> <del> ); <add> ) <ide> } <ide> } <ide> <ide> ProductItem.propTypes = { <ide> inventory: PropTypes.number.isRequired <ide> }).isRequired, <ide> onAddToCartClicked: PropTypes.func.isRequired <del>}; <add>} <ide><path>examples/shopping-cart/components/ProductsList.js <del>import React, { Component, PropTypes } from 'react'; <add>import React, { Component, PropTypes } from 'react' <ide> <ide> export default class ProductsList extends Component { <ide> render() { <ide> export default class ProductsList extends Component { <ide> <h2>{this.props.title}</h2> <ide> <div>{this.props.children}</div> <ide> </div> <del> ); <add> ) <ide> } <ide> } <ide> <ide> ProductsList.propTypes = { <ide> children: PropTypes.node, <ide> title: PropTypes.string.isRequired <del>}; <add>} <ide><path>examples/shopping-cart/constants/ActionTypes.js <del>export const ADD_TO_CART = 'ADD_TO_CART'; <del>export const CHECKOUT_REQUEST = 'CHECKOUT_REQUEST'; <del>export const CHECKOUT_SUCCESS = 'CHECKOUT_SUCCESS'; <del>export const CHECKOUT_FAILURE = 'CHECKOUT_FAILURE'; <del>export const RECEIVE_PRODUCTS = 'RECEIVE_PRODUCTS'; <add>export const ADD_TO_CART = 'ADD_TO_CART' <add>export const CHECKOUT_REQUEST = 'CHECKOUT_REQUEST' <add>export const CHECKOUT_SUCCESS = 'CHECKOUT_SUCCESS' <add>export const CHECKOUT_FAILURE = 'CHECKOUT_FAILURE' <add>export const RECEIVE_PRODUCTS = 'RECEIVE_PRODUCTS' <ide><path>examples/shopping-cart/containers/App.js <del>import React, { Component } from 'react'; <del>import ProductsContainer from './ProductsContainer'; <del>import CartContainer from './CartContainer'; <add>import React, { Component } from 'react' <add>import ProductsContainer from './ProductsContainer' <add>import CartContainer from './CartContainer' <ide> <ide> export default class App extends Component { <ide> render() { <ide> export default class App extends Component { <ide> <hr/> <ide> <CartContainer /> <ide> </div> <del> ); <add> ) <ide> } <ide> } <ide><path>examples/shopping-cart/containers/CartContainer.js <del>import React, { Component, PropTypes } from 'react'; <del>import { connect } from 'react-redux'; <del>import { checkout } from '../actions'; <del>import { getTotal, getCartProducts } from '../reducers'; <del>import Cart from '../components/Cart'; <add>import React, { Component, PropTypes } from 'react' <add>import { connect } from 'react-redux' <add>import { checkout } from '../actions' <add>import { getTotal, getCartProducts } from '../reducers' <add>import Cart from '../components/Cart' <ide> <ide> class CartContainer extends Component { <ide> render() { <del> const { products, total } = this.props; <add> const { products, total } = this.props <ide> <ide> return ( <ide> <Cart <ide> products={products} <ide> total={total} <ide> onCheckoutClicked={() => this.props.checkout()} /> <del> ); <add> ) <ide> } <ide> } <ide> <ide> CartContainer.propTypes = { <ide> id: PropTypes.number.isRequired, <ide> title: PropTypes.string.isRequired, <ide> price: PropTypes.number.isRequired, <del> quantity: PropTypes.number.isRequired, <add> quantity: PropTypes.number.isRequired <ide> })).isRequired, <ide> total: PropTypes.string, <ide> checkout: PropTypes.func.isRequired <del>}; <add>} <ide> <ide> const mapStateToProps = (state) => { <ide> return { <ide> products: getCartProducts(state), <ide> total: getTotal(state) <del> }; <del>}; <add> } <add>} <ide> <ide> export default connect( <ide> mapStateToProps, <ide> { checkout } <del>)(CartContainer); <add>)(CartContainer) <ide><path>examples/shopping-cart/containers/ProductsContainer.js <del>import React, { Component, PropTypes } from 'react'; <del>import { connect } from 'react-redux'; <del>import { addToCart } from '../actions'; <del>import { getVisibleProducts } from '../reducers/products'; <del>import ProductItem from '../components/ProductItem'; <del>import ProductsList from '../components/ProductsList'; <add>import React, { Component, PropTypes } from 'react' <add>import { connect } from 'react-redux' <add>import { addToCart } from '../actions' <add>import { getVisibleProducts } from '../reducers/products' <add>import ProductItem from '../components/ProductItem' <add>import ProductsList from '../components/ProductsList' <ide> <ide> class ProductsContainer extends Component { <ide> render() { <del> const { products } = this.props; <add> const { products } = this.props <ide> return ( <ide> <ProductsList title="Flux Shop Demo (Redux)"> <ide> {products.map(product => <ide> class ProductsContainer extends Component { <ide> onAddToCartClicked={() => this.props.addToCart(product.id)} /> <ide> )} <ide> </ProductsList> <del> ); <add> ) <ide> } <ide> } <ide> <ide> ProductsContainer.propTypes = { <ide> id: PropTypes.number.isRequired, <ide> title: PropTypes.string.isRequired, <ide> price: PropTypes.number.isRequired, <del> inventory: PropTypes.number.isRequired, <add> inventory: PropTypes.number.isRequired <ide> })).isRequired, <ide> addToCart: PropTypes.func.isRequired <del>}; <add>} <ide> <ide> function mapStateToProps(state) { <ide> return { <ide> products: getVisibleProducts(state.products) <del> }; <add> } <ide> } <ide> <ide> export default connect( <ide> mapStateToProps, <ide> { addToCart } <del>)(ProductsContainer); <add>)(ProductsContainer) <ide><path>examples/shopping-cart/index.js <del>import React from 'react'; <del>import { createStore, applyMiddleware } from 'redux'; <del>import { Provider } from 'react-redux'; <del>import logger from 'redux-logger'; <del>import thunk from 'redux-thunk'; <del>import reducer from './reducers'; <del>import { getAllProducts } from './actions'; <del>import App from './containers/App'; <add>import React from 'react' <add>import { createStore, applyMiddleware } from 'redux' <add>import { Provider } from 'react-redux' <add>import logger from 'redux-logger' <add>import thunk from 'redux-thunk' <add>import reducer from './reducers' <add>import { getAllProducts } from './actions' <add>import App from './containers/App' <ide> <ide> const middleware = process.env.NODE_ENV === 'production' ? <del> [thunk] : <del> [thunk, logger()]; <add> [ thunk ] : <add> [ thunk, logger() ] <ide> <del>const createStoreWithMiddleware = applyMiddleware(...middleware)(createStore); <del>const store = createStoreWithMiddleware(reducer); <add>const createStoreWithMiddleware = applyMiddleware(...middleware)(createStore) <add>const store = createStoreWithMiddleware(reducer) <ide> <del>store.dispatch(getAllProducts()); <add>store.dispatch(getAllProducts()) <ide> <ide> React.render( <del> <Provider store={store}> <add> <Provider store={ store }> <ide> {() => <App />} <ide> </Provider>, <ide> document.getElementById('root') <del>); <add>) <ide><path>examples/shopping-cart/reducers/cart.js <ide> import { <ide> ADD_TO_CART, <ide> CHECKOUT_REQUEST, <ide> CHECKOUT_FAILURE <del>} from '../constants/ActionTypes'; <add>} from '../constants/ActionTypes' <ide> <ide> const initialState = { <ide> addedIds: [], <ide> quantityById: {} <del>}; <add>} <ide> <ide> function addedIds(state = initialState.addedIds, action) { <ide> switch (action.type) { <del> case ADD_TO_CART: <del> if (state.indexOf(action.productId) !== -1) { <del> return state; <del> } <del> return [...state, action.productId]; <del> default: <del> return state; <add> case ADD_TO_CART: <add> if (state.indexOf(action.productId) !== -1) { <add> return state <add> } <add> return [ ...state, action.productId ] <add> default: <add> return state <ide> } <ide> } <ide> <ide> function quantityById(state = initialState.quantityById, action) { <ide> switch (action.type) { <del> case ADD_TO_CART: <del> const { productId } = action; <del> return { <del> ...state, <del> [productId]: (state[productId] || 0) + 1 <del> }; <del> default: <del> return state; <add> case ADD_TO_CART: <add> const { productId } = action <add> return { <add> ...state, <add> [productId]: (state[productId] || 0) + 1 <add> } <add> default: <add> return state <ide> } <ide> } <ide> <ide> export default function cart(state = initialState, action) { <ide> switch (action.type) { <del> case CHECKOUT_REQUEST: <del> return initialState; <del> case CHECKOUT_FAILURE: <del> return action.cart; <del> default: <del> return { <del> addedIds: addedIds(state.addedIds, action), <del> quantityById: quantityById(state.quantityById, action) <del> }; <add> case CHECKOUT_REQUEST: <add> return initialState <add> case CHECKOUT_FAILURE: <add> return action.cart <add> default: <add> return { <add> addedIds: addedIds(state.addedIds, action), <add> quantityById: quantityById(state.quantityById, action) <add> } <ide> } <ide> } <ide> <ide> export function getQuantity(state, productId) { <del> return state.quantityById[productId] || 0; <add> return state.quantityById[productId] || 0 <ide> } <ide> <ide> export function getAddedIds(state) { <del> return state.addedIds; <add> return state.addedIds <ide> } <ide><path>examples/shopping-cart/reducers/index.js <del>import { combineReducers } from 'redux'; <del>import { default as cart, getQuantity, getAddedIds } from './cart'; <del>import { default as products, getProduct } from './products'; <add>import { combineReducers } from 'redux' <add>import { default as cart, getQuantity, getAddedIds } from './cart' <add>import { default as products, getProduct } from './products' <ide> <ide> export function getTotal(state) { <ide> return getAddedIds(state.cart).reduce((total, id) => <ide> total + getProduct(state.products, id).price * getQuantity(state.cart, id), <ide> 0 <del> ).toFixed(2); <add> ).toFixed(2) <ide> } <ide> <ide> export function getCartProducts(state) { <ide> return getAddedIds(state.cart).map(id => ({ <ide> ...getProduct(state.products, id), <ide> quantity: getQuantity(state.cart, id) <del> })); <add> })) <ide> } <ide> <ide> export default combineReducers({ <ide> cart, <ide> products <del>}); <add>}) <ide><path>examples/shopping-cart/reducers/products.js <del>import { combineReducers } from 'redux'; <del>import { RECEIVE_PRODUCTS, ADD_TO_CART } from '../constants/ActionTypes'; <add>import { combineReducers } from 'redux' <add>import { RECEIVE_PRODUCTS, ADD_TO_CART } from '../constants/ActionTypes' <ide> <ide> function products(state, action) { <ide> switch (action.type) { <del> case ADD_TO_CART: <del> return { <del> ...state, <del> inventory: state.inventory - 1 <del> }; <del> default: <del> return state; <add> case ADD_TO_CART: <add> return { <add> ...state, <add> inventory: state.inventory - 1 <add> } <add> default: <add> return state <ide> } <ide> } <ide> <ide> function byId(state = {}, action) { <ide> switch (action.type) { <del> case RECEIVE_PRODUCTS: <del> return { <del> ...state, <del> ...action.products.reduce((obj, product) => { <del> obj[product.id] = product; <del> return obj; <del> }, {}) <del> }; <del> default: <del> const { productId } = action; <del> if (productId) { <add> case RECEIVE_PRODUCTS: <ide> return { <ide> ...state, <del> [productId]: products(state[productId], action) <del> }; <del> } <del> return state; <add> ...action.products.reduce((obj, product) => { <add> obj[product.id] = product <add> return obj <add> }, {}) <add> } <add> default: <add> const { productId } = action <add> if (productId) { <add> return { <add> ...state, <add> [productId]: products(state[productId], action) <add> } <add> } <add> return state <ide> } <ide> } <ide> <ide> function visibleIds(state = [], action) { <ide> switch (action.type) { <del> case RECEIVE_PRODUCTS: <del> return action.products.map(product => product.id); <del> default: <del> return state; <add> case RECEIVE_PRODUCTS: <add> return action.products.map(product => product.id) <add> default: <add> return state <ide> } <ide> } <ide> <ide> export default combineReducers({ <ide> byId, <ide> visibleIds <del>}); <add>}) <ide> <ide> export function getProduct(state, id) { <del> return state.byId[id]; <add> return state.byId[id] <ide> } <ide> <ide> export function getVisibleProducts(state) { <del> return state.visibleIds.map(id => getProduct(state, id)); <add> return state.visibleIds.map(id => getProduct(state, id)) <ide> } <ide><path>examples/shopping-cart/server.js <del>var webpack = require('webpack'); <del>var webpackDevMiddleware = require('webpack-dev-middleware'); <del>var webpackHotMiddleware = require('webpack-hot-middleware'); <del>var config = require('./webpack.config'); <add>var webpack = require('webpack') <add>var webpackDevMiddleware = require('webpack-dev-middleware') <add>var webpackHotMiddleware = require('webpack-hot-middleware') <add>var config = require('./webpack.config') <ide> <del>var app = new require('express')(); <del>var port = 3000; <add>var app = new require('express')() <add>var port = 3000 <ide> <del>var compiler = webpack(config); <del>app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath })); <del>app.use(webpackHotMiddleware(compiler)); <add>var compiler = webpack(config) <add>app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath })) <add>app.use(webpackHotMiddleware(compiler)) <ide> <ide> app.get("/", function(req, res) { <del> res.sendFile(__dirname + '/index.html'); <del>}); <add> res.sendFile(__dirname + '/index.html') <add>}) <ide> <ide> app.listen(port, function(error) { <ide> if (error) { <del> console.error(error); <add> console.error(error) <ide> } else { <del> console.info("==> 🌎 Listening on port %s. Open up http://localhost:%s/ in your browser.", port, port); <add> console.info("==> 🌎 Listening on port %s. Open up http://localhost:%s/ in your browser.", port, port) <ide> } <del>}); <add>}) <ide><path>examples/shopping-cart/webpack.config.js <del>var path = require('path'); <del>var webpack = require('webpack'); <add>var path = require('path') <add>var webpack = require('webpack') <ide> <ide> module.exports = { <ide> devtool: 'cheap-module-eval-source-map', <ide> module.exports = { <ide> module: { <ide> loaders: [{ <ide> test: /\.js$/, <del> loaders: ['babel'], <add> loaders: [ 'babel' ], <ide> exclude: /node_modules/, <ide> include: __dirname <ide> }, <ide> { <ide> test: /\.json$/, <del> loaders: ['json'], <add> loaders: [ 'json' ], <ide> exclude: /node_modules/, <ide> include: __dirname <ide> }] <ide> } <del>}; <add>} <ide> <ide> <ide> // When inside Redux repo, prefer src to compiled version. <ide> // You can safely delete these lines in your project. <del>var reduxSrc = path.join(__dirname, '..', '..', 'src'); <del>var reduxNodeModules = path.join(__dirname, '..', '..', 'node_modules'); <del>var fs = require('fs'); <add>var reduxSrc = path.join(__dirname, '..', '..', 'src') <add>var reduxNodeModules = path.join(__dirname, '..', '..', 'node_modules') <add>var fs = require('fs') <ide> if (fs.existsSync(reduxSrc) && fs.existsSync(reduxNodeModules)) { <ide> // Resolve Redux to source <del> module.exports.resolve = { alias: { 'redux': reduxSrc } }; <add> module.exports.resolve = { alias: { 'redux': reduxSrc } } <ide> // Compile Redux from source <ide> module.exports.module.loaders.push({ <ide> test: /\.js$/, <del> loaders: ['babel'], <add> loaders: [ 'babel' ], <ide> include: reduxSrc <del> }); <add> }) <ide> }
16
Python
Python
mark the top 3 slowest tests to save ~10 seconds
db9cc9093677ce61f168fd8381dc2cfd30e2060f
<ide><path>numpy/core/tests/test_mem_overlap.py <ide> def check(ufunc, a, ind, out): <ide> a = np.arange(10000, dtype=np.int16) <ide> check(np.add, a, a[::-1], a) <ide> <add> @pytest.mark.slow <ide> def test_unary_gufunc_fuzz(self): <ide> shapes = [7, 13, 8, 21, 29, 32] <ide> gufunc = _umath_tests.euclidean_pdist <ide><path>numpy/core/tests/test_multiarray.py <ide> def test_max_dims(self): <ide> a = np.empty((1,) * 32) <ide> self._check_roundtrip(a) <ide> <add> @pytest.mark.slow <ide> def test_error_too_many_dims(self): <ide> def make_ctype(shape, scalar_type): <ide> t = scalar_type <ide><path>numpy/linalg/tests/test_linalg.py <ide> def test_xerbla_override(): <ide> pytest.skip('Numpy xerbla not linked in.') <ide> <ide> <add>@pytest.mark.slow <ide> def test_sdot_bug_8577(): <ide> # Regression test that loading certain other libraries does not <ide> # result to wrong results in float32 linear algebra.
3
Ruby
Ruby
remove unused code
64fc8963b9998cc833d7f2b04e4b9fef3428b858
<ide><path>railties/lib/rails/info.rb <ide> def property(name, value = nil) <ide> rescue Exception <ide> end <ide> <del> def frameworks <del> %w( active_record action_pack action_view action_mailer active_support active_model ) <del> end <del> <del> def framework_version(framework) <del> if Object.const_defined?(framework.classify) <del> require "#{framework}/version" <del> framework.classify.constantize.version.to_s <del> end <del> end <del> <ide> def to_s <ide> column_width = properties.names.map {|name| name.length}.max <ide> info = properties.map do |name, value| <ide><path>railties/test/rails_info_test.rb <ide> def test_property_with_block <ide> end <ide> <ide> def test_rails_version <del> assert_property 'Rails version', <add> assert_property 'Rails version', <ide> File.read(File.realpath('../../../RAILS_VERSION', __FILE__)).chomp <ide> end <ide> <del> def test_framework_version <del> assert_property 'Active Support version', ActiveSupport.version.to_s <del> end <del> <del> def test_frameworks_exist <del> Rails::Info.frameworks.each do |framework| <del> dir = File.dirname(__FILE__) + "/../../" + framework.delete('_') <del> assert File.directory?(dir), "#{framework.classify} does not exist" <del> end <del> end <del> <ide> def test_html_includes_middleware <ide> Rails::Info.module_eval do <ide> property 'Middleware', ['Rack::Lock', 'Rack::Static']
2
Python
Python
update runtests.py to specify c99 for gcc
1709249c788323afdeb6ab606dc75d252c4a7814
<ide><path>runtests.py <ide> def build_project(args): <ide> # add flags used as werrors <ide> warnings_as_errors = ' '.join([ <ide> # from tools/travis-test.sh <del> '-Werror=declaration-after-statement', <ide> '-Werror=vla', <ide> '-Werror=nonnull', <ide> '-Werror=pointer-arith', <ide> def build_project(args): <ide> '-Werror=unused-function', <ide> ]) <ide> env['CFLAGS'] = warnings_as_errors + ' ' + env.get('CFLAGS', '') <add> # NumPy > 1.16 should be C99 compatible. <add> env['CFLAGS'] = '-std=c99' + ' ' + env.get('CFLAGS', '') <ide> if args.debug or args.gcov: <ide> # assume everyone uses gcc/gfortran <ide> env['OPT'] = '-O0 -ggdb'
1
Javascript
Javascript
add types to dependency and subclasses
eba85a491ddd63bee3fdd0539d6fb6bb3b7777a8
<ide><path>lib/Dependency.js <ide> const DependencyReference = require("./dependencies/DependencyReference"); <ide> /** @typedef {import("webpack-sources").Source} Source */ <ide> /** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ <ide> /** @typedef {import("./DependencyTemplates")} DependencyTemplates */ <add>/** @typedef {import("./util/createHash").Hash} Hash */ <add>/** @typedef {import("./WebpackError")} WebpackError */ <ide> <ide> /** @typedef {Object} SourcePosition <ide> * @property {number} line <ide> const DependencyReference = require("./dependencies/DependencyReference"); <ide> <ide> /** @typedef {SynteticDependencyLocation|RealDependencyLocation} DependencyLocation */ <ide> <add>/** <add> * @typedef {Object} ExportsSpec <add> * @property {string[] | true | null} exports exported names, true for unknown exports or null for no exports <add> * @property {Module[]=} dependencies module on which the result depends on <add> */ <add> <ide> class Dependency { <ide> constructor() { <ide> /** @type {Module|null} */ <ide> class Dependency { <ide> this.loc = undefined; <ide> } <ide> <add> /** <add> * @returns {string} a display name for the type of dependency <add> */ <add> get type() { <add> return "unknown"; <add> } <add> <add> /** <add> * @returns {string | null} an identifier to merge equal requests <add> */ <ide> getResourceIdentifier() { <ide> return null; <ide> } <ide> <del> // Returns the referenced module and export <add> /** <add> * Returns the referenced module and export <add> * @returns {DependencyReference} reference <add> */ <ide> getReference() { <ide> if (!this.module) return null; <ide> return new DependencyReference(this.module, true, this.weak); <ide> } <ide> <del> // Returns the exported names <add> /** <add> * Returns the exported names <add> * @returns {ExportsSpec | undefined} export names <add> */ <ide> getExports() { <ide> return null; <ide> } <ide> <add> /** <add> * Returns warnings <add> * @returns {WebpackError[]} warnings <add> */ <ide> getWarnings() { <ide> return null; <ide> } <ide> <add> /** <add> * Returns errors <add> * @returns {WebpackError[]} errors <add> */ <ide> getErrors() { <ide> return null; <ide> } <ide> <add> /** <add> * Update the hash <add> * @param {Hash} hash hash to be updated <add> * @returns {void} <add> */ <ide> updateHash(hash) { <ide> hash.update((this.module && this.module.id) + ""); <ide> } <ide> <add> /** <add> * Disconnect the dependency from the graph <add> * @returns {void} <add> */ <ide> disconnect() { <ide> this.module = null; <ide> } <ide><path>lib/dependencies/ConstDependency.js <ide> const NullDependency = require("./NullDependency"); <ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ <ide> /** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ <ide> /** @typedef {import("../DependencyTemplates")} DependencyTemplates */ <add>/** @typedef {import("../util/createHash").Hash} Hash */ <ide> <ide> class ConstDependency extends NullDependency { <ide> constructor(expression, range, requireWebpackRequire) { <ide> class ConstDependency extends NullDependency { <ide> this.requireWebpackRequire = requireWebpackRequire; <ide> } <ide> <add> /** <add> * Update the hash <add> * @param {Hash} hash hash to be updated <add> * @returns {void} <add> */ <ide> updateHash(hash) { <ide> hash.update(this.range + ""); <ide> hash.update(this.expression + ""); <ide><path>lib/dependencies/ContextDependency.js <ide> const Dependency = require("../Dependency"); <ide> const DependencyTemplate = require("../DependencyTemplate"); <ide> const CriticalDependencyWarning = require("./CriticalDependencyWarning"); <ide> <add>/** @typedef {import("../WebpackError")} WebpackError */ <add> <ide> const regExpToString = r => (r ? r + "" : ""); <ide> <ide> class ContextDependency extends Dependency { <ide> class ContextDependency extends Dependency { <ide> this.replaces = undefined; <ide> } <ide> <add> /** <add> * @returns {string | null} an identifier to merge equal requests <add> */ <ide> getResourceIdentifier() { <ide> return ( <ide> `context${this.options.request} ${this.options.recursive} ` + <ide> class ContextDependency extends Dependency { <ide> ); <ide> } <ide> <add> /** <add> * Returns warnings <add> * @returns {WebpackError[]} warnings <add> */ <ide> getWarnings() { <ide> let warnings = super.getWarnings() || []; <ide> if (this.critical) { <ide><path>lib/dependencies/DelegatedExportsDependency.js <ide> const DependencyReference = require("./DependencyReference"); <ide> const NullDependency = require("./NullDependency"); <ide> <add>/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ <add> <ide> class DelegatedExportsDependency extends NullDependency { <ide> constructor(originModule, exports) { <ide> super(); <ide> class DelegatedExportsDependency extends NullDependency { <ide> return "delegated exports"; <ide> } <ide> <add> /** <add> * Returns the referenced module and export <add> * @returns {DependencyReference} reference <add> */ <ide> getReference() { <ide> return new DependencyReference(this.originModule, true, false); <ide> } <ide> <add> /** <add> * Returns the exported names <add> * @returns {ExportsSpec | undefined} export names <add> */ <ide> getExports() { <ide> return { <ide> exports: this.exports, <ide><path>lib/dependencies/HarmonyExportExpressionDependency.js <ide> const NullDependency = require("./NullDependency"); <ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ <ide> /** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ <ide> /** @typedef {import("../DependencyTemplates")} DependencyTemplates */ <add>/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ <ide> <ide> class HarmonyExportExpressionDependency extends NullDependency { <ide> constructor(originModule, range, rangeStatement) { <ide> class HarmonyExportExpressionDependency extends NullDependency { <ide> return "harmony export expression"; <ide> } <ide> <add> /** <add> * Returns the exported names <add> * @returns {ExportsSpec | undefined} export names <add> */ <ide> getExports() { <ide> return { <ide> exports: ["default"], <ide><path>lib/dependencies/HarmonyExportImportedSpecifierDependency.js <ide> const Template = require("../Template"); <ide> const HarmonyLinkingError = require("../HarmonyLinkingError"); <ide> <ide> /** @typedef {import("../Module")} Module */ <add>/** @typedef {import("../util/createHash").Hash} Hash */ <add>/** @typedef {import("../WebpackError")} WebpackError */ <add>/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ <ide> <ide> /** @typedef {"missing"|"unused"|"empty-star"|"reexport-non-harmony-default"|"reexport-named-default"|"reexport-namespace-object"|"reexport-non-harmony-default-strict"|"reexport-fake-namespace-object"|"rexport-non-harmony-undefined"|"safe-reexport"|"checked-reexport"|"dynamic-reexport"} ExportModeType */ <ide> <ide> class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency { <ide> return mode; <ide> } <ide> <add> /** <add> * Returns the referenced module and export <add> * @returns {DependencyReference} reference <add> */ <ide> getReference() { <ide> const mode = this.getMode(false); <ide> <ide> class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency { <ide> return result; <ide> } <ide> <add> /** <add> * Returns the exported names <add> * @returns {ExportsSpec | undefined} export names <add> */ <ide> getExports() { <ide> if (this.name) { <ide> return { <ide> class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency { <ide> }; <ide> } <ide> <add> /** <add> * Returns warnings <add> * @returns {WebpackError[]} warnings <add> */ <ide> getWarnings() { <ide> if ( <ide> this.strictExportPresence || <ide> class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency { <ide> return this._getErrors(); <ide> } <ide> <add> /** <add> * Returns errors <add> * @returns {WebpackError[]} errors <add> */ <ide> getErrors() { <ide> if ( <ide> this.strictExportPresence || <ide> class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency { <ide> return [new HarmonyLinkingError(errorMessage)]; <ide> } <ide> <add> /** <add> * Update the hash <add> * @param {Hash} hash hash to be updated <add> * @returns {void} <add> */ <ide> updateHash(hash) { <ide> super.updateHash(hash); <ide> const hashValue = this.getHashValue(this._module); <ide><path>lib/dependencies/HarmonyExportSpecifierDependency.js <ide> const NullDependency = require("./NullDependency"); <ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ <ide> /** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ <ide> /** @typedef {import("../DependencyTemplates")} DependencyTemplates */ <add>/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ <ide> <ide> class HarmonyExportSpecifierDependency extends NullDependency { <ide> constructor(originModule, id, name) { <ide> class HarmonyExportSpecifierDependency extends NullDependency { <ide> return "harmony export specifier"; <ide> } <ide> <add> /** <add> * Returns the exported names <add> * @returns {ExportsSpec | undefined} export names <add> */ <ide> getExports() { <ide> return { <ide> exports: [this.name], <ide><path>lib/dependencies/HarmonyImportDependency.js <ide> const Template = require("../Template"); <ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ <ide> /** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ <ide> /** @typedef {import("../DependencyTemplates")} DependencyTemplates */ <add>/** @typedef {import("../util/createHash").Hash} Hash */ <ide> <ide> class HarmonyImportDependency extends ModuleDependency { <ide> constructor(request, originModule, sourceOrder, parserScope) { <ide> class HarmonyImportDependency extends ModuleDependency { <ide> return this.redirectedModule || this.module; <ide> } <ide> <add> /** <add> * Returns the referenced module and export <add> * @returns {DependencyReference} reference <add> */ <ide> getReference() { <ide> if (!this._module) return null; <ide> return new DependencyReference( <ide> class HarmonyImportDependency extends ModuleDependency { <ide> }); <ide> } <ide> <add> /** <add> * Update the hash <add> * @param {Hash} hash hash to be updated <add> * @returns {void} <add> */ <ide> updateHash(hash) { <ide> super.updateHash(hash); <ide> const importedModule = this._module; <ide> class HarmonyImportDependency extends ModuleDependency { <ide> hash.update((importedModule && importedModule.id) + ""); <ide> } <ide> <add> /** <add> * Disconnect the dependency from the graph <add> * @returns {void} <add> */ <ide> disconnect() { <ide> super.disconnect(); <ide> this.redirectedModule = undefined; <ide><path>lib/dependencies/HarmonyImportSideEffectDependency.js <ide> "use strict"; <ide> const HarmonyImportDependency = require("./HarmonyImportDependency"); <ide> <add>/** @typedef {import("./DependencyReference")} DependencyReference */ <add> <ide> class HarmonyImportSideEffectDependency extends HarmonyImportDependency { <ide> constructor(request, originModule, sourceOrder, parserScope) { <ide> super(request, originModule, sourceOrder, parserScope); <ide> } <ide> <add> /** <add> * Returns the referenced module and export <add> * @returns {DependencyReference} reference <add> */ <ide> getReference() { <ide> if (this._module && this._module.factoryMeta.sideEffectFree) return null; <ide> <ide><path>lib/dependencies/HarmonyImportSpecifierDependency.js <ide> const HarmonyLinkingError = require("../HarmonyLinkingError"); <ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ <ide> /** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ <ide> /** @typedef {import("../DependencyTemplates")} DependencyTemplates */ <add>/** @typedef {import("../util/createHash").Hash} Hash */ <add>/** @typedef {import("../WebpackError")} WebpackError */ <add>/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ <ide> <ide> class HarmonyImportSpecifierDependency extends HarmonyImportDependency { <ide> constructor( <ide> class HarmonyImportSpecifierDependency extends HarmonyImportDependency { <ide> return this.redirectedId || this.id; <ide> } <ide> <add> /** <add> * Returns the referenced module and export <add> * @returns {DependencyReference} reference <add> */ <ide> getReference() { <ide> if (!this._module) return null; <ide> return new DependencyReference( <ide> class HarmonyImportSpecifierDependency extends HarmonyImportDependency { <ide> ); <ide> } <ide> <add> /** <add> * Returns warnings <add> * @returns {WebpackError[]} warnings <add> */ <ide> getWarnings() { <ide> if ( <ide> this.strictExportPresence || <ide> class HarmonyImportSpecifierDependency extends HarmonyImportDependency { <ide> return this._getErrors(); <ide> } <ide> <add> /** <add> * Returns errors <add> * @returns {WebpackError[]} errors <add> */ <ide> getErrors() { <ide> if ( <ide> this.strictExportPresence || <ide> class HarmonyImportSpecifierDependency extends HarmonyImportDependency { <ide> return 0; <ide> } <ide> <add> /** <add> * Update the hash <add> * @param {Hash} hash hash to be updated <add> * @returns {void} <add> */ <ide> updateHash(hash) { <ide> super.updateHash(hash); <ide> const importedModule = this._module; <ide> class HarmonyImportSpecifierDependency extends HarmonyImportDependency { <ide> ); <ide> } <ide> <add> /** <add> * Disconnect the dependency from the graph <add> * @returns {void} <add> */ <ide> disconnect() { <ide> super.disconnect(); <ide> this.redirectedId = undefined; <ide><path>lib/dependencies/JsonExportsDependency.js <ide> "use strict"; <ide> const NullDependency = require("./NullDependency"); <ide> <add>/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ <add> <ide> class JsonExportsDependency extends NullDependency { <ide> constructor(exports) { <ide> super(); <ide> class JsonExportsDependency extends NullDependency { <ide> return "json exports"; <ide> } <ide> <add> /** <add> * Returns the exported names <add> * @returns {ExportsSpec | undefined} export names <add> */ <ide> getExports() { <ide> return { <ide> exports: this.exports, <ide><path>lib/dependencies/ModuleDependency.js <ide> class ModuleDependency extends Dependency { <ide> this.range = undefined; <ide> } <ide> <add> /** <add> * @returns {string | null} an identifier to merge equal requests <add> */ <ide> getResourceIdentifier() { <ide> return `module${this.request}`; <ide> } <ide><path>lib/dependencies/NullDependency.js <ide> const DependencyTemplate = require("../DependencyTemplate"); <ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ <ide> /** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ <ide> /** @typedef {import("../DependencyTemplates")} DependencyTemplates */ <add>/** @typedef {import("../util/createHash").Hash} Hash */ <ide> <ide> class NullDependency extends Dependency { <ide> get type() { <ide> return "null"; <ide> } <ide> <del> updateHash() {} <add> /** <add> * Update the hash <add> * @param {Hash} hash hash to be updated <add> * @returns {void} <add> */ <add> updateHash(hash) {} <ide> } <ide> <ide> NullDependency.Template = class NullDependencyTemplate extends DependencyTemplate { <ide><path>lib/dependencies/RequireIncludeDependency.js <ide> class RequireIncludeDependency extends ModuleDependency { <ide> this.range = range; <ide> } <ide> <add> /** <add> * Returns the referenced module and export <add> * @returns {DependencyReference} reference <add> */ <ide> getReference() { <ide> if (!this.module) return null; <ide> // This doesn't use any export <ide><path>lib/dependencies/WebAssemblyExportImportedDependency.js <ide> class WebAssemblyExportImportedDependency extends ModuleDependency { <ide> this.name = name; <ide> } <ide> <add> /** <add> * Returns the referenced module and export <add> * @returns {DependencyReference} reference <add> */ <ide> getReference() { <ide> if (!this.module) return null; <ide> return new DependencyReference(this.module, [this.name], false); <ide><path>lib/dependencies/WebAssemblyImportDependency.js <ide> const DependencyReference = require("./DependencyReference"); <ide> const ModuleDependency = require("./ModuleDependency"); <ide> const UnsupportedWebAssemblyFeatureError = require("../wasm/UnsupportedWebAssemblyFeatureError"); <ide> <add>/** @typedef {import("../WebpackError")} WebpackError */ <add> <ide> class WebAssemblyImportDependency extends ModuleDependency { <ide> constructor(request, name, description, onlyDirectImport) { <ide> super(request); <ide> class WebAssemblyImportDependency extends ModuleDependency { <ide> this.onlyDirectImport = onlyDirectImport; <ide> } <ide> <add> /** <add> * Returns the referenced module and export <add> * @returns {DependencyReference} reference <add> */ <ide> getReference() { <ide> if (!this.module) return null; <ide> return new DependencyReference(this.module, [this.name], false); <ide> } <ide> <add> /** <add> * Returns errors <add> * @returns {WebpackError[]} errors <add> */ <ide> getErrors() { <ide> if ( <ide> this.onlyDirectImport &&
16
PHP
PHP
add bound check to env resolving
d0353b8dd16bd6010e37bd658cc29d469ef4ee8d
<ide><path>src/Illuminate/Foundation/Application.php <ide> public function runningInConsole() <ide> */ <ide> public function runningUnitTests() <ide> { <del> return $this['env'] === 'testing'; <add> return $this->bound('env') && $this['env'] === 'testing'; <ide> } <ide> <ide> /**
1
PHP
PHP
add withdefault to morphone relations
ff00aa9e02634b94ec2b6572a3dcdb90d4349071
<ide><path>src/Illuminate/Database/Eloquent/Relations/BelongsTo.php <ide> use Illuminate\Database\Eloquent\Model; <ide> use Illuminate\Database\Eloquent\Builder; <ide> use Illuminate\Database\Eloquent\Collection; <add>use Illuminate\Database\Eloquent\Relations\Concerns\HasDefault; <ide> <ide> class BelongsTo extends Relation <ide> { <del> /** <del> * Indicates if a default model instance should be used. <del> * <del> * Alternatively, may be a Closure or array. <del> * <del> * @var \Closure|array|bool <del> */ <del> protected $withDefault; <add> use HasDefault; <ide> <ide> /** <ide> * The child model instance of the relation. <ide> public function initRelation(array $models, $relation) <ide> return $models; <ide> } <ide> <del> /** <del> * Get the default value for this relation. <del> * <del> * @param \Illuminate\Database\Eloquent\Model $model <del> * @return \Illuminate\Database\Eloquent\Model|null <del> */ <del> protected function getDefaultFor(Model $model) <del> { <del> if (! $this->withDefault) { <del> return; <del> } <del> <del> $instance = $this->related->newInstance(); <del> <del> if (is_callable($this->withDefault)) { <del> return call_user_func($this->withDefault, $instance) ?: $instance; <del> } <del> <del> if (is_array($this->withDefault)) { <del> $instance->forceFill($this->withDefault); <del> } <del> <del> return $instance; <del> } <del> <ide> /** <ide> * Match the eagerly loaded results to their parents. <ide> * <ide> protected function relationHasIncrementingId() <ide> $this->related->getKeyType() === 'int'; <ide> } <ide> <del> /** <del> * Return a new model instance in case the relationship does not exist. <del> * <del> * @param \Closure|array|bool $callback <del> * @return $this <del> */ <del> public function withDefault($callback = true) <del> { <del> $this->withDefault = $callback; <del> <del> return $this; <del> } <del> <ide> /** <ide> * Get the foreign key of the relationship. <ide> * <ide> public function getRelation() <ide> { <ide> return $this->relation; <ide> } <add> <add> /** <add> * Make a new related instance for the given model. <add> * <add> * @param \Illuminate\Database\Eloquent\Model $parent <add> * @return \Illuminate\Database\Eloquent\Model <add> */ <add> protected function newRelatedInstanceFor(Model $parent) <add> { <add> return $this->related->newInstance(); <add> } <ide> } <ide><path>src/Illuminate/Database/Eloquent/Relations/Concerns/HasDefault.php <add><?php <add> <add>namespace Illuminate\Database\Eloquent\Relations\Concerns; <add> <add>use Illuminate\Database\Eloquent\Model; <add> <add>trait HasDefault <add>{ <add> /** <add> * Indicates if a default model instance should be used. <add> * <add> * Alternatively, may be a Closure or array. <add> * <add> * @var \Closure|array|bool <add> */ <add> protected $withDefault; <add> <add> /** <add> * Return a new model instance in case the relationship does not exist. <add> * <add> * @param \Closure|array|bool $callback <add> * @return $this <add> */ <add> public function withDefault($callback = true) <add> { <add> $this->withDefault = $callback; <add> <add> return $this; <add> } <add> <add> /** <add> * Get the default value for this relation. <add> * <add> * @param \Illuminate\Database\Eloquent\Model $parent <add> * @return \Illuminate\Database\Eloquent\Model|null <add> */ <add> protected function getDefaultFor(Model $parent) <add> { <add> if (! $this->withDefault) { <add> return; <add> } <add> <add> $instance = $this->newRelatedInstanceFor($parent); <add> <add> if (is_callable($this->withDefault)) { <add> return call_user_func($this->withDefault, $instance) ?: $instance; <add> } <add> <add> if (is_array($this->withDefault)) { <add> $instance->forceFill($this->withDefault); <add> } <add> <add> return $instance; <add> } <add> <add> /** <add> * Make a new related instance for the given model. <add> * <add> * @param \Illuminate\Database\Eloquent\Model $parent <add> * @return \Illuminate\Database\Eloquent\Model <add> */ <add> abstract protected function newRelatedInstanceFor(Model $parent); <add>} <ide><path>src/Illuminate/Database/Eloquent/Relations/HasOne.php <ide> <ide> use Illuminate\Database\Eloquent\Model; <ide> use Illuminate\Database\Eloquent\Collection; <add>use Illuminate\Database\Eloquent\Relations\Concerns\HasDefault; <ide> <ide> class HasOne extends HasOneOrMany <ide> { <del> /** <del> * Indicates if a default model instance should be used. <del> * <del> * Alternatively, may be a Closure or array. <del> * <del> * @var \Closure|array|bool <del> */ <del> protected $withDefault; <add> use HasDefault; <ide> <ide> /** <ide> * Get the results of the relationship. <ide> public function initRelation(array $models, $relation) <ide> return $models; <ide> } <ide> <del> /** <del> * Get the default value for this relation. <del> * <del> * @param \Illuminate\Database\Eloquent\Model $model <del> * @return \Illuminate\Database\Eloquent\Model|null <del> */ <del> protected function getDefaultFor(Model $model) <del> { <del> if (! $this->withDefault) { <del> return; <del> } <del> <del> $instance = $this->related->newInstance()->setAttribute( <del> $this->getForeignKeyName(), $model->getAttribute($this->localKey) <del> ); <del> <del> if (is_callable($this->withDefault)) { <del> return call_user_func($this->withDefault, $instance) ?: $instance; <del> } <del> <del> if (is_array($this->withDefault)) { <del> $instance->forceFill($this->withDefault); <del> } <del> <del> return $instance; <del> } <del> <ide> /** <ide> * Match the eagerly loaded results to their parents. <ide> * <ide> public function match(array $models, Collection $results, $relation) <ide> } <ide> <ide> /** <del> * Return a new model instance in case the relationship does not exist. <add> * Make a new related instance for the given model. <ide> * <del> * @param \Closure|array|bool $callback <del> * @return $this <add> * @param \Illuminate\Database\Eloquent\Model $parent <add> * @return \Illuminate\Database\Eloquent\Model <ide> */ <del> public function withDefault($callback = true) <add> public function newRelatedInstanceFor(Model $parent) <ide> { <del> $this->withDefault = $callback; <del> <del> return $this; <add> return $this->related->newInstance() <add> ->setAttribute($this->getForeignKeyName(), $parent->{$this->localKey}); <ide> } <ide> } <ide><path>src/Illuminate/Database/Eloquent/Relations/MorphOne.php <ide> <ide> namespace Illuminate\Database\Eloquent\Relations; <ide> <add>use Illuminate\Database\Eloquent\Model; <ide> use Illuminate\Database\Eloquent\Collection; <add>use Illuminate\Database\Eloquent\Relations\Concerns\HasDefault; <ide> <ide> class MorphOne extends MorphOneOrMany <ide> { <add> use HasDefault; <add> <ide> /** <ide> * Get the results of the relationship. <ide> * <ide> * @return mixed <ide> */ <ide> public function getResults() <ide> { <del> return $this->query->first(); <add> return $this->query->first() ?: $this->getDefaultFor($this->parent); <ide> } <ide> <ide> /** <ide> public function getResults() <ide> public function initRelation(array $models, $relation) <ide> { <ide> foreach ($models as $model) { <del> $model->setRelation($relation, null); <add> $model->setRelation($relation, $this->getDefaultFor($model)); <ide> } <ide> <ide> return $models; <ide> public function match(array $models, Collection $results, $relation) <ide> { <ide> return $this->matchOne($models, $results, $relation); <ide> } <add> <add> /** <add> * Make a new related instance for the given model. <add> * <add> * @param \Illuminate\Database\Eloquent\Model $parent <add> * @return \Illuminate\Database\Eloquent\Model <add> */ <add> public function newRelatedInstanceFor(Model $parent) <add> { <add> return $this->related->newInstance() <add> ->setAttribute($this->getForeignKeyName(), $parent->{$this->localKey}) <add> ->setAttribute($this->getMorphType(), $this->morphClass); <add> } <ide> }
4
Ruby
Ruby
remove warning of unused variable
1938c9646b7edcae88817a9b3b0e5d8b897ecc77
<ide><path>activerecord/test/cases/adapters/postgresql/bytea_test.rb <ide> def test_write_value <ide> <ide> def test_via_to_sql <ide> data = "'\u001F\\" <del> record = ByteaDataType.create(payload: data) <add> ByteaDataType.create(payload: data) <ide> sql = ByteaDataType.where(payload: data).select(:payload).to_sql <ide> result = @connection.query(sql) <ide> assert_equal([[data]], result)
1
Javascript
Javascript
write ci fingerprint in build.js
250d1044f3eaf1a7f40b334edccc2d0978b46334
<ide><path>build/build.js <ide> require('coffee-script/register') <ide> <ide> const cleanOutputDirectory = require('./lib/clean-output-directory') <ide> const copyAssets = require('./lib/copy-assets') <add>const generateMetadata = require('./lib/generate-metadata') <add>const generateModuleCache = require('./lib/generate-module-cache') <add>const packageApplication = require('./lib/package-application') <add>const prebuildLessCache = require('./lib/prebuild-less-cache') <ide> const transpileBabelPaths = require('./lib/transpile-babel-paths') <ide> const transpileCoffeeScriptPaths = require('./lib/transpile-coffee-script-paths') <ide> const transpileCsonPaths = require('./lib/transpile-cson-paths') <ide> const transpilePegJsPaths = require('./lib/transpile-peg-js-paths') <del>const generateModuleCache = require('./lib/generate-module-cache') <del>const prebuildLessCache = require('./lib/prebuild-less-cache') <del>const generateMetadata = require('./lib/generate-metadata') <del>const packageApplication = require('./lib/package-application') <add>const writeFingerprint = require('./lib/fingerprint').writeFingerprint <ide> <ide> cleanOutputDirectory() <ide> copyAssets() <ide> generateModuleCache() <ide> prebuildLessCache() <ide> generateMetadata() <ide> packageApplication() <add>writeFingerprint() <ide><path>build/config.js <ide> const path = require('path') <ide> <ide> const appMetadata = require('../package.json') <add>const apmMetadata = require('../apm/node_modules/atom-package-manager/package.json') <add> <ide> const channel = getChannel() <ide> <ide> const repositoryRootPath = path.resolve(__dirname, '..') <ide> const cachePath = path.join(repositoryRootPath, 'cache') <ide> const homeDirPath = process.env.HOME || process.env.USERPROFILE <ide> <ide> module.exports = { <del> appMetadata, channel, <add> appMetadata, apmMetadata, channel, <ide> repositoryRootPath, buildOutputPath, intermediateAppPath, <ide> cachePath, homeDirPath <ide> } <ide><path>build/lib/fingerprint.js <add>const crypto = require('crypto') <add>const fs = require('fs') <add>const path = require('path') <add> <add>const CONFIG = require('../config') <add>const FINGERPRINT_PATH = path.join(CONFIG.repositoryRootPath, 'node_modules', '.atom-ci-fingerprint') <add> <add>exports.writeFingerprint = function () { <add> const fingerprint = computeFingerprint() <add> fs.writeFileSync(FINGERPRINT_PATH, fingerprint) <add> console.log('Wrote CI fingerprint:', FINGERPRINT_PATH, fingerprint) <add>}, <add> <add>exports.fingerprintMatches = function () { <add> const oldFingerprint = readFingerprint() <add> return oldFingerprint && oldFingerprint === computeFingerprint() <add>} <add> <add>function computeFingerprint () { <add> //Include the electron minor version in the fingerprint since that changing requires a re-install <add> const electronVersion = CONFIG.appMetadata.electronVersion.replace(/\.\d+$/, '') <add> const apmVersion = CONFIG.apmMetadata.version <add> <add> const body = electronVersion + apmVersion + process.platform + process.version <add> return crypto.createHash('sha1').update(body).digest('hex') <add>} <add> <add>function readFingerprint () { <add> if (fs.existsSync(FINGERPRINT_PATH)) { <add> return fs.readFileSync(FINGERPRINT_PATH, 'utf8') <add> } else { <add> return null <add> } <add>}
3
Python
Python
remove useless statement in task_group_to_grid
84718f92334b7e43607ab617ef31f3ffc4257635
<ide><path>airflow/www/views.py <ide> def set_overall_state(record): <ide> record['state'] = state <ide> break <ide> if None in record['mapped_states']: <del> # When turnong the dict into JSON we can't have None as a key, so use the string that <del> # the UI does <add> # When turning the dict into JSON we can't have None as a key, <add> # so use the string that the UI does. <ide> record['mapped_states']['no_status'] = record['mapped_states'].pop(None) <ide> <ide> for ti_summary in ti_summaries: <del> if ti_summary.state is None: <del> ti_summary.state == 'no_status' <ide> if run_id != ti_summary.run_id: <ide> run_id = ti_summary.run_id <ide> if record:
1
Python
Python
fix model outputs test
8bcceaceff990f77d22994c1aa25540d6874b640
<ide><path>tests/test_modeling_common.py <ide> def recursive_check(tuple_object, dict_object): <ide> recursive_check(tuple_iterable_value, dict_iterable_value) <ide> elif tuple_object is None: <ide> return <add> elif torch.isinf(tuple_object).any() and torch.isinf(dict_object).any(): <add> # TODO: (Lysandre) - maybe take a look if that's ok here <add> return <ide> else: <ide> self.assertTrue( <ide> torch.allclose(tuple_object, dict_object, atol=1e-5), <del> msg=f"Tuple and dict output are not equal. Difference: {torch.max(torch.abs(tuple_object - dict_object))}", <add> msg=f"Tuple and dict output are not equal. Difference: {torch.max(torch.abs(tuple_object - dict_object))}. Tuple has `nan`: {torch.isnan(tuple_object).any()} and `inf`: {torch.isinf(tuple_object)}. Dict has `nan`: {torch.isnan(dict_object).any()} and `inf`: {torch.isinf(dict_object)}.", <ide> ) <ide> <ide> recursive_check(tuple_output, dict_output)
1
Ruby
Ruby
use predicatebuilder for sql hash sanitization
77c23b2104d62ab1cf1fb5808fef14e38d094605
<ide><path>activerecord/lib/active_record/associations.rb <ide> def configure_dependency_for_has_many(reflection, extra_conditions = nil) <ide> dependent_conditions = [] <ide> dependent_conditions << "#{reflection.primary_key_name} = \#{record.#{reflection.name}.send(:owner_quoted_id)}" <ide> dependent_conditions << "#{reflection.options[:as]}_type = '#{base_class.name}'" if reflection.options[:as] <del> dependent_conditions << sanitize_sql(reflection.options[:conditions], reflection.quoted_table_name) if reflection.options[:conditions] <add> dependent_conditions << sanitize_sql(reflection.options[:conditions], reflection.table_name) if reflection.options[:conditions] <ide> dependent_conditions << extra_conditions if extra_conditions <ide> dependent_conditions = dependent_conditions.collect {|where| "(#{where})" }.join(" AND ") <ide> dependent_conditions = dependent_conditions.gsub('@', '\@') <ide><path>activerecord/lib/active_record/base.rb <ide> def arel_table(table = nil) <ide> Relation.new(self, Arel::Table.new(table || table_name)) <ide> end <ide> <add> def engine <add> @engine ||= Arel::Sql::Engine.new(self) <add> end <add> <ide> private <ide> # Finder methods must instantiate through this method to work with the <ide> # single-table inheritance model that makes it possible to create <ide> def class_name_of_active_record_descendant(klass) #:nodoc: <ide> # ["name='%s' and group_id='%s'", "foo'bar", 4] returns "name='foo''bar' and group_id='4'" <ide> # { :name => "foo'bar", :group_id => 4 } returns "name='foo''bar' and group_id='4'" <ide> # "name='foo''bar' and group_id='4'" returns "name='foo''bar' and group_id='4'" <del> def sanitize_sql_for_conditions(condition, table_name = quoted_table_name) <add> def sanitize_sql_for_conditions(condition, table_name = self.table_name) <ide> return nil if condition.blank? <ide> <ide> case condition <ide> def expand_hash_conditions_for_aggregates(attrs) <ide> # And for value objects on a composed_of relationship: <ide> # { :address => Address.new("123 abc st.", "chicago") } <ide> # # => "address_street='123 abc st.' and address_city='chicago'" <del> def sanitize_sql_hash_for_conditions(attrs, default_table_name = quoted_table_name) <add> def sanitize_sql_hash_for_conditions(attrs, default_table_name = self.table_name) <ide> attrs = expand_hash_conditions_for_aggregates(attrs) <ide> <del> conditions = attrs.map do |attr, value| <del> table_name = default_table_name <del> <del> unless value.is_a?(Hash) <del> attr = attr.to_s <del> <del> # Extract table name from qualified attribute names. <del> if attr.include?('.') <del> attr_table_name, attr = attr.split('.', 2) <del> attr_table_name = connection.quote_table_name(attr_table_name) <del> else <del> attr_table_name = table_name <del> end <del> <del> attribute_condition("#{attr_table_name}.#{connection.quote_column_name(attr)}", value) <del> else <del> sanitize_sql_hash_for_conditions(value, connection.quote_table_name(attr.to_s)) <del> end <del> end.join(' AND ') <del> <del> replace_bind_variables(conditions, expand_range_bind_variables(attrs.values)) <add> table = Arel::Table.new(default_table_name, engine) <add> builder = PredicateBuilder.new(engine) <add> builder.build_from_hash(attrs, table).map(&:to_sql).join(' AND ') <ide> end <ide> alias_method :sanitize_sql_hash, :sanitize_sql_hash_for_conditions <ide> <ide><path>activerecord/lib/active_record/relation/predicate_builder.rb <ide> def build_from_hash(attributes, default_table) <ide> arel_table = Arel::Table.new(table_name, @engine) <ide> end <ide> <add> attribute = Arel::Attribute.new(arel_table, column.to_sym) <add> <ide> case value <ide> when Array, Range, ActiveRecord::Associations::AssociationCollection, ActiveRecord::NamedScope::Scope <del> arel_table[column].in(value) <add> attribute.in(value) <ide> else <del> arel_table[column].eq(value) <add> attribute.eq(value) <ide> end <ide> end <ide> end
3
Javascript
Javascript
remove unused function argument
520db0ca7e73a01e34dddab8079f41b243947345
<ide><path>src/ngAnimate/animate.js <ide> angular.module('ngAnimate', ['ng']) <ide> // This will automatically be called by $animate so <ide> // there is no need to attach this internally to the <ide> // timeout done method. <del> function onEnd(cancelled) { <add> function onEnd() { <ide> element.off(css3AnimationEvents, onAnimationProgress); <ide> element.removeClass(activeClassName); <ide> element.removeClass(pendingClassName);
1