content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Javascript
Javascript
fix performance regression
9cbf6af5b5ace0cc53c1a1da3234aeca02522ec6
<ide><path>lib/internal/streams/lazy_transform.js <ide> module.exports = LazyTransform; <ide> <ide> function LazyTransform(options) { <ide> this._options = options; <del> this.writable = true; <del> this.readable = true; <ide> } <ide> ObjectSetPrototypeOf(LazyTransform.prototype, stream.Transform.prototype); <ide> ObjectSetPrototypeOf(LazyTransform, stream.Transform);
1
Ruby
Ruby
add arm to cpu.type
c6cbf9590d897db7cff7f2f81863ae34ccc947ed
<ide><path>Library/Homebrew/extend/os/linux/hardware/cpu.rb <ide> def cpuinfo <ide> def type <ide> @type ||= if cpuinfo =~ /Intel|AMD/ <ide> :intel <add> elsif cpuinfo =~ /ARM|Marvell/ <add> :arm <ide> else <ide> :dunno <ide> end <ide> def cores <ide> end <ide> <ide> def flags <del> @flags ||= cpuinfo[/^flags.*/, 0].split <add> @flags ||= cpuinfo[/^(flags|Features).*/, 0].split <ide> end <ide> <ide> # Compatibility with Mac method, which returns lowercase symbols
1
Ruby
Ruby
add view paths to engine setup
02c5137eadbb3530033d919b7aebeb6f4f389b83
<ide><path>actionmailer/lib/action_mailer/railtie.rb <ide> class Railtie < Rails::Railtie <ide> <ide> initializer "action_mailer.view_paths" do |app| <ide> # TODO: this should be combined with the logic for default config.action_mailer.view_paths <del> view_path = ActionView::PathSet.type_cast(app.config.view_path, app.config.cache_classes) <del> ActionMailer::Base.template_root = view_path if ActionMailer::Base.view_paths.blank? <add> ActionMailer::Base.template_root = [] if ActionMailer::Base.view_paths.blank? <ide> end <ide> end <ide> end <ide>\ No newline at end of file <ide><path>actionpack/lib/action_controller/railtie.rb <ide> class Railtie < Rails::Railtie <ide> # set to use Configuration#view_path. <ide> initializer "action_controller.initialize_framework_views" do |app| <ide> # TODO: this should be combined with the logic for default config.action_controller.view_paths <del> view_path = ActionView::PathSet.type_cast(app.config.view_path, app.config.cache_classes) <del> ActionController::Base.view_paths = view_path if ActionController::Base.view_paths.blank? <add> ActionController::Base.view_paths = [] if ActionController::Base.view_paths.blank? <ide> end <ide> <ide> end <ide><path>railties/lib/rails/application.rb <del>require "fileutils" <add>require 'fileutils' <ide> <ide> module Rails <ide> class Application < Engine <ide> include Initializable <ide> <ide> class << self <ide> alias :configure :class_eval <del> delegate :initialize!, :load_tasks, :load_generators, :to => :instance <add> delegate :initialize!, :load_tasks, :load_generators, :root, :to => :instance <ide> <ide> private :new <ide> def instance <ide> @instance ||= new <ide> end <ide> <ide> def config <del> @config ||= Configuration.new(root) <add> @config ||= Configuration.new(original_root) <ide> end <ide> <del> def root <del> @root ||= find_root_with_file_flag("config.ru", Dir.pwd) <add> def original_root <add> @original_root ||= find_root_with_file_flag("config.ru", Dir.pwd) <ide> end <ide> <ide> def inherited(base) <ide> def call(env) <ide> app.call(env) <ide> end <ide> <del> initializer :build_middleware_stack, :after => :load_application_initializers do <del> app <del> end <del> <ide> initializer :add_builtin_route do |app| <ide> if Rails.env.development? <ide> app.route_configuration_files << File.join(RAILTIES_PATH, 'builtin', 'routes.rb') <ide> end <ide> end <ide> <add> initializer :build_middleware_stack, :after => :load_application_initializers do <add> app <add> end <add> <ide> # Fires the user-supplied after_initialize block (Configuration#after_initialize) <ide> initializer :after_initialize, :after => :build_middleware_stack do <ide> config.after_initialize_blocks.each do |block| <ide><path>railties/lib/rails/configuration.rb <ide> def config_keys <ide> end <ide> <ide> class Engine::Configuration < Railtie::Configuration <del> attr_reader :root <add> attr_reader :root <add> attr_accessor :eager_load_paths, :load_once_paths, :load_paths <ide> <ide> def initialize(root) <ide> @root = root <ide> def initialize(root) <ide> <ide> def paths <ide> @paths ||= begin <del> paths = Rails::Application::Root.new(root) <add> paths = Rails::Application::Root.new(@root) <ide> paths.app "app", :load_path => true <ide> paths.app_glob "app/*", :load_path => true, :eager_load => true <del> paths.app.controllers "app/controllers" <add> paths.app.controllers "app/controllers", :eager_load => true <ide> paths.app.metals "app/metal" <ide> paths.app.views "app/views" <ide> paths.lib "lib", :load_path => true <ide> paths.config "config" <add> paths.config.environment "config/environments/#{Rails.env}.rb" <ide> paths.config.environments "config/environments", :glob => "#{Rails.env}.rb" <ide> paths.config.initializers "config/initializers" <ide> paths.config.locales "config/locales" <ide> def paths <ide> end <ide> end <ide> <add> def root=(value) <add> @root = paths.path = Pathname.new(value).expand_path <add> end <add> <ide> def eager_load_paths <ide> @eager_load_paths ||= paths.eager_load <ide> end <ide> def load_once_paths <ide> def load_paths <ide> @load_paths ||= paths.load_paths <ide> end <add> <add> def controller_paths <add> paths.app.controllers.to_a.uniq <add> end <ide> end <ide> <ide> class Configuration < Engine::Configuration <ide> class Configuration < Engine::Configuration <ide> :preload_frameworks, :reload_plugins, :serve_static_assets, <ide> :time_zone, :whiny_nils <ide> <del> attr_writer :cache_store, :controller_paths, <del> :database_configuration_file, <del> :i18n, :log_level, :log_path <add> attr_writer :cache_store, :controller_paths, :i18n, :log_level <ide> <ide> def initialize(*) <ide> super <ide> def after_initialize(&blk) <ide> def paths <ide> @paths ||= begin <ide> paths = super <del> paths.builtin_controller builtin_directories, :eager_load => true <add> paths.app.controllers << builtin_directories <ide> paths.config.database "config/database.yml" <ide> paths.log "log/#{Rails.env}.log" <ide> paths.tmp "tmp" <ide> def paths <ide> <ide> if File.exists?("#{root}/test/mocks/#{Rails.env}") <ide> ActiveSupport::Deprecation.warn "\"RAILS_ROOT/test/mocks/#{Rails.env}\" won't be added " << <del> "automatically to load paths anymore in next releases." <add> "automatically to load paths anymore in future releases" <ide> paths.mocks_path "test/mocks/#{Rails.env}", :load_path => true <ide> end <ide> <ide> def log_path <ide> paths.config.log.to_a.first <ide> end <ide> <del> <del> <del> # TODO Router needs this, but this wouldn't work with engines. <del> # There is a high chance of plugins routes to be broken. <del> def controller_paths <del> @controller_paths ||= begin <del> paths = [File.join(root, 'app', 'controllers')] <del> paths.concat builtin_directories <del> paths <del> end <del> end <del> <ide> def cache_store <ide> @cache_store ||= begin <ide> if File.exist?("#{root}/tmp/cache/") <ide><path>railties/lib/rails/engine.rb <ide> require 'active_support/core_ext/module/delegation' <ide> <ide> module Rails <del> # TODO Move I18n and views path setup <add> # TODO Move I18n here <add> # TODO Set routes namespaces <ide> class Engine < Railtie <ide> <ide> class << self <ide> attr_accessor :called_from <ide> <del> def root <del> @root ||= find_root_with_file_flag("lib") <add> def original_root <add> @original_root ||= find_root_with_file_flag("lib") <ide> end <ide> <ide> def config <del> @config ||= Configuration.new(root) <add> @config ||= Configuration.new(original_root) <ide> end <ide> <ide> def inherited(base) <ide> base.called_from = begin <ide> call_stack = caller.map { |p| p.split(':').first } <ide> File.dirname(call_stack.detect { |p| p !~ %r[railties/lib/rails|rack/lib/rack] }) <ide> end <add> <ide> super <ide> end <ide> <ide> def find_root_with_file_flag(flag, default=nil) <ide> root_path = parent != root_path && parent <ide> end <ide> <del> root = File.exist?("#{root_path}/flag") ? root_path : default <add> root = File.exist?("#{root_path}/#{flag}") ? root_path : default <ide> <ide> raise "Could not find root path for #{self}" unless root <ide> <ide> def find_root_with_file_flag(flag, default=nil) <ide> end <ide> end <ide> <del> delegate :root, :config, :to => :'self.class' <del> delegate :middleware, :to => :config <add> delegate :config, :to => :'self.class' <add> delegate :middleware, :root, :to => :config <ide> <ide> # Add configured load paths to ruby load paths and remove duplicates. <ide> initializer :set_load_path, :before => :container do <ide> def find_root_with_file_flag(flag, default=nil) <ide> initializer :set_autoload_paths, :before => :container do <ide> require 'active_support/dependencies' <ide> <del> ActiveSupport::Dependencies.load_paths = expand_load_path(config.load_paths) <add> ActiveSupport::Dependencies.load_paths = expand_load_path(config.load_paths) <ide> ActiveSupport::Dependencies.load_once_paths = expand_load_path(config.load_once_paths) <ide> <del> extra = ActiveSupport::Dependencies.load_once_paths - ActiveSupport::Dependencies.load_paths <add> extra = ActiveSupport::Dependencies.load_once_paths - <add> ActiveSupport::Dependencies.load_paths <ide> <ide> unless extra.empty? <ide> abort <<-end_error <ide> def find_root_with_file_flag(flag, default=nil) <ide> config.load_once_paths.freeze <ide> end <ide> <del> initializer :load_application_initializers do <del> Dir["#{root}/config/initializers/**/*.rb"].sort.each do |initializer| <del> load(initializer) <del> end <add> # Routing must be initialized after plugins to allow the former to extend the routes <add> initializer :add_routing_files do |app| <add> routes = select_existing(config.paths.config.routes) <add> app.route_configuration_files.concat(routes) <ide> end <ide> <del> # Routing must be initialized after plugins to allow the former to extend the routes <del> initializer :initialize_routing do |app| <del> app.route_configuration_files.concat(config.paths.config.routes.to_a) <add> initializer :add_view_paths do <add> views = select_existing(config.paths.app.views) <add> ActionController::Base.view_paths.concat(views) if defined? ActionController <add> ActionMailer::Base.view_paths.concat(views) if defined? ActionMailer <add> end <add> <add> initializer :load_application_initializers do <add> select_existing(config.paths.config.initializers).each do |initializers| <add> Dir["#{initializers}/**/*.rb"].sort.each do |initializer| <add> load(initializer) <add> end <add> end <ide> end <ide> <ide> # Eager load application classes <ide> def find_root_with_file_flag(flag, default=nil) <ide> <ide> private <ide> <add> def select_existing(paths) <add> paths.to_a.select { |path| File.exists?(path) }.uniq <add> end <add> <ide> def expand_load_path(load_paths) <ide> load_paths.map { |path| Dir.glob(path.to_s) }.flatten.uniq <ide> end <ide><path>railties/lib/rails/railtie.rb <ide> def inherited(base) <ide> @@plugins << base unless abstract_railtie?(base) <ide> end <ide> <add> # This should be called railtie_name and engine_name <ide> def plugin_name(plugin_name = nil) <ide> @plugin_name ||= name.demodulize.underscore <ide> @plugin_name = plugin_name if plugin_name <ide><path>railties/test/application/configuration_test.rb <ide> def setup <ide> add_to_config <<-RUBY <ide> config.root = '#{new_app}' <ide> RUBY <del> <add> <ide> use_frameworks [] <del> <add> <ide> require "#{app_path}/config/environment" <ide> assert_equal Pathname.new(new_app), Rails.application.root <ide> end
7
Text
Text
standardize typography for _semantic versioning_
87089bf8c63db4696090b52bd8b2d9794ffe83c2
<ide><path>README.md <ide> Looking for help? Check out the <ide> * **Nightly**: Code from the Current branch built every 24-hours when there are <ide> changes. Use with caution. <ide> <del>Current and LTS releases follow [Semantic Versioning](https://semver.org). A <add>Current and LTS releases follow [semantic versioning](https://semver.org). A <ide> member of the Release Team [signs](#release-keys) each Current and LTS release. <ide> For more information, see the <ide> [Release README](https://github.com/nodejs/Release#readme). <ide><path>doc/api/documentation.md <ide> The stability indices are as follows: <ide> <!-- separator --> <ide> <ide> > Stability: 1 - Experimental. The feature is not subject to <del>> [Semantic Versioning][] rules. Non-backward compatible changes or removal may <add>> [semantic versioning][] rules. Non-backward compatible changes or removal may <ide> > occur in any future release. Use of the feature is not recommended in <ide> > production environments. <ide> <ide> The stability indices are as follows: <ide> <!-- separator --> <ide> <ide> > Stability 3 - Legacy. Although this feature is unlikely to be removed and is <del>> still covered by semantic-versioning guarantees, it is no longer actively <add>> still covered by semantic versioning guarantees, it is no longer actively <ide> > maintained, and other alternatives are available. <ide> <ide> Features are marked as legacy rather than being deprecated if their use does no <ide> to the corresponding man pages which describe how the system call works. <ide> Most Unix system calls have Windows analogues. Still, behavior differences may <ide> be unavoidable. <ide> <del>[Semantic Versioning]: https://semver.org/ <ide> [V8 JavaScript engine]: https://v8.dev/ <add>[semantic versioning]: https://semver.org/ <ide> [the contributing guide]: https://github.com/nodejs/node/blob/HEAD/CONTRIBUTING.md <ide> [the issue tracker]: https://github.com/nodejs/node/issues/new <ide> [warning]: process.md#event-warning
2
Python
Python
fix some bare except statements
34434c5f44ed19e6a8e70996782f9839d6659e1d
<ide><path>glances/exports/glances_cassandra.py <ide> def init(self): <ide> # Table <ide> try: <ide> session.execute("CREATE TABLE %s (plugin text, time timeuuid, stat map<text,float>, PRIMARY KEY (plugin, time)) WITH CLUSTERING ORDER BY (time DESC)" % self.table) <del> except: <add> except Exception: <ide> logger.debug("Cassandra table %s already exist" % self.table) <ide> <ide> return cluster, session <ide><path>glances/folder_list.py <ide> def __set_folder_list(self, section): <ide> for i in ['careful', 'warning', 'critical']: <ide> try: <ide> value[i] = self.config.get_value(section, key + i) <del> except: <add> except Exception: <ide> value[i] = None <ide> logger.debug("No {} threshold for folder {}".format(i, value["path"])) <ide> <ide><path>glances/plugins/glances_docker.py <ide> def update(self): <ide> # First time, try to connect to the server <ide> try: <ide> self.docker_client = self.connect() <del> except: <add> except Exception: <ide> docker_tag = False <ide> else: <ide> if self.docker_client is None: <ide><path>glances/plugins/glances_network.py <ide> def update(self): <ide> netstatus = {} <ide> try: <ide> netstatus = psutil.net_if_stats() <del> except: <add> except AttributeError: <ide> pass <ide> <ide> # Previous network interface stats are stored in the network_old variable
4
Javascript
Javascript
improve cross-platform consistency
8b2f96609d289f81dd5f7091da1f9f1a1c40b8bf
<ide><path>client/src/templates/Challenges/components/Hotkeys.js <ide> import { HotKeys, GlobalHotKeys } from 'react-hotkeys'; <ide> import { navigate } from 'gatsby'; <ide> <ide> const keyMap = { <del> EXECUTE_CHALLENGE: 'ctrl+enter', <add> EXECUTE_CHALLENGE: ['ctrl+enter', 'cmd+enter'], <ide> NAVIGATE_PREV: ['ctrl+left', 'cmd+left'], <ide> NAVIGATE_NEXT: ['ctrl+right', 'cmd+right'] <ide> };
1
PHP
PHP
get usages
706d0d6aafee7ac942000cffa55b84ff4b24f82e
<ide><path>src/Illuminate/Broadcasting/BroadcastManager.php <ide> protected function callCustomCreator(array $config) <ide> protected function createPusherDriver(array $config) <ide> { <ide> return new PusherBroadcaster( <del> new Pusher($config['key'], $config['secret'], $config['app_id'], array_get($config, 'options', [])) <add> new Pusher($config['key'], $config['secret'], $config['app_id'], Arr::get($config, 'options', [])) <ide> ); <ide> } <ide> <ide><path>src/Illuminate/Cache/CacheManager.php <ide> protected function createRedisDriver(array $config) <ide> { <ide> $redis = $this->app['redis']; <ide> <del> $connection = Arr::get($config, 'connection', 'default') ?: 'default'; <add> $connection = Arr::get($config, 'connection', 'default'); <ide> <ide> return $this->repository(new RedisStore($redis, $this->getPrefix($config), $connection)); <ide> } <ide><path>src/Illuminate/Support/ViewErrorBag.php <ide> public function hasBag($key = 'default') <ide> */ <ide> public function getBag($key) <ide> { <del> return Arr::get($this->bags, $key, new MessageBag); <add> return Arr::get($this->bags, $key) ?: new MessageBag; <ide> } <ide> <ide> /** <ide> public function __call($method, $parameters) <ide> */ <ide> public function __get($key) <ide> { <del> return Arr::get($this->bags, $key, new MessageBag); <add> return Arr::get($this->bags, $key) ?: new MessageBag; <ide> } <ide> <ide> /**
3
Ruby
Ruby
fix failing test under sqlite3
813e4cc14233d8c87b6b7165592c48998af48072
<ide><path>activerecord/test/cases/migration_test.rb <ide> class MigrationTest < ActiveRecord::TestCase <ide> <ide> def setup <ide> super <del> %w(reminders people_reminders prefix_reminders_suffix).each do |table| <add> %w(reminders people_reminders prefix_reminders_suffix p_things_s).each do |table| <ide> Reminder.connection.drop_table(table) rescue nil <ide> end <ide> Reminder.reset_column_information
1
PHP
PHP
add command to clean batches table
3b87b6f972de4445bed7458c810671f2bbc861cb
<ide><path>src/Illuminate/Bus/BatchRepository.php <ide> public function delete(string $batchId); <ide> * @return mixed <ide> */ <ide> public function transaction(Closure $callback); <add> <add> /** <add> * Prune all of the entries older than the given date. <add> * <add> * @param \DateTimeInterface $before <add> * @return int <add> */ <add> public function prune(\DateTimeInterface $before); <ide> } <ide><path>src/Illuminate/Bus/DatabaseBatchRepository.php <ide> public function transaction(Closure $callback) <ide> }); <ide> } <ide> <add> /** <add> * Prune all of the entries older than the given date. <add> * <add> * @param \DateTimeInterface $before <add> * @return int <add> */ <add> public function prune(\DateTimeInterface $before) <add> { <add> $query = $this->connection->table($this->table) <add> ->where('finished_at', '<', $before); <add> <add> $totalDeleted = 0; <add> <add> do { <add> $deleted = $query->take(1000)->delete(); <add> <add> $totalDeleted += $deleted; <add> } while ($deleted !== 0); <add> <add> return $totalDeleted; <add> } <add> <ide> /** <ide> * Convert the given raw batch to a Batch object. <ide> * <ide><path>src/Illuminate/Foundation/Providers/ArtisanServiceProvider.php <ide> use Illuminate\Queue\Console\ClearCommand as QueueClearCommand; <ide> use Illuminate\Queue\Console\FailedTableCommand; <ide> use Illuminate\Queue\Console\FlushFailedCommand as FlushFailedQueueCommand; <add>use Illuminate\Queue\Console\FlushBatchCommand as FlushBatchQueueCommand; <ide> use Illuminate\Queue\Console\ForgetFailedCommand as ForgetFailedQueueCommand; <ide> use Illuminate\Queue\Console\ListenCommand as QueueListenCommand; <ide> use Illuminate\Queue\Console\ListFailedCommand as ListFailedQueueCommand; <ide> class ArtisanServiceProvider extends ServiceProvider implements DeferrableProvid <ide> 'QueueClear' => 'command.queue.clear', <ide> 'QueueFailed' => 'command.queue.failed', <ide> 'QueueFlush' => 'command.queue.flush', <add> 'QueueFlushBatch' => 'command.queue.flush-batch', <ide> 'QueueForget' => 'command.queue.forget', <ide> 'QueueListen' => 'command.queue.listen', <ide> 'QueueRestart' => 'command.queue.restart', <ide> protected function registerQueueFlushCommand() <ide> }); <ide> } <ide> <add> /** <add> * Register the command. <add> * <add> * @return void <add> */ <add> protected function registerQueueFlushBatchCommand() <add> { <add> $this->app->singleton('command.queue.flush-batch', function () { <add> return new FlushBatchQueueCommand; <add> }); <add> } <add> <ide> /** <ide> * Register the command. <ide> * <ide><path>src/Illuminate/Queue/Console/FlushBatchCommand.php <add><?php <add> <add>namespace Illuminate\Queue\Console; <add> <add>use Carbon\Carbon; <add>use Illuminate\Bus\BatchRepository; <add>use Illuminate\Console\Command; <add> <add>class FlushBatchCommand extends Command <add>{ <add> /** <add> * The console command signature. <add> * <add> * @var string <add> */ <add> protected $signature = 'queue:flush-batch {--hours=24 : The number of hours to retain batch data}'; <add> <add> /** <add> * The console command description. <add> * <add> * @var string <add> */ <add> protected $description = 'Prune stale entries from the batches database'; <add> <add> /** <add> * Execute the console command. <add> * <add> * @return int|null <add> */ <add> public function handle() <add> { <add> $hours = $this->option('hours'); <add> <add> $before = Carbon::now()->subHours($hours); <add> <add> $count = $this->laravel[BatchRepository::class]->prune($before); <add> <add> $this->info("{$count} entries deleted successfully."); <add> } <add>} <ide><path>src/Illuminate/Support/Testing/Fakes/BatchRepositoryFake.php <ide> use Illuminate\Bus\BatchRepository; <ide> use Illuminate\Bus\PendingBatch; <ide> use Illuminate\Bus\UpdatedBatchJobCounts; <add>use Illuminate\Database\Query\Builder; <ide> use Illuminate\Support\Facades\Facade; <ide> use Illuminate\Support\Str; <ide> <ide> public function transaction(Closure $callback) <ide> { <ide> return $callback(); <ide> } <add> <add> /** <add> * Prune all of the entries older than the given date. <add> * <add> * @param \DateTimeInterface $before <add> * @return int <add> */ <add> public function prune(\DateTimeInterface $before) <add> { <add> return 0; <add> } <ide> }
5
Ruby
Ruby
add java_cache env
b331e03c39f247beeee8c6083745d48b35b138f4
<ide><path>Library/Homebrew/extend/ENV/shared.rb <ide> def fortran <ide> set_cpu_flags(flags) <ide> end <ide> <add> def java_cache <add> append "_JAVA_OPTIONS", "-Duser.home=#{HOMEBREW_CACHE}/java_cache" <add> end <add> <ide> # ld64 is a newer linker provided for Xcode 2.5 <ide> # @private <ide> def ld64
1
Javascript
Javascript
fix lint errors
6fec6507ed7d316551ad78975d5037f1138b6f9c
<ide><path>src/renderers/dom/fiber/ReactDOMFiber.js <ide> var DOMRenderer = ReactFiberReconciler({ <ide> parentInstance.appendChild(child); <ide> }, <ide> <del> insertBefore(parentInstance : Instance, child : Instance | TextInstance, beforeChild : Instance | TextInstance) : void { <add> insertBefore( <add> parentInstance : Instance, <add> child : Instance | TextInstance, <add> beforeChild : Instance | TextInstance <add> ) : void { <ide> parentInstance.insertBefore(child, beforeChild); <ide> }, <ide> <ide><path>src/renderers/noop/ReactNoop.js <ide> type TextInstance = { tag: 98, text: string }; <ide> <ide> var instanceCounter = 0; <ide> <del>function recursivelyAppendChildren(flatArray : Array<Instance | TextInstance>, child : HostChildren<Instance | TextInstance>) { <add>function recursivelyAppendChildren( <add> flatArray : Array<Instance | TextInstance>, <add> child : HostChildren<Instance | TextInstance> <add>) { <ide> if (!child) { <ide> return; <ide> } <ide> var NoopRenderer = ReactFiberReconciler({ <ide> parentInstance.children.push(child); <ide> }, <ide> <del> insertBefore(parentInstance : Instance, child : Instance | TextInstance, beforeChild : Instance | TextInstance) : void { <add> insertBefore( <add> parentInstance : Instance, <add> child : Instance | TextInstance, <add> beforeChild : Instance | TextInstance <add> ) : void { <ide> const index = parentInstance.children.indexOf(child); <ide> if (index !== -1) { <ide> parentInstance.children.splice(index, 1); <ide><path>src/renderers/shared/fiber/ReactFiberBeginWork.js <ide> var { <ide> } = require('ReactTypeOfSideEffect'); <ide> var ReactFiberClassComponent = require('ReactFiberClassComponent'); <ide> <del>module.exports = function<T, P, I, TI, C>(config : HostConfig<T, P, I, TI, C>, scheduleUpdate : (fiber: Fiber, priorityLevel : PriorityLevel) => void) { <add>module.exports = function<T, P, I, TI, C>( <add> config : HostConfig<T, P, I, TI, C>, <add> scheduleUpdate : (fiber: Fiber, priorityLevel : PriorityLevel) => void <add>) { <ide> <ide> const { <ide> adoptClassInstance, <ide> module.exports = function<T, P, I, TI, C>(config : HostConfig<T, P, I, TI, C>, s <ide> } <ide> } <ide> <add> var nextChildren; <add> <ide> if (__DEV__) { <ide> ReactCurrentOwner.current = workInProgress; <del> var nextChildren = fn(props); <add> nextChildren = fn(props); <ide> } else { <del> var nextChildren = fn(props); <add> nextChildren = fn(props); <ide> } <ide> reconcileChildren(current, workInProgress, nextChildren); <ide> return workInProgress.child; <ide> module.exports = function<T, P, I, TI, C>(config : HostConfig<T, P, I, TI, C>, s <ide> } <ide> var fn = workInProgress.type; <ide> var props = workInProgress.pendingProps; <add> var value; <ide> <ide> if (__DEV__) { <ide> ReactCurrentOwner.current = workInProgress; <del> var value = fn(props); <add> value = fn(props); <ide> } else { <del> var value = fn(props); <add> value = fn(props); <ide> } <ide> <ide> if (typeof value === 'object' && value && typeof value.render === 'function') {
3
Javascript
Javascript
extract mockwindow, use tohavebeencalledonce
cbedf556416522a0a4b08abd3101e856e59c6a6a
<ide><path>test/BrowserSpecs.js <ide> 'use strict'; <ide> <del>describe('browser', function(){ <add>function MockWindow() { <add> var events = {}; <add> var timeouts = this.timeouts = []; <ide> <del> var browser, fakeWindow, xhr, logs, scripts, removedScripts, setTimeoutQueue, sniffer; <add> this.setTimeout = function(fn) { <add> return timeouts.push(fn) - 1; <add> }; <ide> <del> function fakeSetTimeout(fn) { <del> return setTimeoutQueue.push(fn) - 1; //return position in the queue <del> } <add> this.clearTimeout = function(id) { <add> timeouts[id] = noop; <add> }; <ide> <del> function fakeClearTimeout(deferId) { <del> setTimeoutQueue[deferId] = noop; //replace fn with noop to preserve other deferId indexes <del> } <add> this.setTimeout.flush = function() { <add> var length = timeouts.length; <add> while (length-- > 0) timeouts.shift()(); <add> }; <ide> <del> fakeSetTimeout.flush = function() { <del> var currentTimeoutQueue = setTimeoutQueue; <del> setTimeoutQueue = []; <del> forEach(currentTimeoutQueue, function(fn) { <del> fn(); <add> this.addEventListener = function(name, listener) { <add> if (isUndefined(events[name])) events[name] = []; <add> events[name].push(listener); <add> }; <add> <add> this.attachEvent = function(name, listener) { <add> this.addEventListener(name.substr(2), listener); <add> }; <add> <add> this.removeEventListener = noop; <add> this.detachEvent = noop; <add> <add> this.fire = function(name) { <add> forEach(events[name], function(fn) { <add> fn({type: name}); // type to make jQuery happy <ide> }); <ide> }; <ide> <add> this.location = { <add> href: 'http://server', <add> replace: noop <add> }; <add> <add> this.history = { <add> replaceState: noop, <add> pushState: noop <add> }; <add>} <add> <add>describe('browser', function(){ <add> <add> var browser, fakeWindow, xhr, logs, scripts, removedScripts, sniffer; <ide> <ide> beforeEach(function(){ <del> setTimeoutQueue = []; <ide> scripts = []; <ide> removedScripts = []; <ide> xhr = null; <ide> sniffer = {history: true, hashchange: true}; <del> <del> // mock window, extract ? <del> fakeWindow = { <del> events: {}, <del> fire: function(name) { <del> forEach(this.events[name], function(listener) { <del> listener.apply(null, arguments); <del> }); <del> }, <del> addEventListener: function(name, listener) { <del> if (isUndefined(this.events[name])) { <del> this.events[name] = []; <del> } <del> this.events[name].push(listener); <del> }, <del> attachEvent: function(name, listener) { <del> if (isUndefined(this.events[name])) { <del> this.events[name] = []; <del> } <del> this.events[name].push(listener); <del> }, <del> removeEventListener: noop, <del> detachEvent: noop, <del> location: {href: 'http://server', replace: noop}, <del> history: {replaceState: noop, pushState: noop}, <del> setTimeout: fakeSetTimeout, <del> clearTimeout: fakeClearTimeout <del> }; <add> fakeWindow = new MockWindow(); <ide> <ide> var fakeBody = [{appendChild: function(node){scripts.push(node);}, <ide> removeChild: function(node){removedScripts.push(node);}}]; <ide> describe('browser', function(){ <ide> <ide> describe('defer', function() { <ide> it('should execute fn asynchroniously via setTimeout', function() { <del> var counter = 0; <del> browser.defer(function() {counter++;}); <del> expect(counter).toBe(0); <add> var callback = jasmine.createSpy('deferred'); <ide> <del> fakeSetTimeout.flush(); <del> expect(counter).toBe(1); <add> browser.defer(callback); <add> expect(callback).not.toHaveBeenCalled(); <add> <add> fakeWindow.setTimeout.flush(); <add> expect(callback).toHaveBeenCalledOnce(); <ide> }); <ide> <ide> <ide> it('should update outstandingRequests counter', function() { <del> var callback = jasmine.createSpy('callback'); <add> var callback = jasmine.createSpy('deferred'); <add> <ide> browser.defer(callback); <ide> expect(callback).not.toHaveBeenCalled(); <ide> <del> fakeSetTimeout.flush(); <del> expect(callback).toHaveBeenCalled(); <add> fakeWindow.setTimeout.flush(); <add> expect(callback).toHaveBeenCalledOnce(); <ide> }); <ide> <ide> <ide> describe('browser', function(){ <ide> expect(log).toEqual([]); <ide> browser.defer.cancel(deferId1); <ide> browser.defer.cancel(deferId3); <del> fakeSetTimeout.flush(); <add> fakeWindow.setTimeout.flush(); <ide> expect(log).toEqual(['ok']); <ide> }); <ide> }); <ide> describe('browser', function(){ <ide> browser.addPollFn(function(){log+='a';}); <ide> browser.addPollFn(function(){log+='b';}); <ide> expect(log).toEqual(''); <del> fakeSetTimeout.flush(); <add> fakeWindow.setTimeout.flush(); <ide> expect(log).toEqual('ab'); <del> fakeSetTimeout.flush(); <add> fakeWindow.setTimeout.flush(); <ide> expect(log).toEqual('abab'); <ide> }); <ide> <ide> it('should startPoller', function(){ <del> expect(setTimeoutQueue.length).toEqual(0); <add> expect(fakeWindow.timeouts.length).toEqual(0); <ide> <ide> browser.addPollFn(function(){}); <del> expect(setTimeoutQueue.length).toEqual(1); <add> expect(fakeWindow.timeouts.length).toEqual(1); <ide> <ide> //should remain 1 as it is the check fn <ide> browser.addPollFn(function(){}); <del> expect(setTimeoutQueue.length).toEqual(1); <add> expect(fakeWindow.timeouts.length).toEqual(1); <ide> }); <ide> <ide> it('should return fn that was passed into addPollFn', function() { <ide> describe('browser', function(){ <ide> sniffer.history = true; <ide> browser.url('http://new.org'); <ide> <del> expect(pushState).toHaveBeenCalled(); <add> expect(pushState).toHaveBeenCalledOnce(); <ide> expect(pushState.argsForCall[0][2]).toEqual('http://new.org'); <ide> <ide> expect(replaceState).not.toHaveBeenCalled(); <ide> describe('browser', function(){ <ide> sniffer.history = true; <ide> browser.url('http://new.org', true); <ide> <del> expect(replaceState).toHaveBeenCalled(); <add> expect(replaceState).toHaveBeenCalledOnce(); <ide> expect(replaceState.argsForCall[0][2]).toEqual('http://new.org'); <ide> <ide> expect(pushState).not.toHaveBeenCalled(); <ide> describe('browser', function(){ <ide> expect(callback).toHaveBeenCalledWith('http://server/new'); <ide> <ide> fakeWindow.fire('hashchange'); <del> fakeSetTimeout.flush(); <del> expect(callback.callCount).toBe(1); <add> fakeWindow.setTimeout.flush(); <add> expect(callback).toHaveBeenCalledOnce(); <ide> }); <ide> <ide> it('should forward only popstate event when both history and hashchange supported', function() { <ide> describe('browser', function(){ <ide> expect(callback).toHaveBeenCalledWith('http://server/new'); <ide> <ide> fakeWindow.fire('hashchange'); <del> fakeSetTimeout.flush(); <del> expect(callback.callCount).toBe(1); <add> fakeWindow.setTimeout.flush(); <add> expect(callback).toHaveBeenCalledOnce(); <ide> }); <ide> <ide> it('should forward hashchange event with new url when only hashchange supported', function() { <ide> describe('browser', function(){ <ide> expect(callback).toHaveBeenCalledWith('http://server/new'); <ide> <ide> fakeWindow.fire('popstate'); <del> fakeSetTimeout.flush(); <del> expect(callback.callCount).toBe(1); <add> fakeWindow.setTimeout.flush(); <add> expect(callback).toHaveBeenCalledOnce(); <ide> }); <ide> <ide> it('should use polling when neither history nor hashchange supported', function() { <ide> describe('browser', function(){ <ide> browser.onUrlChange(callback); <ide> <ide> fakeWindow.location.href = 'http://server.new'; <del> fakeSetTimeout.flush(); <add> fakeWindow.setTimeout.flush(); <ide> expect(callback).toHaveBeenCalledWith('http://server.new'); <ide> <ide> fakeWindow.fire('popstate'); <ide> fakeWindow.fire('hashchange'); <del> expect(callback.callCount).toBe(1); <add> expect(callback).toHaveBeenCalledOnce(); <ide> }); <ide> <ide> it('should not fire urlChange if changed by browser.url method (polling)', function() { <ide> describe('browser', function(){ <ide> browser.onUrlChange(callback); <ide> browser.url('http://new.com'); <ide> <del> fakeSetTimeout.flush(); <add> fakeWindow.setTimeout.flush(); <ide> expect(callback).not.toHaveBeenCalled(); <ide> }); <ide>
1
Python
Python
set version to v2.1.7.dev1
97c51ef93bbad7bb63be3c5280ce2e48af6db513
<ide><path>spacy/about.py <ide> # fmt: off <ide> <ide> __title__ = "spacy" <del>__version__ = "2.1.7.dev0" <add>__version__ = "2.1.7.dev1" <ide> __summary__ = "Industrial-strength Natural Language Processing (NLP) with Python and Cython" <ide> __uri__ = "https://spacy.io" <ide> __author__ = "Explosion AI"
1
Ruby
Ruby
update variable name and msg string per comments
77c242548eab3df72f4905ffb29b896073ee11d2
<ide><path>Library/Homebrew/cmd/update-report.rb <ide> def update_report <ide> HOMEBREW_REPOSITORY.cd do <ide> analytics_message_displayed = <ide> Utils.popen_read("git", "config", "--local", "--get", "homebrew.analyticsmessage").chuzzle <del> cask_analytics_message_displayed = <add> caskanalyticsmessage = <ide> Utils.popen_read("git", "config", "--local", "--get", "homebrew.cask.analyticsmessage").chuzzle <ide> analytics_disabled = <ide> Utils.popen_read("git", "config", "--local", "--get", "homebrew.analyticsdisabled").chuzzle <ide> if analytics_message_displayed != "true" && <del> cask_analytics_message_displayed != "true" && <add> caskanalyticsmessage != "true" && <ide> analytics_disabled != "true" && <ide> !ENV["HOMEBREW_NO_ANALYTICS"] && <ide> !ENV["HOMEBREW_NO_ANALYTICS_MESSAGE_OUTPUT"] <ide> def update_report <ide> print "\a" <ide> <ide> # Use an extra newline and bold to avoid this being missed. <del> ohai "Homebrew and Homebrew Cask have enabled anonymous aggregate user behaviour analytics." <add> ohai "Homebrew (and Cask) have enabled anonymous aggregate user behaviour analytics." <ide> puts <<~EOS <ide> #{Tty.bold}Read the analytics documentation (and how to opt-out) here: <ide> #{Formatter.url("https://docs.brew.sh/Analytics")}#{Tty.reset}
1
Javascript
Javascript
update skeleton in existing loop
e80b396b90af872ff91e6f609b7c340dea111f97
<ide><path>src/renderers/WebGLRenderer.js <ide> THREE.WebGLRenderer = function ( parameters ) { <ide> <ide> if ( camera.parent === undefined ) camera.updateMatrixWorld(); <ide> <del> // update Skeleton objects <del> <del> scene.traverse( function ( object ) { <del> <del> if ( object instanceof THREE.SkinnedMesh ) { <del> <del> object.skeleton.update(); <del> <del> } <del> <del> } ); <del> <ide> camera.matrixWorldInverse.getInverse( camera.matrixWorld ); <ide> <ide> _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); <ide> THREE.WebGLRenderer = function ( parameters ) { <ide> <ide> } else { <ide> <add> // update Skeleton objects <add> if ( object instanceof THREE.SkinnedMesh ) { <add> <add> object.skeleton.update(); <add> <add> } <add> <ide> objects.init( object ); <ide> <ide> if ( object instanceof THREE.Light ) {
1
Text
Text
add mention of canary vs stable
6c1389b69e83794fc96c405126c9366d99c09055
<ide><path>README.md <ide> Next.js is a minimalistic framework for server-rendered React applications. <ide> <ide> --- <ide> <add>**The below readme is the documentation for the `canary` (prerelease) branch. To view the documentation for the latest stable Next.js version visit [nextjs.org/docs](https://nextjs.org/docs)** <add> <add>--- <add> <ide> <!-- START doctoc generated TOC please keep comment here to allow auto update --> <ide> <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --> <ide> <!-- https://github.com/thlorenz/doctoc -->
1
Ruby
Ruby
make average compatible accross ruby versions
d237c7c72ccfd87302983669f83c8c90d2aec82e
<ide><path>activerecord/lib/active_record/relation/calculations.rb <ide> def type_cast_calculated_value(value, type, operation = nil) <ide> case operation <ide> when "count" then value.to_i <ide> when "sum" then type.deserialize(value || 0) <del> when "average" then value.respond_to?(:to_d) ? value.to_d : value <add> when "average" then value&.respond_to?(:to_d) ? value.to_d : value <ide> else type.deserialize(value) <ide> end <ide> end
1
Javascript
Javascript
simplify test runner
98ba33e7a3305b898f0262180706df5cb8d2e41c
<ide><path>curriculum/test/test-challenges.js <ide> const DeepFreeze = o => { <ide> return o; <ide> }; <ide> <del>function isPromise(value) { <del> return ( <del> value && <del> typeof value.subscribe !== 'function' && <del> typeof value.then === 'function' <del> ); <del>} <del> <ide> function transformSass(solution) { <ide> const fragment = JSDOM.fragment(`<div>${solution}</div>`); <ide> const styleTags = fragment.querySelectorAll('style[type="text/sass"]'); <ide> async function runTestInBrowser(code, testString) { <ide> }; <ide> /* eslint-enable no-unused-vars */ <ide> <del> const isPromise = value => <del> value && <del> typeof value.subscribe !== 'function' && <del> typeof value.then === 'function'; <del> <ide> try { <ide> // eslint-disable-next-line no-eval <ide> const test = eval(testString); <ide> if (typeof test === 'function') { <del> const __result = test(() => code); <del> if (isPromise(__result)) { <del> await __result; <del> } <add> await test(() => code); <ide> } <ide> } catch (e) { <ide> return { <ide> async function runTestInJsdom(dom, testString, scriptString = '') { <ide> dom.window.assert = assert; <ide> dom.window.DeepEqual = DeepEqual; <ide> dom.window.DeepFreeze = DeepFreeze; <del> dom.window.isPromise = isPromise; <ide> <ide> dom.window.__test = testString; <ide> scriptString += `; <ide> async function runTestInJsdom(dom, testString, scriptString = '') { <ide> try { <ide> const testResult = eval(__test); <ide> if (typeof testResult === 'function') { <del> const __result = testResult(() => code); <del> if (isPromise(__result)) { <del> await __result; <del> } <add> await testResult(() => code); <ide> } <ide> }catch (e) { <ide> window.__error = e;
1
Text
Text
remove comma and correct the sentence
298159c73abd0c085f07f4ad9ca1d080f5dcc55c
<ide><path>curriculum/challenges/english/06-quality-assurance/quality-assurance-and-testing-with-chai/assert-deep-equality-with-.deepequal-and-.notdeepequal.md <ide> dashedName: assert-deep-equality-with--deepequal-and--notdeepequal <ide> <ide> # --description-- <ide> <del>As a reminder, this project is being built upon the following starter project on ,<a href="https://replit.com/github/freeCodeCamp/boilerplate-mochachai" target="_blank" rel="noopener noreferrer nofollow">Replit</a> or cloned from <a href="https://github.com/freeCodeCamp/boilerplate-mochachai/" target="_blank" rel="noopener noreferrer nofollow">GitHub</a>. <add>As a reminder, this project is being built upon the following starter project on <a href="https://replit.com/github/freeCodeCamp/boilerplate-mochachai" target="_blank" rel="noopener noreferrer nofollow">Replit</a> or cloned from <a href="https://github.com/freeCodeCamp/boilerplate-mochachai/" target="_blank" rel="noopener noreferrer nofollow">GitHub</a>. <ide> <ide> `deepEqual()` asserts that two objects are deep equal. <ide> <ide><path>curriculum/challenges/english/10-coding-interview-prep/rosetta-code/discordian-date.md <ide> Holidays: `'Chaoflux', 'Discoflux', 'Confuflux', 'Bureflux', 'Afflux'`. <ide> <ide> Convert a given date from the Gregorian calendar to the Discordian calendar. <ide> <del>Note that in the Discordian calendar (Chaos 1, 3188 YOLD) is (January 1, 2022), in the Gregorian calendar. <add>Note that the day Chaos 1, 3188 YOLD in the Discordian calendar is the day January 1, 2022 in the Gregorian calendar. <ide> <ide> # --hints-- <ide>
2
Text
Text
update changelog [ci skip]
2d4cfb28408f53daea11f45fb5e0aebdce8963d3
<ide><path>railties/CHANGELOG.md <add>* Configure `secrets.yml` and `database.yml` to read configuration <add> from the system environment by default for production. <add> <add> *José Valim* <add> <ide> * `config.assets.raise_runtime_errors` is set to true by default <ide> <ide> This option has been introduced in
1
Javascript
Javascript
remove legacy warning in keyframetrack
c184493e3cf4fb22f50ed330a6456fd705052def
<ide><path>src/animation/KeyframeTrack.js <ide> Object.assign( THREE.KeyframeTrack, { <ide> <ide> if ( json.times === undefined ) { <ide> <del> console.warn( "legacy JSON format detected, converting" ); <del> <ide> var times = [], values = []; <ide> <ide> THREE.AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
1
Javascript
Javascript
fix shadowing of apolloclient
d166840e5a2d10ec10dc40105f79f2de80a30c42
<ide><path>examples/with-apollo/lib/apollo.js <ide> import { InMemoryCache } from 'apollo-cache-inmemory' <ide> import { HttpLink } from 'apollo-link-http' <ide> import fetch from 'isomorphic-unfetch' <ide> <del>let apolloClient = null <add>let globalApolloClient = null <ide> <ide> /** <ide> * Creates and provides the apolloContext <ide> export function withApollo(PageComponent, { ssr = true } = {}) { <ide> <ide> // Initialize ApolloClient, add it to the ctx object so <ide> // we can use it in `PageComponent.getInitialProp`. <del> const apolloClient = (ctx.apolloClient = initApolloClient()) <add> globalApolloClient = ctx.apolloClient = initApolloClient() <ide> <ide> // Run wrapped getInitialProps methods <ide> let pageProps = {} <ide> export function withApollo(PageComponent, { ssr = true } = {}) { <ide> <AppTree <ide> pageProps={{ <ide> ...pageProps, <del> apolloClient, <add> globalApolloClient, <ide> }} <ide> /> <ide> ) <ide> export function withApollo(PageComponent, { ssr = true } = {}) { <ide> } <ide> <ide> // Extract query data from the Apollo store <del> const apolloState = apolloClient.cache.extract() <add> const apolloState = globalApolloClient.cache.extract() <ide> <ide> return { <ide> ...pageProps, <ide> function initApolloClient(initialState) { <ide> } <ide> <ide> // Reuse client on the client-side <del> if (!apolloClient) { <del> apolloClient = createApolloClient(initialState) <add> if (!globalApolloClient) { <add> globalApolloClient = createApolloClient(initialState) <ide> } <ide> <del> return apolloClient <add> return globalApolloClient <ide> } <ide> <ide> /**
1
PHP
PHP
move route hook into a separate interface
bb152bdb673a77ee9193eb8f34a1616e02ad90b4
<ide><path>src/Console/CommandRunner.php <ide> use Cake\Console\Exception\MissingOptionException; <ide> use Cake\Console\Exception\StopException; <ide> use Cake\Core\ConsoleApplicationInterface; <del>use Cake\Core\HttpApplicationInterface; <ide> use Cake\Core\PluginApplicationInterface; <ide> use Cake\Event\EventDispatcherInterface; <ide> use Cake\Event\EventDispatcherTrait; <ide> use Cake\Event\EventManager; <ide> use Cake\Event\EventManagerInterface; <ide> use Cake\Routing\Router; <add>use Cake\Routing\RoutingApplicationInterface; <ide> use Cake\Utility\Inflector; <ide> use InvalidArgumentException; <ide> use RuntimeException; <ide> protected function createShell(string $className, ConsoleIo $io) <ide> */ <ide> protected function loadRoutes(): void <ide> { <add> if (!($this->app instanceof RoutingApplicationInterface)) { <add> return; <add> } <ide> $builder = Router::createRouteBuilder('/'); <ide> <del> if ($this->app instanceof HttpApplicationInterface) { <del> $this->app->routes($builder); <del> } <add> $this->app->routes($builder); <ide> if ($this->app instanceof PluginApplicationInterface) { <ide> $this->app->pluginRoutes($builder); <ide> } <ide><path>src/Core/HttpApplicationInterface.php <ide> interface HttpApplicationInterface extends RequestHandlerInterface <ide> * @return void <ide> */ <ide> public function bootstrap(): void; <del> <del> /** <del> * Define the routes for an application. <del> * <del> * Use the provided RouteBuilder to define an application's routing. <del> * <del> * @param \Cake\Routing\RouteBuilder $routes A route builder to add routes into. <del> * @return void <del> */ <del> public function routes(RouteBuilder $routes): void; <del> <ide> /** <ide> * Define the HTTP middleware layers for an application. <ide> * <ide><path>src/Http/BaseApplication.php <ide> use Cake\Event\EventManagerInterface; <ide> use Cake\Routing\RouteBuilder; <ide> use Cake\Routing\Router; <add>use Cake\Routing\RoutingApplicationInterface; <ide> use Psr\Http\Message\ResponseInterface; <ide> use Psr\Http\Message\ServerRequestInterface; <ide> <ide> /** <del> * Base class for application classes. <add> * Base class for full-stack applications <add> * <add> * This class serves as a base class for applications that are using <add> * CakePHP as a full stack framework. If you are only using the Http or Console libraries <add> * you should implement the relevant interfaces directly. <ide> * <ide> * The application class is responsible for bootstrapping the application, <ide> * and ensuring that middleware is attached. It is also invoked as the last piece <ide> abstract class BaseApplication implements <ide> ConsoleApplicationInterface, <ide> HttpApplicationInterface, <del> PluginApplicationInterface <add> PluginApplicationInterface, <add> RoutingApplicationInterface <ide> { <ide> use EventDispatcherTrait; <ide> <ide><path>src/Routing/Middleware/RoutingMiddleware.php <ide> namespace Cake\Routing\Middleware; <ide> <ide> use Cake\Cache\Cache; <del>use Cake\Core\HttpApplicationInterface; <ide> use Cake\Core\PluginApplicationInterface; <ide> use Cake\Http\MiddlewareQueue; <ide> use Cake\Http\Runner; <ide> use Cake\Routing\Exception\RedirectException; <ide> use Cake\Routing\RouteCollection; <ide> use Cake\Routing\Router; <add>use Cake\Routing\RoutingApplicationInterface; <ide> use Psr\Http\Message\ResponseInterface; <ide> use Psr\Http\Message\ServerRequestInterface; <ide> use Psr\Http\Server\MiddlewareInterface; <ide> class RoutingMiddleware implements MiddlewareInterface <ide> /** <ide> * The application that will have its routing hook invoked. <ide> * <del> * @var \Cake\Core\HttpApplicationInterface <add> * @var \Cake\Core\RoutingApplicationInterface <ide> */ <ide> protected $app; <ide> <ide> class RoutingMiddleware implements MiddlewareInterface <ide> /** <ide> * Constructor <ide> * <del> * @param \Cake\Core\HttpApplicationInterface $app The application instance that routes are defined on. <add> * @param \Cake\Core\RoutingApplicationInterface $app The application instance that routes are defined on. <ide> * @param string|null $cacheConfig The cache config name to use or null to disable routes cache <ide> */ <del> public function __construct(HttpApplicationInterface $app, ?string $cacheConfig = null) <add> public function __construct(RoutingApplicationInterface $app, ?string $cacheConfig = null) <ide> { <ide> $this->app = $app; <ide> $this->cacheConfig = $cacheConfig; <ide><path>src/Routing/RoutingApplicationInterface.php <add><?php <add>declare(strict_types=1); <add> <add>/** <add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * <add> * Licensed under The MIT License <add> * For full copyright and license information, please see the LICENSE.txt <add> * Redistributions of files must retain the above copyright notice. <add> * <add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * @link https://cakephp.org CakePHP(tm) Project <add> * @since 4.0.0 <add> * @license https://opensource.org/licenses/mit-license.php MIT License <add> */ <add>namespace Cake\Routing; <add> <add>/** <add> * Interface for applications that use routing. <add> */ <add>interface RoutingApplicationInterface <add>{ <add> /** <add> * Define the routes for an application. <add> * <add> * Use the provided RouteBuilder to define an application's routing. <add> * <add> * @param \Cake\Routing\RouteBuilder $routes A route builder to add routes into. <add> * @return void <add> */ <add> public function routes(RouteBuilder $routes): void; <add>} <ide><path>src/TestSuite/MiddlewareDispatcher.php <ide> protected function resolveRoute(array $url): string <ide> } <ide> $builder = Router::createRouteBuilder('/'); <ide> <del> if ($this->app instanceof HttpApplicationInterface) { <add> if ($this->app instanceof RoutingApplicationInterface) { <ide> $this->app->routes($builder); <ide> } <ide> if ($this->app instanceof PluginApplicationInterface) {
6
Javascript
Javascript
add note about view rerender to didinsertelement
908981282ed8a3ad9ea388b51dd60cada92cdd47
<ide><path>packages/ember-views/lib/views/view.js <ide> Ember.View = Ember.CoreView.extend( <ide> willInsertElement: Ember.K, <ide> <ide> /** <del> Called when the element of the view has been inserted into the DOM. <del> Override this function to do any set up that requires an element in the <del> document body. <add> Called when the element of the view has been inserted into the DOM <add> or after the view was re-rendered. Override this function to do any <add> set up that requires an element in the document body. <ide> <ide> @event didInsertElement <ide> */
1
Text
Text
update parameter type for fs.chmod()
283e7a43dc401da1437dada74a6fb4321dd5555e
<ide><path>doc/api/fs.md <ide> changes: <ide> --> <ide> <ide> * `path` {string|Buffer|URL} <del>* `mode` {integer} <add>* `mode` {string|integer} <ide> * `callback` {Function} <ide> * `err` {Error} <ide> <ide> changes: <ide> --> <ide> <ide> * `path` {string|Buffer|URL} <del>* `mode` {integer} <add>* `mode` {string|integer} <ide> <ide> For detailed information, see the documentation of the asynchronous version of <ide> this API: [`fs.chmod()`][].
1
PHP
PHP
fix drop_foreign sql grammar for mysql
d43157b61f8e9f035403f3a220123f7fea007589
<ide><path>laravel/database/schema/grammars/mysql.php <ide> protected function drop_key(Table $table, Fluent $command) <ide> */ <ide> public function drop_foreign(Table $table, Fluent $command) <ide> { <del> return $this->drop_constraint($table, $command); <add> return "ALTER TABLE ".$this->wrap($table)." DROP FOREIGN KEY ".$command->name; <ide> } <ide> <ide> /**
1
Ruby
Ruby
remove basic authentication support for github
09c3058618a5f938f5d648a5dc510bd3f770cf3f
<ide><path>Library/Homebrew/dev-cmd/pr-pull.rb <ide> def changed_formulae(tap, original_commit) <ide> end <ide> <ide> def download_artifact(url, dir, pr) <del> token, username = GitHub.api_credentials <del> case GitHub.api_credentials_type <del> when :env_username_password, :keychain_username_password <del> curl_args = ["--user", "#{username}:#{token}"] <del> when :env_token <del> curl_args = ["--header", "Authorization: token #{token}"] <del> when :none <del> raise "Credentials must be set to access the Artifacts API" <del> end <add> raise "Credentials must be set to access the Artifacts API" if GitHub.api_credentials_type == :none <add> <add> token = GitHub.api_credentials <add> curl_args = ["--header", "Authorization: token #{token}"] <ide> <ide> # Download the artifact as a zip file and unpack it into `dir`. This is <ide> # preferred over system `curl` and `tar` as this leverages the Homebrew <ide><path>Library/Homebrew/utils/github.rb <ide> def env_username_password <ide> odisabled "the GitHub API with HOMEBREW_GITHUB_API_PASSWORD", "HOMEBREW_GITHUB_API_TOKEN" <ide> end <ide> <add> # Gets the password field from `git-credential-osxkeychain` for github.com, <add> # but only if that password looks like a GitHub Personal Access Token. <add> sig { returns(T.nilable(String)) } <ide> def keychain_username_password <ide> github_credentials = Utils.popen(["git", "credential-osxkeychain", "get"], "w+") do |pipe| <ide> pipe.write "protocol=https\nhost=github.com\n" <ide> def keychain_username_password <ide> # https://github.com/Homebrew/brew/issues/6862#issuecomment-572610344 <ide> return unless /^[a-f0-9]{40}$/i.match?(github_password) <ide> <del> [github_password, github_username] <add> github_password <ide> rescue Errno::EPIPE <ide> # The above invocation via `Utils.popen` can fail, causing the pipe to be <ide> # prematurely closed (before we can write to it) and thus resulting in a <ide> def open_api(url, data: nil, data_binary_path: nil, request_method: nil, scopes: <ide> args = ["--header", "Accept: application/vnd.github.v3+json", "--write-out", "\n%\{http_code}"] <ide> args += ["--header", "Accept: application/vnd.github.antiope-preview+json"] <ide> <del> token, username = api_credentials <del> case api_credentials_type <del> when :env_username_password, :keychain_username_password <del> args += ["--user", "#{username}:#{token}"] <del> when :env_token <del> args += ["--header", "Authorization: token #{token}"] <del> end <add> token = api_credentials <add> args += ["--header", "Authorization: token #{token}"] unless api_credentials_type == :none <ide> <ide> data_tmpfile = nil <ide> if data <ide> def create_fork(repo) <ide> def check_fork_exists(repo) <ide> _, reponame = repo.split("/") <ide> <del> case api_credentials_type <del> when :env_username_password, :keychain_username_password <del> _, username = api_credentials <del> when :env_token <del> username = open_api(url_to("user")) { |json| json["login"] } <del> end <add> username = open_api(url_to("user")) { |json| json["login"] } <ide> json = open_api(url_to("repos", username, reponame)) <ide> <ide> return false if json["message"] == "Not Found"
2
Java
Java
remove unused imports in tests
a30cf3058eee3737074a35f14408f9ec28feea1a
<ide><path>spring-test/src/main/java/org/springframework/test/web/servlet/setup/DefaultMockMvcBuilder.java <ide> /* <del> * Copyright 2002-2013 the original author or authors. <add> * Copyright 2002-2014 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> <ide> package org.springframework.test.web.servlet.setup; <ide> <del>import java.util.ArrayList; <del>import java.util.List; <del> <del>import javax.servlet.Filter; <del>import javax.servlet.ServletContext; <del> <del>import org.springframework.mock.web.MockServletConfig; <del>import org.springframework.test.web.servlet.MockMvc; <del>import org.springframework.test.web.servlet.MockMvcBuilder; <del>import org.springframework.test.web.servlet.MockMvcBuilderSupport; <del>import org.springframework.test.web.servlet.RequestBuilder; <del>import org.springframework.test.web.servlet.ResultHandler; <del>import org.springframework.test.web.servlet.ResultMatcher; <ide> import org.springframework.util.Assert; <ide> import org.springframework.web.context.WebApplicationContext; <del>import org.springframework.web.servlet.DispatcherServlet; <ide> <ide> /** <ide> * An concrete implementation of {@link AbstractMockMvcBuilder} that simply <ide><path>spring-test/src/test/java/org/springframework/test/web/servlet/setup/StandaloneMockMvcBuilderTests.java <ide> /* <del> * Copyright 2002-2013 the original author or authors. <add> * Copyright 2002-2014 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> <ide> import org.junit.Test; <ide> import org.springframework.mock.web.test.MockHttpServletRequest; <del>import org.springframework.mock.web.test.MockServletContext; <ide> import org.springframework.stereotype.Controller; <ide> import org.springframework.web.bind.annotation.RequestMapping; <ide> import org.springframework.web.context.WebApplicationContext;
2
Ruby
Ruby
fix args error
7e47d1be94d02522057554cca73d77a41c3395ce
<ide><path>Library/Homebrew/cmd/log.rb <ide> def log <ide> ENV["PATH"] = ENV["HOMEBREW_PATH"] <ide> <ide> if args.no_named? <del> git_log HOMEBREW_REPOSITORY <add> git_log HOMEBREW_REPOSITORY, args: args <ide> else <ide> path = Formulary.path(args.named.first) <ide> tap = Tap.from_path(path)
1
Javascript
Javascript
remove last change
516b6ab872060be003bc9f01733d8e2414a3fc55
<ide><path>src/main-process/atom-window.js <ide> const getAppName = require('../get-app-name'); <ide> const path = require('path'); <ide> const url = require('url'); <ide> const { EventEmitter } = require('events'); <del>const { compose } = require('@hyurl/structured-clone'); <ide> const StartupTime = require('../startup-time'); <ide> <ide> const ICON_PATH = path.resolve(__dirname, '..', '..', 'resources', 'atom.png'); <ide> module.exports = class AtomWindow extends EventEmitter { <ide> sendCommandToBrowserWindow(command, ...args) { <ide> const action = <ide> args[0] && args[0].contextCommand ? 'context-command' : 'command'; <del> this.browserWindow.webContents.send(action, command, compose(...args)); <add> this.browserWindow.webContents.send(action, command, ...args); <ide> } <ide> <ide> getDimensions() {
1
Mixed
Javascript
expose buildid to custom webpack configs
ddd30787efbf699beb873f07df5333f01c58ba83
<ide><path>readme.md <ide> In order to extend our usage of `webpack`, you can define a function that extend <ide> // (But you could use ES2015 features supported by your Node.js version) <ide> <ide> module.exports = { <del> webpack: (config, { dev }) => { <add> webpack: (config, { buildId, dev }) => { <ide> // Perform customizations to webpack config <ide> <ide> // Important: return the modified config <ide><path>server/build/webpack.js <ide> export default async function createCompiler (dir, { buildId, dev = false, quiet <ide> <ide> if (config.webpack) { <ide> console.log(`> Using "webpack" config function defined in ${config.configOrigin}.`) <del> webpackConfig = await config.webpack(webpackConfig, { dev }) <add> webpackConfig = await config.webpack(webpackConfig, { buildId, dev }) <ide> } <ide> return webpack(webpackConfig) <ide> }
2
PHP
PHP
remove deprecated method
fcad5ec272c9406e2afa9f1fde25271920ca6e24
<ide><path>src/Illuminate/Collections/Traits/EnumeratesValues.php <ide> public function uniqueStrict($key = null) <ide> return $this->unique($key, true); <ide> } <ide> <del> /** <del> * Take items in the collection until the given condition is met. <del> * <del> * This is an alias to the "takeUntil" method. <del> * <del> * @param mixed $value <del> * @return static <del> * <del> * @deprecated Use the "takeUntil" method directly. <del> */ <del> public function until($value) <del> { <del> return $this->takeUntil($value); <del> } <del> <ide> /** <ide> * Collect the values into a collection. <ide> *
1
Mixed
Go
update secret command
d87c91e39ff0d3defb5b98fdc9275c8c0bfc987e
<ide><path>cli/command/secret/create.go <ide> func newSecretCreateCommand(dockerCli *command.DockerCli) *cobra.Command { <ide> } <ide> <ide> cmd := &cobra.Command{ <del> Use: "create [name]", <add> Use: "create [OPTIONS] SECRET [SECRET...]", <ide> Short: "Create a secret using stdin as content", <ide> Args: cli.RequiresMinArgs(1), <ide> RunE: func(cmd *cobra.Command, args []string) error { <ide><path>cli/command/secret/inspect.go <ide> type inspectOptions struct { <ide> func newSecretInspectCommand(dockerCli *command.DockerCli) *cobra.Command { <ide> opts := inspectOptions{} <ide> cmd := &cobra.Command{ <del> Use: "inspect SECRET [SECRET]", <del> Short: "Inspect a secret", <add> Use: "inspect [OPTIONS] SECRET [SECRET...]", <add> Short: "Display detailed information on one or more secrets", <ide> Args: cli.RequiresMinArgs(1), <ide> RunE: func(cmd *cobra.Command, args []string) error { <ide> opts.names = args <ide><path>cli/command/secret/ls.go <ide> func newSecretListCommand(dockerCli *command.DockerCli) *cobra.Command { <ide> opts := listOptions{} <ide> <ide> cmd := &cobra.Command{ <del> Use: "ls", <add> Use: "ls [OPTIONS]", <ide> Short: "List secrets", <ide> Args: cli.NoArgs, <ide> RunE: func(cmd *cobra.Command, args []string) error { <ide><path>cli/command/secret/remove.go <ide> type removeOptions struct { <ide> <ide> func newSecretRemoveCommand(dockerCli *command.DockerCli) *cobra.Command { <ide> return &cobra.Command{ <del> Use: "rm SECRET [SECRET]", <del> Short: "Remove a secret", <add> Use: "rm SECRET [SECRET...]", <add> Short: "Remove one or more secrets", <ide> Args: cli.RequiresMinArgs(1), <ide> RunE: func(cmd *cobra.Command, args []string) error { <ide> opts := removeOptions{ <ide><path>docs/reference/commandline/secret_create.md <ide> keywords: ["secret, create"] <ide> # secret create <ide> <ide> ```Markdown <del>Usage: docker secret create [NAME] <add>Usage: docker secret create [OPTIONS] SECRET <ide> <ide> Create a secret using stdin as content <ide> Options: <ide> $ docker secret inspect secret.json <ide> * [secret inspect](secret_inspect.md) <ide> * [secret ls](secret_ls.md) <ide> * [secret rm](secret_rm.md) <del> <del><style>table tr > td:first-child { white-space: nowrap;}</style>
5
PHP
PHP
fix missing arguments in development errors
219db9d0c2a1e1362b4ce7d8e59a521d332e1c19
<ide><path>src/Error/Renderer/WebExceptionRenderer.php <ide> public function render(): ResponseInterface <ide> if ($isDebug) { <ide> $trace = (array)Debugger::formatTrace($exception->getTrace(), [ <ide> 'format' => 'array', <del> 'args' => false, <add> 'args' => true, <ide> ]); <ide> $origin = [ <ide> 'file' => $exception->getFile() ?: 'null', <ide><path>templates/layout/dev_error.php <ide> border-bottom: 1px solid #ccc; <ide> } <ide> </style> <add> <?php require CAKE . 'Error/Debug/dumpHeader.html'; ?> <ide> </head> <ide> <body> <ide> <header>
2
PHP
PHP
remove outdated doc block note
232abb7f0607b2f67fefe9271af21348eaa3eb0f
<ide><path>src/Validation/Validator.php <ide> public function __construct() <ide> * @param array $data The data to be checked for errors <ide> * @param bool $newRecord whether the data to be validated is new or to be updated. <ide> * @return array Array of invalid fields <del> * @see Validator::validates() <ide> */ <ide> public function errors(array $data, $newRecord = true) <ide> {
1
Go
Go
remove all images matching a regexp
74c88fdbc0180c276f75322066e7da2e3cd38f6d
<ide><path>image/image.go <ide> import ( <ide> "os" <ide> "path" <ide> "path/filepath" <add> "regexp" <ide> "sort" <ide> "strings" <ide> "time" <ide> func (index *Index) Delete(name string) error { <ide> return nil <ide> } <ide> <add>// DeleteMatch deletes all images whose name matches `pattern` <add>func (index *Index) DeleteMatch(pattern string) error { <add> // Load <add> if err := index.load(); err != nil { <add> return err <add> } <add> for name, history := range index.ByName { <add> if match, err := regexp.MatchString(pattern, name); err != nil { <add> return err <add> } else if match { <add> fmt.Printf("Match: %s %s\n", name, pattern) <add> // Remove from index lookup <add> for _, image := range *history { <add> delete(index.ById, image.Id) <add> } <add> // Remove from name lookup <add> delete(index.ByName, name) <add> } <add> } <add> // Save <add> if err := index.save(); err != nil { <add> return err <add> } <add> return nil <add>} <add> <ide> func (index *Index) Names() []string { <ide> if err := index.load(); err != nil { <ide> return []string{} <ide><path>server/server.go <ide> func (srv *Server) CmdInspect(stdin io.ReadCloser, stdout io.Writer, args ...str <ide> // 'docker rmi NAME' removes all images with the name NAME <ide> func (srv *Server) CmdRmi(stdin io.ReadCloser, stdout io.Writer, args ...string) error { <ide> cmd := rcli.Subcmd(stdout, "rmimage", "[OPTIONS] IMAGE", "Remove an image") <add> fl_regexp := cmd.Bool("r", false, "Use IMAGE as a regular expression instead of an exact name") <ide> if err := cmd.Parse(args); err != nil { <ide> cmd.Usage() <ide> return nil <ide> func (srv *Server) CmdRmi(stdin io.ReadCloser, stdout io.Writer, args ...string) <ide> return nil <ide> } <ide> for _, name := range cmd.Args() { <del> image := srv.images.Find(name) <del> if image == nil { <del> return errors.New("No such image: " + name) <add> var err error <add> if *fl_regexp { <add> err = srv.images.DeleteMatch(name) <add> } else { <add> image := srv.images.Find(name) <add> if image == nil { <add> return errors.New("No such image: " + name) <add> } <add> err = srv.images.Delete(name) <ide> } <del> if err := srv.images.Delete(name); err != nil { <add> if err != nil { <ide> return err <ide> } <ide> }
2
Text
Text
add helpers to contribute docs
87830f3a9c4a3b0cab09aa152ec7e043f24cdba2
<ide><path>docs/_sidebar.md <ide> - [Work on video challenges](how-to-help-with-video-challenges.md) <ide> - [Work on the news theme](how-to-work-on-the-news-theme.md) <ide> - [Work on the docs theme](how-to-work-on-the-docs-theme.md) <add> - [Work on practice projects](how-to-work-on-practice-projects.md) <ide> - **Translation Contribution** <ide> - [Work on translating resources](how-to-translate-files.md) <ide> - [Work on proofreading translations](how-to-proofread-files.md) <ide><path>docs/how-to-work-on-coding-challenges.md <ide> Before you work on the curriculum, you would need to set up some tooling to help <ide> <ide> - Edit the files on GitHub's interface by clicking the pencil icon for the corresponding file. While this is the quickest way, It is **not recommended**, because you are unable to test your changes on GitHub. If our maintainers conclude that the changes you made need to be tested locally, you would need to follow the methods above instead. <ide> <add>### How to work on practice projects <add> <add>The practice projects have some additional tooling to help create new projects and steps. To read more, see [these docs](how-to-work-on-practice-projects.md) <ide> ## Challenge Template <ide> <ide> ````md <add><path>docs/how-to-work-on-practice-projects.md <del><path>tools/challenge-helper-scripts/README.md <del># freeCodeCamp Project-based Curriculum Tools <add># How to Work on Practice Projects <ide> <del>This folder contains tools to help facilitate the creation and maintenance of the freeCodeCamp project-based curriculum. <add>The `tools/challenge-helper-scripts` folder contains tools to help facilitate the creation and maintenance of the freeCodeCamp project-based curriculum. <add> <add>## Create a new project <add> <add>Run `npm run create-project`. This opens up a command line ui that guides you through the process. Once that has finished, there should be a new challenge in the English curriculum that you can use for the first step of the project. For example, if you created a project called `test-project` in the Responsive Web Design certification, it would be in `curriculum/challenges/english/01-responsive-web-design/test-project`. <add> <add>If you want to create new steps, the following tools simplify that process. <add> <add>## create-next-step <ide> <del>## [create-next-step.js](create-next-step.js) <ide> A one-off script that will automatically add the next step based on the last step numbered as `part-xxx.md` where `xxx` represents the 3-digit step number of the last step. The challenge seed code will use the previous step's challenge seed code with the editable region markers (ERMs) removed. <ide> <del>**Note:** This script also runs [reorder-steps.js](reorder-steps.js). <add>**Note:** This script also runs [reorder-steps](how-to-work-on-practice-projects#reorder-steps). <ide> <ide> ### How to run script: <add> <ide> 1. Change to the directory of the project. <ide> 2. Run the following npm command: <del> ```bash <del> npm run create-next-step <del> ``` <ide> <del>## [create-empty-steps.js](create-empty-steps.js) <add>```bash <add>npm run create-next-step <add>``` <add> <add>## create-empty-steps <add> <ide> A one-off script that automatically adds a specified number of steps at a specific starting step number. The challenge seed code for all steps created will be empty. <ide> <del>**Note:** This script also runs [reorder-steps.js](reorder-steps.js). <add>**Note:** This script also runs [reorder-steps](how-to-work-on-practice-projects#reorder-steps). <ide> <ide> ### How to run script: <add> <ide> 1. Change to the directory of the project. <ide> 2. Run the following npm command: <del> ```bash <del> npm run create-empty-steps start=X num=Y # where X is the starting step number and Y is the number of steps to create. <del> ``` <ide> <del>## [create-step-between.js](create-step-between.js) <add>```bash <add>npm run create-empty-steps start=X num=Y # where X is the starting step number and Y is the number of steps to create. <add>``` <add> <add>## create-step-between <add> <ide> A one-off script that automatically adds a new step between two existing consecutive steps. The challenge seed code will use the existing starting step's challenge seed code with the editable region markers (ERMs) removed. <ide> <del>**Note:** This script also runs [reorder-steps.js](reorder-steps.js). <add>**Note:** This script also runs [reorder-steps](how-to-work-on-practice-projects#reorder-steps). <ide> <ide> ### How to run script: <add> <ide> 1. Change to the directory of the project. <ide> 2. Run the following npm command: <del> ```bash <del> npm run create-step-between start=X # where X is the starting step number <del> ``` <ide> <del>## [delete-step.js](delete-step.js) <add>```bash <add>npm run create-step-between start=X # where X is the starting step number <add>``` <add> <add>## delete-step <add> <ide> A one-off script that deletes an existing step and then reorders the remaining step files in the project's folder as well as updates the `challengeOrder` property array in the project's `meta.json` with the new order of the steps. <ide> <ide> ### How to run script <add> <ide> 1. Change to the directory of the project. <ide> 2. Run the following npm command: <del> ```bash <del> npm run delete-step num=x # where x is the step number to be deleted. <del> ``` <ide> <del>## [reorder-steps.js](reorder-steps.js) <del>A one-off script that automatically reorders the step files in a project's markdown files based on the filename. It also updates the `challengeOrder` property array in the project's `meta.json` with the new order of the steps. <add>```bash <add>npm run delete-step num=x # where x is the step number to be deleted. <add>``` <add> <add>## reorder-steps <add> <add>A one-off script that automatically reorders the step files in a project's markdown files based on the filename. It also updates the `challengeOrder` property array in the project's `meta.json` with the new order of the steps. <ide> <ide> ### Working Example <add> <ide> Let's say you start with the following project structure: <ide> <ide> ```bash <ide> part-4.md <ide> part-5.md <ide> part-6.md <ide> ``` <del>At some point you decide you need to delete `part-2.md`, because that step is no longer needed. Also, you decide to break down `part-4.md` into three steps instead of just one. <ide> <del>To accomplish the this restructure, you would need to delete `part-2.md` and then add a `part-4a.md` and a `part=5b.md`. The new folder structure would look like the following: <add>At some point you decide you need to delete `part-2.md`, because that step is no longer needed. Also, you decide to break down `part-4.md` into three steps instead of just one. <add> <add>To accomplish this restructure, you would need to delete `part-2.md` and then add a `part-4a.md` and a `part-5b.md`. The new folder structure would look like the following: <add> <ide> ```bash <ide> part-001.md <ide> part-003.md <ide> part-004b.md <ide> part-005.md <ide> part-006.md <ide> ``` <add> <ide> You now need the file names to be `part-1.md` through `part-7.md`, because you removed one but gained two more for a net difference of one file. Also, the frontmatter of each file below a deleted step or added step will need to be modified by making the `title` key value match the new step number. For example, after renaming `part-3.md` to `part-2.md`, you would need to change `part-2.md`'s title from `Part 03` to `Part 02`. <ide> <ide> See below for the actual project folder changes needed: <add> <ide> ```bash <ide> part-001.md <ide> part-003.md renamed to part-002.md and title changes to "Part 2" <ide> part-004b.md renames to part-005.md and title changes to "Part 5" <ide> part-005.md renames to part-006.md and title changes to "Part 6" <ide> part-006.md renames to part-007.md and title changes to "Part 7" <ide> ``` <del>Along with the above changes, the `challengeOrder` key in the project's `meta.json` file needs to reflect the new step order. This is needed because each step below a step deletion and/or step addtion changes the `title` assoiciated with each of the affected step's challenge `id`. <add> <add>Along with the above changes, the `challengeOrder` key in the project's `meta.json` file needs to reflect the new step order. This is needed because each step below a step deletion and/or step addition changes the `title` associated with each of the affected step's challenge `id`. <ide> <ide> ### How to run script <add> <ide> 1. Change to the directory of the project. <ide> 2. Run the following npm command: <del> ```bash <del> npm run reorder-steps <del> ``` <add> <add>```bash <add>npm run reorder-steps <add>```
3
Text
Text
improve documentation for using react with webpack
a3d6553a304d42794363efeefbf50e8e6883424e
<ide><path>docs/docs/getting-started.md <ide> $ npm install --save react react-dom babelify babel-preset-react <ide> $ browserify -t [ babelify --presets [ react ] ] main.js -o bundle.js <ide> ``` <ide> <del>To install React DOM and build your bundle with webpack: <add>To install React DOM and build your bundle with webpack: <ide> <ide> ```sh <ide> $ npm install --save react react-dom babel-preset-react <ide> $ webpack <ide> > <ide> > If you are using ES2015, you will want to also use the `babel-preset-es2015` package. <ide> <add>**Note:** by default, React will be in development mode, which is slower, and not advised for production. To use React in production mode, set the environment variable `NODE_ENV` to `production` (using envify or webpack's DefinePlugin). For example: <add> <add>```js <add>new webpack.DefinePlugin({ <add> "process.env": { <add> NODE_ENV: JSON.stringify("production") <add> } <add>}); <add>``` <ide> <ide> ## Quick Start Without npm <ide>
1
Ruby
Ruby
expect 8.0 on macos 10.12
425eedf43e7e6171f18e42f1d43c400bea3b0d02
<ide><path>Library/Homebrew/os/mac/xcode.rb <ide> def latest_version <ide> when "10.9" then "6.2" <ide> when "10.10" then "7.2.1" <ide> when "10.11" then "7.3.1" <add> when "10.12" then "8.0" <ide> else <ide> # Default to newest known version of Xcode for unreleased OSX versions. <ide> if OS::Mac.prerelease? <del> "7.3.1" <add> "8.0" <ide> else <ide> raise "OS X '#{MacOS.version}' is invalid" <ide> end <ide> def uncached_version <ide> when 61 then "6.1" <ide> when 70 then "7.0" <ide> when 73 then "7.3" <del> else "7.3" <add> when 80 then "8.0" <add> else "8.0" <ide> end <ide> end <ide> <ide> def installed? <ide> <ide> def latest_version <ide> case MacOS.version <add> when "10.12" then "800.0.24.1" <ide> when "10.11" then "703.0.31" <ide> when "10.10" then "700.1.81" <ide> when "10.9" then "600.0.57"
1
Text
Text
create article for autoencoder networks
b1a9ae7b65881180b33b35bd8f7fddda0a989a87
<ide><path>guide/english/machine-learning/autoencoders/index.md <add>--- <add>title: Autoencoder Networks <add>--- <add>## Autoencoder Networks <add>![Autoencoder network](http://ufldl.stanford.edu/tutorial/images/Autoencoder636.png) <add> <add>The Autoencoder is a type of neural network used to reduce the dimensionality of a set of data. The idea is to use a neural network whose structure is hourglass-shaped (many units on the input and output layers, but few units in the center layers) to encourage a network to represent the data in the smallest amount of information possible. The name, autoencoder, refers to the idea that the network is effectively learning efficient encodings for the type of data it is being trained upon. <add> <add>Typically, when using neural networks as approximators for a set of data, one would have a training dataset which has some inputs that can be collected as data and some outputs which the aforementioned inputs are fed through the network to predict. When using autoencoders, the idea is to train a network to use the inputs to predict themselves. In other words, a perfect autoencoder would simply be an identity function; its outputs would be identical to its inputs in all cases. <add> <add>If one were to use an autoencoder network which had the same number of hidden units throughout all of its layers, it would not be a very useful tool, as it would simply predict its inputs without reducing the spatial usage. However, the key idea of autoencoder networks is to reduce the dimensionality of the network gradually through the network structure to a minimum in the center. At this minimum-dimension central layer, if the network has been trained to accurately predict its own inputs, the input data itself is actually being fully represented in terms of far fewer units than there are inputs to the network. This effectively means that the data is "compressed" or encoded at this point in the network. <add> <add>In real-world applications, by giving a distant party a copy of the trained network, one could transmit this encoded low-dimensional data from the network across the internet for a far smaller cost than transferring the original dataset. The party on the receiving end of the transmission would simply complete the data's forward-pass through the network to obtain the data which was encoded. <add> <add>### Real-world applications <add>* Compression <add>* Dimensional reduction <add>* Pretraining <add> <add>### More Information: <add>- [Wikipedia](https://en.wikipedia.org/wiki/Autoencoder) <add>- [Stanford University - Autoencoders](http://ufldl.stanford.edu/tutorial/unsupervised/Autoencoders/) <add>- [Deng et al. - Encoding Speech Spectrograms using Autoencoders](https://www.isca-speech.org/archive/interspeech_2010/i10_1692.html)
1
Ruby
Ruby
adjust formula count for unsymlinked files
e714a47c10c35bffd8de2d9e703db9d8c9e6d0eb
<ide><path>Library/Homebrew/cmd/tap.rb <ide> def install_tap user, repo <ide> <ide> files = [] <ide> tapd.find_formula{ |file| files << tapd.basename.join(file) } <del> tapped = link_tap_formula(files) <del> puts "Tapped #{tapped} formula" <add> link_tap_formula(files) <add> puts "Tapped #{files.count} formula" <ide> <ide> # Figure out if this repo is private <ide> # curl will throw an exception if the repo is private (Github returns a 404) <ide><path>Library/Homebrew/cmd/untap.rb <ide> def untap <ide> <ide> files = [] <ide> tapd.find_formula{ |file| files << Pathname.new("#{user}-#{repo}").join(file) } <del> untapped = unlink_tap_formula(files) <add> unlink_tap_formula(files) <ide> rm_rf tapd <del> puts "Untapped #{untapped} formula" <add> puts "Untapped #{files.count} formula" <ide> end <ide> <ide> def unlink_tap_formula formulae
2
Python
Python
extract common variable
235e58d51d27a9f8665f43050d485d3d23f7288f
<ide><path>numpy/core/tests/test_multiarray.py <ide> def test_searchsorted(self): <ide> assert_equal(b, out + 1) <ide> # Test empty array, use a fresh array to get warnings in <ide> # valgrind if access happens. <del> b = np.ndarray(shape=0, buffer=b'', dtype=dt).searchsorted(a, 'l') <add> e = np.ndarray(shape=0, buffer=b'', dtype=dt) <add> b = e.searchsorted(a, 'l') <ide> assert_array_equal(b, np.zeros(len(a), dtype=np.intp)) <del> b = a.searchsorted(np.ndarray(shape=0, buffer=b'', dtype=dt), 'l') <add> b = a.searchsorted(e, 'l') <ide> assert_array_equal(b, np.zeros(0, dtype=np.intp)) <ide> <ide> def test_searchsorted_unicode(self): <ide> def test_searchsorted_with_sorter(self): <ide> assert_equal(b, out + 1) <ide> # Test empty array, use a fresh array to get warnings in <ide> # valgrind if access happens. <del> b = np.ndarray(shape=0, buffer=b'', dtype=dt).searchsorted( <del> a, 'l', s[:0]) <add> e = np.ndarray(shape=0, buffer=b'', dtype=dt) <add> b = e.searchsorted(a, 'l', s[:0]) <ide> assert_array_equal(b, np.zeros(len(a), dtype=np.intp)) <del> b = a.searchsorted( <del> np.ndarray(shape=0, buffer=b'', dtype=dt), 'l', s) <add> b = a.searchsorted(e, 'l', s) <ide> assert_array_equal(b, np.zeros(0, dtype=np.intp)) <ide> <ide> # Test non-contiguous sorter array
1
Go
Go
use spf13/cobra for docker commit
939a142c8db7054600cf911a8a19071f794da5f0
<ide><path>api/client/commands.go <ide> package client <ide> // Command returns a cli command handler if one exists <ide> func (cli *DockerCli) Command(name string) func(...string) error { <ide> return map[string]func(...string) error{ <del> "commit": cli.CmdCommit, <ide> "cp": cli.CmdCp, <ide> "exec": cli.CmdExec, <ide> "info": cli.CmdInfo, <ide><path>api/client/commit.go <del>package client <del> <del>import ( <del> "encoding/json" <del> "fmt" <del> <del> "golang.org/x/net/context" <del> <del> Cli "github.com/docker/docker/cli" <del> "github.com/docker/docker/opts" <del> flag "github.com/docker/docker/pkg/mflag" <del> "github.com/docker/engine-api/types" <del> "github.com/docker/engine-api/types/container" <del>) <del> <del>// CmdCommit creates a new image from a container's changes. <del>// <del>// Usage: docker commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]] <del>func (cli *DockerCli) CmdCommit(args ...string) error { <del> cmd := Cli.Subcmd("commit", []string{"CONTAINER [REPOSITORY[:TAG]]"}, Cli.DockerCommands["commit"].Description, true) <del> flPause := cmd.Bool([]string{"p", "-pause"}, true, "Pause container during commit") <del> flComment := cmd.String([]string{"m", "-message"}, "", "Commit message") <del> flAuthor := cmd.String([]string{"a", "-author"}, "", "Author (e.g., \"John Hannibal Smith <hannibal@a-team.com>\")") <del> flChanges := opts.NewListOpts(nil) <del> cmd.Var(&flChanges, []string{"c", "-change"}, "Apply Dockerfile instruction to the created image") <del> // FIXME: --run is deprecated, it will be replaced with inline Dockerfile commands. <del> flConfig := cmd.String([]string{"#-run"}, "", "This option is deprecated and will be removed in a future version in favor of inline Dockerfile-compatible commands") <del> cmd.Require(flag.Max, 2) <del> cmd.Require(flag.Min, 1) <del> <del> cmd.ParseFlags(args, true) <del> <del> var ( <del> name = cmd.Arg(0) <del> reference = cmd.Arg(1) <del> ) <del> <del> var config *container.Config <del> if *flConfig != "" { <del> config = &container.Config{} <del> if err := json.Unmarshal([]byte(*flConfig), config); err != nil { <del> return err <del> } <del> } <del> <del> options := types.ContainerCommitOptions{ <del> Reference: reference, <del> Comment: *flComment, <del> Author: *flAuthor, <del> Changes: flChanges.GetAll(), <del> Pause: *flPause, <del> Config: config, <del> } <del> <del> response, err := cli.client.ContainerCommit(context.Background(), name, options) <del> if err != nil { <del> return err <del> } <del> <del> fmt.Fprintln(cli.out, response.ID) <del> return nil <del>} <ide><path>api/client/container/commit.go <add>package container <add> <add>import ( <add> "encoding/json" <add> "fmt" <add> <add> "golang.org/x/net/context" <add> <add> "github.com/docker/docker/api/client" <add> "github.com/docker/docker/cli" <add> dockeropts "github.com/docker/docker/opts" <add> "github.com/docker/engine-api/types" <add> containertypes "github.com/docker/engine-api/types/container" <add> "github.com/spf13/cobra" <add>) <add> <add>type commitOptions struct { <add> container string <add> reference string <add> <add> pause bool <add> comment string <add> author string <add> changes dockeropts.ListOpts <add> config string <add>} <add> <add>// NewCommitCommand creats a new cobra.Command for `docker commit` <add>func NewCommitCommand(dockerCli *client.DockerCli) *cobra.Command { <add> var opts commitOptions <add> <add> cmd := &cobra.Command{ <add> Use: "commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]", <add> Short: "Create a new image from a container's changes", <add> Args: cli.RequiresRangeArgs(1, 2), <add> RunE: func(cmd *cobra.Command, args []string) error { <add> opts.container = args[0] <add> if len(args) > 1 { <add> opts.reference = args[1] <add> } <add> return runCommit(dockerCli, &opts) <add> }, <add> } <add> cmd.SetFlagErrorFunc(flagErrorFunc) <add> <add> flags := cmd.Flags() <add> flags.SetInterspersed(false) <add> <add> flags.BoolVarP(&opts.pause, "pause", "p", true, "Pause container during commit") <add> flags.StringVarP(&opts.comment, "message", "m", "", "Commit message") <add> flags.StringVarP(&opts.author, "author", "a", "", "Author (e.g., \"John Hannibal Smith <hannibal@a-team.com>\")") <add> <add> opts.changes = dockeropts.NewListOpts(nil) <add> flags.VarP(&opts.changes, "change", "c", "Apply Dockerfile instruction to the created image") <add> <add> // FIXME: --run is deprecated, it will be replaced with inline Dockerfile commands. <add> flags.StringVar(&opts.config, "run", "", "This option is deprecated and will be removed in a future version in favor of inline Dockerfile-compatible commands") <add> flags.MarkDeprecated("run", "it will be replaced with inline Dockerfile commands.") <add> <add> return cmd <add>} <add> <add>func runCommit(dockerCli *client.DockerCli, opts *commitOptions) error { <add> ctx := context.Background() <add> <add> name := opts.container <add> reference := opts.reference <add> <add> var config *containertypes.Config <add> if opts.config != "" { <add> config = &containertypes.Config{} <add> if err := json.Unmarshal([]byte(opts.config), config); err != nil { <add> return err <add> } <add> } <add> <add> options := types.ContainerCommitOptions{ <add> Reference: reference, <add> Comment: opts.comment, <add> Author: opts.author, <add> Changes: opts.changes.GetAll(), <add> Pause: opts.pause, <add> Config: config, <add> } <add> <add> response, err := dockerCli.Client().ContainerCommit(ctx, name, options) <add> if err != nil { <add> return err <add> } <add> <add> fmt.Fprintln(dockerCli.Out(), response.ID) <add> return nil <add>} <ide><path>api/client/container/port.go <ide> func NewPortCommand(dockerCli *client.DockerCli) *cobra.Command { <ide> cmd := &cobra.Command{ <ide> Use: "port CONTAINER [PRIVATE_PORT[/PROTO]]", <ide> Short: "List port mappings or a specific mapping for the container", <del> Args: cli.RequiresMinMaxArgs(1, 2), <add> Args: cli.RequiresRangeArgs(1, 2), <ide> RunE: func(cmd *cobra.Command, args []string) error { <ide> opts.container = args[0] <ide> if len(args) > 1 { <ide><path>cli/cobraadaptor/adaptor.go <ide> func NewCobraAdaptor(clientFlags *cliflags.ClientFlags) CobraAdaptor { <ide> rootCmd.SetOutput(stdout) <ide> rootCmd.AddCommand( <ide> container.NewAttachCommand(dockerCli), <add> container.NewCommitCommand(dockerCli), <ide> container.NewCreateCommand(dockerCli), <ide> container.NewDiffCommand(dockerCli), <ide> container.NewExportCommand(dockerCli), <ide><path>cli/required.go <ide> func RequiresMaxArgs(max int) cobra.PositionalArgs { <ide> } <ide> } <ide> <del>// RequiresMinMaxArgs returns an error if there is not at least min args and at most max args <del>func RequiresMinMaxArgs(min int, max int) cobra.PositionalArgs { <add>// RequiresRangeArgs returns an error if there is not at least min args and at most max args <add>func RequiresRangeArgs(min int, max int) cobra.PositionalArgs { <ide> return func(cmd *cobra.Command, args []string) error { <ide> if len(args) >= min && len(args) <= max { <ide> return nil <ide><path>cli/usage.go <ide> type Command struct { <ide> <ide> // DockerCommandUsage lists the top level docker commands and their short usage <ide> var DockerCommandUsage = []Command{ <del> {"commit", "Create a new image from a container's changes"}, <ide> {"cp", "Copy files/folders between a container and the local filesystem"}, <ide> {"exec", "Run a command in a running container"}, <ide> {"info", "Display system-wide information"},
7
Ruby
Ruby
expand metaprogramming for symbol, slash and dot
0086400dd75e73152429f9acf2fce984d8f46e02
<ide><path>actionpack/lib/action_dispatch/journey/nodes/node.rb <ide> def initialize(x = Object.new) <ide> def literal?; false; end <ide> end <ide> <del> %w{ Symbol Slash Dot }.each do |t| <del> class_eval <<-eoruby, __FILE__, __LINE__ + 1 <del> class #{t} < Terminal; <del> def type; :#{t.upcase}; end <del> end <del> eoruby <add> class Slash < Terminal # :nodoc: <add> def type; :SLASH; end <add> end <add> <add> class Dot < Terminal # :nodoc: <add> def type; :DOT; end <ide> end <ide> <ide> class Symbol < Terminal # :nodoc: <ide> def default_regexp? <ide> regexp == DEFAULT_EXP <ide> end <ide> <add> def type; :SYMBOL; end <ide> def symbol?; true; end <ide> end <ide>
1
PHP
PHP
detect persistent connection reset
d48d7b4d4b91a0597960407687bc01b2094da02a
<ide><path>src/Illuminate/Database/DetectsLostConnections.php <ide> protected function causedByLostConnection(Exception $e) <ide> 'Transaction() on null', <ide> 'child connection forced to terminate due to client_idle_limit', <ide> 'query_wait_timeout', <add> 'reset by peer', <ide> ]); <ide> } <ide> }
1
Go
Go
fix typo in devmapper error message
029625981d3872872f0de95c5a4ea68cb1fa93af
<ide><path>graphdriver/devmapper/deviceset.go <ide> func (devices *DeviceSet) allocateTransactionId() uint64 { <ide> func (devices *DeviceSet) saveMetadata() error { <ide> jsonData, err := json.Marshal(devices.MetaData) <ide> if err != nil { <del> return fmt.Errorf("Error encoding metaadata to json: %s", err) <add> return fmt.Errorf("Error encoding metadata to json: %s", err) <ide> } <ide> tmpFile, err := ioutil.TempFile(filepath.Dir(devices.jsonFile()), ".json") <ide> if err != nil {
1
Javascript
Javascript
increase timeout for test-tls-fast-writing
c133d07b8311907b3ec11980dce512ecc0f90635
<ide><path>test/parallel/test-tls-fast-writing.js <ide> var gotDrain = false; <ide> setTimeout(function() { <ide> console.log('not ok - timed out'); <ide> process.exit(1); <del>}, common.platformTimeout(500)); <add>}, common.platformTimeout(1000)); <ide> <ide> function onconnection(conn) { <ide> conn.on('data', function(c) {
1
Javascript
Javascript
update meta and description
00c475f663d21cb5f245a9a4b5d6bf8a33ccee75
<ide><path>client/src/components/landing/index.js <ide> export const Landing = ({ edges }) => { <ide> return ( <ide> <Fragment> <ide> <Helmet> <del> <title>Learn to code | freeCodeCamp.org</title> <add> <title>Learn to code at home | freeCodeCamp.org</title> <ide> </Helmet> <ide> <main className='landing-page'> <ide> <Spacer /> <ide> export const Landing = ({ edges }) => { <ide> Welcome to freeCodeCamp.org <ide> </h1> <ide> <Spacer /> <del> <h2 className='medium-heading text-center'>Learn to code.</h2> <add> <h2 className='medium-heading text-center'> <add> Learn to code at home. <add> </h2> <ide> <h2 className='medium-heading text-center'>Build projects.</h2> <ide> <h2 className='medium-heading text-center'> <ide> Earn certifications. <ide><path>client/src/components/layouts/Default.js <ide> class DefaultLayout extends Component { <ide> meta={[ <ide> { <ide> name: 'description', <del> content: <del> 'Learn to code with free online courses, programming ' + <del> 'projects, and interview preparation for developer jobs.' <add> content: `Learn to code at home. Build projects. Earn certifications. Since 2014, <add> more than 40,000 freeCodeCamp.org graduates have gotten jobs at tech <add> companies including Google, Apple, Amazon, and Microsoft.` <ide> }, <ide> { name: 'keywords', content: metaKeywords.join(', ') } <ide> ]} <ide><path>client/src/pages/learn.js <ide> export const LearnPage = ({ <ide> const hashValue = hashValueSelector(state, hash); <ide> return ( <ide> <LearnLayout> <del> <Helmet title='Learn | freeCodeCamp.org' /> <add> <Helmet title='Learn to code at home | freeCodeCamp.org' /> <ide> <Grid> <ide> <Intro <ide> complete={complete}
3
Python
Python
apply proposed changes
cef6aa3830f915f9589a50700670da062e6acffd
<ide><path>numpy/core/_add_newdocs.py <ide> <ide> Examples <ide> -------- <del> For a 1D array, ``a.tolist()`` is almost the same as ``list(a)``, except that it changes numpy scalars to Python scalars: <add> For a 1D array, ``a.tolist()`` is almost the same as ``list(a)``, <add> except that ``tolist`` changes numpy scalars to Python scalars: <ide> <ide> >>> a = np.uint32([1, 2]) <ide> >>> a_list = list(a) <ide> >>> a_list <ide> [1, 2] <del> >>> type(a_list) <del> <class 'list'> <ide> >>> type(a_list[0]) <ide> <class 'numpy.uint32'> <ide> >>> a_tolist = a.tolist() <ide> >>> a_tolist <ide> [1, 2] <del> >>> type(a_tolist) <del> <class 'list'> <ide> >>> type(a_tolist[0]) <ide> <class 'int'> <ide> <del> However, for a 2D array, ``tolist`` applies recursively: <add> Additionally, for a 2D array, ``tolist`` applies recursively: <ide> <ide> >>> a = np.array([[1, 2], [3, 4]]) <ide> >>> list(a)
1
PHP
PHP
add missing return tags
f9435aff277f9a06be11af41ebe8e6748f736832
<ide><path>lib/Cake/View/Helper/NumberHelper.php <ide> public function __construct(View $View, $settings = array()) { <ide> <ide> /** <ide> * Call methods from CakeNumber utility class <add> * @return mixed Whatever is returned by called method, or false on failure <ide> */ <ide> public function __call($method, $params) { <ide> return call_user_func_array(array($this->_engine, $method), $params); <ide><path>lib/Cake/View/Helper/TextHelper.php <ide> public function __construct(View $View, $settings = array()) { <ide> <ide> /** <ide> * Call methods from String utility class <add> * @return mixed Whatever is returned by called method, or false on failure <ide> */ <ide> public function __call($method, $params) { <ide> return call_user_func_array(array($this->_engine, $method), $params); <ide><path>lib/Cake/View/Helper/TimeHelper.php <ide> public function __get($name) { <ide> <ide> /** <ide> * Call methods from CakeTime utility class <add> * @return mixed Whatever is returned by called method, or false on failure <ide> */ <ide> public function __call($method, $params) { <ide> return call_user_func_array(array($this->_engine, $method), $params);
3
PHP
PHP
remove un-necessary parameter
6a95b5746ab50b43e0bf90eed3e418b6bbb3dd83
<ide><path>lib/Cake/Controller/Component/Auth/DigestAuthenticate.php <ide> public function getUser($request) { <ide> if (empty($digest)) { <ide> return false; <ide> } <del> $user = $this->_findUser($digest['username'], null); <add> $user = $this->_findUser($digest['username']); <ide> if (empty($user)) { <ide> return false; <ide> }
1
Go
Go
remove deprecation warning
1d02ad2a519765179480e0ae113bcf510a2713af
<ide><path>volume/volume.go <ide> import ( <ide> "os" <ide> "runtime" <ide> "strings" <del> <del> "github.com/Sirupsen/logrus" <del> "github.com/docker/docker/pkg/system" <ide> ) <ide> <ide> // DefaultDriverName is the driver name used for the driver <ide> func (m *MountPoint) Setup() (string, error) { <ide> return "", err <ide> } <ide> if runtime.GOOS != "windows" { // Windows does not have deprecation issues here <del> logrus.Warnf("Auto-creating non-existent volume host path %s, this is deprecated and will be removed soon", m.Source) <del> if err := system.MkdirAll(m.Source, 0755); err != nil { <add> if err := os.MkdirAll(m.Source, 0755); err != nil { <ide> return "", err <ide> } <ide> }
1
Text
Text
remove trailing whitespace
d0bf5ca90b2e816c37511e30225a373b8810ed0d
<ide><path>README.md <ide> The open source license grants you the freedom to use Node.js. It does not <ide> guarantee commitments of other people's time. Please be respectful and manage <ide> your expectations. <ide> <del>## Release Types <add>## Release Types <ide> <ide> * **Current**: Under active development. Code for the Current release is in the <ide> branch for its major version number (for example,
1
Javascript
Javascript
add more information about the italic angle
233439949855ac14182c0371552dbe6f027b1805
<ide><path>fonts.js <ide> var Font = (function () { <ide> "\x00\x00" + // yMin <ide> "\x00\x00" + // xMax <ide> "\x00\x00" + // yMax <del> "\x00\x00" + // macStyle <add> string16(properties.italicAngle ? 1 : 0) + // macStyle <ide> "\x00\x11" + // lowestRecPPEM <ide> "\x00\x00" + // fontDirectionHint <ide> "\x00\x00" + // indexToLocFormat <ide> var Font = (function () { <ide> "\x00\x00" + // minRightSidebearing <ide> "\x00\x00" + // xMaxExtent <ide> "\x00\x00" + // caretSlopeRise <del> "\x00\x00" + // caretSlopeRun <add> string16(properties.italicAngle) + // caretSlopeRun <ide> "\x00\x00" + // caretOffset <ide> "\x00\x00" + // -reserved- <ide> "\x00\x00" + // -reserved-
1
PHP
PHP
add "use" statement
b4b05c1c340f20335295290790f34d1929b7d934
<ide><path>src/basics.php <ide> <ide> use Cake\Core\Configure; <ide> use Cake\Error\Debugger; <add>use Psy\Shell as PsyShell; <ide> <ide> define('SECOND', 1); <ide> define('MINUTE', 60); <ide> function stackTrace(array $options = []): void <ide> */ <ide> function breakpoint(): ?string <ide> { <del> if ((PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') && class_exists(\Psy\Shell::class)) { <add> if ((PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') && class_exists(PsyShell::class)) { <ide> return 'extract(\Psy\Shell::debug(get_defined_vars(), isset($this) ? $this : null));'; <ide> } <ide> trigger_error(
1
Ruby
Ruby
use method instead of variable
89bd945bb7d623571da389db0167843fdbc805d6
<ide><path>Library/Homebrew/tap.rb <ide> def initialize(user, repo) <ide> def remote <ide> @remote ||= if installed? <ide> if git? <del> @path.cd do <add> path.cd do <ide> Utils.popen_read("git", "config", "--get", "remote.origin.url").chomp <ide> end <ide> end <ide> def remote <ide> <ide> # True if this {Tap} is a git repository. <ide> def git? <del> (@path/".git").exist? <add> (path/".git").exist? <ide> end <ide> <ide> def to_s <ide> def to_s <ide> <ide> # True if this {Tap} is an official Homebrew tap. <ide> def official? <del> @user == "Homebrew" <add> user == "Homebrew" <ide> end <ide> <ide> # True if the remote of this {Tap} is a private repository. <ide> def private? <ide> return true if custom_remote? <del> GitHub.private_repo?(@user, "homebrew-#{@repo}") <add> GitHub.private_repo?(user, "homebrew-#{repo}") <ide> rescue GitHub::HTTPNotFoundError <ide> true <ide> rescue GitHub::Error <ide> def private? <ide> <ide> # True if this {Tap} has been installed. <ide> def installed? <del> @path.directory? <add> path.directory? <ide> end <ide> <ide> # install this {Tap}. <ide> def install(options = {}) <ide> # ensure git is installed <ide> Utils.ensure_git_installed! <ide> ohai "Tapping #{name}" <del> remote = options[:clone_target] || "https://github.com/#{@user}/homebrew-#{@repo}" <del> args = %W[clone #{remote} #{@path}] <add> remote = options[:clone_target] || "https://github.com/#{user}/homebrew-#{repo}" <add> args = %W[clone #{remote} #{path}] <ide> args << "--depth=1" unless options.fetch(:full_clone, false) <ide> <ide> begin <ide> safe_system "git", *args <ide> rescue Interrupt, ErrorDuringExecution <ide> ignore_interrupts do <ide> sleep 0.1 # wait for git to cleanup the top directory when interrupt happens. <del> @path.parent.rmdir_if_possible <add> path.parent.rmdir_if_possible <ide> end <ide> raise <ide> end <ide> <ide> formula_count = formula_files.size <del> puts "Tapped #{formula_count} formula#{plural(formula_count, "e")} (#{@path.abv})" <add> puts "Tapped #{formula_count} formula#{plural(formula_count, "e")} (#{path.abv})" <ide> Descriptions.cache_formulae(formula_names) <ide> <ide> if !options[:clone_target] && private? <ide> puts <<-EOS.undent <ide> It looks like you tapped a private repository. To avoid entering your <ide> credentials each time you update, you can use git HTTP credential <ide> caching or issue the following command: <del> cd #{@path} <del> git remote set-url origin git@github.com:#{@user}/homebrew-#{@repo}.git <add> cd #{path} <add> git remote set-url origin git@github.com:#{user}/homebrew-#{repo}.git <ide> EOS <ide> end <ide> end <ide> def install(options = {}) <ide> def uninstall <ide> raise TapUnavailableError, name unless installed? <ide> <del> puts "Untapping #{name}... (#{@path.abv})" <add> puts "Untapping #{name}... (#{path.abv})" <ide> unpin if pinned? <ide> formula_count = formula_files.size <ide> Descriptions.uncache_formulae(formula_names) <del> @path.rmtree <del> @path.dirname.rmdir_if_possible <add> path.rmtree <add> path.dirname.rmdir_if_possible <ide> puts "Untapped #{formula_count} formula#{plural(formula_count, "e")}" <ide> end <ide> <ide> # True if the {#remote} of {Tap} is customized. <ide> def custom_remote? <ide> return true unless remote <del> remote.casecmp("https://github.com/#{@user}/homebrew-#{@repo}") != 0 <add> remote.casecmp("https://github.com/#{user}/homebrew-#{repo}") != 0 <ide> end <ide> <ide> # an array of all {Formula} files of this {Tap}. <ide> def formula_files <del> @formula_files ||= if dir = [@path/"Formula", @path/"HomebrewFormula", @path].detect(&:directory?) <add> @formula_files ||= if dir = [path/"Formula", path/"HomebrewFormula", path].detect(&:directory?) <ide> dir.children.select { |p| p.extname == ".rb" } <ide> else <ide> [] <ide> def command_files <ide> # path to the pin record for this {Tap}. <ide> # @private <ide> def pinned_symlink_path <del> HOMEBREW_LIBRARY/"PinnedTaps/#{@name}" <add> HOMEBREW_LIBRARY/"PinnedTaps/#{name}" <ide> end <ide> <ide> # True if this {Tap} has been pinned. <ide> def pinned? <ide> def pin <ide> raise TapUnavailableError, name unless installed? <ide> raise TapPinStatusError.new(name, true) if pinned? <del> pinned_symlink_path.make_relative_symlink(@path) <add> pinned_symlink_path.make_relative_symlink(path) <ide> @pinned = true <ide> end <ide> <ide> def unpin <ide> <ide> def to_hash <ide> hash = { <del> "name" => @name, <del> "user" => @user, <del> "repo" => @repo, <del> "path" => @path.to_s, <add> "name" => name, <add> "user" => user, <add> "repo" => repo, <add> "path" => path.to_s, <ide> "installed" => installed?, <ide> "official" => official?, <ide> "formula_names" => formula_names,
1
Javascript
Javascript
add undefined guard for window.devicepixelratio
7f4b1d9715f3da507893cf145009c729fad3606b
<ide><path>src/core/core.helpers.js <ide> module.exports = function(Chart) { <ide> document.defaultView.getComputedStyle(el, null).getPropertyValue(property); <ide> }; <ide> helpers.retinaScale = function(chart, forceRatio) { <del> var pixelRatio = chart.currentDevicePixelRatio = forceRatio || window.devicePixelRatio || 1; <add> var pixelRatio = chart.currentDevicePixelRatio = forceRatio || (typeof window !== 'undefined' && window.devicePixelRatio) || 1; <ide> if (pixelRatio === 1) { <ide> return; <ide> }
1
Text
Text
refine document by review comments
8d682bf734539ade2d618349f82b8b5e83a87167
<ide><path>docs/man/docker-history.1.md <ide> Show the history of when and how an image was created. <ide> 511136ea3c5a 10 months ago 0 B Imported from - <ide> <ide> ## Show the history of images created through docker commit command <del>`docker commit` command accepts a **-m** parameter to provide comment messages to the image. You can see these messages in image history. <add>The `docker commit` command has a **-m** flag for adding comments to the image. These comments will be displayed in the image history. <ide> <ide> $ sudo docker history docker:scm <ide> IMAGE CREATED CREATED BY SIZE COMMENT <ide><path>docs/sources/reference/commandline/cli.md <ide> To see how the `docker:latest` image was built: <ide> 750d58736b4b 6 weeks ago /bin/sh -c #(nop) MAINTAINER Tianon Gravi <ad 0 B <ide> 511136ea3c5a 9 months ago 0 B Imported from - <ide> <del>To see how the `docker:apache` image which was commited from a container: <add>To see how the `docker:apache` image was added to a container's base image: <ide> <ide> $ sudo docker history docker:scm <ide> IMAGE CREATED CREATED BY SIZE COMMENT
2
PHP
PHP
fix some input stuff and revert paginator changes
9e8acd1edafbc156690390454be8d14bc1a7a37b
<ide><path>laravel/input.php <ide> class Input { <ide> */ <ide> public static function all() <ide> { <del> $input = array_merge(static::get(), static::query(), $_FILES); <add> $input = array_merge(static::get(), static::query(), static::file()); <ide> <ide> unset($input[Request::spoofer]); <ide> <ide> public static function has($key) <ide> */ <ide> public static function get($key = null, $default = null) <ide> { <del> return array_get(Request::foundation()->request->all(), $key, $default); <add> $value = Request::foundation()->request->get($key); <add> <add> if (is_null($value)) <add> { <add> return array_get(static::query(), $key, $default); <add> } <add> <add> return $value; <ide> } <ide> <ide> /** <ide> public static function old($key = null, $default = null) <ide> */ <ide> public static function file($key = null, $default = null) <ide> { <del> return array_get(Request::foundation()->files->all(), $key, $default); <add> return array_get($_FILES, $key, $default); <add> } <add> <add> /** <add> * Move an uploaded file to permanent storage. <add> * <add> * This method is simply a convenient wrapper around move_uploaded_file. <add> * <add> * <code> <add> * // Move the "picture" file to a new permanent location on disk <add> * Input::upload('picture', 'path/to/photos', 'picture.jpg'); <add> * </code> <add> * <add> * @param string $key <add> * @param string $directory <add> * @param string $name <add> * @return bool <add> */ <add> public static function upload($key, $directory, $name = null) <add> { <add> if (is_null(static::file($key))) return false; <add> <add> return Request::foundation()->files->get($key)->move($directory, $name); <ide> } <ide> <ide> /** <ide><path>laravel/paginator.php <ide> public static function make($results, $total, $per_page) <ide> */ <ide> public static function page($total, $per_page) <ide> { <del> $page = Input::query('page', 1); <add> $page = Input::get('page', 1); <ide> <ide> // The page will be validated and adjusted if it is less than one or greater <ide> // than the last page. For example, if the current page is not an integer or
2
Mixed
Javascript
fix usage of next/css
83400a8f38fe003f57184521346457353ae8f5b4
<ide><path>Readme.md <ide> We use [glamor](https://github.com/threepointone/glamor) to provide a great buil <ide> <ide> ```jsx <ide> import React from 'react' <del>import { style } from 'next/css' <add>import style from 'next/css' <ide> <ide> export default () => ( <ide> <div className={style}> <ide><path>examples/basic-css/pages/index.js <ide> import React from 'react' <del>import { style } from 'next/css' <add>import style from 'next/css' <ide> <ide> export default () => ( <ide> <div className={styles}> <ide><path>examples/nested-components/components/paragraph.js <ide> import React from 'react' <del>import { style } from 'next/css' <add>import style from 'next/css' <ide> <ide> export default ({ children }) => ( <ide> <p className={styles}>{children}</p> <ide><path>examples/nested-components/components/post.js <ide> import React from 'react' <del>import { style } from 'next/css' <add>import style from 'next/css' <ide> <ide> export default ({ title, children }) => ( <ide> <div className={mainStyle}> <ide><path>examples/nested-components/pages/index.js <ide> import React from 'react' <ide> import P from '../components/paragraph' <ide> import Post from '../components/post' <del>import { style } from 'next/css' <add>import style from 'next/css' <ide> <ide> export default () => ( <ide> <div className={styles.main}> <ide><path>pages/_error-debug.js <ide> import React from 'react' <ide> import stripAnsi from 'strip-ansi' <ide> import Head from 'next/head' <del>import { style } from 'next/css' <add>import style from 'next/css' <ide> <ide> export default class ErrorDebug extends React.Component { <ide> static getInitialProps ({ err }) { <ide><path>pages/_error.js <ide> import React from 'react' <del>import { style, merge } from 'next/css' <add>import style, { merge } from 'next/css' <ide> <ide> export default class Error extends React.Component { <ide> static getInitialProps ({ res, xhr }) { <ide><path>test/fixtures/basic/pages/css.js <ide> import React from 'react' <del>import { style } from 'next/css' <add>import style from 'next/css' <ide> <ide> export default () => <div className={styles}>This is red</div> <ide>
8
Java
Java
remove dead fallback code
0f36569d75b814a43b081d5a8036534fc1090d62
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/FreeMarkerConfigurerBeanDefinitionParser.java <ide> /* <del> * Copyright 2002-2018 the original author or authors. <add> * Copyright 2002-2021 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> protected void doParse(Element element, ParserContext parserContext, BeanDefinit <ide> for (Element childElement : childElements) { <ide> locations.add(childElement.getAttribute("location")); <ide> } <del> if (locations.isEmpty()) { <del> locations.add("/WEB-INF/"); <del> } <ide> builder.addPropertyValue("templateLoaderPaths", StringUtils.toStringArray(locations)); <ide> } <ide> }
1
Javascript
Javascript
use case insensitive compare
dd7ce6909709044d61e554727b80442047e01241
<ide><path>test/simple/test-require-resolve.js <ide> var fixturesDir = common.fixturesDir; <ide> var assert = require('assert'); <ide> var path = require('path'); <ide> <del>assert.equal(path.join(__dirname, '../fixtures/a.js'), <del> path.normalize(require.resolve('../fixtures/a'))); <del>assert.equal(path.join(fixturesDir, 'a.js'), <del> path.normalize(require.resolve(path.join(fixturesDir, 'a')))); <del>assert.equal(path.join(fixturesDir, 'nested-index', 'one', 'index.js'), <del> path.normalize(require.resolve('../fixtures/nested-index/one'))); <add>assert.equal( <add> path.join(__dirname, '../fixtures/a.js').toLowerCase(), <add> require.resolve('../fixtures/a').toLowerCase()); <add>assert.equal( <add> path.join(fixturesDir, 'a.js').toLowerCase(), <add> require.resolve(path.join(fixturesDir, 'a')).toLowerCase()); <add>assert.equal( <add> path.join(fixturesDir, 'nested-index', 'one', 'index.js').toLowerCase(), <add> require.resolve('../fixtures/nested-index/one').toLowerCase()); <ide> assert.equal('path', require.resolve('path')); <ide> <ide> console.log('ok');
1
Ruby
Ruby
avoid value_for_database if attribute not updated
98aa59a7f625c5ac8e7b1575f6692d78a8f5c328
<ide><path>activemodel/lib/active_model/attribute.rb <ide> def type_cast(value) <ide> type.deserialize(value) <ide> end <ide> <add> def forgetting_assignment <add> # If this attribute was not persisted (with a `value_for_database` <add> # that might differ from `value_before_type_cast`) and `value` has not <add> # changed in place, we can simply dup this attribute to avoid <add> # deserialize / cast / serialize calls from computing the new <add> # attribute's `value_before_type_cast`. <add> if !defined?(@value_for_database) && !changed_in_place? <add> dup <add> else <add> super <add> end <add> end <add> <ide> private <ide> def _original_value_for_database <ide> value_before_type_cast
1
Javascript
Javascript
convert controllers to es6 classes
6affaa2a73429da1a1b990ff1c726dc317148931
<ide><path>src/controllers/controller.bar.js <ide> function isFloatBar(custom) { <ide> return custom && custom.barStart !== undefined && custom.barEnd !== undefined; <ide> } <ide> <del>export default DatasetController.extend({ <add>class BarController extends DatasetController { <ide> <del> dataElementType: Rectangle, <del> <del> /** <del> * @private <del> */ <del> _dataElementOptions: [ <del> 'backgroundColor', <del> 'borderColor', <del> 'borderSkipped', <del> 'borderWidth', <del> 'barPercentage', <del> 'barThickness', <del> 'categoryPercentage', <del> 'maxBarThickness', <del> 'minBarLength' <del> ], <add> constructor(chart, datasetIndex) { <add> super(chart, datasetIndex); <add> } <ide> <ide> /** <ide> * Overriding primitive data parsing since we support mixed primitive/array <ide> * data for float bars <ide> * @private <ide> */ <del> _parsePrimitiveData: function() { <add> _parsePrimitiveData() { <ide> return parseArrayOrPrimitive.apply(this, arguments); <del> }, <add> } <ide> <ide> /** <ide> * Overriding array data parsing since we support mixed primitive/array <ide> * data for float bars <ide> * @private <ide> */ <del> _parseArrayData: function() { <add> _parseArrayData() { <ide> return parseArrayOrPrimitive.apply(this, arguments); <del> }, <add> } <ide> <ide> /** <ide> * Overriding object data parsing since we support mixed primitive/array <ide> * value-scale data for float bars <ide> * @private <ide> */ <del> _parseObjectData: function(meta, data, start, count) { <add> _parseObjectData(meta, data, start, count) { <ide> const {iScale, vScale} = meta; <ide> const vProp = vScale.axis; <ide> const parsed = []; <ide> export default DatasetController.extend({ <ide> parsed.push(item); <ide> } <ide> return parsed; <del> }, <add> } <ide> <ide> /** <ide> * @private <ide> */ <del> _getLabelAndValue: function(index) { <add> _getLabelAndValue(index) { <ide> const me = this; <ide> const meta = me._cachedMeta; <ide> const {iScale, vScale} = meta; <ide> export default DatasetController.extend({ <ide> label: '' + iScale.getLabelForValue(parsed[iScale.axis]), <ide> value: value <ide> }; <del> }, <add> } <ide> <del> initialize: function() { <add> initialize() { <ide> var me = this; <ide> var meta; <ide> <ide> export default DatasetController.extend({ <ide> meta = me._cachedMeta; <ide> meta.stack = me.getDataset().stack; <ide> meta.bar = true; <del> }, <add> } <ide> <del> update: function(mode) { <add> update(mode) { <ide> const me = this; <ide> const rects = me._cachedMeta.data; <ide> <ide> me.updateElements(rects, 0, mode); <del> }, <add> } <ide> <del> updateElements: function(rectangles, start, mode) { <add> updateElements(rectangles, start, mode) { <ide> const me = this; <ide> const reset = mode === 'reset'; <ide> const vscale = me._cachedMeta.vScale; <ide> export default DatasetController.extend({ <ide> } <ide> <ide> me._updateSharedOptions(sharedOptions, mode); <del> }, <add> } <ide> <ide> /** <ide> * Returns the stacks based on groups and bar visibility. <ide> * @param {number} [last] - The dataset index <ide> * @returns {string[]} The list of stack IDs <ide> * @private <ide> */ <del> _getStacks: function(last) { <add> _getStacks(last) { <ide> const me = this; <ide> const meta = me._cachedMeta; <ide> const iScale = meta.iScale; <ide> export default DatasetController.extend({ <ide> } <ide> <ide> return stacks; <del> }, <add> } <ide> <ide> /** <ide> * Returns the effective number of stacks based on groups and bar visibility. <ide> * @private <ide> */ <del> getStackCount: function() { <add> getStackCount() { <ide> return this._getStacks().length; <del> }, <add> } <ide> <ide> /** <ide> * Returns the stack index for the given dataset based on groups and bar visibility. <ide> export default DatasetController.extend({ <ide> * @returns {number} The stack index <ide> * @private <ide> */ <del> getStackIndex: function(datasetIndex, name) { <add> getStackIndex(datasetIndex, name) { <ide> var stacks = this._getStacks(datasetIndex); <ide> var index = (name !== undefined) <ide> ? stacks.indexOf(name) <ide> export default DatasetController.extend({ <ide> return (index === -1) <ide> ? stacks.length - 1 <ide> : index; <del> }, <add> } <ide> <ide> /** <ide> * @private <ide> */ <del> getRuler: function() { <add> getRuler() { <ide> const me = this; <ide> const meta = me._cachedMeta; <ide> const iScale = meta.iScale; <ide> export default DatasetController.extend({ <ide> stackCount: me.getStackCount(), <ide> scale: iScale <ide> }; <del> }, <add> } <ide> <ide> /** <ide> * Note: pixel values are not clamped to the scale area. <ide> * @private <ide> */ <del> calculateBarValuePixels: function(index, options) { <add> calculateBarValuePixels(index, options) { <ide> const me = this; <ide> const meta = me._cachedMeta; <ide> const vScale = meta.vScale; <ide> export default DatasetController.extend({ <ide> head: head, <ide> center: head + size / 2 <ide> }; <del> }, <add> } <ide> <ide> /** <ide> * @private <ide> */ <del> calculateBarIndexPixels: function(index, ruler, options) { <add> calculateBarIndexPixels(index, ruler, options) { <ide> var me = this; <ide> var range = options.barThickness === 'flex' <ide> ? computeFlexCategoryTraits(index, ruler, options) <ide> export default DatasetController.extend({ <ide> center: center, <ide> size: size <ide> }; <del> }, <add> } <ide> <del> draw: function() { <add> draw() { <ide> const me = this; <ide> const chart = me.chart; <ide> const meta = me._cachedMeta; <ide> export default DatasetController.extend({ <ide> unclipArea(chart.ctx); <ide> } <ide> <del>}); <add>} <add> <add>BarController.prototype.dataElementType = Rectangle; <add> <add>/** <add> * @private <add> */ <add>BarController.prototype._dataElementOptions = [ <add> 'backgroundColor', <add> 'borderColor', <add> 'borderSkipped', <add> 'borderWidth', <add> 'barPercentage', <add> 'barThickness', <add> 'categoryPercentage', <add> 'maxBarThickness', <add> 'minBarLength' <add>]; <add> <add>export default BarController; <ide><path>src/controllers/controller.bubble.js <ide> defaults._set('bubble', { <ide> } <ide> }); <ide> <del>export default DatasetController.extend({ <del> /** <del> * @protected <del> */ <del> dataElementType: Point, <add>class BubbleController extends DatasetController { <ide> <del> /** <del> * @private <del> */ <del> _dataElementOptions: [ <del> 'backgroundColor', <del> 'borderColor', <del> 'borderWidth', <del> 'hitRadius', <del> 'radius', <del> 'pointStyle', <del> 'rotation' <del> ], <add> constructor(chart, datasetIndex) { <add> super(chart, datasetIndex); <add> } <ide> <ide> /** <ide> * Parse array of objects <ide> * @private <ide> */ <del> _parseObjectData: function(meta, data, start, count) { <add> _parseObjectData(meta, data, start, count) { <ide> const {xScale, yScale} = meta; <ide> const parsed = []; <ide> let i, ilen, item; <ide> export default DatasetController.extend({ <ide> }); <ide> } <ide> return parsed; <del> }, <add> } <ide> <ide> /** <ide> * @private <ide> */ <del> _getMaxOverflow: function() { <add> _getMaxOverflow() { <ide> const me = this; <ide> const meta = me._cachedMeta; <ide> let i = (meta.data || []).length - 1; <ide> export default DatasetController.extend({ <ide> max = Math.max(max, me.getStyle(i, true).radius); <ide> } <ide> return max > 0 && max; <del> }, <add> } <ide> <ide> /** <ide> * @private <ide> */ <del> _getLabelAndValue: function(index) { <add> _getLabelAndValue(index) { <ide> const me = this; <ide> const meta = me._cachedMeta; <ide> const {xScale, yScale} = meta; <ide> export default DatasetController.extend({ <ide> label: meta.label, <ide> value: '(' + x + ', ' + y + (r ? ', ' + r : '') + ')' <ide> }; <del> }, <add> } <ide> <ide> /** <ide> * @protected <ide> */ <del> update: function(mode) { <add> update(mode) { <ide> const me = this; <ide> const points = me._cachedMeta.data; <ide> <ide> // Update Points <ide> me.updateElements(points, 0, mode); <del> }, <add> } <ide> <ide> /** <ide> * @protected <ide> */ <del> updateElements: function(points, start, mode) { <add> updateElements(points, start, mode) { <ide> const me = this; <ide> const reset = mode === 'reset'; <ide> const {xScale, yScale} = me._cachedMeta; <ide> export default DatasetController.extend({ <ide> } <ide> <ide> me._updateSharedOptions(sharedOptions, mode); <del> }, <add> } <ide> <ide> /** <ide> * @private <ide> */ <del> _resolveDataElementOptions: function(index, mode) { <add> _resolveDataElementOptions(index, mode) { <ide> var me = this; <ide> var chart = me.chart; <ide> var dataset = me.getDataset(); <ide> export default DatasetController.extend({ <ide> <ide> return values; <ide> } <del>}); <add>} <add> <add>/** <add> * @protected <add> */ <add>BubbleController.prototype.dataElementType = Point; <add> <add>/** <add> * @private <add> */ <add>BubbleController.prototype._dataElementOptions = [ <add> 'backgroundColor', <add> 'borderColor', <add> 'borderWidth', <add> 'hitRadius', <add> 'radius', <add> 'pointStyle', <add> 'rotation' <add>]; <add> <add> <add>export default BubbleController; <ide><path>src/controllers/controller.doughnut.js <ide> import DatasetController from '../core/core.datasetController'; <ide> import defaults from '../core/core.defaults'; <ide> import Arc from '../elements/element.arc'; <del>import {isArray, noop, valueOrDefault} from '../helpers/helpers.core'; <add>import {isArray, valueOrDefault} from '../helpers/helpers.core'; <ide> <ide> const PI = Math.PI; <ide> const DOUBLE_PI = PI * 2; <ide> defaults._set('doughnut', { <ide> } <ide> }); <ide> <del>export default DatasetController.extend({ <add>class DoughnutController extends DatasetController { <ide> <del> dataElementType: Arc, <del> <del> linkScales: noop, <add> constructor(chart, datasetIndex) { <add> super(chart, datasetIndex); <add> } <ide> <del> /** <del> * @private <del> */ <del> _dataElementOptions: [ <del> 'backgroundColor', <del> 'borderColor', <del> 'borderWidth', <del> 'borderAlign', <del> 'hoverBackgroundColor', <del> 'hoverBorderColor', <del> 'hoverBorderWidth', <del> ], <add> linkScales() {} <ide> <ide> /** <ide> * Override data parsing, since we are not using scales <ide> * @private <ide> */ <del> _parse: function(start, count) { <add> _parse(start, count) { <ide> var data = this.getDataset().data; <ide> var meta = this._cachedMeta; <ide> var i, ilen; <ide> for (i = start, ilen = start + count; i < ilen; ++i) { <ide> meta._parsed[i] = +data[i]; <ide> } <del> }, <add> } <ide> <ide> // Get index of the dataset in relation to the visible datasets. This allows determining the inner and outer radius correctly <del> getRingIndex: function(datasetIndex) { <add> getRingIndex(datasetIndex) { <ide> var ringIndex = 0; <ide> <ide> for (var j = 0; j < datasetIndex; ++j) { <ide> export default DatasetController.extend({ <ide> } <ide> <ide> return ringIndex; <del> }, <add> } <ide> <del> update: function(mode) { <add> update(mode) { <ide> var me = this; <ide> var chart = me.chart; <ide> var chartArea = chart.chartArea; <ide> export default DatasetController.extend({ <ide> me.innerRadius = Math.max(me.outerRadius - chart.radiusLength * chartWeight, 0); <ide> <ide> me.updateElements(arcs, 0, mode); <del> }, <add> } <ide> <ide> /** <ide> * @private <ide> */ <del> _circumference: function(i, reset) { <add> _circumference(i, reset) { <ide> const me = this; <ide> const opts = me.chart.options; <ide> const meta = me._cachedMeta; <ide> return reset && opts.animation.animateRotate ? 0 : meta.data[i].hidden ? 0 : me.calculateCircumference(meta._parsed[i] * opts.circumference / DOUBLE_PI); <del> }, <add> } <ide> <del> updateElements: function(arcs, start, mode) { <add> updateElements(arcs, start, mode) { <ide> const me = this; <ide> const reset = mode === 'reset'; <ide> const chart = me.chart; <ide> export default DatasetController.extend({ <ide> <ide> me._updateElement(arc, index, properties, mode); <ide> } <del> }, <add> } <ide> <del> calculateTotal: function() { <add> calculateTotal() { <ide> const meta = this._cachedMeta; <ide> const metaData = meta.data; <ide> let total = 0; <ide> export default DatasetController.extend({ <ide> }*/ <ide> <ide> return total; <del> }, <add> } <ide> <del> calculateCircumference: function(value) { <add> calculateCircumference(value) { <ide> var total = this._cachedMeta.total; <ide> if (total > 0 && !isNaN(value)) { <ide> return DOUBLE_PI * (Math.abs(value) / total); <ide> } <ide> return 0; <del> }, <add> } <ide> <ide> // gets the max border or hover width to properly scale pie charts <del> getMaxBorderWidth: function(arcs) { <add> getMaxBorderWidth(arcs) { <ide> var me = this; <ide> var max = 0; <ide> var chart = me.chart; <ide> export default DatasetController.extend({ <ide> } <ide> } <ide> return max; <del> }, <add> } <ide> <ide> /** <ide> * Get radius length offset of the dataset in relation to the visible datasets weights. This allows determining the inner and outer radius correctly <ide> * @private <ide> */ <del> _getRingWeightOffset: function(datasetIndex) { <add> _getRingWeightOffset(datasetIndex) { <ide> var ringWeightOffset = 0; <ide> <ide> for (var i = 0; i < datasetIndex; ++i) { <ide> export default DatasetController.extend({ <ide> } <ide> <ide> return ringWeightOffset; <del> }, <add> } <ide> <ide> /** <ide> * @private <ide> */ <del> _getRingWeight: function(dataSetIndex) { <add> _getRingWeight(dataSetIndex) { <ide> return Math.max(valueOrDefault(this.chart.data.datasets[dataSetIndex].weight, 1), 0); <del> }, <add> } <ide> <ide> /** <ide> * Returns the sum of all visibile data set weights. This value can be 0. <ide> * @private <ide> */ <del> _getVisibleDatasetWeightTotal: function() { <add> _getVisibleDatasetWeightTotal() { <ide> return this._getRingWeightOffset(this.chart.data.datasets.length); <ide> } <del>}); <add>} <add> <add>DoughnutController.prototype.dataElementType = Arc; <add> <add> <add>/** <add> * @private <add> */ <add>DoughnutController.prototype._dataElementOptions = [ <add> 'backgroundColor', <add> 'borderColor', <add> 'borderWidth', <add> 'borderAlign', <add> 'hoverBackgroundColor', <add> 'hoverBorderColor', <add> 'hoverBorderWidth', <add>]; <add> <add>export default DoughnutController; <ide><path>src/controllers/controller.horizontalBar.js <ide> defaults._set('horizontalBar', { <ide> } <ide> }); <ide> <del>export default BarController.extend({ <add>class HorizontalBarController extends BarController { <add> <add> constructor(chart, datasetIndex) { <add> super(chart, datasetIndex); <add> } <add> <ide> /** <ide> * @private <ide> */ <del> _getValueScaleId: function() { <add> _getValueScaleId() { <ide> return this._cachedMeta.xAxisID; <del> }, <add> } <ide> <ide> /** <ide> * @private <ide> */ <del> _getIndexScaleId: function() { <add> _getIndexScaleId() { <ide> return this._cachedMeta.yAxisID; <ide> } <del>}); <add>} <add> <add>export default HorizontalBarController; <ide><path>src/controllers/controller.line.js <ide> defaults._set('line', { <ide> } <ide> }); <ide> <del>export default DatasetController.extend({ <add>class LineController extends DatasetController { <ide> <del> datasetElementType: Line, <del> <del> dataElementType: Point, <del> <del> /** <del> * @private <del> */ <del> _datasetElementOptions: [ <del> 'backgroundColor', <del> 'borderCapStyle', <del> 'borderColor', <del> 'borderDash', <del> 'borderDashOffset', <del> 'borderJoinStyle', <del> 'borderWidth', <del> 'capBezierPoints', <del> 'cubicInterpolationMode', <del> 'fill' <del> ], <del> <del> /** <del> * @private <del> */ <del> _dataElementOptions: { <del> backgroundColor: 'pointBackgroundColor', <del> borderColor: 'pointBorderColor', <del> borderWidth: 'pointBorderWidth', <del> hitRadius: 'pointHitRadius', <del> hoverHitRadius: 'pointHitRadius', <del> hoverBackgroundColor: 'pointHoverBackgroundColor', <del> hoverBorderColor: 'pointHoverBorderColor', <del> hoverBorderWidth: 'pointHoverBorderWidth', <del> hoverRadius: 'pointHoverRadius', <del> pointStyle: 'pointStyle', <del> radius: 'pointRadius', <del> rotation: 'pointRotation' <del> }, <add> constructor(chart, datasetIndex) { <add> super(chart, datasetIndex); <add> } <ide> <del> update: function(mode) { <add> update(mode) { <ide> const me = this; <ide> const meta = me._cachedMeta; <ide> const line = meta.dataset; <ide> export default DatasetController.extend({ <ide> if (meta.visible) { <ide> me.updateElements(points, 0, mode); <ide> } <del> }, <add> } <ide> <del> updateElements: function(points, start, mode) { <add> updateElements(points, start, mode) { <ide> const me = this; <ide> const reset = mode === 'reset'; <ide> const {xScale, yScale, _stacked} = me._cachedMeta; <ide> export default DatasetController.extend({ <ide> } <ide> <ide> me._updateSharedOptions(sharedOptions, mode); <del> }, <add> } <ide> <ide> /** <ide> * @private <ide> */ <del> _resolveDatasetElementOptions: function() { <add> _resolveDatasetElementOptions() { <ide> const me = this; <ide> const config = me._config; <ide> const options = me.chart.options; <ide> export default DatasetController.extend({ <ide> values.steppedLine = resolve([config.steppedLine, lineOptions.stepped]); <ide> <ide> return values; <del> }, <add> } <ide> <ide> /** <ide> * @private <ide> */ <del> _getMaxOverflow: function() { <add> _getMaxOverflow() { <ide> const me = this; <ide> const meta = me._cachedMeta; <ide> const border = me._showLine && meta.dataset.options.borderWidth || 0; <ide> export default DatasetController.extend({ <ide> const firstPoint = data[0].size(); <ide> const lastPoint = data[data.length - 1].size(); <ide> return Math.max(border, firstPoint, lastPoint) / 2; <del> }, <add> } <ide> <del> draw: function() { <add> draw() { <ide> const me = this; <ide> const ctx = me._ctx; <ide> const chart = me.chart; <ide> export default DatasetController.extend({ <ide> for (i = 0, ilen = active.length; i < ilen; ++i) { <ide> active[i].draw(ctx, area); <ide> } <del> }, <del>}); <add> } <add>} <add> <add>LineController.prototype.datasetElementType = Line; <add> <add>LineController.prototype.dataElementType = Point; <add> <add>/** <add> * @private <add> */ <add>LineController.prototype._datasetElementOptions = [ <add> 'backgroundColor', <add> 'borderCapStyle', <add> 'borderColor', <add> 'borderDash', <add> 'borderDashOffset', <add> 'borderJoinStyle', <add> 'borderWidth', <add> 'capBezierPoints', <add> 'cubicInterpolationMode', <add> 'fill' <add>]; <add> <add>/** <add> * @private <add> */ <add>LineController.prototype._dataElementOptions = { <add> backgroundColor: 'pointBackgroundColor', <add> borderColor: 'pointBorderColor', <add> borderWidth: 'pointBorderWidth', <add> hitRadius: 'pointHitRadius', <add> hoverHitRadius: 'pointHitRadius', <add> hoverBackgroundColor: 'pointHoverBackgroundColor', <add> hoverBorderColor: 'pointHoverBorderColor', <add> hoverBorderWidth: 'pointHoverBorderWidth', <add> hoverRadius: 'pointHoverRadius', <add> pointStyle: 'pointStyle', <add> radius: 'pointRadius', <add> rotation: 'pointRotation' <add>}; <add> <add>export default LineController; <ide><path>src/controllers/controller.polarArea.js <ide> function getStartAngleRadians(deg) { <ide> return toRadians(deg) - 0.5 * Math.PI; <ide> } <ide> <del>export default DatasetController.extend({ <add>class PolarAreaController extends DatasetController { <ide> <del> dataElementType: Arc, <del> <del> /** <del> * @private <del> */ <del> _dataElementOptions: [ <del> 'backgroundColor', <del> 'borderColor', <del> 'borderWidth', <del> 'borderAlign', <del> 'hoverBackgroundColor', <del> 'hoverBorderColor', <del> 'hoverBorderWidth', <del> ], <add> constructor(chart, datasetIndex) { <add> super(chart, datasetIndex); <add> } <ide> <ide> /** <ide> * @private <ide> */ <del> _getIndexScaleId: function() { <add> _getIndexScaleId() { <ide> return this._cachedMeta.rAxisID; <del> }, <add> } <ide> <ide> /** <ide> * @private <ide> */ <del> _getValueScaleId: function() { <add> _getValueScaleId() { <ide> return this._cachedMeta.rAxisID; <del> }, <add> } <ide> <del> update: function(mode) { <add> update(mode) { <ide> const arcs = this._cachedMeta.data; <ide> <ide> this._updateRadius(); <ide> this.updateElements(arcs, 0, mode); <del> }, <add> } <ide> <ide> /** <ide> * @private <ide> */ <del> _updateRadius: function() { <add> _updateRadius() { <ide> var me = this; <ide> var chart = me.chart; <ide> var chartArea = chart.chartArea; <ide> export default DatasetController.extend({ <ide> <ide> me.outerRadius = chart.outerRadius - (chart.radiusLength * me.index); <ide> me.innerRadius = me.outerRadius - chart.radiusLength; <del> }, <add> } <ide> <del> updateElements: function(arcs, start, mode) { <add> updateElements(arcs, start, mode) { <ide> const me = this; <ide> const reset = mode === 'reset'; <ide> const chart = me.chart; <ide> export default DatasetController.extend({ <ide> <ide> me._updateElement(arc, index, properties, mode); <ide> } <del> }, <add> } <ide> <del> countVisibleElements: function() { <add> countVisibleElements() { <ide> var dataset = this.getDataset(); <ide> var meta = this._cachedMeta; <ide> var count = 0; <ide> export default DatasetController.extend({ <ide> }); <ide> <ide> return count; <del> }, <add> } <ide> <ide> /** <ide> * @private <ide> */ <del> _computeAngle: function(index) { <add> _computeAngle(index) { <ide> var me = this; <ide> var meta = me._cachedMeta; <ide> var count = meta.count; <ide> export default DatasetController.extend({ <ide> (2 * Math.PI) / count <ide> ], context, index); <ide> } <del>}); <add>} <add> <add>PolarAreaController.prototype.dataElementType = Arc; <add> <add>/** <add> * @private <add> */ <add>PolarAreaController.prototype._dataElementOptions = [ <add> 'backgroundColor', <add> 'borderColor', <add> 'borderWidth', <add> 'borderAlign', <add> 'hoverBackgroundColor', <add> 'hoverBorderColor', <add> 'hoverBorderWidth' <add>]; <add> <add>export default PolarAreaController; <ide><path>src/controllers/controller.radar.js <ide> defaults._set('radar', { <ide> } <ide> }); <ide> <del>export default DatasetController.extend({ <del> datasetElementType: Line, <add>class RadarController extends DatasetController { <ide> <del> dataElementType: Point, <del> <del> /** <del> * @private <del> */ <del> _datasetElementOptions: [ <del> 'backgroundColor', <del> 'borderWidth', <del> 'borderColor', <del> 'borderCapStyle', <del> 'borderDash', <del> 'borderDashOffset', <del> 'borderJoinStyle', <del> 'fill' <del> ], <del> <del> /** <del> * @private <del> */ <del> _dataElementOptions: { <del> backgroundColor: 'pointBackgroundColor', <del> borderColor: 'pointBorderColor', <del> borderWidth: 'pointBorderWidth', <del> hitRadius: 'pointHitRadius', <del> hoverBackgroundColor: 'pointHoverBackgroundColor', <del> hoverBorderColor: 'pointHoverBorderColor', <del> hoverBorderWidth: 'pointHoverBorderWidth', <del> hoverRadius: 'pointHoverRadius', <del> pointStyle: 'pointStyle', <del> radius: 'pointRadius', <del> rotation: 'pointRotation' <del> }, <add> constructor(chart, datasetIndex) { <add> super(chart, datasetIndex); <add> } <ide> <ide> /** <ide> * @private <ide> */ <del> _getIndexScaleId: function() { <add> _getIndexScaleId() { <ide> return this._cachedMeta.rAxisID; <del> }, <add> } <ide> <ide> /** <ide> * @private <ide> */ <del> _getValueScaleId: function() { <add> _getValueScaleId() { <ide> return this._cachedMeta.rAxisID; <del> }, <add> } <ide> <ide> /** <ide> * @private <ide> */ <del> _getLabelAndValue: function(index) { <add> _getLabelAndValue(index) { <ide> const me = this; <ide> const vScale = me._cachedMeta.vScale; <ide> const parsed = me._getParsed(index); <ide> export default DatasetController.extend({ <ide> label: vScale._getLabels()[index], <ide> value: '' + vScale.getLabelForValue(parsed[vScale.axis]) <ide> }; <del> }, <add> } <ide> <del> update: function(mode) { <add> update(mode) { <ide> const me = this; <ide> const meta = me._cachedMeta; <ide> const line = meta.dataset; <ide> export default DatasetController.extend({ <ide> me.updateElements(points, 0, mode); <ide> <ide> line.updateControlPoints(me.chart.chartArea); <del> }, <add> } <ide> <del> updateElements: function(points, start, mode) { <add> updateElements(points, start, mode) { <ide> const me = this; <ide> const dataset = me.getDataset(); <ide> const scale = me.chart.scales.r; <ide> export default DatasetController.extend({ <ide> <ide> me._updateElement(point, index, properties, mode); <ide> } <del> }, <add> } <ide> <ide> /** <ide> * @private <ide> */ <del> _resolveDatasetElementOptions: function() { <add> _resolveDatasetElementOptions() { <ide> const me = this; <ide> const config = me._config; <ide> const options = me.chart.options; <ide> export default DatasetController.extend({ <ide> <ide> return values; <ide> } <del>}); <add>} <add> <add>RadarController.prototype.datasetElementType = Line; <add> <add>RadarController.prototype.dataElementType = Point; <add> <add>/** <add> * @private <add> */ <add>RadarController.prototype._datasetElementOptions = [ <add> 'backgroundColor', <add> 'borderWidth', <add> 'borderColor', <add> 'borderCapStyle', <add> 'borderDash', <add> 'borderDashOffset', <add> 'borderJoinStyle', <add> 'fill' <add>]; <add> <add>/** <add> * @private <add> */ <add>RadarController.prototype._dataElementOptions = { <add> backgroundColor: 'pointBackgroundColor', <add> borderColor: 'pointBorderColor', <add> borderWidth: 'pointBorderWidth', <add> hitRadius: 'pointHitRadius', <add> hoverBackgroundColor: 'pointHoverBackgroundColor', <add> hoverBorderColor: 'pointHoverBorderColor', <add> hoverBorderWidth: 'pointHoverBorderWidth', <add> hoverRadius: 'pointHoverRadius', <add> pointStyle: 'pointStyle', <add> radius: 'pointRadius', <add> rotation: 'pointRotation' <add>}; <add> <add>export default RadarController;
7
PHP
PHP
add comment. fix formatting
7612009667db1b7796a3525ce8614ccec38def53
<ide><path>src/Illuminate/Database/Query/Builder.php <ide> public function aggregate($function, $columns = ['*']) <ide> $this->aggregate = compact('function', 'columns'); <ide> <ide> $previousColumns = $this->columns; <add> <add> // We will also back up the select bindings since the select clause will be <add> // removed when performing the aggregate function. Once the query is run <add> // we will add the bindings back onto this query so they can get used. <ide> $previousSelectBindings = $this->bindings['select']; <add> <ide> $this->bindings['select'] = []; <ide> <ide> $results = $this->get($columns); <ide> public function aggregate($function, $columns = ['*']) <ide> $this->aggregate = null; <ide> <ide> $this->columns = $previousColumns; <add> <ide> $this->bindings['select'] = $previousSelectBindings; <ide> <ide> if (isset($results[0])) {
1
Go
Go
update integration test with assert
c6b02ad73b545cedeb53715b2d7b22a2354722f8
<ide><path>integration-cli/docker_cli_rmi_test.go <ide> import ( <ide> "os/exec" <ide> "strings" <ide> <add> "github.com/docker/docker/pkg/integration/checker" <ide> "github.com/go-check/check" <ide> ) <ide> <ide> func (s *DockerSuite) TestRmiWithContainerFails(c *check.C) { <ide> errSubstr := "is using it" <ide> <ide> // create a container <del> out, _, err := dockerCmdWithError("run", "-d", "busybox", "true") <del> if err != nil { <del> c.Fatalf("failed to create a container: %s, %v", out, err) <del> } <add> out, _ := dockerCmd(c, "run", "-d", "busybox", "true") <ide> <ide> cleanedContainerID := strings.TrimSpace(out) <ide> <ide> // try to delete the image <del> out, _, err = dockerCmdWithError("rmi", "busybox") <del> if err == nil { <del> c.Fatalf("Container %q is using image, should not be able to rmi: %q", cleanedContainerID, out) <del> } <del> if !strings.Contains(out, errSubstr) { <del> c.Fatalf("Container %q is using image, error message should contain %q: %v", cleanedContainerID, errSubstr, out) <del> } <add> out, _, err := dockerCmdWithError("rmi", "busybox") <add> // Container is using image, should not be able to rmi <add> c.Assert(err, checker.NotNil) <add> // Container is using image, error message should contain errSubstr <add> c.Assert(out, checker.Contains, errSubstr, check.Commentf("Container: %q", cleanedContainerID)) <ide> <ide> // make sure it didn't delete the busybox name <ide> images, _ := dockerCmd(c, "images") <del> if !strings.Contains(images, "busybox") { <del> c.Fatalf("The name 'busybox' should not have been removed from images: %q", images) <del> } <add> // The name 'busybox' should not have been removed from images <add> c.Assert(images, checker.Contains, "busybox") <ide> } <ide> <ide> func (s *DockerSuite) TestRmiTag(c *check.C) { <ide> func (s *DockerSuite) TestRmiTag(c *check.C) { <ide> dockerCmd(c, "tag", "busybox", "utest:5000/docker:tag3") <ide> { <ide> imagesAfter, _ := dockerCmd(c, "images", "-a") <del> if strings.Count(imagesAfter, "\n") != strings.Count(imagesBefore, "\n")+3 { <del> c.Fatalf("before: %q\n\nafter: %q\n", imagesBefore, imagesAfter) <del> } <add> c.Assert(strings.Count(imagesAfter, "\n"), checker.Equals, strings.Count(imagesBefore, "\n")+3, check.Commentf("before: %q\n\nafter: %q\n", imagesBefore, imagesAfter)) <ide> } <ide> dockerCmd(c, "rmi", "utest/docker:tag2") <ide> { <ide> imagesAfter, _ := dockerCmd(c, "images", "-a") <del> if strings.Count(imagesAfter, "\n") != strings.Count(imagesBefore, "\n")+2 { <del> c.Fatalf("before: %q\n\nafter: %q\n", imagesBefore, imagesAfter) <del> } <del> <add> c.Assert(strings.Count(imagesAfter, "\n"), checker.Equals, strings.Count(imagesBefore, "\n")+2, check.Commentf("before: %q\n\nafter: %q\n", imagesBefore, imagesAfter)) <ide> } <ide> dockerCmd(c, "rmi", "utest:5000/docker:tag3") <ide> { <ide> imagesAfter, _ := dockerCmd(c, "images", "-a") <del> if strings.Count(imagesAfter, "\n") != strings.Count(imagesBefore, "\n")+1 { <del> c.Fatalf("before: %q\n\nafter: %q\n", imagesBefore, imagesAfter) <del> } <add> c.Assert(strings.Count(imagesAfter, "\n"), checker.Equals, strings.Count(imagesBefore, "\n")+1, check.Commentf("before: %q\n\nafter: %q\n", imagesBefore, imagesAfter)) <ide> <ide> } <ide> dockerCmd(c, "rmi", "utest:tag1") <ide> { <ide> imagesAfter, _ := dockerCmd(c, "images", "-a") <del> if strings.Count(imagesAfter, "\n") != strings.Count(imagesBefore, "\n")+0 { <del> c.Fatalf("before: %q\n\nafter: %q\n", imagesBefore, imagesAfter) <del> } <add> c.Assert(strings.Count(imagesAfter, "\n"), checker.Equals, strings.Count(imagesBefore, "\n"), check.Commentf("before: %q\n\nafter: %q\n", imagesBefore, imagesAfter)) <ide> <ide> } <ide> } <ide> <ide> func (s *DockerSuite) TestRmiImgIDMultipleTag(c *check.C) { <ide> testRequires(c, DaemonIsLinux) <del> out, _, err := dockerCmdWithError("run", "-d", "busybox", "/bin/sh", "-c", "mkdir '/busybox-one'") <del> if err != nil { <del> c.Fatalf("failed to create a container:%s, %v", out, err) <del> } <add> out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "mkdir '/busybox-one'") <ide> <ide> containerID := strings.TrimSpace(out) <del> out, _, err = dockerCmdWithError("commit", containerID, "busybox-one") <del> if err != nil { <del> c.Fatalf("failed to commit a new busybox-one:%s, %v", out, err) <del> } <add> dockerCmd(c, "commit", containerID, "busybox-one") <ide> <ide> imagesBefore, _ := dockerCmd(c, "images", "-a") <ide> dockerCmd(c, "tag", "busybox-one", "busybox-one:tag1") <ide> dockerCmd(c, "tag", "busybox-one", "busybox-one:tag2") <ide> <ide> imagesAfter, _ := dockerCmd(c, "images", "-a") <del> if strings.Count(imagesAfter, "\n") != strings.Count(imagesBefore, "\n")+2 { <del> c.Fatalf("tag busybox to create 2 more images with same imageID; docker images shows: %q\n", imagesAfter) <del> } <add> // tag busybox to create 2 more images with same imageID <add> c.Assert(strings.Count(imagesAfter, "\n"), checker.Equals, strings.Count(imagesBefore, "\n")+2, check.Commentf("docker images shows: %q\n", imagesAfter)) <ide> <ide> imgID, err := inspectField("busybox-one:tag1", "Id") <del> c.Assert(err, check.IsNil) <add> c.Assert(err, checker.IsNil) <ide> <ide> // run a container with the image <del> out, _, err = dockerCmdWithError("run", "-d", "busybox-one", "top") <del> if err != nil { <del> c.Fatalf("failed to create a container:%s, %v", out, err) <del> } <add> out, _ = dockerCmd(c, "run", "-d", "busybox-one", "top") <ide> <ide> containerID = strings.TrimSpace(out) <ide> <ide> // first checkout without force it fails <ide> out, _, err = dockerCmdWithError("rmi", imgID) <ide> expected := fmt.Sprintf("conflict: unable to delete %s (cannot be forced) - image is being used by running container %s", imgID[:12], containerID[:12]) <del> if err == nil || !strings.Contains(out, expected) { <del> c.Fatalf("rmi tagged in multiple repos should have failed without force: %s, %v, expected: %s", out, err, expected) <del> } <add> // rmi tagged in multiple repos should have failed without force <add> c.Assert(err, checker.NotNil) <add> c.Assert(out, checker.Contains, expected) <ide> <ide> dockerCmd(c, "stop", containerID) <ide> dockerCmd(c, "rmi", "-f", imgID) <ide> <ide> imagesAfter, _ = dockerCmd(c, "images", "-a") <del> if strings.Contains(imagesAfter, imgID[:12]) { <del> c.Fatalf("rmi -f %s failed, image still exists: %q\n\n", imgID, imagesAfter) <del> } <add> // rmi -f failed, image still exists <add> c.Assert(imagesAfter, checker.Not(checker.Contains), imgID[:12], check.Commentf("ImageID:%q; ImagesAfter: %q", imgID, imagesAfter)) <ide> } <ide> <ide> func (s *DockerSuite) TestRmiImgIDForce(c *check.C) { <ide> testRequires(c, DaemonIsLinux) <del> out, _, err := dockerCmdWithError("run", "-d", "busybox", "/bin/sh", "-c", "mkdir '/busybox-test'") <del> if err != nil { <del> c.Fatalf("failed to create a container:%s, %v", out, err) <del> } <add> out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "mkdir '/busybox-test'") <ide> <ide> containerID := strings.TrimSpace(out) <del> out, _, err = dockerCmdWithError("commit", containerID, "busybox-test") <del> if err != nil { <del> c.Fatalf("failed to commit a new busybox-test:%s, %v", out, err) <del> } <add> dockerCmd(c, "commit", containerID, "busybox-test") <ide> <ide> imagesBefore, _ := dockerCmd(c, "images", "-a") <ide> dockerCmd(c, "tag", "busybox-test", "utest:tag1") <ide> func (s *DockerSuite) TestRmiImgIDForce(c *check.C) { <ide> dockerCmd(c, "tag", "busybox-test", "utest:5000/docker:tag4") <ide> { <ide> imagesAfter, _ := dockerCmd(c, "images", "-a") <del> if strings.Count(imagesAfter, "\n") != strings.Count(imagesBefore, "\n")+4 { <del> c.Fatalf("tag busybox to create 4 more images with same imageID; docker images shows: %q\n", imagesAfter) <del> } <add> c.Assert(strings.Count(imagesAfter, "\n"), checker.Equals, strings.Count(imagesBefore, "\n")+4, check.Commentf("before: %q\n\nafter: %q\n", imagesBefore, imagesAfter)) <ide> } <ide> imgID, err := inspectField("busybox-test", "Id") <del> c.Assert(err, check.IsNil) <add> c.Assert(err, checker.IsNil) <ide> <ide> // first checkout without force it fails <ide> out, _, err = dockerCmdWithError("rmi", imgID) <del> if err == nil || !strings.Contains(out, "(must be forced) - image is referenced in one or more repositories") { <del> c.Fatalf("rmi tagged in multiple repos should have failed without force:%s, %v", out, err) <del> } <add> // rmi tagged in multiple repos should have failed without force <add> c.Assert(err, checker.NotNil) <add> // rmi tagged in multiple repos should have failed without force <add> c.Assert(out, checker.Contains, "(must be forced) - image is referenced in one or more repositories", check.Commentf("out: %s; err: %v;", out, err)) <ide> <ide> dockerCmd(c, "rmi", "-f", imgID) <ide> { <ide> imagesAfter, _ := dockerCmd(c, "images", "-a") <del> if strings.Contains(imagesAfter, imgID[:12]) { <del> c.Fatalf("rmi -f %s failed, image still exists: %q\n\n", imgID, imagesAfter) <del> } <add> // rmi failed, image still exists <add> c.Assert(imagesAfter, checker.Not(checker.Contains), imgID[:12]) <ide> } <ide> } <ide> <ide> func (s *DockerSuite) TestRmiImageIDForceWithRunningContainersAndMultipleTags(c <ide> testRequires(c, DaemonIsLinux) <ide> dockerfile := "FROM busybox\nRUN echo test 14116\n" <ide> imgID, err := buildImage("test-14116", dockerfile, false) <del> c.Assert(err, check.IsNil) <add> c.Assert(err, checker.IsNil) <ide> <ide> newTag := "newtag" <ide> dockerCmd(c, "tag", imgID, newTag) <ide> dockerCmd(c, "run", "-d", imgID, "top") <ide> <ide> out, _, err := dockerCmdWithError("rmi", "-f", imgID) <del> if err == nil || !strings.Contains(out, "(cannot be forced) - image is being used by running container") { <del> c.Log(out) <del> c.Fatalf("rmi -f should not delete image with running containers") <del> } <add> // rmi -f should not delete image with running containers <add> c.Assert(err, checker.NotNil) <add> c.Assert(out, checker.Contains, "(cannot be forced) - image is being used by running container") <ide> } <ide> <ide> func (s *DockerSuite) TestRmiTagWithExistingContainers(c *check.C) { <ide> testRequires(c, DaemonIsLinux) <ide> container := "test-delete-tag" <ide> newtag := "busybox:newtag" <ide> bb := "busybox:latest" <del> if out, _, err := dockerCmdWithError("tag", bb, newtag); err != nil { <del> c.Fatalf("Could not tag busybox: %v: %s", err, out) <del> } <del> if out, _, err := dockerCmdWithError("run", "--name", container, bb, "/bin/true"); err != nil { <del> c.Fatalf("Could not run busybox: %v: %s", err, out) <del> } <del> out, _, err := dockerCmdWithError("rmi", newtag) <del> if err != nil { <del> c.Fatalf("Could not remove tag %s: %v: %s", newtag, err, out) <del> } <del> if d := strings.Count(out, "Untagged: "); d != 1 { <del> c.Fatalf("Expected 1 untagged entry got %d: %q", d, out) <del> } <add> dockerCmd(c, "tag", bb, newtag) <add> <add> dockerCmd(c, "run", "--name", container, bb, "/bin/true") <add> <add> out, _ := dockerCmd(c, "rmi", newtag) <add> c.Assert(strings.Count(out, "Untagged: "), checker.Equals, 1) <ide> } <ide> <ide> func (s *DockerSuite) TestRmiForceWithExistingContainers(c *check.C) { <ide> func (s *DockerSuite) TestRmiForceWithExistingContainers(c *check.C) { <ide> cmd.Stdin = strings.NewReader(`FROM busybox <ide> MAINTAINER foo`) <ide> <del> if out, _, err := runCommandWithOutput(cmd); err != nil { <del> c.Fatalf("Could not build %s: %s, %v", image, out, err) <del> } <add> out, _, err := runCommandWithOutput(cmd) <add> c.Assert(err, checker.IsNil, check.Commentf("Could not build %s: %s", image, out)) <ide> <del> if out, _, err := dockerCmdWithError("run", "--name", "test-force-rmi", image, "/bin/true"); err != nil { <del> c.Fatalf("Could not run container: %s, %v", out, err) <del> } <add> dockerCmd(c, "run", "--name", "test-force-rmi", image, "/bin/true") <ide> <del> if out, _, err := dockerCmdWithError("rmi", "-f", image); err != nil { <del> c.Fatalf("Could not remove image %s: %s, %v", image, out, err) <del> } <add> dockerCmd(c, "rmi", "-f", image) <ide> } <ide> <ide> func (s *DockerSuite) TestRmiWithMultipleRepositories(c *check.C) { <ide> testRequires(c, DaemonIsLinux) <ide> newRepo := "127.0.0.1:5000/busybox" <ide> oldRepo := "busybox" <ide> newTag := "busybox:test" <del> out, _, err := dockerCmdWithError("tag", oldRepo, newRepo) <del> if err != nil { <del> c.Fatalf("Could not tag busybox: %v: %s", err, out) <del> } <add> dockerCmd(c, "tag", oldRepo, newRepo) <ide> <del> out, _, err = dockerCmdWithError("run", "--name", "test", oldRepo, "touch", "/home/abcd") <del> if err != nil { <del> c.Fatalf("failed to run container: %v, output: %s", err, out) <del> } <add> dockerCmd(c, "run", "--name", "test", oldRepo, "touch", "/home/abcd") <ide> <del> out, _, err = dockerCmdWithError("commit", "test", newTag) <del> if err != nil { <del> c.Fatalf("failed to commit container: %v, output: %s", err, out) <del> } <add> dockerCmd(c, "commit", "test", newTag) <ide> <del> out, _, err = dockerCmdWithError("rmi", newTag) <del> if err != nil { <del> c.Fatalf("failed to remove image: %v, output: %s", err, out) <del> } <del> if !strings.Contains(out, "Untagged: "+newTag) { <del> c.Fatalf("Could not remove image %s: %s, %v", newTag, out, err) <del> } <add> out, _ := dockerCmd(c, "rmi", newTag) <add> c.Assert(out, checker.Contains, "Untagged: "+newTag) <ide> } <ide> <ide> func (s *DockerSuite) TestRmiBlank(c *check.C) { <ide> testRequires(c, DaemonIsLinux) <ide> // try to delete a blank image name <ide> out, _, err := dockerCmdWithError("rmi", "") <del> if err == nil { <del> c.Fatal("Should have failed to delete '' image") <del> } <del> if strings.Contains(out, "no such id") { <del> c.Fatalf("Wrong error message generated: %s", out) <del> } <del> if !strings.Contains(out, "image name cannot be blank") { <del> c.Fatalf("Expected error message not generated: %s", out) <del> } <add> // Should have failed to delete '' image <add> c.Assert(err, checker.NotNil) <add> // Wrong error message generated <add> c.Assert(out, checker.Not(checker.Contains), "no such id", check.Commentf("out: %s", out)) <add> // Expected error message not generated <add> c.Assert(out, checker.Contains, "image name cannot be blank", check.Commentf("out: %s", out)) <ide> <ide> out, _, err = dockerCmdWithError("rmi", " ") <del> if err == nil { <del> c.Fatal("Should have failed to delete '' image") <del> } <del> if !strings.Contains(out, "no such id") { <del> c.Fatalf("Expected error message not generated: %s", out) <del> } <add> // Should have failed to delete '' image <add> c.Assert(err, checker.NotNil) <add> // Expected error message not generated <add> c.Assert(out, checker.Contains, "no such id", check.Commentf("out: %s", out)) <ide> } <ide> <ide> func (s *DockerSuite) TestRmiContainerImageNotFound(c *check.C) { <ide> func (s *DockerSuite) TestRmiContainerImageNotFound(c *check.C) { <ide> for i, name := range imageNames { <ide> dockerfile := fmt.Sprintf("FROM busybox\nMAINTAINER %s\nRUN echo %s\n", name, name) <ide> id, err := buildImage(name, dockerfile, false) <del> c.Assert(err, check.IsNil) <add> c.Assert(err, checker.IsNil) <ide> imageIds[i] = id <ide> } <ide> <ide> func (s *DockerSuite) TestRmiContainerImageNotFound(c *check.C) { <ide> <ide> // Try to remove the image of the running container and see if it fails as expected. <ide> out, _, err := dockerCmdWithError("rmi", "-f", imageIds[0]) <del> if err == nil || !strings.Contains(out, "image is being used by running container") { <del> c.Log(out) <del> c.Fatal("The image of the running container should not be removed.") <del> } <add> // The image of the running container should not be removed. <add> c.Assert(err, checker.NotNil) <add> c.Assert(out, checker.Contains, "image is being used by running container", check.Commentf("out: %s", out)) <ide> } <ide> <ide> // #13422 <ide> RUN echo 1 #layer1 <ide> RUN echo 2 #layer2 <ide> ` <ide> _, err := buildImage(image, dockerfile, false) <del> c.Assert(err, check.IsNil) <add> c.Assert(err, checker.IsNil) <ide> <ide> out, _ := dockerCmd(c, "history", "-q", image) <ide> ids := strings.Split(out, "\n") <ide> RUN echo 2 #layer2 <ide> <ide> // See if the "tmp2" can be untagged. <ide> out, _ = dockerCmd(c, "rmi", newTag) <del> if d := strings.Count(out, "Untagged: "); d != 1 { <del> c.Log(out) <del> c.Fatalf("Expected 1 untagged entry got %d: %q", d, out) <del> } <add> // Expected 1 untagged entry <add> c.Assert(strings.Count(out, "Untagged: "), checker.Equals, 1, check.Commentf("out: %s", out)) <ide> <ide> // Now let's add the tag again and create a container based on it. <ide> dockerCmd(c, "tag", idToTag, newTag) <ide> RUN echo 2 #layer2 <ide> // At this point we have 2 containers, one based on layer2 and another based on layer0. <ide> // Try to untag "tmp2" without the -f flag. <ide> out, _, err = dockerCmdWithError("rmi", newTag) <del> if err == nil || !strings.Contains(out, cid[:12]) || !strings.Contains(out, "(must force)") { <del> c.Log(out) <del> c.Fatalf("%q should not be untagged without the -f flag", newTag) <del> } <add> // should not be untagged without the -f flag <add> c.Assert(err, checker.NotNil) <add> c.Assert(out, checker.Contains, cid[:12]) <add> c.Assert(out, checker.Contains, "(must force)") <ide> <ide> // Add the -f flag and test again. <ide> out, _ = dockerCmd(c, "rmi", "-f", newTag) <del> if !strings.Contains(out, fmt.Sprintf("Untagged: %s:latest", newTag)) { <del> c.Log(out) <del> c.Fatalf("%q should be allowed to untag with the -f flag", newTag) <del> } <add> // should be allowed to untag with the -f flag <add> c.Assert(out, checker.Contains, fmt.Sprintf("Untagged: %s:latest", newTag)) <ide> }
1
PHP
PHP
add dirname test
b1d86bde040d418f995b6cf920c671275a979a89
<ide><path>tests/Support/SupportStringableTest.php <ide> public function testWhenContainsAll() <ide> return $stringable->studly(); <ide> })); <ide> } <add> <add> public function testDirname() <add> { <add> $this->assertSame('/framework/tests', (string) $this->stringable('/framework/tests/Support')->dirname()); <add> $this->assertSame('/framework', (string) $this->stringable('/framework/tests/Support')->dirname(2)); <add> <add> $this->assertSame('/', (string) $this->stringable('/framework/')->dirname()); <add> <add> $this->assertSame('/', (string) $this->stringable('/')->dirname()); <add> $this->assertSame('.', (string) $this->stringable('.')->dirname()); <add> <add> // without slash <add> $this->assertSame('.', (string) $this->stringable('framework')->dirname()); <add> } <ide> <ide> public function testUcsplitOnStringable() <ide> {
1
Ruby
Ruby
explain edge case in install/cmd
0afc41ceefcf2b69443287f12a45bb7d2c2c35e3
<ide><path>Library/Homebrew/cmd/install.rb <ide> def install <ide> return <ide> end <ide> <add> # We don't seem to get good search results when the tap is specified <add> # so we might as well return early. <ide> return if name.include?("/") <ide> <ide> ohai "Searching for similarly named formulae and casks..."
1
Python
Python
remove custom asynchookstestconfiguration
3a056c04090ae58bef7ed8af9abf68228d8ff41a
<ide><path>test/async-hooks/testcfg.py <ide> import testpy <ide> <ide> def GetConfiguration(context, root): <del> return testpy.AsyncHooksTestConfiguration(context, root, 'async-hooks') <add> return testpy.ParallelTestConfiguration(context, root, 'async-hooks') <ide><path>test/testpy/__init__.py <ide> def ListTests(self, current_path, path, arch, mode): <ide> SimpleTestCase(test, file_path, arch, mode, self.context, self, self.additional_flags)) <ide> return result <ide> <del>class AsyncHooksTestConfiguration(SimpleTestConfiguration): <del> def __init__(self, context, root, section, additional=None): <del> super(AsyncHooksTestConfiguration, self).__init__(context, root, section, <del> additional) <del> <del> def ListTests(self, current_path, path, arch, mode): <del> result = super(AsyncHooksTestConfiguration, self).ListTests( <del> current_path, path, arch, mode) <del> for test in result: <del> test.parallel = True <del> return result <del> <ide> class AbortTestConfiguration(SimpleTestConfiguration): <ide> def __init__(self, context, root, section, additional=None): <ide> super(AbortTestConfiguration, self).__init__(context, root, section,
2
Python
Python
copy smalloc.h on installation
d3204b0225f9087cf419c69abeab7d1586e6af5d
<ide><path>tools/install.py <ide> def files(action): <ide> 'src/node_internals.h', <ide> 'src/node_object_wrap.h', <ide> 'src/node_version.h', <add> 'src/smalloc.h', <ide> ], 'include/node/') <ide> <ide> if 'false' == variables.get('node_shared_cares'):
1
Javascript
Javascript
fix handleless node_handle handling
71ca122def15ae58584ea680399e3d049e172365
<ide><path>lib/internal/child_process.js <ide> const errnoException = util._errnoException; <ide> const SocketListSend = SocketList.SocketListSend; <ide> const SocketListReceive = SocketList.SocketListReceive; <ide> <add>const MAX_HANDLE_RETRANSMISSIONS = 3; <add> <ide> // this object contain function to convert TCP objects to native handle objects <ide> // and back again. <ide> const handleConversion = { <ide> const handleConversion = { <ide> return handle; <ide> }, <ide> <del> postSend: function(handle, options, target) { <add> postSend: function(message, handle, options, callback, target) { <ide> // Store the handle after successfully sending it, so it can be closed <ide> // when the NODE_HANDLE_ACK is received. If the handle could not be sent, <ide> // just close it. <ide> if (handle && !options.keepOpen) { <ide> if (target) { <del> // There can only be one _pendingHandle as passing handles are <add> // There can only be one _pendingMessage as passing handles are <ide> // processed one at a time: handles are stored in _handleQueue while <ide> // waiting for the NODE_HANDLE_ACK of the current passing handle. <del> assert(!target._pendingHandle); <del> target._pendingHandle = handle; <add> assert(!target._pendingMessage); <add> target._pendingMessage = <add> { callback, message, handle, options, retransmissions: 0 }; <ide> } else { <ide> handle.close(); <ide> } <ide> function getHandleWrapType(stream) { <ide> return false; <ide> } <ide> <add>function closePendingHandle(target) { <add> target._pendingMessage.handle.close(); <add> target._pendingMessage = null; <add>} <add> <ide> <ide> ChildProcess.prototype.spawn = function(options) { <ide> var ipc; <ide> function setupChannel(target, channel) { <ide> }); <ide> <ide> target._handleQueue = null; <del> target._pendingHandle = null; <add> target._pendingMessage = null; <ide> <ide> const control = new Control(channel); <ide> <ide> function setupChannel(target, channel) { <ide> // handlers will go through this <ide> target.on('internalMessage', function(message, handle) { <ide> // Once acknowledged - continue sending handles. <del> if (message.cmd === 'NODE_HANDLE_ACK') { <del> if (target._pendingHandle) { <del> target._pendingHandle.close(); <del> target._pendingHandle = null; <add> if (message.cmd === 'NODE_HANDLE_ACK' || <add> message.cmd === 'NODE_HANDLE_NACK') { <add> <add> if (target._pendingMessage) { <add> if (message.cmd === 'NODE_HANDLE_ACK') { <add> closePendingHandle(target); <add> } else if (target._pendingMessage.retransmissions++ === <add> MAX_HANDLE_RETRANSMISSIONS) { <add> closePendingHandle(target); <add> process.emitWarning('Handle did not reach the receiving process ' + <add> 'correctly', 'SentHandleNotReceivedWarning'); <add> } <ide> } <ide> <ide> assert(Array.isArray(target._handleQueue)); <ide> var queue = target._handleQueue; <ide> target._handleQueue = null; <ide> <add> if (target._pendingMessage) { <add> target._send(target._pendingMessage.message, <add> target._pendingMessage.handle, <add> target._pendingMessage.options, <add> target._pendingMessage.callback); <add> } <add> <ide> for (var i = 0; i < queue.length; i++) { <ide> var args = queue[i]; <ide> target._send(args.message, args.handle, args.options, args.callback); <ide> function setupChannel(target, channel) { <ide> <ide> if (message.cmd !== 'NODE_HANDLE') return; <ide> <add> // It is possible that the handle is not received because of some error on <add> // ancillary data reception such as MSG_CTRUNC. In this case, report the <add> // sender about it by sending a NODE_HANDLE_NACK message. <add> if (!handle) <add> return target._send({ cmd: 'NODE_HANDLE_NACK' }, null, true); <add> <ide> // Acknowledge handle receival. Don't emit error events (for example if <ide> // the other side has disconnected) because this call to send() is not <ide> // initiated by the user and it shouldn't be fatal to be unable to ACK <ide> function setupChannel(target, channel) { <ide> net._setSimultaneousAccepts(handle); <ide> } <ide> } else if (this._handleQueue && <del> !(message && message.cmd === 'NODE_HANDLE_ACK')) { <add> !(message && (message.cmd === 'NODE_HANDLE_ACK' || <add> message.cmd === 'NODE_HANDLE_NACK'))) { <ide> // Queue request anyway to avoid out-of-order messages. <ide> this._handleQueue.push({ <ide> callback: callback, <ide> function setupChannel(target, channel) { <ide> if (!this._handleQueue) <ide> this._handleQueue = []; <ide> if (obj && obj.postSend) <del> obj.postSend(handle, options, target); <add> obj.postSend(message, handle, options, callback, target); <ide> } <ide> <ide> if (req.async) { <ide> function setupChannel(target, channel) { <ide> } else { <ide> // Cleanup handle on error <ide> if (obj && obj.postSend) <del> obj.postSend(handle, options); <add> obj.postSend(message, handle, options, callback); <ide> <ide> if (!options.swallowErrors) { <ide> const ex = errnoException(err, 'write'); <ide> function setupChannel(target, channel) { <ide> // This marks the fact that the channel is actually disconnected. <ide> this.channel = null; <ide> <del> if (this._pendingHandle) { <del> this._pendingHandle.close(); <del> this._pendingHandle = null; <del> } <add> if (this._pendingMessage) <add> closePendingHandle(this); <ide> <ide> var fired = false; <ide> function finish() {
1
Go
Go
move network operations out of container package
cc8f358c23d307d19b06cd5e7d039d8fad01a947
<ide><path>container/container.go <ide> import ( <ide> "encoding/json" <ide> "fmt" <ide> "io" <del> "net" <ide> "os" <ide> "path/filepath" <ide> "runtime" <del> "strconv" <ide> "strings" <ide> "sync" <ide> "syscall" <ide> import ( <ide> "github.com/containerd/containerd/cio" <ide> containertypes "github.com/docker/docker/api/types/container" <ide> mounttypes "github.com/docker/docker/api/types/mount" <del> networktypes "github.com/docker/docker/api/types/network" <ide> swarmtypes "github.com/docker/docker/api/types/swarm" <ide> "github.com/docker/docker/container/stream" <ide> "github.com/docker/docker/daemon/exec" <ide> import ( <ide> "github.com/docker/docker/daemon/network" <ide> "github.com/docker/docker/image" <ide> "github.com/docker/docker/layer" <del> "github.com/docker/docker/opts" <ide> "github.com/docker/docker/pkg/containerfs" <ide> "github.com/docker/docker/pkg/idtools" <ide> "github.com/docker/docker/pkg/ioutils" <ide> "github.com/docker/docker/pkg/signal" <ide> "github.com/docker/docker/pkg/symlink" <ide> "github.com/docker/docker/pkg/system" <ide> "github.com/docker/docker/restartmanager" <del> "github.com/docker/docker/runconfig" <ide> "github.com/docker/docker/volume" <ide> volumemounts "github.com/docker/docker/volume/mounts" <del> "github.com/docker/go-connections/nat" <del> units "github.com/docker/go-units" <del> "github.com/docker/libnetwork" <del> "github.com/docker/libnetwork/netlabel" <del> "github.com/docker/libnetwork/options" <del> "github.com/docker/libnetwork/types" <add> "github.com/docker/go-units" <ide> agentexec "github.com/docker/swarmkit/agent/exec" <ide> "github.com/pkg/errors" <ide> "github.com/sirupsen/logrus" <ide> ) <ide> <ide> const configFileName = "config.v2.json" <ide> <del>var ( <del> errInvalidEndpoint = errors.New("invalid endpoint while building port map info") <del> errInvalidNetwork = errors.New("invalid network settings while building port map info") <del>) <del> <ide> // ExitStatus provides exit reasons for a container. <ide> type ExitStatus struct { <ide> // The exit code with which the container exited. <ide> func (container *Container) InitDNSHostConfig() { <ide> } <ide> } <ide> <del>// GetEndpointInNetwork returns the container's endpoint to the provided network. <del>func (container *Container) GetEndpointInNetwork(n libnetwork.Network) (libnetwork.Endpoint, error) { <del> endpointName := strings.TrimPrefix(container.Name, "/") <del> return n.EndpointByName(endpointName) <del>} <del> <del>func (container *Container) buildPortMapInfo(ep libnetwork.Endpoint) error { <del> if ep == nil { <del> return errInvalidEndpoint <del> } <del> <del> networkSettings := container.NetworkSettings <del> if networkSettings == nil { <del> return errInvalidNetwork <del> } <del> <del> if len(networkSettings.Ports) == 0 { <del> pm, err := getEndpointPortMapInfo(ep) <del> if err != nil { <del> return err <del> } <del> networkSettings.Ports = pm <del> } <del> return nil <del>} <del> <del>func getEndpointPortMapInfo(ep libnetwork.Endpoint) (nat.PortMap, error) { <del> pm := nat.PortMap{} <del> driverInfo, err := ep.DriverInfo() <del> if err != nil { <del> return pm, err <del> } <del> <del> if driverInfo == nil { <del> // It is not an error for epInfo to be nil <del> return pm, nil <del> } <del> <del> if expData, ok := driverInfo[netlabel.ExposedPorts]; ok { <del> if exposedPorts, ok := expData.([]types.TransportPort); ok { <del> for _, tp := range exposedPorts { <del> natPort, err := nat.NewPort(tp.Proto.String(), strconv.Itoa(int(tp.Port))) <del> if err != nil { <del> return pm, fmt.Errorf("Error parsing Port value(%v):%v", tp.Port, err) <del> } <del> pm[natPort] = nil <del> } <del> } <del> } <del> <del> mapData, ok := driverInfo[netlabel.PortMap] <del> if !ok { <del> return pm, nil <del> } <del> <del> if portMapping, ok := mapData.([]types.PortBinding); ok { <del> for _, pp := range portMapping { <del> natPort, err := nat.NewPort(pp.Proto.String(), strconv.Itoa(int(pp.Port))) <del> if err != nil { <del> return pm, err <del> } <del> natBndg := nat.PortBinding{HostIP: pp.HostIP.String(), HostPort: strconv.Itoa(int(pp.HostPort))} <del> pm[natPort] = append(pm[natPort], natBndg) <del> } <del> } <del> <del> return pm, nil <del>} <del> <del>// GetSandboxPortMapInfo retrieves the current port-mapping programmed for the given sandbox <del>func GetSandboxPortMapInfo(sb libnetwork.Sandbox) nat.PortMap { <del> pm := nat.PortMap{} <del> if sb == nil { <del> return pm <del> } <del> <del> for _, ep := range sb.Endpoints() { <del> pm, _ = getEndpointPortMapInfo(ep) <del> if len(pm) > 0 { <del> break <del> } <del> } <del> return pm <del>} <del> <del>// BuildEndpointInfo sets endpoint-related fields on container.NetworkSettings based on the provided network and endpoint. <del>func (container *Container) BuildEndpointInfo(n libnetwork.Network, ep libnetwork.Endpoint) error { <del> if ep == nil { <del> return errInvalidEndpoint <del> } <del> <del> networkSettings := container.NetworkSettings <del> if networkSettings == nil { <del> return errInvalidNetwork <del> } <del> <del> epInfo := ep.Info() <del> if epInfo == nil { <del> // It is not an error to get an empty endpoint info <del> return nil <del> } <del> <del> if _, ok := networkSettings.Networks[n.Name()]; !ok { <del> networkSettings.Networks[n.Name()] = &network.EndpointSettings{ <del> EndpointSettings: &networktypes.EndpointSettings{}, <del> } <del> } <del> networkSettings.Networks[n.Name()].NetworkID = n.ID() <del> networkSettings.Networks[n.Name()].EndpointID = ep.ID() <del> <del> iface := epInfo.Iface() <del> if iface == nil { <del> return nil <del> } <del> <del> if iface.MacAddress() != nil { <del> networkSettings.Networks[n.Name()].MacAddress = iface.MacAddress().String() <del> } <del> <del> if iface.Address() != nil { <del> ones, _ := iface.Address().Mask.Size() <del> networkSettings.Networks[n.Name()].IPAddress = iface.Address().IP.String() <del> networkSettings.Networks[n.Name()].IPPrefixLen = ones <del> } <del> <del> if iface.AddressIPv6() != nil && iface.AddressIPv6().IP.To16() != nil { <del> onesv6, _ := iface.AddressIPv6().Mask.Size() <del> networkSettings.Networks[n.Name()].GlobalIPv6Address = iface.AddressIPv6().IP.String() <del> networkSettings.Networks[n.Name()].GlobalIPv6PrefixLen = onesv6 <del> } <del> <del> return nil <del>} <del> <del>type named interface { <del> Name() string <del>} <del> <del>// UpdateJoinInfo updates network settings when container joins network n with endpoint ep. <del>func (container *Container) UpdateJoinInfo(n named, ep libnetwork.Endpoint) error { <del> if err := container.buildPortMapInfo(ep); err != nil { <del> return err <del> } <del> <del> epInfo := ep.Info() <del> if epInfo == nil { <del> // It is not an error to get an empty endpoint info <del> return nil <del> } <del> if epInfo.Gateway() != nil { <del> container.NetworkSettings.Networks[n.Name()].Gateway = epInfo.Gateway().String() <del> } <del> if epInfo.GatewayIPv6().To16() != nil { <del> container.NetworkSettings.Networks[n.Name()].IPv6Gateway = epInfo.GatewayIPv6().String() <del> } <del> <del> return nil <del>} <del> <del>// UpdateSandboxNetworkSettings updates the sandbox ID and Key. <del>func (container *Container) UpdateSandboxNetworkSettings(sb libnetwork.Sandbox) error { <del> container.NetworkSettings.SandboxID = sb.ID() <del> container.NetworkSettings.SandboxKey = sb.Key() <del> return nil <del>} <del> <del>// BuildJoinOptions builds endpoint Join options from a given network. <del>func (container *Container) BuildJoinOptions(n named) ([]libnetwork.EndpointOption, error) { <del> var joinOptions []libnetwork.EndpointOption <del> if epConfig, ok := container.NetworkSettings.Networks[n.Name()]; ok { <del> for _, str := range epConfig.Links { <del> name, alias, err := opts.ParseLink(str) <del> if err != nil { <del> return nil, err <del> } <del> joinOptions = append(joinOptions, libnetwork.CreateOptionAlias(name, alias)) <del> } <del> for k, v := range epConfig.DriverOpts { <del> joinOptions = append(joinOptions, libnetwork.EndpointOptionGeneric(options.Generic{k: v})) <del> } <del> } <del> <del> return joinOptions, nil <del>} <del> <del>// BuildCreateEndpointOptions builds endpoint options from a given network. <del>func (container *Container) BuildCreateEndpointOptions(n libnetwork.Network, epConfig *networktypes.EndpointSettings, sb libnetwork.Sandbox, daemonDNS []string) ([]libnetwork.EndpointOption, error) { <del> var ( <del> bindings = make(nat.PortMap) <del> pbList []types.PortBinding <del> exposeList []types.TransportPort <del> createOptions []libnetwork.EndpointOption <del> ) <del> <del> defaultNetName := runconfig.DefaultDaemonNetworkMode().NetworkName() <del> <del> if (!container.EnableServiceDiscoveryOnDefaultNetwork() && n.Name() == defaultNetName) || <del> container.NetworkSettings.IsAnonymousEndpoint { <del> createOptions = append(createOptions, libnetwork.CreateOptionAnonymous()) <del> } <del> <del> if epConfig != nil { <del> ipam := epConfig.IPAMConfig <del> <del> if ipam != nil { <del> var ( <del> ipList []net.IP <del> ip, ip6, linkip net.IP <del> ) <del> <del> for _, ips := range ipam.LinkLocalIPs { <del> if linkip = net.ParseIP(ips); linkip == nil && ips != "" { <del> return nil, errors.Errorf("Invalid link-local IP address: %s", ipam.LinkLocalIPs) <del> } <del> ipList = append(ipList, linkip) <del> <del> } <del> <del> if ip = net.ParseIP(ipam.IPv4Address); ip == nil && ipam.IPv4Address != "" { <del> return nil, errors.Errorf("Invalid IPv4 address: %s)", ipam.IPv4Address) <del> } <del> <del> if ip6 = net.ParseIP(ipam.IPv6Address); ip6 == nil && ipam.IPv6Address != "" { <del> return nil, errors.Errorf("Invalid IPv6 address: %s)", ipam.IPv6Address) <del> } <del> <del> createOptions = append(createOptions, <del> libnetwork.CreateOptionIpam(ip, ip6, ipList, nil)) <del> <del> } <del> <del> for _, alias := range epConfig.Aliases { <del> createOptions = append(createOptions, libnetwork.CreateOptionMyAlias(alias)) <del> } <del> for k, v := range epConfig.DriverOpts { <del> createOptions = append(createOptions, libnetwork.EndpointOptionGeneric(options.Generic{k: v})) <del> } <del> } <del> <del> if container.NetworkSettings.Service != nil { <del> svcCfg := container.NetworkSettings.Service <del> <del> var vip string <del> if svcCfg.VirtualAddresses[n.ID()] != nil { <del> vip = svcCfg.VirtualAddresses[n.ID()].IPv4 <del> } <del> <del> var portConfigs []*libnetwork.PortConfig <del> for _, portConfig := range svcCfg.ExposedPorts { <del> portConfigs = append(portConfigs, &libnetwork.PortConfig{ <del> Name: portConfig.Name, <del> Protocol: libnetwork.PortConfig_Protocol(portConfig.Protocol), <del> TargetPort: portConfig.TargetPort, <del> PublishedPort: portConfig.PublishedPort, <del> }) <del> } <del> <del> createOptions = append(createOptions, libnetwork.CreateOptionService(svcCfg.Name, svcCfg.ID, net.ParseIP(vip), portConfigs, svcCfg.Aliases[n.ID()])) <del> } <del> <del> if !containertypes.NetworkMode(n.Name()).IsUserDefined() { <del> createOptions = append(createOptions, libnetwork.CreateOptionDisableResolution()) <del> } <del> <del> // configs that are applicable only for the endpoint in the network <del> // to which container was connected to on docker run. <del> // Ideally all these network-specific endpoint configurations must be moved under <del> // container.NetworkSettings.Networks[n.Name()] <del> if n.Name() == container.HostConfig.NetworkMode.NetworkName() || <del> (n.Name() == defaultNetName && container.HostConfig.NetworkMode.IsDefault()) { <del> if container.Config.MacAddress != "" { <del> mac, err := net.ParseMAC(container.Config.MacAddress) <del> if err != nil { <del> return nil, err <del> } <del> <del> genericOption := options.Generic{ <del> netlabel.MacAddress: mac, <del> } <del> <del> createOptions = append(createOptions, libnetwork.EndpointOptionGeneric(genericOption)) <del> } <del> <del> } <del> <del> // Port-mapping rules belong to the container & applicable only to non-internal networks <del> portmaps := GetSandboxPortMapInfo(sb) <del> if n.Info().Internal() || len(portmaps) > 0 { <del> return createOptions, nil <del> } <del> <del> if container.HostConfig.PortBindings != nil { <del> for p, b := range container.HostConfig.PortBindings { <del> bindings[p] = []nat.PortBinding{} <del> for _, bb := range b { <del> bindings[p] = append(bindings[p], nat.PortBinding{ <del> HostIP: bb.HostIP, <del> HostPort: bb.HostPort, <del> }) <del> } <del> } <del> } <del> <del> portSpecs := container.Config.ExposedPorts <del> ports := make([]nat.Port, len(portSpecs)) <del> var i int <del> for p := range portSpecs { <del> ports[i] = p <del> i++ <del> } <del> nat.SortPortMap(ports, bindings) <del> for _, port := range ports { <del> expose := types.TransportPort{} <del> expose.Proto = types.ParseProtocol(port.Proto()) <del> expose.Port = uint16(port.Int()) <del> exposeList = append(exposeList, expose) <del> <del> pb := types.PortBinding{Port: expose.Port, Proto: expose.Proto} <del> binding := bindings[port] <del> for i := 0; i < len(binding); i++ { <del> pbCopy := pb.GetCopy() <del> newP, err := nat.NewPort(nat.SplitProtoPort(binding[i].HostPort)) <del> var portStart, portEnd int <del> if err == nil { <del> portStart, portEnd, err = newP.Range() <del> } <del> if err != nil { <del> return nil, errors.Wrapf(err, "Error parsing HostPort value (%s)", binding[i].HostPort) <del> } <del> pbCopy.HostPort = uint16(portStart) <del> pbCopy.HostPortEnd = uint16(portEnd) <del> pbCopy.HostIP = net.ParseIP(binding[i].HostIP) <del> pbList = append(pbList, pbCopy) <del> } <del> <del> if container.HostConfig.PublishAllPorts && len(binding) == 0 { <del> pbList = append(pbList, pb) <del> } <del> } <del> <del> var dns []string <del> <del> if len(container.HostConfig.DNS) > 0 { <del> dns = container.HostConfig.DNS <del> } else if len(daemonDNS) > 0 { <del> dns = daemonDNS <del> } <del> <del> if len(dns) > 0 { <del> createOptions = append(createOptions, <del> libnetwork.CreateOptionDNS(dns)) <del> } <del> <del> createOptions = append(createOptions, <del> libnetwork.CreateOptionPortMapping(pbList), <del> libnetwork.CreateOptionExposedPorts(exposeList)) <del> <del> return createOptions, nil <del>} <del> <ide> // UpdateMonitor updates monitor configure for running container <ide> func (container *Container) UpdateMonitor(restartPolicy containertypes.RestartPolicy) { <ide> type policySetter interface { <ide><path>daemon/container_operations.go <ide> var ( <ide> // ErrRootFSReadOnly is returned when a container <ide> // rootfs is marked readonly. <ide> ErrRootFSReadOnly = errors.New("container rootfs is marked read-only") <del> getPortMapInfo = container.GetSandboxPortMapInfo <add> getPortMapInfo = getSandboxPortMapInfo <ide> ) <ide> <ide> func (daemon *Daemon) getDNSSearchSettings(container *container.Container) []string { <ide> func (daemon *Daemon) updateNetworkSettings(container *container.Container, n li <ide> } <ide> <ide> func (daemon *Daemon) updateEndpointNetworkSettings(container *container.Container, n libnetwork.Network, ep libnetwork.Endpoint) error { <del> if err := container.BuildEndpointInfo(n, ep); err != nil { <add> if err := buildEndpointInfo(container.NetworkSettings, n, ep); err != nil { <ide> return err <ide> } <ide> <ide> func (daemon *Daemon) allocateNetwork(container *container.Container) error { <ide> if err != nil { <ide> return err <ide> } <del> container.UpdateSandboxNetworkSettings(sb) <add> updateSandboxNetworkSettings(container, sb) <ide> defer func() { <ide> if err != nil { <ide> sb.Delete() <ide> func (daemon *Daemon) connectToNetwork(container *container.Container, idOrName <ide> <ide> controller := daemon.netController <ide> sb := daemon.getNetworkSandbox(container) <del> createOptions, err := container.BuildCreateEndpointOptions(n, endpointConfig, sb, daemon.configStore.DNS) <add> createOptions, err := buildCreateEndpointOptions(container, n, endpointConfig, sb, daemon.configStore.DNS) <ide> if err != nil { <ide> return err <ide> } <ide> func (daemon *Daemon) connectToNetwork(container *container.Container, idOrName <ide> return err <ide> } <ide> <del> container.UpdateSandboxNetworkSettings(sb) <add> updateSandboxNetworkSettings(container, sb) <ide> } <ide> <del> joinOptions, err := container.BuildJoinOptions(n) <add> joinOptions, err := buildJoinOptions(container.NetworkSettings, n) <ide> if err != nil { <ide> return err <ide> } <ide> func (daemon *Daemon) connectToNetwork(container *container.Container, idOrName <ide> } <ide> } <ide> <del> if err := container.UpdateJoinInfo(n, ep); err != nil { <add> if err := updateJoinInfo(container.NetworkSettings, n, ep); err != nil { <ide> return fmt.Errorf("Updating join info failed: %v", err) <ide> } <ide> <ide> func (daemon *Daemon) connectToNetwork(container *container.Container, idOrName <ide> return nil <ide> } <ide> <add>func updateJoinInfo(networkSettings *network.Settings, n libnetwork.Network, ep libnetwork.Endpoint) error { // nolint: interfacer <add> if ep == nil { <add> return errors.New("invalid enppoint whhile building portmap info") <add> } <add> <add> if networkSettings == nil { <add> return errors.New("invalid network settings while building port map info") <add> } <add> <add> if len(networkSettings.Ports) == 0 { <add> pm, err := getEndpointPortMapInfo(ep) <add> if err != nil { <add> return err <add> } <add> networkSettings.Ports = pm <add> } <add> <add> epInfo := ep.Info() <add> if epInfo == nil { <add> // It is not an error to get an empty endpoint info <add> return nil <add> } <add> if epInfo.Gateway() != nil { <add> networkSettings.Networks[n.Name()].Gateway = epInfo.Gateway().String() <add> } <add> if epInfo.GatewayIPv6().To16() != nil { <add> networkSettings.Networks[n.Name()].IPv6Gateway = epInfo.GatewayIPv6().String() <add> } <add> return nil <add>} <add> <ide> // ForceEndpointDelete deletes an endpoint from a network forcefully <ide> func (daemon *Daemon) ForceEndpointDelete(name string, networkName string) error { <ide> n, err := daemon.FindNetwork(networkName) <ide> func getNetworkID(name string, endpointSettings *networktypes.EndpointSettings) <ide> } <ide> return name <ide> } <add> <add>// updateSandboxNetworkSettings updates the sandbox ID and Key. <add>func updateSandboxNetworkSettings(c *container.Container, sb libnetwork.Sandbox) error { <add> c.NetworkSettings.SandboxID = sb.ID() <add> c.NetworkSettings.SandboxKey = sb.Key() <add> return nil <add>} <ide><path>daemon/container_operations_windows.go <ide> func (daemon *Daemon) initializeNetworkingPaths(container *container.Container, <ide> continue <ide> } <ide> <del> ep, err := nc.GetEndpointInNetwork(sn) <add> ep, err := getEndpointInNetwork(nc.Name, sn) <ide> if err != nil { <ide> continue <ide> } <ide><path>daemon/network.go <ide> import ( <ide> "net" <ide> "runtime" <ide> "sort" <add> "strconv" <ide> "strings" <ide> "sync" <ide> <ide> "github.com/docker/docker/api/types" <add> containertypes "github.com/docker/docker/api/types/container" <ide> "github.com/docker/docker/api/types/network" <add> "github.com/docker/docker/container" <ide> clustertypes "github.com/docker/docker/daemon/cluster/provider" <add> internalnetwork "github.com/docker/docker/daemon/network" <ide> "github.com/docker/docker/errdefs" <add> "github.com/docker/docker/opts" <ide> "github.com/docker/docker/pkg/plugingetter" <ide> "github.com/docker/docker/runconfig" <add> "github.com/docker/go-connections/nat" <ide> "github.com/docker/libnetwork" <ide> lncluster "github.com/docker/libnetwork/cluster" <ide> "github.com/docker/libnetwork/driverapi" <ide> "github.com/docker/libnetwork/ipamapi" <add> "github.com/docker/libnetwork/netlabel" <add> "github.com/docker/libnetwork/options" <ide> networktypes "github.com/docker/libnetwork/types" <ide> "github.com/pkg/errors" <ide> "github.com/sirupsen/logrus" <ide> func (daemon *Daemon) NetworkControllerEnabled() bool { <ide> func (daemon *Daemon) FindNetwork(term string) (libnetwork.Network, error) { <ide> listByFullName := []libnetwork.Network{} <ide> listByPartialID := []libnetwork.Network{} <del> for _, nw := range daemon.GetNetworks() { <add> for _, nw := range daemon.getAllNetworks() { <ide> if nw.ID() == term { <ide> return nw, nil <ide> } <ide> func (daemon *Daemon) GetNetworks() []libnetwork.Network { <ide> // clearAttachableNetworks removes the attachable networks <ide> // after disconnecting any connected container <ide> func (daemon *Daemon) clearAttachableNetworks() { <del> for _, n := range daemon.GetNetworks() { <add> for _, n := range daemon.getAllNetworks() { <ide> if !n.Info().Attachable() { <ide> continue <ide> } <ide> func (daemon *Daemon) clearAttachableNetworks() { <ide> } <ide> } <ide> } <add> <add>// buildCreateEndpointOptions builds endpoint options from a given network. <add>func buildCreateEndpointOptions(c *container.Container, n libnetwork.Network, epConfig *network.EndpointSettings, sb libnetwork.Sandbox, daemonDNS []string) ([]libnetwork.EndpointOption, error) { <add> var ( <add> bindings = make(nat.PortMap) <add> pbList []networktypes.PortBinding <add> exposeList []networktypes.TransportPort <add> createOptions []libnetwork.EndpointOption <add> ) <add> <add> defaultNetName := runconfig.DefaultDaemonNetworkMode().NetworkName() <add> <add> if (!c.EnableServiceDiscoveryOnDefaultNetwork() && n.Name() == defaultNetName) || <add> c.NetworkSettings.IsAnonymousEndpoint { <add> createOptions = append(createOptions, libnetwork.CreateOptionAnonymous()) <add> } <add> <add> if epConfig != nil { <add> ipam := epConfig.IPAMConfig <add> <add> if ipam != nil { <add> var ( <add> ipList []net.IP <add> ip, ip6, linkip net.IP <add> ) <add> <add> for _, ips := range ipam.LinkLocalIPs { <add> if linkip = net.ParseIP(ips); linkip == nil && ips != "" { <add> return nil, errors.Errorf("Invalid link-local IP address: %s", ipam.LinkLocalIPs) <add> } <add> ipList = append(ipList, linkip) <add> <add> } <add> <add> if ip = net.ParseIP(ipam.IPv4Address); ip == nil && ipam.IPv4Address != "" { <add> return nil, errors.Errorf("Invalid IPv4 address: %s)", ipam.IPv4Address) <add> } <add> <add> if ip6 = net.ParseIP(ipam.IPv6Address); ip6 == nil && ipam.IPv6Address != "" { <add> return nil, errors.Errorf("Invalid IPv6 address: %s)", ipam.IPv6Address) <add> } <add> <add> createOptions = append(createOptions, <add> libnetwork.CreateOptionIpam(ip, ip6, ipList, nil)) <add> <add> } <add> <add> for _, alias := range epConfig.Aliases { <add> createOptions = append(createOptions, libnetwork.CreateOptionMyAlias(alias)) <add> } <add> for k, v := range epConfig.DriverOpts { <add> createOptions = append(createOptions, libnetwork.EndpointOptionGeneric(options.Generic{k: v})) <add> } <add> } <add> <add> if c.NetworkSettings.Service != nil { <add> svcCfg := c.NetworkSettings.Service <add> <add> var vip string <add> if svcCfg.VirtualAddresses[n.ID()] != nil { <add> vip = svcCfg.VirtualAddresses[n.ID()].IPv4 <add> } <add> <add> var portConfigs []*libnetwork.PortConfig <add> for _, portConfig := range svcCfg.ExposedPorts { <add> portConfigs = append(portConfigs, &libnetwork.PortConfig{ <add> Name: portConfig.Name, <add> Protocol: libnetwork.PortConfig_Protocol(portConfig.Protocol), <add> TargetPort: portConfig.TargetPort, <add> PublishedPort: portConfig.PublishedPort, <add> }) <add> } <add> <add> createOptions = append(createOptions, libnetwork.CreateOptionService(svcCfg.Name, svcCfg.ID, net.ParseIP(vip), portConfigs, svcCfg.Aliases[n.ID()])) <add> } <add> <add> if !containertypes.NetworkMode(n.Name()).IsUserDefined() { <add> createOptions = append(createOptions, libnetwork.CreateOptionDisableResolution()) <add> } <add> <add> // configs that are applicable only for the endpoint in the network <add> // to which container was connected to on docker run. <add> // Ideally all these network-specific endpoint configurations must be moved under <add> // container.NetworkSettings.Networks[n.Name()] <add> if n.Name() == c.HostConfig.NetworkMode.NetworkName() || <add> (n.Name() == defaultNetName && c.HostConfig.NetworkMode.IsDefault()) { <add> if c.Config.MacAddress != "" { <add> mac, err := net.ParseMAC(c.Config.MacAddress) <add> if err != nil { <add> return nil, err <add> } <add> <add> genericOption := options.Generic{ <add> netlabel.MacAddress: mac, <add> } <add> <add> createOptions = append(createOptions, libnetwork.EndpointOptionGeneric(genericOption)) <add> } <add> <add> } <add> <add> // Port-mapping rules belong to the container & applicable only to non-internal networks <add> portmaps := getSandboxPortMapInfo(sb) <add> if n.Info().Internal() || len(portmaps) > 0 { <add> return createOptions, nil <add> } <add> <add> if c.HostConfig.PortBindings != nil { <add> for p, b := range c.HostConfig.PortBindings { <add> bindings[p] = []nat.PortBinding{} <add> for _, bb := range b { <add> bindings[p] = append(bindings[p], nat.PortBinding{ <add> HostIP: bb.HostIP, <add> HostPort: bb.HostPort, <add> }) <add> } <add> } <add> } <add> <add> portSpecs := c.Config.ExposedPorts <add> ports := make([]nat.Port, len(portSpecs)) <add> var i int <add> for p := range portSpecs { <add> ports[i] = p <add> i++ <add> } <add> nat.SortPortMap(ports, bindings) <add> for _, port := range ports { <add> expose := networktypes.TransportPort{} <add> expose.Proto = networktypes.ParseProtocol(port.Proto()) <add> expose.Port = uint16(port.Int()) <add> exposeList = append(exposeList, expose) <add> <add> pb := networktypes.PortBinding{Port: expose.Port, Proto: expose.Proto} <add> binding := bindings[port] <add> for i := 0; i < len(binding); i++ { <add> pbCopy := pb.GetCopy() <add> newP, err := nat.NewPort(nat.SplitProtoPort(binding[i].HostPort)) <add> var portStart, portEnd int <add> if err == nil { <add> portStart, portEnd, err = newP.Range() <add> } <add> if err != nil { <add> return nil, errors.Wrapf(err, "Error parsing HostPort value (%s)", binding[i].HostPort) <add> } <add> pbCopy.HostPort = uint16(portStart) <add> pbCopy.HostPortEnd = uint16(portEnd) <add> pbCopy.HostIP = net.ParseIP(binding[i].HostIP) <add> pbList = append(pbList, pbCopy) <add> } <add> <add> if c.HostConfig.PublishAllPorts && len(binding) == 0 { <add> pbList = append(pbList, pb) <add> } <add> } <add> <add> var dns []string <add> <add> if len(c.HostConfig.DNS) > 0 { <add> dns = c.HostConfig.DNS <add> } else if len(daemonDNS) > 0 { <add> dns = daemonDNS <add> } <add> <add> if len(dns) > 0 { <add> createOptions = append(createOptions, <add> libnetwork.CreateOptionDNS(dns)) <add> } <add> <add> createOptions = append(createOptions, <add> libnetwork.CreateOptionPortMapping(pbList), <add> libnetwork.CreateOptionExposedPorts(exposeList)) <add> <add> return createOptions, nil <add>} <add> <add>// getEndpointInNetwork returns the container's endpoint to the provided network. <add>func getEndpointInNetwork(name string, n libnetwork.Network) (libnetwork.Endpoint, error) { <add> endpointName := strings.TrimPrefix(name, "/") <add> return n.EndpointByName(endpointName) <add>} <add> <add>// getSandboxPortMapInfo retrieves the current port-mapping programmed for the given sandbox <add>func getSandboxPortMapInfo(sb libnetwork.Sandbox) nat.PortMap { <add> pm := nat.PortMap{} <add> if sb == nil { <add> return pm <add> } <add> <add> for _, ep := range sb.Endpoints() { <add> pm, _ = getEndpointPortMapInfo(ep) <add> if len(pm) > 0 { <add> break <add> } <add> } <add> return pm <add>} <add> <add>func getEndpointPortMapInfo(ep libnetwork.Endpoint) (nat.PortMap, error) { <add> pm := nat.PortMap{} <add> driverInfo, err := ep.DriverInfo() <add> if err != nil { <add> return pm, err <add> } <add> <add> if driverInfo == nil { <add> // It is not an error for epInfo to be nil <add> return pm, nil <add> } <add> <add> if expData, ok := driverInfo[netlabel.ExposedPorts]; ok { <add> if exposedPorts, ok := expData.([]networktypes.TransportPort); ok { <add> for _, tp := range exposedPorts { <add> natPort, err := nat.NewPort(tp.Proto.String(), strconv.Itoa(int(tp.Port))) <add> if err != nil { <add> return pm, fmt.Errorf("Error parsing Port value(%v):%v", tp.Port, err) <add> } <add> pm[natPort] = nil <add> } <add> } <add> } <add> <add> mapData, ok := driverInfo[netlabel.PortMap] <add> if !ok { <add> return pm, nil <add> } <add> <add> if portMapping, ok := mapData.([]networktypes.PortBinding); ok { <add> for _, pp := range portMapping { <add> natPort, err := nat.NewPort(pp.Proto.String(), strconv.Itoa(int(pp.Port))) <add> if err != nil { <add> return pm, err <add> } <add> natBndg := nat.PortBinding{HostIP: pp.HostIP.String(), HostPort: strconv.Itoa(int(pp.HostPort))} <add> pm[natPort] = append(pm[natPort], natBndg) <add> } <add> } <add> <add> return pm, nil <add>} <add> <add>// buildEndpointInfo sets endpoint-related fields on container.NetworkSettings based on the provided network and endpoint. <add>func buildEndpointInfo(networkSettings *internalnetwork.Settings, n libnetwork.Network, ep libnetwork.Endpoint) error { <add> if ep == nil { <add> return errors.New("endpoint cannot be nil") <add> } <add> <add> if networkSettings == nil { <add> return errors.New("network cannot be nil") <add> } <add> <add> epInfo := ep.Info() <add> if epInfo == nil { <add> // It is not an error to get an empty endpoint info <add> return nil <add> } <add> <add> if _, ok := networkSettings.Networks[n.Name()]; !ok { <add> networkSettings.Networks[n.Name()] = &internalnetwork.EndpointSettings{ <add> EndpointSettings: &network.EndpointSettings{}, <add> } <add> } <add> networkSettings.Networks[n.Name()].NetworkID = n.ID() <add> networkSettings.Networks[n.Name()].EndpointID = ep.ID() <add> <add> iface := epInfo.Iface() <add> if iface == nil { <add> return nil <add> } <add> <add> if iface.MacAddress() != nil { <add> networkSettings.Networks[n.Name()].MacAddress = iface.MacAddress().String() <add> } <add> <add> if iface.Address() != nil { <add> ones, _ := iface.Address().Mask.Size() <add> networkSettings.Networks[n.Name()].IPAddress = iface.Address().IP.String() <add> networkSettings.Networks[n.Name()].IPPrefixLen = ones <add> } <add> <add> if iface.AddressIPv6() != nil && iface.AddressIPv6().IP.To16() != nil { <add> onesv6, _ := iface.AddressIPv6().Mask.Size() <add> networkSettings.Networks[n.Name()].GlobalIPv6Address = iface.AddressIPv6().IP.String() <add> networkSettings.Networks[n.Name()].GlobalIPv6PrefixLen = onesv6 <add> } <add> <add> return nil <add>} <add> <add>// buildJoinOptions builds endpoint Join options from a given network. <add>func buildJoinOptions(networkSettings *internalnetwork.Settings, n interface { <add> Name() string <add>}) ([]libnetwork.EndpointOption, error) { <add> var joinOptions []libnetwork.EndpointOption <add> if epConfig, ok := networkSettings.Networks[n.Name()]; ok { <add> for _, str := range epConfig.Links { <add> name, alias, err := opts.ParseLink(str) <add> if err != nil { <add> return nil, err <add> } <add> joinOptions = append(joinOptions, libnetwork.CreateOptionAlias(name, alias)) <add> } <add> for k, v := range epConfig.DriverOpts { <add> joinOptions = append(joinOptions, libnetwork.EndpointOptionGeneric(options.Generic{k: v})) <add> } <add> } <add> <add> return joinOptions, nil <add>} <ide><path>daemon/oci_windows.go <ide> func (daemon *Daemon) createSpec(c *container.Container) (*specs.Spec, error) { <ide> continue <ide> } <ide> <del> ep, err := c.GetEndpointInNetwork(sn) <add> ep, err := getEndpointInNetwork(c.Name, sn) <ide> if err != nil { <ide> continue <ide> }
5
Java
Java
fix javadoc link in dynamicintroductionadvice
a78701cc4b7cb66be91ebee4fa9764e753dacd68
<ide><path>spring-aop/src/main/java/org/springframework/aop/DynamicIntroductionAdvice.java <ide> * <p>Introductions are often <b>mixins</b>, enabling the building of composite <ide> * objects that can achieve many of the goals of multiple inheritance in Java. <ide> * <del> * <p>Compared to {qlink IntroductionInfo}, this interface allows an advice to <add> * <p>Compared to {@link IntroductionInfo}, this interface allows an advice to <ide> * implement a range of interfaces that is not necessarily known in advance. <ide> * Thus an {@link IntroductionAdvisor} can be used to specify which interfaces <ide> * will be exposed in an advised object.
1
Python
Python
remove unused function in plot_lfads
597fb3e6e75896bac4a6961e1873c44a0aeccfe2
<ide><path>lfads/plot_lfads.py <ide> def all_plot(d, full_name="", exclude="", nspaces=0): <ide> _plot_item(v, name=k, full_name=full_name+"/"+k, nspaces=nspaces+4) <ide> <ide> <del>def plot_priors(): <del> g0s_prior_mean_bxn = train_modelvals['prior_g0_mean'] <del> g0s_prior_var_bxn = train_modelvals['prior_g0_var'] <del> g0s_post_mean_bxn = train_modelvals['posterior_g0_mean'] <del> g0s_post_var_bxn = train_modelvals['posterior_g0_var'] <del> <del> plt.figure(figsize=(10,4), tight_layout=True); <del> plt.subplot(1,2,1) <del> plt.hist(g0s_post_mean_bxn.flatten(), bins=20, color='b'); <del> plt.hist(g0s_prior_mean_bxn.flatten(), bins=20, color='g'); <del> <del> plt.title('Histogram of Prior/Posterior Mean Values') <del> plt.subplot(1,2,2) <del> plt.hist((g0s_post_var_bxn.flatten()), bins=20, color='b'); <del> plt.hist((g0s_prior_var_bxn.flatten()), bins=20, color='g'); <del> plt.title('Histogram of Prior/Posterior Log Variance Values') <del> <del> plt.figure(figsize=(10,10), tight_layout=True) <del> plt.subplot(2,2,1) <del> plt.imshow(g0s_prior_mean_bxn.T, interpolation='nearest', cmap='jet') <del> plt.colorbar(fraction=0.025, pad=0.04) <del> plt.title('Prior g0 means') <del> <del> plt.subplot(2,2,2) <del> plt.imshow(g0s_post_mean_bxn.T, interpolation='nearest', cmap='jet') <del> plt.colorbar(fraction=0.025, pad=0.04) <del> plt.title('Posterior g0 means'); <del> <del> plt.subplot(2,2,3) <del> plt.imshow(g0s_prior_var_bxn.T, interpolation='nearest', cmap='jet') <del> plt.colorbar(fraction=0.025, pad=0.04) <del> plt.title('Prior g0 variance Values') <del> <del> plt.subplot(2,2,4) <del> plt.imshow(g0s_post_var_bxn.T, interpolation='nearest', cmap='jet') <del> plt.colorbar(fraction=0.025, pad=0.04) <del> plt.title('Posterior g0 variance Values') <del> <del> plt.figure(figsize=(10,5)) <del> plt.stem(np.sort(np.log(g0s_post_mean_bxn.std(axis=0)))); <del> plt.title('Log standard deviation of h0 means'); <del> <ide> <ide> def plot_time_series(vals_bxtxn, bidx=None, n_to_plot=np.inf, scale=1.0, <ide> color='r', title=None):
1
Javascript
Javascript
show thrown message in doesnotthrow()
c53db1e8e9bb65779d791046daa39ed88c8f1045
<ide><path>lib/assert.js <ide> function innerThrows(shouldThrow, block, expected, message) { <ide> } else if (actual !== undefined) { <ide> if (!expected || expectedException(actual, expected)) { <ide> details = message ? `: ${message}` : '.'; <del> fail(actual, expected, `Got unwanted exception${details}`, fail); <add> fail(actual, <add> expected, <add> `Got unwanted exception${details}\n${actual.message}`, <add> fail); <ide> } <ide> throw actual; <ide> } <ide><path>test/parallel/test-assert.js <ide> assert.throws(() => { <ide> }, /Got unwanted exception: user message/, <ide> 'a.doesNotThrow ignores user message'); <ide> <add>{ <add> let threw = false; <add> try { <add> assert.doesNotThrow(makeBlock(thrower, Error), 'user message'); <add> } catch (e) { <add> threw = true; <add> common.expectsError({ <add> code: 'ERR_ASSERTION', <add> message: /Got unwanted exception: user message\n\[object Object\]/ <add> })(e); <add> } <add> assert.ok(threw); <add>} <add> <add>{ <add> let threw = false; <add> try { <add> assert.doesNotThrow(makeBlock(thrower, Error)); <add> } catch (e) { <add> threw = true; <add> common.expectsError({ <add> code: 'ERR_ASSERTION', <add> message: /Got unwanted exception\.\n\[object Object\]/ <add> })(e); <add> } <add> assert.ok(threw); <add>} <add> <ide> // make sure that validating using constructor really works <ide> { <ide> let threw = false;
2
Go
Go
fix path corruption in 'docker diff'
e16c93486d16ac4f3a05f720ee6478b5cef93f10
<ide><path>changes.go <ide> func Changes(layers []string, rw string) ([]Change, error) { <ide> file := filepath.Base(path) <ide> // If there is a whiteout, then the file was removed <ide> if strings.HasPrefix(file, ".wh.") { <del> originalFile := strings.TrimLeft(file, ".wh.") <add> originalFile := strings.TrimPrefix(file, ".wh.") <ide> change.Path = filepath.Join(filepath.Dir(path), originalFile) <ide> change.Kind = ChangeDelete <ide> } else {
1
Javascript
Javascript
upgrade watchignoreplugin to es6
ce4ce3e7cf46d1611e5267bfedb4a5badfc51aaf
<ide><path>lib/WatchIgnorePlugin.js <ide> MIT License http://www.opensource.org/licenses/mit-license.php <ide> Author Tobias Koppers @sokra <ide> */ <del>function WatchIgnorePlugin(paths) { <del> this.paths = paths; <add>"use strict" <add> <add>class WatchIgnorePlugin { <add> constructor(paths) { <add> this.paths = paths; <add> } <add> <add> apply(compiler) { <add> compiler.plugin("after-environment", () => { <add> compiler.watchFileSystem = new IgnoringWatchFileSystem(compiler.watchFileSystem, this.paths); <add> }); <add> } <ide> } <ide> <ide> module.exports = WatchIgnorePlugin; <ide> <del>WatchIgnorePlugin.prototype.apply = function(compiler) { <del> compiler.plugin("after-environment", function() { <del> compiler.watchFileSystem = new IgnoringWatchFileSystem(compiler.watchFileSystem, this.paths); <del> }.bind(this)); <del>}; <add>class IgnoringWatchFileSystem { <add> constructor(wfs, paths) { <add> this.wfs = wfs; <add> this.paths = paths; <add> } <ide> <del>function IgnoringWatchFileSystem(wfs, paths) { <del> this.wfs = wfs; <del> this.paths = paths; <del>} <add> watch(files, dirs, missing, startTime, options, callback, callbackUndelayed) { <add> const ignored = path => this.paths.some(p => p instanceof RegExp ? p.test(path) : path.indexOf(p) === 0); <ide> <del>IgnoringWatchFileSystem.prototype.watch = function(files, dirs, missing, startTime, options, callback, callbackUndelayed) { <del> var ignored = function(path) { <del> return this.paths.some(function(p) { <del> return p instanceof RegExp ? p.test(path) : path.indexOf(p) === 0; <del> }); <del> }.bind(this); <add> const notIgnored = path => !ignored(path); <ide> <del> var notIgnored = function(path) { <del> return !ignored(path); <del> }; <add> const ignoredFiles = files.filter(ignored); <add> const ignoredDirs = dirs.filter(ignored); <ide> <del> var ignoredFiles = files.filter(ignored); <del> var ignoredDirs = dirs.filter(ignored); <add> this.wfs.watch(files.filter(notIgnored), dirs.filter(notIgnored), missing, startTime, options, (err, filesModified, dirsModified, missingModified, fileTimestamps, dirTimestamps) => { <add> if(err) return callback(err); <ide> <del> this.wfs.watch(files.filter(notIgnored), dirs.filter(notIgnored), missing, startTime, options, function(err, filesModified, dirsModified, missingModified, fileTimestamps, dirTimestamps) { <del> if(err) return callback(err); <add> ignoredFiles.forEach(path => { <add> fileTimestamps[path] = 1; <add> }); <ide> <del> ignoredFiles.forEach(function(path) { <del> fileTimestamps[path] = 1; <del> }); <del> <del> ignoredDirs.forEach(function(path) { <del> dirTimestamps[path] = 1; <del> }); <add> ignoredDirs.forEach(path => { <add> dirTimestamps[path] = 1; <add> }); <ide> <del> callback(err, filesModified, dirsModified, missingModified, fileTimestamps, dirTimestamps); <del> }, callbackUndelayed); <del>}; <add> callback(err, filesModified, dirsModified, missingModified, fileTimestamps, dirTimestamps); <add> }, callbackUndelayed); <add> } <add>} <ide><path>test/watchCases/plugins/watch-ignore-plugin/0/foo/0.js <add>export default 0; <ide><path>test/watchCases/plugins/watch-ignore-plugin/0/index.js <ide> import value from "./file" <ide> import a from "./a" <del>it("should ignore change to file", function() { <add>const req = require.context("./foo", false, /^.*\.js$/); <add>it("should ignore change to file and directory", function() { <ide> a.should.be.eql(+WATCH_STEP); <add> req.keys().should.be.deepEqual(["./0.js"]) <ide> value.should.be.eql(1); <ide> }); <ide><path>test/watchCases/plugins/watch-ignore-plugin/1/foo/1.js <add>export default 1; <ide><path>test/watchCases/plugins/watch-ignore-plugin/2/foo/2.js <add>export default 2; <ide><path>test/watchCases/plugins/watch-ignore-plugin/webpack.config.js <ide> var webpack = require("../../../../"); <add>var path = require("path"); <ide> <ide> module.exports = { <ide> plugins: [ <del> new webpack.WatchIgnorePlugin([/file\.js$/]) <add> new webpack.WatchIgnorePlugin([/file\.js$/, /foo$/]) <ide> ] <ide> };
6
Javascript
Javascript
hide editor mode if not used in a terminal
df43754fe1bf70042ae364f2365b42271468f102
<ide><path>lib/repl.js <ide> function defineDefaultCommands(repl) { <ide> this.displayPrompt(); <ide> } <ide> }); <del> <del> repl.defineCommand('editor', { <del> help: 'Enter editor mode', <del> action() { <del> if (!this.terminal) return; <del> _turnOnEditorMode(this); <del> this.outputStream.write( <del> '// Entering editor mode (^D to finish, ^C to cancel)\n'); <del> } <del> }); <add> if (repl.terminal) { <add> repl.defineCommand('editor', { <add> help: 'Enter editor mode', <add> action() { <add> _turnOnEditorMode(this); <add> this.outputStream.write( <add> '// Entering editor mode (^D to finish, ^C to cancel)\n'); <add> } <add> }); <add> } <ide> } <ide> <ide> function regexpEscape(s) { <ide><path>test/parallel/test-repl-save-load.js <ide> assert.strictEqual(fs.readFileSync(saveFileName, 'utf8'), <ide> '}' <ide> ]; <ide> const putIn = new ArrayStream(); <del> const replServer = repl.start('', putIn); <add> const replServer = repl.start({ terminal: true, stream: putIn }); <ide> <ide> putIn.run(['.editor']); <ide> putIn.run(cmds); <ide><path>test/parallel/test-repl.js <ide> const errorTests = [ <ide> expect: [ <ide> /\.break/, <ide> /\.clear/, <del> /\.editor/, <ide> /\.exit/, <ide> /\.help/, <ide> /\.load/,
3
Go
Go
skip non-persistent endpoints in sandbox store
d9ad8c961c01357cb6f0efc7678f6198761e6631
<ide><path>libnetwork/sandbox_store.go <ide> func (sb *sandbox) storeUpdate() error { <ide> retry: <ide> sbs.Eps = nil <ide> for _, ep := range sb.getConnectedEndpoints() { <add> // If the endpoint is not persisted then do not add it to <add> // the sandbox checkpoint <add> if ep.Skip() { <add> continue <add> } <add> <ide> eps := epState{ <ide> Nid: ep.getNetwork().ID(), <ide> Eid: ep.ID(),
1
Ruby
Ruby
extract encrypted models to their own files
81afcabd1985ba2c1b816d223b18eda6f0953282
<ide><path>activerecord/test/cases/encryption/concurrency_test.rb <ide> # frozen_string_literal: true <ide> <ide> require "cases/encryption/helper" <del>require "models/post" <add>require "models/post_encrypted" <ide> <ide> class ActiveRecord::Encryption::ConcurrencyTest < ActiveRecord::TestCase <ide> setup do <ide><path>activerecord/test/cases/encryption/configurable_test.rb <ide> # frozen_string_literal: true <ide> <ide> require "cases/encryption/helper" <del>require "models/book" <add>require "models/book_encrypted" <ide> <ide> class ActiveRecord::Encryption::ConfigurableTest < ActiveRecord::TestCase <ide> test "can access context properties with top level getters" do <ide><path>activerecord/test/cases/encryption/contexts_test.rb <ide> # frozen_string_literal: true <ide> <ide> require "cases/encryption/helper" <del>require "models/book" <del>require "models/post" <add>require "models/book_encrypted" <add>require "models/post_encrypted" <ide> <ide> class ActiveRecord::Encryption::ContextsTest < ActiveRecord::TestCase <ide> fixtures :posts <ide><path>activerecord/test/cases/encryption/encryptable_record_api_test.rb <ide> # frozen_string_literal: true <ide> <ide> require "cases/encryption/helper" <del>require "models/author" <del>require "models/book" <del>require "models/post" <add>require "models/author_encrypted" <add>require "models/book_encrypted" <add>require "models/post_encrypted" <ide> <ide> class ActiveRecord::Encryption::EncryptableRecordApiTest < ActiveRecord::TestCase <ide> fixtures :posts <ide><path>activerecord/test/cases/encryption/encryptable_record_test.rb <ide> # frozen_string_literal: true <ide> <ide> require "cases/encryption/helper" <del>require "models/author" <del>require "models/book" <del>require "models/post" <del>require "models/traffic_light" <add>require "models/author_encrypted" <add>require "models/book_encrypted" <add>require "models/post_encrypted" <add>require "models/traffic_light_encrypted" <ide> <ide> class ActiveRecord::Encryption::EncryptableRecordTest < ActiveRecord::TestCase <ide> fixtures :books, :posts <ide><path>activerecord/test/cases/encryption/encrypted_fixtures_test.rb <ide> # frozen_string_literal: true <ide> <ide> require "cases/encryption/helper" <del>require "models/book" <add>require "models/book_encrypted" <ide> <ide> class ActiveRecord::Encryption::EncryptableFixtureTest < ActiveRecord::TestCase <ide> fixtures :encrypted_books, :encrypted_book_that_ignores_cases <ide><path>activerecord/test/cases/encryption/encryption_schemes_test.rb <ide> # frozen_string_literal: true <ide> <ide> require "cases/encryption/helper" <del>require "models/author" <add>require "models/author_encrypted" <ide> <ide> class ActiveRecord::Encryption::EncryptionSchemesTest < ActiveRecord::TestCase <ide> test "can decrypt encrypted_value encrypted with a different encryption scheme" do <ide><path>activerecord/test/cases/encryption/extended_deterministic_queries_test.rb <ide> # frozen_string_literal: true <ide> <ide> require "cases/encryption/helper" <del>require "models/book" <add>require "models/book_encrypted" <ide> <ide> class ActiveRecord::Encryption::ExtendedDeterministicQueriesTest < ActiveRecord::TestCase <ide> setup do <ide><path>activerecord/test/cases/encryption/mass_encryption_test.rb <ide> # frozen_string_literal: true <ide> <ide> require "cases/encryption/helper" <del>require "models/author" <del>require "models/post" <add>require "models/author_encrypted" <add>require "models/post_encrypted" <ide> <ide> class ActiveRecord::Encryption::MassEncryptionTest < ActiveRecord::TestCase <ide> setup do <ide><path>activerecord/test/cases/encryption/performance/encryption_performance_test.rb <ide> # frozen_string_literal: true <ide> <ide> require "cases/encryption/helper" <del>require "models/book" <del>require "models/post" <add>require "models/book_encrypted" <add>require "models/post_encrypted" <ide> <ide> class ActiveRecord::Encryption::EncryptionPerformanceTest < ActiveRecord::TestCase <ide> fixtures :encrypted_books, :posts <ide><path>activerecord/test/cases/encryption/performance/envelope_encryption_performance_test.rb <ide> # frozen_string_literal: true <ide> <ide> require "cases/encryption/helper" <del>require "models/book" <add>require "models/book_encrypted" <ide> <ide> class ActiveRecord::Encryption::EvenlopeEncryptionPerformanceTest < ActiveRecord::TestCase <ide> fixtures :encrypted_books <ide><path>activerecord/test/cases/encryption/performance/extended_deterministic_queries_performance_test.rb <ide> # frozen_string_literal: true <ide> <ide> require "cases/encryption/helper" <del>require "models/book" <add>require "models/book_encrypted" <ide> <ide> class ActiveRecord::Encryption::ExtendedDeterministicQueriesPerformanceTest < ActiveRecord::TestCase <ide> # TODO: Is this failing only with SQLite/in memory adapter? <ide><path>activerecord/test/cases/encryption/unencrypted_attributes_test.rb <ide> # frozen_string_literal: true <ide> <ide> require "cases/encryption/helper" <del>require "models/post" <add>require "models/post_encrypted" <ide> <ide> class ActiveRecord::Encryption::UnencryptedAttributesTest < ActiveRecord::TestCase <ide> test "when :support_unencrypted_data is off, it works with unencrypted attributes normally" do <ide><path>activerecord/test/models/author.rb <ide> class AuthorFavoriteWithScope < ActiveRecord::Base <ide> belongs_to :author <ide> belongs_to :favorite_author, class_name: "Author" <ide> end <del> <del>class EncryptedAuthor < Author <del> self.table_name = "authors" <del> <del> encrypts :name, key: "my very own key", previous: { deterministic: true } <del>end <ide><path>activerecord/test/models/author_encrypted.rb <add># frozen_string_literal: true <add> <add>require "models/author" <add> <add>class EncryptedAuthor < Author <add> self.table_name = "authors" <add> <add> encrypts :name, key: "my very own key", previous: { deterministic: true } <add>end <ide><path>activerecord/test/models/book.rb <ide> class PublishedBook < ActiveRecord::Base <ide> <ide> validates_uniqueness_of :isbn <ide> end <del> <del>class EncryptedBook < Book <del> self.table_name = "books" <del> <del> encrypts :name, deterministic: true <del>end <del> <del>class EncryptedBookWithDowncaseName < Book <del> self.table_name = "books" <del> <del> encrypts :name, deterministic: true, downcase: true <del>end <del> <del>class EncryptedBookThatIgnoresCase < Book <del> self.table_name = "books" <del> <del> encrypts :name, deterministic: true, ignore_case: true <del>end <ide><path>activerecord/test/models/book_encrypted.rb <add># frozen_string_literal: true <add> <add>require "models/book" <add> <add>class EncryptedBook < Book <add> self.table_name = "books" <add> <add> encrypts :name, deterministic: true <add>end <add> <add>class EncryptedBookWithDowncaseName < Book <add> self.table_name = "books" <add> <add> encrypts :name, deterministic: true, downcase: true <add>end <add> <add>class EncryptedBookThatIgnoresCase < Book <add> self.table_name = "books" <add> <add> encrypts :name, deterministic: true, ignore_case: true <add>end <ide><path>activerecord/test/models/post.rb <ide> class Postesque < ActiveRecord::Base <ide> belongs_to :author_with_address, class_name: "Author", foreign_key: :author_id <ide> belongs_to :author_with_the_letter_a, class_name: "Author", foreign_key: :author_id <ide> end <del> <del>class EncryptedPost < Post <del> self.table_name = "posts" <del> <del> # We want to modify the key for testing purposes <del> class MutableDerivedSecretKeyProvider < ActiveRecord::Encryption::DerivedSecretKeyProvider <del> attr_accessor :key <del> end <del> <del> encrypts :title <del> encrypts :body, key_provider: MutableDerivedSecretKeyProvider.new("my post body secret!") <del>end <ide><path>activerecord/test/models/post_encrypted.rb <add># frozen_string_literal: true <add> <add>require "models/post" <add> <add>class EncryptedPost < Post <add> self.table_name = "posts" <add> <add> # We want to modify the key for testing purposes <add> class MutableDerivedSecretKeyProvider < ActiveRecord::Encryption::DerivedSecretKeyProvider <add> attr_accessor :key <add> end <add> <add> encrypts :title <add> encrypts :body, key_provider: MutableDerivedSecretKeyProvider.new("my post body secret!") <add>end <ide><path>activerecord/test/models/traffic_light.rb <ide> class TrafficLight < ActiveRecord::Base <ide> serialize :state, Array <ide> serialize :long_state, Array <ide> end <del> <del>class EncryptedTrafficLight < TrafficLight <del> encrypts :state <del>end <ide><path>activerecord/test/models/traffic_light_encrypted.rb <add># frozen_string_literal: true <add> <add> <add>require "models/traffic_light" <add> <add>class EncryptedTrafficLight < TrafficLight <add> encrypts :state <add>end
21
Java
Java
fix missing resources in gzipresourceresolvertests
72e4fac28d59ed5db3e81efe01ccbcc3a8311dbf
<ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/resource/GzipResourceResolverTests.java <ide> <ide> package org.springframework.web.reactive.resource; <ide> <add>import java.io.File; <ide> import java.io.FileOutputStream; <ide> import java.io.IOException; <add>import java.nio.file.Files; <add>import java.nio.file.Path; <add>import java.nio.file.Paths; <ide> import java.util.ArrayList; <ide> import java.util.HashMap; <ide> import java.util.List; <ide> public static void createGzippedResources() throws IOException { <ide> private static void createGzFile(String filePath) throws IOException { <ide> Resource location = new ClassPathResource("test/", GzipResourceResolverTests.class); <ide> Resource fileResource = new FileSystemResource(location.createRelative(filePath).getFile()); <del> Resource gzFileResource = location.createRelative(filePath + ".gz"); <del> <del> if (gzFileResource.getFile().createNewFile()) { <del> GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(gzFileResource.getFile())); <del> FileCopyUtils.copy(fileResource.getInputStream(), out); <del> } <del> <del> assertTrue(gzFileResource.exists()); <add> Path gzFilePath = Paths.get(fileResource.getFile().getAbsolutePath() + ".gz"); <add> Files.deleteIfExists(gzFilePath); <add> File gzFile = Files.createFile(gzFilePath).toFile(); <add> GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(gzFile)); <add> FileCopyUtils.copy(fileResource.getInputStream(), out); <add> gzFile.deleteOnExit(); <ide> } <ide> <ide> @Before <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/resource/GzipResourceResolverTests.java <ide> <ide> package org.springframework.web.servlet.resource; <ide> <add>import java.io.File; <ide> import java.io.FileOutputStream; <ide> import java.io.IOException; <add>import java.nio.file.Files; <add>import java.nio.file.Path; <add>import java.nio.file.Paths; <ide> import java.util.ArrayList; <ide> import java.util.HashMap; <ide> import java.util.List; <ide> public static void createGzippedResources() throws IOException { <ide> private static void createGzFile(String filePath) throws IOException { <ide> Resource location = new ClassPathResource("test/", GzipResourceResolverTests.class); <ide> Resource fileResource = new FileSystemResource(location.createRelative(filePath).getFile()); <del> Resource gzFileResource = location.createRelative(filePath + ".gz"); <del> <del> if (gzFileResource.getFile().createNewFile()) { <del> GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(gzFileResource.getFile())); <del> FileCopyUtils.copy(fileResource.getInputStream(), out); <del> } <del> <del> assertTrue(gzFileResource.exists()); <add> Path gzFilePath = Paths.get(fileResource.getFile().getAbsolutePath() + ".gz"); <add> Files.deleteIfExists(gzFilePath); <add> File gzFile = Files.createFile(gzFilePath).toFile(); <add> GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(gzFile)); <add> FileCopyUtils.copy(fileResource.getInputStream(), out); <add> gzFile.deleteOnExit(); <ide> } <ide> <ide>
2
Javascript
Javascript
replace instanceof check with nullness check
6a694f80f41730e9a32d208b5dc5547e3b286de9
<ide><path>src/workspace.js <ide> module.exports = class Workspace extends Model { <ide> if (paneContainer === this.getCenter()) { <ide> const itemIsTextEditor = item instanceof TextEditor <ide> const activeTextEditorChanged = <del> itemIsTextEditor || (this.activeTextEditor instanceof TextEditor) <add> itemIsTextEditor || (this.activeTextEditor != null) <ide> <ide> if (activeTextEditorChanged) { <ide> this.activeTextEditor = itemIsTextEditor ? item : null
1
Javascript
Javascript
remove rc suffix from versions
fc46dba67fc47783bbb5919e656c66c6e51ce16d
<ide><path>ReactVersions.js <ide> // <ide> // 0.0.0-experimental-241c4467e-20200129 <ide> <del>const ReactVersion = '18.0.0-rc.3'; <add>const ReactVersion = '18.0.0'; <ide> <ide> // The label used by the @next channel. Represents the upcoming release's <ide> // stability. Could be "alpha", "beta", "rc", etc. <ide> const nextChannelLabel = 'next'; <ide> <ide> const stablePackages = { <ide> 'create-subscription': ReactVersion, <del> 'eslint-plugin-react-hooks': '4.2.1-rc.3', <del> 'jest-react': '0.12.1-rc.3', <add> 'eslint-plugin-react-hooks': '4.4.0', <add> 'jest-react': '0.12.1', <ide> react: ReactVersion, <ide> 'react-art': ReactVersion, <ide> 'react-dom': ReactVersion, <ide> 'react-is': ReactVersion, <del> 'react-reconciler': '0.27.0-rc.3', <del> 'react-refresh': '0.11.0-rc.3', <add> 'react-reconciler': '0.27.0', <add> 'react-refresh': '0.11.0', <ide> 'react-test-renderer': ReactVersion, <del> 'use-subscription': '1.6.0-rc.3', <del> 'use-sync-external-store': '1.0.0-rc.3', <del> scheduler: '0.21.0-rc.3', <add> 'use-subscription': '1.6.0', <add> 'use-sync-external-store': '1.0.0', <add> scheduler: '0.21.0', <ide> }; <ide> <ide> // These packages do not exist in the @next or @latest channel, only
1
Java
Java
check both connection and connected flag
3bc1121b9d6f73f601776a20e6ec5b0e1ea0f4b2
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandler.java <ide> public void afterConnectionClosed() { <ide> public ListenableFuture<Void> forward(final Message<?> message, final StompHeaderAccessor accessor) { <ide> TcpConnection<byte[]> conn = this.tcpConnection; <ide> <del> if (!this.isStompConnected) { <add> if (!this.isStompConnected || conn == null) { <ide> if (this.isRemoteClientSession) { <ide> if (logger.isDebugEnabled()) { <ide> logger.debug("TCP connection closed already, ignoring " +
1
Go
Go
check version for docker-default aa profile
f8db9a09e0ec9b1925839ffff4f1cc5fe3ace630
<ide><path>contrib/apparmor/main.go <ide> import ( <ide> "fmt" <ide> "log" <ide> "os" <del> "os/exec" <ide> "path" <del> "strconv" <del> "strings" <ide> "text/template" <add> <add> "github.com/docker/docker/pkg/aaparser" <ide> ) <ide> <ide> type profileData struct { <ide> func main() { <ide> // parse the arg <ide> apparmorProfilePath := os.Args[1] <ide> <del> // get the apparmor_version version <del> cmd := exec.Command("/sbin/apparmor_parser", "--version") <del> <del> output, err := cmd.CombinedOutput() <del> if err != nil { <del> log.Fatalf("getting apparmor_parser version failed: %s (%s)", err, output) <del> } <del> <del> // parse the version from the output <del> // output is in the form of the following: <del> // AppArmor parser version 2.9.1 <del> // Copyright (C) 1999-2008 Novell Inc. <del> // Copyright 2009-2012 Canonical Ltd. <del> lines := strings.SplitN(string(output), "\n", 2) <del> words := strings.Split(lines[0], " ") <del> version := words[len(words)-1] <del> // split by major minor version <del> v := strings.Split(version, ".") <del> if len(v) < 2 { <del> log.Fatalf("parsing major minor version failed for %q", version) <del> } <del> <del> majorVersion, err := strconv.Atoi(v[0]) <del> if err != nil { <del> log.Fatal(err) <del> } <del> minorVersion, err := strconv.Atoi(v[1]) <add> majorVersion, minorVersion, err := aaparser.GetVersion() <ide> if err != nil { <ide> log.Fatal(err) <ide> } <ide><path>daemon/execdriver/native/apparmor.go <ide> import ( <ide> "strings" <ide> "text/template" <ide> <add> "github.com/docker/docker/pkg/aaparser" <ide> "github.com/opencontainers/runc/libcontainer/apparmor" <ide> ) <ide> <ide> const ( <ide> <ide> type data struct { <ide> Name string <add> ExecPath string <ide> Imports []string <ide> InnerImports []string <add> MajorVersion int <add> MinorVersion int <ide> } <ide> <ide> const baseTemplate = ` <ide> profile {{.Name}} flags=(attach_disconnected,mediate_deleted) { <ide> deny /sys/firmware/efi/efivars/** rwklx, <ide> deny /sys/kernel/security/** rwklx, <ide> <add>{{if ge .MajorVersion 2}}{{if ge .MinorVersion 9}} <ide> # docker daemon confinement requires explict allow rule for signal <del> signal (receive) set=(kill,term) peer=/usr/bin/docker, <add> signal (receive) set=(kill,term) peer={{.ExecPath}}, <ide> <ide> # suppress ptrace denails when using 'docker ps' <ide> ptrace (trace,read) peer=docker-default, <add>{{end}}{{end}} <ide> } <ide> ` <ide> <ide> func generateProfile(out io.Writer) error { <ide> if abstractionsExists() { <ide> data.InnerImports = append(data.InnerImports, "#include <abstractions/base>") <ide> } <add> data.MajorVersion, data.MinorVersion, err = aaparser.GetVersion() <add> if err != nil { <add> return err <add> } <add> data.ExecPath, err = exec.LookPath("docker") <add> if err != nil { <add> return err <add> } <ide> if err := compiled.Execute(out, data); err != nil { <ide> return err <ide> } <ide><path>pkg/aaparser/aaparser.go <add>package aaparser <add> <add>import ( <add> "fmt" <add> "log" <add> "os/exec" <add> "strconv" <add> "strings" <add>) <add> <add>// GetVersion returns the major and minor version of apparmor_parser <add>func GetVersion() (int, int, error) { <add> // get the apparmor_version version <add> cmd := exec.Command("apparmor_parser", "--version") <add> <add> output, err := cmd.CombinedOutput() <add> if err != nil { <add> log.Fatalf("getting apparmor_parser version failed: %s (%s)", err, output) <add> } <add> <add> // parse the version from the output <add> // output is in the form of the following: <add> // AppArmor parser version 2.9.1 <add> // Copyright (C) 1999-2008 Novell Inc. <add> // Copyright 2009-2012 Canonical Ltd. <add> lines := strings.SplitN(string(output), "\n", 2) <add> words := strings.Split(lines[0], " ") <add> version := words[len(words)-1] <add> // split by major minor version <add> v := strings.Split(version, ".") <add> if len(v) < 2 { <add> return -1, -1, fmt.Errorf("parsing major minor version failed for %q", version) <add> } <add> <add> majorVersion, err := strconv.Atoi(v[0]) <add> if err != nil { <add> return -1, -1, err <add> } <add> minorVersion, err := strconv.Atoi(v[1]) <add> if err != nil { <add> return -1, -1, err <add> } <add> <add> return majorVersion, minorVersion, nil <add>}
3
Javascript
Javascript
add dedicated lanepriority for suspense retries
965d08cfff50609eed5d3f2317145f7be762423d
<ide><path>packages/react-reconciler/src/ReactFiberLane.js <ide> export opaque type LanePriority = <ide> | 13 <ide> | 14 <ide> | 15 <del> | 16; <add> | 16 <add> | 17; <ide> export opaque type Lanes = number; <ide> export opaque type Lane = number; <ide> export opaque type LaneMap<T> = Array<T>; <ide> import { <ide> NoPriority as NoSchedulerPriority, <ide> } from './SchedulerWithReactIntegration.new'; <ide> <del>export const SyncLanePriority: LanePriority = 16; <del>const SyncBatchedLanePriority: LanePriority = 15; <add>export const SyncLanePriority: LanePriority = 17; <add>const SyncBatchedLanePriority: LanePriority = 16; <ide> <del>const InputDiscreteHydrationLanePriority: LanePriority = 14; <del>export const InputDiscreteLanePriority: LanePriority = 13; <add>const InputDiscreteHydrationLanePriority: LanePriority = 15; <add>export const InputDiscreteLanePriority: LanePriority = 14; <ide> <del>const InputContinuousHydrationLanePriority: LanePriority = 12; <del>export const InputContinuousLanePriority: LanePriority = 11; <add>const InputContinuousHydrationLanePriority: LanePriority = 13; <add>export const InputContinuousLanePriority: LanePriority = 12; <ide> <del>const DefaultHydrationLanePriority: LanePriority = 10; <del>export const DefaultLanePriority: LanePriority = 9; <add>const DefaultHydrationLanePriority: LanePriority = 11; <add>export const DefaultLanePriority: LanePriority = 10; <ide> <del>const TransitionShortHydrationLanePriority: LanePriority = 8; <del>export const TransitionShortLanePriority: LanePriority = 7; <add>const TransitionShortHydrationLanePriority: LanePriority = 9; <add>export const TransitionShortLanePriority: LanePriority = 8; <ide> <del>const TransitionLongHydrationLanePriority: LanePriority = 6; <del>export const TransitionLongLanePriority: LanePriority = 5; <add>const TransitionLongHydrationLanePriority: LanePriority = 7; <add>export const TransitionLongLanePriority: LanePriority = 6; <add> <add>const RetryLanePriority: LanePriority = 5; <ide> <ide> const SelectiveHydrationLanePriority: LanePriority = 4; <ide> <ide> const InputContinuousUpdateRangeStart = 6; <ide> const InputContinuousUpdateRangeEnd = 8; <ide> <ide> export const DefaultHydrationLane: Lane = /* */ 0b0000000000000000000000100000000; <del>const DefaultLanes: Lanes = /* */ 0b0000000000000000011111100000000; <add>export const DefaultLanes: Lanes = /* */ 0b0000000000000000000111100000000; <ide> const DefaultUpdateRangeStart = 9; <del>const DefaultUpdateRangeEnd = 14; <add>const DefaultUpdateRangeEnd = 12; <add> <add>const TransitionShortHydrationLane: Lane = /* */ 0b0000000000000000001000000000000; <add>const TransitionShortLanes: Lanes = /* */ 0b0000000000000011111000000000000; <add>const TransitionShortUpdateRangeStart = 13; <add>const TransitionShortUpdateRangeEnd = 17; <ide> <del>const TransitionShortHydrationLane: Lane = /* */ 0b0000000000000000100000000000000; <del>const TransitionShortLanes: Lanes = /* */ 0b0000000000011111100000000000000; <del>const TransitionShortUpdateRangeStart = 15; <del>const TransitionShortUpdateRangeEnd = 20; <add>const TransitionLongHydrationLane: Lane = /* */ 0b0000000000000100000000000000000; <add>const TransitionLongLanes: Lanes = /* */ 0b0000000001111100000000000000000; <add>const TransitionLongUpdateRangeStart = 18; <add>const TransitionLongUpdateRangeEnd = 22; <ide> <del>const TransitionLongHydrationLane: Lane = /* */ 0b0000000000100000000000000000000; <del>const TransitionLongLanes: Lanes = /* */ 0b0000011111100000000000000000000; <del>const TransitionLongUpdateRangeStart = 21; <del>const TransitionLongUpdateRangeEnd = 26; <add>// Includes all updates. Except Idle updates, which have special semantics. <add>const UpdateRangeEnd = TransitionLongUpdateRangeEnd; <ide> <del>export const SelectiveHydrationLane: Lane = /* */ 0b0000110000000000000000000000000; <add>const RetryLanes: Lanes = /* */ 0b0000011110000000000000000000000; <add>const RetryRangeStart = 22; <add>const RetryRangeEnd = 26; <add> <add>export const SelectiveHydrationLane: Lane = /* */ 0b0000100000000000000000000000000; <ide> const SelectiveHydrationRangeEnd = 27; <ide> <del>// Includes all non-Idle updates <del>const UpdateRangeEnd = 27; <ide> const NonIdleLanes = /* */ 0b0000111111111111111111111111111; <ide> <ide> export const IdleHydrationLane: Lane = /* */ 0b0001000000000000000000000000000; <ide> function getHighestPriorityLanes(lanes: Lanes | Lane): Lanes { <ide> return transitionLongLanes; <ide> } <ide> } <add> const retryLanes = RetryLanes & lanes; <add> if (retryLanes !== NoLanes) { <add> return_highestLanePriority = RetryLanePriority; <add> return_updateRangeEnd = RetryRangeEnd; <add> return retryLanes; <add> } <ide> if (lanes & SelectiveHydrationLane) { <ide> return_highestLanePriority = SelectiveHydrationLanePriority; <ide> return_updateRangeEnd = SelectiveHydrationRangeEnd; <ide> export function lanePriorityToSchedulerPriority( <ide> case TransitionLongHydrationLanePriority: <ide> case TransitionLongLanePriority: <ide> case SelectiveHydrationLanePriority: <add> case RetryLanePriority: <ide> return NormalSchedulerPriority; <ide> case IdleHydrationLanePriority: <ide> case IdleLanePriority: <ide> export function findUpdateLane( <ide> case TransitionLongLanePriority: <ide> // Should be handled by findTransitionLane instead <ide> break; <add> case RetryLanePriority: <add> // Should be handled by findRetryLane instead <add> break; <ide> case IdleLanePriority: <ide> let lane = findLane(IdleUpdateRangeStart, IdleUpdateRangeEnd, wipLanes); <ide> if (lane === NoLane) { <ide> export function findTransitionLane( <ide> ); <ide> } <ide> <add>// To ensure consistency across multiple updates in the same event, this should <add>// be pure function, so that it always returns the same lane for given inputs. <add>export function findRetryLane(wipLanes: Lanes): Lane { <add> // This is a fork of `findUpdateLane` designed specifically for Suspense <add> // "retries" — a special update that attempts to flip a Suspense boundary <add> // from its placeholder state to its primary/resolved state. <add> let lane = findLane(RetryRangeStart, RetryRangeEnd, wipLanes); <add> if (lane === NoLane) { <add> lane = pickArbitraryLane(RetryLanes); <add> } <add> return lane; <add>} <add> <ide> function findLane(start, end, skipLanes) { <ide> // This finds the first bit between the `start` and `end` positions that isn't <ide> // in `skipLanes`. <ide> export function getBumpedLaneForHydration( <ide> case TransitionLongLanePriority: <ide> lane = TransitionLongHydrationLane; <ide> break; <add> case RetryLanePriority: <add> // Shouldn't be reachable under normal circumstances, so there's no <add> // dedicated lane for retry priority. Use the one for long transitions. <add> lane = TransitionLongHydrationLane; <add> break; <ide> case SelectiveHydrationLanePriority: <ide> lane = SelectiveHydrationLane; <ide> break; <ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.new.js <ide> import { <ide> NoTimestamp, <ide> findUpdateLane, <ide> findTransitionLane, <add> findRetryLane, <ide> includesSomeLane, <ide> isSubsetOfLanes, <ide> mergeLanes, <ide> export function requestUpdateLane( <ide> return lane; <ide> } <ide> <add>function requestRetryLane(fiber: Fiber) { <add> // This is a fork of `requestUpdateLane` designed specifically for Suspense <add> // "retries" — a special update that attempts to flip a Suspense boundary <add> // from its placeholder state to its primary/resolved state. <add> <add> // Special cases <add> const mode = fiber.mode; <add> if ((mode & BlockingMode) === NoMode) { <add> return (SyncLane: Lane); <add> } else if ((mode & ConcurrentMode) === NoMode) { <add> return getCurrentPriorityLevel() === ImmediateSchedulerPriority <add> ? (SyncLane: Lane) <add> : (SyncBatchedLane: Lane); <add> } <add> <add> // See `requestUpdateLane` for explanation of `currentEventWipLanes` <add> if (currentEventWipLanes === NoLanes) { <add> currentEventWipLanes = workInProgressRootIncludedLanes; <add> } <add> return findRetryLane(currentEventWipLanes); <add>} <add> <ide> export function scheduleUpdateOnFiber( <ide> fiber: Fiber, <ide> lane: Lane, <ide> function retryTimedOutBoundary(boundaryFiber: Fiber, retryLane: Lane) { <ide> // suspended it has resolved, which means at least part of the tree was <ide> // likely unblocked. Try rendering again, at a new expiration time. <ide> if (retryLane === NoLane) { <del> const suspenseConfig = null; // Retries don't carry over the already committed update. <del> // TODO: Should retries get their own lane? Maybe it could share with <del> // transitions. <del> retryLane = requestUpdateLane(boundaryFiber, suspenseConfig); <add> retryLane = requestRetryLane(boundaryFiber); <ide> } <ide> // TODO: Special case idle priority? <ide> const eventTime = requestEventTime(); <ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.old.js <ide> import { <ide> NoTimestamp, <ide> findUpdateLane, <ide> findTransitionLane, <add> findRetryLane, <ide> includesSomeLane, <ide> isSubsetOfLanes, <ide> mergeLanes, <ide> export function requestUpdateLane( <ide> return lane; <ide> } <ide> <add>function requestRetryLane(fiber: Fiber) { <add> // This is a fork of `requestUpdateLane` designed specifically for Suspense <add> // "retries" — a special update that attempts to flip a Suspense boundary <add> // from its placeholder state to its primary/resolved state. <add> <add> // Special cases <add> const mode = fiber.mode; <add> if ((mode & BlockingMode) === NoMode) { <add> return (SyncLane: Lane); <add> } else if ((mode & ConcurrentMode) === NoMode) { <add> return getCurrentPriorityLevel() === ImmediateSchedulerPriority <add> ? (SyncLane: Lane) <add> : (SyncBatchedLane: Lane); <add> } <add> <add> // See `requestUpdateLane` for explanation of `currentEventWipLanes` <add> if (currentEventWipLanes === NoLanes) { <add> currentEventWipLanes = workInProgressRootIncludedLanes; <add> } <add> return findRetryLane(currentEventWipLanes); <add>} <add> <ide> export function scheduleUpdateOnFiber( <ide> fiber: Fiber, <ide> lane: Lane, <ide> function retryTimedOutBoundary(boundaryFiber: Fiber, retryLane: Lane) { <ide> // suspended it has resolved, which means at least part of the tree was <ide> // likely unblocked. Try rendering again, at a new expiration time. <ide> if (retryLane === NoLane) { <del> const suspenseConfig = null; // Retries don't carry over the already committed update. <del> // TODO: Should retries get their own lane? Maybe it could share with <del> // transitions. <del> retryLane = requestUpdateLane(boundaryFiber, suspenseConfig); <add> retryLane = requestRetryLane(boundaryFiber); <ide> } <ide> // TODO: Special case idle priority? <ide> const eventTime = requestEventTime(); <ide><path>packages/react-reconciler/src/__tests__/ReactSuspenseCallback-test.internal.js <ide> describe('ReactSuspense', () => { <ide> await resolve1(); <ide> ReactNoop.render(element); <ide> expect(Scheduler).toFlushWithoutYielding(); <add> <add> // Force fallback to commit. <add> // TODO: Should be able to use `act` here. <add> jest.runAllTimers(); <add> <ide> expect(ReactNoop.getChildren()).toEqual([ <ide> text('Waiting Tier 2'), <ide> text('Done'), <ide><path>packages/react-reconciler/src/__tests__/ReactSuspenseWithNoopRenderer-test.js <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> // The new reconciler batches everything together, so it finishes without <ide> // suspending again. <ide> 'Sibling', <add> <add> // NOTE: The final of the update got pushed into a lower priority range of <add> // lanes, leading to the extra intermediate render. This is because when <add> // we schedule the fourth update, we're already in the middle of rendering <add> // the three others. Since there are only three lanes in the default <add> // range, the fourth lane is shifted to slightly lower priority. This <add> // could easily change when we tweak our batching heuristics. Ideally, <add> // they'd all have default priority and render in a single batch. <add> 'Suspend! [Step 3]', <add> 'Sibling', <add> <ide> 'Step 4', <ide> ]); <ide> }); <ide> describe('ReactSuspenseWithNoopRenderer', () => { <ide> expect(Scheduler).toHaveYielded(['Promise resolved [B]', 'B']); <ide> expect(root).toMatchRenderedOutput(<span prop="B" />); <ide> }); <add> <add> it('retries have lower priority than normal updates', async () => { <add> const {useState} = React; <add> <add> let setText; <add> function UpdatingText() { <add> const [text, _setText] = useState('A'); <add> setText = _setText; <add> return <Text text={text} />; <add> } <add> <add> const root = ReactNoop.createRoot(); <add> await ReactNoop.act(async () => { <add> root.render( <add> <> <add> <UpdatingText /> <add> <Suspense fallback={<Text text="Loading..." />}> <add> <AsyncText text="Async" /> <add> </Suspense> <add> </>, <add> ); <add> }); <add> expect(Scheduler).toHaveYielded(['A', 'Suspend! [Async]', 'Loading...']); <add> expect(root).toMatchRenderedOutput( <add> <> <add> <span prop="A" /> <add> <span prop="Loading..." /> <add> </>, <add> ); <add> <add> await ReactNoop.act(async () => { <add> // Resolve the promise. This will trigger a retry. <add> await resolveText('Async'); <add> expect(Scheduler).toHaveYielded(['Promise resolved [Async]']); <add> // Before the retry happens, schedule a new update. <add> setText('B'); <add> <add> // The update should be allowed to finish before the retry is attempted. <add> expect(Scheduler).toFlushUntilNextPaint(['B']); <add> expect(root).toMatchRenderedOutput( <add> <> <add> <span prop="B" /> <add> <span prop="Loading..." /> <add> </>, <add> ); <add> }); <add> // Then do the retry. <add> expect(Scheduler).toHaveYielded(['Async']); <add> expect(root).toMatchRenderedOutput( <add> <> <add> <span prop="B" /> <add> <span prop="Async" /> <add> </>, <add> ); <add> }); <ide> }); <ide><path>packages/react/src/__tests__/ReactProfiler-test.internal.js <ide> describe('Profiler', () => { <ide> <ide> expect(onPostCommit).toHaveBeenCalledTimes(1); <ide> expect(onPostCommit.mock.calls[0][4]).toMatchInteractions([ <del> initialRenderInteraction, <ide> highPriUpdateInteraction, <ide> ]); <ide>
6
Text
Text
remove duplicate content
28e1be83df3453b2a14d6ecc9b3bcd89733c50d5
<ide><path>examples/with-iron-session/README.md <ide> It uses current best practices for authentication in the Next.js ecosystem. <ide> <ide> **Features:** <ide> <del>- [Static Generation](https://nextjs.org/docs/basic-features/pages#static-generation-recommended) (SG), recommended example <del>- [Server-side Rendering](https://nextjs.org/docs/basic-features/pages#server-side-rendering) (SSR) example in case you need it <del>- Logged in status synchronized between browser windows/tabs using **`withUser`** hook and [`swr`](https://swr.now.sh/) module <del>- Layout based on logged-in status <del>- Session data is signed and encrypted in a cookie <del> <del>This example creates an authentication system that uses a **signed and encrypted cookie to store session data**. It relies on [`next-iron-session`](https://github.com/vvo/next-iron-session). <del> <del>It uses current best practices for authentication in the Next.js ecosystem. <del> <del>**Features:** <del> <ide> - [Static Generation](https://nextjs.org/docs/basic-features/pages#static-generation-recommended) (SG), recommended example <ide> - [Server-side Rendering](https://nextjs.org/docs/basic-features/pages#server-side-rendering) (SSR) example in case you need it <ide> - Logged in status synchronized between browser windows/tabs using **`withUser`** hook and [`swr`](https://swr.now.sh/) module
1
Ruby
Ruby
improve support for local bottle installs
0735eba995a1b35d14fbba8f41553d96b2fa14f7
<ide><path>Library/Homebrew/formula_installer.rb <ide> def install <ide> options = display_options(formula).join(" ") <ide> oh1 "Installing #{Formatter.identifier(formula.full_name)} #{options}".strip if show_header? <ide> <del> unless formula.tap&.private? <add> if formula.tap&.installed? && !formula.tap&.private? <ide> action = "#{formula.full_name} #{options}".strip <ide> Utils::Analytics.report_event("install", action) <ide> <ide> def pour <ide> tab.source["versions"]["stable"] = formula.stable.version.to_s <ide> tab.source["versions"]["version_scheme"] = formula.version_scheme <ide> tab.source["path"] = formula.specified_path.to_s <del> tab.source["tap_git_head"] = formula.tap&.git_head <add> tab.source["tap_git_revision"] = formula.tap&.installed? ? formula.tap&.git_head : nil <ide> tab.tap = formula.tap <ide> tab.write <ide> <ide><path>Library/Homebrew/tab.rb <ide> def self.create(formula, compiler, stdlib) <ide> "runtime_dependencies" => Tab.runtime_deps_hash(formula, runtime_deps), <ide> "arch" => Hardware::CPU.arch, <ide> "source" => { <del> "path" => formula.specified_path.to_s, <del> "tap" => formula.tap&.name, <del> "tap_git_head" => formula.tap&.git_head, <del> "spec" => formula.active_spec_sym.to_s, <del> "versions" => { <add> "path" => formula.specified_path.to_s, <add> "tap" => formula.tap&.name, <add> "tap_git_revision" => formula.tap&.git_head, <add> "spec" => formula.active_spec_sym.to_s, <add> "versions" => { <ide> "stable" => formula.stable&.version.to_s, <ide> "head" => formula.head&.version.to_s, <ide> "version_scheme" => formula.version_scheme, <ide> def self.empty <ide> "runtime_dependencies" => nil, <ide> "arch" => nil, <ide> "source" => { <del> "path" => nil, <del> "tap" => nil, <del> "tap_git_head" => nil, <del> "spec" => "stable", <del> "versions" => { <add> "path" => nil, <add> "tap" => nil, <add> "tap_git_revision" => nil, <add> "spec" => "stable", <add> "versions" => { <ide> "stable" => nil, <ide> "head" => nil, <ide> "version_scheme" => 0,
2
Ruby
Ruby
fix status code check in check_bintray_mirror
7a75de7cb135cfa832acbf58819329cc19b0fe41
<ide><path>Library/Homebrew/dev-cmd/pull.rb <ide> def verify_bintray_published(formulae_names) <ide> def check_bintray_mirror(name, url) <ide> headers = curl_output("--connect-timeout", "15", "--head", url)[0] <ide> status_code = headers.scan(%r{^HTTP\/.* (\d+)}).last.first <del> return if status_code.start_with?("3") <add> return if status_code.start_with?("2") <ide> opoo "The Bintray mirror #{url} is not reachable (HTTP status code #{status_code})." <ide> opoo "Do you need to upload it with `brew mirror #{name}`?" <ide> end
1
Javascript
Javascript
provide support for dynamic message resolution
c9a4421fc3c97448527eadef1f42eb2f487ec2e0
<ide><path>src/ngMessages/messages.js <ide> 'use strict'; <ide> <add>/* jshint ignore:start */ <add>// this code is in the core, but not in angular-messages.js <add>var isArray = angular.isArray; <add>var forEach = angular.forEach; <add>var isString = angular.isString; <add>var jqLite = angular.element; <add>/* jshint ignore:end */ <add> <ide> /** <ide> * @ngdoc module <ide> * @name ngMessages <ide> * `ngMessage` directives are designed to handle the complexity, inheritance and priority <ide> * sequencing based on the order of how the messages are defined in the template. <ide> * <del> * Currently, the ngMessages module only contains the code for the `ngMessages` <del> * and `ngMessage` directives. <add> * Currently, the ngMessages module only contains the code for the `ngMessages`, `ngMessagesInclude` <add> * `ngMessage` and `ngMessageExp` directives. <ide> * <ide> * # Usage <ide> * The `ngMessages` directive listens on a key/value collection which is set on the ngMessages attribute. <ide> * <input type="text" ng-model="field" name="myField" required minlength="5" /> <ide> * <div ng-messages="myForm.myField.$error"> <ide> * <div ng-message="required">You did not enter a field</div> <del> * <div ng-message="minlength">The value entered is too short</div> <add> * <div ng-message="minlength, maxlength"> <add> * Your email must be between 5 and 100 characters long <add> * </div> <ide> * </div> <ide> * </form> <ide> * ``` <ide> * ngMessages directive to make this happen. <ide> * <ide> * ```html <add> * <!-- attribute-style usage --> <ide> * <div ng-messages="myForm.myField.$error" ng-messages-multiple>...</div> <add> * <add> * <!-- element-style usage --> <add> * <ng-messages for="myForm.myField.$error" multiple>...</ng-messages> <ide> * ``` <ide> * <ide> * ## Reusing and Overriding Messages <ide> * <div ng-message="required">This field is required</div> <ide> * <div ng-message="minlength">This field is too short</div> <ide> * </script> <del> * <div ng-messages="myForm.myField.$error" ng-messages-include="error-messages"></div> <add> * <add> * <div ng-messages="myForm.myField.$error"> <add> * <div ng-messages-include="error-messages"></div> <add> * </div> <ide> * ``` <ide> * <ide> * However, including generic messages may not be useful enough to match all input fields, therefore, <ide> * minlength="5" <ide> * required /> <ide> * <del> * <div ng-messages="myForm.myEmail.$error" ng-messages-include="my-custom-messages"> <add> * <!-- any ng-message elements that appear BEFORE the ng-messages-include will <add> * override the messages present in the ng-messages-include template --> <add> * <div ng-messages="myForm.myEmail.$error"> <ide> * <!-- this required message has overridden the template message --> <ide> * <div ng-message="required">You did not enter your email address</div> <ide> * <ide> * <!-- this is a brand new message and will appear last in the prioritization --> <ide> * <div ng-message="email">Your email address is invalid</div> <add> * <add> * <!-- and here are the generic error messages --> <add> * <div ng-messages-include="error-messages"></div> <ide> * </div> <ide> * </form> <ide> * ``` <ide> * email addresses, date fields, autocomplete inputs, etc...), specialized error messages can be applied <ide> * while more generic messages can be used to handle other, more general input errors. <ide> * <add> * ## Dynamic Messaging <add> * ngMessages also supports using expressions to dynamically change key values. Using arrays and <add> * repeaters to list messages is also supported. This means that the code below will be able to <add> * fully adapt itself and display the appropriate message when any of the expression data changes: <add> * <add> * ```html <add> * <form name="myForm"> <add> * <input type="email" <add> * name="myEmail" <add> * ng-model="email" <add> * minlength="5" <add> * required /> <add> * <add> * <div ng-messages="myForm.myEmail.$error"> <add> * <div ng-message="required">You did not enter your email address</div> <add> * <div ng-repeat="errorMessage in errorMessages"> <add> * <!-- use ng-message-exp for a message whose key is given by an expression --> <add> * <div ng-message-exp="errorMessage.type">{{ errorMessage.text }}</div> <add> * </div> <add> * </div> <add> * </form> <add> * ``` <add> * <add> * The `errorMessage.type` expression can be a string value or it can be an array so <add> * that multiple errors can be associated with a single error message: <add> * <add> * ```html <add> * <input type="email" <add> * ng-model="data.email" <add> * name="myEmail" <add> * ng-minlength="5" <add> * ng-maxlength="100" <add> * required /> <add> * <div ng-messages="myForm.myEmail.$error"> <add> * <div ng-message-exp="'required'">You did not enter your email address</div> <add> * <div ng-message-exp="['minlength', 'maxlength]"> <add> * Your email must be between 5 and 100 characters long <add> * </div> <add> * </div> <add> * ``` <add> * <add> * Feel free to use other structural directives such as ng-if and ng-switch to further control <add> * what messages are active and when. Be careful, if you place ng-message on the same element <add> * as these structural directives, Angular may not be able to determine if a message is active <add> * or not. Therefore it is best to place the ng-message on a child element of the structural <add> * directive. <add> * <add> * ```html <add> * <div ng-messages="myForm.myEmail.$error"> <add> * <div ng-if="showRequiredError"> <add> * <div ng-message="required">Please enter something</div> <add> * </div> <add> * </div> <add> * ``` <add> * <ide> * ## Animations <del> * If the `ngAnimate` module is active within the application then both the `ngMessages` and <del> * `ngMessage` directives will trigger animations whenever any messages are added and removed <del> * from the DOM by the `ngMessages` directive. <add> * If the `ngAnimate` module is active within the application then the `ngMessages`, `ngMessage` and <add> * `ngMessageExp` directives will trigger animations whenever any messages are added and removed from <add> * the DOM by the `ngMessages` directive. <ide> * <ide> * Whenever the `ngMessages` directive contains one or more visible messages then the `.ng-active` CSS <ide> * class will be added to the element. The `.ng-inactive` CSS class will be applied when there are no <ide> angular.module('ngMessages', []) <ide> * messages use the `ngMessage` directive and will be inserted/removed from the page depending <ide> * on if they're present within the key/value object. By default, only one message will be displayed <ide> * at a time and this depends on the prioritization of the messages within the template. (This can <del> * be changed by using the ng-messages-multiple on the directive container.) <add> * be changed by using the `ng-messages-multiple` or `multiple` attribute on the directive container.) <ide> * <ide> * A remote template can also be used to promote message reusability and messages can also be <ide> * overridden. <ide> angular.module('ngMessages', []) <ide> * ```html <ide> * <!-- using attribute directives --> <ide> * <ANY ng-messages="expression"> <del> * <ANY ng-message="keyValue1">...</ANY> <del> * <ANY ng-message="keyValue2">...</ANY> <del> * <ANY ng-message="keyValue3">...</ANY> <add> * <ANY ng-message="stringValue">...</ANY> <add> * <ANY ng-message="stringValue1, stringValue2, ...">...</ANY> <add> * <ANY ng-message-exp="expressionValue">...</ANY> <ide> * </ANY> <ide> * <ide> * <!-- or by using element directives --> <ide> * <ng-messages for="expression"> <del> * <ng-message when="keyValue1">...</ng-message> <del> * <ng-message when="keyValue2">...</ng-message> <del> * <ng-message when="keyValue3">...</ng-message> <add> * <ng-message when="stringValue">...</ng-message> <add> * <ng-message when="stringValue1, stringValue2, ...">...</ng-message> <add> * <ng-message when-exp="expressionValue">...</ng-message> <ide> * </ng-messages> <ide> * ``` <ide> * <ide> * @param {string} ngMessages an angular expression evaluating to a key/value object <ide> * (this is typically the $error object on an ngModel instance). <ide> * @param {string=} ngMessagesMultiple|multiple when set, all messages will be displayed with true <del> * @param {string=} ngMessagesInclude|include when set, the specified template will be included into the ng-messages container <ide> * <ide> * @example <ide> * <example name="ngMessages-directive" module="ngMessagesExample" <ide> angular.module('ngMessages', []) <ide> * </file> <ide> * </example> <ide> */ <del> .directive('ngMessages', ['$compile', '$animate', '$templateRequest', <del> function($compile, $animate, $templateRequest) { <del> var ACTIVE_CLASS = 'ng-active'; <del> var INACTIVE_CLASS = 'ng-inactive'; <add> .directive('ngMessages', ['$animate', function($animate) { <add> var ACTIVE_CLASS = 'ng-active'; <add> var INACTIVE_CLASS = 'ng-inactive'; <ide> <del> return { <del> restrict: 'AE', <del> controller: function() { <del> this.$renderNgMessageClasses = angular.noop; <del> <del> var messages = []; <del> this.registerMessage = function(index, message) { <del> for (var i = 0; i < messages.length; i++) { <del> if (messages[i].type == message.type) { <del> if (index != i) { <del> var temp = messages[index]; <del> messages[index] = messages[i]; <del> if (index < messages.length) { <del> messages[i] = temp; <del> } else { <del> messages.splice(0, i); //remove the old one (and shift left) <del> } <del> } <del> return; <del> } <del> } <del> messages.splice(index, 0, message); //add the new one (and shift right) <del> }; <add> return { <add> require: 'ngMessages', <add> restrict: 'AE', <add> controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) { <add> var ctrl = this; <add> var latestKey = 0; <ide> <del> this.renderMessages = function(values, multiple) { <del> values = values || {}; <add> var messages = this.messages = {}; <add> var renderLater, cachedCollection; <ide> <del> var found; <del> angular.forEach(messages, function(message) { <del> if ((!found || multiple) && truthyVal(values[message.type])) { <del> message.attach(); <del> found = true; <del> } else { <del> message.detach(); <del> } <del> }); <add> this.render = function(collection) { <add> collection = collection || {}; <ide> <del> this.renderElementClasses(found); <add> renderLater = false; <add> cachedCollection = collection; <ide> <del> function truthyVal(value) { <del> return value !== null && value !== false && value; <del> } <del> }; <del> }, <del> require: 'ngMessages', <del> link: function($scope, element, $attrs, ctrl) { <del> ctrl.renderElementClasses = function(bool) { <del> bool ? $animate.setClass(element, ACTIVE_CLASS, INACTIVE_CLASS) <del> : $animate.setClass(element, INACTIVE_CLASS, ACTIVE_CLASS); <del> }; <add> // this is true if the attribute is empty or if the attribute value is truthy <add> var multiple = isAttrTruthy($scope, $attrs.ngMessagesMultiple) || <add> isAttrTruthy($scope, $attrs.multiple); <ide> <del> //JavaScript treats empty strings as false, but ng-message-multiple by itself is an empty string <del> var multiple = angular.isString($attrs.ngMessagesMultiple) || <del> angular.isString($attrs.multiple); <add> var unmatchedMessages = []; <add> var matchedKeys = {}; <add> var messageItem = ctrl.head; <add> var messageFound = false; <add> var totalMessages = 0; <ide> <del> var cachedValues, watchAttr = $attrs.ngMessages || $attrs['for']; //for is a reserved keyword <del> $scope.$watchCollection(watchAttr, function(values) { <del> cachedValues = values; <del> ctrl.renderMessages(values, multiple); <del> }); <add> // we use != instead of !== to allow for both undefined and null values <add> while (messageItem != null) { <add> totalMessages++; <add> var messageCtrl = messageItem.message; <ide> <del> var tpl = $attrs.ngMessagesInclude || $attrs.include; <del> if (tpl) { <del> $templateRequest(tpl) <del> .then(function processTemplate(html) { <del> var after, container = angular.element('<div/>').html(html); <del> angular.forEach(container.children(), function(elm) { <del> elm = angular.element(elm); <del> after ? after.after(elm) <del> : element.prepend(elm); //start of the container <del> after = elm; <del> $compile(elm)($scope); <del> }); <del> ctrl.renderMessages(cachedValues, multiple); <del> }); <del> } <del> } <del> }; <del> }]) <add> var messageUsed = false; <add> if (!messageFound) { <add> forEach(collection, function(value, key) { <add> if (!messageUsed && truthy(value) && messageCtrl.test(key)) { <add> // this is to prevent the same error name from showing up twice <add> if (matchedKeys[key]) return; <add> matchedKeys[key] = true; <add> <add> messageUsed = true; <add> messageCtrl.attach(); <add> } <add> }); <add> } <add> <add> if (messageUsed) { <add> // unless we want to display multiple messages then we should <add> // set a flag here to avoid displaying the next message in the list <add> messageFound = !multiple; <add> } else { <add> unmatchedMessages.push(messageCtrl); <add> } <add> <add> messageItem = messageItem.next; <add> } <add> <add> forEach(unmatchedMessages, function(messageCtrl) { <add> messageCtrl.detach(); <add> }); <ide> <add> unmatchedMessages.length !== totalMessages <add> ? $animate.setClass($element, ACTIVE_CLASS, INACTIVE_CLASS) <add> : $animate.setClass($element, INACTIVE_CLASS, ACTIVE_CLASS); <add> }; <add> <add> $scope.$watchCollection($attrs.ngMessages || $attrs['for'], ctrl.render); <add> <add> this.reRender = function() { <add> if (!renderLater) { <add> renderLater = true; <add> $scope.$evalAsync(function() { <add> if (renderLater) { <add> cachedCollection && ctrl.render(cachedCollection); <add> } <add> }); <add> } <add> }; <add> <add> this.register = function(comment, messageCtrl) { <add> var nextKey = latestKey.toString(); <add> messages[nextKey] = { <add> message: messageCtrl <add> }; <add> insertMessageNode($element[0], comment, nextKey); <add> comment.$$ngMessageNode = nextKey; <add> latestKey++; <add> <add> ctrl.reRender(); <add> }; <add> <add> this.deregister = function(comment) { <add> var key = comment.$$ngMessageNode; <add> delete comment.$$ngMessageNode; <add> removeMessageNode($element[0], comment, key); <add> delete messages[key]; <add> ctrl.reRender(); <add> }; <add> <add> function findPreviousMessage(parent, comment) { <add> var prevNode = comment; <add> var parentLookup = []; <add> while (prevNode && prevNode !== parent) { <add> var prevKey = prevNode.$$ngMessageNode; <add> if (prevKey && prevKey.length) { <add> return messages[prevKey]; <add> } <add> <add> // dive deeper into the DOM and examine its children for any ngMessage <add> // comments that may be in an element that appears deeper in the list <add> if (prevNode.childNodes.length && parentLookup.indexOf(prevNode) == -1) { <add> parentLookup.push(prevNode); <add> prevNode = prevNode.childNodes[prevNode.childNodes.length - 1]; <add> } else { <add> prevNode = prevNode.previousSibling || prevNode.parentNode; <add> } <add> } <add> } <add> <add> function insertMessageNode(parent, comment, key) { <add> var messageNode = messages[key]; <add> if (!ctrl.head) { <add> ctrl.head = messageNode; <add> } else { <add> var match = findPreviousMessage(parent, comment); <add> if (match) { <add> messageNode.next = match.next; <add> match.next = messageNode; <add> } else { <add> messageNode.next = ctrl.head; <add> ctrl.head = messageNode; <add> } <add> } <add> } <add> <add> function removeMessageNode(parent, comment, key) { <add> var messageNode = messages[key]; <add> <add> var match = findPreviousMessage(parent, comment); <add> if (match) { <add> match.next = messageNode.next; <add> } else { <add> ctrl.head = messageNode.next; <add> } <add> } <add> }] <add> }; <add> <add> function isAttrTruthy(scope, attr) { <add> return (isString(attr) && attr.length === 0) || //empty attribute <add> truthy(scope.$eval(attr)); <add> } <add> <add> function truthy(val) { <add> return isString(val) ? val.length : !!val; <add> } <add> }]) <add> <add> /** <add> * @ngdoc directive <add> * @name ngMessagesInclude <add> * @restrict AE <add> * @scope <add> * <add> * @description <add> * `ngMessagesInclude` is a directive with the purpose to import existing ngMessage template <add> * code from a remote template and place the downloaded template code into the exact spot <add> * that the ngMessagesInclude directive is placed within the ngMessages container. This allows <add> * for a series of pre-defined messages to be reused and also allows for the developer to <add> * determine what messages are overridden due to the placement of the ngMessagesInclude directive. <add> * <add> * @usage <add> * ```html <add> * <!-- using attribute directives --> <add> * <ANY ng-messages="expression"> <add> * <ANY ng-messages-include="remoteTplString">...</ANY> <add> * </ANY> <add> * <add> * <!-- or by using element directives --> <add> * <ng-messages for="expression"> <add> * <ng-messages-include src="expressionValue1">...</ng-messages-include> <add> * </ng-messages> <add> * ``` <add> * <add> * {@link module:ngMessages Click here} to learn more about `ngMessages` and `ngMessage`. <add> * <add> * @param {string} ngMessagesInclude|src a string value corresponding to the remote template. <add> */ <add> .directive('ngMessagesInclude', <add> ['$templateRequest', '$document', '$compile', function($templateRequest, $document, $compile) { <add> <add> return { <add> restrict: 'AE', <add> require: '^^ngMessages', <add> compile: function(element, attrs) { <add> var comment = jqLite($document[0].createComment(' ngMessagesInclude: ')); <add> element.after(comment); <add> <add> return function($scope, $element, attrs, ngMessagesCtrl) { <add> // we're removing this since we only need access to the newly <add> // created comment node as an anchor. <add> element.remove(); <add> <add> $templateRequest(attrs.ngMessagesInclude || attrs.src).then(function(html) { <add> var elements = jqLite('<div></div>').html(html).contents(); <add> var cursor = comment; <add> forEach(elements, function(elm) { <add> elm = jqLite(elm); <add> cursor.after(elm); <add> cursor = elm; <add> }); <add> $compile(elements)($scope); <add> }); <add> }; <add> } <add> }; <add> }]) <ide> <ide> /** <ide> * @ngdoc directive <ide> angular.module('ngMessages', []) <ide> * ```html <ide> * <!-- using attribute directives --> <ide> * <ANY ng-messages="expression"> <del> * <ANY ng-message="keyValue1">...</ANY> <del> * <ANY ng-message="keyValue2">...</ANY> <del> * <ANY ng-message="keyValue3">...</ANY> <add> * <ANY ng-message="stringValue">...</ANY> <add> * <ANY ng-message="stringValue1, stringValue2, ...">...</ANY> <add> * <ANY ng-message-exp="expressionValue">...</ANY> <ide> * </ANY> <ide> * <ide> * <!-- or by using element directives --> <ide> * <ng-messages for="expression"> <del> * <ng-message when="keyValue1">...</ng-message> <del> * <ng-message when="keyValue2">...</ng-message> <del> * <ng-message when="keyValue3">...</ng-message> <add> * <ng-message when="stringValue">...</ng-message> <add> * <ng-message when="stringValue1, stringValue2, ...">...</ng-message> <add> * <ng-message when-exp="expressionValue">...</ng-message> <ide> * </ng-messages> <ide> * ``` <ide> * <ide> * {@link module:ngMessages Click here} to learn more about `ngMessages` and `ngMessage`. <ide> * <del> * @param {string} ngMessage a string value corresponding to the message key. <add> * @param {expression} ngMessage|when a string value corresponding to the message key. <add> * @param {expression} ngMessageExp|whenExp an expression value corresponding to the message key. <ide> */ <del> .directive('ngMessage', ['$animate', function($animate) { <del> var COMMENT_NODE = 8; <add> .directive('ngMessage', ngMessageDirectiveFactory('AE')) <add> .directive('ngMessageExp', ngMessageDirectiveFactory('A')); <add> <add>function ngMessageDirectiveFactory(restrict) { <add> return ['$animate', function($animate) { <ide> return { <del> require: '^ngMessages', <add> restrict: 'AE', <ide> transclude: 'element', <ide> terminal: true, <del> restrict: 'AE', <del> link: function($scope, $element, $attrs, ngMessages, $transclude) { <del> var index, element; <del> <del> var commentNode = $element[0]; <del> var parentNode = commentNode.parentNode; <del> for (var i = 0, j = 0; i < parentNode.childNodes.length; i++) { <del> var node = parentNode.childNodes[i]; <del> if (node.nodeType == COMMENT_NODE && node.nodeValue.indexOf('ngMessage') >= 0) { <del> if (node === commentNode) { <del> index = j; <del> break; <del> } <del> j++; <del> } <add> require: '^^ngMessages', <add> link: function(scope, element, attrs, ngMessagesCtrl, $transclude) { <add> var commentNode = element[0]; <add> <add> var records; <add> var staticExp = attrs.ngMessage || attrs.when; <add> var dynamicExp = attrs.ngMessageExp || attrs.whenExp; <add> var assignRecords = function(items) { <add> records = items <add> ? (isArray(items) <add> ? items <add> : items.split(/[\s,]+/)) <add> : null; <add> ngMessagesCtrl.reRender(); <add> }; <add> <add> if (dynamicExp) { <add> assignRecords(scope.$eval(dynamicExp)); <add> scope.$watchCollection(dynamicExp, assignRecords); <add> } else { <add> assignRecords(staticExp); <ide> } <ide> <del> ngMessages.registerMessage(index, { <del> type: $attrs.ngMessage || $attrs.when, <add> var currentElement, messageCtrl; <add> ngMessagesCtrl.register(commentNode, messageCtrl = { <add> test: function(name) { <add> return contains(records, name); <add> }, <ide> attach: function() { <del> if (!element) { <del> $transclude($scope, function(clone) { <del> $animate.enter(clone, null, $element); <del> element = clone; <add> if (!currentElement) { <add> $transclude(scope, function(elm) { <add> $animate.enter(elm, null, element); <add> currentElement = elm; <add> <add> // in the event that the parent element is destroyed <add> // by any other structural directive then it's time <add> // to deregister the message from the controller <add> currentElement.on('$destroy', function() { <add> if (currentElement) { <add> ngMessagesCtrl.deregister(commentNode); <add> messageCtrl.detach(); <add> } <add> }); <ide> }); <ide> } <ide> }, <ide> detach: function() { <del> if (element) { <del> $animate.leave(element); <del> element = null; <add> if (currentElement) { <add> var elm = currentElement; <add> currentElement = null; <add> $animate.leave(elm); <ide> } <ide> } <ide> }); <ide> } <ide> }; <del> }]); <add> }]; <add> <add> function contains(collection, key) { <add> if (collection) { <add> return isArray(collection) <add> ? collection.indexOf(key) >= 0 <add> : collection.hasOwnProperty(key); <add> } <add> } <add>} <ide><path>test/ngMessages/messagesSpec.js <ide> describe('ngMessages', function() { <ide> expect(element.text()).toContain('Message is set'); <ide> })); <ide> <del> it('should use the data attribute when an element directive is used', <add> it('should render the same message if multiple message keys match', inject(function($rootScope, $compile) { <add> element = $compile('<div ng-messages="col">' + <add> ' <div ng-message="one, two, three">Message is set</div>' + <add> '</div>')($rootScope); <add> $rootScope.$digest(); <add> <add> expect(element.text()).not.toContain('Message is set'); <add> <add> $rootScope.$apply(function() { <add> $rootScope.col = { one: true }; <add> }); <add> <add> expect(element.text()).toContain('Message is set'); <add> <add> $rootScope.$apply(function() { <add> $rootScope.col = { two: true, one: false }; <add> }); <add> <add> expect(element.text()).toContain('Message is set'); <add> <add> $rootScope.$apply(function() { <add> $rootScope.col = { three: true, two: false }; <add> }); <add> <add> expect(element.text()).toContain('Message is set'); <add> <add> $rootScope.$apply(function() { <add> $rootScope.col = { three: false }; <add> }); <add> <add> expect(element.text()).not.toContain('Message is set'); <add> })); <add> <add> it('should use the when attribute when an element directive is used', <ide> inject(function($rootScope, $compile) { <ide> <ide> element = $compile('<ng-messages for="col">' + <ide> describe('ngMessages', function() { <ide> expect(element.text()).toContain('Message is set'); <ide> })); <ide> <add> it('should render the same message if multiple message keys match based on the when attribute', inject(function($rootScope, $compile) { <add> element = $compile('<ng-messages for="col">' + <add> ' <ng-message when=" one two three ">Message is set</div>' + <add> '</ng-messages>')($rootScope); <add> $rootScope.$digest(); <add> <add> expect(element.text()).not.toContain('Message is set'); <add> <add> $rootScope.$apply(function() { <add> $rootScope.col = { one: true }; <add> }); <add> <add> expect(element.text()).toContain('Message is set'); <add> <add> $rootScope.$apply(function() { <add> $rootScope.col = { two: true, one: false }; <add> }); <add> <add> expect(element.text()).toContain('Message is set'); <add> <add> $rootScope.$apply(function() { <add> $rootScope.col = { three: true, two: false }; <add> }); <add> <add> expect(element.text()).toContain('Message is set'); <add> <add> $rootScope.$apply(function() { <add> $rootScope.col = { three: false }; <add> }); <add> <add> expect(element.text()).not.toContain('Message is set'); <add> })); <add> <add> it('should allow a dynamic expression to be set when ng-message-exp is used', <add> inject(function($rootScope, $compile) { <add> <add> element = $compile('<div ng-messages="col">' + <add> ' <div ng-message-exp="variable">Message is crazy</div>' + <add> '</div>')($rootScope); <add> $rootScope.$digest(); <add> <add> expect(element.text()).not.toContain('Message is crazy'); <add> <add> $rootScope.$apply(function() { <add> $rootScope.variable = 'error'; <add> $rootScope.col = { error: true }; <add> }); <add> <add> expect(element.text()).toContain('Message is crazy'); <add> <add> $rootScope.$apply(function() { <add> $rootScope.col = { error: false, failure: true }; <add> }); <add> <add> expect(element.text()).not.toContain('Message is crazy'); <add> <add> $rootScope.$apply(function() { <add> $rootScope.variable = ['failure']; <add> }); <add> <add> expect(element.text()).toContain('Message is crazy'); <add> <add> $rootScope.$apply(function() { <add> $rootScope.variable = null; <add> }); <add> <add> expect(element.text()).not.toContain('Message is crazy'); <add> })); <add> <add> it('should allow a dynamic expression to be set when the when-exp attribute is used', <add> inject(function($rootScope, $compile) { <add> <add> element = $compile('<ng-messages for="col">' + <add> ' <ng-message when-exp="variable">Message is crazy</ng-message>' + <add> '</ng-messages>')($rootScope); <add> $rootScope.$digest(); <add> <add> expect(element.text()).not.toContain('Message is crazy'); <add> <add> $rootScope.$apply(function() { <add> $rootScope.variable = 'error, failure'; <add> $rootScope.col = { error: true }; <add> }); <add> <add> expect(element.text()).toContain('Message is crazy'); <add> <add> $rootScope.$apply(function() { <add> $rootScope.col = { error: false, failure: true }; <add> }); <add> <add> expect(element.text()).toContain('Message is crazy'); <add> <add> $rootScope.$apply(function() { <add> $rootScope.variable = []; <add> }); <add> <add> expect(element.text()).not.toContain('Message is crazy'); <add> <add> $rootScope.$apply(function() { <add> $rootScope.variable = null; <add> }); <add> <add> expect(element.text()).not.toContain('Message is crazy'); <add> })); <add> <ide> they('should render empty when $prop is used as a collection value', <ide> { 'null': null, <ide> 'false': false, <ide> describe('ngMessages', function() { <ide> expect(element.hasClass('ng-inactive')).toBe(false); <ide> })); <ide> <add> it('should automatically re-render the messages when other directives dynmically change them', <add> inject(function($rootScope, $compile) { <add> <add> element = $compile('<div ng-messages="col">' + <add> ' <div ng-message="primary">Enter something</div>' + <add> ' <div ng-repeat="item in items">' + <add> ' <div ng-message-exp="item.name">{{ item.text }}</div>' + <add> ' </div>' + <add> '</div>')($rootScope); <add> <add> $rootScope.$apply(function() { <add> $rootScope.col = {}; <add> $rootScope.items = [ <add> { text: 'Your age is incorrect', name: 'age' }, <add> { text: 'You\'re too tall man!', name: 'height' }, <add> { text: 'Your hair is too long', name: 'hair' } <add> ]; <add> }); <add> <add> expect(messageChildren().length).toBe(0); <add> expect(trim(element.text())).toEqual(""); <add> <add> $rootScope.$apply(function() { <add> $rootScope.col = { hair: true }; <add> }); <add> <add> expect(messageChildren().length).toBe(1); <add> expect(trim(element.text())).toEqual("Your hair is too long"); <add> <add> $rootScope.$apply(function() { <add> $rootScope.col = { age: true, hair: true}; <add> }); <add> <add> expect(messageChildren().length).toBe(1); <add> expect(trim(element.text())).toEqual("Your age is incorrect"); <add> <add> $rootScope.$apply(function() { <add> // remove the age! <add> $rootScope.items.shift(); <add> }); <add> <add> expect(messageChildren().length).toBe(1); <add> expect(trim(element.text())).toEqual("Your hair is too long"); <add> <add> $rootScope.$apply(function() { <add> // remove the hair! <add> $rootScope.items.length = 0; <add> $rootScope.col.primary = true; <add> }); <add> <add> expect(messageChildren().length).toBe(1); <add> expect(trim(element.text())).toEqual("Enter something"); <add> <add> function messageChildren() { <add> return element[0].querySelectorAll('[ng-message], [ng-message-exp]'); <add> } <add> })); <add> <add> <ide> it('should render animations when the active/inactive classes are added/removed', function() { <ide> module('ngAnimate'); <ide> module('ngAnimateMock'); <ide> describe('ngMessages', function() { <ide> <ide> describe('when including templates', function() { <ide> they('should load a remote template using $prop', <del> {'<div ng-messages ng-messages-include="...">': <del> '<div ng-messages="data" ng-messages-include="abc.html"></div>', <del> '<ng-messages include="...">': <del> '<ng-messages for="data" include="abc.html"></ng-messages>'}, <add> {'<div ng-messages-include="...">': '<div ng-messages="data">' + <add> '<div ng-messages-include="abc.html"></div>' + <add> '</div>', <add> '<ng-messages-include src="...">': '<ng-messages for="data">' + <add> '<ng-messages-include src="abc.html"></ng-messages-include>' + <add> '</ng-messages>'}, <ide> function(html) { <ide> inject(function($compile, $rootScope, $templateCache) { <ide> $templateCache.put('abc.html', '<div ng-message="a">A</div>' + <ide> describe('ngMessages', function() { <ide> <ide> expect($templateCache.get('tpl')).toBeUndefined(); <ide> <del> element = $compile('<div ng-messages="data" ng-messages-include="tpl"></div>')($rootScope); <add> element = $compile('<div ng-messages="data"><div ng-messages-include="tpl"></div></div>')($rootScope); <ide> <ide> $rootScope.$digest(); <ide> $httpBackend.flush(); <ide> describe('ngMessages', function() { <ide> it('should re-render the messages after download without an extra digest', <ide> inject(function($rootScope, $compile, $httpBackend) { <ide> <del> $httpBackend.expect('GET', 'my-messages').respond(201,'<div ng-message="required">You did not enter a value</div>'); <add> $httpBackend.expect('GET', 'my-messages').respond(201, <add> '<div ng-message="required">You did not enter a value</div>'); <ide> <del> element = $compile('<div ng-messages="data" ng-messages-include="my-messages">' + <add> element = $compile('<div ng-messages="data">' + <add> ' <div ng-messages-include="my-messages"></div>' + <ide> ' <div ng-message="failed">Your value is that of failure</div>' + <ide> '</div>')($rootScope); <ide> <ide> describe('ngMessages', function() { <ide> expect(trim(element.text())).toEqual("Your value is that of failure"); <ide> <ide> $httpBackend.flush(); <add> $rootScope.$digest(); <ide> <ide> expect(element.children().length).toBe(1); <ide> expect(trim(element.text())).toEqual("You did not enter a value"); <ide> })); <ide> <del> it('should allow for overriding the remote template messages within the element', <add> it('should allow for overriding the remote template messages within the element depending on where the remote template is placed', <ide> inject(function($compile, $rootScope, $templateCache) { <ide> <ide> $templateCache.put('abc.html', '<div ng-message="a">A</div>' + <ide> '<div ng-message="b">B</div>' + <ide> '<div ng-message="c">C</div>'); <ide> <del> element = $compile('<div ng-messages="data" ng-messages-include="abc.html">' + <add> element = $compile('<div ng-messages="data">' + <ide> ' <div ng-message="a">AAA</div>' + <add> ' <div ng-messages-include="abc.html"></div>' + <ide> ' <div ng-message="c">CCC</div>' + <ide> '</div>')($rootScope); <ide> <ide> describe('ngMessages', function() { <ide> }); <ide> <ide> expect(element.children().length).toBe(1); <del> expect(trim(element.text())).toEqual("CCC"); <del> })); <del> <del> it('should retain the order of the remote template\'s messages when overriding within the element', <del> inject(function($compile, $rootScope, $templateCache) { <del> <del> $templateCache.put('abc.html', '<div ng-message="c">C</div>' + <del> '<div ng-message="a">A</div>' + <del> '<div ng-message="b">B</div>'); <del> <del> element = $compile('<div ng-messages="data" ng-messages-include="abc.html">' + <del> ' <div ng-message="a">AAA</div>' + <del> ' <div ng-message="c">CCC</div>' + <del> '</div>')($rootScope); <del> <del> $rootScope.$apply(function() { <del> $rootScope.data = { <del> 'a': 1, <del> 'b': 2, <del> 'c': 3 <del> }; <del> }); <del> <del> expect(element.children().length).toBe(1); <del> expect(trim(element.text())).toEqual("CCC"); <del> <del> $rootScope.$apply(function() { <del> $rootScope.data = { <del> 'a': 1, <del> 'b': 2 <del> }; <del> }); <del> <del> expect(element.children().length).toBe(1); <del> expect(trim(element.text())).toEqual("AAA"); <del> <del> $rootScope.$apply(function() { <del> $rootScope.data = { <del> 'b': 3 <del> }; <del> }); <del> <del> expect(element.children().length).toBe(1); <del> expect(trim(element.text())).toEqual("B"); <add> expect(trim(element.text())).toEqual("C"); <ide> })); <ide> <ide> }); <ide> describe('ngMessages', function() { <ide> '<div ng-message="y">Y</div>' + <ide> '<div ng-message="z">Z</div>'); <ide> <del> element = $compile('<div ng-messages="data" ' + <del> 'ng-messages-multiple="true" ' + <del> 'ng-messages-include="xyz.html"></div>')($rootScope); <add> element = $compile('<div ng-messages="data" ng-messages-multiple="true">' + <add> '<div ng-messages-include="xyz.html"></div>' + <add> '</div>')($rootScope); <ide> <ide> $rootScope.$apply(function() { <ide> $rootScope.data = { <ide> describe('ngMessages', function() { <ide> '<div ng-message="y">Y</div>' + <ide> '<div ng-message="z">Z</div>'); <ide> <del> element = $compile('<div ng-messages="data" ' + <del> 'ng-messages-multiple="true" ' + <del> 'ng-messages-include="xyz.html">' + <del> '<div ng-message="y">YYY</div>' + <del> '<div ng-message="z">ZZZ</div>' + <add> element = $compile('<div ng-messages="data" ng-messages-multiple="true">' + <add> '<div ng-message="y">YYY</div>' + <add> '<div ng-message="z">ZZZ</div>' + <add> '<div ng-messages-include="xyz.html"></div>' + <ide> '</div>')($rootScope); <ide> <ide> $rootScope.$apply(function() { <ide> describe('ngMessages', function() { <ide> }); <ide> <ide> expect(element.children().length).toBe(2); <del> expect(s(element.text())).toEqual("XZZZ"); <add> expect(s(element.text())).toEqual("ZZZX"); <ide> <ide> $rootScope.$apply(function() { <ide> $rootScope.data.y = {}; <ide> }); <ide> <ide> expect(element.children().length).toBe(3); <del> expect(s(element.text())).toEqual("XYYYZZZ"); <add> expect(s(element.text())).toEqual("YYYZZZX"); <ide> })); <ide> }); <ide> });
2
Javascript
Javascript
avoid a dynamic require in lib/util/serialization
686725a6c3c871735cf255d53f2a10992c935fae
<ide><path>lib/util/internalSerializables.js <add>/* <add> MIT License http://www.opensource.org/licenses/mit-license.php <add> Author Tobias Koppers @sokra <add>*/ <add> <add>"use strict"; <add> <add>// We need to include a list of requires here <add>// to allow webpack to be bundled with only static requires <add>// We could use a dynamic require(`../${request}`) but this <add>// would include too many modules and not every tool is able <add>// to process this <add>module.exports = { <add> AsyncDependenciesBlock: () => require("../AsyncDependenciesBlock"), <add> CommentCompilationWarning: () => require("../CommentCompilationWarning"), <add> ContextModule: () => require("../ContextModule"), <add> "cache/PackFileCacheStrategy": () => <add> require("../cache/PackFileCacheStrategy"), <add> "dependencies/AMDDefineDependency": () => <add> require("../dependencies/AMDDefineDependency"), <add> "dependencies/AMDRequireArrayDependency": () => <add> require("../dependencies/AMDRequireArrayDependency"), <add> "dependencies/AMDRequireContextDependency": () => <add> require("../dependencies/AMDRequireContextDependency"), <add> "dependencies/AMDRequireDependenciesBlock": () => <add> require("../dependencies/AMDRequireDependenciesBlock"), <add> "dependencies/AMDRequireDependency": () => <add> require("../dependencies/AMDRequireDependency"), <add> "dependencies/AMDRequireItemDependency": () => <add> require("../dependencies/AMDRequireItemDependency"), <add> "dependencies/CachedConstDependency": () => <add> require("../dependencies/CachedConstDependency"), <add> "dependencies/CommonJsRequireContextDependency": () => <add> require("../dependencies/CommonJsRequireContextDependency"), <add> "dependencies/CommonJsRequireDependency": () => <add> require("../dependencies/CommonJsRequireDependency"), <add> "dependencies/ConstDependency": () => <add> require("../dependencies/ConstDependency"), <add> "dependencies/ContextDependency": () => <add> require("../dependencies/ContextDependency"), <add> "dependencies/ContextElementDependency": () => <add> require("../dependencies/ContextElementDependency"), <add> "dependencies/CriticalDependencyWarning": () => <add> require("../dependencies/CriticalDependencyWarning"), <add> "dependencies/DllEntryDependency": () => <add> require("../dependencies/DllEntryDependency"), <add> "dependencies/ExportsInfoDependency": () => <add> require("../dependencies/ExportsInfoDependency"), <add> "dependencies/HarmonyAcceptDependency": () => <add> require("../dependencies/HarmonyAcceptDependency"), <add> "dependencies/HarmonyAcceptImportDependency": () => <add> require("../dependencies/HarmonyAcceptImportDependency"), <add> "dependencies/HarmonyCompatibilityDependency": () => <add> require("../dependencies/HarmonyCompatibilityDependency"), <add> "dependencies/HarmonyExportExpressionDependency": () => <add> require("../dependencies/HarmonyExportExpressionDependency"), <add> "dependencies/HarmonyExportHeaderDependency": () => <add> require("../dependencies/HarmonyExportHeaderDependency"), <add> "dependencies/HarmonyExportImportedSpecifierDependency": () => <add> require("../dependencies/HarmonyExportImportedSpecifierDependency"), <add> "dependencies/HarmonyExportSpecifierDependency": () => <add> require("../dependencies/HarmonyExportSpecifierDependency"), <add> "dependencies/HarmonyImportSideEffectDependency": () => <add> require("../dependencies/HarmonyImportSideEffectDependency"), <add> "dependencies/HarmonyImportSpecifierDependency": () => <add> require("../dependencies/HarmonyImportSpecifierDependency"), <add> "dependencies/ImportContextDependency": () => <add> require("../dependencies/ImportContextDependency"), <add> "dependencies/ImportDependenciesBlock": () => <add> require("../dependencies/ImportDependenciesBlock"), <add> "dependencies/ImportDependency": () => <add> require("../dependencies/ImportDependency"), <add> "dependencies/ImportEagerDependency": () => <add> require("../dependencies/ImportEagerDependency"), <add> "dependencies/ImportWeakDependency": () => <add> require("../dependencies/ImportWeakDependency"), <add> "dependencies/LocalModule": () => require("../dependencies/LocalModule"), <add> "dependencies/LocalModuleDependency": () => <add> require("../dependencies/LocalModuleDependency"), <add> "dependencies/ModuleDecoratorDependency": () => <add> require("../dependencies/ModuleDecoratorDependency"), <add> "dependencies/ModuleHotAcceptDependency": () => <add> require("../dependencies/ModuleHotAcceptDependency"), <add> "dependencies/ModuleHotDeclineDependency": () => <add> require("../dependencies/ModuleHotDeclineDependency"), <add> "dependencies/ModuleHotDependency": () => <add> require("../dependencies/ModuleHotDependency"), <add> "dependencies/ProvidedDependency": () => <add> require("../dependencies/ProvidedDependency"), <add> "dependencies/PureExpressionDependency": () => <add> require("../dependencies/PureExpressionDependency"), <add> "dependencies/RequireContextDependency": () => <add> require("../dependencies/RequireContextDependency"), <add> "dependencies/RequireEnsureDependenciesBlock": () => <add> require("../dependencies/RequireEnsureDependenciesBlock"), <add> "dependencies/RequireEnsureDependency": () => <add> require("../dependencies/RequireEnsureDependency"), <add> "dependencies/RequireEnsureItemDependency": () => <add> require("../dependencies/RequireEnsureItemDependency"), <add> "dependencies/RequireHeaderDependency": () => <add> require("../dependencies/RequireHeaderDependency"), <add> "dependencies/RequireIncludeDependency": () => <add> require("../dependencies/RequireIncludeDependency"), <add> "dependencies/RequireResolveContextDependency": () => <add> require("../dependencies/RequireResolveContextDependency"), <add> "dependencies/RequireResolveDependency": () => <add> require("../dependencies/RequireResolveDependency"), <add> "dependencies/RequireResolveHeaderDependency": () => <add> require("../dependencies/RequireResolveHeaderDependency"), <add> "dependencies/RuntimeRequirementsDependency": () => <add> require("../dependencies/RuntimeRequirementsDependency"), <add> "dependencies/StaticExportsDependency": () => <add> require("../dependencies/StaticExportsDependency"), <add> "dependencies/UnsupportedDependency": () => <add> require("../dependencies/UnsupportedDependency"), <add> "dependencies/WebAssemblyExportImportedDependency": () => <add> require("../dependencies/WebAssemblyExportImportedDependency"), <add> "dependencies/WebAssemblyImportDependency": () => <add> require("../dependencies/WebAssemblyImportDependency"), <add> DependenciesBlock: () => require("../DependenciesBlock"), <add> ExternalModule: () => require("../ExternalModule"), <add> Module: () => require("../Module"), <add> ModuleBuildError: () => require("../ModuleBuildError"), <add> ModuleError: () => require("../ModuleError"), <add> ModuleParseError: () => require("../ModuleParseError"), <add> ModuleWarning: () => require("../ModuleWarning"), <add> NormalModule: () => require("../NormalModule"), <add> RawModule: () => require("../RawModule"), <add> UnsupportedFeatureWarning: () => require("../UnsupportedFeatureWarning"), <add> WebpackError: () => require("../WebpackError"), <add> <add> "util/registerExternalSerializer": () => { <add> // already registered <add> } <add>}; <ide><path>lib/util/serialization.js <ide> const FileMiddleware = require("../serialization/FileMiddleware"); <ide> const ObjectMiddleware = require("../serialization/ObjectMiddleware"); <ide> const Serializer = require("../serialization/Serializer"); <ide> const SingleItemMiddleware = require("../serialization/SingleItemMiddleware"); <add>const internalSerializables = require("./internalSerializables"); <ide> <ide> /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ <ide> /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ <ide> require("./registerExternalSerializer"); <ide> <ide> // Load internal paths with a relative require <ide> // This allows bundling all internal serializers <del>registerLoader(/^webpack\/lib\//, req => <del> require("../" + req.slice("webpack/lib/".length)) <del>); <add>registerLoader(/^webpack\/lib\//, req => { <add> const loader = internalSerializables[req.slice("webpack/lib/".length)]; <add> if (loader) { <add> loader(); <add> } else { <add> console.warn(`${req} not found in internalSerializables`); <add> } <add> return true; <add>}); <ide><path>tooling/format-file-header.js <ide> const schema = [ <ide> } <ide> ]; <ide> <add>const allSerializables = new Set(); <add> <ide> for (const filePath of allFiles) { <ide> let content = fs.readFileSync(filePath, "utf-8"); <ide> const nl = /(\r?\n)/.exec(content); <ide> for (const filePath of allFiles) { <ide> process.exitCode = 1; <ide> } <ide> } <add> <add> const matches = content.match( <add> /makeSerializable\(\s*[^,]+,\s*"webpack\/lib\/[^"]+"\s*(?:,[^,]+)\)/g <add> ); <add> if (matches) { <add> for (const match of matches) { <add> const str = /makeSerializable\(\s*[^,]+,\s*"webpack\/lib\/([^"]+)"\s*(?:,[^,]+)\)/.exec( <add> match <add> )[1]; <add> allSerializables.add(str); <add> } <add> } <add>} <add> <add>// Check if lib/util/internalSerializables.js includes all serializables in webpack <add>{ <add> const content = fs.readFileSync( <add> path.resolve(__dirname, "../lib/util/internalSerializables.js") <add> ); <add> for (const serializable of allSerializables) { <add> if (!content.includes(`../${serializable}`)) { <add> console.log( <add> `lib/util/internalSerializables.js: must include static require to ../${serializable}` <add> ); <add> process.exitCode = 1; <add> } <add> } <ide> } <ide> <ide> if (canUpdateWithWrite) {
3
PHP
PHP
fix fqcn in docblocks
6b3aaa272ae06cf18f3341b73ae2da2bee74287b
<ide><path>src/Database/Expression/QueryExpression.php <ide> protected function _parseCondition($field, $value) <ide> /** <ide> * Returns the type name for the passed field if it was stored in the typeMap <ide> * <del> * @param string|Cake\Database\Expression\QueryExpression $field The field name to get a type for. <add> * @param string|\Cake\Database\Expression\QueryExpression $field The field name to get a type for. <ide> * @return string|null The computed type or null, if the type is unknown. <ide> */ <ide> protected function _calculateType($field) <ide><path>src/Routing/Filter/RoutingFilter.php <ide> class RoutingFilter extends DispatcherFilter <ide> * If Routes have not been loaded they will be loaded, and config/routes.php will be run. <ide> * <ide> * @param \Cake\Event\Event $event containing the request, response and additional params <del> * @return void|Cake\Network\Response A response will be returned when a redirect route is encountered. <add> * @return \Cake\Network\Response|null A response will be returned when a redirect route is encountered. <ide> */ <ide> public function beforeDispatch(Event $event) <ide> {
2
Ruby
Ruby
support insert with multiple values
5e6312e1745dc278ba0a99bf2bc7b78977785d35
<ide><path>lib/arel/insert_manager.rb <ide> def insert fields <ide> def create_values values, columns <ide> Nodes::Values.new values, columns <ide> end <add> <add> def create_values_list(rows) <add> Nodes::ValuesList.new(rows) <add> end <ide> end <ide> end <ide><path>lib/arel/nodes.rb <ide> require 'arel/nodes/count' <ide> require 'arel/nodes/extract' <ide> require 'arel/nodes/values' <add>require 'arel/nodes/values_list' <ide> require 'arel/nodes/named_function' <ide> <ide> # windows <ide><path>lib/arel/nodes/values_list.rb <add># frozen_string_literal: true <add>module Arel <add> module Nodes <add> class ValuesList < Node <add> attr_reader :rows <add> <add> def initialize(rows) <add> @rows = rows <add> super() <add> end <add> end <add> end <add>end <ide><path>lib/arel/visitors/to_sql.rb <ide> def visit_Arel_Nodes_False o, collector <ide> collector << "FALSE" <ide> end <ide> <add> def visit_Arel_Nodes_ValuesList o, collector <add> collector << "VALUES " <add> <add> len = o.rows.length - 1 <add> o.rows.each_with_index { |row, i| <add> collector << '(' <add> row_len = row.length - 1 <add> row.each_with_index do |value, k| <add> case value <add> when Nodes::SqlLiteral, Nodes::BindParam <add> collector = visit(value, collector) <add> else <add> collector << quote(value) <add> end <add> collector << COMMA unless k == row_len <add> end <add> collector << ')' <add> collector << COMMA unless i == len <add> } <add> collector <add> end <add> <ide> def visit_Arel_Nodes_Values o, collector <ide> collector << "VALUES (" <ide> <ide><path>test/test_insert_manager.rb <ide> module Arel <ide> } <ide> end <ide> <add> it 'works with multiple values' do <add> table = Table.new(:users) <add> manager = Arel::InsertManager.new <add> manager.into table <add> <add> manager.columns << table[:id] <add> manager.columns << table[:name] <add> <add> manager.values = manager.create_values_list([ <add> %w{1 david}, <add> %w{2 kir}, <add> ["3", Arel.sql('DEFAULT')], <add> ]) <add> <add> manager.to_sql.must_be_like %{ <add> INSERT INTO \"users\" (\"id\", \"name\") VALUES ('1', 'david'), ('2', 'kir'), ('3', DEFAULT) <add> } <add> end <add> <add> it 'literals in multiple values are not escaped' do <add> table = Table.new(:users) <add> manager = Arel::InsertManager.new <add> manager.into table <add> <add> manager.columns << table[:name] <add> <add> manager.values = manager.create_values_list([ <add> [Arel.sql('*')], <add> [Arel.sql('DEFAULT')], <add> ]) <add> <add> manager.to_sql.must_be_like %{ <add> INSERT INTO \"users\" (\"name\") VALUES (*), (DEFAULT) <add> } <add> end <add> <add> it 'works with multiple single values' do <add> table = Table.new(:users) <add> manager = Arel::InsertManager.new <add> manager.into table <add> <add> manager.columns << table[:name] <add> <add> manager.values = manager.create_values_list([ <add> %w{david}, <add> %w{kir}, <add> [Arel.sql('DEFAULT')], <add> ]) <add> <add> manager.to_sql.must_be_like %{ <add> INSERT INTO \"users\" (\"name\") VALUES ('david'), ('kir'), (DEFAULT) <add> } <add> end <add> <ide> it "inserts false" do <ide> table = Table.new(:users) <ide> manager = Arel::InsertManager.new
5
PHP
PHP
fix fatal error on file uploads
eb6e0fd3d77193f392181a12bef51a1c721652e7
<ide><path>src/Illuminate/Http/Request.php <ide> protected function filterFiles($files) <ide> $files[$key] = $this->filterFiles($files[$key]); <ide> } <ide> <del> if (! $files[$key]) { <add> if (empty($files[$key])) { <ide> unset($files[$key]); <ide> } <ide> }
1
Python
Python
fix dropout in rnn
90d24ddf1aefc1493436d8952da97b224cf937f4
<ide><path>keras/layers/recurrent.py <ide> def step(self, inputs, states): <ide> <ide> def get_constants(self, inputs, training=None): <ide> constants = [] <del> if self.implementation == 0 and 0 < self.dropout < 1: <add> if self.implementation != 0 and 0 < self.dropout < 1: <ide> input_shape = K.int_shape(inputs) <ide> input_dim = input_shape[-1] <ide> ones = K.ones_like(K.reshape(inputs[:, 0, 0], (-1, 1))) <ide> def preprocess_input(self, inputs, training=None): <ide> <ide> def get_constants(self, inputs, training=None): <ide> constants = [] <del> if self.implementation == 0 and 0 < self.dropout < 1: <add> if self.implementation != 0 and 0 < self.dropout < 1: <ide> input_shape = K.int_shape(inputs) <ide> input_dim = input_shape[-1] <ide> ones = K.ones_like(K.reshape(inputs[:, 0, 0], (-1, 1))) <ide> def preprocess_input(self, inputs, training=None): <ide> <ide> def get_constants(self, inputs, training=None): <ide> constants = [] <del> if self.implementation == 0 and 0 < self.dropout < 1: <add> if self.implementation != 0 and 0 < self.dropout < 1: <ide> input_shape = K.int_shape(inputs) <ide> input_dim = input_shape[-1] <ide> ones = K.ones_like(K.reshape(inputs[:, 0, 0], (-1, 1)))
1
Python
Python
fix reuters example
c53c15dbd007480100920b692782e28f6f23c86f
<ide><path>examples/reuters_mlp.py <ide> <ide> ''' <ide> Train and evaluate a simple MLP on the Reuters newswire topic classification task. <del> <ide> GPU run command: <ide> THEANO_FLAGS=mode=FAST_RUN,device=gpu,floatX=float32 python examples/reuters_mlp.py <del> <ide> CPU run command: <ide> python examples/reuters_mlp.py <ide> ''' <ide> model = Sequential() <ide> model.add(Dense(max_words, 256, init='normal')) <ide> model.add(Activation('relu')) <del>model.add(BatchNormalization(input_shape=(256,))) # try without batch normalization (doesn't work as well!) <ide> model.add(Dropout(0.5)) <ide> model.add(Dense(256, nb_classes, init='normal')) <ide> model.add(Activation('softmax')) <ide> <ide> model.compile(loss='categorical_crossentropy', optimizer='adam') <ide> <del># import cPickle <del># model = cPickle.load(open('testsave.m.pkl')) <del> <del>for v in range(3): <del> for sa in [True, False]: <del> for vs in [0, 0.1]: <del> print('='*40) <del> print('v:%d, sa:%r, vs:%f' % (v, sa, vs)) <del> print("Training...") <del> model.fit(X_train, Y_train, nb_epoch=2, batch_size=batch_size, verbose=v, show_accuracy=sa, validation_split=vs) <del> score = model.evaluate(X_test, Y_test, batch_size=batch_size, verbose=v, show_accuracy=sa) <del> print('Test score:', score) <del> <del> classes = model.predict_classes(X_test, batch_size=batch_size, verbose=v) <del> acc = np_utils.accuracy(classes, y_test) <del> print('Test accuracy:', acc) <del> <del># model.save('testsave.m') <del> <add>model.fit(X_train, Y_train, nb_epoch=4, batch_size=batch_size, verbose=1, show_accuracy=True, validation_split=0.1) <add>score = model.evaluate(X_test, Y_test, batch_size=batch_size, verbose=1, show_accuracy=True) <add>print('Test score:', score) <ide> <add>classes = model.predict_classes(X_test, batch_size=batch_size, verbose=0) <add>acc = np_utils.accuracy(classes, y_test) <add>print('Test accuracy:', acc) <ide><path>keras/preprocessing/text.py <ide> def sequences_to_matrix(self, sequences, mode="binary"): <ide> if mode == "tfidf" and not self.document_count: <ide> raise Exception("Fit the Tokenizer on some data before using tfidf mode") <ide> <del> X = np.zeros((len(sequences), nb_words+1)) <add> X = np.zeros((len(sequences), nb_words)) <ide> for i, seq in enumerate(sequences): <ide> if not seq: <ide> pass
2
Python
Python
require django 1.11 lts for celery 4.3
072dab85261599234341cc714b0d6f0caca20f00
<ide><path>celery/fixups/django.py <ide> def _maybe_close_fd(fh): <ide> <ide> <ide> def _verify_django_version(django): <del> if django.VERSION < (1, 8): <del> raise ImproperlyConfigured('Celery 4.x requires Django 1.8 or later.') <add> if django.VERSION < (1, 11): <add> raise ImproperlyConfigured('Celery 4.x requires Django 1.11 or later.') <ide> <ide> <ide> def fixup(app, env='DJANGO_SETTINGS_MODULE'): <ide><path>t/unit/fixups/test_django.py <ide> def test_fixup(self, patching): <ide> Fixup.assert_not_called() <ide> with mock.module_exists('django'): <ide> import django <del> django.VERSION = (1, 10, 1) <add> django.VERSION = (1, 11, 1) <ide> fixup(self.app) <ide> Fixup.assert_called() <ide>
2
Javascript
Javascript
add more test cases of server.listen option
474e9d64b54b91f6c38454d5e7700337b4c54406
<ide><path>test/parallel/test-net-server-listen-handle.js <add>'use strict'; <add> <add>const common = require('../common'); <add>const assert = require('assert'); <add>const net = require('net'); <add>const fs = require('fs'); <add>const uv = process.binding('uv'); <add>const TCP = process.binding('tcp_wrap').TCP; <add>const Pipe = process.binding('pipe_wrap').Pipe; <add> <add>common.refreshTmpDir(); <add> <add>function closeServer() { <add> return common.mustCall(function() { <add> this.close(); <add> }); <add>} <add> <add>// server.listen(pipe) creates a new pipe wrap, <add>// so server.close() doesn't actually unlink this existing pipe. <add>// It needs to be unlinked separately via handle.close() <add>function closePipeServer(handle) { <add> return common.mustCall(function() { <add> this.close(); <add> handle.close(); <add> }); <add>} <add> <add>let counter = 0; <add> <add>// Avoid conflict with listen-path <add>function randomPipePath() { <add> return common.PIPE + '-listen-handle-' + (counter++); <add>} <add> <add>function randomHandle(type) { <add> let handle, errno, handleName; <add> if (type === 'tcp') { <add> handle = new TCP(); <add> errno = handle.bind('0.0.0.0', 0); <add> handleName = 'arbitrary tcp port'; <add> } else { <add> const path = randomPipePath(); <add> handle = new Pipe(); <add> errno = handle.bind(path); <add> handleName = `pipe ${path}`; <add> } <add> <add> if (errno < 0) { // uv.errname requires err < 0 <add> assert(errno >= 0, `unable to bind ${handleName}: ${uv.errname(errno)}`); <add> } <add> if (!common.isWindows) { // fd doesn't work on windows <add> // err >= 0 but fd = -1, should not happen <add> assert.notStrictEqual(handle.fd, -1, <add> `Bound ${handleName} has fd -1 and errno ${errno}`); <add> } <add> return handle; <add>} <add> <add>// Not a public API, used by child_process <add>{ <add> // Test listen(tcp) <add> net.createServer() <add> .listen(randomHandle('tcp')) <add> .on('listening', closeServer()); <add> // Test listen(tcp, cb) <add> net.createServer() <add> .listen(randomHandle('tcp'), closeServer()); <add>} <add> <add>function randomPipes(number) { <add> const arr = []; <add> for (let i = 0; i < number; ++i) { <add> arr.push(randomHandle('pipe')); <add> } <add> return arr; <add>} <add> <add>// Not a public API, used by child_process <add>if (!common.isWindows) { // Windows doesn't support {fd: <n>} <add> const handles = randomPipes(2); // generate pipes in advance <add> // Test listen(pipe) <add> net.createServer() <add> .listen(handles[0]) <add> .on('listening', closePipeServer(handles[0])); <add> // Test listen(pipe, cb) <add> net.createServer() <add> .listen(handles[1], closePipeServer(handles[1])); <add>} <add> <add>{ <add> // Test listen({handle: tcp}, cb) <add> net.createServer() <add> .listen({handle: randomHandle('tcp')}, closeServer()); <add> // Test listen({handle: tcp}) <add> net.createServer() <add> .listen({handle: randomHandle('tcp')}) <add> .on('listening', closeServer()); <add> // Test listen({_handle: tcp}, cb) <add> net.createServer() <add> .listen({_handle: randomHandle('tcp')}, closeServer()); <add> // Test listen({_handle: tcp}) <add> net.createServer() <add> .listen({_handle: randomHandle('tcp')}) <add> .on('listening', closeServer()); <add>} <add> <add>if (!common.isWindows) { // Windows doesn't support {fd: <n>} <add> // Test listen({fd: tcp.fd}, cb) <add> net.createServer() <add> .listen({fd: randomHandle('tcp').fd}, closeServer()); <add> // Test listen({fd: tcp.fd}) <add> net.createServer() <add> .listen({fd: randomHandle('tcp').fd}) <add> .on('listening', closeServer()); <add>} <add> <add>if (!common.isWindows) { // Windows doesn't support {fd: <n>} <add> const handles = randomPipes(6); // generate pipes in advance <add> // Test listen({handle: pipe}, cb) <add> net.createServer() <add> .listen({handle: handles[0]}, closePipeServer(handles[0])); <add> // Test listen({handle: pipe}) <add> net.createServer() <add> .listen({handle: handles[1]}) <add> .on('listening', closePipeServer(handles[1])); <add> // Test listen({_handle: pipe}, cb) <add> net.createServer() <add> .listen({_handle: handles[2]}, closePipeServer(handles[2])); <add> // Test listen({_handle: pipe}) <add> net.createServer() <add> .listen({_handle: handles[3]}) <add> .on('listening', closePipeServer(handles[3])); <add> // Test listen({fd: pipe.fd}, cb) <add> net.createServer() <add> .listen({fd: handles[4].fd}, closePipeServer(handles[4])); <add> // Test listen({fd: pipe.fd}) <add> net.createServer() <add> .listen({fd: handles[5].fd}) <add> .on('listening', closePipeServer(handles[5])); <add>} <add> <add>if (!common.isWindows) { // Windows doesn't support {fd: <n>} <add> // Test invalid fd <add> const fd = fs.openSync(__filename, 'r'); <add> net.createServer() <add> .listen({fd: fd}, common.mustNotCall()) <add> .on('error', common.mustCall(function(err) { <add> assert.strictEqual(err + '', 'Error: listen EINVAL'); <add> this.close(); <add> })); <add>} <ide><path>test/parallel/test-net-server-listen-options.js <ide> function listenError(literals, ...values) { <ide> net.createServer().listen().on('listening', common.mustCall(close)); <ide> // Test listen(cb) <ide> net.createServer().listen(common.mustCall(close)); <add> // Test listen(port) <add> net.createServer().listen(0).on('listening', common.mustCall(close)); <add> // Test listen({port}) <add> net.createServer().listen({port: 0}) <add> .on('listening', common.mustCall(close)); <ide> } <ide> <ide> // Test listen(port, cb) and listen({port: port}, cb) combinations <ide><path>test/parallel/test-net-server-listen-path.js <add>'use strict'; <add> <add>const common = require('../common'); <add>const net = require('net'); <add> <add>common.refreshTmpDir(); <add> <add>function closeServer() { <add> return common.mustCall(function() { <add> this.close(); <add> }); <add>} <add> <add>let counter = 0; <add> <add>// Avoid conflict with listen-handle <add>function randomPipePath() { <add> return common.PIPE + '-listen-path-' + (counter++); <add>} <add> <add>// Test listen(path) <add>{ <add> const handlePath = randomPipePath(); <add> net.createServer() <add> .listen(handlePath) <add> .on('listening', closeServer()); <add>} <add> <add>// Test listen({path}) <add>{ <add> const handlePath = randomPipePath(); <add> net.createServer() <add> .listen({path: handlePath}) <add> .on('listening', closeServer()); <add>} <add> <add>// Test listen(path, cb) <add>{ <add> const handlePath = randomPipePath(); <add> net.createServer() <add> .listen(handlePath, closeServer()); <add>} <add> <add>// Test listen(path, cb) <add>{ <add> const handlePath = randomPipePath(); <add> net.createServer() <add> .listen({path: handlePath}, closeServer()); <add>}
3
Javascript
Javascript
fix comment typo
90e5d3638844414e1b9df0fe66c3fc46b211d210
<ide><path>packages/react-server/src/ReactFizzHooks.js <ide> export function resetHooksState(): void { <ide> } <ide> <ide> function getCacheForType<T>(resourceType: () => T): T { <del> // TODO: This should silently mark this as client rendered since it's not necesssarily <add> // TODO: This should silently mark this as client rendered since it's not necessarily <ide> // considered an error. It needs to work for things like Flight though. <ide> throw new Error('Not implemented.'); <ide> }
1
Javascript
Javascript
remove unused arg to createsecurecontext()
3b4159c8ed85b6b531b7df09378d67168574d731
<ide><path>lib/_tls_common.js <ide> const { SSL_OP_CIPHER_SERVER_PREFERENCE } = internalBinding('constants').crypto; <ide> let toBuf = null; <ide> <ide> const { SecureContext: NativeSecureContext } = internalBinding('crypto'); <del>function SecureContext(secureProtocol, secureOptions, context) { <add>function SecureContext(secureProtocol, secureOptions) { <ide> if (!(this instanceof SecureContext)) { <del> return new SecureContext(secureProtocol, secureOptions, context); <add> return new SecureContext(secureProtocol, secureOptions); <ide> } <ide> <del> if (context) { <del> this.context = context; <del> } else { <del> this.context = new NativeSecureContext(); <del> <del> if (secureProtocol) { <del> this.context.init(secureProtocol); <del> } else { <del> this.context.init(); <del> } <del> } <add> this.context = new NativeSecureContext(); <add> this.context.init(secureProtocol); <ide> <ide> if (secureOptions) this.context.setOptions(secureOptions); <ide> } <ide> function validateKeyCert(name, value) { <ide> exports.SecureContext = SecureContext; <ide> <ide> <del>exports.createSecureContext = function createSecureContext(options, context) { <add>exports.createSecureContext = function createSecureContext(options) { <ide> if (!options) options = {}; <ide> <ide> var secureOptions = options.secureOptions; <ide> if (options.honorCipherOrder) <ide> secureOptions |= SSL_OP_CIPHER_SERVER_PREFERENCE; <ide> <del> const c = new SecureContext(options.secureProtocol, secureOptions, context); <add> const c = new SecureContext(options.secureProtocol, secureOptions); <ide> var i; <ide> var val; <ide> <del> if (context) return c; <del> <ide> // NOTE: It's important to add CA before the cert to be able to load <ide> // cert's issuer in C++ code. <ide> const { ca } = options;
1