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
Go
Go
add extra prometheus metrics
a28b173a780cd06db6d93197c54b00a7d616b3dc
<ide><path>builder/dockerfile/builder.go <ide> func NewBuildManager(b builder.Backend) *BuildManager { <ide> <ide> // Build starts a new build from a BuildConfig <ide> func (bm *BuildManager) Build(ctx context.Context, config backend.BuildConfig) (*builder.Result, error) { <add> buildsTriggered.Inc() <ide> if config.Options.Dockerfile == "" { <ide> config.Options.Dockerfile = builder.DefaultDockerfileName <ide> } <ide> func (b *Builder) build(source builder.Source, dockerfile *parser.Result) (*buil <ide> addNodesForLabelOption(dockerfile.AST, b.options.Labels) <ide> <ide> if err := checkDispatchDockerfile(dockerfile.AST); err != nil { <add> buildsFailed.WithValues(metricsDockerfileSyntaxError).Inc() <ide> return nil, err <ide> } <ide> <ide> func (b *Builder) build(source builder.Source, dockerfile *parser.Result) (*buil <ide> } <ide> <ide> if b.options.Target != "" && !dispatchState.isCurrentStage(b.options.Target) { <add> buildsFailed.WithValues(metricsBuildTargetNotReachableError).Inc() <ide> return nil, errors.Errorf("failed to reach build target %s in Dockerfile", b.options.Target) <ide> } <ide> <ide> b.warnOnUnusedBuildArgs() <ide> <ide> if dispatchState.imageID == "" { <add> buildsFailed.WithValues(metricsDockerfileEmptyError).Inc() <ide> return nil, errors.New("No image was generated. Is your Dockerfile empty?") <ide> } <ide> return &builder.Result{ImageID: dispatchState.imageID, FromImage: dispatchState.baseImage}, nil <ide> func (b *Builder) dispatchDockerfileWithCancellation(dockerfile *parser.Result) <ide> case <-b.clientCtx.Done(): <ide> logrus.Debug("Builder: build cancelled!") <ide> fmt.Fprint(b.Stdout, "Build cancelled") <add> buildsFailed.WithValues(metricsBuildCanceled).Inc() <ide> return nil, errors.New("Build cancelled") <ide> default: <ide> // Not cancelled yet, keep going... <ide><path>builder/dockerfile/evaluator.go <ide> func (b *Builder) dispatch(options dispatchOptions) (*dispatchState, error) { <ide> // To ensure the user is given a decent error message if the platform <ide> // on which the daemon is running does not support a builder command. <ide> if err := platformSupports(strings.ToLower(cmd)); err != nil { <add> buildsFailed.WithValues(metricsCommandNotSupportedError).Inc() <ide> return nil, err <ide> } <ide> <ide> func (b *Builder) dispatch(options dispatchOptions) (*dispatchState, error) { <ide> processFunc := createProcessWordFunc(options.shlex, cmd, envs) <ide> words, err := getDispatchArgsFromNode(ast, processFunc, msg) <ide> if err != nil { <add> buildsFailed.WithValues(metricsErrorProcessingCommandsError).Inc() <ide> return nil, err <ide> } <ide> args = append(args, words...) <ide> func (b *Builder) dispatch(options dispatchOptions) (*dispatchState, error) { <ide> <ide> f, ok := evaluateTable[cmd] <ide> if !ok { <add> buildsFailed.WithValues(metricsUnknownInstructionError).Inc() <ide> return nil, fmt.Errorf("unknown instruction: %s", upperCasedCmd) <ide> } <ide> if err := f(newDispatchRequestFromOptions(options, b, args)); err != nil { <ide> func checkDispatch(ast *parser.Node) error { <ide> // least one argument <ide> if upperCasedCmd == "ONBUILD" { <ide> if ast.Next == nil { <add> buildsFailed.WithValues(metricsMissingOnbuildArgumentsError).Inc() <ide> return errors.New("ONBUILD requires at least one argument") <ide> } <ide> } <ide> <ide> if _, ok := evaluateTable[cmd]; ok { <ide> return nil <ide> } <del> <add> buildsFailed.WithValues(metricsUnknownInstructionError).Inc() <ide> return errors.Errorf("unknown instruction: %s", upperCasedCmd) <ide> } <ide><path>builder/dockerfile/metrics.go <add>package dockerfile <add> <add>import ( <add> "github.com/docker/go-metrics" <add>) <add> <add>var ( <add> buildsTriggered metrics.Counter <add> buildsFailed metrics.LabeledCounter <add>) <add> <add>// Build metrics prometheus messages, these values must be initialized before <add>// using them. See the example below in the "builds_failed" metric definition. <add>const ( <add> metricsDockerfileSyntaxError = "dockerfile_syntax_error" <add> metricsDockerfileEmptyError = "dockerfile_empty_error" <add> metricsCommandNotSupportedError = "command_not_supported_error" <add> metricsErrorProcessingCommandsError = "error_processing_commands_error" <add> metricsBuildTargetNotReachableError = "build_target_not_reachable_error" <add> metricsMissingOnbuildArgumentsError = "missing_onbuild_arguments_error" <add> metricsUnknownInstructionError = "unknown_instruction_error" <add> metricsBuildCanceled = "build_canceled" <add>) <add> <add>func init() { <add> buildMetrics := metrics.NewNamespace("builder", "", nil) <add> <add> buildsTriggered = buildMetrics.NewCounter("builds_triggered", "Number of triggered image builds") <add> buildsFailed = buildMetrics.NewLabeledCounter("builds_failed", "Number of failed image builds", "reason") <add> for _, r := range []string{ <add> metricsDockerfileSyntaxError, <add> metricsDockerfileEmptyError, <add> metricsCommandNotSupportedError, <add> metricsErrorProcessingCommandsError, <add> metricsBuildTargetNotReachableError, <add> metricsMissingOnbuildArgumentsError, <add> metricsUnknownInstructionError, <add> metricsBuildCanceled, <add> } { <add> buildsFailed.WithValues(r) <add> } <add> <add> metrics.Register(buildMetrics) <add>} <ide><path>daemon/daemon.go <ide> func NewDaemon(config *config.Config, registryService registry.Service, containe <ide> // FIXME: this method never returns an error <ide> info, _ := d.SystemInfo() <ide> <del> engineVersion.WithValues( <add> engineInfo.WithValues( <ide> dockerversion.Version, <ide> dockerversion.GitCommit, <ide> info.Architecture, <ide> info.Driver, <ide> info.KernelVersion, <ide> info.OperatingSystem, <add> info.OSType, <add> info.ID, <ide> ).Set(1) <ide> engineCpus.Set(float64(info.NCPU)) <ide> engineMemory.Set(float64(info.MemTotal)) <ide><path>daemon/metrics.go <ide> var ( <ide> containerActions metrics.LabeledTimer <ide> imageActions metrics.LabeledTimer <ide> networkActions metrics.LabeledTimer <del> engineVersion metrics.LabeledGauge <add> engineInfo metrics.LabeledGauge <ide> engineCpus metrics.Gauge <ide> engineMemory metrics.Gauge <ide> healthChecksCounter metrics.Counter <ide> func init() { <ide> containerActions.WithValues(a).Update(0) <ide> } <ide> networkActions = ns.NewLabeledTimer("network_actions", "The number of seconds it takes to process each network action", "action") <del> engineVersion = ns.NewLabeledGauge("engine", "The version and commit information for the engine process", metrics.Unit("info"), <add> engineInfo = ns.NewLabeledGauge("engine", "The information related to the engine and the OS it is running on", metrics.Unit("info"), <ide> "version", <ide> "commit", <ide> "architecture", <del> "graph_driver", "kernel", <del> "os", <add> "graphdriver", <add> "kernel", "os", <add> "os_type", <add> "daemon_id", // ID is a randomly generated unique identifier (e.g. UUID4) <ide> ) <ide> engineCpus = ns.NewGauge("engine_cpus", "The number of cpus that the host system of the engine has", metrics.Unit("cpus")) <ide> engineMemory = ns.NewGauge("engine_memory", "The number of bytes of memory that the host system of the engine has", metrics.Bytes)
5
Javascript
Javascript
add test for quadtree with no bounds
bcf70c96c93858710c5218b931f82b3edd988181
<ide><path>test/geom/quadtree-test.js <ide> suite.addBatch({ <ide> }, <ide> "has the default y-accessor, d[1]": function(q) { <ide> assert.strictEqual(q.y()([42, 43]), 43); <add> }, <add> "can create a single-node quadtree with no bounds": function(q) { <add> var point = [0, 0], <add> q = q([point]), <add> n = 0; <add> q.visit(function(node, x1, y1, x2, y2) { <add> assert.deepEqual(node.point, point); <add> assert.isUndefined(node[0]); <add> assert.isUndefined(node[1]); <add> assert.isUndefined(node[2]); <add> assert.isUndefined(node[3]); <add> assert.isTrue(node.leaf); <add> ++n; <add> }); <add> assert.strictEqual(n, 1, "number of visits"); <ide> } <ide> }, <ide> "the quadtree applied directly": { <add> "can create a single-node quadtree with no bounds": function(quadtree) { <add> var point = {x: 0, y: 0}, <add> q = quadtree([point]), <add> n = 0; <add> q.visit(function(node, x1, y1, x2, y2) { <add> assert.deepEqual(node.point, point); <add> assert.isUndefined(node[0]); <add> assert.isUndefined(node[1]); <add> assert.isUndefined(node[2]); <add> assert.isUndefined(node[3]); <add> assert.isTrue(node.leaf); <add> ++n; <add> }); <add> assert.strictEqual(n, 1, "number of visits"); <add> }, <ide> "can create an empty quadtree": function(quadtree) { <ide> var q = quadtree([], 8, 10, 56, 47), <ide> n = 0;
1
Python
Python
set version to v2.1.0a7.dev5
aebf71bc72e920b8c2ad34f0d8dca3267bec55f9
<ide><path>spacy/about.py <ide> # fmt: off <ide> <ide> __title__ = "spacy-nightly" <del>__version__ = "2.1.0a7.dev4" <add>__version__ = "2.1.0a7.dev5" <ide> __summary__ = "Industrial-strength Natural Language Processing (NLP) with Python and Cython" <ide> __uri__ = "https://spacy.io" <ide> __author__ = "Explosion AI"
1
Ruby
Ruby
add missing test for inreplace with tabs
701691c261778c8f3b531b2b827f046b97ac0bf0
<ide><path>Library/Homebrew/test/test_inreplace.rb <ide> def test_get_make_var <ide> s.extend(StringInreplaceExtension) <ide> assert_equal "-Wall -O2", s.get_make_var("CFLAGS") <ide> end <add> <add> def test_change_make_var_with_tabs <add> s = "CFLAGS\t=\t-Wall -O2\nLDFLAGS\t=\t-lcrypto -lssl" <add> s.extend(StringInreplaceExtension) <add> <add> assert_equal "-Wall -O2", s.get_make_var("CFLAGS") <add> <add> s.change_make_var! "CFLAGS", "-O3" <add> assert_equal "CFLAGS=-O3\nLDFLAGS\t=\t-lcrypto -lssl", s <add> <add> s.remove_make_var! "LDFLAGS" <add> assert_equal "CFLAGS=-O3\n", s <add> end <ide> end
1
Javascript
Javascript
pass null as error on successful send()
4bc1cccb228fdfd1a527de0ee1d9cedc6dac87e2
<ide><path>lib/dgram.js <ide> function doSend(ex, self, ip, buffer, address, port, callback) { <ide> function afterSend(err, sent) { <ide> if (err) { <ide> err = exceptionWithHostPort(err, 'send', this.address, this.port); <add> } else { <add> err = null; <ide> } <add> <ide> this.callback(err, sent); <ide> } <ide> <ide><path>test/parallel/test-dgram-send-callback-buffer.js <ide> const client = dgram.createSocket('udp4'); <ide> const buf = Buffer.allocUnsafe(256); <ide> <ide> const onMessage = common.mustCall(function(err, bytes) { <add> assert.strictEqual(err, null); <ide> assert.equal(bytes, buf.length); <ide> clearTimeout(timer); <ide> client.close();
2
PHP
PHP
simplify the code for object collection
91c09d87bcda582b492fdd5cb330068df49fe24b
<ide><path>lib/Cake/Utility/ObjectCollection.php <ide> public function trigger($callback, $params = array(), $options = array()) { <ide> if ($options['modParams'] !== false && !isset($params[$options['modParams']])) { <ide> throw new CakeException(__d('cake_dev', 'Cannot use modParams with indexes that do not exist.')); <ide> } <add> $result = null; <ide> foreach ($list as $name) { <ide> $result = call_user_func_array(array($this->_loaded[$name], $callback), compact('subject') + $params); <ide> if ($options['collectReturn'] === true) { <ide> public function enable($name, $prioritize = true) { <ide> $enabled = false; <ide> foreach ((array)$name as $object) { <ide> if (isset($this->_loaded[$object]) && !isset($this->_enabled[$object])) { <del> $priority = isset($this->_loaded[$object]->settings['priority']) ? $this->_loaded[$object]->settings['priority'] : $this->defaultPriority; <add> $priority = $this->defaultPriority; <add> if (isset($this->_loaded[$object]->settings['priority'])) { <add> $priority = $this->_loaded[$object]->settings['priority']; <add> } <ide> $this->_enabled[$object] = array($priority); <ide> $enabled = true; <ide> } <ide> public function setPriority($name, $priority = null) { <ide> if (is_string($name)) { <ide> $name = array($name => $priority); <ide> } <del> foreach ($name as $obj => $prio) { <del> if (isset($this->_loaded[$obj])) { <del> if (is_null($prio)) { <del> $prio = $this->defaultPriority; <add> foreach ($name as $object => $objectPriority) { <add> if (isset($this->_loaded[$object])) { <add> if (is_null($objectPriority)) { <add> $objectPriority = $this->defaultPriority; <ide> } <del> $this->_loaded[$obj]->settings['priority'] = $prio; <del> if (isset($this->_enabled[$obj])) { <del> $this->_enabled[$obj] = array($prio); <add> $this->_loaded[$object]->settings['priority'] = $objectPriority; <add> if (isset($this->_enabled[$object])) { <add> $this->_enabled[$object] = array($objectPriority); <ide> } <ide> } <ide> } <ide> public function attached($name = null) { <ide> * @return void <ide> */ <ide> public function unload($name) { <del> list($plugin, $name) = pluginSplit($name); <del> unset($this->_loaded[$name]); <del> unset($this->_enabled[$name]); <add> $name = array_pop(pluginSplit($name)); <add> unset($this->_loaded[$name], $this->_enabled[$name]); <ide> } <ide> <ide> /** <ide> public function unload($name) { <ide> */ <ide> public function set($name = null, $object = null) { <ide> if (!empty($name) && !empty($object)) { <del> list($plugin, $name) = pluginSplit($name); <del> $this->_loaded[$name] = $object; <add> $this->_loaded[array_pop(pluginSplit($name))] = $object; <ide> } <ide> return $this->_loaded; <ide> } <ide> public static function normalizeObjectArray($objects) { <ide> $options = (array)$objectName; <ide> $objectName = $i; <ide> } <del> list($plugin, $name) = pluginSplit($objectName); <del> $normal[$name] = array('class' => $objectName, 'settings' => $options); <add> $normal[array_pop(pluginSplit($objectName))] = array('class' => $objectName, 'settings' => $options); <ide> } <ide> return $normal; <ide> }
1
Javascript
Javascript
use main entry points from ember-runtime
20151a75d9276ed92497ed3d01b0b2766c9fe3ec
<ide><path>packages/ember-metal/lib/index.js <ide> export { <ide> export { <ide> intern, <ide> GUID_KEY, <add> GUID_KEY_PROPERTY, <ide> apply, <ide> applyStr, <ide> canInvoke, <ide> export { <ide> } from './testing'; <ide> export { <ide> getOnerror, <del> setOnerror <add> setOnerror, <add> dispatchError <ide> } from './error_handler'; <ide> export { <ide> META_DESC, <ide> export { <ide> _suspendObservers, <ide> addObserver, <ide> observersFor, <del> removeObserver <add> removeObserver, <add> _addBeforeObserver, <add> _removeBeforeObserver <ide> } from './observer'; <ide> export { <ide> NAME_KEY, <ide> Mixin, <ide> aliasMethod, <ide> _immediateObserver, <add> _beforeObserver, <ide> mixin, <ide> observer, <del> required <add> required, <add> REQUIRED, <add> hasUnprocessedMixins, <add> clearUnprocessedMixins, <add> detectBinding <ide> } from './mixin'; <ide> export { <ide> Binding, <ide> export { <ide> export { default as symbol } from './symbol'; <ide> export { default as dictionary } from './dictionary'; <ide> export { default as EmptyObject } from './empty_object'; <add>export { default as InjectedProperty } from './injected_property'; <add>export { tagFor, markObjectAsDirty } from './tags'; <add>export { default as replace } from './replace'; <ide> <ide> <ide> // TODO: this needs to be deleted once we refactor the build tooling <ide><path>packages/ember-runtime/lib/computed/computed_macros.js <del>import { assert, deprecate } from 'ember-metal/debug'; <del>import { get } from 'ember-metal/property_get'; <del>import { set } from 'ember-metal/property_set'; <del>import { computed } from 'ember-metal/computed'; <del>import isEmpty from 'ember-metal/is_empty'; <del>import isNone from 'ember-metal/is_none'; <del>import alias from 'ember-metal/alias'; <del>import expandProperties from 'ember-metal/expand_properties'; <add>import { <add> assert, <add> deprecate, <add> get, <add> set, <add> computed, <add> isEmpty, <add> isNone, <add> alias, <add> expandProperties <add>} from 'ember-metal'; <ide> <ide> /** <ide> @module ember <ide><path>packages/ember-runtime/lib/computed/reduce_computed_macros.js <ide> @submodule ember-runtime <ide> */ <ide> <del>import { assert } from 'ember-metal/debug'; <del>import { get } from 'ember-metal/property_get'; <del>import EmberError from 'ember-metal/error'; <del>import { ComputedProperty, computed } from 'ember-metal/computed'; <del>import { addObserver, removeObserver } from 'ember-metal/observer'; <add>import { <add> assert, <add> get, <add> Error as EmberError, <add> ComputedProperty, <add> computed, <add> addObserver, <add> removeObserver, <add> isNone, <add> getProperties, <add> EmptyObject, <add> guidFor, <add> WeakMap <add>} from 'ember-metal'; <ide> import compare from '../compare'; <ide> import { isArray } from '../utils'; <ide> import { A as emberA } from '../system/native_array'; <del>import isNone from 'ember-metal/is_none'; <del>import getProperties from 'ember-metal/get_properties'; <del>import EmptyObject from 'ember-metal/empty_object'; <del>import { guidFor } from 'ember-metal/utils'; <del>import WeakMap from 'ember-metal/weak_map'; <ide> <ide> <ide> function reduceMacro(dependentKey, callback, initialValue) { <ide><path>packages/ember-runtime/lib/controllers/controller.js <del>import { assert } from 'ember-metal/debug'; <add>import { assert } from 'ember-metal'; <ide> import EmberObject from '../system/object'; <ide> import Mixin from '../mixins/controller'; <ide> import { createInjectionHelper } from '../inject'; <ide><path>packages/ember-runtime/lib/copy.js <del>import { assert } from 'ember-metal/debug'; <add>import { assert } from 'ember-metal'; <ide> import EmberObject from './system/object'; <ide> import Copyable from './mixins/copyable'; <ide> <ide><path>packages/ember-runtime/lib/ext/function.js <ide> */ <ide> <ide> import { ENV } from 'ember-environment'; <del>import { assert, deprecateFunc } from 'ember-metal/debug'; <del>import { computed } from 'ember-metal/computed'; <del>import { observer } from 'ember-metal/mixin'; <add>import { <add> assert, <add> deprecateFunc, <add> computed, <add> observer <add>} from 'ember-metal'; <ide> <ide> const a_slice = Array.prototype.slice; <ide> const FunctionPrototype = Function.prototype; <ide><path>packages/ember-runtime/lib/ext/rsvp.js <ide> import * as RSVP from 'rsvp'; <del>import run from 'ember-metal/run_loop'; <del>import { assert } from 'ember-metal/debug'; <del>import { dispatchError } from 'ember-metal/error_handler'; <add>import { <add> run, <add> assert, <add> dispatchError <add>} from 'ember-metal'; <ide> <ide> const backburner = run.backburner; <ide> run._addQueue('rsvpAfter', 'destroy'); <ide><path>packages/ember-runtime/lib/inject.js <del>import { assert } from 'ember-metal/debug'; <del>import InjectedProperty from 'ember-metal/injected_property'; <add>import { <add> assert, <add> InjectedProperty <add>} from 'ember-metal'; <ide> <ide> /** <ide> Namespace for injection helper methods. <ide><path>packages/ember-runtime/lib/mixins/-proxy.js <ide> @submodule ember-runtime <ide> */ <ide> <del>import { assert, deprecate } from 'ember-metal/debug'; <del>import { get } from 'ember-metal/property_get'; <del>import { set } from 'ember-metal/property_set'; <del>import { meta } from 'ember-metal/meta'; <ide> import { <add> assert, <add> deprecate, <add> get, <add> set, <add> meta, <ide> addObserver, <ide> removeObserver, <ide> _addBeforeObserver, <del> _removeBeforeObserver <del>} from 'ember-metal/observer'; <del>import { <add> _removeBeforeObserver, <ide> propertyWillChange, <del> propertyDidChange <del>} from 'ember-metal/property_events'; <add> propertyDidChange, <add> defineProperty, <add> Mixin, <add> observer, <add> tagFor, <add> symbol <add>} from 'ember-metal'; <ide> import { bool } from '../computed/computed_macros'; <ide> import { POST_INIT } from '../system/core_object'; <del>import { defineProperty } from 'ember-metal/properties'; <del>import { Mixin, observer } from 'ember-metal/mixin'; <del>import { tagFor } from 'ember-metal/tags'; <del>import symbol from 'ember-metal/symbol'; <ide> import require, { has } from 'require'; <ide> <ide> const hasGlimmer = has('glimmer-reference'); <ide><path>packages/ember-runtime/lib/mixins/action_handler.js <ide> @submodule ember-runtime <ide> */ <ide> <del>import { assert, deprecate } from 'ember-metal/debug'; <del>import { Mixin } from 'ember-metal/mixin'; <del>import { get } from 'ember-metal/property_get'; <add>import { <add> assert, <add> deprecate, <add> Mixin, <add> get <add>} from 'ember-metal'; <ide> <ide> /** <ide> `Ember.ActionHandler` is available on some familiar classes including <ide><path>packages/ember-runtime/lib/mixins/array.js <ide> // .......................................................... <ide> // HELPERS <ide> // <del>import Ember from 'ember-metal/core'; // ES6TODO: Ember.A <del> <del>import symbol from 'ember-metal/symbol'; <del>import { get } from 'ember-metal/property_get'; <del>import { <add>import Ember, { // ES6TODO: Ember.A <add> symbol, <add> get, <ide> computed, <del> cacheFor <del>} from 'ember-metal/computed'; <del>import isNone from 'ember-metal/is_none'; <del>import Enumerable from './enumerable'; <del>import { Mixin } from 'ember-metal/mixin'; <del>import { <add> cacheFor, <add> isNone, <add> Mixin, <ide> propertyWillChange, <del> propertyDidChange <del>} from 'ember-metal/property_events'; <del>import { <add> propertyDidChange, <ide> addListener, <ide> removeListener, <ide> sendEvent, <del> hasListeners <del>} from 'ember-metal/events'; <del>import { meta as metaFor } from 'ember-metal/meta'; <del>import { markObjectAsDirty } from 'ember-metal/tags'; <add> hasListeners, <add> meta as metaFor, <add> markObjectAsDirty, <add> deprecate, <add> isFeatureEnabled <add>} from 'ember-metal'; <add> <add>import Enumerable from './enumerable'; <ide> import EachProxy from '../system/each_proxy'; <del>import { deprecate } from 'ember-metal/debug'; <del>import isEnabled from 'ember-metal/features'; <ide> <ide> function arrayObserversHelper(obj, target, opts, operation, notify) { <ide> let willChange = (opts && opts.willChange) || 'arrayWillChange'; <ide> const ArrayMixin = Mixin.create(Enumerable, { <ide> <ide> // optimized version from Enumerable <ide> contains(obj) { <del> if (isEnabled('ember-runtime-enumerable-includes')) { <add> if (isFeatureEnabled('ember-runtime-enumerable-includes')) { <ide> deprecate( <ide> '`Enumerable#contains` is deprecated, use `Enumerable#includes` instead.', <ide> false, <ide> const ArrayMixin = Mixin.create(Enumerable, { <ide> }).volatile() <ide> }); <ide> <del>if (isEnabled('ember-runtime-enumerable-includes')) { <add>if (isFeatureEnabled('ember-runtime-enumerable-includes')) { <ide> ArrayMixin.reopen({ <ide> /** <ide> Returns `true` if the passed object can be found in the array. <ide><path>packages/ember-runtime/lib/mixins/comparable.js <del>import { Mixin } from 'ember-metal/mixin'; <add>import { Mixin } from 'ember-metal'; <ide> <ide> /** <ide> @module ember <ide><path>packages/ember-runtime/lib/mixins/container_proxy.js <ide> @module ember <ide> @submodule ember-runtime <ide> */ <del>import run from 'ember-metal/run_loop'; <del>import { deprecate } from 'ember-metal/debug'; <del>import { Mixin } from 'ember-metal/mixin'; <add>import { <add> deprecate, <add> Mixin, <add> run <add>} from 'ember-metal'; <ide> <ide> <ide> /** <ide><path>packages/ember-runtime/lib/mixins/controller.js <del>import { Mixin } from 'ember-metal/mixin'; <del>import alias from 'ember-metal/alias'; <add>import { Mixin, alias } from 'ember-metal'; <ide> import ActionHandler from './action_handler'; <ide> import ControllerContentModelAliasDeprecation from './controller_content_model_alias_deprecation'; <ide> <ide><path>packages/ember-runtime/lib/mixins/controller_content_model_alias_deprecation.js <del>import { deprecate } from 'ember-metal/debug'; <del>import { Mixin } from 'ember-metal/mixin'; <add>import { <add> deprecate, <add> Mixin <add>} from 'ember-metal'; <ide> <ide> /* <ide> The ControllerContentModelAliasDeprecation mixin is used to provide a useful <ide><path>packages/ember-runtime/lib/mixins/copyable.js <ide> @submodule ember-runtime <ide> */ <ide> <del>import { deprecate } from 'ember-metal/debug'; <del>import { get } from 'ember-metal/property_get'; <del>import { Mixin } from 'ember-metal/mixin'; <add>import { <add> deprecate, <add> get, <add> Mixin, <add> Error as EmberError <add>} from 'ember-metal'; <ide> import { Freezable } from './freezable'; <del>import EmberError from 'ember-metal/error'; <ide> <ide> /** <ide> Implements some standard methods for copying an object. Add this mixin to <ide><path>packages/ember-runtime/lib/mixins/enumerable.js <ide> // HELPERS <ide> // <ide> <del>import { get } from 'ember-metal/property_get'; <del>import { set } from 'ember-metal/property_set'; <ide> import { <add> get, <add> set, <ide> Mixin, <del> aliasMethod <del>} from 'ember-metal/mixin'; <del>import { guidFor } from 'ember-metal/utils'; <del>import { computed } from 'ember-metal/computed'; <del>import EmptyObject from 'ember-metal/empty_object'; <del>import isEnabled from 'ember-metal/features'; <del>import { <add> aliasMethod, <add> guidFor, <add> computed, <add> EmptyObject, <add> isFeatureEnabled, <ide> propertyWillChange, <del> propertyDidChange <del>} from 'ember-metal/property_events'; <del>import { <add> propertyDidChange, <ide> addListener, <ide> removeListener, <ide> sendEvent, <del> hasListeners <del>} from 'ember-metal/events'; <add> hasListeners, <add> assert, <add> deprecate <add>} from 'ember-metal'; <ide> import compare from '../compare'; <ide> import require from 'require'; <del>import { assert, deprecate } from 'ember-metal/debug'; <ide> <ide> let _emberA; <ide> <ide> const Enumerable = Mixin.create({ <ide> @public <ide> */ <ide> contains(obj) { <del> if (isEnabled('ember-runtime-enumerable-includes')) { <add> if (isFeatureEnabled('ember-runtime-enumerable-includes')) { <ide> deprecate( <ide> '`Enumerable#contains` is deprecated, use `Enumerable#includes` instead.', <ide> false, <ide> const Enumerable = Mixin.create({ <ide> }); <ide> <ide> <del>if (isEnabled('ember-runtime-computed-uniq-by')) { <add>if (isFeatureEnabled('ember-runtime-computed-uniq-by')) { <ide> Enumerable.reopen({ <ide> /** <ide> Returns a new enumerable that contains only items containing a unique property value. <ide> if (isEnabled('ember-runtime-computed-uniq-by')) { <ide> }); <ide> } <ide> <del>if (isEnabled('ember-runtime-enumerable-includes')) { <add>if (isFeatureEnabled('ember-runtime-enumerable-includes')) { <ide> Enumerable.reopen({ <ide> /** <ide> Returns `true` if the passed object can be found in the enumerable. <ide><path>packages/ember-runtime/lib/mixins/evented.js <del>import { Mixin } from 'ember-metal/mixin'; <ide> import { <add> Mixin, <ide> addListener, <ide> removeListener, <ide> hasListeners, <ide> sendEvent <del>} from 'ember-metal/events'; <add>} from 'ember-metal'; <ide> <ide> /** <ide> @module ember <ide><path>packages/ember-runtime/lib/mixins/freezable.js <ide> @submodule ember-runtime <ide> */ <ide> <del>import { deprecate } from 'ember-metal/debug'; <del>import { Mixin } from 'ember-metal/mixin'; <del>import { get } from 'ember-metal/property_get'; <del>import { set } from 'ember-metal/property_set'; <add>import { <add> deprecate, <add> Mixin, <add> get, <add> set <add>} from 'ember-metal'; <ide> <ide> /** <ide> The `Ember.Freezable` mixin implements some basic methods for marking an <ide><path>packages/ember-runtime/lib/mixins/mutable_array.js <ide> const EMPTY = []; <ide> // HELPERS <ide> // <ide> <del>import { get } from 'ember-metal/property_get'; <del>import EmberError from 'ember-metal/error'; <del>import { Mixin } from 'ember-metal/mixin'; <add>import { <add> get, <add> Error as EmberError, <add> Mixin, <add> isFeatureEnabled <add>} from 'ember-metal'; <ide> import EmberArray, { objectAt } from './array'; <ide> import MutableEnumerable from './mutable_enumerable'; <ide> import Enumerable from './enumerable'; <del>import isEnabled from 'ember-metal/features'; <ide> <ide> export function removeAt(array, start, len) { <ide> if ('number' === typeof start) { <ide> export default Mixin.create(EmberArray, MutableEnumerable, { <ide> addObject(obj) { <ide> let included; <ide> <del> if (isEnabled('ember-runtime-enumerable-includes')) { <add> if (isFeatureEnabled('ember-runtime-enumerable-includes')) { <ide> included = this.includes(obj); <ide> } else { <ide> included = this.contains(obj); <ide><path>packages/ember-runtime/lib/mixins/mutable_enumerable.js <ide> import Enumerable from './enumerable'; <del>import { Mixin } from 'ember-metal/mixin'; <del>import {beginPropertyChanges, endPropertyChanges} from 'ember-metal/property_events'; <add>import { <add> Mixin, <add> beginPropertyChanges, <add> endPropertyChanges <add>} from 'ember-metal'; <ide> <ide> /** <ide> @module ember <ide><path>packages/ember-runtime/lib/mixins/observable.js <ide> @submodule ember-runtime <ide> */ <ide> <del>import { assert } from 'ember-metal/debug'; <ide> import { <add> assert, <ide> get, <del> getWithDefault <del>} from 'ember-metal/property_get'; <del>import { set } from 'ember-metal/property_set'; <del>import getProperties from 'ember-metal/get_properties'; <del>import setProperties from 'ember-metal/set_properties'; <del>import { Mixin } from 'ember-metal/mixin'; <del>import { hasListeners } from 'ember-metal/events'; <del>import { <add> getWithDefault, <add> set, <add> getProperties, <add> setProperties, <add> Mixin, <add> hasListeners, <ide> beginPropertyChanges, <ide> propertyWillChange, <ide> propertyDidChange, <del> endPropertyChanges <del>} from 'ember-metal/property_events'; <del>import { <add> endPropertyChanges, <ide> addObserver, <ide> removeObserver, <del> observersFor <del>} from 'ember-metal/observer'; <del>import { cacheFor } from 'ember-metal/computed'; <del>import isNone from 'ember-metal/is_none'; <add> observersFor, <add> cacheFor, <add> isNone <add>} from 'ember-metal'; <ide> <ide> /** <ide> ## Overview <ide><path>packages/ember-runtime/lib/mixins/promise_proxy.js <del>import { get } from 'ember-metal/property_get'; <del>import setProperties from 'ember-metal/set_properties'; <del>import { computed } from 'ember-metal/computed'; <add>import { <add> get, <add> setProperties, <add> computed, <add> Mixin, <add> Error as EmberError <add>} from 'ember-metal'; <ide> import { not, or } from '../computed/computed_macros'; <del>import { Mixin } from 'ember-metal/mixin'; <del>import EmberError from 'ember-metal/error'; <ide> <ide> /** <ide> @module ember <ide><path>packages/ember-runtime/lib/mixins/registry_proxy.js <ide> @submodule ember-runtime <ide> */ <ide> <del>import { deprecate } from 'ember-metal/debug'; <del>import { Mixin } from 'ember-metal/mixin'; <add>import { <add> deprecate, <add> Mixin <add>} from 'ember-metal'; <ide> <ide> /** <ide> RegistryProxyMixin is used to provide public access to specific <ide><path>packages/ember-runtime/lib/mixins/target_action_support.js <ide> */ <ide> <ide> import { context } from 'ember-environment'; <del>import { assert } from 'ember-metal/debug'; <del>import { get } from 'ember-metal/property_get'; <del>import { Mixin } from 'ember-metal/mixin'; <del>import { computed } from 'ember-metal/computed'; <add>import { <add> assert, <add> get, <add> Mixin, <add> computed <add>} from 'ember-metal'; <ide> <ide> /** <ide> `Ember.TargetActionSupport` is a mixin that can be included in a class <ide><path>packages/ember-runtime/lib/system/array_proxy.js <del>import { assert } from 'ember-metal/debug'; <del>import { get } from 'ember-metal/property_get'; <del>import { <del> isArray <del>} from '../utils'; <del>import { computed } from 'ember-metal/computed'; <ide> import { <add> assert, <add> get, <add> computed, <ide> _beforeObserver, <del> observer <del>} from 'ember-metal/mixin'; <del>import { <add> observer, <ide> beginPropertyChanges, <del> endPropertyChanges <del>} from 'ember-metal/property_events'; <del>import EmberError from 'ember-metal/error'; <add> endPropertyChanges, <add> Error as EmberError, <add> alias <add>} from 'ember-metal'; <add>import { <add> isArray <add>} from '../utils'; <ide> import EmberObject from './object'; <ide> import MutableArray from '../mixins/mutable_array'; <ide> import Enumerable from '../mixins/enumerable'; <del>import alias from 'ember-metal/alias'; <ide> import { <ide> addArrayObserver, <ide> removeArrayObserver, <ide><path>packages/ember-runtime/lib/system/core_object.js <ide> <ide> // using ember-metal/lib/main here to ensure that ember-debug is setup <ide> // if present <del>import { assert, runInDebug } from 'ember-metal/debug'; <del>import isEnabled from 'ember-metal/features'; <del>import assign from 'ember-metal/assign'; <del> <del>// NOTE: this object should never be included directly. Instead use `Ember.Object`. <del>// We only define this separately so that `Ember.Set` can depend on it. <del>import { get } from 'ember-metal/property_get'; <del>import { <del> guidFor <del>} from 'ember-metal/utils'; <ide> import { <add> assert, <add> runInDebug, <add> isFeatureEnabled, <add> assign, <add> get, <add> guidFor, <ide> generateGuid, <ide> GUID_KEY_PROPERTY, <del> makeArray <del>} from 'ember-metal/utils'; <del>import { meta } from 'ember-metal/meta'; <del>import { finishChains } from 'ember-metal/chains'; <del>import { sendEvent } from 'ember-metal/events'; <del>import { <add> makeArray, <add> meta, <add> finishChains, <add> sendEvent, <ide> detectBinding, <ide> Mixin, <del> REQUIRED <del>} from 'ember-metal/mixin'; <del>import EmberError from 'ember-metal/error'; <add> REQUIRED, <add> Error as EmberError, <add> defineProperty, <add> Binding, <add> ComputedProperty, <add> computed, <add> InjectedProperty, <add> run, <add> destroy, <add> symbol <add>} from 'ember-metal'; <ide> import ActionHandler from '../mixins/action_handler'; <del>import { defineProperty } from 'ember-metal/properties'; <del>import { Binding } from 'ember-metal/binding'; <del>import { ComputedProperty, computed } from 'ember-metal/computed'; <del>import InjectedProperty from 'ember-metal/injected_property'; <del>import run from 'ember-metal/run_loop'; <del>import { destroy } from 'ember-metal/watching'; <ide> import { validatePropertyInjections } from '../inject'; <del>import symbol from 'ember-metal/symbol'; <ide> <ide> export let POST_INIT = symbol('POST_INIT'); <ide> var schedule = run.schedule; <ide> function makeCtor() { <ide> if (typeof this.setUnknownProperty === 'function' && !(keyName in this)) { <ide> this.setUnknownProperty(keyName, value); <ide> } else { <del> if (isEnabled('mandatory-setter')) { <add> if (isFeatureEnabled('mandatory-setter')) { <ide> defineProperty(this, keyName, null, value); // setup mandatory setter <ide> } else { <ide> this[keyName] = value; <ide><path>packages/ember-runtime/lib/system/each_proxy.js <del>import { assert } from 'ember-metal/debug'; <del>import { get } from 'ember-metal/property_get'; <ide> import { <add> assert, <add> get, <ide> _addBeforeObserver, <ide> _removeBeforeObserver, <ide> addObserver, <del> removeObserver <del>} from 'ember-metal/observer'; <del>import { <add> removeObserver, <ide> propertyDidChange, <del> propertyWillChange <del>} from 'ember-metal/property_events'; <del>import EmptyObject from 'ember-metal/empty_object'; <add> propertyWillChange, <add> EmptyObject <add>} from 'ember-metal'; <ide> import { objectAt } from '../mixins/array'; <ide> <ide> /** <ide><path>packages/ember-runtime/lib/system/namespace.js <ide> @module ember <ide> @submodule ember-runtime <ide> */ <del>import Ember from 'ember-metal/core'; // Preloaded into namespaces <del>import { context } from 'ember-environment'; <del>import { get } from 'ember-metal/property_get'; <del>import { <del> guidFor <del>} from 'ember-metal/utils'; <del>import { <add>import Ember, { <add> get, <add> guidFor, <ide> Mixin, <ide> hasUnprocessedMixins, <ide> clearUnprocessedMixins, <ide> NAME_KEY <del>} from 'ember-metal/mixin'; <add>} from 'ember-metal'; // Preloaded into namespaces <add>import { context } from 'ember-environment'; <ide> <ide> import EmberObject from './object'; <ide> <ide><path>packages/ember-runtime/lib/system/native_array.js <ide> @module ember <ide> @submodule ember-runtime <ide> */ <del>import Ember from 'ember-metal/core'; // Ember.A circular <add>import Ember, { // Ember.A circular <add> replace, <add> get, <add> Mixin <add>} from 'ember-metal'; <ide> import { ENV } from 'ember-environment'; <del>import replace from 'ember-metal/replace'; <del>import { get } from 'ember-metal/property_get'; <del>import { Mixin } from 'ember-metal/mixin'; <ide> import EmberArray, { <ide> arrayContentDidChange, <ide> arrayContentWillChange <ide><path>packages/ember-runtime/lib/system/string.js <ide> @module ember <ide> @submodule ember-runtime <ide> */ <del>import { deprecate } from 'ember-metal/debug'; <ide> import { <del> inspect as emberInspect <del>} from 'ember-metal/utils'; <add> deprecate, <add> inspect as emberInspect, <add> Cache <add>} from 'ember-metal'; <ide> import { isArray } from '../utils'; <ide> import { <ide> get as getString <ide> } from '../string_registry'; <ide> <del>import Cache from 'ember-metal/cache'; <del> <ide> const STRING_DASHERIZE_REGEXP = (/[ _]/g); <ide> <ide> const STRING_DASHERIZE_CACHE = new Cache(1000, function(key) { <ide><path>packages/ember/lib/index.js <ide> import isEnabled from 'ember-metal/features'; <ide> // ****ember-environment**** <ide> import { ENV, context } from 'ember-environment'; <ide> <add>import { <add> Registry, <add> Container, <add> getOwner, <add> setOwner <add>} from 'container'; <ide> <ide> // ****ember-metal**** <ide> import Ember, * as metal from 'ember-metal'; <ide> Ember.Backburner = function() { <ide> <ide> Ember._Backburner = Backburner; <ide> <del>import { <del> Registry, <del> Container, <del> getOwner, <del> setOwner <del>} from 'container'; <ide> <ide> Ember.Container = Container; <ide> Ember.Registry = Registry;
32
Mixed
Ruby
fix error when assigning nan to an integer column
807e176aba7804cad8d630d04f3b771011be4fe6
<ide><path>activerecord/CHANGELOG.md <ide> <ide> *Rob Worley* <ide> <del>* Fix undefined method `to_i` when calling `new` on a scope that uses an Array. <del> Fixes #8718, #8734. <add>* Fix undefined method `to_i` when calling `new` on a scope that uses an <add> Array; Fix FloatDomainError when setting integer column to NaN. <add> Fixes #8718, #8734, #8757. <ide> <del> *Jason Stirk* <add> *Jason Stirk + Tristan Harward* <ide> <ide> * Rename `update_attributes` to `update`, keep `update_attributes` as an alias for `update` method. <ide> This is a soft-deprecation for `update_attributes`, although it will still work without any <ide> *Amparo Luna + Guillermo Iguaran* <ide> <ide> * `after_commit` and `after_rollback` now validate the `:on` option and raise an `ArgumentError` <del> if it is not one of `:create`, `:destroy` or ``:update` <add> if it is not one of `:create`, `:destroy` or `:update` <ide> <ide> *Pascal Friederich* <ide> <ide><path>activerecord/lib/active_record/connection_adapters/column.rb <ide> def value_to_integer(value) <ide> when TrueClass, FalseClass <ide> value ? 1 : 0 <ide> else <del> if value.respond_to?(:to_i) <del> value.to_i <del> else <del> nil <del> end <add> value.to_i rescue nil <ide> end <ide> end <ide> <ide><path>activerecord/test/cases/column_test.rb <ide> def test_type_cast_object_without_to_i_to_integer <ide> assert_nil column.type_cast(Object.new) <ide> end <ide> <add> def test_type_cast_nan_and_infinity_to_integer <add> column = Column.new("field", nil, "integer") <add> assert_nil column.type_cast(Float::NAN) <add> assert_nil column.type_cast(1.0/0.0) <add> end <add> <ide> def test_type_cast_time <ide> column = Column.new("field", nil, "time") <ide> assert_equal nil, column.type_cast('')
3
Ruby
Ruby
fix indentation in the template for secrets
ac345f5dadc31a63239e0705dcacc51ef74fdd61
<ide><path>railties/lib/rails/secrets.rb <ide> def template <ide> <<-end_of_template.strip_heredoc <ide> # See `secrets.yml` for tips on generating suitable keys. <ide> # production: <del> # external_api_key: 1466aac22e6a869134be3d09b9e89232fc2c2289 <add> # external_api_key: 1466aac22e6a869134be3d09b9e89232fc2c2289 <ide> <ide> end_of_template <ide> end <ide><path>railties/test/generators/encrypted_secrets_generator_test.rb <ide> def test_generates_key_file_and_encrypted_secrets_file <ide> assert_file "config/secrets.yml.key", /\w+/ <ide> <ide> assert File.exist?("config/secrets.yml.enc") <del> assert_no_match(/production:\n# external_api_key: \w+/, IO.binread("config/secrets.yml.enc")) <del> assert_match(/production:\n# external_api_key: \w+/, Rails::Secrets.read) <add> assert_no_match(/# production:\n# external_api_key: \w+/, IO.binread("config/secrets.yml.enc")) <add> assert_match(/# production:\n# external_api_key: \w+/, Rails::Secrets.read) <ide> end <ide> <ide> def test_appends_to_gitignore <ide><path>railties/test/secrets_test.rb <ide> def teardown <ide> ENV["RAILS_MASTER_KEY"] = IO.binread("config/secrets.yml.key").strip <ide> FileUtils.rm("config/secrets.yml.key") <ide> <del> assert_match "production:\n# external_api_key", Rails::Secrets.read <add> assert_match "# production:\n# external_api_key:", Rails::Secrets.read <ide> ensure <ide> ENV["RAILS_MASTER_KEY"] = old_key <ide> end <ide> def teardown <ide> Rails::Secrets.read_for_editing do |tmp_path| <ide> decrypted_path = tmp_path <ide> <del> assert_match(/production:\n# external_api_key/, File.read(tmp_path)) <add> assert_match(/# production:\n# external_api_key/, File.read(tmp_path)) <ide> <ide> File.write(tmp_path, "Empty streets, empty nights. The Downtown Lights.") <ide> end
3
Java
Java
update copyright date
b34404916a6640e2b30ca030db61186313b7a957
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java <ide> /* <del> * Copyright 2002-2018 the original author or authors. <add> * Copyright 2002-2020 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide><path>spring-core/src/main/java/org/springframework/core/type/classreading/AnnotationMetadataReadingVisitor.java <ide> /* <del> * Copyright 2002-2019 the original author or authors. <add> * Copyright 2002-2020 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License.
2
PHP
PHP
remove duplicate queries to find batch
502a5054025a81996d45d2657a598809db3c2aab
<ide><path>src/Illuminate/Queue/CallQueuedHandler.php <ide> protected function ensureSuccessfulBatchJobIsRecorded($command) <ide> $uses = class_uses_recursive($command); <ide> <ide> if (! in_array(Batchable::class, $uses) || <del> ! in_array(InteractsWithQueue::class, $uses) || <del> is_null($command->batch())) { <add> ! in_array(InteractsWithQueue::class, $uses)) { <ide> return; <ide> } <ide> <del> $command->batch()->recordSuccessfulJob($command->job->uuid()); <add> if ($batch = $command->batch()) { <add> $batch->recordSuccessfulJob($command->job->uuid()); <add> } <ide> } <ide> <ide> /** <ide> public function failed(array $data, $e, string $uuid) <ide> */ <ide> protected function ensureFailedBatchJobIsRecorded(string $uuid, $command, $e) <ide> { <del> if (! in_array(Batchable::class, class_uses_recursive($command)) || <del> is_null($command->batch())) { <add> if (! in_array(Batchable::class, class_uses_recursive($command))) { <ide> return; <ide> } <ide> <del> $command->batch()->recordFailedJob($uuid, $e); <add> if ($batch = $command->batch()) { <add> $batch->recordFailedJob($uuid, $e); <add> } <ide> } <ide> <ide> /**
1
Python
Python
add logic to lock db and avoid race condition
c1aa93f1a7c9dbe88889b78b541b3abe05ded081
<ide><path>airflow/models.py <ide> def error(self, session=None): <ide> session.commit() <ide> <ide> @provide_session <del> def refresh_from_db(self, session=None): <add> def refresh_from_db(self, session=None, lock_for_update=False): <ide> """ <ide> Refreshes the task instance from the database based on the primary key <add> <add> :param lock_for_update: if True, indicates that the database should <add> lock the TaskInstance (issuing a FOR UPDATE clause) until the session <add> is committed. <ide> """ <ide> TI = TaskInstance <del> ti = session.query(TI).filter( <add> <add> qry = session.query(TI).filter( <ide> TI.dag_id == self.dag_id, <ide> TI.task_id == self.task_id, <del> TI.execution_date == self.execution_date, <del> ).first() <add> TI.execution_date == self.execution_date) <add> <add> if lock_for_update: <add> ti = qry.with_for_update().first() <add> else: <add> ti = qry.first() <ide> if ti: <ide> self.state = ti.state <ide> self.start_date = ti.start_date <ide> def run( <ide> self.pool = pool or task.pool <ide> self.test_mode = test_mode <ide> self.force = force <del> self.refresh_from_db() <add> self.refresh_from_db(session=session, lock_for_update=True) <ide> self.clear_xcom_data() <ide> self.job_id = job_id <ide> iso = datetime.now().isoformat()
1
Mixed
Go
add cpuset cpus support for docker
adbe3096e8c8572925dbae5f19ac2ce2dc84fb1c
<ide><path>daemon/container.go <ide> func populateCommand(c *Container, env []string) error { <ide> Memory: c.Config.Memory, <ide> MemorySwap: c.Config.MemorySwap, <ide> CpuShares: c.Config.CpuShares, <add> Cpuset: c.Config.Cpuset, <ide> } <ide> c.command = &execdriver.Command{ <ide> ID: c.ID, <ide><path>daemon/execdriver/driver.go <ide> type NetworkInterface struct { <ide> } <ide> <ide> type Resources struct { <del> Memory int64 `json:"memory"` <del> MemorySwap int64 `json:"memory_swap"` <del> CpuShares int64 `json:"cpu_shares"` <add> Memory int64 `json:"memory"` <add> MemorySwap int64 `json:"memory_swap"` <add> CpuShares int64 `json:"cpu_shares"` <add> Cpuset string `json:"cpuset"` <ide> } <ide> <ide> type Mount struct { <ide><path>daemon/execdriver/lxc/lxc_template.go <ide> lxc.cgroup.memory.memsw.limit_in_bytes = {{$memSwap}} <ide> {{if .Resources.CpuShares}} <ide> lxc.cgroup.cpu.shares = {{.Resources.CpuShares}} <ide> {{end}} <add>{{if .Resources.Cpuset}} <add>lxc.cgroup.cpuset.cpus = {{.Resources.Cpuset}} <add>{{end}} <ide> {{end}} <ide> <ide> {{if .Config.lxc}} <ide><path>daemon/execdriver/native/create.go <ide> func (d *driver) setupCgroups(container *libcontainer.Container, c *execdriver.C <ide> container.Cgroups.Memory = c.Resources.Memory <ide> container.Cgroups.MemoryReservation = c.Resources.Memory <ide> container.Cgroups.MemorySwap = c.Resources.MemorySwap <add> container.Cgroups.CpusetCpus = c.Resources.Cpuset <ide> } <ide> return nil <ide> } <ide><path>docs/sources/reference/commandline/cli.md <ide> Run a command in a new container <ide> <ide> -a, --attach=[] Attach to stdin, stdout or stderr. <ide> -c, --cpu-shares=0 CPU shares (relative weight) <add> --cpuset="" CPUs in which to allow execution (0-3, 0,1) <ide> --cidfile="" Write the container ID to the file <ide> -d, --detach=false Detached mode: Run container in the background, print new container id <ide> --dns=[] Set custom dns servers <ide><path>integration-cli/docker_cli_run_test.go <ide> func TestProcWritableInPrivilegedContainers(t *testing.T) { <ide> <ide> logDone("run - proc writable in privileged container") <ide> } <add> <add>func TestRunWithCpuset(t *testing.T) { <add> cmd := exec.Command(dockerBinary, "run", "--cpuset", "0", "busybox", "true") <add> if code, err := runCommand(cmd); err != nil || code != 0 { <add> t.Fatalf("container should run successfuly with cpuset of 0: %s", err) <add> } <add> <add> deleteAllContainers() <add> <add> logDone("run - cpuset 0") <add>} <ide><path>runconfig/config.go <ide> type Config struct { <ide> Hostname string <ide> Domainname string <ide> User string <del> Memory int64 // Memory limit (in bytes) <del> MemorySwap int64 // Total memory usage (memory + swap); set `-1' to disable swap <del> CpuShares int64 // CPU shares (relative weight vs. other containers) <add> Memory int64 // Memory limit (in bytes) <add> MemorySwap int64 // Total memory usage (memory + swap); set `-1' to disable swap <add> CpuShares int64 // CPU shares (relative weight vs. other containers) <add> Cpuset string // Cpuset 0-2, 0,1 <ide> AttachStdin bool <ide> AttachStdout bool <ide> AttachStderr bool <ide> func ContainerConfigFromJob(job *engine.Job) *Config { <ide> Memory: job.GetenvInt64("Memory"), <ide> MemorySwap: job.GetenvInt64("MemorySwap"), <ide> CpuShares: job.GetenvInt64("CpuShares"), <add> Cpuset: job.Getenv("Cpuset"), <ide> AttachStdin: job.GetenvBool("AttachStdin"), <ide> AttachStdout: job.GetenvBool("AttachStdout"), <ide> AttachStderr: job.GetenvBool("AttachStderr"), <ide><path>runconfig/parse.go <ide> func parseRun(cmd *flag.FlagSet, args []string, sysInfo *sysinfo.SysInfo) (*Conf <ide> flUser = cmd.String([]string{"u", "-user"}, "", "Username or UID") <ide> flWorkingDir = cmd.String([]string{"w", "-workdir"}, "", "Working directory inside the container") <ide> flCpuShares = cmd.Int64([]string{"c", "-cpu-shares"}, 0, "CPU shares (relative weight)") <add> flCpuset = cmd.String([]string{"-cpuset"}, "", "CPUs in which to allow execution (0-3, 0,1)") <ide> flNetMode = cmd.String([]string{"-net"}, "bridge", "Set the Network mode for the container\n'bridge': creates a new network stack for the container on the docker bridge\n'none': no networking for this container\n'container:<name|id>': reuses another container network stack\n'host': use the host network stack inside the contaner") <ide> // For documentation purpose <ide> _ = cmd.Bool([]string{"#sig-proxy", "-sig-proxy"}, true, "Proxify all received signal to the process (even in non-tty mode)") <ide> func parseRun(cmd *flag.FlagSet, args []string, sysInfo *sysinfo.SysInfo) (*Conf <ide> OpenStdin: *flStdin, <ide> Memory: flMemory, <ide> CpuShares: *flCpuShares, <add> Cpuset: *flCpuset, <ide> AttachStdin: flAttach.Get("stdin"), <ide> AttachStdout: flAttach.Get("stdout"), <ide> AttachStderr: flAttach.Get("stderr"),
8
Text
Text
update example in repl.md
d8f8096ec6e6b9516cd5ca3f046669194ec0984c
<ide><path>doc/api/repl.md <ide> const replServer = repl.start({prompt: '> '}); <ide> replServer.defineCommand('sayhello', { <ide> help: 'Say hello', <ide> action(name) { <del> this.lineParser.reset(); <ide> this.bufferedCommand = ''; <ide> console.log(`Hello, ${name}!`); <ide> this.displayPrompt();
1
Text
Text
edit addon text about event loop blocking
e28f23f39f6a6d1d42d959a3c3ae9cce2c08d694
<ide><path>doc/api/addons.md <ide> involving knowledge of several components and APIs: <ide> as interacting with the filesystem, sockets, timers, and system events. libuv <ide> also provides a threading abstraction similar to POSIX threads for <ide> more sophisticated asynchronous addons that need to move beyond the <del> standard event loop. Addon authors are encouraged to think about how to <add> standard event loop. Addon authors should <ide> avoid blocking the event loop with I/O or other time-intensive tasks by <del> off-loading work via libuv to non-blocking system operations, worker threads <del> or a custom use of libuv's threads. <add> offloading work via libuv to non-blocking system operations, worker threads, <add> or a custom use of libuv threads. <ide> <ide> * Internal Node.js libraries. Node.js itself exports C++ APIs that addons can <ide> use, the most important of which is the `node::ObjectWrap` class.
1
Text
Text
improve discoverability of code of conduct
d781cdc349973891030d2a46b72bb779a06aa7e0
<ide><path>CODE_OF_CONDUCT.md <add>## Code of Conduct <add> <add>This Code of Conduct is adapted from [Rust's wonderful <add>CoC](http://www.rust-lang.org/conduct.html). <add> <add>* We are committed to providing a friendly, safe and welcoming <add> environment for all, regardless of gender, sexual orientation, <add> disability, ethnicity, religion, or similar personal characteristic. <add>* Please avoid using overtly sexual nicknames or other nicknames that <add> might detract from a friendly, safe and welcoming environment for <add> all. <add>* Please be kind and courteous. There's no need to be mean or rude. <add>* Respect that people have differences of opinion and that every <add> design or implementation choice carries a trade-off and numerous <add> costs. There is seldom a right answer. <add>* Please keep unstructured critique to a minimum. If you have solid <add> ideas you want to experiment with, make a fork and see how it works. <add>* We will exclude you from interaction if you insult, demean or harass <add> anyone. That is not welcome behavior. We interpret the term <add> "harassment" as including the definition in the [Citizen Code of <add> Conduct](http://citizencodeofconduct.org/); if you have any lack of <add> clarity about what might be included in that concept, please read <add> their definition. In particular, we don't tolerate behavior that <add> excludes people in socially marginalized groups. <add>* Private harassment is also unacceptable. No matter who you are, if <add> you feel you have been or are being harassed or made uncomfortable <add> by a community member, please contact one of the channel ops or any <add> of the TSC members immediately with a capture (log, photo, email) of <add> the harassment if possible. Whether you're a regular contributor or <add> a newcomer, we care about making this community a safe place for you <add> and we've got your back. <add>* Likewise any spamming, trolling, flaming, baiting or other <add> attention-stealing behavior is not welcome. <add>* Avoid the use of personal pronouns in code comments or <add> documentation. There is no need to address persons when explaining <add> code (e.g. "When the developer"). <ide><path>CONTRIBUTING.md <ide> # Contributing to Node.js <ide> <add>## Code of Conduct <add> <add>The Code of Conduct explains the *bare minimum* behavior <add>expectations the Node Foundation requires of its contributors. <add>[Please read it before participating.](./CODE_OF_CONDUCT.md) <add> <ide> ## Issue Contributions <ide> <ide> When opening new issues or commenting on existing issues on this repository <ide> By making a contribution to this project, I certify that: <ide> different license), as indicated in the file; or <ide> * (c) The contribution was provided directly to me by some other <ide> person who certified (a), (b) or (c) and I have not modified it. <del> <del> <del>## Code of Conduct <del> <del>This Code of Conduct is adapted from [Rust's wonderful <del>CoC](http://www.rust-lang.org/conduct.html). <del> <del>* We are committed to providing a friendly, safe and welcoming <del> environment for all, regardless of gender, sexual orientation, <del> disability, ethnicity, religion, or similar personal characteristic. <del>* Please avoid using overtly sexual nicknames or other nicknames that <del> might detract from a friendly, safe and welcoming environment for <del> all. <del>* Please be kind and courteous. There's no need to be mean or rude. <del>* Respect that people have differences of opinion and that every <del> design or implementation choice carries a trade-off and numerous <del> costs. There is seldom a right answer. <del>* Please keep unstructured critique to a minimum. If you have solid <del> ideas you want to experiment with, make a fork and see how it works. <del>* We will exclude you from interaction if you insult, demean or harass <del> anyone. That is not welcome behavior. We interpret the term <del> "harassment" as including the definition in the [Citizen Code of <del> Conduct](http://citizencodeofconduct.org/); if you have any lack of <del> clarity about what might be included in that concept, please read <del> their definition. In particular, we don't tolerate behavior that <del> excludes people in socially marginalized groups. <del>* Private harassment is also unacceptable. No matter who you are, if <del> you feel you have been or are being harassed or made uncomfortable <del> by a community member, please contact one of the channel ops or any <del> of the TC members immediately with a capture (log, photo, email) of <del> the harassment if possible. Whether you're a regular contributor or <del> a newcomer, we care about making this community a safe place for you <del> and we've got your back. <del>* Likewise any spamming, trolling, flaming, baiting or other <del> attention-stealing behavior is not welcome. <del>* Avoid the use of personal pronouns in code comments or <del> documentation. There is no need to address persons when explaining <del> code (e.g. "When the developer"). <ide><path>README.md <ide> We intend to land, with increasing regularity, releases which are <ide> compatible with the npm ecosystem that has been built to date for <ide> Node.js. <ide> <add>We also have a Code of Conduct. [Please read it.](./CODE_OF_CONDUCT.md) <add> <ide> ## Download <ide> <ide> Binaries, installers, and source tarballs are available at <ide> Instructions: <ide> <ide> ## Resources for Newcomers <ide> <add>* [CODE_OF_CONDUCT.md](./CODE_OF_CONDUCT.md) <ide> * [CONTRIBUTING.md](./CONTRIBUTING.md) <ide> * [GOVERNANCE.md](./GOVERNANCE.md) <ide> * IRC:
3
Javascript
Javascript
add newline to cert and key if not present
cdde9a386aca90ae151be9ad9455d0d0586d113b
<ide><path>lib/crypto.js <ide> function Credentials(secureProtocol, flags, context) { <ide> <ide> exports.Credentials = Credentials; <ide> <add>function addNewline(buf) { <add> var last = buf[buf.length - 1]; <add> var isBuf = Buffer.isBuffer(buf); <add> <add> if (!isBuf && !util.isString(buf)) <add> throw new Error('Certificate should be of type Buffer or string'); <add> <add> if (isBuf ? last !== 10 : last !== '\n') <add> return buf.toString().trim() + '\n'; <add> else <add> return buf; <add>} <ide> <ide> exports.createCredentials = function(options, context) { <ide> if (!options) options = {}; <ide> exports.createCredentials = function(options, context) { <ide> if (context) return c; <ide> <ide> if (options.key) { <add> var key = addNewline(options.key); <ide> if (options.passphrase) { <del> c.context.setKey(options.key, options.passphrase); <add> c.context.setKey(key, options.passphrase); <ide> } else { <del> c.context.setKey(options.key); <add> c.context.setKey(key); <ide> } <ide> } <ide> <del> if (options.cert) c.context.setCert(options.cert); <add> if (options.cert) c.context.setCert(addNewline(options.cert)); <ide> <ide> if (options.ciphers) c.context.setCiphers(options.ciphers); <ide> <ide><path>test/simple/test-tls-cert-regression.js <add>// Copyright Joyent, Inc. and other Node contributors. <add>// <add>// Permission is hereby granted, free of charge, to any person obtaining a <add>// copy of this software and associated documentation files (the <add>// "Software"), to deal in the Software without restriction, including <add>// without limitation the rights to use, copy, modify, merge, publish, <add>// distribute, sublicense, and/or sell copies of the Software, and to permit <add>// persons to whom the Software is furnished to do so, subject to the <add>// following conditions: <add>// <add>// The above copyright notice and this permission notice shall be included <add>// in all copies or substantial portions of the Software. <add>// <add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS <add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF <add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN <add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, <add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR <add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE <add>// USE OR OTHER DEALINGS IN THE SOFTWARE. <add> <add>if (!process.versions.openssl) { <add> console.error('Skipping because node compiled without OpenSSL.'); <add> process.exit(0); <add>} <add> <add>var tls = require('tls'); <add> <add>var assert = require('assert'); <add>var common = require('../common'); <add> <add>var cert = '-----BEGIN CERTIFICATE-----\n' + <add> 'MIIBfjCCASgCCQDmmNjAojbDQjANBgkqhkiG9w0BAQUFADBFMQswCQYDVQQGEwJB\n' + <add> 'VTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50ZXJuZXQgV2lkZ2l0\n' + <add> 'cyBQdHkgTHRkMCAXDTE0MDExNjE3NTMxM1oYDzIyODcxMDMxMTc1MzEzWjBFMQsw\n' + <add> 'CQYDVQQGEwJBVTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50ZXJu\n' + <add> 'ZXQgV2lkZ2l0cyBQdHkgTHRkMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAPKwlfMX\n' + <add> '6HGZIt1xm7fna72eWcOYfUfSxSugghvqYgJt2Oi3lH+wsU1O9FzRIVmpeIjDXhbp\n' + <add> 'Mjsa1HtzSiccPXsCAwEAATANBgkqhkiG9w0BAQUFAANBAHOoKy0NkyfiYH7Ne5ka\n' + <add> 'uvCyndyeB4d24FlfqEUlkfaWCZlNKRaV9YhLDiEg3BcIreFo4brtKQfZzTRs0GVm\n' + <add> 'KHg=\n' + <add> '-----END CERTIFICATE-----'; <add>var key = '-----BEGIN RSA PRIVATE KEY-----\n' + <add> 'MIIBPQIBAAJBAPKwlfMX6HGZIt1xm7fna72eWcOYfUfSxSugghvqYgJt2Oi3lH+w\n' + <add> 'sU1O9FzRIVmpeIjDXhbpMjsa1HtzSiccPXsCAwEAAQJBAM4uU9aJE0OfdE1p/X+K\n' + <add> 'LrCT3XMdFCJ24GgmHyOURtwDy18upQJecDVdcZp16fjtOPmaW95GoYRyifB3R4I5\n' + <add> 'RxECIQD7jRM9slCSVV8xp9kOJQNpHjhRQYVGBn+pyllS2sb+RQIhAPb7Y+BIccri\n' + <add> 'NWnuhwCW8hA7Fkj/kaBdAwyW7L3Tvui/AiEAiqLCovMecre4Yi6GcsQ1b/6mvSmm\n' + <add> 'IOS+AT6zIfXPTB0CIQCJKGR3ymN/Qw5crL1GQ41cHCQtF9ickOq/lBUW+j976wIh\n' + <add> 'AOaJnkQrmurlRdePX6LvN/LgGAQoxwovfjcOYNnZsIVY\n' + <add> '-----END RSA PRIVATE KEY-----'; <add> <add>function test(cert, key, cb) { <add> var server = tls.createServer({ <add> cert: cert, <add> key: key <add> }).listen(common.PORT, function() { <add> server.close(cb); <add> }); <add>} <add> <add>var completed = false; <add>test(cert, key, function() { <add> test(new Buffer(cert), new Buffer(key), function() { <add> completed = true; <add> }); <add>}); <add> <add>process.on('exit', function() { <add> assert(completed); <add>});
2
Javascript
Javascript
correct iteration count for objectsequence
80cf20b9cd85d0be956074a3df7a6ce9e22dcc41
<ide><path>dist/Immutable.js <ide> var ObjectSequence = function ObjectSequence(object) { <ide> for (var ii = 0; ii <= maxIndex; ii++) { <ide> var iteration = reverse ? maxIndex - ii : ii; <ide> if (fn(object[keys[iteration]], keys[iteration], object) === false) { <del> break; <add> return ii + 1; <ide> } <ide> } <ide> return ii; <ide><path>dist/Immutable.min.js <ide> * of patent rights can be found in the PATENTS file in the same directory. <ide> */ <ide> function t(){function t(t,e,n,r){var i;if(r){var u=r.prototype;i=De.create(u)}else i=t.prototype;return De.keys(e).forEach(function(t){i[t]=e[t]}),De.keys(n).forEach(function(e){t[e]=n[e]}),i.constructor=t,t.prototype=i,t}function e(t,e,n,r){return De.getPrototypeOf(e)[n].apply(t,r)}function n(t,n,r){e(t,n,"constructor",r)}function r(t){return t.value=!1,t}function i(t){t&&(t.value=!0)}function u(){}function s(t,e){e=e||0;for(var n=Math.max(0,t.length-e),r=Array(n),i=0;n>i;i++)r[i]=t[i+e];return r}function a(t){return Ue.value=t,Ue.done=!1,Ue}function o(){return Ue.value=void 0,Ue.done=!0,Ue}function h(t,e){if(!t)throw Error(e)}function c(t){return!!_(t)}function f(t){return t&&"function"==typeof t.next}function l(t){var e=_(t);return"function"==typeof e?e.call(t):void 0}function _(t){return t&&(t[Ke]||t[We])}function v(t){if(!t)return 0;if(t===!0)return 1;var e=typeof t;if("number"===e){if((0|t)===t)return t&Be;t=""+t,e="string"}return"string"===e?t.length>Ne?g(t):p(t):t.hashCode?v("function"==typeof t.hashCode?t.hashCode():t.hashCode):m(t)}function g(t){var e=Ge[t];return null==e&&(e=p(t),Fe===Te&&(Fe=0,Ge={}),Fe++,Ge[t]=e),e}function p(t){for(var e=0,n=0;t.length>n;n++)e=31*e+t.charCodeAt(n)&Be;return e}function m(t){var e=t[Ve];if(e)return e;if(!Je){if(e=t.propertyIsEnumerable&&t.propertyIsEnumerable[Ve])return e;if(e=y(t))return e}if(!Je||Object.isExtensible(t)){if(e=++Le&Be,Je)Object.defineProperty(t,Ve,{enumerable:!1,configurable:!1,writable:!1,value:e});else if(t.propertyIsEnumerable===ze)t.propertyIsEnumerable=function(){return Object.prototype.propertyIsEnumerable.apply(this,arguments)},t.propertyIsEnumerable[Ve]=e;else{if(!t.nodeType)throw Error("Unable to set a non-enumerable property on object.");t[Ve]=e}return e}throw Error("Non-extensible objects are not allowed as keys.")}function y(t){if(t&&t.nodeType>0)switch(t.nodeType){case 1:return t.uniqueID;case 9:return t.documentElement&&t.documentElement.uniqueID}}function d(){return Object.create(Xe)}function w(){return Object.create($e)}function S(t,e,n,r){var i=t.get?t.get(e[r],Ae):Ae; <del>return i===Ae?n:++r===e.length?i:S(i,e,n,r)}function b(t,e,n){return(0===t||null!=n&&-n>=t)&&(null==e||null!=n&&e>=n)}function I(t,e){return q(t,e,0)}function k(t,e){return q(t,e,e)}function q(t,e,n){return null==t?n:0>t?Math.max(0,e+t):e?Math.min(e,t):t}function M(t){return t}function D(t,e){return[e,t]}function O(){return!0}function x(){return this}function E(t,e){var n=t.__makeSequence();return n.reverse=function(){return t},n.length=t.length,n.__iterateUncached=function(n,r,i){var u=this,s=i?this.length:0;return t.__iterate(function(t,r){return n(t,e?r:i?--s:s++,u)},!r)},n}function C(t,e,n,r){var i=t.__makeSequence();return i.__iterateUncached=function(i,u){var s=this,a=0;return t.__iterate(function(t,u,o){return e.call(n,t,u,o)?(a++,i(t,r?u:a-1,s)):void 0},u),a},i}function A(t,e,n,r){var i={},u=[];return t.forEach(function(s,a){var o=e.call(n,s,a,t),h=v(o),c=r?[a,s]:s;i.hasOwnProperty(h)?u[i[h]][1].push(c):(i[h]=u.length,u.push([o,[c]]))}),He(u).fromEntrySeq().map(r?function(t){return He(t).fromEntrySeq()}:function(t){return He(t)})}function j(t,e,n){if(0>=e)return t;var r=t.__makeSequence();return r.__iterateUncached=function(r,i,u){var s=this;if(i)return this.cacheResult().__iterate(r,i,u);var a=0,o=!0,h=0;return t.__iterate(function(t,i){return o&&(o=a++<e)?void 0:(h++,r(t,n?i:h-1,s))}),h},r.length=t.length&&Math.max(0,t.length-e),r}function R(t,e,n,r){var i=t.__makeSequence();return i.__iterateUncached=function(i,u,s){var a=this;if(u)return this.cacheResult().__iterate(i,u,s);var o=!0,h=0;return t.__iterate(function(t,u,s){return o&&(o=e.call(n,t,u,s))?void 0:(h++,i(t,r?u:h-1,a))}),h},i}function U(t,e,n){var r=[t].concat(e),i=He(r);return n&&(i=i.toKeyedSeq()),i=i.flatten(),i.length=r.reduce(function(t,e){if(void 0!==t){var n=He(e).length;if(null!=n)return t+n}},0),i}function P(t,e){var n=t.__makeSequence();return n.__iterateUncached=function(n,r,i){var u=this,s=0,a=this.length;return t.__iterate(function(t){var o=!1;return He(t).__iterate(function(t,r){return s++,n(t,e?r:i?a-s:s-1,u)===!1?(o=!0,!1):void 0 <add>return i===Ae?n:++r===e.length?i:S(i,e,n,r)}function I(t,e,n){return(0===t||null!=n&&-n>=t)&&(null==e||null!=n&&e>=n)}function b(t,e){return q(t,e,0)}function k(t,e){return q(t,e,e)}function q(t,e,n){return null==t?n:0>t?Math.max(0,e+t):e?Math.min(e,t):t}function M(t){return t}function D(t,e){return[e,t]}function O(){return!0}function x(){return this}function E(t,e){var n=t.__makeSequence();return n.reverse=function(){return t},n.length=t.length,n.__iterateUncached=function(n,r,i){var u=this,s=i?this.length:0;return t.__iterate(function(t,r){return n(t,e?r:i?--s:s++,u)},!r)},n}function C(t,e,n,r){var i=t.__makeSequence();return i.__iterateUncached=function(i,u){var s=this,a=0;return t.__iterate(function(t,u,o){return e.call(n,t,u,o)?(a++,i(t,r?u:a-1,s)):void 0},u),a},i}function A(t,e,n,r){var i={},u=[];return t.forEach(function(s,a){var o=e.call(n,s,a,t),h=v(o),c=r?[a,s]:s;i.hasOwnProperty(h)?u[i[h]][1].push(c):(i[h]=u.length,u.push([o,[c]]))}),He(u).fromEntrySeq().map(r?function(t){return He(t).fromEntrySeq()}:function(t){return He(t)})}function j(t,e,n){if(0>=e)return t;var r=t.__makeSequence();return r.__iterateUncached=function(r,i,u){var s=this;if(i)return this.cacheResult().__iterate(r,i,u);var a=0,o=!0,h=0;return t.__iterate(function(t,i){return o&&(o=a++<e)?void 0:(h++,r(t,n?i:h-1,s))}),h},r.length=t.length&&Math.max(0,t.length-e),r}function R(t,e,n,r){var i=t.__makeSequence();return i.__iterateUncached=function(i,u,s){var a=this;if(u)return this.cacheResult().__iterate(i,u,s);var o=!0,h=0;return t.__iterate(function(t,u,s){return o&&(o=e.call(n,t,u,s))?void 0:(h++,i(t,r?u:h-1,a))}),h},i}function U(t,e,n){var r=[t].concat(e),i=He(r);return n&&(i=i.toKeyedSeq()),i=i.flatten(),i.length=r.reduce(function(t,e){if(void 0!==t){var n=He(e).length;if(null!=n)return t+n}},0),i}function P(t,e){var n=t.__makeSequence();return n.__iterateUncached=function(n,r,i){var u=this,s=0,a=this.length;return t.__iterate(function(t){var o=!1;return He(t).__iterate(function(t,r){return s++,n(t,e?r:i?a-s:s-1,u)===!1?(o=!0,!1):void 0 <ide> },r),!o},r),s},n}function W(t){return function(){return!t.apply(this,arguments)}}function K(t){return"string"==typeof t?JSON.stringify(t):t}function z(t,e){return t>e?1:e>t?-1:0}function J(t,e){return 0>e?(null==t.length&&t.cacheResult(),t.length+e):e}function B(t){h(1/0!==t,"Cannot perform this action with an infinite sequence.")}function L(t,e){var n=new sn;return n.next=function(){var n=t.next();return n.done?n:(n.value=e(n.value),n)},n}function V(t,e,n){return n instanceof He?N(t,e,n):n}function N(t,e,n){return new on(t._rootData,t._keyPath.concat(e),t._onChange,n)}function T(t,e,n){var r=t._rootData.updateIn(t._keyPath,n?hn.empty():void 0,e),i=t._keyPath||[];return t._onChange&&t._onChange.call(void 0,r,t._rootData,n?i.concat(n):i),new on(r,t._keyPath,t._onChange)}function F(t,e){return t instanceof on&&(t=t.deref()),e instanceof on&&(e=e.deref()),t===e?0!==t||0!==e||1/t===1/e:t!==t?e!==e:t instanceof He?t.equals(e):!1}function G(t,e){return a(0===t||1===t?e[t]:[e[0],e[1]])}function H(t,e){return{node:t,index:0,__prev:e}}function Q(t,e,n,r){var i=Object.create(fn);return i.length=t,i._root=e,i.__ownerID=n,i.__hash=r,i.__altered=!1,i}function X(t,e,n){var i=r(je),u=r(Re),s=Y(t._root,t.__ownerID,0,v(e),e,n,i,u);if(!u.value)return t;var a=t.length+(i.value?n===Ae?-1:1:0);return t.__ownerID?(t.length=a,t._root=s,t.__hash=void 0,t.__altered=!0,t):s?Q(a,s):hn.empty()}function Y(t,e,n,r,u,s,a,o){return t?t.update(e,n,r,u,s,a,o):s===Ae?t:(i(o),i(a),new yn(e,r,[u,s]))}function Z(t){return t.constructor===yn||t.constructor===pn}function $(t,e,n,r,i){if(t.hash===r)return new pn(e,r,[t.entry,i]);var u,s=(0===n?t.hash:t.hash>>>n)&Ce,a=(0===n?r:r>>>n)&Ce,o=s===a?[$(t,e,n+xe,r,i)]:(u=new yn(e,r,i),a>s?[t,u]:[u,t]);return new ln(e,1<<s|1<<a,o)}function te(t,e,n,r){for(var i=0,u=0,s=Array(n),a=0,o=1,h=e.length;h>a;a++,o<<=1){var c=e[a];null!=c&&a!==r&&(i|=o,s[u++]=c)}return new ln(t,i,s)}function ee(t,e,n,r,i){for(var u=0,s=Array(Ee),a=0;0!==n;a++,n>>>=1)s[a]=1&n?e[u++]:null;return s[r]=i,new vn(t,u+1,s)}function ne(t,e,n){for(var r=[],i=0;n.length>i;i++){var u=n[i]; <ide> u instanceof He||(u=He(u),u instanceof Ye&&(u=u.fromEntrySeq())),u&&r.push(u)}return ie(t,e,r)}function re(t){return function(e,n){return e&&e.mergeDeepWith?e.mergeDeepWith(t,n):t?t(e,n):n}}function ie(t,e,n){return 0===n.length?t:t.withMutations(function(t){for(var r=e?function(n,r){var i=t.get(r,Ae);t.set(r,i===Ae?n:e(i,n))}:function(e,n){t.set(n,e)},i=0;n.length>i;i++)n[i].forEach(r)})}function ue(t,e,n,r,i){var u=e.length;if(i===u)return r(t);h(t.set,"updateIn with invalid keyPath");var s=i===u-1?n:hn.empty(),a=e[i],o=t.get(a,s),c=ue(o,e,n,r,i+1);return c===o?t:t.set(a,c)}function se(t){return t-=t>>1&1431655765,t=(858993459&t)+(t>>2&858993459),t=t+(t>>4)&252645135,t+=t>>8,t+=t>>16,127&t}function ae(t,e,n,r){var i=r?t:s(t);return i[e]=n,i}function oe(t,e,n,r){var i=t.length+1;if(r&&e+1===i)return t[e]=n,t;for(var u=Array(i),s=0,a=0;i>a;a++)a===e?(u[a]=n,s=-1):u[a]=t[a+s];return u}function he(t,e,n){var r=t.length-1;if(n&&e===r)return t.pop(),t;for(var i=Array(r),u=0,s=0;r>s;s++)s===e&&(u=1),i[s]=t[s+u];return i}function ce(t,e,n,r,i,u){var s,a=t&&t.array;if(0===e){var o=0>n?-n:0,h=r-n;for(h>Ee&&(h=Ee),s=o;h>s;s++)if(i(a&&a[u?o+h-1-s:s])===!1)return!1}else{var c=1<<e,f=e-xe;for(s=0;Ce>=s;s++){var l=u?Ce-s:s,_=n+(l<<e);if(r>_&&_+c>0){var v=a&&a[l];if(!ce(v,f,_,r,i,u))return!1}}}return!0}function fe(t,e,n,r,i){return{array:t,level:e,offset:n,max:r,rawMax:r-n>>e,index:0,__prev:i}}function le(t,e,n,r,i,u,s){var a=Object.create(Mn);return a.length=e-t,a._origin=t,a._size=e,a._level=n,a._root=r,a._tail=i,a.__ownerID=u,a.__hash=s,a.__altered=!1,a}function _e(t,e,n){if(e=J(t,e),e>=t.length||0>e)return n===Ae?t:t.withMutations(function(t){0>e?me(t,e).set(0,n):me(t,0,e+1).set(e,n)});e+=t._origin;var i=t._tail,u=t._root,s=r(Re);return e>=de(t._size)?i=ve(i,t.__ownerID,0,e,n,s):u=ve(u,t.__ownerID,t._level,e,n,s),s.value?t.__ownerID?(t._root=u,t._tail=i,t.__hash=void 0,t.__altered=!0,t):le(t._origin,t._size,t._level,u,i):t}function ve(t,e,n,r,u,s){var a,o=u===Ae,h=r>>>n&Ce,c=t&&t.array.length>h;if(o&&!c)return t;if(n>0){var f=t&&t.array[h],l=ve(f,e,n-xe,r,u,s); <del>return l===f?t:(a=ge(t,e),a.array[h]=l,a)}return!o&&c&&t.array[h]===u?t:(i(s),a=ge(t,e),o&&h===a.array.length-1?a.array.pop():a.array[h]=o?void 0:u,a)}function ge(t,e){return e&&t&&e===t.ownerID?t:new Dn(t?t.array.slice():[],e)}function pe(t,e){if(e>=de(t._size))return t._tail;if(1<<t._level+xe>e){for(var n=t._root,r=t._level;n&&r>0;)n=n.array[e>>>r&Ce],r-=xe;return n}}function me(t,e,n){var r=t.__ownerID||new u,i=t._origin,s=t._size,a=i+e,o=null==n?s:0>n?s+n:i+n;if(a===i&&o===s)return t;if(a>=o)return t.clear();for(var h=t._level,c=t._root,f=0;0>a+f;)c=new Dn(c&&c.array.length?[null,c]:[],r),h+=xe,f+=1<<h;f&&(a+=f,i+=f,o+=f,s+=f);for(var l=de(s),_=de(o);_>=1<<h+xe;)c=new Dn(c&&c.array.length?[c]:[],r),h+=xe;var v=t._tail,g=l>_?pe(t,o-1):_>l?new Dn([],r):v;if(v&&_>l&&s>a&&v.array.length){c=ge(c,r);for(var p=c,m=h;m>xe;m-=xe){var y=l>>>m&Ce;p=p.array[y]=ge(p.array[y],r)}p.array[l>>>xe&Ce]=v}if(s>o&&(g=g&&g.removeAfter(r,0,o)),a>=_)a-=_,o-=_,h=xe,c=null,g=g&&g.removeBefore(r,0,a);else if(a>i||l>_){var d,w;f=0;do d=a>>>h&Ce,w=_-1>>>h&Ce,d===w&&(d&&(f+=(1<<h)*d),h-=xe,c=c&&c.array[d]);while(c&&d===w);c&&a>i&&(c=c&&c.removeBefore(r,h,a-f)),c&&l>_&&(c=c&&c.removeAfter(r,h,_-f)),f&&(a-=f,o-=f)}return t.__ownerID?(t.length=o-a,t._origin=a,t._size=o,t._level=h,t._root=c,t._tail=g,t.__hash=void 0,t.__altered=!0,t):le(a,o,h,c,g)}function ye(t,e,n){for(var r=[],i=0;n.length>i;i++){var u=n[i];u&&r.push(He(u))}var s=Math.max.apply(null,r.map(function(t){return t.length||0}));return s>t.length&&(t=t.setLength(s)),ie(t,e,r)}function de(t){return Ee>t?0:t-1>>>xe<<xe}function we(t,e){var n=Object.create(jn);return n.length=t?t.length:0,n._map=t,n.__ownerID=e,n}function Se(t,e,n,r){var i=Object.create(Un.prototype);return i.length=t?t.length:0,i._map=t,i._vector=e,i.__ownerID=n,i.__hash=r,i}function be(t,e,n){var r=t._map,i=t._vector,u=r.get(e),s=void 0!==u,a=n===Ae;if(!s&&a||s&&n===i.get(u)[1])return t;s||(u=i.length);var o=a?r.remove(e):s?r:r.set(e,u),h=a?i.remove(u):i.set(u,[e,n]);return t.__ownerID?(t.length=o.length,t._map=o,t._vector=h,t.__hash=void 0,t):Se(o,h) <del>}function Ie(t,e,n){var r=Object.create(Object.getPrototypeOf(t));return r._map=e,r.__ownerID=n,r}function ke(t,e){return e?qe(e,t,"",{"":t}):Me(t)}function qe(t,e,n,r){return e&&(Array.isArray(e)||e.constructor===Object)?t.call(r,n,He(e).map(function(n,r){return qe(t,n,r,e)})):e}function Me(t){if(t){if(Array.isArray(t))return He(t).map(Me).toVector();if(t.constructor===Object)return He(t).map(Me).toMap()}return t}var De=Object,Oe={};Oe.createClass=t,Oe.superCall=e,Oe.defaultSuperCall=n;var xe=5,Ee=1<<xe,Ce=Ee-1,Ae={},je={value:!1},Re={value:!1},Ue={value:void 0,done:!1},Pe="delete",We="@@iterator",Ke="undefined"!=typeof Symbol?Symbol.iterator:We,ze=Object.prototype.propertyIsEnumerable,Je=function(){try{return Object.defineProperty({},"x",{}),!0}catch(t){return!1}}(),Be=2147483647,Le=0,Ve="__immutablehash__";"undefined"!=typeof Symbol&&(Ve=Symbol(Ve));var Ne=16,Te=255,Fe=0,Ge={},He=function(t){return Qe.from(1===arguments.length?t:Array.prototype.slice.call(arguments))},Qe=He;Oe.createClass(He,{toString:function(){return this.__toString("Seq {","}")},__toString:function(t,e){return 0===this.length?t+e:t+" "+this.map(this.__toStringMapper).join(", ")+" "+e},__toStringMapper:function(t,e){return e+": "+K(t)},toJS:function(){return this.map(function(t){return t instanceof Qe?t.toJS():t}).__toJS()},toArray:function(){B(this.length);var t=Array(this.length||0);return this.valueSeq().forEach(function(e,n){t[n]=e}),t},toObject:function(){B(this.length);var t={};return this.forEach(function(e,n){t[n]=e}),t},toVector:function(){return B(this.length),kn.from(this)},toMap:function(){return B(this.length),hn.from(this)},toOrderedMap:function(){return B(this.length),Un.from(this)},toSet:function(){return B(this.length),Cn.from(this)},toKeyedSeq:function(){return this},hashCode:function(){return this.__hash||(this.__hash=1/0===this.length?0:this.reduce(function(t,e,n){return t+(v(e)^(e===n?0:v(n)))&Be},0))},equals:function(t){if(this===t)return!0;if(!(t instanceof Qe))return!1;if(null!=this.length&&null!=t.length){if(this.length!==t.length)return!1; <add>return l===f?t:(a=ge(t,e),a.array[h]=l,a)}return!o&&c&&t.array[h]===u?t:(i(s),a=ge(t,e),o&&h===a.array.length-1?a.array.pop():a.array[h]=o?void 0:u,a)}function ge(t,e){return e&&t&&e===t.ownerID?t:new Dn(t?t.array.slice():[],e)}function pe(t,e){if(e>=de(t._size))return t._tail;if(1<<t._level+xe>e){for(var n=t._root,r=t._level;n&&r>0;)n=n.array[e>>>r&Ce],r-=xe;return n}}function me(t,e,n){var r=t.__ownerID||new u,i=t._origin,s=t._size,a=i+e,o=null==n?s:0>n?s+n:i+n;if(a===i&&o===s)return t;if(a>=o)return t.clear();for(var h=t._level,c=t._root,f=0;0>a+f;)c=new Dn(c&&c.array.length?[null,c]:[],r),h+=xe,f+=1<<h;f&&(a+=f,i+=f,o+=f,s+=f);for(var l=de(s),_=de(o);_>=1<<h+xe;)c=new Dn(c&&c.array.length?[c]:[],r),h+=xe;var v=t._tail,g=l>_?pe(t,o-1):_>l?new Dn([],r):v;if(v&&_>l&&s>a&&v.array.length){c=ge(c,r);for(var p=c,m=h;m>xe;m-=xe){var y=l>>>m&Ce;p=p.array[y]=ge(p.array[y],r)}p.array[l>>>xe&Ce]=v}if(s>o&&(g=g&&g.removeAfter(r,0,o)),a>=_)a-=_,o-=_,h=xe,c=null,g=g&&g.removeBefore(r,0,a);else if(a>i||l>_){var d,w;f=0;do d=a>>>h&Ce,w=_-1>>>h&Ce,d===w&&(d&&(f+=(1<<h)*d),h-=xe,c=c&&c.array[d]);while(c&&d===w);c&&a>i&&(c=c&&c.removeBefore(r,h,a-f)),c&&l>_&&(c=c&&c.removeAfter(r,h,_-f)),f&&(a-=f,o-=f)}return t.__ownerID?(t.length=o-a,t._origin=a,t._size=o,t._level=h,t._root=c,t._tail=g,t.__hash=void 0,t.__altered=!0,t):le(a,o,h,c,g)}function ye(t,e,n){for(var r=[],i=0;n.length>i;i++){var u=n[i];u&&r.push(He(u))}var s=Math.max.apply(null,r.map(function(t){return t.length||0}));return s>t.length&&(t=t.setLength(s)),ie(t,e,r)}function de(t){return Ee>t?0:t-1>>>xe<<xe}function we(t,e){var n=Object.create(jn);return n.length=t?t.length:0,n._map=t,n.__ownerID=e,n}function Se(t,e,n,r){var i=Object.create(Un.prototype);return i.length=t?t.length:0,i._map=t,i._vector=e,i.__ownerID=n,i.__hash=r,i}function Ie(t,e,n){var r=t._map,i=t._vector,u=r.get(e),s=void 0!==u,a=n===Ae;if(!s&&a||s&&n===i.get(u)[1])return t;s||(u=i.length);var o=a?r.remove(e):s?r:r.set(e,u),h=a?i.remove(u):i.set(u,[e,n]);return t.__ownerID?(t.length=o.length,t._map=o,t._vector=h,t.__hash=void 0,t):Se(o,h) <add>}function be(t,e,n){var r=Object.create(Object.getPrototypeOf(t));return r._map=e,r.__ownerID=n,r}function ke(t,e){return e?qe(e,t,"",{"":t}):Me(t)}function qe(t,e,n,r){return e&&(Array.isArray(e)||e.constructor===Object)?t.call(r,n,He(e).map(function(n,r){return qe(t,n,r,e)})):e}function Me(t){if(t){if(Array.isArray(t))return He(t).map(Me).toVector();if(t.constructor===Object)return He(t).map(Me).toMap()}return t}var De=Object,Oe={};Oe.createClass=t,Oe.superCall=e,Oe.defaultSuperCall=n;var xe=5,Ee=1<<xe,Ce=Ee-1,Ae={},je={value:!1},Re={value:!1},Ue={value:void 0,done:!1},Pe="delete",We="@@iterator",Ke="undefined"!=typeof Symbol?Symbol.iterator:We,ze=Object.prototype.propertyIsEnumerable,Je=function(){try{return Object.defineProperty({},"x",{}),!0}catch(t){return!1}}(),Be=2147483647,Le=0,Ve="__immutablehash__";"undefined"!=typeof Symbol&&(Ve=Symbol(Ve));var Ne=16,Te=255,Fe=0,Ge={},He=function(t){return Qe.from(1===arguments.length?t:Array.prototype.slice.call(arguments))},Qe=He;Oe.createClass(He,{toString:function(){return this.__toString("Seq {","}")},__toString:function(t,e){return 0===this.length?t+e:t+" "+this.map(this.__toStringMapper).join(", ")+" "+e},__toStringMapper:function(t,e){return e+": "+K(t)},toJS:function(){return this.map(function(t){return t instanceof Qe?t.toJS():t}).__toJS()},toArray:function(){B(this.length);var t=Array(this.length||0);return this.valueSeq().forEach(function(e,n){t[n]=e}),t},toObject:function(){B(this.length);var t={};return this.forEach(function(e,n){t[n]=e}),t},toVector:function(){return B(this.length),kn.from(this)},toMap:function(){return B(this.length),hn.from(this)},toOrderedMap:function(){return B(this.length),Un.from(this)},toSet:function(){return B(this.length),Cn.from(this)},toKeyedSeq:function(){return this},hashCode:function(){return this.__hash||(this.__hash=1/0===this.length?0:this.reduce(function(t,e,n){return t+(v(e)^(e===n?0:v(n)))&Be},0))},equals:function(t){if(this===t)return!0;if(!(t instanceof Qe))return!1;if(null!=this.length&&null!=t.length){if(this.length!==t.length)return!1; <ide> if(0===this.length&&0===t.length)return!0}return null!=this.__hash&&null!=t.__hash&&this.__hash!==t.__hash?!1:this.__deepEquals(t)},__deepEquals:function(t){var e=this.cacheResult().entrySeq().toArray(),n=0;return t.every(function(t,r){var i=e[n++];return F(r,i[0])&&F(t,i[1])})},join:function(t){t=void 0!==t?""+t:",";var e="",n=!0;return this.forEach(function(r){n?n=!1:e+=t,e+=null!=r?r:""}),e},count:function(t,e){return t?this.filter(t,e).count():(null==this.length&&(this.length=this.forEach(O)),this.length)},countBy:function(t,e){var n=this,r={},i=[];return this.forEach(function(u,s){var a=t.call(e,u,s,n),o=v(a);r.hasOwnProperty(o)?i[r[o]][1]++:(r[o]=i.length,i.push([a,1]))}),Qe(i).fromEntrySeq()},concat:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];return U(this,t,!0)},flatten:function(){return P(this,!0)},flatMap:function(t,e){return this.map(t,e).flatten()},reverse:function(){return E(this,!0)},keySeq:function(){return this.flip().valueSeq()},valueSeq:function(){var t=this,e=w(t);return e.length=t.length,e.__iterateUncached=function(e,n,r){var i,u=this,s=0;if(r){var a=this.length-1;i=function(t){return e(t,a-s++,u)!==!1}}else i=function(t){return e(t,s++,u)!==!1};return t.__iterate(i,n),s},e},entrySeq:function(){var t=this;if(t._cache)return Qe(t._cache);var e=t.toKeyedSeq().map(D).valueSeq();return e.fromEntries=function(){return t},e},forEach:function(t,e){return this.__iterate(e?t.bind(e):t)},reduce:function(t,e,n){var r,i;return 2>arguments.length?i=!0:r=e,this.forEach(function(e,u,s){i?(i=!1,r=e):r=t.call(n,r,e,u,s)}),r},reduceRight:function(){var t=this.toKeyedSeq().reverse();return t.reduce.apply(t,arguments)},every:function(t,e){var n=!0;return this.forEach(function(r,i,u){return t.call(e,r,i,u)?void 0:(n=!1,!1)}),n},some:function(t,e){return!this.every(W(t),e)},first:function(){return this.find(O)},last:function(){return this.findLast(O)},rest:function(){return this.slice(1)},butLast:function(){return this.slice(0,-1)},has:function(t){return this.get(t,Ae)!==Ae},get:function(t,e){return this.find(function(e,n){return F(n,t) <del>},null,e)},getIn:function(t,e){return t&&0!==t.length?S(this,t,e,0):this},contains:function(t){return this.find(function(e){return F(e,t)},null,Ae)!==Ae},find:function(t,e,n){var r=n;return this.forEach(function(n,i,u){return t.call(e,n,i,u)?(r=n,!1):void 0}),r},findKey:function(t,e){var n;return this.forEach(function(r,i,u){return t.call(e,r,i,u)?(n=i,!1):void 0}),n},findLast:function(t,e,n){return this.toKeyedSeq().reverse().find(t,e,n)},findLastKey:function(t,e){return this.toKeyedSeq().reverse().findKey(t,e)},flip:function(){var t=this.toKeyedSeq(),e=t.__makeSequence();return e.length=t.length,e.flip=function(){return t},e.__iterateUncached=function(e,n){var r=this;return t.__iterate(function(t,n){return e(n,t,r)!==!1},n)},e},map:function(t,e){var n=this,r=n.__makeSequence();return r.length=n.length,r.__iterateUncached=function(r,i){var u=this;return n.__iterate(function(n,i,s){return r(t.call(e,n,i,s),i,u)!==!1},i)},r},mapKeys:function(t,e){var n=this;return this.flip().map(function(r,i){return t.call(e,r,i,n)}).flip()},mapEntries:function(t,e){var n=this;return this.entrySeq().map(function(r,i){return t.call(e,r,i,n)}).fromEntrySeq()},filter:function(t,e){return C(this,t,e,!0)},slice:function(t,e){if(b(t,e,this.length))return this;var n=I(t,this.length),r=k(e,this.length);if(n!==n||r!==r)return this.cacheResult().slice(t,e);var i=0===n?this:this.skip(n);return null==r||r===this.length?i:i.take(r-n)},take:function(t){var e=this;if(t>e.length)return e;0>t&&(t=0);var n=e.__makeSequence();return n.__iterateUncached=function(n,r,i){var u=this;if(0===t)return 0;if(r)return this.cacheResult().__iterate(n,r,i);var s=0;return e.__iterate(function(e,r){return++s&&n(e,r,u)!==!1&&t>s}),s},n.length=this.length&&Math.min(this.length,t),n},takeLast:function(t){return this.reverse().take(t).reverse()},takeWhile:function(t,e){var n=this,r=n.__makeSequence();return r.__iterateUncached=function(r,i,u){var s=this;if(i)return this.cacheResult().__iterate(r,i,u);var a=0;return n.__iterate(function(n,i,u){return t.call(e,n,i,u)&&++a&&r(n,i,s) <add>},null,e)},getIn:function(t,e){return t&&0!==t.length?S(this,t,e,0):this},contains:function(t){return this.find(function(e){return F(e,t)},null,Ae)!==Ae},find:function(t,e,n){var r=n;return this.forEach(function(n,i,u){return t.call(e,n,i,u)?(r=n,!1):void 0}),r},findKey:function(t,e){var n;return this.forEach(function(r,i,u){return t.call(e,r,i,u)?(n=i,!1):void 0}),n},findLast:function(t,e,n){return this.toKeyedSeq().reverse().find(t,e,n)},findLastKey:function(t,e){return this.toKeyedSeq().reverse().findKey(t,e)},flip:function(){var t=this.toKeyedSeq(),e=t.__makeSequence();return e.length=t.length,e.flip=function(){return t},e.__iterateUncached=function(e,n){var r=this;return t.__iterate(function(t,n){return e(n,t,r)!==!1},n)},e},map:function(t,e){var n=this,r=n.__makeSequence();return r.length=n.length,r.__iterateUncached=function(r,i){var u=this;return n.__iterate(function(n,i,s){return r(t.call(e,n,i,s),i,u)!==!1},i)},r},mapKeys:function(t,e){var n=this;return this.flip().map(function(r,i){return t.call(e,r,i,n)}).flip()},mapEntries:function(t,e){var n=this;return this.entrySeq().map(function(r,i){return t.call(e,r,i,n)}).fromEntrySeq()},filter:function(t,e){return C(this,t,e,!0)},slice:function(t,e){if(I(t,e,this.length))return this;var n=b(t,this.length),r=k(e,this.length);if(n!==n||r!==r)return this.cacheResult().slice(t,e);var i=0===n?this:this.skip(n);return null==r||r===this.length?i:i.take(r-n)},take:function(t){var e=this;if(t>e.length)return e;0>t&&(t=0);var n=e.__makeSequence();return n.__iterateUncached=function(n,r,i){var u=this;if(0===t)return 0;if(r)return this.cacheResult().__iterate(n,r,i);var s=0;return e.__iterate(function(e,r){return++s&&n(e,r,u)!==!1&&t>s}),s},n.length=this.length&&Math.min(this.length,t),n},takeLast:function(t){return this.reverse().take(t).reverse()},takeWhile:function(t,e){var n=this,r=n.__makeSequence();return r.__iterateUncached=function(r,i,u){var s=this;if(i)return this.cacheResult().__iterate(r,i,u);var a=0;return n.__iterate(function(n,i,u){return t.call(e,n,i,u)&&++a&&r(n,i,s) <ide> }),a},r},takeUntil:function(t,e){return this.takeWhile(W(t),e)},skip:function(t){return j(this,t,!0)},skipLast:function(t){return this.reverse().skip(t).reverse()},skipWhile:function(t,e){return R(this,t,e,!0)},skipUntil:function(t,e){return this.skipWhile(W(t),e)},groupBy:function(t,e){return A(this,t,e,!0)},sort:function(t){return this.sortBy(M,t)},sortBy:function(t,e){e=e||z;var n=this;return Qe(this.entrySeq().entrySeq().toArray().sort(function(r,i){return e(t(r[1][1],r[1][0],n),t(i[1][1],i[1][0],n))||r[0]-i[0]})).fromEntrySeq().valueSeq().fromEntrySeq()},cacheResult:function(){return!this._cache&&this.__iterateUncached&&(B(this.length),this._cache=this.entrySeq().toArray(),null==this.length&&(this.length=this._cache.length)),this},__iterate:function(t,e){var n=this._cache;if(n){for(var r=n.length-1,i=0;r>=i;i++){var u=n[e?r-i:i];if(t(u[1],u[0],this)===!1)break}return i}return this.__iterateUncached(t,e)},__makeSequence:function(){return d()}},{from:function(t){if(t instanceof Qe)return t;if(!Array.isArray(t)){if(f(t))return new en(t);if(c(t))return new nn(t);if(t&&t.constructor===Object)return new rn(t);t=[t]}return new un(t)}});var Xe=He.prototype;Xe.toJSON=Xe.toJS,Xe.__toJS=Xe.toObject,Xe.inspect=Xe.toSource=function(){return""+this};var Ye=function(){Oe.defaultSuperCall(this,Ze.prototype,arguments)},Ze=Ye;Oe.createClass(Ye,{toString:function(){return this.__toString("Seq [","]")},toKeyedSeq:function(){return new tn(this)},valueSeq:function(){return this},fromEntrySeq:function(){var t=this,e=d();return e.length=t.length,e.entrySeq=function(){return t},e.__iterateUncached=function(e,n){var r=this;return t.__iterate(function(t){return t&&e(t[1],t[0],r)},n)},e},concat:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];return U(this,t,!1)},reverse:function(){return E(this,!1)},filter:function(t,e){return C(this,t,e,!1)},get:function(t,e){return t=J(this,t),this.find(function(e,n){return n===t},null,e)},first:function(){return this.get(0)},last:function(){return this.get(this.length?this.length-1:0) <del>},indexOf:function(t){return this.findIndex(function(e){return F(e,t)})},lastIndexOf:function(t){return this.toKeyedSeq().reverse().indexOf(t)},findIndex:function(t,e){var n=this.findKey(t,e);return null==n?-1:n},findLastIndex:function(t,e){return this.toKeyedSeq().reverse().findIndex(t,e)},splice:function(t,e){var n=arguments.length;if(e=Math.max(0|e,0),0===n||2===n&&!e)return this;t=I(t,this.length);var r=this.slice(0,t);return 1===n?r:r.concat(s(arguments,2),this.slice(t+e))},flatten:function(){return P(this,!1)},skip:function(t){return j(this,t,!1)},skipWhile:function(t,e){return R(this,t,e,!1)},groupBy:function(t,e){return A(this,t,e,!1)},sortBy:function(t,e){e=e||z;var n=this;return He(this.entrySeq().toArray().sort(function(r,i){return e(t(r[1],r[0],n),t(i[1],i[0],n))||r[0]-i[0]})).fromEntrySeq().valueSeq()},__iterate:function(t,e,n){var r=this._cache;if(r){n^=e;for(var i=r.length-1,u=0;i>=u;u++){var s=r[e?i-u:u],a=s[0];if(t(s[1],n?i-a:a,this)===!1)break}return u}return n&&!this.length?this.cacheResult().__iterate(t,e,n):this.__iterateUncached(t,e,n)},__makeSequence:function(){return w(this)}},{},He);var $e=Ye.prototype;$e.__toJS=$e.toArray,$e.__toStringMapper=K,$e.chain=$e.flatMap;var tn=function(t){this._seq=t,this.length=t.length};Oe.createClass(tn,{get:function(t,e){return this._seq.get(t,e)},has:function(t){return this._seq.has(t)},__iterate:function(t,e){return this._seq.__iterate(t,e,e)}},{},He);var en=function(t){this._iterator=t,this._iteratorCache=[]};Oe.createClass(en,{__iterateUncached:function(t,e,n){if(e)return this.cacheResult().__iterate(t,e,n);for(var r=this._iterator,i=this._iteratorCache,u=0;i.length>u;)if(t(i[u],u++,this)===!1)return u;for(var s;!(s=r.next()).done;){var a=s.value;if(i[u]=a,t(a,u++,this)===!1)break}return u}},{},Ye);var nn=function(t){this._iterable=t,this.length=t.length||t.size};Oe.createClass(nn,{__iterateUncached:function(t,e,n){if(e)return this.cacheResult().__iterate(t,e,n);var r=this._iterable,i=l(r),u=0;if(f(i))for(var s;!(s=i.next()).done&&t(s.value,u++,r)!==!1;);return u <del>}},{},Ye);var rn=function(t){var e=Object.keys(t);this._object=t,this._keys=e,this.length=e.length};Oe.createClass(rn,{toObject:function(){return this._object},get:function(t,e){return void 0===e||this.has(t)?this._object[t]:e},has:function(t){return this._object.hasOwnProperty(t)},__iterate:function(t,e){for(var n=this._object,r=this._keys,i=r.length-1,u=0;i>=u;u++){var s=e?i-u:u;if(t(n[r[s]],r[s],n)===!1)break}return u}},{},He);var un=function(t){this._array=t,this.length=t.length};Oe.createClass(un,{toArray:function(){return this._array},get:function(t,e){return this.has(t)?this._array[J(this,t)]:e},has:function(t){return t=J(this,t),t>=0&&this.length>t},__iterate:function(t,e,n){var r,i,u=this._array,s=u.length-1,a=e^n;for(r=0;s>=r;r++)if(i=s-r,t(u[e?i:r],n?i:r,u)===!1)return a?e?i:r:u.length;return u.length}},{},Ye);var sn=function(){};Oe.createClass(sn,{toString:function(){return"[Iterator]"}},{});var an=sn.prototype;an[Ke]=x,an.inspect=an.toSource=function(){return""+this};var on=function(t,e,n,r){r=r?r:t.getIn(e),this.length=r instanceof He?r.length:null,this._rootData=t,this._keyPath=e,this._onChange=n};Oe.createClass(on,{deref:function(t){return this._rootData.getIn(this._keyPath,t)},get:function(t,e){if(Array.isArray(t)&&0===t.length)return this;var n=this._rootData.getIn(this._keyPath.concat(t),Ae);return n===Ae?e:V(this,t,n)},set:function(t,e){return T(this,function(n){return n.set(t,e)},t)},remove:function(t){return T(this,function(e){return e.remove(t)},t)},clear:function(){return T(this,function(t){return t.clear()})},update:function(t,e,n){return 1===arguments.length?T(this,t):T(this,function(r){return r.update(t,e,n)},t)},withMutations:function(t){return T(this,function(e){return(e||hn.empty()).withMutations(t)})},cursor:function(t){return Array.isArray(t)&&0===t.length?this:N(this,t)},__iterate:function(t,e,n){var r=this,i=r.deref();return i&&i.__iterate?i.__iterate(function(e,n,i){return t(V(r,n,e),n,i)},e,n):0}},{},He),on.prototype[Pe]=on.prototype.remove,on.prototype.getIn=on.prototype.get;var hn=function(t){var e=cn.empty(); <del>return t?t.constructor===cn?t:e.merge(t):e},cn=hn;Oe.createClass(hn,{toString:function(){return this.__toString("Map {","}")},get:function(t,e){return this._root?this._root.get(0,v(t),t,e):e},set:function(t,e){return X(this,t,e)},remove:function(t){return X(this,t,Ae)},update:function(t,e,n){return 1===arguments.length?this.updateIn([],null,t):this.updateIn([t],e,n)},updateIn:function(t,e,n){var r;return n||(r=[e,n],n=r[0],e=r[1],r),ue(this,t,e,n,0)},clear:function(){return 0===this.length?this:this.__ownerID?(this.length=0,this._root=null,this.__hash=void 0,this.__altered=!0,this):cn.empty()},merge:function(){return ne(this,null,arguments)},mergeWith:function(t){for(var e=[],n=1;arguments.length>n;n++)e[n-1]=arguments[n];return ne(this,t,e)},mergeDeep:function(){return ne(this,re(null),arguments)},mergeDeepWith:function(t){for(var e=[],n=1;arguments.length>n;n++)e[n-1]=arguments[n];return ne(this,re(t),e)},cursor:function(t,e){return e||"function"!=typeof t?0===arguments.length?t=[]:Array.isArray(t)||(t=[t]):(e=t,t=[]),new on(this,t,e)},withMutations:function(t){var e=this.asMutable();return t(e),e.wasAltered()?e.__ensureOwner(this.__ownerID):this},asMutable:function(){return this.__ownerID?this:this.__ensureOwner(new u)},asImmutable:function(){return this.__ensureOwner()},wasAltered:function(){return this.__altered},keys:function(){return new wn(this,0)},values:function(){return new wn(this,1)},entries:function(){return new wn(this,2)},__iterator:function(t){return new wn(this,2,t)},__iterate:function(t,e){var n=this,r=0;return this._root&&this._root.iterate(function(e){return r++,t(e[1],e[0],n)},e),r},__deepEquals:function(t){var e=this;return t.every(function(t,n){return F(e.get(n,Ae),t)})},__ensureOwner:function(t){return t===this.__ownerID?this:t?Q(this.length,this._root,t,this.__hash):(this.__ownerID=t,this.__altered=!1,this)}},{empty:function(){return Sn||(Sn=Q(0))}},He);var fn=hn.prototype;fn[Pe]=fn.remove,fn[Ke]=function(){return this.entries()},hn.from=hn;var ln=function(t,e,n){this.ownerID=t,this.bitmap=e,this.nodes=n <del>},_n=ln;Oe.createClass(ln,{get:function(t,e,n,r){var i=1<<((0===t?e:e>>>t)&Ce),u=this.bitmap;return 0===(u&i)?r:this.nodes[se(u&i-1)].get(t+xe,e,n,r)},update:function(t,e,n,r,i,u,s){var a=(0===e?n:n>>>e)&Ce,o=1<<a,h=this.bitmap,c=0!==(h&o);if(!c&&i===Ae)return this;var f=se(h&o-1),l=this.nodes,_=c?l[f]:null,v=Y(_,t,e+xe,n,r,i,u,s);if(v===_)return this;if(!c&&v&&l.length>=bn)return ee(t,l,h,a,v);if(c&&!v&&2===l.length&&Z(l[1^f]))return l[1^f];if(c&&v&&1===l.length&&Z(v))return v;var g=t&&t===this.ownerID,p=c?v?h:h^o:h|o,m=c?v?ae(l,f,v,g):he(l,f,g):oe(l,f,v,g);return g?(this.bitmap=p,this.nodes=m,this):new _n(t,p,m)},iterate:function(t,e){for(var n=this.nodes,r=0,i=n.length-1;i>=r;r++)if(n[e?i-r:r].iterate(t,e)===!1)return!1}},{});var vn=function(t,e,n){this.ownerID=t,this.count=e,this.nodes=n},gn=vn;Oe.createClass(vn,{get:function(t,e,n,r){var i=(0===t?e:e>>>t)&Ce,u=this.nodes[i];return u?u.get(t+xe,e,n,r):r},update:function(t,e,n,r,i,u,s){var a=(0===e?n:n>>>e)&Ce,o=i===Ae,h=this.nodes,c=h[a];if(o&&!c)return this;var f=Y(c,t,e+xe,n,r,i,u,s);if(f===c)return this;var l=this.count;if(c){if(!f&&(l--,In>l))return te(t,h,l,a)}else l++;var _=t&&t===this.ownerID,v=ae(h,a,f,_);return _?(this.count=l,this.nodes=v,this):new gn(t,l,v)},iterate:function(t,e){for(var n=this.nodes,r=0,i=n.length-1;i>=r;r++){var u=n[e?i-r:r];if(u&&u.iterate(t,e)===!1)return!1}}},{});var pn=function(t,e,n){this.ownerID=t,this.hash=e,this.entries=n},mn=pn;Oe.createClass(pn,{get:function(t,e,n,r){for(var i=this.entries,u=0,s=i.length;s>u;u++)if(F(n,i[u][0]))return i[u][1];return r},update:function(t,e,n,r,u,a,o){var h=u===Ae;if(n!==this.hash)return h?this:(i(o),i(a),$(this,t,e,n,[r,u]));for(var c=this.entries,f=0,l=c.length;l>f&&!F(r,c[f][0]);f++);var _=l>f;if(h&&!_)return this;if(i(o),(h||!_)&&i(a),h&&2===l)return new yn(t,this.hash,c[1^f]);var v=t&&t===this.ownerID,g=v?c:s(c);return _?h?f===l-1?g.pop():g[f]=g.pop():g[f]=[r,u]:g.push([r,u]),v?(this.entries=g,this):new mn(t,this.hash,g)},iterate:function(t,e){for(var n=this.entries,r=0,i=n.length-1;i>=r;r++)if(t(n[e?i-r:r])===!1)return!1 <del>}},{});var yn=function(t,e,n){this.ownerID=t,this.hash=e,this.entry=n},dn=yn;Oe.createClass(yn,{get:function(t,e,n,r){return F(n,this.entry[0])?this.entry[1]:r},update:function(t,e,n,r,u,s,a){var o=u===Ae,h=F(r,this.entry[0]);return(h?u===this.entry[1]:o)?this:(i(a),o?(i(s),null):h?t&&t===this.ownerID?(this.entry[1]=u,this):new dn(t,n,[r,u]):(i(s),$(this,t,e,n,[r,u])))},iterate:function(t){return t(this.entry)}},{});var wn=function(t,e,n){this._type=e,this._reverse=n,this._stack=t._root&&H(t._root)};Oe.createClass(wn,{next:function(){for(var t=this._type,e=this._stack;e;){var n,r=e.node,i=e.index++;if(r.entry){if(0===i)return G(t,r.entry)}else if(r.entries){if(n=r.entries.length-1,n>=i)return G(t,r.entries[this._reverse?n-i:i])}else if(n=r.nodes.length-1,n>=i){var u=r.nodes[this._reverse?n-i:i];if(u){if(u.entry)return G(t,u.entry);e=this._stack=H(u,e)}continue}e=this._stack=this._stack.__prev}return o()}},{},sn);var Sn,bn=Ee/2,In=Ee/4,kn=function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];return qn.from(t)},qn=kn;Oe.createClass(kn,{toString:function(){return this.__toString("Vector [","]")},has:function(t){return t=J(this,t),t>=0&&this.length>t},get:function(t,e){if(t=J(this,t),0>t||t>=this.length)return e;t+=this._origin;var n=pe(this,t);return n&&n.array[t&Ce]},set:function(t,e){return _e(this,t,e)},remove:function(t){return _e(this,t,Ae)},clear:function(){return 0===this.length?this:this.__ownerID?(this.length=this._origin=this._size=0,this._level=xe,this._root=this._tail=null,this.__hash=void 0,this.__altered=!0,this):qn.empty()},push:function(){var t=arguments,e=this.length;return this.withMutations(function(n){me(n,0,e+t.length);for(var r=0;t.length>r;r++)n.set(e+r,t[r])})},pop:function(){return me(this,0,-1)},unshift:function(){var t=arguments;return this.withMutations(function(e){me(e,-t.length);for(var n=0;t.length>n;n++)e.set(n,t[n])})},shift:function(){return me(this,1)},merge:function(){return ye(this,null,arguments)},mergeWith:function(t){for(var e=[],n=1;arguments.length>n;n++)e[n-1]=arguments[n]; <add>},indexOf:function(t){return this.findIndex(function(e){return F(e,t)})},lastIndexOf:function(t){return this.toKeyedSeq().reverse().indexOf(t)},findIndex:function(t,e){var n=this.findKey(t,e);return null==n?-1:n},findLastIndex:function(t,e){return this.toKeyedSeq().reverse().findIndex(t,e)},splice:function(t,e){var n=arguments.length;if(e=Math.max(0|e,0),0===n||2===n&&!e)return this;t=b(t,this.length);var r=this.slice(0,t);return 1===n?r:r.concat(s(arguments,2),this.slice(t+e))},flatten:function(){return P(this,!1)},skip:function(t){return j(this,t,!1)},skipWhile:function(t,e){return R(this,t,e,!1)},groupBy:function(t,e){return A(this,t,e,!1)},sortBy:function(t,e){e=e||z;var n=this;return He(this.entrySeq().toArray().sort(function(r,i){return e(t(r[1],r[0],n),t(i[1],i[0],n))||r[0]-i[0]})).fromEntrySeq().valueSeq()},__iterate:function(t,e,n){var r=this._cache;if(r){n^=e;for(var i=r.length-1,u=0;i>=u;u++){var s=r[e?i-u:u],a=s[0];if(t(s[1],n?i-a:a,this)===!1)break}return u}return n&&!this.length?this.cacheResult().__iterate(t,e,n):this.__iterateUncached(t,e,n)},__makeSequence:function(){return w(this)}},{},He);var $e=Ye.prototype;$e.__toJS=$e.toArray,$e.__toStringMapper=K,$e.chain=$e.flatMap;var tn=function(t){this._seq=t,this.length=t.length};Oe.createClass(tn,{get:function(t,e){return this._seq.get(t,e)},has:function(t){return this._seq.has(t)},__iterate:function(t,e){return this._seq.__iterate(t,e,e)}},{},He);var en=function(t){this._iterator=t,this._iteratorCache=[]};Oe.createClass(en,{__iterateUncached:function(t,e,n){if(e)return this.cacheResult().__iterate(t,e,n);for(var r=this._iterator,i=this._iteratorCache,u=0;i.length>u;)if(t(i[u],u++,this)===!1)return u;for(var s;!(s=r.next()).done;){var a=s.value;if(i[u]=a,t(a,u++,this)===!1)break}return u}},{},Ye);var nn=function(t){this._iterable=t,this.length=t.length||t.size};Oe.createClass(nn,{__iterateUncached:function(t,e,n){if(e)return this.cacheResult().__iterate(t,e,n);var r=this._iterable,i=l(r),u=0;if(f(i))for(var s;!(s=i.next()).done&&t(s.value,u++,r)!==!1;);return u <add>}},{},Ye);var rn=function(t){var e=Object.keys(t);this._object=t,this._keys=e,this.length=e.length};Oe.createClass(rn,{toObject:function(){return this._object},get:function(t,e){return void 0===e||this.has(t)?this._object[t]:e},has:function(t){return this._object.hasOwnProperty(t)},__iterate:function(t,e){for(var n=this._object,r=this._keys,i=r.length-1,u=0;i>=u;u++){var s=e?i-u:u;if(t(n[r[s]],r[s],n)===!1)return u+1}return u}},{},He);var un=function(t){this._array=t,this.length=t.length};Oe.createClass(un,{toArray:function(){return this._array},get:function(t,e){return this.has(t)?this._array[J(this,t)]:e},has:function(t){return t=J(this,t),t>=0&&this.length>t},__iterate:function(t,e,n){var r,i,u=this._array,s=u.length-1,a=e^n;for(r=0;s>=r;r++)if(i=s-r,t(u[e?i:r],n?i:r,u)===!1)return a?e?i:r:u.length;return u.length}},{},Ye);var sn=function(){};Oe.createClass(sn,{toString:function(){return"[Iterator]"}},{});var an=sn.prototype;an[Ke]=x,an.inspect=an.toSource=function(){return""+this};var on=function(t,e,n,r){r=r?r:t.getIn(e),this.length=r instanceof He?r.length:null,this._rootData=t,this._keyPath=e,this._onChange=n};Oe.createClass(on,{deref:function(t){return this._rootData.getIn(this._keyPath,t)},get:function(t,e){if(Array.isArray(t)&&0===t.length)return this;var n=this._rootData.getIn(this._keyPath.concat(t),Ae);return n===Ae?e:V(this,t,n)},set:function(t,e){return T(this,function(n){return n.set(t,e)},t)},remove:function(t){return T(this,function(e){return e.remove(t)},t)},clear:function(){return T(this,function(t){return t.clear()})},update:function(t,e,n){return 1===arguments.length?T(this,t):T(this,function(r){return r.update(t,e,n)},t)},withMutations:function(t){return T(this,function(e){return(e||hn.empty()).withMutations(t)})},cursor:function(t){return Array.isArray(t)&&0===t.length?this:N(this,t)},__iterate:function(t,e,n){var r=this,i=r.deref();return i&&i.__iterate?i.__iterate(function(e,n,i){return t(V(r,n,e),n,i)},e,n):0}},{},He),on.prototype[Pe]=on.prototype.remove,on.prototype.getIn=on.prototype.get; <add>var hn=function(t){var e=cn.empty();return t?t.constructor===cn?t:e.merge(t):e},cn=hn;Oe.createClass(hn,{toString:function(){return this.__toString("Map {","}")},get:function(t,e){return this._root?this._root.get(0,v(t),t,e):e},set:function(t,e){return X(this,t,e)},remove:function(t){return X(this,t,Ae)},update:function(t,e,n){return 1===arguments.length?this.updateIn([],null,t):this.updateIn([t],e,n)},updateIn:function(t,e,n){var r;return n||(r=[e,n],n=r[0],e=r[1],r),ue(this,t,e,n,0)},clear:function(){return 0===this.length?this:this.__ownerID?(this.length=0,this._root=null,this.__hash=void 0,this.__altered=!0,this):cn.empty()},merge:function(){return ne(this,null,arguments)},mergeWith:function(t){for(var e=[],n=1;arguments.length>n;n++)e[n-1]=arguments[n];return ne(this,t,e)},mergeDeep:function(){return ne(this,re(null),arguments)},mergeDeepWith:function(t){for(var e=[],n=1;arguments.length>n;n++)e[n-1]=arguments[n];return ne(this,re(t),e)},cursor:function(t,e){return e||"function"!=typeof t?0===arguments.length?t=[]:Array.isArray(t)||(t=[t]):(e=t,t=[]),new on(this,t,e)},withMutations:function(t){var e=this.asMutable();return t(e),e.wasAltered()?e.__ensureOwner(this.__ownerID):this},asMutable:function(){return this.__ownerID?this:this.__ensureOwner(new u)},asImmutable:function(){return this.__ensureOwner()},wasAltered:function(){return this.__altered},keys:function(){return new wn(this,0)},values:function(){return new wn(this,1)},entries:function(){return new wn(this,2)},__iterator:function(t){return new wn(this,2,t)},__iterate:function(t,e){var n=this,r=0;return this._root&&this._root.iterate(function(e){return r++,t(e[1],e[0],n)},e),r},__deepEquals:function(t){var e=this;return t.every(function(t,n){return F(e.get(n,Ae),t)})},__ensureOwner:function(t){return t===this.__ownerID?this:t?Q(this.length,this._root,t,this.__hash):(this.__ownerID=t,this.__altered=!1,this)}},{empty:function(){return Sn||(Sn=Q(0))}},He);var fn=hn.prototype;fn[Pe]=fn.remove,fn[Ke]=function(){return this.entries()},hn.from=hn;var ln=function(t,e,n){this.ownerID=t,this.bitmap=e,this.nodes=n <add>},_n=ln;Oe.createClass(ln,{get:function(t,e,n,r){var i=1<<((0===t?e:e>>>t)&Ce),u=this.bitmap;return 0===(u&i)?r:this.nodes[se(u&i-1)].get(t+xe,e,n,r)},update:function(t,e,n,r,i,u,s){var a=(0===e?n:n>>>e)&Ce,o=1<<a,h=this.bitmap,c=0!==(h&o);if(!c&&i===Ae)return this;var f=se(h&o-1),l=this.nodes,_=c?l[f]:null,v=Y(_,t,e+xe,n,r,i,u,s);if(v===_)return this;if(!c&&v&&l.length>=In)return ee(t,l,h,a,v);if(c&&!v&&2===l.length&&Z(l[1^f]))return l[1^f];if(c&&v&&1===l.length&&Z(v))return v;var g=t&&t===this.ownerID,p=c?v?h:h^o:h|o,m=c?v?ae(l,f,v,g):he(l,f,g):oe(l,f,v,g);return g?(this.bitmap=p,this.nodes=m,this):new _n(t,p,m)},iterate:function(t,e){for(var n=this.nodes,r=0,i=n.length-1;i>=r;r++)if(n[e?i-r:r].iterate(t,e)===!1)return!1}},{});var vn=function(t,e,n){this.ownerID=t,this.count=e,this.nodes=n},gn=vn;Oe.createClass(vn,{get:function(t,e,n,r){var i=(0===t?e:e>>>t)&Ce,u=this.nodes[i];return u?u.get(t+xe,e,n,r):r},update:function(t,e,n,r,i,u,s){var a=(0===e?n:n>>>e)&Ce,o=i===Ae,h=this.nodes,c=h[a];if(o&&!c)return this;var f=Y(c,t,e+xe,n,r,i,u,s);if(f===c)return this;var l=this.count;if(c){if(!f&&(l--,bn>l))return te(t,h,l,a)}else l++;var _=t&&t===this.ownerID,v=ae(h,a,f,_);return _?(this.count=l,this.nodes=v,this):new gn(t,l,v)},iterate:function(t,e){for(var n=this.nodes,r=0,i=n.length-1;i>=r;r++){var u=n[e?i-r:r];if(u&&u.iterate(t,e)===!1)return!1}}},{});var pn=function(t,e,n){this.ownerID=t,this.hash=e,this.entries=n},mn=pn;Oe.createClass(pn,{get:function(t,e,n,r){for(var i=this.entries,u=0,s=i.length;s>u;u++)if(F(n,i[u][0]))return i[u][1];return r},update:function(t,e,n,r,u,a,o){var h=u===Ae;if(n!==this.hash)return h?this:(i(o),i(a),$(this,t,e,n,[r,u]));for(var c=this.entries,f=0,l=c.length;l>f&&!F(r,c[f][0]);f++);var _=l>f;if(h&&!_)return this;if(i(o),(h||!_)&&i(a),h&&2===l)return new yn(t,this.hash,c[1^f]);var v=t&&t===this.ownerID,g=v?c:s(c);return _?h?f===l-1?g.pop():g[f]=g.pop():g[f]=[r,u]:g.push([r,u]),v?(this.entries=g,this):new mn(t,this.hash,g)},iterate:function(t,e){for(var n=this.entries,r=0,i=n.length-1;i>=r;r++)if(t(n[e?i-r:r])===!1)return!1 <add>}},{});var yn=function(t,e,n){this.ownerID=t,this.hash=e,this.entry=n},dn=yn;Oe.createClass(yn,{get:function(t,e,n,r){return F(n,this.entry[0])?this.entry[1]:r},update:function(t,e,n,r,u,s,a){var o=u===Ae,h=F(r,this.entry[0]);return(h?u===this.entry[1]:o)?this:(i(a),o?(i(s),null):h?t&&t===this.ownerID?(this.entry[1]=u,this):new dn(t,n,[r,u]):(i(s),$(this,t,e,n,[r,u])))},iterate:function(t){return t(this.entry)}},{});var wn=function(t,e,n){this._type=e,this._reverse=n,this._stack=t._root&&H(t._root)};Oe.createClass(wn,{next:function(){for(var t=this._type,e=this._stack;e;){var n,r=e.node,i=e.index++;if(r.entry){if(0===i)return G(t,r.entry)}else if(r.entries){if(n=r.entries.length-1,n>=i)return G(t,r.entries[this._reverse?n-i:i])}else if(n=r.nodes.length-1,n>=i){var u=r.nodes[this._reverse?n-i:i];if(u){if(u.entry)return G(t,u.entry);e=this._stack=H(u,e)}continue}e=this._stack=this._stack.__prev}return o()}},{},sn);var Sn,In=Ee/2,bn=Ee/4,kn=function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];return qn.from(t)},qn=kn;Oe.createClass(kn,{toString:function(){return this.__toString("Vector [","]")},has:function(t){return t=J(this,t),t>=0&&this.length>t},get:function(t,e){if(t=J(this,t),0>t||t>=this.length)return e;t+=this._origin;var n=pe(this,t);return n&&n.array[t&Ce]},set:function(t,e){return _e(this,t,e)},remove:function(t){return _e(this,t,Ae)},clear:function(){return 0===this.length?this:this.__ownerID?(this.length=this._origin=this._size=0,this._level=xe,this._root=this._tail=null,this.__hash=void 0,this.__altered=!0,this):qn.empty()},push:function(){var t=arguments,e=this.length;return this.withMutations(function(n){me(n,0,e+t.length);for(var r=0;t.length>r;r++)n.set(e+r,t[r])})},pop:function(){return me(this,0,-1)},unshift:function(){var t=arguments;return this.withMutations(function(e){me(e,-t.length);for(var n=0;t.length>n;n++)e.set(n,t[n])})},shift:function(){return me(this,1)},merge:function(){return ye(this,null,arguments)},mergeWith:function(t){for(var e=[],n=1;arguments.length>n;n++)e[n-1]=arguments[n]; <ide> return ye(this,t,e)},mergeDeep:function(){return ye(this,re(null),arguments)},mergeDeepWith:function(t){for(var e=[],n=1;arguments.length>n;n++)e[n-1]=arguments[n];return ye(this,re(t),e)},setLength:function(t){return me(this,0,t)},slice:function(t,e){var n=Oe.superCall(this,qn.prototype,"slice",[t,e]);if(n!==this){var r=this,i=r.length;n.toVector=function(){return me(r,0>t?Math.max(0,i+t):i?Math.min(i,t):t,null==e?i:0>e?Math.max(0,i+e):i?Math.min(i,e):e)}}return n},keys:function(){return new xn(this,0)},values:function(){return new xn(this,1)},entries:function(){return new xn(this,2)},__iterator:function(t,e){return new xn(this,2,t,e)},__iterate:function(t,e,n){var r=this,i=0,u=this.length,s=function(e){return t(e,n?u-++i:i++,r)},a=de(this._size);return e?ce(this._tail,0,a-this._origin,this._size-this._origin,s,e)&&ce(this._root,this._level,-this._origin,a-this._origin,s,e):ce(this._root,this._level,-this._origin,a-this._origin,s,e)&&ce(this._tail,0,a-this._origin,this._size-this._origin,s,e),i},__deepEquals:function(t){var e=this.entries(!0);return t.every(function(t,n){var r=e.next().value;return r&&r[0]===n&&F(r[1],t)})},__ensureOwner:function(t){return t===this.__ownerID?this:t?le(this._origin,this._size,this._level,this._root,this._tail,t,this.__hash):(this.__ownerID=t,this)}},{empty:function(){return En||(En=le(0,0,xe))},from:function(t){if(!t||0===t.length)return qn.empty();if(t.constructor===qn)return t;var e=Array.isArray(t);return t.length>0&&Ee>t.length?le(0,t.length,xe,null,new Dn(e?s(t):He(t).toArray())):(e||(t=He(t).valueSeq()),qn.empty().merge(t))}},Ye);var Mn=kn.prototype;Mn[Pe]=Mn.remove,Mn[Ke]=Mn.values,Mn.update=fn.update,Mn.updateIn=fn.updateIn,Mn.cursor=fn.cursor,Mn.withMutations=fn.withMutations,Mn.asMutable=fn.asMutable,Mn.asImmutable=fn.asImmutable,Mn.wasAltered=fn.wasAltered;var Dn=function(t,e){this.array=t,this.ownerID=e},On=Dn;Oe.createClass(Dn,{removeBefore:function(t,e,n){if(n===e?1<<e:0||0===this.array.length)return this;var r=n>>>e&Ce;if(r>=this.array.length)return new On([],t);var i,u=0===r; <ide> if(e>0){var s=this.array[r];if(i=s&&s.removeBefore(t,e-xe,n),i===s&&u)return this}if(u&&!i)return this;var a=ge(this,t);if(!u)for(var o=0;r>o;o++)a.array[o]=void 0;return i&&(a.array[r]=i),a},removeAfter:function(t,e,n){if(n===e?1<<e:0||0===this.array.length)return this;var r=n-1>>>e&Ce;if(r>=this.array.length)return this;var i,u=r===this.array.length-1;if(e>0){var s=this.array[r];if(i=s&&s.removeAfter(t,e-xe,n),i===s&&u)return this}if(u&&!i)return this;var a=ge(this,t);return u||a.array.pop(),i&&(a.array[r]=i),a}},{});var xn=function(t,e,n,r){this._type=e,this._reverse=!!n,this._reverseIndices=!!(r^n),this._maxIndex=t.length-1;var i=de(t._size),u=fe(t._root&&t._root.array,t._level,-t._origin,i-t._origin-1),s=fe(t._tail&&t._tail.array,0,i-t._origin,t._size-t._origin-1);this._stack=n?s:u,this._stack.__prev=n?u:s};Oe.createClass(xn,{next:function(){for(var t=this._stack;t;){var e=t.array,n=t.index++;if(this._reverse&&(n=Ce-n,n>t.rawMax&&(n=t.rawMax,t.index=Ee-n)),n>=0&&Ee>n&&t.rawMax>=n){var r=e&&e[n];if(0===t.level){var i,u=this._type;return 1!==u&&(i=t.offset+(n<<t.level),this._reverseIndices&&(i=this._maxIndex-i)),a(0===u?i:1===u?r:[i,r])}this._stack=t=fe(r&&r.array,t.level-xe,t.offset+(n<<t.level),t.max,t)}else t=this._stack=this._stack.__prev}return o()}},{},sn);var En,Cn=function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];return An.from(t)},An=Cn;Oe.createClass(Cn,{toString:function(){return this.__toString("Set {","}")},has:function(t){return this._map.has(t)},get:function(t,e){return this.has(t)?t:e},add:function(t){var e=this._map.set(t,null);return this.__ownerID?(this.length=e.length,this._map=e,this):e===this._map?this:we(e)},remove:function(t){var e=this._map.remove(t);return this.__ownerID?(this.length=e.length,this._map=e,this):e===this._map?this:0===e.length?An.empty():we(e)},clear:function(){return 0===this.length?this:this.__ownerID?(this.length=0,this._map.clear(),this):An.empty()},union:function(){var t=arguments;return 0===t.length?this:this.withMutations(function(e){for(var n=0;t.length>n;n++)He(t[n]).forEach(function(t){return e.add(t) <ide> })})},intersect:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];if(0===t.length)return this;t=t.map(function(t){return He(t)});var n=this;return this.withMutations(function(e){n.forEach(function(n){t.every(function(t){return t.contains(n)})||e.remove(n)})})},subtract:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];if(0===t.length)return this;t=t.map(function(t){return He(t)});var n=this;return this.withMutations(function(e){n.forEach(function(n){t.some(function(t){return t.contains(n)})&&e.remove(n)})})},isSubset:function(t){return t=He(t),this.every(function(e){return t.contains(e)})},isSuperset:function(t){var e=this;return t=He(t),t.every(function(t){return e.contains(t)})},wasAltered:function(){return this._map.wasAltered()},values:function(){return this._map.keys()},entries:function(){return L(this.values(),function(t){return[t,t]})},hashCode:function(){return this._map.hashCode()},__iterate:function(t,e){var n=this;return this._map.__iterate(function(e,r){return t(r,r,n)},e)},__deepEquals:function(t){return this.isSuperset(t)},__ensureOwner:function(t){if(t===this.__ownerID)return this;var e=this._map.__ensureOwner(t);return t?we(e,t):(this.__ownerID=t,this._map=e,this)}},{empty:function(){return Rn||(Rn=we(hn.empty()))},from:function(t){var e=An.empty();return t?t.constructor===An?t:e.union(t):e},fromKeys:function(t){return An.from(He(t).flip())}},He);var jn=Cn.prototype;jn[Pe]=jn.remove,jn[Ke]=jn.keys=jn.values,jn.contains=jn.has,jn.mergeDeep=jn.merge=jn.union,jn.mergeDeepWith=jn.mergeWith=function(){for(var t=[],e=1;arguments.length>e;e++)t[e-1]=arguments[e];return this.merge.apply(this,t)},jn.withMutations=fn.withMutations,jn.asMutable=fn.asMutable,jn.asImmutable=fn.asImmutable,jn.__toJS=$e.__toJS,jn.__toStringMapper=$e.__toStringMapper;var Rn,Un=function(t){var e=Pn.empty();return t?t.constructor===Pn?t:e.merge(t):e},Pn=Un;Oe.createClass(Un,{toString:function(){return this.__toString("OrderedMap {","}")},get:function(t,e){var n=this._map.get(t);return null!=n?this._vector.get(n)[1]:e <del>},clear:function(){return 0===this.length?this:this.__ownerID?(this.length=0,this._map.clear(),this._vector.clear(),this):Pn.empty()},set:function(t,e){return be(this,t,e)},remove:function(t){return be(this,t,Ae)},wasAltered:function(){return this._map.wasAltered()||this._vector.wasAltered()},keys:function(){return L(this.entries(),function(t){return t[0]})},values:function(){return L(this.entries(),function(t){return t[1]})},entries:function(){return this._vector.values(!0)},__iterate:function(t,e){return this._vector.fromEntrySeq().__iterate(t,e)},__deepEquals:function(t){var e=this.entries();return t.every(function(t,n){var r=e.next().value;return r&&F(r[0],n)&&F(r[1],t)})},__ensureOwner:function(t){if(t===this.__ownerID)return this;var e=this._map.__ensureOwner(t),n=this._vector.__ensureOwner(t);return t?Se(e,n,t,this.__hash):(this.__ownerID=t,this._map=e,this._vector=n,this)}},{empty:function(){return Wn||(Wn=Se(hn.empty(),kn.empty()))}},hn),Un.from=Un,Un.prototype[Pe]=Un.prototype.remove;var Wn,Kn=function(t,e){var n=function(t){return this instanceof n?void(this._map=hn(t)):new n(t)};t=He(t);var r=n.prototype=Object.create(Jn);r.constructor=n,r._name=e,r._defaultValues=t;var i=Object.keys(t);return n.prototype.length=i.length,Object.defineProperty&&t.forEach(function(t,e){Object.defineProperty(n.prototype,e,{get:function(){return this.get(e)},set:function(t){h(this.__ownerID,"Cannot set on an immutable record."),this.set(e,t)}})}),n},zn=Kn;Oe.createClass(Kn,{toString:function(){return this.__toString((this._name||"Record")+" {","}")},has:function(t){return this._defaultValues.has(t)},get:function(t,e){return void 0===e||this.has(t)?this._map.get(t,this._defaultValues.get(t)):e},clear:function(){if(this.__ownerID)return this._map.clear(),this;Object.getPrototypeOf(this).constructor;return zn._empty||(zn._empty=Ie(this,hn.empty()))},set:function(t,e){if(null==t||!this.has(t))return this;var n=this._map.set(t,e);return this.__ownerID||n===this._map?this:Ie(this,n)},remove:function(t){if(null==t||!this.has(t))return this; <del>var e=this._map.remove(t);return this.__ownerID||e===this._map?this:Ie(this,e)},keys:function(){return this._map.keys()},values:function(){return this._map.values()},entries:function(){return this._map.entries()},wasAltered:function(){return this._map.wasAltered()},__iterate:function(t,e){var n=this;return this._defaultValues.map(function(t,e){return n.get(e)}).__iterate(t,e)},__ensureOwner:function(t){if(t===this.__ownerID)return this;var e=this._map&&this._map.__ensureOwner(t);return t?Ie(this,e,t):(this.__ownerID=t,this._map=e,this)}},{},He);var Jn=Kn.prototype;Jn[Pe]=Jn.remove,Jn[Ke]=fn[Ke],Jn.merge=fn.merge,Jn.mergeWith=fn.mergeWith,Jn.mergeDeep=fn.mergeDeep,Jn.mergeDeepWith=fn.mergeDeepWith,Jn.update=fn.update,Jn.updateIn=fn.updateIn,Jn.cursor=fn.cursor,Jn.withMutations=fn.withMutations,Jn.asMutable=fn.asMutable,Jn.asImmutable=fn.asImmutable,Jn.__deepEquals=fn.__deepEquals;var Bn=function(t,e,n){return this instanceof Ln?(h(0!==n,"Cannot step a Range by 0"),t=t||0,null==e&&(e=1/0),t===e&&Nn?Nn:(n=null==n?1:Math.abs(n),t>e&&(n=-n),this._start=t,this._end=e,this._step=n,void(this.length=Math.max(0,Math.ceil((e-t)/n-1)+1)))):new Ln(t,e,n)},Ln=Bn;Oe.createClass(Bn,{toString:function(){return 0===this.length?"Range []":"Range [ "+this._start+"..."+this._end+(this._step>1?" by "+this._step:"")+" ]"},has:function(t){return t=J(this,t),t>=0&&(1/0===this.length||this.length>t)},get:function(t,e){return t=J(this,t),this.has(t)?this._start+t*this._step:e},contains:function(t){var e=(t-this._start)/this._step;return e>=0&&this.length>e&&e===Math.floor(e)},slice:function(t,e){return b(t,e,this.length)?this:(t=I(t,this.length),e=k(e,this.length),t>=e?Nn:new Ln(this.get(t,this._end),this.get(e,this._end),this._step))},indexOf:function(t){var e=t-this._start;if(e%this._step===0){var n=e/this._step;if(n>=0&&this.length>n)return n}return-1},lastIndexOf:function(t){return this.indexOf(t)},take:function(t){return this.slice(0,Math.max(0,t))},skip:function(t){return this.slice(Math.max(0,t))},__iterate:function(t,e,n){for(var r=this.length-1,i=this._step,u=e?this._start+r*i:this._start,s=0;r>=s;s++){if(t(u,n?r-s:s,this)===!1)return s+1; <add>},clear:function(){return 0===this.length?this:this.__ownerID?(this.length=0,this._map.clear(),this._vector.clear(),this):Pn.empty()},set:function(t,e){return Ie(this,t,e)},remove:function(t){return Ie(this,t,Ae)},wasAltered:function(){return this._map.wasAltered()||this._vector.wasAltered()},keys:function(){return L(this.entries(),function(t){return t[0]})},values:function(){return L(this.entries(),function(t){return t[1]})},entries:function(){return this._vector.values(!0)},__iterate:function(t,e){return this._vector.fromEntrySeq().__iterate(t,e)},__deepEquals:function(t){var e=this.entries();return t.every(function(t,n){var r=e.next().value;return r&&F(r[0],n)&&F(r[1],t)})},__ensureOwner:function(t){if(t===this.__ownerID)return this;var e=this._map.__ensureOwner(t),n=this._vector.__ensureOwner(t);return t?Se(e,n,t,this.__hash):(this.__ownerID=t,this._map=e,this._vector=n,this)}},{empty:function(){return Wn||(Wn=Se(hn.empty(),kn.empty()))}},hn),Un.from=Un,Un.prototype[Pe]=Un.prototype.remove;var Wn,Kn=function(t,e){var n=function(t){return this instanceof n?void(this._map=hn(t)):new n(t)};t=He(t);var r=n.prototype=Object.create(Jn);r.constructor=n,r._name=e,r._defaultValues=t;var i=Object.keys(t);return n.prototype.length=i.length,Object.defineProperty&&t.forEach(function(t,e){Object.defineProperty(n.prototype,e,{get:function(){return this.get(e)},set:function(t){h(this.__ownerID,"Cannot set on an immutable record."),this.set(e,t)}})}),n},zn=Kn;Oe.createClass(Kn,{toString:function(){return this.__toString((this._name||"Record")+" {","}")},has:function(t){return this._defaultValues.has(t)},get:function(t,e){return void 0===e||this.has(t)?this._map.get(t,this._defaultValues.get(t)):e},clear:function(){if(this.__ownerID)return this._map.clear(),this;Object.getPrototypeOf(this).constructor;return zn._empty||(zn._empty=be(this,hn.empty()))},set:function(t,e){if(null==t||!this.has(t))return this;var n=this._map.set(t,e);return this.__ownerID||n===this._map?this:be(this,n)},remove:function(t){if(null==t||!this.has(t))return this; <add>var e=this._map.remove(t);return this.__ownerID||e===this._map?this:be(this,e)},keys:function(){return this._map.keys()},values:function(){return this._map.values()},entries:function(){return this._map.entries()},wasAltered:function(){return this._map.wasAltered()},__iterate:function(t,e){var n=this;return this._defaultValues.map(function(t,e){return n.get(e)}).__iterate(t,e)},__ensureOwner:function(t){if(t===this.__ownerID)return this;var e=this._map&&this._map.__ensureOwner(t);return t?be(this,e,t):(this.__ownerID=t,this._map=e,this)}},{},He);var Jn=Kn.prototype;Jn[Pe]=Jn.remove,Jn[Ke]=fn[Ke],Jn.merge=fn.merge,Jn.mergeWith=fn.mergeWith,Jn.mergeDeep=fn.mergeDeep,Jn.mergeDeepWith=fn.mergeDeepWith,Jn.update=fn.update,Jn.updateIn=fn.updateIn,Jn.cursor=fn.cursor,Jn.withMutations=fn.withMutations,Jn.asMutable=fn.asMutable,Jn.asImmutable=fn.asImmutable,Jn.__deepEquals=fn.__deepEquals;var Bn=function(t,e,n){return this instanceof Ln?(h(0!==n,"Cannot step a Range by 0"),t=t||0,null==e&&(e=1/0),t===e&&Nn?Nn:(n=null==n?1:Math.abs(n),t>e&&(n=-n),this._start=t,this._end=e,this._step=n,void(this.length=Math.max(0,Math.ceil((e-t)/n-1)+1)))):new Ln(t,e,n)},Ln=Bn;Oe.createClass(Bn,{toString:function(){return 0===this.length?"Range []":"Range [ "+this._start+"..."+this._end+(this._step>1?" by "+this._step:"")+" ]"},has:function(t){return t=J(this,t),t>=0&&(1/0===this.length||this.length>t)},get:function(t,e){return t=J(this,t),this.has(t)?this._start+t*this._step:e},contains:function(t){var e=(t-this._start)/this._step;return e>=0&&this.length>e&&e===Math.floor(e)},slice:function(t,e){return I(t,e,this.length)?this:(t=b(t,this.length),e=k(e,this.length),t>=e?Nn:new Ln(this.get(t,this._end),this.get(e,this._end),this._step))},indexOf:function(t){var e=t-this._start;if(e%this._step===0){var n=e/this._step;if(n>=0&&this.length>n)return n}return-1},lastIndexOf:function(t){return this.indexOf(t)},take:function(t){return this.slice(0,Math.max(0,t))},skip:function(t){return this.slice(Math.max(0,t))},__iterate:function(t,e,n){for(var r=this.length-1,i=this._step,u=e?this._start+r*i:this._start,s=0;r>=s;s++){if(t(u,n?r-s:s,this)===!1)return s+1; <ide> u+=e?-i:i}return s},__deepEquals:function(t){return this._start===t._start&&this._end===t._end&&this._step===t._step}},{},Ye);var Vn=Bn.prototype;Vn.__toJS=Vn.toArray,Vn.first=Mn.first,Vn.last=Mn.last;var Nn=Bn(0,0),Tn=function(t,e){return 0===e&&Hn?Hn:this instanceof Fn?(this._value=t,void(this.length=null==e?1/0:Math.max(0,e))):new Fn(t,e)},Fn=Tn;Oe.createClass(Tn,{toString:function(){return 0===this.length?"Repeat []":"Repeat [ "+this._value+" "+this.length+" times ]"},get:function(t,e){return this.has(t)?this._value:e},contains:function(t){return F(this._value,t)},slice:function(t,e){var n=this.length;return t=0>t?Math.max(0,n+t):Math.min(n,t),e=null==e?n:e>0?Math.min(n,e):Math.max(0,n+e),e>t?new Fn(this._value,e-t):Hn},reverse:function(){return this},indexOf:function(t){return F(this._value,t)?0:-1},lastIndexOf:function(t){return F(this._value,t)?this.length:-1},__iterate:function(t,e,n){h(!n||1/0>this.length,"Cannot access end of infinite range.");for(var r=this.length-1,i=0;r>=i;i++)if(t(this._value,n?r-i:i,this)===!1)return i+1;return i},__deepEquals:function(t){return F(this._value,t._value)}},{},Ye);var Gn=Tn.prototype;Gn.last=Gn.first,Gn.has=Vn.has,Gn.take=Vn.take,Gn.skip=Vn.skip,Gn.__toJS=Vn.__toJS;var Hn=new Tn(void 0,0),Qn={Sequence:He,Map:hn,Vector:kn,Set:Cn,OrderedMap:Un,Record:Kn,Range:Bn,Repeat:Tn,is:F,fromJS:ke};return Qn}"object"==typeof exports?module.exports=t():"function"==typeof define&&define.amd?define(t):Immutable=t(); <ide>\ No newline at end of file <ide><path>src/Sequence.js <ide> class ObjectSequence extends Sequence { <ide> for (var ii = 0; ii <= maxIndex; ii++) { <ide> var iteration = reverse ? maxIndex - ii : ii; <ide> if (fn(object[keys[iteration]], keys[iteration], object) === false) { <del> break; <add> return ii + 1; <ide> } <ide> } <ide> return ii;
3
PHP
PHP
fix requesthandler ajax handling
29205f14a21b4c4b5c6784d23c8612abf7b37ba0
<ide><path>src/Controller/Component/RequestHandlerComponent.php <ide> public function beforeRedirect(Event $event, $url, Response $response) <ide> return; <ide> } <ide> if (is_array($url)) { <del> $url = Router::url($url + ['base' => false]); <add> $url = Router::url($url + ['_base' => false]); <ide> } <ide> $controller = $event->subject(); <ide> $response->body($controller->requestAction($url, [
1
Python
Python
fix a test failure for python 3.7
10cb25f6dd600f3aa636b3b8db7b7fd102c2eccf
<ide><path>numpy/typing/tests/data/pass/array_constructors.py <add>import sys <ide> from typing import List, Any <ide> import numpy as np <ide> <ide> def func(i: int, j: int, **kwargs: Any) -> SubClass: <ide> B_stack = np.array([[1], [1]]).view(SubClass) <ide> C = [1] <ide> <del>np.ndarray(Index()) <del>np.ndarray([Index()]) <add>if sys.version_info >= (3, 8): <add> np.ndarray(Index()) <add> np.ndarray([Index()]) <ide> <ide> np.array(1, dtype=float) <ide> np.array(1, copy=False)
1
Java
Java
update javadoc for multipartfile.transferto
78f3a3cb11536b5305555c70c867c9daf7c355ad
<ide><path>spring-web/src/main/java/org/springframework/web/multipart/MultipartFile.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2015 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public interface MultipartFile { <ide> * <p>If the file has been moved in the filesystem, this operation cannot <ide> * be invoked again. Therefore, call this method just once to be able to <ide> * work with any storage mechanism. <add> * <p><strong>Note:</strong> when using Servlet 3.0 multipart support you <add> * need to configure the location relative to which files will be copied <add> * as explained in {@link javax.servlet.http.Part#write}. <ide> * @param dest the destination file <ide> * @throws IOException in case of reading or writing errors <ide> * @throws IllegalStateException if the file has already been moved
1
Python
Python
allow tags on aws batch job submission
bd74eb0ca0bb5f81cd98e2c151257a404d4a55a5
<ide><path>airflow/providers/amazon/aws/hooks/batch_client.py <ide> def submit_job( <ide> arrayProperties: Dict, <ide> parameters: Dict, <ide> containerOverrides: Dict, <add> tags: Dict, <ide> ) -> Dict: <ide> """ <ide> Submit a batch job <ide> def submit_job( <ide> :param containerOverrides: the same parameter that boto3 will receive <ide> :type containerOverrides: Dict <ide> <add> :param tags: the same parameter that boto3 will receive <add> :type tags: Dict <add> <ide> :return: an API response <ide> :rtype: Dict <ide> """ <ide><path>airflow/providers/amazon/aws/operators/batch.py <ide> class AwsBatchOperator(BaseOperator): <ide> Override the region_name in connection (if provided) <ide> :type region_name: str <ide> <add> :param tags: collection of tags to apply to the AWS Batch job submission <add> if None, no tags are submitted <add> :type tags: dict <add> <ide> .. note:: <ide> Any custom waiters must return a waiter for these calls: <ide> .. code-block:: python <ide> def __init__( <ide> status_retries: Optional[int] = None, <ide> aws_conn_id: Optional[str] = None, <ide> region_name: Optional[str] = None, <add> tags: Optional[dict] = None, <ide> **kwargs, <ide> ): # pylint: disable=too-many-arguments <ide> <ide> def __init__( <ide> self.array_properties = array_properties or {} <ide> self.parameters = parameters or {} <ide> self.waiters = waiters <add> self.tags = tags or {} <ide> self.hook = AwsBatchClientHook( <ide> max_retries=max_retries, <ide> status_retries=status_retries, <ide> def submit_job(self, context: Dict): # pylint: disable=unused-argument <ide> arrayProperties=self.array_properties, <ide> parameters=self.parameters, <ide> containerOverrides=self.overrides, <add> tags=self.tags, <ide> ) <ide> self.job_id = response["jobId"] <ide> <ide><path>tests/providers/amazon/aws/operators/test_batch.py <ide> def setUp(self, get_client_type_mock): <ide> array_properties=None, <ide> aws_conn_id='airflow_test', <ide> region_name="eu-west-1", <add> tags={}, <ide> ) <ide> self.client_mock = self.get_client_type_mock.return_value <ide> self.assertEqual(self.batch.hook.client, self.client_mock) # setup client property <ide> def test_init(self): <ide> self.assertEqual(self.batch.hook.region_name, "eu-west-1") <ide> self.assertEqual(self.batch.hook.aws_conn_id, "airflow_test") <ide> self.assertEqual(self.batch.hook.client, self.client_mock) <add> self.assertEqual(self.batch.tags, {}) <ide> <ide> self.get_client_type_mock.assert_called_once_with("batch", region_name="eu-west-1") <ide>
3
PHP
PHP
make extracttasktest more robust
a4a55a0b91c641436b41c2fb152e170e71f81e30
<ide><path>Cake/Test/TestCase/Console/Command/Task/ExtractTaskTest.php <ide> public function testExecute() { <ide> $this->assertRegExp($pattern, $result); <ide> <ide> // extract.ctp <del> $pattern = '/\#: (\\\\|\/)extract\.ctp:15;6\n'; <add> $pattern = '/\#: (\\\\|\/)extract\.ctp:\d+;\d+\n'; <ide> $pattern .= 'msgid "You have %d new message."\nmsgid_plural "You have %d new messages."/'; <ide> $this->assertRegExp($pattern, $result); <ide> <ide> $pattern = '/msgid "You have %d new message."\nmsgstr ""/'; <ide> $this->assertNotRegExp($pattern, $result, 'No duplicate msgid'); <ide> <del> $pattern = '/\#: (\\\\|\/)extract\.ctp:7\n'; <add> $pattern = '/\#: (\\\\|\/)extract\.ctp:\d+\n'; <ide> $pattern .= 'msgid "You deleted %d message."\nmsgid_plural "You deleted %d messages."/'; <ide> $this->assertRegExp($pattern, $result); <ide> <del> $pattern = '/\#: (\\\\|\/)extract\.ctp:14\n'; <del> $pattern .= '\#: (\\\\|\/)home\.ctp:126\n'; <add> $pattern = '/\#: (\\\\|\/)extract\.ctp:\d+\n'; <add> $pattern .= '\#: (\\\\|\/)home\.ctp:\d+\n'; <ide> $pattern .= 'msgid "Editing this Page"\nmsgstr ""/'; <ide> $this->assertRegExp($pattern, $result); <ide> <del> $pattern = '/\#: (\\\\|\/)extract\.ctp:22\nmsgid "'; <add> $pattern = '/\#: (\\\\|\/)extract\.ctp:\d+\nmsgid "'; <ide> $pattern .= 'Hot features!'; <ide> $pattern .= '\\\n - No Configuration: Set-up the database and let the magic begin'; <ide> $pattern .= '\\\n - Extremely Simple: Just look at the name...It\'s Cake'; <ide> public function testExtractCategory() { <ide> <ide> $result = file_get_contents($this->path . DS . 'default.pot'); <ide> <del> $pattern = '/\#: .*extract\.ctp:31\n/'; <del> $this->assertNotRegExp($pattern, $result); <add> $this->assertNotContains('You have a new message (category: LC_TIME).', $result); <ide> } <ide> <ide> /** <ide> public function testExtractWithExclude() { <ide> $this->assertTrue(file_exists($this->path . DS . 'default.pot')); <ide> $result = file_get_contents($this->path . DS . 'default.pot'); <ide> <del> $pattern = '/\#: .*extract\.ctp:6\n/'; <add> $pattern = '/\#: .*extract\.ctp:\d+\n/'; <ide> $this->assertNotRegExp($pattern, $result); <ide> <del> $pattern = '/\#: .*default\.ctp:26\n/'; <add> $pattern = '/\#: .*default\.ctp:\d+\n/'; <ide> $this->assertNotRegExp($pattern, $result); <ide> } <ide> <ide> public function testExtractPlugin() { <ide> $this->Task->execute(); <ide> $result = file_get_contents($this->path . DS . 'default.pot'); <ide> $this->assertNotRegExp('#Pages#', $result); <del> $this->assertContains('translate.ctp:1', $result); <add> $this->assertRegExp('/translate\.ctp:\d+/', $result); <ide> $this->assertContains('This is a translatable string', $result); <ide> $this->assertContains('I can haz plugin model validation message', $result); <ide> }
1
Java
Java
remove deleted parameter from javadoc
72ddd692228de55e4a7abb274c615be436e9dc15
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModule.java <ide> import android.content.ComponentCallbacks2; <ide> import android.content.res.Configuration; <ide> import android.view.View; <add>import androidx.annotation.NonNull; <ide> import androidx.annotation.Nullable; <ide> import androidx.collection.ArrayMap; <ide> import com.facebook.common.logging.FLog; <ide> public UIImplementation getUIImplementation() { <ide> } <ide> <ide> @Override <del> public String getName() { <add> public @NonNull String getName() { <ide> return NAME; <ide> } <ide> <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewManager.java <ide> * <ide> * @param viewToUpdate <ide> * @param props <del> * @param stateWrapper <ide> */ <ide> public void updateProperties(@NonNull T viewToUpdate, ReactStylesDiffMap props) { <ide> final ViewManagerDelegate<T> delegate;
2
Ruby
Ruby
add comments with urls for email previews
cbd4bc84afa354e9b4c50d53a0d6deb7141eb15d
<ide><path>railties/lib/rails/generators/test_unit/mailer/templates/preview.rb <ide> <% module_namespacing do -%> <add># Preview all emails at http://localhost:3000/rails/mailers/<%= file_path %> <ide> class <%= class_name %>Preview < ActionMailer::Preview <ide> <% actions.each do |action| -%> <ide> <add> # Preview this email at http://localhost:3000/rails/mailers/<%= file_path %>/<%= action %> <ide> def <%= action %> <ide> <%= class_name %>.<%= action %> <ide> end <ide><path>railties/test/generators/mailer_generator_test.rb <ide> def test_invokes_default_test_framework <ide> assert_match(/test "foo"/, test) <ide> assert_match(/test "bar"/, test) <ide> end <del> assert_file "test/mailers/previews/notifier_preview.rb" do |mailer| <del> assert_match(/class NotifierPreview < ActionMailer::Preview/, mailer) <del> assert_instance_method :foo, mailer do |foo| <add> assert_file "test/mailers/previews/notifier_preview.rb" do |preview| <add> assert_match(/\# Preview all emails at http:\/\/localhost\:3000\/rails\/mailers\/notifier/, preview) <add> assert_match(/class NotifierPreview < ActionMailer::Preview/, preview) <add> assert_match(/\# Preview this email at http:\/\/localhost\:3000\/rails\/mailers\/notifier\/foo/, preview) <add> assert_instance_method :foo, preview do |foo| <ide> assert_match(/Notifier.foo/, foo) <ide> end <del> assert_instance_method :bar, mailer do |bar| <add> assert_match(/\# Preview this email at http:\/\/localhost\:3000\/rails\/mailers\/notifier\/bar/, preview) <add> assert_instance_method :bar, preview do |bar| <ide> assert_match(/Notifier.bar/, bar) <ide> end <ide> end <ide> def test_mailer_with_namedspaced_mailer <ide> assert_match(/class Farm::Animal < ActionMailer::Base/, mailer) <ide> assert_match(/en\.farm\.animal\.moos\.subject/, mailer) <ide> end <del> assert_file "test/mailers/previews/farm/animal_preview.rb" do |mailer| <del> assert_match(/class Farm::AnimalPreview < ActionMailer::Preview/, mailer) <add> assert_file "test/mailers/previews/farm/animal_preview.rb" do |preview| <add> assert_match(/\# Preview all emails at http:\/\/localhost\:3000\/rails\/mailers\/farm\/animal/, preview) <add> assert_match(/class Farm::AnimalPreview < ActionMailer::Preview/, preview) <add> assert_match(/\# Preview this email at http:\/\/localhost\:3000\/rails\/mailers\/farm\/animal\/moos/, preview) <ide> end <ide> assert_file "app/views/farm/animal/moos.text.erb" <ide> assert_file "app/views/farm/animal/moos.html.erb"
2
Ruby
Ruby
fix failing tests in new callbacks
64ae5b56fff7c51fd436aaf81b8f30488cce3a2d
<ide><path>activesupport/lib/active_support/new_callbacks.rb <ide> def #{method_name}(&blk) <ide> <ide> def _normalize_legacy_filter(kind, filter) <ide> if !filter.respond_to?(kind) && filter.respond_to?(:filter) <del> filter.class_eval( <add> filter.metaclass.class_eval( <ide> "def #{kind}(context, &block) filter(context, &block) end", <ide> __FILE__, __LINE__ - 1) <ide> elsif filter.respond_to?(:before) && filter.respond_to?(:after) && kind == :around
1
Ruby
Ruby
handle new non-string xcode version
b69d71edea36ed8845801c037a72e92dace248a8
<ide><path>Library/Homebrew/extend/os/mac/system_config.rb <ide> def xcode <ide> if instance_variable_defined?(:@xcode) <ide> @xcode <ide> elsif MacOS::Xcode.installed? <del> @xcode = MacOS::Xcode.version <add> @xcode = MacOS::Xcode.version.to_s <ide> @xcode += " => #{MacOS::Xcode.prefix}" unless MacOS::Xcode.default_prefix? <ide> @xcode <ide> end
1
PHP
PHP
fix psalm errors
8fc50b698c64ff25cfe87198d8dcc69233ec9fc1
<ide><path>src/Console/ConsoleOptionParser.php <ide> public function help(?string $subcommand = null, string $format = 'text', int $w <ide> return (string)$formatter->xml(); <ide> } <ide> } <add> $subcommand = (string)$subcommand; <ide> <ide> if (isset($this->_subcommands[$subcommand])) { <ide> $command = $this->_subcommands[$subcommand]; <ide><path>src/Console/Exception/InvalidOptionException.php <ide> protected function findClosestItem($needle, $haystack): ?string <ide> foreach ($haystack as $item) { <ide> $score = levenshtein($needle, $item); <ide> <del> if (!isset($bestScore) || $score < $bestScore) { <add> if ($score < $bestScore) { <ide> $bestScore = $score; <ide> $bestGuess = $item; <ide> }
2
Javascript
Javascript
add count to array computed meta
acefb532e2e5f51f32f593e3038e0ad20b91d913
<ide><path>packages_es6/ember-runtime/lib/computed/reduce_computed.js <ide> DependentArraysObserver.prototype = { <ide> <ide> forEach(itemPropertyKeys, removeObservers, this); <ide> <del> changeMeta = createChangeMeta(dependentArray, item, itemIndex, this.instanceMeta.propertyName, this.cp); <add> changeMeta = new ChangeMeta(dependentArray, item, itemIndex, this.instanceMeta.propertyName, this.cp, normalizedRemoveCount); <ide> this.setValue( removedItem.call( <ide> this.instanceMeta.context, this.getValue(), item, changeMeta, this.instanceMeta.sugarMeta)); <ide> } <ide> DependentArraysObserver.prototype = { <ide> }, this); <ide> } <ide> <del> changeMeta = createChangeMeta(dependentArray, item, normalizedIndex + sliceIndex, this.instanceMeta.propertyName, this.cp); <add> changeMeta = new ChangeMeta(dependentArray, item, normalizedIndex + sliceIndex, this.instanceMeta.propertyName, this.cp, addedCount); <ide> this.setValue( addedItem.call( <ide> this.instanceMeta.context, this.getValue(), item, changeMeta, this.instanceMeta.sugarMeta)); <ide> }, this); <ide> DependentArraysObserver.prototype = { <ide> <ide> this.updateIndexes(c.observerContext.trackedArray, c.observerContext.dependentArray); <ide> <del> changeMeta = createChangeMeta(c.array, c.obj, c.observerContext.index, this.instanceMeta.propertyName, this.cp, c.previousValues); <add> changeMeta = new ChangeMeta(c.array, c.obj, c.observerContext.index, this.instanceMeta.propertyName, this.cp, changedItems.length, c.previousValues); <ide> this.setValue( <ide> this.callbacks.removedItem.call(this.instanceMeta.context, this.getValue(), c.obj, changeMeta, this.instanceMeta.sugarMeta)); <ide> this.setValue( <ide> function normalizeRemoveCount(index, length, removedCount) { <ide> return Math.min(removedCount, length - index); <ide> } <ide> <del>function createChangeMeta(dependentArray, item, index, propertyName, property, previousValues) { <del> var meta = { <del> arrayChanged: dependentArray, <del> index: index, <del> item: item, <del> propertyName: propertyName, <del> property: property <del> }; <add>function ChangeMeta(dependentArray, item, index, propertyName, property, changedCount, previousValues){ <add> this.arrayChanged = dependentArray; <add> this.index = index; <add> this.item = item; <add> this.propertyName = propertyName; <add> this.property = property; <add> this.changedCount = changedCount; <ide> <ide> if (previousValues) { <ide> // previous values only available for item property changes <del> meta.previousValues = previousValues; <add> this.previousValues = previousValues; <ide> } <del> <del> return meta; <ide> } <ide> <ide> function addItems (dependentArray, callbacks, cp, propertyName, meta) { <ide> forEach(dependentArray, function (item, index) { <ide> meta.setValue( callbacks.addedItem.call( <del> this, meta.getValue(), item, createChangeMeta(dependentArray, item, index, propertyName, cp), meta.sugarMeta)); <add> this, meta.getValue(), item, new ChangeMeta(dependentArray, item, index, propertyName, cp, dependentArray.length), meta.sugarMeta)); <ide> }, this); <ide> } <ide> <ide><path>packages_es6/ember-runtime/tests/computed/reduce_computed_test.js <ide> test("changeMeta includes item and index", function() { <ide> deepEqual(callbackItems, expected, "items removed from the array had observers removed"); <ide> }); <ide> <add>test("changeMeta includes changedCount and arrayChanged", function() { <add> var callbackLetters = []; <add> var obj = EmberObject.createWithMixins({ <add> letters: Ember.A(['a', 'b']), <add> lettersArrayComputed: arrayComputed('letters', { <add> addedItem: function (array, item, changeMeta, instanceMeta) { <add> callbackItems.push('add:' + changeMeta.changedCount + ":" + changeMeta.arrayChanged.join('')); <add> }, <add> removedItem: function (array, item, changeMeta, instanceMeta) { <add> callbackItems.push('remove:' + changeMeta.changedCount + ":" + changeMeta.arrayChanged.join('')); <add> } <add> }) <add> }); <add> <add> var letters = get(obj, 'letters'); <add> <add> obj.get('lettersArrayComputed'); <add> letters.pushObject('c'); <add> letters.popObject(); <add> letters.replace(0, 1, ['d']); <add> letters.removeAt(0, letters.length); <add> <add> var expected = ["add:2:ab", "add:2:ab", "add:1:abc", "remove:1:abc", "remove:1:ab", "add:1:db", "remove:2:db", "remove:2:db"]; <add> deepEqual(callbackItems, expected, "changeMeta has count and changed"); <add>}); <add> <ide> test("when initialValue is undefined, everything works as advertised", function() { <ide> var chars = EmberObject.createWithMixins({ <ide> letters: Ember.A(),
2
Javascript
Javascript
remove debugger statement from unit test
0ffa758cd39fbc11c38fe00011457c218feb39f3
<ide><path>packages/sproutcore-handlebars/tests/handlebars_test.js <ide> test("should not enter an infinite loop when binding an attribute in Handlebars" <ide> classNames: ['app-link'], <ide> tagName: 'a', <ide> attributeBindings: ['href'], <del> // href: '#none', <del> href: function(key, value) { <del> debugger; <del> }.property(), <add> href: '#none', <add> <ide> click: function() { <ide> return false; <ide> }
1
Python
Python
add support for collection routes to simplerouter
d72603bc6a16112008959c5267839f819c2bc43a
<ide><path>rest_framework/decorators.py <ide> def link(**kwargs): <ide> """ <ide> def decorator(func): <ide> func.bind_to_methods = ['get'] <add> func.collection = False <ide> func.kwargs = kwargs <ide> return func <ide> return decorator <ide> def action(methods=['post'], **kwargs): <ide> """ <ide> def decorator(func): <ide> func.bind_to_methods = methods <add> func.collection = False <add> func.kwargs = kwargs <add> return func <add> return decorator <add> <add> <add>def collection_link(**kwargs): <add> """ <add> Used to mark a method on a ViewSet that should be routed for GET requests. <add> """ <add> def decorator(func): <add> func.bind_to_methods = ['get'] <add> func.collection = True <add> func.kwargs = kwargs <add> return func <add> return decorator <add> <add> <add>def collection_action(methods=['post'], **kwargs): <add> """ <add> Used to mark a method on a ViewSet that should be routed for POST requests. <add> """ <add> def decorator(func): <add> func.bind_to_methods = methods <add> func.collection = True <ide> func.kwargs = kwargs <ide> return func <ide> return decorator <ide><path>rest_framework/routers.py <ide> class SimpleRouter(BaseRouter): <ide> name='{basename}-list', <ide> initkwargs={'suffix': 'List'} <ide> ), <add> # Dynamically generated collection routes. <add> # Generated using @collection_action or @collection_link decorators <add> # on methods of the viewset. <add> Route( <add> url=r'^{prefix}/{methodname}{trailing_slash}$', <add> mapping={ <add> '{httpmethod}': '{methodname}', <add> }, <add> name='{basename}-collection-{methodnamehyphen}', <add> initkwargs={} <add> ), <ide> # Detail route. <ide> Route( <ide> url=r'^{prefix}/{lookup}{trailing_slash}$', <ide> class SimpleRouter(BaseRouter): <ide> mapping={ <ide> '{httpmethod}': '{methodname}', <ide> }, <del> name='{basename}-{methodnamehyphen}', <add> name='{basename}-dynamic-{methodnamehyphen}', <ide> initkwargs={} <ide> ), <ide> ] <ide> def get_routes(self, viewset): <ide> known_actions = flatten([route.mapping.values() for route in self.routes]) <ide> <ide> # Determine any `@action` or `@link` decorated methods on the viewset <add> collection_routes = [] <ide> dynamic_routes = [] <ide> for methodname in dir(viewset): <ide> attr = getattr(viewset, methodname) <ide> httpmethods = getattr(attr, 'bind_to_methods', None) <add> collection = getattr(attr, 'collection', False) <ide> if httpmethods: <ide> if methodname in known_actions: <ide> raise ImproperlyConfigured('Cannot use @action or @link decorator on ' <ide> 'method "%s" as it is an existing route' % methodname) <ide> httpmethods = [method.lower() for method in httpmethods] <del> dynamic_routes.append((httpmethods, methodname)) <add> if collection: <add> collection_routes.append((httpmethods, methodname)) <add> else: <add> dynamic_routes.append((httpmethods, methodname)) <ide> <ide> ret = [] <ide> for route in self.routes: <del> if route.mapping == {'{httpmethod}': '{methodname}'}: <add> if route.name == '{basename}-dynamic-{methodnamehyphen}': <ide> # Dynamic routes (@link or @action decorator) <ide> for httpmethods, methodname in dynamic_routes: <ide> initkwargs = route.initkwargs.copy() <ide> def get_routes(self, viewset): <ide> name=replace_methodname(route.name, methodname), <ide> initkwargs=initkwargs, <ide> )) <add> elif route.name == '{basename}-collection-{methodnamehyphen}': <add> # Dynamic routes (@collection_link or @collection_action decorator) <add> for httpmethods, methodname in collection_routes: <add> initkwargs = route.initkwargs.copy() <add> initkwargs.update(getattr(viewset, methodname).kwargs) <add> ret.append(Route( <add> url=replace_methodname(route.url, methodname), <add> mapping=dict((httpmethod, methodname) for httpmethod in httpmethods), <add> name=replace_methodname(route.name, methodname), <add> initkwargs=initkwargs, <add> )) <ide> else: <ide> # Standard route <ide> ret.append(route) <ide><path>rest_framework/tests/test_routers.py <ide> from django.core.exceptions import ImproperlyConfigured <ide> from rest_framework import serializers, viewsets, permissions <ide> from rest_framework.compat import include, patterns, url <del>from rest_framework.decorators import link, action <add>from rest_framework.decorators import link, action, collection_link, collection_action <ide> from rest_framework.response import Response <ide> from rest_framework.routers import SimpleRouter, DefaultRouter <ide> from rest_framework.test import APIRequestFactory <ide> def retrieve(self, request, *args, **kwargs): <ide> <ide> with self.assertRaises(ImproperlyConfigured): <ide> self.router.urls <add> <add> <add>class StaticAndDynamicViewSet(viewsets.ViewSet): <add> def list(self, request, *args, **kwargs): <add> return Response({'method': 'list'}) <add> <add> @collection_action() <add> def collection_action(self, request, *args, **kwargs): <add> return Response({'method': 'action1'}) <add> <add> @action() <add> def dynamic_action(self, request, *args, **kwargs): <add> return Response({'method': 'action2'}) <add> <add> @collection_link() <add> def collection_link(self, request, *args, **kwargs): <add> return Response({'method': 'link1'}) <add> <add> @link() <add> def dynamic_link(self, request, *args, **kwargs): <add> return Response({'method': 'link2'}) <add> <add> <add>class TestStaticAndDynamicRouter(TestCase): <add> def setUp(self): <add> self.router = SimpleRouter() <add> <add> def test_link_and_action_decorator(self): <add> routes = self.router.get_routes(StaticAndDynamicViewSet) <add> decorator_routes = [r for r in routes if not (r.name.endswith('-list') or r.name.endswith('-detail'))] <add> # Make sure all these endpoints exist and none have been clobbered <add> for i, endpoint in enumerate(['collection_action', 'collection_link', 'dynamic_action', 'dynamic_link']): <add> route = decorator_routes[i] <add> # check url listing <add> if endpoint.startswith('collection_'): <add> self.assertEqual(route.url, <add> '^{{prefix}}/{0}{{trailing_slash}}$'.format(endpoint)) <add> else: <add> self.assertEqual(route.url, <add> '^{{prefix}}/{{lookup}}/{0}{{trailing_slash}}$'.format(endpoint)) <add> # check method to function mapping <add> if endpoint.endswith('action'): <add> method_map = 'post' <add> else: <add> method_map = 'get' <add> self.assertEqual(route.mapping[method_map], endpoint)
3
PHP
PHP
refactor the validate required method for clarity
dae283943fed8639236fb30ef9127eb0bcc74cc9
<ide><path>laravel/validator.php <ide> protected function error($attribute, $rule, $parameters) <ide> */ <ide> protected function validate_required($attribute, $value) <ide> { <del> return ! (is_null($value) or (is_string($value) and trim($value) === '')); <add> if (is_null($value)) <add> { <add> return false; <add> } <add> elseif (is_string($value) and trim($value) === '') <add> { <add> return false; <add> } <add> elseif (is_array($value) and count($value) == 0) <add> { <add> return false; <add> } <add> <add> return true; <ide> } <ide> <ide> /**
1
Javascript
Javascript
simplify code and remove unused properties
1eec5f091ab00860539ac2474e47232b31925cea
<ide><path>lib/_http_common.js <ide> function parserOnMessageComplete() { <ide> parser._url = ''; <ide> } <ide> <del> if (!stream.upgrade) <del> // For upgraded connections, also emit this after parser.execute <del> stream.push(null); <del> } <del> <del> if (stream && !parser.incoming._pendings.length) { <ide> // For emit end event <ide> stream.push(null); <ide> } <ide><path>lib/_http_incoming.js <ide> function IncomingMessage(socket) { <ide> <ide> this.readable = true; <ide> <del> this._pendings = []; <del> this._pendingIndex = 0; <ide> this.upgrade = null; <ide> <ide> // request (server) only <ide> function IncomingMessage(socket) { <ide> // response (client) only <ide> this.statusCode = null; <ide> this.statusMessage = null; <del> this.client = this.socket; <add> this._client = socket; // deprecated <ide> <ide> // flag for backwards compatibility grossness. <ide> this._consuming = false; <ide> util.inherits(IncomingMessage, Stream.Readable); <ide> <ide> exports.IncomingMessage = IncomingMessage; <ide> <add>Object.defineProperty(IncomingMessage.prototype, 'client', { <add> configurable: true, <add> enumerable: true, <add> get: util.deprecate(function() { <add> return this._client; <add> }, 'client is deprecated, use socket or connection instead'), <add> set: util.deprecate(function(val) { <add> this._client = val; <add> }, 'client is deprecated, use socket or connection instead') <add>}); <ide> <ide> IncomingMessage.prototype.setTimeout = function(msecs, callback) { <ide> if (callback) <ide><path>lib/_http_outgoing.js <ide> function OutgoingMessage() { <ide> this._trailer = ''; <ide> <ide> this.finished = false; <del> this._hangupClose = false; <ide> this._headerSent = false; <ide> <ide> this.socket = null;
3
PHP
PHP
close php tags for ajax tests on swarm
f6e86c3ca4d527d5453a0b5b9591ef38b5d3c000
<ide><path>test/data/errorWithJSON.php <ide> header("HTTP/1.0 400 Bad Request"); <ide> header("Content-Type: application/json"); <ide> <del>echo '{ "code": 40, "message": "Bad Request" }'; <ide>\ No newline at end of file <add>echo '{ "code": 40, "message": "Bad Request" }'; <add> <add>?> <ide>\ No newline at end of file <ide><path>test/data/errorWithText.php <ide> <ide> header("HTTP/1.0 400 Bad Request"); <ide> <del>echo "plain text message"; <ide>\ No newline at end of file <add>echo "plain text message"; <add> <add>?> <ide>\ No newline at end of file <ide><path>test/data/headers.php <ide> foreach( explode( "_" , $_GET[ "keys" ] ) as $key ) { <ide> echo "$key: " . @$headers[ strtoupper( $key ) ] . "\n"; <ide> } <add> <add>?> <ide>\ No newline at end of file
3
Javascript
Javascript
change support test to be wwa-friendly
85af4e6412e49c2e6a872feef00718a46c2fa2ce
<ide><path>src/manipulation/support.js <ide> define([ <ide> <ide> (function() { <ide> var fragment = document.createDocumentFragment(), <del> div = fragment.appendChild( document.createElement( "div" ) ); <add> div = fragment.appendChild( document.createElement( "div" ) ), <add> input = document.createElement( "input" ); <ide> <ide> // #11217 - WebKit loses check when the name is after the checked attribute <del> div.innerHTML = "<input type='radio' checked='checked' name='t'/>"; <add> // Support: Windows Web Apps (WWA) <add> // `name` and `type` need .setAttribute for WWA <add> input.setAttribute( "type", "radio" ); <add> input.setAttribute( "checked", "checked" ); <add> input.setAttribute( "name", "t" ); <add> <add> div.appendChild( input ); <ide> <ide> // Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3 <ide> // old WebKit doesn't clone checked state correctly in fragments
1
Python
Python
fix the batch_size of the ncf benchmark
f519c0157718b13d3c95fdefafb43b9ae8c84899
<ide><path>official/recommendation/ncf_keras_benchmark.py <ide> def __init__(self, <ide> default_flags['num_gpus'] = 1 <ide> default_flags['train_epochs'] = 14 <ide> default_flags['clean'] = True <del> default_flags['batch_size'] = 16000 <add> default_flags['batch_size'] = 160000 <ide> default_flags['learning_rate'] = 0.00382059 <ide> default_flags['beta1'] = 0.783529 <ide> default_flags['beta2'] = 0.909003 <ide> def __init__(self, <ide> default_flags['dataset'] = 'ml-20m' <ide> default_flags['num_gpus'] = 1 <ide> default_flags['train_epochs'] = 14 <del> default_flags['batch_size'] = 16000 <add> default_flags['batch_size'] = 160000 <ide> default_flags['learning_rate'] = 0.00382059 <ide> default_flags['beta1'] = 0.783529 <ide> default_flags['beta2'] = 0.909003
1
Text
Text
add a question about autoplay
e5a240a63118a2f9dfe487b6ae493e6ae4bc650a
<ide><path>docs/faq.md <ide> * [If you don't think you can fix the issue or add the feature](#if-you-dont-think-you-can-fix-the-issue-or-add-the-feature) <ide> * [Q: What is a reduced test case?](#q-what-is-a-reduced-test-case) <ide> * [Q: What media formats does video.js support?](#q-what-media-formats-does-videojs-support) <add>* [Q: How to I autoplay the video?](#q-how-to-i-autoplay-the-video) <add> * [Q: How can I autoplay a video on a mobile device?](#q-how-can-i-autoplay-a-video-on-a-mobile-device) <ide> * [Q: How can I play RTMP video in video.js?](#q-how-can-i-play-rtmp-video-in-videojs) <ide> * [Q: How can I hide the links to my video/subtitles/audio/tracks?](#q-how-can-i-hide-the-links-to-my-videosubtitlesaudiotracks) <ide> * [Q: What is a plugin?](#q-what-is-a-plugin) <ide> techs made available to video.js. For example, video.js 5 includes the Flash tec <ide> enables the playback of FLV video where the Flash plugin is available. For more information <ide> on media formats see the [troubleshooting guide][troubleshooting]. <ide> <add>## Q: How to I autoplay the video? <add> <add>Video.js supports the standard html5 `autoplay` attribute on the video element. <add>It also supports it as an option to video.js or as a method invocation on the player. <add> <add>```html <add><video autoplay controls class="video-js"> <add>``` <add> <add>```js <add>var player = videojs('my-video', { <add> autoplay: true <add>}); <add> <add>// or <add> <add>player.autoplay(true); <add>``` <add> <add>### Q: How can I autoplay a video on a mobile device? <add> <add>Most mobile devices have blocked autoplaying videos until recently. <add>For mobile devices that don't support autoplaying, autoplay isn't supported by video.js. <add>For those devices that support autoplaying, like iOS10 and Chrome for Android 53+, <add>you must mute the video or have a video without audio tracks to be able to play it. <add>For example: <add> <add>```html <add><video muted autoplay playsinline> <add>``` <add> <add>Will make an inline, muted, autoplaying video on an iPhone with iOS10. <add> <ide> ## Q: How can I play RTMP video in video.js? <ide> <ide> Make sure that the Flash tech is available -- RTMP is not playable on browsers without Flash including mobile. Then, just set the rtmp source with
1
PHP
PHP
add a test for auto-tables with an alias
f6cc721b0633cdfabf31fbe98c474bb68891c0cd
<ide><path>tests/TestCase/ORM/TableRegistryTest.php <ide> public function testGet() <ide> $this->assertEquals('my_articles', $result->table()); <ide> } <ide> <add> /** <add> * Are auto-models instanciated correctly? How about when they have an alias? <add> * <add> * @return void <add> */ <add> public function testGetFallbacks() <add> { <add> $result = TableRegistry::get('Droids'); <add> $this->assertInstanceOf('Cake\ORM\Table', $result); <add> $this->assertEquals('droids', $result->table()); <add> $this->assertEquals('Droids', $result->alias()); <add> <add> $result = TableRegistry::get('R2D2', ['className' => 'Droids']); <add> $this->assertInstanceOf('Cake\ORM\Table', $result); <add> $this->assertEquals('droids', $result->table()); <add> $this->assertEquals('R2D2', $result->alias()); <add> } <add> <ide> /** <ide> * Test that get() uses config data set with config() <ide> *
1
Ruby
Ruby
remove unused requires
6d5eefd453c641c317f3cdfa1286f07cfc5b11e7
<ide><path>activerecord/test/cases/associations/has_many_associations_test.rb <ide> require "models/image" <ide> require "models/post" <ide> require "models/author" <del>require "models/book" <ide> require "models/essay" <ide> require "models/comment" <ide> require "models/person" <ide> require "models/minivan" <ide> require "models/speedometer" <ide> require "models/reference" <del>require "models/job" <ide> require "models/college" <ide> require "models/student" <ide> require "models/pirate" <ide> def test_blank_custom_primary_key_on_new_record_should_not_run_queries <ide> class HasManyAssociationsTest < ActiveRecord::TestCase <ide> fixtures :accounts, :categories, :companies, :developers, :projects, <ide> :developers_projects, :topics, :authors, :author_addresses, :comments, <del> :posts, :readers, :taggings, :cars, :jobs, :tags, <add> :posts, :readers, :taggings, :cars, :tags, <ide> :categorizations, :zines, :interests <ide> <ide> def setup
1
Javascript
Javascript
add rewrites in storybook preset
b87b2d46eacccc09cc81e37e7904427d4fcc990b
<ide><path>packages/next-plugin-storybook/preset.js <ide> async function webpackFinal(config) { <ide> target: 'server', <ide> config: nextConfig, <ide> buildId: 'storybook', <add> rewrites: [], <ide> }) <ide> <ide> config.plugins = [...config.plugins, ...nextWebpackConfig.plugins]
1
Javascript
Javascript
add weak event handlers
5ef4c64e5b912aa2f90d73ea08753362ec396c36
<ide><path>lib/events.js <ide> function getEventListeners(emitterOrTarget, type) { <ide> const listeners = []; <ide> let handler = root?.next; <ide> while (handler?.listener !== undefined) { <del> ArrayPrototypePush(listeners, handler.listener); <add> const listener = handler.listener?.deref ? <add> handler.listener.deref() : handler.listener; <add> ArrayPrototypePush(listeners, listener); <ide> handler = handler.next; <ide> } <ide> return listeners; <ide><path>lib/internal/event_target.js <ide> const { <ide> ReflectApply, <ide> SafeArrayIterator, <ide> SafeMap, <add> SafeWeakMap, <add> SafeWeakSet, <ide> String, <ide> Symbol, <ide> SymbolFor, <ide> SymbolToStringTag, <del> SafeWeakSet, <ide> } = primordials; <ide> <ide> const { <ide> const kEvents = Symbol('kEvents'); <ide> const kStop = Symbol('kStop'); <ide> const kTarget = Symbol('kTarget'); <ide> const kHandlers = Symbol('khandlers'); <add>const kWeakHandler = Symbol('kWeak'); <ide> <ide> const kHybridDispatch = SymbolFor('nodejs.internal.kHybridDispatch'); <ide> const kCreateEvent = Symbol('kCreateEvent'); <ide> class NodeCustomEvent extends Event { <ide> } <ide> } <ide> } <add> <add>// Weak listener cleanup <add>// This has to be lazy for snapshots to work <add>let weakListenersState = null; <add>// The resource needs to retain the callback so that it doesn't <add>// get garbage collected now that it's weak. <add>let objectToWeakListenerMap = null; <add>function weakListeners() { <add> weakListenersState ??= new globalThis.FinalizationRegistry( <add> (listener) => listener.remove() <add> ); <add> objectToWeakListenerMap ??= new SafeWeakMap(); <add> return { registry: weakListenersState, map: objectToWeakListenerMap }; <add>} <add> <ide> // The listeners for an EventTarget are maintained as a linked list. <ide> // Unfortunately, the way EventTarget is defined, listeners are accounted <ide> // using the tuple [handler,capture], and even if we don't actually make <ide> class NodeCustomEvent extends Event { <ide> // the linked list makes dispatching faster, even if adding/removing is <ide> // slower. <ide> class Listener { <del> constructor(previous, listener, once, capture, passive, isNodeStyleListener) { <add> constructor(previous, listener, once, capture, passive, <add> isNodeStyleListener, weak) { <ide> this.next = undefined; <ide> if (previous !== undefined) <ide> previous.next = this; <ide> class Listener { <ide> this.passive = passive; <ide> this.isNodeStyleListener = isNodeStyleListener; <ide> this.removed = false; <del> <del> this.callback = <del> typeof listener === 'function' ? <del> listener : <del> FunctionPrototypeBind(listener.handleEvent, listener); <add> this.weak = Boolean(weak); // Don't retain the object <add> <add> if (this.weak) { <add> this.callback = new globalThis.WeakRef(listener); <add> weakListeners().registry.register(listener, this, this); <add> // Make the retainer retain the listener in a WeakMap <add> weakListeners().map.set(weak, listener); <add> this.listener = this.callback; <add> } else if (typeof listener === 'function') { <add> this.callback = listener; <add> this.listener = listener; <add> } else { <add> this.callback = FunctionPrototypeBind(listener.handleEvent, listener); <add> this.listener = listener; <add> } <ide> } <ide> <ide> same(listener, capture) { <del> return this.listener === listener && this.capture === capture; <add> const myListener = this.weak ? this.listener.deref() : this.listener; <add> return myListener === listener && this.capture === capture; <ide> } <ide> <ide> remove() { <ide> class Listener { <ide> if (this.next !== undefined) <ide> this.next.previous = this.previous; <ide> this.removed = true; <add> if (this.weak) <add> weakListeners().registry.unregister(this); <ide> } <ide> } <ide> <ide> class EventTarget { <ide> capture, <ide> passive, <ide> signal, <del> isNodeStyleListener <add> isNodeStyleListener, <add> weak, <ide> } = validateEventListenerOptions(options); <ide> <ide> if (!shouldAddListener(listener)) { <ide> class EventTarget { <ide> // not prevent the event target from GC. <ide> signal.addEventListener('abort', () => { <ide> this.removeEventListener(type, listener, options); <del> }, { once: true }); <add> }, { once: true, [kWeakHandler]: this }); <ide> } <ide> <ide> let root = this[kEvents].get(type); <ide> <ide> if (root === undefined) { <ide> root = { size: 1, next: undefined }; <ide> // This is the first handler in our linked list. <del> new Listener(root, listener, once, capture, passive, isNodeStyleListener); <add> new Listener(root, listener, once, capture, passive, <add> isNodeStyleListener, weak); <ide> this[kNewListener](root.size, type, listener, once, capture, passive); <ide> this[kEvents].set(type, root); <ide> return; <ide> class EventTarget { <ide> } <ide> <ide> new Listener(previous, listener, once, capture, passive, <del> isNodeStyleListener); <add> isNodeStyleListener, weak); <ide> root.size++; <ide> this[kNewListener](root.size, type, listener, once, capture, passive); <ide> } <ide> class EventTarget { <ide> } else { <ide> arg = createEvent(); <ide> } <del> const result = FunctionPrototypeCall(handler.callback, this, arg); <add> const callback = handler.weak ? <add> handler.callback.deref() : handler.callback; <add> let result; <add> if (callback) { <add> result = FunctionPrototypeCall(callback, this, arg); <add> } <ide> if (result !== undefined && result !== null) <ide> addCatch(this, result, createEvent()); <ide> } catch (err) { <ide> function validateEventListenerOptions(options) { <ide> capture: Boolean(options.capture), <ide> passive: Boolean(options.passive), <ide> signal: options.signal, <add> weak: options[kWeakHandler], <ide> isNodeStyleListener: Boolean(options[kIsNodeStyleListener]) <ide> }; <ide> } <ide> module.exports = { <ide> kTrustEvent, <ide> kRemoveListener, <ide> kEvents, <add> kWeakHandler, <ide> isEventTarget, <ide> }; <ide><path>test/parallel/test-events-static-geteventlisteners.js <ide> 'use strict'; <del> <add>// Flags: --expose-internals --no-warnings <ide> const common = require('../common'); <add>const { kWeakHandler } = require('internal/event_target'); <ide> <ide> const { <ide> deepStrictEqual, <ide> const { getEventListeners, EventEmitter } = require('events'); <ide> getEventListeners('INVALID_EMITTER'); <ide> }, /ERR_INVALID_ARG_TYPE/); <ide> } <add>{ <add> // Test weak listeners <add> const target = new EventTarget(); <add> const fn = common.mustNotCall(); <add> target.addEventListener('foo', fn, { [kWeakHandler]: {} }); <add> const listeners = getEventListeners(target, 'foo'); <add> deepStrictEqual(listeners, [fn]); <add>} <ide><path>test/parallel/test-eventtarget.js <del>// Flags: --expose-internals --no-warnings <add>// Flags: --expose-internals --no-warnings --expose-gc <ide> 'use strict'; <ide> <ide> const common = require('../common'); <del>const { defineEventHandler } = require('internal/event_target'); <add>const { <add> defineEventHandler, <add> kWeakHandler, <add>} = require('internal/event_target'); <ide> <ide> const { <ide> ok, <ide> let asyncTest = Promise.resolve(); <ide> const et = new EventTarget(); <ide> strictEqual(et.constructor.name, 'EventTarget'); <ide> } <add>{ <add> // Weak event handlers work <add> const et = new EventTarget(); <add> const listener = common.mustCall(); <add> et.addEventListener('foo', listener, { [kWeakHandler]: et }); <add> et.dispatchEvent(new Event('foo')); <add>} <add>{ <add> // Weak event handlers can be removed and weakness is not part of the key <add> const et = new EventTarget(); <add> const listener = common.mustNotCall(); <add> et.addEventListener('foo', listener, { [kWeakHandler]: et }); <add> et.removeEventListener('foo', listener); <add> et.dispatchEvent(new Event('foo')); <add>} <add>{ <add> // Test listeners are held weakly <add> const et = new EventTarget(); <add> et.addEventListener('foo', common.mustNotCall(), { [kWeakHandler]: {} }); <add> setImmediate(() => { <add> global.gc(); <add> et.dispatchEvent(new Event('foo')); <add> }); <add>}
4
Javascript
Javascript
remove unused swc option
cf9eb36e7cf994bd593a7be3aaa9e3d4639ea60a
<ide><path>packages/next/build/webpack/loaders/next-swc-loader.js <ide> function getSWCOptions({ <ide> : {}), <ide> // Disables getStaticProps/getServerSideProps tree shaking on the server compilation for pages <ide> disableNextSsg: true, <del> allowWrongLineComments: true, <ide> pagesDir, <ide> env: { <ide> targets: {
1
Javascript
Javascript
allow direct access to data_priv for cleanup
c1b8edfcc90961290f7555c55851209bc860c0b4
<ide><path>src/data.js <ide> Data.prototype = { <ide> ); <ide> }, <ide> discard: function( owner ) { <del> delete this.cache[ this.key( owner ) ]; <add> if ( owner[ this.expando ] ) { <add> delete this.cache[ owner[ this.expando ] ]; <add> } <ide> } <ide> }; <ide> <ide><path>src/manipulation.js <ide> jQuery.extend({ <ide> }, <ide> <ide> cleanData: function( elems ) { <del> var data, elem, type, <del> l = elems.length, <del> i = 0, <del> special = jQuery.event.special; <del> <del> for ( ; i < l; i++ ) { <del> elem = elems[ i ]; <del> <del> if ( jQuery.acceptData( elem ) ) { <add> var data, elem, events, type, key, j, <add> special = jQuery.event.special, <add> i = 0; <ide> <del> data = data_priv.access( elem ); <add> for ( ; (elem = elems[ i ]) !== undefined; i++ ) { <add> if ( Data.accepts( elem ) ) { <add> key = elem[ data_priv.expando ]; <ide> <del> if ( data ) { <del> for ( type in data.events ) { <del> if ( special[ type ] ) { <del> jQuery.event.remove( elem, type ); <add> if ( key && (data = data_priv.cache[ key ]) ) { <add> events = Object.keys( data.events || {} ); <add> if ( events.length ) { <add> for ( j = 0; (type = events[j]) !== undefined; j++ ) { <add> if ( special[ type ] ) { <add> jQuery.event.remove( elem, type ); <ide> <del> // This is a shortcut to avoid jQuery.event.remove's overhead <del> } else { <del> jQuery.removeEvent( elem, type, data.handle ); <add> // This is a shortcut to avoid jQuery.event.remove's overhead <add> } else { <add> jQuery.removeEvent( elem, type, data.handle ); <add> } <ide> } <ide> } <add> if ( data_priv.cache[ key ] ) { <add> // Discard any remaining `private` data <add> delete data_priv.cache[ key ]; <add> } <ide> } <ide> } <del> // Discard any remaining `private` and `user` data <del> // One day we'll replace the dual arrays with a WeakMap and this won't be an issue. <del> // (Splices the data objects out of the internal cache arrays) <del> data_user.discard( elem ); <del> data_priv.discard( elem ); <add> // Discard any remaining `user` data <add> delete data_user.cache[ elem[ data_user.expando ] ]; <ide> } <ide> }, <ide>
2
Javascript
Javascript
reduce run time for misc benchmark tests
ce848a450152095c3d0f5b7a4acdd2252a1f9549
<ide><path>benchmark/misc/console.js <ide> function runUsingArgumentsAndApply(n, concat) { <ide> function main(conf) { <ide> const n = +conf.n; <ide> switch (conf.method) { <add> // '' is a default case for tests <add> case '': <ide> case 'restAndSpread': <ide> runUsingRestAndSpread(n, conf.concat); <ide> break; <ide><path>benchmark/misc/object-property-bench.js <ide> function main(conf) { <ide> const n = +conf.millions * 1e6; <ide> <ide> switch (conf.method) { <add> // '' is a default case for tests <add> case '': <ide> case 'property': <ide> runProperty(n); <ide> break; <ide><path>benchmark/misc/punycode.js <ide> function main(conf) { <ide> const n = +conf.n; <ide> const val = conf.val; <ide> switch (conf.method) { <add> // '' is a default case for tests <add> case '': <ide> case 'punycode': <ide> runPunycode(n, val); <ide> break; <ide><path>test/parallel/test-benchmark-misc.js <ide> require('../common'); <ide> const runBenchmark = require('../common/benchmark'); <ide> <ide> runBenchmark('misc', [ <del> 'n=1', <del> 'val=magyarország.icom.museum', <add> 'concat=0', <add> 'method=', <ide> 'millions=.000001', <add> 'n=1', <ide> 'type=extend', <del> 'concat=0' <add> 'val=magyarország.icom.museum' <ide> ]);
4
Javascript
Javascript
fix typo in array mixin docs
a8384b2aeee841bcfa6c400d538dee03c27a12ba
<ide><path>packages/ember-runtime/lib/mixins/array.js <ide> Ember.Array = Ember.Mixin.create(Ember.Enumerable, /** @scope Ember.Array.protot <ide> Adds an array observer to the receiving array. The array observer object <ide> normally must implement two methods: <ide> <del> * `arrayWillChange(start, removeCount, addCount)` - This method will be <add> * `arrayWillChange(observedObj, start, removeCount, addCount)` - This method will be <ide> called just before the array is modified. <del> * `arrayDidChange(start, removeCount, addCount)` - This method will be <add> * `arrayDidChange(observedObj, start, removeCount, addCount)` - This method will be <ide> called just after the array is modified. <ide> <del> Both callbacks will be passed the starting index of the change as well a <del> a count of the items to be removed and added. You can use these callbacks <del> to optionally inspect the array during the change, clear caches, or do <del> any other bookkeeping necessary. <add> Both callbacks will be passed the observed object, starting index of the <add> change as well a a count of the items to be removed and added. You can use <add> these callbacks to optionally inspect the array during the change, clear <add> caches, or do any other bookkeeping necessary. <ide> <ide> In addition to passing a target, you can also include an options hash <ide> which you can use to override the method names that will be invoked on the
1
PHP
PHP
failed-table
4ea441ea82bac647ed802ab96bf4ec841bffadb1
<ide><path>src/Illuminate/Queue/Console/FailedTableCommand.php <ide> protected function createBaseMigration() <ide> { <ide> $name = 'create_failed_jobs_table'; <ide> <del> $path = $this->laravel['path'].'/database/migrations'; <add> $path = $this->laravel['path.database'].'/migrations'; <ide> <ide> return $this->laravel['migration.creator']->create($name, $path); <ide> }
1
Javascript
Javascript
use ternary operator simplify statement
5d06a374ea0f8b8d75dc70ba8e765847818dd15b
<ide><path>lib/internal/dns/promises.js <ide> function createLookupPromise(family, hostname, all, hints, verbatim) { <ide> return new Promise((resolve, reject) => { <ide> if (!hostname) { <ide> emitInvalidHostnameWarning(hostname); <del> if (all) <del> resolve([]); <del> else <del> resolve({ address: null, family: family === 6 ? 6 : 4 }); <del> <add> resolve(all ? [] : { address: null, family: family === 6 ? 6 : 4 }); <ide> return; <ide> } <ide> <ide> const matchedFamily = isIP(hostname); <ide> <ide> if (matchedFamily !== 0) { <ide> const result = { address: hostname, family: matchedFamily }; <del> if (all) <del> resolve([result]); <del> else <del> resolve(result); <del> <add> resolve(all ? [result] : result); <ide> return; <ide> } <ide>
1
Python
Python
improve check copies
1f7e40d04f41569e41a2d606261fceac02a801e9
<ide><path>utils/check_copies.py <ide> def is_copy_consistent(filename, overwrite=False): <ide> <ide> # Test for a diff and act accordingly. <ide> if observed_code != theoretical_code: <del> diffs.append([object_name, start_index]) <add> diff_index = start_index + 1 <add> for observed_line, theoretical_line in zip(observed_code.split("\n"), theoretical_code.split("\n")): <add> if observed_line != theoretical_line: <add> break <add> diff_index += 1 <add> diffs.append([object_name, diff_index]) <ide> if overwrite: <ide> lines = lines[:start_index] + [theoretical_code] + lines[line_index:] <ide> line_index = start_index + 1
1
Ruby
Ruby
use formula from keg for local bottle installs
a0dfe4aa180f602af0c4b5ed6d9c0ffd315dbc6d
<ide><path>Library/Homebrew/formula_installer.rb <ide> def post_install <ide> -I #{$LOAD_PATH.join(File::PATH_SEPARATOR)} <ide> -- <ide> #{HOMEBREW_LIBRARY_PATH}/postinstall.rb <del> #{formula.path} <ide> ] <ide> <add> args << if formula.local_bottle_path.present? <add> formula.prefix/".brew/#{formula.name}.rb" <add> else <add> formula.path <add> end <add> <ide> Utils.safe_fork do <ide> if Sandbox.available? <ide> sandbox = Sandbox.new
1
Python
Python
add test for ticket #390
92ce54ed154e972e649800fcfceda52458c18664
<ide><path>numpy/core/tests/test_records.py <del>from os import path <add>import numpy as np <ide> from numpy.testing import * <add>from os import path <ide> set_package_path() <del>import numpy.core <del>reload(numpy.core) <del>import numpy <del>from numpy.core import * <ide> restore_path() <ide> <ide> class TestFromrecords(TestCase): <ide> def test_fromrecords(self): <del> r = rec.fromrecords([[456,'dbe',1.2],[2,'de',1.3]], <add> r = np.rec.fromrecords([[456,'dbe',1.2],[2,'de',1.3]], <ide> names='col1,col2,col3') <del> assert_equal(r[0].item(),(456, 'dbe', 1.2)) <add> assert_equal(r[0].item(), (456, 'dbe', 1.2)) <ide> <ide> def test_method_array(self): <del> r = rec.array('abcdefg'*100,formats='i2,a3,i4',shape=3,byteorder='big') <del> assert_equal(r[1].item(),(25444, 'efg', 1633837924)) <add> r = np.rec.array('abcdefg'*100,formats='i2,a3,i4',shape=3,byteorder='big') <add> assert_equal(r[1].item(), (25444, 'efg', 1633837924)) <ide> <ide> def test_method_array2(self): <del> r=rec.array([(1,11,'a'),(2,22,'b'),(3,33,'c'),(4,44,'d'),(5,55,'ex'), <add> r = np.rec.array([(1,11,'a'),(2,22,'b'),(3,33,'c'),(4,44,'d'),(5,55,'ex'), <ide> (6,66,'f'),(7,77,'g')],formats='u1,f4,a1') <del> assert_equal(r[1].item(),(2, 22.0, 'b')) <add> assert_equal(r[1].item(), (2, 22.0, 'b')) <ide> <ide> def test_recarray_slices(self): <del> r=rec.array([(1,11,'a'),(2,22,'b'),(3,33,'c'),(4,44,'d'),(5,55,'ex'), <add> r = np.rec.array([(1,11,'a'),(2,22,'b'),(3,33,'c'),(4,44,'d'),(5,55,'ex'), <ide> (6,66,'f'),(7,77,'g')],formats='u1,f4,a1') <del> assert_equal(r[1::2][1].item(),(4, 44.0, 'd')) <add> assert_equal(r[1::2][1].item(), (4, 44.0, 'd')) <ide> <ide> def test_recarray_fromarrays(self): <del> x1 = array([1,2,3,4]) <del> x2 = array(['a','dd','xyz','12']) <del> x3 = array([1.1,2,3,4]) <del> r = rec.fromarrays([x1,x2,x3],names='a,b,c') <del> assert_equal(r[1].item(),(2,'dd',2.0)) <add> x1 = np.array([1,2,3,4]) <add> x2 = np.array(['a','dd','xyz','12']) <add> x3 = np.array([1.1,2,3,4]) <add> r = np.rec.fromarrays([x1,x2,x3],names='a,b,c') <add> assert_equal(r[1].item(), (2,'dd',2.0)) <ide> x1[1] = 34 <del> assert_equal(r.a,array([1,2,3,4])) <add> assert_equal(r.a, np.array([1,2,3,4])) <ide> <ide> def test_recarray_fromfile(self): <ide> data_dir = path.join(path.dirname(__file__),'data') <ide> filename = path.join(data_dir,'recarray_from_file.fits') <ide> fd = open(filename) <ide> fd.seek(2880*2) <del> r = rec.fromfile(fd, formats='f8,i4,a5', shape=3, byteorder='big') <add> r = np.rec.fromfile(fd, formats='f8,i4,a5', shape=3, byteorder='big') <ide> <ide> def test_recarray_from_obj(self): <ide> count = 10 <del> a = zeros(count, dtype='O') <del> b = zeros(count, dtype='f8') <del> c = zeros(count, dtype='f8') <add> a = np.zeros(count, dtype='O') <add> b = np.zeros(count, dtype='f8') <add> c = np.zeros(count, dtype='f8') <ide> for i in range(len(a)): <ide> a[i] = range(1,10) <ide> <del> mine = numpy.rec.fromarrays([a,b,c], <del> names='date,data1,data2') <add> mine = np.rec.fromarrays([a,b,c], names='date,data1,data2') <ide> for i in range(len(a)): <del> assert(mine.date[i]==range(1,10)) <del> assert(mine.data1[i]==0.0) <del> assert(mine.data2[i]==0.0) <del> <add> assert (mine.date[i] == range(1,10)) <add> assert (mine.data1[i] == 0.0) <add> assert (mine.data2[i] == 0.0) <add> <add> def check_recarray_from_repr(self): <add> x = np.rec.array([ (1, 2)],dtype=[('a', np.int8), ('b', np.int8)]) <add> y = eval("np." + repr(x)) <add> assert isinstance(y, np.recarray) <add> assert_equal(y, x) <add> <ide> def test_recarray_from_names(self): <del> ra = rec.array([ <add> ra = np.rec.array([ <ide> (1, 'abc', 3.7000002861022949, 0), <ide> (2, 'xy', 6.6999998092651367, 1), <ide> (0, ' ', 0.40000000596046448, 0)], <ide> names='c1, c2, c3, c4') <del> pa = rec.fromrecords([ <add> pa = np.rec.fromrecords([ <ide> (1, 'abc', 3.7000002861022949, 0), <ide> (2, 'xy', 6.6999998092651367, 1), <ide> (0, ' ', 0.40000000596046448, 0)], <ide> def test_recarray_from_names(self): <ide> assert ra[k].item() == pa[k].item() <ide> <ide> def test_recarray_conflict_fields(self): <del> ra = rec.array([(1,'abc',2.3),(2,'xyz',4.2), <add> ra = np.rec.array([(1,'abc',2.3),(2,'xyz',4.2), <ide> (3,'wrs',1.3)], <ide> names='field, shape, mean') <ide> ra.mean = [1.1,2.2,3.3] <ide> def test_recarray_conflict_fields(self): <ide> <ide> class TestRecord(TestCase): <ide> def setUp(self): <del> self.data = rec.fromrecords([(1,2,3),(4,5,6)], <add> self.data = np.rec.fromrecords([(1,2,3),(4,5,6)], <ide> dtype=[("col1", "<i4"), <ide> ("col2", "<i4"), <ide> ("col3", "<i4")])
1
Javascript
Javascript
remove usage of require('util') in `per_thread.js`
4a07a62d04b219ca72271f7cda0880a2a4300d05
<ide><path>lib/internal/process/per_thread.js <ide> const { <ide> ERR_UNKNOWN_SIGNAL <ide> } <ide> } = require('internal/errors'); <del>const util = require('util'); <add>const format = require('internal/util/inspect').format; <ide> const constants = internalBinding('constants').os.signals; <ide> <ide> function assert(x, msg) { <ide> function wrapProcessMethods(binding) { <ide> } = binding; <ide> <ide> function _rawDebug(...args) { <del> binding._rawDebug(util.format.apply(null, args)); <add> binding._rawDebug(format.apply(null, args)); <ide> } <ide> <ide> // Create the argument array that will be passed to the native function.
1
Python
Python
fix typo in recurrent
1c6ab36c63044199c2219e9c9cb1f03e1b54361f
<ide><path>keras/layers/recurrent.py <ide> def build(self): <ide> raise Exception('If a RNN is stateful, a complete ' + <ide> 'input_shape must be provided ' + <ide> '(including batch size).') <del> self.states = [K.zeros(input_shape[0], self.output_dim)] <add> self.states = [K.zeros((input_shape[0], self.output_dim))] <ide> else: <ide> # initial states: all-zero tensor of shape (output_dim) <ide> self.states = [None]
1
Go
Go
move docker rmi to a job
564e6bc7802b606d829a498eee0c2bb8ce4032e1
<ide><path>api.go <ide> func deleteImages(srv *Server, version float64, w http.ResponseWriter, r *http.R <ide> if vars == nil { <ide> return fmt.Errorf("Missing parameter") <ide> } <del> name := vars["name"] <del> imgs, err := srv.ImageDelete(name, version > 1.1) <del> if err != nil { <add> var ( <add> buffer = bytes.NewBuffer(nil) <add> job = srv.Eng.Job("image_delete", vars["name"]) <add> ) <add> job.Stdout.Add(buffer) <add> job.SetenvBool("autoPrune", version > 1.1) <add> if err := job.Run(); err != nil { <ide> return err <ide> } <del> if imgs != nil { <del> if len(imgs) != 0 { <del> return writeJSON(w, http.StatusOK, imgs) <add> <add> outs := engine.NewTable("", 0) <add> if _, err := outs.ReadFrom(buffer); err != nil { <add> return err <add> } <add> <add> if len(outs.Data) != 0 { <add> var err error <add> if version < 1.9 { <add> _, err = outs.WriteTo(w) <add> } else { <add> _, err = outs.WriteListTo(w) <ide> } <del> return fmt.Errorf("Conflict, %s wasn't deleted", name) <add> return err <ide> } <del> w.WriteHeader(http.StatusNoContent) <del> return nil <add> return fmt.Errorf("Conflict, %s wasn't deleted", vars["name"]) <ide> } <ide> <ide> func postContainersStart(srv *Server, version float64, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <ide><path>commands.go <ide> func (cli *DockerCli) CmdRmi(args ...string) error { <ide> fmt.Fprintf(cli.err, "%s\n", err) <ide> encounteredError = fmt.Errorf("Error: failed to remove one or more images") <ide> } else { <del> var outs []APIRmi <del> err = json.Unmarshal(body, &outs) <del> if err != nil { <add> outs := engine.NewTable("Created", 0) <add> if _, err := outs.ReadFrom(bytes.NewReader(body)); err != nil { <ide> fmt.Fprintf(cli.err, "%s\n", err) <ide> encounteredError = fmt.Errorf("Error: failed to remove one or more images") <ide> continue <ide> } <del> for _, out := range outs { <del> if out.Deleted != "" { <del> fmt.Fprintf(cli.out, "Deleted: %s\n", out.Deleted) <add> for _, out := range outs.Data { <add> if out.Get("Deleted") != "" { <add> fmt.Fprintf(cli.out, "Deleted: %s\n", out.Get("Deleted")) <ide> } else { <del> fmt.Fprintf(cli.out, "Untagged: %s\n", out.Untagged) <add> fmt.Fprintf(cli.out, "Untagged: %s\n", out.Get("Untagged")) <ide> } <ide> } <ide> } <ide><path>integration/commands_test.go <ide> func TestContainerOrphaning(t *testing.T) { <ide> buildSomething(template2, imageName) <ide> <ide> // remove the second image by name <del> resp, err := srv.ImageDelete(imageName, true) <add> resp, err := srv.DeleteImage(imageName, true) <ide> <ide> // see if we deleted the first image (and orphaned the container) <del> for _, i := range resp { <del> if img1 == i.Deleted { <add> for _, i := range resp.Data { <add> if img1 == i.Get("Deleted") { <ide> t.Fatal("Orphaned image with container") <ide> } <ide> } <ide><path>integration/runtime_test.go <ide> func cleanup(eng *engine.Engine, t *testing.T) error { <ide> } <ide> for _, image := range images.Data { <ide> if image.Get("ID") != unitTestImageID { <del> mkServerFromEngine(eng, t).ImageDelete(image.Get("ID"), false) <add> mkServerFromEngine(eng, t).DeleteImage(image.Get("ID"), false) <ide> } <ide> } <ide> return nil <ide><path>integration/server_test.go <ide> func TestImageTagImageDelete(t *testing.T) { <ide> t.Errorf("Expected %d images, %d found", nExpected, nActual) <ide> } <ide> <del> if _, err := srv.ImageDelete("utest/docker:tag2", true); err != nil { <add> if _, err := srv.DeleteImage("utest/docker:tag2", true); err != nil { <ide> t.Fatal(err) <ide> } <ide> <ide> func TestImageTagImageDelete(t *testing.T) { <ide> t.Errorf("Expected %d images, %d found", nExpected, nActual) <ide> } <ide> <del> if _, err := srv.ImageDelete("utest:5000/docker:tag3", true); err != nil { <add> if _, err := srv.DeleteImage("utest:5000/docker:tag3", true); err != nil { <ide> t.Fatal(err) <ide> } <ide> <ide> func TestImageTagImageDelete(t *testing.T) { <ide> nExpected = len(initialImages.Data[0].GetList("RepoTags")) + 1 <ide> nActual = len(images.Data[0].GetList("RepoTags")) <ide> <del> if _, err := srv.ImageDelete("utest:tag1", true); err != nil { <add> if _, err := srv.DeleteImage("utest:tag1", true); err != nil { <ide> t.Fatal(err) <ide> } <ide> <ide> func TestRmi(t *testing.T) { <ide> t.Fatalf("Expected 2 new images, found %d.", images.Len()-initialImages.Len()) <ide> } <ide> <del> _, err = srv.ImageDelete(imageID, true) <add> _, err = srv.DeleteImage(imageID, true) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide> func TestDeleteTagWithExistingContainers(t *testing.T) { <ide> } <ide> <ide> // Try to remove the tag <del> imgs, err := srv.ImageDelete("utest:tag1", true) <add> imgs, err := srv.DeleteImage("utest:tag1", true) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide> <del> if len(imgs) != 1 { <del> t.Fatalf("Should only have deleted one untag %d", len(imgs)) <add> if len(imgs.Data) != 1 { <add> t.Fatalf("Should only have deleted one untag %d", len(imgs.Data)) <ide> } <ide> <del> untag := imgs[0] <del> <del> if untag.Untagged != unitTestImageID { <del> t.Fatalf("Expected %s got %s", unitTestImageID, untag.Untagged) <add> if untag := imgs.Data[0].Get("Untagged"); untag != unitTestImageID { <add> t.Fatalf("Expected %s got %s", unitTestImageID, untag) <ide> } <ide> } <ide><path>server.go <ide> func (srv *Server) ImageExport(job *engine.Job) engine.Status { <ide> job.Error(err) <ide> return engine.StatusErr <ide> } <add> if err := job.Eng.Register("image_delete", srv.ImageDelete); err != nil { <add> job.Error(err) <add> return engine.StatusErr <add> } <ide> return engine.StatusOK <ide> } <ide> <ide> func (srv *Server) ContainerDestroy(job *engine.Job) engine.Status { <ide> <ide> var ErrImageReferenced = errors.New("Image referenced by a repository") <ide> <del>func (srv *Server) deleteImageAndChildren(id string, imgs *[]APIRmi, byParents map[string][]*Image) error { <add>func (srv *Server) deleteImageAndChildren(id string, imgs *engine.Table, byParents map[string][]*Image) error { <ide> // If the image is referenced by a repo, do not delete <ide> if len(srv.runtime.repositories.ByID()[id]) != 0 { <ide> return ErrImageReferenced <ide> func (srv *Server) deleteImageAndChildren(id string, imgs *[]APIRmi, byParents m <ide> if err != nil { <ide> return err <ide> } <del> *imgs = append(*imgs, APIRmi{Deleted: id}) <add> out := &engine.Env{} <add> out.Set("Deleted", id) <add> imgs.Add(out) <ide> srv.LogEvent("delete", id, "") <ide> return nil <ide> } <ide> return nil <ide> } <ide> <del>func (srv *Server) deleteImageParents(img *Image, imgs *[]APIRmi) error { <add>func (srv *Server) deleteImageParents(img *Image, imgs *engine.Table) error { <ide> if img.Parent != "" { <ide> parent, err := srv.runtime.graph.Get(img.Parent) <ide> if err != nil { <ide> func (srv *Server) deleteImageParents(img *Image, imgs *[]APIRmi) error { <ide> return nil <ide> } <ide> <del>func (srv *Server) deleteImage(img *Image, repoName, tag string) ([]APIRmi, error) { <add>func (srv *Server) DeleteImage(name string, autoPrune bool) (*engine.Table, error) { <ide> var ( <del> imgs = []APIRmi{} <del> tags = []string{} <add> repoName, tag string <add> img, err = srv.runtime.repositories.LookupImage(name) <add> imgs = engine.NewTable("", 0) <add> tags = []string{} <ide> ) <ide> <add> if err != nil { <add> return nil, fmt.Errorf("No such image: %s", name) <add> } <add> <add> // FIXME: What does autoPrune mean ? <add> if !autoPrune { <add> if err := srv.runtime.graph.Delete(img.ID); err != nil { <add> return nil, fmt.Errorf("Cannot delete image %s: %s", name, err) <add> } <add> return nil, nil <add> } <add> <add> if !strings.Contains(img.ID, name) { <add> repoName, tag = utils.ParseRepositoryTag(name) <add> } <add> <add> // If we have a repo and the image is not referenced anywhere else <add> // then just perform an untag and do not validate. <add> // <add> // i.e. only validate if we are performing an actual delete and not <add> // an untag op <add> if repoName != "" && len(srv.runtime.repositories.ByID()[img.ID]) == 1 { <add> // Prevent deletion if image is used by a container <add> if err := srv.canDeleteImage(img.ID); err != nil { <add> return nil, err <add> } <add> } <add> <ide> //If delete by id, see if the id belong only to one repository <ide> if repoName == "" { <ide> for _, repoAndTag := range srv.runtime.repositories.ByID()[img.ID] { <ide> func (srv *Server) deleteImage(img *Image, repoName, tag string) ([]APIRmi, erro <ide> return nil, err <ide> } <ide> if tagDeleted { <del> imgs = append(imgs, APIRmi{Untagged: img.ID}) <add> out := &engine.Env{} <add> out.Set("Untagged", img.ID) <add> imgs.Add(out) <ide> srv.LogEvent("untag", img.ID, "") <ide> } <ide> } <ide> <ide> if len(srv.runtime.repositories.ByID()[img.ID]) == 0 { <del> if err := srv.deleteImageAndChildren(img.ID, &imgs, nil); err != nil { <add> if err := srv.deleteImageAndChildren(img.ID, imgs, nil); err != nil { <ide> if err != ErrImageReferenced { <ide> return imgs, err <ide> } <del> } else if err := srv.deleteImageParents(img, &imgs); err != nil { <add> } else if err := srv.deleteImageParents(img, imgs); err != nil { <ide> if err != ErrImageReferenced { <ide> return imgs, err <ide> } <ide> func (srv *Server) deleteImage(img *Image, repoName, tag string) ([]APIRmi, erro <ide> return imgs, nil <ide> } <ide> <del>func (srv *Server) ImageDelete(name string, autoPrune bool) ([]APIRmi, error) { <del> var ( <del> repository, tag string <del> img, err = srv.runtime.repositories.LookupImage(name) <del> ) <del> if err != nil { <del> return nil, fmt.Errorf("No such image: %s", name) <del> } <del> <del> // FIXME: What does autoPrune mean ? <del> if !autoPrune { <del> if err := srv.runtime.graph.Delete(img.ID); err != nil { <del> return nil, fmt.Errorf("Cannot delete image %s: %s", name, err) <del> } <del> return nil, nil <add>func (srv *Server) ImageDelete(job *engine.Job) engine.Status { <add> if n := len(job.Args); n != 1 { <add> job.Errorf("Usage: %s IMAGE", job.Name) <add> return engine.StatusErr <ide> } <ide> <del> if !strings.Contains(img.ID, name) { <del> repository, tag = utils.ParseRepositoryTag(name) <add> imgs, err := srv.DeleteImage(job.Args[0], job.GetenvBool("autoPrune")) <add> if err != nil { <add> job.Error(err) <add> return engine.StatusErr <ide> } <del> <del> // If we have a repo and the image is not referenced anywhere else <del> // then just perform an untag and do not validate. <del> // <del> // i.e. only validate if we are performing an actual delete and not <del> // an untag op <del> if repository != "" && len(srv.runtime.repositories.ByID()[img.ID]) == 1 { <del> // Prevent deletion if image is used by a container <del> if err := srv.canDeleteImage(img.ID); err != nil { <del> return nil, err <del> } <add> if _, err := imgs.WriteTo(job.Stdout); err != nil { <add> job.Error(err) <add> return engine.StatusErr <ide> } <del> return srv.deleteImage(img, repository, tag) <add> return engine.StatusOK <ide> } <ide> <ide> func (srv *Server) canDeleteImage(imgID string) error {
6
Text
Text
add content in mutable section of lists
3189751ae78026ac4c82bda07943175bfdc2f002
<ide><path>guide/english/python/lists/index.md <ide> Also, we can do this: <ide> ``` <ide> **Mutable:** <ide> <del>`lists` are mutable containers. Mutable containers are containers that allow changes to which objects are contained by the container. **TODO: ADD MORE?** <add>`lists` are mutable containers. Mutable containers are containers that allow changes to which objects are contained by the container. <add> <add>We can modify the contents of a list after we have created it, which isn't possible in the case of immutable containers, like tuples. <add> <add>```python <add>>>> L = [1, 2, 3, 4, 6] <add>>>> L[4] = 5 <add>>>> print(L) <add>[1, 2, 3, 4, 5] <add>``` <add>We see that the 4th element in the list `L` has been modified. This property of lists is quite convenient, but it can also be deceiving if we don't keep track of what we're doing. <add>Suppose we create a list and assign a value to it. <add>```python <add>>>> List_old = [1, 2, 3] <add>``` <add>Python binds the `List_old` list to the value `[1, 2, 3]`. Now, we define a new list named `List_new` and assign to it the value `List_old`. <add>```python <add>>>> List_new = List_old <add>``` <add>This binds `List_new` to the same object that `List_old` was bound to, i.e., `[1, 2, 3]`. <add> <add>![listmutability](https://user-images.githubusercontent.com/27547933/47269591-e4241b80-d57d-11e8-8487-3653bed30b5f.jpg) <add> <add>Since both the lists are pointing to the same object, if we modify one, the other gets modified as well. <add>```python <add>>>> List_new.append(9) <add>>>> print(List_old) <add>[1, 2, 3, 4, 5, 9] <add>``` <add>We see that adding the value *9* to `List_new` also adds the same value to `List_old`. <ide> <ide> _Re-arranging elements in a list_ <ide>
1
Python
Python
modify config before super().__init__
32eb29fef9e73a0ade63dcc86c1fceb0bba68a5b
<ide><path>src/transformers/models/bart/modeling_bart.py <ide> def forward(self, *args, **kwargs): <ide> <ide> class BartForCausalLM(BartPretrainedModel): <ide> def __init__(self, config): <del> super().__init__(config) <ide> config = copy.deepcopy(config) <ide> config.is_decoder = True <ide> config.is_encoder_decoder = False <add> super().__init__(config) <ide> self.model = BartDecoderWrapper(config) <ide> <ide> self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) <ide><path>src/transformers/models/bigbird_pegasus/modeling_bigbird_pegasus.py <ide> def forward(self, *args, **kwargs): <ide> # Copied from transformers.models.bart.modeling_bart.BartForCausalLM with Bart->BigBirdPegasus, 'facebook/bart-large'->"google/bigbird-pegasus-large-arxiv" <ide> class BigBirdPegasusForCausalLM(BigBirdPegasusPreTrainedModel): <ide> def __init__(self, config): <del> super().__init__(config) <ide> config = copy.deepcopy(config) <ide> config.is_decoder = True <ide> config.is_encoder_decoder = False <add> super().__init__(config) <ide> self.model = BigBirdPegasusDecoderWrapper(config) <ide> <ide> self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) <ide><path>src/transformers/models/blenderbot/modeling_blenderbot.py <ide> def forward(self, *args, **kwargs): <ide> # Copied from transformers.models.bart.modeling_bart.BartForCausalLM with Bart->Blenderbot <ide> class BlenderbotForCausalLM(BlenderbotPreTrainedModel): <ide> def __init__(self, config): <del> super().__init__(config) <ide> config = copy.deepcopy(config) <ide> config.is_decoder = True <ide> config.is_encoder_decoder = False <add> super().__init__(config) <ide> self.model = BlenderbotDecoderWrapper(config) <ide> <ide> self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) <ide><path>src/transformers/models/blenderbot_small/modeling_blenderbot_small.py <ide> def forward(self, *args, **kwargs): <ide> # Copied from transformers.models.bart.modeling_bart.BartForCausalLM with Bart->BlenderbotSmall <ide> class BlenderbotSmallForCausalLM(BlenderbotSmallPreTrainedModel): <ide> def __init__(self, config): <del> super().__init__(config) <ide> config = copy.deepcopy(config) <ide> config.is_decoder = True <ide> config.is_encoder_decoder = False <add> super().__init__(config) <ide> self.model = BlenderbotSmallDecoderWrapper(config) <ide> <ide> self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) <ide><path>src/transformers/models/marian/modeling_marian.py <ide> def forward(self, *args, **kwargs): <ide> # Copied from transformers.models.bart.modeling_bart.BartForCausalLM with Bart->Marian <ide> class MarianForCausalLM(MarianPreTrainedModel): <ide> def __init__(self, config): <del> super().__init__(config) <ide> config = copy.deepcopy(config) <ide> config.is_decoder = True <ide> config.is_encoder_decoder = False <add> super().__init__(config) <ide> self.model = MarianDecoderWrapper(config) <ide> <ide> self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) <ide><path>src/transformers/models/mbart/modeling_mbart.py <ide> def forward(self, *args, **kwargs): <ide> # Copied from transformers.models.bart.modeling_bart.BartForCausalLM with Bart->MBart <ide> class MBartForCausalLM(MBartPreTrainedModel): <ide> def __init__(self, config): <del> super().__init__(config) <ide> config = copy.deepcopy(config) <ide> config.is_decoder = True <ide> config.is_encoder_decoder = False <add> super().__init__(config) <ide> self.model = MBartDecoderWrapper(config) <ide> <ide> self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) <ide><path>src/transformers/models/pegasus/modeling_pegasus.py <ide> def forward(self, *args, **kwargs): <ide> <ide> class PegasusForCausalLM(PegasusPreTrainedModel): <ide> def __init__(self, config): <del> super().__init__(config) <ide> config = copy.deepcopy(config) <ide> config.is_decoder = True <ide> config.is_encoder_decoder = False <add> super().__init__(config) <ide> self.model = PegasusDecoderWrapper(config) <ide> <ide> self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) <ide><path>src/transformers/models/speech_to_text_2/modeling_speech_to_text_2.py <ide> def forward(self, *args, **kwargs): <ide> ) <ide> class Speech2Text2ForCausalLM(Speech2Text2PreTrainedModel): <ide> def __init__(self, config): <del> super().__init__(config) <ide> config = copy.deepcopy(config) <ide> config.is_decoder = True <ide> config.is_encoder_decoder = False <add> super().__init__(config) <ide> self.model = Speech2Text2DecoderWrapper(config) <ide> <ide> self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) <ide><path>src/transformers/models/trocr/modeling_trocr.py <ide> def forward(self, *args, **kwargs): <ide> ) <ide> class TrOCRForCausalLM(TrOCRPreTrainedModel): <ide> def __init__(self, config): <del> super().__init__(config) <ide> config = copy.deepcopy(config) <ide> config.is_decoder = True <ide> config.is_encoder_decoder = False <add> super().__init__(config) <ide> self.model = TrOCRDecoderWrapper(config) <ide> <ide> self.output_projection = nn.Linear(config.hidden_size, config.vocab_size, bias=False) <ide><path>templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_{{cookiecutter.lowercase_modelname}}.py <ide> def forward(self, *args, **kwargs): <ide> # Copied from transformers.models.bart.modeling_bart.BartForCausalLM with Bart->{{cookiecutter.camelcase_modelname}} <ide> class {{cookiecutter.camelcase_modelname}}ForCausalLM({{cookiecutter.camelcase_modelname}}PreTrainedModel): <ide> def __init__(self, config): <del> super().__init__(config) <ide> config = copy.deepcopy(config) <ide> config.is_decoder = True <ide> config.is_encoder_decoder = False <add> super().__init__(config) <ide> self.model = {{cookiecutter.camelcase_modelname}}DecoderWrapper(config) <ide> <ide> self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
10
Javascript
Javascript
fix spec title for angular.formatter.index
da4b8a74c3c84aeccf2ecb8b5d74d22a579f2438
<ide><path>src/formatters.js <ide> angularFormatter.trim = formatter( <ide> * </div> <ide> * <ide> * @scenario <del> * it('should format trim', function(){ <add> * it('should retrieve object by index', function(){ <ide> * expect(binding('currentUser.password')).toEqual('guest'); <ide> * select('currentUser').option('2'); <ide> * expect(binding('currentUser.password')).toEqual('abc');
1
Go
Go
fix escape-keys by preserving input if invalid
0fb6190243d6101f96283e487cd4911142a05483
<ide><path>container/container.go <ide> func copyEscapable(dst io.Writer, src io.ReadCloser, keys []byte) (written int64 <ide> nr, er := src.Read(buf) <ide> if nr > 0 { <ide> // ---- Docker addition <add> preservBuf := []byte{} <ide> for i, key := range keys { <add> preservBuf = append(preservBuf, buf[0:nr]...) <ide> if nr != 1 || buf[0] != key { <ide> break <ide> } <ide> func copyEscapable(dst io.Writer, src io.ReadCloser, keys []byte) (written int64 <ide> } <ide> nr, er = src.Read(buf) <ide> } <del> // ---- End of docker <del> nw, ew := dst.Write(buf[0:nr]) <add> var nw int <add> var ew error <add> if len(preservBuf) > 0 { <add> nw, ew = dst.Write(preservBuf) <add> nr = len(preservBuf) <add> } else { <add> // ---- End of docker <add> nw, ew = dst.Write(buf[0:nr]) <add> } <ide> if nw > 0 { <ide> written += int64(nw) <ide> } <ide><path>integration-cli/docker_cli_run_unix_test.go <ide> func (s *DockerSuite) TestRunAttachDetachKeysOverrideConfig(c *check.C) { <ide> c.Assert(running, checker.Equals, "true", check.Commentf("expected container to still be running")) <ide> } <ide> <add>func (s *DockerSuite) TestRunAttachInvalidDetachKeySequencePreserved(c *check.C) { <add> name := "attach-detach" <add> keyA := []byte{97} <add> keyB := []byte{98} <add> <add> dockerCmd(c, "run", "--name", name, "-itd", "busybox", "cat") <add> <add> cmd := exec.Command(dockerBinary, "attach", "--detach-keys='a,b,c'", name) <add> stdout, err := cmd.StdoutPipe() <add> if err != nil { <add> c.Fatal(err) <add> } <add> cpty, tty, err := pty.Open() <add> if err != nil { <add> c.Fatal(err) <add> } <add> defer cpty.Close() <add> cmd.Stdin = tty <add> if err := cmd.Start(); err != nil { <add> c.Fatal(err) <add> } <add> c.Assert(waitRun(name), check.IsNil) <add> <add> // Invalid escape sequence aba, should print aba in output <add> if _, err := cpty.Write(keyA); err != nil { <add> c.Fatal(err) <add> } <add> time.Sleep(100 * time.Millisecond) <add> if _, err := cpty.Write(keyB); err != nil { <add> c.Fatal(err) <add> } <add> time.Sleep(100 * time.Millisecond) <add> if _, err := cpty.Write(keyA); err != nil { <add> c.Fatal(err) <add> } <add> time.Sleep(100 * time.Millisecond) <add> if _, err := cpty.Write([]byte("\n")); err != nil { <add> c.Fatal(err) <add> } <add> <add> out, err := bufio.NewReader(stdout).ReadString('\n') <add> if err != nil { <add> c.Fatal(err) <add> } <add> if strings.TrimSpace(out) != "aba" { <add> c.Fatalf("expected 'aba', got %q", out) <add> } <add>} <add> <ide> // "test" should be printed <ide> func (s *DockerSuite) TestRunWithCPUQuota(c *check.C) { <ide> testRequires(c, cpuCfsQuota)
2
Javascript
Javascript
avoid memory leak in lazyset
ada11a286dfff0f835f247d2a3485b3dec5a4c07
<ide><path>lib/util/LazySet.js <ide> class LazySet { <ide> } else { <ide> this._toMerge.add(iterable); <ide> this._needMerge = true; <add> // Avoid a memory leak <add> if (this._toMerge.size > 100000) this._merge(); <ide> } <ide> return this; <ide> }
1
Ruby
Ruby
extract attr_rw from formula for reuse
b97b013fcea50c783faf85e7c12f7844eb86e4b3
<ide><path>Library/Homebrew/compilers.rb <ide> def build <ide> <ide> class CompilerFailure <ide> attr_reader :compiler <add> attr_rw :build, :cause <ide> <ide> def initialize compiler, &block <ide> @compiler = compiler <ide> instance_eval(&block) if block_given? <del> @build ||= 9999 <del> end <del> <del> def build val=nil <del> val.nil? ? @build.to_i : @build = val.to_i <del> end <del> <del> def cause val=nil <del> val.nil? ? @cause : @cause = val <add> @build = (@build || 9999).to_i <ide> end <ide> end <ide> <ide><path>Library/Homebrew/extend/module.rb <add>class Module <add> def attr_rw(*attrs) <add> attrs.each do |attr| <add> module_eval <<-EOS, __FILE__, __LINE__ + 1 <add> def #{attr}(val=nil) <add> val.nil? ? @#{attr} : @#{attr} = val <add> end <add> EOS <add> end <add> end <add>end <ide><path>Library/Homebrew/formula.rb <ide> def self.method_added method <ide> class << self <ide> # The methods below define the formula DSL. <ide> <del> def self.attr_rw(*attrs) <del> attrs.each do |attr| <del> class_eval <<-EOS, __FILE__, __LINE__ + 1 <del> def #{attr}(val=nil) <del> val.nil? ? @#{attr} : @#{attr} = val <del> end <del> EOS <del> end <del> end <del> <ide> attr_rw :homepage, :keg_only_reason, :skip_clean_all, :cc_failures <ide> attr_rw :plist_startup, :plist_manual <ide> <ide><path>Library/Homebrew/formula_support.rb <ide> def verify_download_integrity fn <ide> <ide> class Bottle < SoftwareSpec <ide> attr_writer :url <add> attr_rw :root_url, :prefix, :cellar, :revision <ide> <ide> def initialize <ide> super <ide> def #{cksum}(val) <ide> end <ide> EOS <ide> end <del> <del> def root_url val=nil <del> val.nil? ? @root_url : @root_url = val <del> end <del> <del> def prefix val=nil <del> val.nil? ? @prefix : @prefix = val <del> end <del> <del> def cellar val=nil <del> val.nil? ? @cellar : @cellar = val <del> end <del> <del> def revision val=nil <del> val.nil? ? @revision : @revision = val <del> end <ide> end <ide> <ide> <ide><path>Library/Homebrew/global.rb <add>require 'extend/module' <ide> require 'extend/fileutils' <ide> require 'extend/pathname' <ide> require 'extend/ARGV' <ide><path>Library/Homebrew/requirement.rb <ide> def infer_env_modification(o) <ide> end <ide> <ide> class << self <del> # The default formula to install to satisfy this requirement. <del> def default_formula(val=nil) <del> val.nil? ? @default_formula : @default_formula = val.to_s <del> end <del> <del> def fatal(val=nil) <del> val.nil? ? @fatal : @fatal = val <del> end <del> <del> def build(val=nil) <del> val.nil? ? @build : @build = val <del> end <add> attr_rw :fatal, :build, :default_formula <ide> <ide> def satisfy(options={}, &block) <ide> @satisfied ||= Requirement::Satisfier.new(options, &block) <ide><path>Library/Homebrew/test/testing_env.rb <ide> ABS__FILE__ = File.expand_path(__FILE__) <ide> $:.push(File.expand_path(__FILE__+'/../..')) <ide> <add>require 'extend/module' <ide> require 'extend/fileutils' <ide> require 'extend/pathname' <ide> require 'extend/string' <add>require 'extend/symbol' <ide> require 'exceptions' <ide> require 'utils' <ide> require 'rbconfig'
7
Go
Go
remove head req & pass down response
c47ebe7a351bc639028cd48aed9d2fa2310a2a65
<ide><path>registry/registry.go <ide> func (r *Registry) GetRemoteImageJSON(imgID, registry string, token []string) ([ <ide> <ide> func (r *Registry) GetRemoteImageLayer(imgID, registry string, token []string, imgSize int64) (io.ReadCloser, error) { <ide> var ( <del> retries = 5 <del> headRes *http.Response <del> client *http.Client <del> hasResume bool = false <del> imageURL = fmt.Sprintf("%simages/%s/layer", registry, imgID) <add> retries = 5 <add> client *http.Client <add> res *http.Response <add> imageURL = fmt.Sprintf("%simages/%s/layer", registry, imgID) <ide> ) <del> headReq, err := r.reqFactory.NewRequest("HEAD", imageURL, nil) <add> <add> req, err := r.reqFactory.NewRequest("GET", imageURL, nil) <ide> if err != nil { <ide> return nil, fmt.Errorf("Error while getting from the server: %s\n", err) <ide> } <del> <del> setTokenAuth(headReq, token) <add> setTokenAuth(req, token) <ide> for i := 1; i <= retries; i++ { <del> headRes, client, err = r.doRequest(headReq) <del> if err != nil && i == retries { <del> return nil, fmt.Errorf("Eror while making head request: %s\n", err) <del> } else if err != nil { <add> res, client, err = r.doRequest(req) <add> if err != nil { <add> res.Body.Close() <add> if i == retries { <add> return nil, fmt.Errorf("Server error: Status %d while fetching image layer (%s)", <add> res.StatusCode, imgID) <add> } <ide> time.Sleep(time.Duration(i) * 5 * time.Second) <ide> continue <ide> } <ide> break <ide> } <ide> <del> if headRes.Header.Get("Accept-Ranges") == "bytes" && imgSize > 0 { <del> hasResume = true <del> } <del> <del> req, err := r.reqFactory.NewRequest("GET", imageURL, nil) <del> if err != nil { <del> return nil, fmt.Errorf("Error while getting from the server: %s\n", err) <del> } <del> setTokenAuth(req, token) <del> if hasResume { <del> utils.Debugf("server supports resume") <del> return utils.ResumableRequestReader(client, req, 5, imgSize), nil <del> } <del> utils.Debugf("server doesn't support resume") <del> res, _, err := r.doRequest(req) <del> if err != nil { <del> return nil, err <del> } <ide> if res.StatusCode != 200 { <ide> res.Body.Close() <ide> return nil, fmt.Errorf("Server error: Status %d while fetching image layer (%s)", <ide> res.StatusCode, imgID) <ide> } <add> <add> if res.Header.Get("Accept-Ranges") == "bytes" && imgSize > 0 { <add> utils.Debugf("server supports resume") <add> return utils.ResumableRequestReaderWithInitialResponse(client, req, 5, imgSize, res), nil <add> } <add> utils.Debugf("server doesn't support resume") <ide> return res.Body, nil <ide> } <ide>
1
Text
Text
add missing links to features.md
62076a4bc8c2cc257336331289443b9dbd5cb850
<ide><path>FEATURES.md <ide> for a detailed explanation. <ide> Enables `Ember.run.bind` which is ember run-loop aware variation of <ide> jQuery.proxy. Useful for integrating with 3rd party callbacks. <ide> <add> Added in [161113](https://github.com/emberjs/ember.js/commit/161113a9e5fad7f6dfde09a053166a05660a0051). <add> <ide> * `ember-metal-is-blank` <ide> Adds `Ember.isBlank` method which returns true for an empty value or <ide> a whitespace string. <ide> for a detailed explanation. <ide> instead of waiting for the transition to run to completion, unless <ide> the transition was aborted/redirected within the same run loop. <ide> <add> Added in [#4122](https://github.com/emberjs/ember.js/pull/4122).
1
Mixed
Javascript
return this from clientrequest#destroy()
cad76da198ff59e16d3439cbdb5793750c01f382
<ide><path>doc/api/http.md <ide> is finished. <ide> ### `request.destroy([error])` <ide> <!-- YAML <ide> added: v0.3.0 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/32789 <add> description: The function returns `this` for consistency with other Readable <add> streams. <ide> --> <ide> <ide> * `error` {Error} Optional, an error to emit with `'error'` event. <ide><path>lib/_http_client.js <ide> ClientRequest.prototype.abort = function abort() { <ide> <ide> ClientRequest.prototype.destroy = function destroy(err) { <ide> if (this.destroyed) { <del> return; <add> return this; <ide> } <ide> this.destroyed = true; <ide> <ide> ClientRequest.prototype.destroy = function destroy(err) { <ide> } else if (err) { <ide> this[kError] = err; <ide> } <add> <add> return this; <ide> }; <ide> <ide> function _destroy(req, socket, err) { <ide><path>test/parallel/test-client-request-destroy.js <add>'use strict'; <add> <add>// Test that http.ClientRequest,prototype.destroy() returns `this`. <add>require('../common'); <add> <add>const assert = require('assert'); <add>const http = require('http'); <add>const clientRequest = new http.ClientRequest({ createConnection: () => {} }); <add> <add>assert.strictEqual(clientRequest.destroyed, false); <add>assert.strictEqual(clientRequest.destroy(), clientRequest); <add>assert.strictEqual(clientRequest.destroyed, true); <add>assert.strictEqual(clientRequest.destroy(), clientRequest);
3
Python
Python
drop unused import
c1a40c58999a3ca3dd667d092051dd719fc0588b
<ide><path>rest_framework/views.py <ide> from rest_framework.request import Request <ide> from rest_framework.settings import api_settings <ide> import re <del>import warnings <ide> <ide> <ide> def _remove_trailing_string(content, trailing):
1
Go
Go
wrap some errors
744940056d7335cad4b6785960ec0e5760d76807
<ide><path>client/request.go <ide> func (cli *Client) doRequest(ctx context.Context, req *http.Request) (serverResp <ide> } <ide> <ide> if cli.scheme == "https" && strings.Contains(err.Error(), "bad certificate") { <del> return serverResp, fmt.Errorf("The server probably has client authentication (--tlsverify) enabled. Please check your TLS client certification settings: %v", err) <add> return serverResp, errors.Wrap(err, "The server probably has client authentication (--tlsverify) enabled. Please check your TLS client certification settings") <ide> } <ide> <ide> // Don't decorate context sentinel errors; users may be comparing to <ide> func (cli *Client) checkResponseErr(serverResp serverResponse) error { <ide> if (cli.version == "" || versions.GreaterThan(cli.version, "1.23")) && ct == "application/json" { <ide> var errorResponse types.ErrorResponse <ide> if err := json.Unmarshal(body, &errorResponse); err != nil { <del> return fmt.Errorf("Error reading JSON: %v", err) <add> return errors.Wrap(err, "Error reading JSON") <ide> } <del> errorMessage = errorResponse.Message <add> errorMessage = strings.TrimSpace(errorResponse.Message) <ide> } else { <del> errorMessage = string(body) <add> errorMessage = strings.TrimSpace(string(body)) <ide> } <ide> <del> return fmt.Errorf("Error response from daemon: %s", strings.TrimSpace(errorMessage)) <add> return errors.Wrap(errors.New(errorMessage), "Error response from daemon") <ide> } <ide> <ide> func (cli *Client) addHeaders(req *http.Request, headers headers) *http.Request {
1
PHP
PHP
add message class for email
ffa43b6eaec52fce74e153b27a99f1d717948ac2
<ide><path>src/Mailer/Email.php <ide> namespace Cake\Mailer; <ide> <ide> use BadMethodCallException; <del>use Cake\Core\Configure; <ide> use Cake\Core\StaticConfigTrait; <ide> use Cake\Log\Log; <del>use Cake\Utility\Text; <ide> use Cake\View\ViewBuilder; <ide> use InvalidArgumentException; <ide> use JsonSerializable; <ide> class Email implements JsonSerializable, Serializable <ide> */ <ide> public const EMAIL_PATTERN = '/^((?:[\p{L}0-9.!#$%&\'*+\/=?^_`{|}~-]+)*@[\p{L}0-9-._]+)$/ui'; <ide> <del> /** <del> * Recipient of the email <del> * <del> * @var array <del> */ <del> protected $_to = []; <del> <del> /** <del> * The mail which the email is sent from <del> * <del> * @var array <del> */ <del> protected $_from = []; <del> <del> /** <del> * The sender email <del> * <del> * @var array <del> */ <del> protected $_sender = []; <del> <del> /** <del> * The email the recipient will reply to <del> * <del> * @var array <del> */ <del> protected $_replyTo = []; <del> <del> /** <del> * The read receipt email <del> * <del> * @var array <del> */ <del> protected $_readReceipt = []; <del> <del> /** <del> * The mail that will be used in case of any errors like <del> * - Remote mailserver down <del> * - Remote user has exceeded his quota <del> * - Unknown user <del> * <del> * @var array <del> */ <del> protected $_returnPath = []; <del> <del> /** <del> * Carbon Copy <del> * <del> * List of email's that should receive a copy of the email. <del> * The Recipient WILL be able to see this list <del> * <del> * @var array <del> */ <del> protected $_cc = []; <del> <del> /** <del> * Blind Carbon Copy <del> * <del> * List of email's that should receive a copy of the email. <del> * The Recipient WILL NOT be able to see this list <del> * <del> * @var array <del> */ <del> protected $_bcc = []; <del> <del> /** <del> * Message ID <del> * <del> * @var bool|string <del> */ <del> protected $_messageId = true; <del> <del> /** <del> * Domain for messageId generation. <del> * Needs to be manually set for CLI mailing as env('HTTP_HOST') is empty <del> * <del> * @var string <del> */ <del> protected $_domain = ''; <del> <del> /** <del> * The subject of the email <del> * <del> * @var string <del> */ <del> protected $_subject = ''; <del> <del> /** <del> * Associative array of a user defined headers <del> * Keys will be prefixed 'X-' as per RFC2822 Section 4.7.5 <del> * <del> * @var array <del> */ <del> protected $_headers = []; <del> <del> /** <del> * Text message <del> * <del> * @var string <del> */ <del> protected $_textMessage = ''; <del> <del> /** <del> * Html message <del> * <del> * @var string <del> */ <del> protected $_htmlMessage = ''; <del> <del> /** <del> * Final message to send <del> * <del> * @var array <del> */ <del> protected $_message = []; <del> <del> /** <del> * Available formats to be sent. <del> * <del> * @var array <del> */ <del> protected $_emailFormatAvailable = [self::MESSAGE_TEXT, self::MESSAGE_HTML, self::MESSAGE_BOTH]; <del> <del> /** <del> * What format should the email be sent in <del> * <del> * @var string <del> */ <del> protected $_emailFormat = self::MESSAGE_TEXT; <del> <ide> /** <ide> * The transport instance to use for sending mail. <ide> * <ide> * @var \Cake\Mailer\AbstractTransport|null <ide> */ <ide> protected $_transport; <ide> <del> /** <del> * Charset the email body is sent in <del> * <del> * @var string <del> */ <del> protected $charset = 'utf-8'; <del> <del> /** <del> * Charset the email header is sent in <del> * If null, the $charset property will be used as default <del> * <del> * @var string|null <del> */ <del> protected $headerCharset; <del> <del> /** <del> * The email transfer encoding used. <del> * If null, the $charset property is used for determined the transfer encoding. <del> * <del> * @var string|null <del> */ <del> protected $transferEncoding; <del> <ide> /** <ide> * Email Renderer <ide> * <ide> * @var \Cake\Mailer\Renderer|null <ide> */ <ide> protected $renderer; <ide> <del> /** <del> * Available encoding to be set for transfer. <del> * <del> * @var array <del> */ <del> protected $_transferEncodingAvailable = [ <del> '7bit', <del> '8bit', <del> 'base64', <del> 'binary', <del> 'quoted-printable', <del> ]; <del> <del> /** <del> * The application wide charset, used to encode headers and body <del> * <del> * @var string|null <del> */ <del> protected $_appCharset; <del> <del> /** <del> * List of files that should be attached to the email. <del> * <del> * Only absolute paths <del> * <del> * @var array <del> */ <del> protected $_attachments = []; <del> <ide> /** <ide> * If set, boundary to use for multipart mime messages <ide> * <ide> * @var string|null <ide> */ <ide> protected $_boundary; <ide> <del> /** <del> * Contains the optional priority of the email. <del> * <del> * @var int|null <del> */ <del> protected $_priority; <del> <ide> /** <ide> * A copy of the configuration profile for this <ide> * instance. This copy can be modified with Email::profile(). <ide> class Email implements JsonSerializable, Serializable <ide> protected $_profile = []; <ide> <ide> /** <del> * 8Bit character sets <add> * Message instance. <ide> * <del> * @var array <del> */ <del> protected $_charset8bit = ['UTF-8', 'SHIFT_JIS']; <del> <del> /** <del> * Define Content-Type charset name <del> * <del> * @var array <add> * @var string <ide> */ <del> protected $_contentTypeCharset = [ <del> 'ISO-2022-JP-MS' => 'ISO-2022-JP', <del> ]; <add> protected $messageClass = Message::class; <ide> <ide> /** <del> * Regex for email validation <add> * Message instance. <ide> * <del> * If null, filter_var() will be used. Use the emailPattern() method <del> * to set a custom pattern.' <del> * <del> * @var string|null <add> * @var \Cake\Mailer\Message <ide> */ <del> protected $_emailPattern = self::EMAIL_PATTERN; <add> protected $message; <ide> <ide> /** <ide> * Constructor <ide> class Email implements JsonSerializable, Serializable <ide> */ <ide> public function __construct($config = null) <ide> { <del> $this->_appCharset = Configure::read('App.encoding'); <del> if ($this->_appCharset !== null) { <del> $this->charset = $this->_appCharset; <del> } <del> $this->_domain = preg_replace('/\:\d+$/', '', env('HTTP_HOST')); <del> if (empty($this->_domain)) { <del> $this->_domain = php_uname('n'); <add> $this->message = new $this->messageClass(); <add> <add> if ($config === null) { <add> $config = static::getConfig('default'); <ide> } <ide> <ide> $this->getRenderer()->viewBuilder() <ide> public function __construct($config = null) <ide> ->setLayout('default') <ide> ->setHelpers(['Html']); <ide> <del> if ($config === null) { <del> $config = static::getConfig('default'); <del> } <ide> if ($config) { <ide> $this->setProfile($config); <ide> } <del> if (empty($this->headerCharset)) { <del> $this->headerCharset = $this->charset; <del> } <ide> } <ide> <ide> /** <ide> * Clone Renderer instance when email object is cloned. <ide> * <ide> * @return void <ide> */ <del> public function __clone() <del> { <del> if ($this->renderer) { <del> $this->renderer = clone $this->renderer; <del> } <del> } <del> <del> /** <del> * Sets "from" address. <del> * <del> * @param string|array $email Null to get, String with email, <del> * Array with email as key, name as value or email as value (without name) <del> * @param string|null $name Name <del> * @return $this <del> * @throws \InvalidArgumentException <del> */ <del> public function setFrom($email, ?string $name = null): self <del> { <del> return $this->_setEmailSingle('_from', $email, $name, 'From requires only 1 email address.'); <del> } <del> <del> /** <del> * Gets "from" address. <del> * <del> * @return array <del> */ <del> public function getFrom(): array <del> { <del> return $this->_from; <del> } <del> <del> /** <del> * Sets "sender" address. <del> * <del> * @param string|array $email String with email, <del> * Array with email as key, name as value or email as value (without name) <del> * @param string|null $name Name <del> * @return $this <del> * @throws \InvalidArgumentException <del> */ <del> public function setSender($email, ?string $name = null): self <del> { <del> return $this->_setEmailSingle('_sender', $email, $name, 'Sender requires only 1 email address.'); <del> } <del> <del> /** <del> * Gets "sender" address. <del> * <del> * @return array <del> */ <del> public function getSender(): array <del> { <del> return $this->_sender; <del> } <del> <del> /** <del> * Sets "Reply-To" address. <del> * <del> * @param string|array $email String with email, <del> * Array with email as key, name as value or email as value (without name) <del> * @param string|null $name Name <del> * @return $this <del> * @throws \InvalidArgumentException <del> */ <del> public function setReplyTo($email, ?string $name = null): self <del> { <del> return $this->_setEmailSingle('_replyTo', $email, $name, 'Reply-To requires only 1 email address.'); <del> } <del> <del> /** <del> * Gets "Reply-To" address. <del> * <del> * @return array <del> */ <del> public function getReplyTo(): array <del> { <del> return $this->_replyTo; <del> } <del> <del> /** <del> * Sets Read Receipt (Disposition-Notification-To header). <del> * <del> * @param string|array $email String with email, <del> * Array with email as key, name as value or email as value (without name) <del> * @param string|null $name Name <del> * @return $this <del> * @throws \InvalidArgumentException <del> */ <del> public function setReadReceipt($email, ?string $name = null): self <del> { <del> return $this->_setEmailSingle( <del> '_readReceipt', <del> $email, <del> $name, <del> 'Disposition-Notification-To requires only 1 email address.' <del> ); <del> } <del> <del> /** <del> * Gets Read Receipt (Disposition-Notification-To header). <del> * <del> * @return array <del> */ <del> public function getReadReceipt(): array <del> { <del> return $this->_readReceipt; <del> } <del> <del> /** <del> * Return Path <del> * <del> * @param string|array $email String with email, <del> * Array with email as key, name as value or email as value (without name) <del> * @param string|null $name Name <del> * @return $this <del> * @throws \InvalidArgumentException <del> */ <del> public function setReturnPath($email, ?string $name = null): self <del> { <del> return $this->_setEmailSingle('_returnPath', $email, $name, 'Return-Path requires only 1 email address.'); <del> } <del> <del> /** <del> * Gets return path. <del> * <del> * @return array <del> */ <del> public function getReturnPath(): array <del> { <del> return $this->_returnPath; <del> } <del> <del> /** <del> * Sets "to" address. <del> * <del> * @param string|array $email String with email, <del> * Array with email as key, name as value or email as value (without name) <del> * @param string|null $name Name <del> * @return $this <del> */ <del> public function setTo($email, ?string $name = null): self <del> { <del> return $this->_setEmail('_to', $email, $name); <del> } <del> <del> /** <del> * Gets "to" address <del> * <del> * @return array <del> */ <del> public function getTo(): array <del> { <del> return $this->_to; <del> } <del> <del> /** <del> * Add To <del> * <del> * @param string|array $email Null to get, String with email, <del> * Array with email as key, name as value or email as value (without name) <del> * @param string|null $name Name <del> * @return $this <del> */ <del> public function addTo($email, ?string $name = null): self <del> { <del> return $this->_addEmail('_to', $email, $name); <del> } <del> <del> /** <del> * Sets "cc" address. <del> * <del> * @param string|array $email String with email, <del> * Array with email as key, name as value or email as value (without name) <del> * @param string|null $name Name <del> * @return $this <del> */ <del> public function setCc($email, ?string $name = null): self <del> { <del> return $this->_setEmail('_cc', $email, $name); <del> } <del> <del> /** <del> * Gets "cc" address. <del> * <del> * @return array <del> */ <del> public function getCc(): array <del> { <del> return $this->_cc; <del> } <del> <del> /** <del> * Add Cc <del> * <del> * @param string|array $email Null to get, String with email, <del> * Array with email as key, name as value or email as value (without name) <del> * @param string|null $name Name <del> * @return $this <del> */ <del> public function addCc($email, ?string $name = null): self <del> { <del> return $this->_addEmail('_cc', $email, $name); <del> } <del> <del> /** <del> * Sets "bcc" address. <del> * <del> * @param string|array $email String with email, <del> * Array with email as key, name as value or email as value (without name) <del> * @param string|null $name Name <del> * @return $this <del> */ <del> public function setBcc($email, ?string $name = null): self <del> { <del> return $this->_setEmail('_bcc', $email, $name); <del> } <del> <del> /** <del> * Gets "bcc" address. <del> * <del> * @return array <del> */ <del> public function getBcc(): array <del> { <del> return $this->_bcc; <del> } <del> <del> /** <del> * Add Bcc <del> * <del> * @param string|array $email Null to get, String with email, <del> * Array with email as key, name as value or email as value (without name) <del> * @param string|null $name Name <del> * @return $this <del> */ <del> public function addBcc($email, ?string $name = null): self <del> { <del> return $this->_addEmail('_bcc', $email, $name); <del> } <del> <del> /** <del> * Charset setter. <del> * <del> * @param string $charset Character set. <del> * @return $this <del> */ <del> public function setCharset(string $charset): self <del> { <del> $this->charset = $charset; <del> if (!$this->headerCharset) { <del> $this->headerCharset = $charset; <del> } <del> <del> return $this; <del> } <del> <del> /** <del> * Charset getter. <del> * <del> * @return string Charset <del> */ <del> public function getCharset(): string <del> { <del> return $this->charset; <del> } <del> <del> /** <del> * HeaderCharset setter. <del> * <del> * @param string|null $charset Character set. <del> * @return $this <del> */ <del> public function setHeaderCharset(?string $charset): self <del> { <del> $this->headerCharset = $charset; <del> <del> return $this; <del> } <del> <del> /** <del> * HeaderCharset getter. <del> * <del> * @return string|null Charset <del> */ <del> public function getHeaderCharset(): ?string <del> { <del> return $this->headerCharset; <del> } <del> <del> /** <del> * TransferEncoding setter. <del> * <del> * @param string|null $encoding Encoding set. <del> * @return $this <del> * @throws \InvalidArgumentException <del> */ <del> public function setTransferEncoding(?string $encoding): self <del> { <del> $encoding = strtolower($encoding); <del> if (!in_array($encoding, $this->_transferEncodingAvailable)) { <del> throw new InvalidArgumentException( <del> sprintf( <del> 'Transfer encoding not available. Can be : %s.', <del> implode(', ', $this->_transferEncodingAvailable) <del> ) <del> ); <del> } <del> $this->transferEncoding = $encoding; <del> <del> return $this; <del> } <del> <del> /** <del> * TransferEncoding getter. <del> * <del> * @return string|null Encoding <del> */ <del> public function getTransferEncoding(): ?string <del> { <del> return $this->transferEncoding; <del> } <del> <del> /** <del> * EmailPattern setter/getter <del> * <del> * @param string|null $regex The pattern to use for email address validation, <del> * null to unset the pattern and make use of filter_var() instead. <del> * @return $this <del> */ <del> public function setEmailPattern(?string $regex): self <del> { <del> $this->_emailPattern = $regex; <del> <del> return $this; <del> } <del> <del> /** <del> * EmailPattern setter/getter <del> * <del> * @return string|null <del> */ <del> public function getEmailPattern(): ?string <del> { <del> return $this->_emailPattern; <del> } <del> <del> /** <del> * Set email <del> * <del> * @param string $varName Property name <del> * @param string|array $email String with email, <del> * Array with email as key, name as value or email as value (without name) <del> * @param string|null $name Name <del> * @return $this <del> * @throws \InvalidArgumentException <del> */ <del> protected function _setEmail(string $varName, $email, ?string $name): self <del> { <del> if (!is_array($email)) { <del> $this->_validateEmail($email, $varName); <del> if ($name === null) { <del> $name = $email; <del> } <del> $this->{$varName} = [$email => $name]; <del> <del> return $this; <del> } <del> $list = []; <del> foreach ($email as $key => $value) { <del> if (is_int($key)) { <del> $key = $value; <del> } <del> $this->_validateEmail($key, $varName); <del> $list[$key] = $value; <del> } <del> $this->{$varName} = $list; <del> <del> return $this; <del> } <del> <del> /** <del> * Validate email address <del> * <del> * @param string $email Email address to validate <del> * @param string $context Which property was set <del> * @return void <del> * @throws \InvalidArgumentException If email address does not validate <del> */ <del> protected function _validateEmail(string $email, string $context): void <del> { <del> if ($this->_emailPattern === null) { <del> if (filter_var($email, FILTER_VALIDATE_EMAIL)) { <del> return; <del> } <del> } elseif (preg_match($this->_emailPattern, (string)$email)) { <del> return; <del> } <del> <del> $context = ltrim($context, '_'); <del> if ($email === '') { <del> throw new InvalidArgumentException(sprintf('The email set for "%s" is empty.', $context)); <del> } <del> throw new InvalidArgumentException(sprintf('Invalid email set for "%s". You passed "%s".', $context, $email)); <del> } <del> <del> /** <del> * Set only 1 email <del> * <del> * @param string $varName Property name <del> * @param string|array $email String with email, <del> * Array with email as key, name as value or email as value (without name) <del> * @param string|null $name Name <del> * @param string $throwMessage Exception message <del> * @return $this <del> * @throws \InvalidArgumentException <del> */ <del> protected function _setEmailSingle(string $varName, $email, ?string $name, string $throwMessage): self <del> { <del> if ($email === []) { <del> $this->{$varName} = $email; <del> <del> return $this; <del> } <del> <del> $current = $this->{$varName}; <del> $this->_setEmail($varName, $email, $name); <del> if (count($this->{$varName}) !== 1) { <del> $this->{$varName} = $current; <del> throw new InvalidArgumentException($throwMessage); <del> } <del> <del> return $this; <del> } <del> <del> /** <del> * Add email <del> * <del> * @param string $varName Property name <del> * @param string|array $email String with email, <del> * Array with email as key, name as value or email as value (without name) <del> * @param string|null $name Name <del> * @return $this <del> * @throws \InvalidArgumentException <del> */ <del> protected function _addEmail(string $varName, $email, ?string $name): self <del> { <del> if (!is_array($email)) { <del> $this->_validateEmail($email, $varName); <del> if ($name === null) { <del> $name = $email; <del> } <del> $this->{$varName}[$email] = $name; <del> <del> return $this; <del> } <del> $list = []; <del> foreach ($email as $key => $value) { <del> if (is_int($key)) { <del> $key = $value; <del> } <del> $this->_validateEmail($key, $varName); <del> $list[$key] = $value; <del> } <del> $this->{$varName} = array_merge($this->{$varName}, $list); <del> <del> return $this; <del> } <del> <del> /** <del> * Sets subject. <del> * <del> * @param string $subject Subject string. <del> * @return $this <del> */ <del> public function setSubject(string $subject): self <del> { <del> $this->_subject = $this->_encode($subject); <del> <del> return $this; <del> } <del> <del> /** <del> * Gets subject. <del> * <del> * @return string <del> */ <del> public function getSubject(): string <del> { <del> return $this->_subject; <del> } <del> <del> /** <del> * Get original subject without encoding <del> * <del> * @return string Original subject <del> */ <del> public function getOriginalSubject(): string <del> { <del> return $this->_decode($this->_subject); <del> } <del> <del> /** <del> * Sets headers for the message <del> * <del> * @param array $headers Associative array containing headers to be set. <del> * @return $this <del> */ <del> public function setHeaders(array $headers): self <del> { <del> $this->_headers = $headers; <del> <del> return $this; <del> } <del> <del> /** <del> * Add header for the message <del> * <del> * @param array $headers Headers to set. <del> * @return $this <del> */ <del> public function addHeaders(array $headers): self <del> { <del> $this->_headers = array_merge($this->_headers, $headers); <del> <del> return $this; <del> } <del> <del> /** <del> * Get list of headers <del> * <del> * ### Includes: <del> * <del> * - `from` <del> * - `replyTo` <del> * - `readReceipt` <del> * - `returnPath` <del> * - `to` <del> * - `cc` <del> * - `bcc` <del> * - `subject` <del> * <del> * @param array $include List of headers. <del> * @return array <del> */ <del> public function getHeaders(array $include = []): array <del> { <del> if ($include === array_values($include)) { <del> $include = array_fill_keys($include, true); <del> } <del> $defaults = array_fill_keys( <del> [ <del> 'from', 'sender', 'replyTo', 'readReceipt', 'returnPath', <del> 'to', 'cc', 'bcc', 'subject', <del> ], <del> false <del> ); <del> $include += $defaults; <del> <del> $headers = []; <del> $relation = [ <del> 'from' => 'From', <del> 'replyTo' => 'Reply-To', <del> 'readReceipt' => 'Disposition-Notification-To', <del> 'returnPath' => 'Return-Path', <del> ]; <del> foreach ($relation as $var => $header) { <del> if ($include[$var]) { <del> $var = '_' . $var; <del> $headers[$header] = current($this->_formatAddress($this->{$var})); <del> } <del> } <del> if ($include['sender']) { <del> if (key($this->_sender) === key($this->_from)) { <del> $headers['Sender'] = ''; <del> } else { <del> $headers['Sender'] = current($this->_formatAddress($this->_sender)); <del> } <del> } <del> <del> foreach (['to', 'cc', 'bcc'] as $var) { <del> if ($include[$var]) { <del> $classVar = '_' . $var; <del> $headers[ucfirst($var)] = implode(', ', $this->_formatAddress($this->{$classVar})); <del> } <del> } <del> <del> $headers += $this->_headers; <del> if (!isset($headers['Date'])) { <del> $headers['Date'] = date(DATE_RFC2822); <add> public function __clone() <add> { <add> if ($this->renderer) { <add> $this->renderer = clone $this->renderer; <ide> } <del> if ($this->_messageId !== false) { <del> if ($this->_messageId === true) { <del> $this->_messageId = '<' . str_replace('-', '', Text::uuid()) . '@' . $this->_domain . '>'; <del> } <ide> <del> $headers['Message-ID'] = $this->_messageId; <add> if ($this->message) { <add> $this->message = clone $this->message; <ide> } <add> } <ide> <del> if ($this->_priority) { <del> $headers['X-Priority'] = $this->_priority; <del> } <add> /** <add> * Magic method to forward method class to Email instance. <add> * <add> * @param string $method Method name. <add> * @param array $args Method arguments <add> * @return $this|mixed <add> */ <add> public function __call($method, $args) <add> { <add> $result = $this->message->$method(...$args); <ide> <del> if ($include['subject']) { <del> $headers['Subject'] = $this->_subject; <add> if (strpos($method, 'get') === 0) { <add> return $result; <ide> } <ide> <del> $headers['MIME-Version'] = '1.0'; <del> if ($this->_attachments) { <del> $headers['Content-Type'] = 'multipart/mixed; boundary="' . $this->_boundary . '"'; <del> } elseif ($this->_emailFormat === static::MESSAGE_BOTH) { <del> $headers['Content-Type'] = 'multipart/alternative; boundary="' . $this->_boundary . '"'; <del> } elseif ($this->_emailFormat === static::MESSAGE_TEXT) { <del> $headers['Content-Type'] = 'text/plain; charset=' . $this->getContentTypeCharset(); <del> } elseif ($this->_emailFormat === static::MESSAGE_HTML) { <del> $headers['Content-Type'] = 'text/html; charset=' . $this->getContentTypeCharset(); <add> $getters = ['message']; <add> if (in_array($method, $getters, true)) { <add> return $result; <ide> } <del> $headers['Content-Transfer-Encoding'] = $this->getContentTransferEncoding(); <ide> <del> return $headers; <add> return $this; <ide> } <ide> <ide> /** <del> * Format addresses <add> * Get message instance. <ide> * <del> * If the address contains non alphanumeric/whitespace characters, it will <del> * be quoted as characters like `:` and `,` are known to cause issues <del> * in address header fields. <del> * <del> * @param array $address Addresses to format. <del> * @return array <add> * @return \Cake\Mailer\Message <ide> */ <del> protected function _formatAddress(array $address): array <add> public function getMessage(): Message <ide> { <del> $return = []; <del> foreach ($address as $email => $alias) { <del> if ($email === $alias) { <del> $return[] = $email; <del> } else { <del> $encoded = $this->_encode($alias); <del> if ($encoded === $alias && preg_match('/[^a-z0-9 ]/i', $encoded)) { <del> $encoded = '"' . str_replace('"', '\"', $encoded) . '"'; <del> } <del> $return[] = sprintf('%s <%s>', $encoded, $email); <del> } <del> } <del> <del> return $return; <add> return $this->message; <ide> } <ide> <ide> /** <ide> public function getViewVars(): array <ide> return $this->getRenderer()->viewBuilder()->getVars(); <ide> } <ide> <del> /** <del> * Sets email format. <del> * <del> * @param string $format Formatting string. <del> * @return $this <del> * @throws \InvalidArgumentException <del> */ <del> public function setEmailFormat(string $format): self <del> { <del> if (!in_array($format, $this->_emailFormatAvailable)) { <del> throw new InvalidArgumentException('Format not available.'); <del> } <del> $this->_emailFormat = $format; <del> <del> return $this; <del> } <del> <del> /** <del> * Gets email format. <del> * <del> * @return string <del> */ <del> public function getEmailFormat(): string <del> { <del> return $this->_emailFormat; <del> } <del> <ide> /** <ide> * Sets the transport. <ide> * <ide> public function getTransport(): ?AbstractTransport <ide> } <ide> <ide> /** <del> * Sets message ID. <add> * Sets the configuration profile to use for this instance. <ide> * <del> * @param bool|string $message True to generate a new Message-ID, False to ignore (not send in email), <del> * String to set as Message-ID. <add> * @param string|array $config String with configuration name, or <add> * an array with config. <ide> * @return $this <del> * @throws \InvalidArgumentException <ide> */ <del> public function setMessageId($message): self <add> public function setProfile($config): self <ide> { <del> if (is_bool($message)) { <del> $this->_messageId = $message; <del> } else { <del> if (!preg_match('/^\<.+@.+\>$/', $message)) { <del> throw new InvalidArgumentException( <del> 'Invalid format to Message-ID. The text should be something like "<uuid@server.com>"' <del> ); <add> if (is_string($config)) { <add> $name = $config; <add> $config = static::getConfig($name); <add> if (empty($config)) { <add> throw new InvalidArgumentException(sprintf('Unknown email configuration "%s".', $name)); <ide> } <del> $this->_messageId = $message; <add> unset($name); <ide> } <ide> <del> return $this; <del> } <del> <del> /** <del> * Gets message ID. <del> * <del> * @return bool|string <del> */ <del> public function getMessageId() <del> { <del> return $this->_messageId; <del> } <del> <del> /** <del> * Sets domain. <del> * <del> * Domain as top level (the part after @). <del> * <del> * @param string $domain Manually set the domain for CLI mailing. <del> * @return $this <del> */ <del> public function setDomain(string $domain): self <del> { <del> $this->_domain = $domain; <del> <del> return $this; <del> } <del> <del> /** <del> * Gets domain. <del> * <del> * @return string <del> */ <del> public function getDomain(): string <del> { <del> return $this->_domain; <del> } <add> $this->_profile = array_merge($this->_profile, $config); <ide> <del> /** <del> * Add attachments to the email message <del> * <del> * Attachments can be defined in a few forms depending on how much control you need: <del> * <del> * Attach a single file: <del> * <del> * ``` <del> * $email->setAttachments('path/to/file'); <del> * ``` <del> * <del> * Attach a file with a different filename: <del> * <del> * ``` <del> * $email->setAttachments(['custom_name.txt' => 'path/to/file.txt']); <del> * ``` <del> * <del> * Attach a file and specify additional properties: <del> * <del> * ``` <del> * $email->setAttachments(['custom_name.png' => [ <del> * 'file' => 'path/to/file', <del> * 'mimetype' => 'image/png', <del> * 'contentId' => 'abc123', <del> * 'contentDisposition' => false <del> * ] <del> * ]); <del> * ``` <del> * <del> * Attach a file from string and specify additional properties: <del> * <del> * ``` <del> * $email->setAttachments(['custom_name.png' => [ <del> * 'data' => file_get_contents('path/to/file'), <del> * 'mimetype' => 'image/png' <del> * ] <del> * ]); <del> * ``` <del> * <del> * The `contentId` key allows you to specify an inline attachment. In your email text, you <del> * can use `<img src="cid:abc123" />` to display the image inline. <del> * <del> * The `contentDisposition` key allows you to disable the `Content-Disposition` header, this can improve <del> * attachment compatibility with outlook email clients. <del> * <del> * @param array $attachments Array of filenames. <del> * @return $this <del> * @throws \InvalidArgumentException <del> */ <del> public function setAttachments(array $attachments): self <del> { <del> $attach = []; <del> foreach ($attachments as $name => $fileInfo) { <del> if (!is_array($fileInfo)) { <del> $fileInfo = ['file' => $fileInfo]; <del> } <del> if (!isset($fileInfo['file'])) { <del> if (!isset($fileInfo['data'])) { <del> throw new InvalidArgumentException('No file or data specified.'); <del> } <del> if (is_int($name)) { <del> throw new InvalidArgumentException('No filename specified.'); <del> } <del> $fileInfo['data'] = chunk_split(base64_encode($fileInfo['data']), 76, "\r\n"); <del> } else { <del> $fileName = $fileInfo['file']; <del> $fileInfo['file'] = realpath($fileInfo['file']); <del> if ($fileInfo['file'] === false || !file_exists($fileInfo['file'])) { <del> throw new InvalidArgumentException(sprintf('File not found: "%s"', $fileName)); <del> } <del> if (is_int($name)) { <del> $name = basename($fileInfo['file']); <del> } <del> } <del> if (!isset($fileInfo['mimetype']) && isset($fileInfo['file']) && function_exists('mime_content_type')) { <del> $fileInfo['mimetype'] = mime_content_type($fileInfo['file']); <del> } <del> if (!isset($fileInfo['mimetype'])) { <del> $fileInfo['mimetype'] = 'application/octet-stream'; <add> $simpleMethods = [ <add> 'transport', <add> ]; <add> foreach ($simpleMethods as $method) { <add> if (isset($config[$method])) { <add> $this->{'set' . ucfirst($method)}($config[$method]); <add> unset($config[$method]); <ide> } <del> $attach[$name] = $fileInfo; <ide> } <del> $this->_attachments = $attach; <del> <del> return $this; <del> } <del> <del> /** <del> * Gets attachments to the email message. <del> * <del> * @return array Array of attachments. <del> */ <del> public function getAttachments(): array <del> { <del> return $this->_attachments; <del> } <del> <del> /** <del> * Add attachments <del> * <del> * @param array $attachments Array of filenames. <del> * @return $this <del> * @throws \InvalidArgumentException <del> * @see \Cake\Mailer\Email::setAttachments() <del> */ <del> public function addAttachments(array $attachments): self <del> { <del> $current = $this->_attachments; <del> $this->setAttachments($attachments); <del> $this->_attachments = array_merge($current, $this->_attachments); <del> <del> return $this; <del> } <ide> <del> /** <del> * Get generated message (used by transport classes) <del> * <del> * @param string|null $type Use MESSAGE_* constants or null to return the full message as array <del> * @return string|array String if type is given, array if type is null <del> */ <del> public function message(?string $type = null) <del> { <del> switch ($type) { <del> case static::MESSAGE_HTML: <del> return $this->_htmlMessage; <del> case static::MESSAGE_TEXT: <del> return $this->_textMessage; <add> $viewBuilderMethods = [ <add> 'template', 'layout', 'theme', <add> ]; <add> foreach ($viewBuilderMethods as $method) { <add> if (array_key_exists($method, $config)) { <add> $this->getRenderer()->viewBuilder()->{'set' . ucfirst($method)}($config[$method]); <add> unset($config[$method]); <add> } <ide> } <ide> <del> return $this->_message; <del> } <del> <del> /** <del> * Sets priority. <del> * <del> * @param int|null $priority 1 (highest) to 5 (lowest) <del> * @return $this <del> */ <del> public function setPriority(?int $priority): self <del> { <del> $this->_priority = $priority; <del> <del> return $this; <del> } <del> <del> /** <del> * Gets priority. <del> * <del> * @return int|null <del> */ <del> public function getPriority(): ?int <del> { <del> return $this->_priority; <del> } <add> if (array_key_exists('helpers', $config)) { <add> $this->getRenderer()->viewBuilder()->setHelpers($config['helpers'], false); <add> unset($config['helpers']); <add> } <add> if (array_key_exists('viewRenderer', $config)) { <add> $this->getRenderer()->viewBuilder()->setClassName($config['viewRenderer']); <add> unset($config['viewRenderer']); <add> } <add> if (array_key_exists('viewVars', $config)) { <add> $this->getRenderer()->viewBuilder()->setVars($config['viewVars']); <add> unset($config['viewVars']); <add> } <ide> <del> /** <del> * Sets the configuration profile to use for this instance. <del> * <del> * @param string|array $config String with configuration name, or <del> * an array with config. <del> * @return $this <del> */ <del> public function setProfile($config): self <del> { <del> $this->_applyConfig($config); <add> $this->message->setConfig($config); <ide> <ide> return $this; <ide> } <ide> public function getProfile(): array <ide> */ <ide> public function send($content = null): array <ide> { <del> if (empty($this->_from)) { <add> if (empty($this->message->getFrom())) { <ide> throw new BadMethodCallException('From is not specified.'); <ide> } <del> if (empty($this->_to) && empty($this->_cc) && empty($this->_bcc)) { <add> <add> if (empty($this->message->getTo()) <add> && empty($this->message->getCc()) <add> && empty($this->message->getBcc()) <add> ) { <ide> throw new BadMethodCallException('You need specify one destination on to, cc or bcc.'); <ide> } <ide> <ide> public function send($content = null): array <ide> */ <ide> public function render(?string $content = null): void <ide> { <del> $content = $this->getRenderer()->render($this, $content); <add> $data = $this->getRenderer()->render($this, $content); <add> $this->_boundary = $data['boundary']; <ide> <del> $this->_message = $content['message']; <del> $this->_boundary = $content['boundary']; <del> $this->_textMessage = $content['textMessage']; <del> $this->_htmlMessage = $content['htmlMessage']; <add> $this->message->setContent($data); <ide> } <ide> <ide> /** <ide> public function viewBuilder(): ViewBuilder <ide> public function getRenderer(): Renderer <ide> { <ide> if ($this->renderer === null) { <del> $this->renderer = new Renderer($this->_appCharset); <add> $this->renderer = new Renderer(); <ide> } <ide> <ide> return $this->renderer; <ide> public static function deliver( <ide> return $instance; <ide> } <ide> <del> /** <del> * Apply the config to an instance <del> * <del> * @param string|array $config Configuration options. <del> * @return void <del> * @throws \InvalidArgumentException When using a configuration that doesn't exist. <del> */ <del> protected function _applyConfig($config): void <del> { <del> if (is_string($config)) { <del> $name = $config; <del> $config = static::getConfig($name); <del> if (empty($config)) { <del> throw new InvalidArgumentException(sprintf('Unknown email configuration "%s".', $name)); <del> } <del> unset($name); <del> } <del> <del> $this->_profile = array_merge($this->_profile, $config); <del> <del> $simpleMethods = [ <del> 'from', 'sender', 'to', 'replyTo', 'readReceipt', 'returnPath', <del> 'cc', 'bcc', 'messageId', 'domain', 'subject', 'attachments', <del> 'transport', 'emailFormat', 'emailPattern', 'charset', 'headerCharset', <del> ]; <del> foreach ($simpleMethods as $method) { <del> if (isset($config[$method])) { <del> $this->{'set' . ucfirst($method)}($config[$method]); <del> } <del> } <del> <del> if (empty($this->headerCharset)) { <del> $this->headerCharset = $this->charset; <del> } <del> if (isset($config['headers'])) { <del> $this->setHeaders($config['headers']); <del> } <del> <del> $viewBuilderMethods = [ <del> 'template', 'layout', 'theme', <del> ]; <del> foreach ($viewBuilderMethods as $method) { <del> if (array_key_exists($method, $config)) { <del> $this->getRenderer()->viewBuilder()->{'set' . ucfirst($method)}($config[$method]); <del> } <del> } <del> <del> if (array_key_exists('helpers', $config)) { <del> $this->getRenderer()->viewBuilder()->setHelpers($config['helpers'], false); <del> } <del> if (array_key_exists('viewRender', $config)) { <del> $this->getRenderer()->viewBuilder()->setClassName($config['viewRender']); <del> } <del> if (array_key_exists('viewVars', $config)) { <del> $this->getRenderer()->viewBuilder()->setVars($config['viewVars']); <del> } <del> } <del> <ide> /** <ide> * Reset all the internal variables to be able to send out a new email. <ide> * <ide> * @return $this <ide> */ <ide> public function reset(): self <ide> { <del> $this->_to = []; <del> $this->_from = []; <del> $this->_sender = []; <del> $this->_replyTo = []; <del> $this->_readReceipt = []; <del> $this->_returnPath = []; <del> $this->_cc = []; <del> $this->_bcc = []; <del> $this->_messageId = true; <del> $this->_subject = ''; <del> $this->_headers = []; <del> $this->_textMessage = ''; <del> $this->_htmlMessage = ''; <del> $this->_message = []; <del> $this->_emailFormat = static::MESSAGE_TEXT; <add> $this->message->reset(); <ide> $this->_transport = null; <ide> $this->_priority = null; <del> $this->charset = 'utf-8'; <del> $this->headerCharset = null; <del> $this->transferEncoding = null; <del> $this->_attachments = []; <ide> $this->_profile = []; <del> $this->_emailPattern = self::EMAIL_PATTERN; <ide> <ide> $this->getRenderer()->viewBuilder() <ide> ->setLayout('default') <ide> public function reset(): self <ide> return $this; <ide> } <ide> <del> /** <del> * Encode the specified string using the current charset <del> * <del> * @param string $text String to encode <del> * @return string Encoded string <del> */ <del> protected function _encode(string $text): string <del> { <del> $restore = mb_internal_encoding(); <del> mb_internal_encoding($this->_appCharset); <del> if (empty($this->headerCharset)) { <del> $this->headerCharset = $this->charset; <del> } <del> $return = mb_encode_mimeheader($text, $this->headerCharset, 'B'); <del> mb_internal_encoding($restore); <del> <del> return $return; <del> } <del> <del> /** <del> * Decode the specified string <del> * <del> * @param string $text String to decode <del> * @return string Decoded string <del> */ <del> protected function _decode(string $text): string <del> { <del> $restore = mb_internal_encoding(); <del> mb_internal_encoding($this->_appCharset); <del> $return = mb_decode_mimeheader($text); <del> mb_internal_encoding($restore); <del> <del> return $return; <del> } <del> <del> /** <del> * Read the file contents and return a base64 version of the file contents. <del> * <del> * @param string $path The absolute path to the file to read. <del> * @return string File contents in base64 encoding <del> */ <del> protected function _readFile(string $path): string <del> { <del> return chunk_split(base64_encode((string)file_get_contents($path))); <del> } <del> <del> /** <del> * Return the Content-Transfer Encoding value based <del> * on the set transferEncoding or set charset. <del> * <del> * @return string <del> */ <del> public function getContentTransferEncoding(): string <del> { <del> if ($this->transferEncoding) { <del> return $this->transferEncoding; <del> } <del> <del> $charset = strtoupper($this->charset); <del> if (in_array($charset, $this->_charset8bit)) { <del> return '8bit'; <del> } <del> <del> return '7bit'; <del> } <del> <del> /** <del> * Return charset value for Content-Type. <del> * <del> * Checks fallback/compatibility types which include workarounds <del> * for legacy japanese character sets. <del> * <del> * @return string <del> */ <del> public function getContentTypeCharset(): string <del> { <del> $charset = strtoupper($this->charset); <del> if (array_key_exists($charset, $this->_contentTypeCharset)) { <del> return strtoupper($this->_contentTypeCharset[$charset]); <del> } <del> <del> return strtoupper($this->charset); <del> } <del> <ide> /** <ide> * Serializes the email object to a value that can be natively serialized and re-used <ide> * to clone this email instance. <ide> public function getContentTypeCharset(): string <ide> */ <ide> public function jsonSerialize(): array <ide> { <del> $properties = [ <del> '_to', '_from', '_sender', '_replyTo', '_cc', '_bcc', '_subject', <del> '_returnPath', '_readReceipt', '_emailFormat', '_emailPattern', '_domain', <del> '_attachments', '_messageId', '_headers', '_appCharset', 'charset', 'headerCharset', <del> ]; <del> <del> $array = ['viewConfig' => $this->getRenderer()->viewBuilder()->jsonSerialize()]; <del> <del> foreach ($properties as $property) { <del> $array[$property] = $this->{$property}; <del> } <add> $array = $this->message->jsonSerialize(); <add> $array['viewConfig'] = $this->getRenderer()->viewBuilder()->jsonSerialize(); <ide> <del> array_walk($array['_attachments'], function (&$item, $key) { <del> if (!empty($item['file'])) { <del> $item['data'] = $this->_readFile($item['file']); <del> unset($item['file']); <del> } <del> }); <del> <del> return array_filter($array, function ($i) { <del> return !is_array($i) && strlen($i) || !empty($i); <del> }); <add> return $array; <ide> } <ide> <ide> /** <ide> public function createFromArray(array $config): self <ide> unset($config['viewConfig']); <ide> } <ide> <del> foreach ($config as $property => $value) { <del> $this->{$property} = $value; <add> if (!$this->message) { <add> $this->message = new $this->messageClass(); <ide> } <add> $this->message->createFromArray($config); <ide> <ide> return $this; <ide> } <ide><path>src/Mailer/Message.php <add><?php <add>declare(strict_types=1); <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\Mailer; <add> <add>use Cake\Core\Configure; <add>use Cake\Utility\Text; <add>use InvalidArgumentException; <add>use JsonSerializable; <add>use Serializable; <add>use SimpleXMLElement; <add> <add>/** <add> * Email message class. <add> * <add> * This class is used for sending Internet Message Format based <add> * on the standard outlined in https://www.rfc-editor.org/rfc/rfc2822.txt <add> */ <add>class Message implements JsonSerializable, Serializable <add>{ <add> /** <add> * Type of message - HTML <add> * <add> * @var string <add> */ <add> public const MESSAGE_HTML = 'html'; <add> <add> /** <add> * Type of message - TEXT <add> * <add> * @var string <add> */ <add> public const MESSAGE_TEXT = 'text'; <add> <add> /** <add> * Type of message - BOTH <add> * <add> * @var string <add> */ <add> public const MESSAGE_BOTH = 'both'; <add> <add> /** <add> * Holds the regex pattern for email validation <add> * <add> * @var string <add> */ <add> public const EMAIL_PATTERN = '/^((?:[\p{L}0-9.!#$%&\'*+\/=?^_`{|}~-]+)*@[\p{L}0-9-._]+)$/ui'; <add> <add> /** <add> * Recipient of the email <add> * <add> * @var array <add> */ <add> protected $_to = []; <add> <add> /** <add> * The mail which the email is sent from <add> * <add> * @var array <add> */ <add> protected $_from = []; <add> <add> /** <add> * The sender email <add> * <add> * @var array <add> */ <add> protected $_sender = []; <add> <add> /** <add> * The email the recipient will reply to <add> * <add> * @var array <add> */ <add> protected $_replyTo = []; <add> <add> /** <add> * The read receipt email <add> * <add> * @var array <add> */ <add> protected $_readReceipt = []; <add> <add> /** <add> * The mail that will be used in case of any errors like <add> * - Remote mailserver down <add> * - Remote user has exceeded his quota <add> * - Unknown user <add> * <add> * @var array <add> */ <add> protected $_returnPath = []; <add> <add> /** <add> * Carbon Copy <add> * <add> * List of email's that should receive a copy of the email. <add> * The Recipient WILL be able to see this list <add> * <add> * @var array <add> */ <add> protected $_cc = []; <add> <add> /** <add> * Blind Carbon Copy <add> * <add> * List of email's that should receive a copy of the email. <add> * The Recipient WILL NOT be able to see this list <add> * <add> * @var array <add> */ <add> protected $_bcc = []; <add> <add> /** <add> * Message ID <add> * <add> * @var bool|string <add> */ <add> protected $_messageId = true; <add> <add> /** <add> * Domain for messageId generation. <add> * Needs to be manually set for CLI mailing as env('HTTP_HOST') is empty <add> * <add> * @var string <add> */ <add> protected $_domain = ''; <add> <add> /** <add> * The subject of the email <add> * <add> * @var string <add> */ <add> protected $_subject = ''; <add> <add> /** <add> * Associative array of a user defined headers <add> * Keys will be prefixed 'X-' as per RFC2822 Section 4.7.5 <add> * <add> * @var array <add> */ <add> protected $_headers = []; <add> <add> /** <add> * Text message <add> * <add> * @var string <add> */ <add> protected $_textMessage = ''; <add> <add> /** <add> * Html message <add> * <add> * @var string <add> */ <add> protected $_htmlMessage = ''; <add> <add> /** <add> * Final message to send <add> * <add> * @var array <add> */ <add> protected $_message = []; <add> <add> /** <add> * Available formats to be sent. <add> * <add> * @var array <add> */ <add> protected $_emailFormatAvailable = [self::MESSAGE_TEXT, self::MESSAGE_HTML, self::MESSAGE_BOTH]; <add> <add> /** <add> * What format should the email be sent in <add> * <add> * @var string <add> */ <add> protected $_emailFormat = self::MESSAGE_TEXT; <add> <add> /** <add> * Charset the email body is sent in <add> * <add> * @var string <add> */ <add> protected $charset = 'utf-8'; <add> <add> /** <add> * Charset the email header is sent in <add> * If null, the $charset property will be used as default <add> * <add> * @var string|null <add> */ <add> protected $headerCharset; <add> <add> /** <add> * The email transfer encoding used. <add> * If null, the $charset property is used for determined the transfer encoding. <add> * <add> * @var string|null <add> */ <add> protected $transferEncoding; <add> <add> /** <add> * Available encoding to be set for transfer. <add> * <add> * @var array <add> */ <add> protected $_transferEncodingAvailable = [ <add> '7bit', <add> '8bit', <add> 'base64', <add> 'binary', <add> 'quoted-printable', <add> ]; <add> <add> /** <add> * The application wide charset, used to encode headers and body <add> * <add> * @var string|null <add> */ <add> protected $_appCharset; <add> <add> /** <add> * List of files that should be attached to the email. <add> * <add> * Only absolute paths <add> * <add> * @var array <add> */ <add> protected $_attachments = []; <add> <add> /** <add> * If set, boundary to use for multipart mime messages <add> * <add> * @var string|null <add> */ <add> protected $_boundary; <add> <add> /** <add> * Contains the optional priority of the email. <add> * <add> * @var int|null <add> */ <add> protected $_priority; <add> <add> /** <add> * A copy of the configuration profile for this <add> * instance. This copy can be modified with Email::profile(). <add> * <add> * @var array <add> */ <add> protected $_profile = []; <add> <add> /** <add> * 8Bit character sets <add> * <add> * @var array <add> */ <add> protected $_charset8bit = ['UTF-8', 'SHIFT_JIS']; <add> <add> /** <add> * Define Content-Type charset name <add> * <add> * @var array <add> */ <add> protected $_contentTypeCharset = [ <add> 'ISO-2022-JP-MS' => 'ISO-2022-JP', <add> ]; <add> <add> /** <add> * Regex for email validation <add> * <add> * If null, filter_var() will be used. Use the emailPattern() method <add> * to set a custom pattern.' <add> * <add> * @var string|null <add> */ <add> protected $_emailPattern = self::EMAIL_PATTERN; <add> <add> /** <add> * Constructor <add> * <add> * @param array|null $config Array of configs, or string to load configs from app.php <add> */ <add> public function __construct(?array $config = null) <add> { <add> $this->_appCharset = Configure::read('App.encoding'); <add> if ($this->_appCharset !== null) { <add> $this->charset = $this->_appCharset; <add> } <add> $this->_domain = preg_replace('/\:\d+$/', '', env('HTTP_HOST')); <add> if (empty($this->_domain)) { <add> $this->_domain = php_uname('n'); <add> } <add> <add> if ($config) { <add> $this->setProfile($config); <add> } <add> } <add> <add> /** <add> * Clone Renderer instance when email object is cloned. <add> * <add> * @return void <add> */ <add> public function __clone() <add> { <add> if ($this->renderer) { <add> $this->renderer = clone $this->renderer; <add> } <add> } <add> <add> /** <add> * Sets "from" address. <add> * <add> * @param string|array $email Null to get, String with email, <add> * Array with email as key, name as value or email as value (without name) <add> * @param string|null $name Name <add> * @return $this <add> * @throws \InvalidArgumentException <add> */ <add> public function setFrom($email, ?string $name = null): self <add> { <add> return $this->_setEmailSingle('_from', $email, $name, 'From requires only 1 email address.'); <add> } <add> <add> /** <add> * Gets "from" address. <add> * <add> * @return array <add> */ <add> public function getFrom(): array <add> { <add> return $this->_from; <add> } <add> <add> /** <add> * Sets "sender" address. <add> * <add> * @param string|array $email String with email, <add> * Array with email as key, name as value or email as value (without name) <add> * @param string|null $name Name <add> * @return $this <add> * @throws \InvalidArgumentException <add> */ <add> public function setSender($email, ?string $name = null): self <add> { <add> return $this->_setEmailSingle('_sender', $email, $name, 'Sender requires only 1 email address.'); <add> } <add> <add> /** <add> * Gets "sender" address. <add> * <add> * @return array <add> */ <add> public function getSender(): array <add> { <add> return $this->_sender; <add> } <add> <add> /** <add> * Sets "Reply-To" address. <add> * <add> * @param string|array $email String with email, <add> * Array with email as key, name as value or email as value (without name) <add> * @param string|null $name Name <add> * @return $this <add> * @throws \InvalidArgumentException <add> */ <add> public function setReplyTo($email, ?string $name = null): self <add> { <add> return $this->_setEmailSingle('_replyTo', $email, $name, 'Reply-To requires only 1 email address.'); <add> } <add> <add> /** <add> * Gets "Reply-To" address. <add> * <add> * @return array <add> */ <add> public function getReplyTo(): array <add> { <add> return $this->_replyTo; <add> } <add> <add> /** <add> * Sets Read Receipt (Disposition-Notification-To header). <add> * <add> * @param string|array $email String with email, <add> * Array with email as key, name as value or email as value (without name) <add> * @param string|null $name Name <add> * @return $this <add> * @throws \InvalidArgumentException <add> */ <add> public function setReadReceipt($email, ?string $name = null): self <add> { <add> return $this->_setEmailSingle( <add> '_readReceipt', <add> $email, <add> $name, <add> 'Disposition-Notification-To requires only 1 email address.' <add> ); <add> } <add> <add> /** <add> * Gets Read Receipt (Disposition-Notification-To header). <add> * <add> * @return array <add> */ <add> public function getReadReceipt(): array <add> { <add> return $this->_readReceipt; <add> } <add> <add> /** <add> * Return Path <add> * <add> * @param string|array $email String with email, <add> * Array with email as key, name as value or email as value (without name) <add> * @param string|null $name Name <add> * @return $this <add> * @throws \InvalidArgumentException <add> */ <add> public function setReturnPath($email, ?string $name = null): self <add> { <add> return $this->_setEmailSingle('_returnPath', $email, $name, 'Return-Path requires only 1 email address.'); <add> } <add> <add> /** <add> * Gets return path. <add> * <add> * @return array <add> */ <add> public function getReturnPath(): array <add> { <add> return $this->_returnPath; <add> } <add> <add> /** <add> * Sets "to" address. <add> * <add> * @param string|array $email String with email, <add> * Array with email as key, name as value or email as value (without name) <add> * @param string|null $name Name <add> * @return $this <add> */ <add> public function setTo($email, ?string $name = null): self <add> { <add> return $this->_setEmail('_to', $email, $name); <add> } <add> <add> /** <add> * Gets "to" address <add> * <add> * @return array <add> */ <add> public function getTo(): array <add> { <add> return $this->_to; <add> } <add> <add> /** <add> * Add To <add> * <add> * @param string|array $email Null to get, String with email, <add> * Array with email as key, name as value or email as value (without name) <add> * @param string|null $name Name <add> * @return $this <add> */ <add> public function addTo($email, ?string $name = null): self <add> { <add> return $this->_addEmail('_to', $email, $name); <add> } <add> <add> /** <add> * Sets "cc" address. <add> * <add> * @param string|array $email String with email, <add> * Array with email as key, name as value or email as value (without name) <add> * @param string|null $name Name <add> * @return $this <add> */ <add> public function setCc($email, ?string $name = null): self <add> { <add> return $this->_setEmail('_cc', $email, $name); <add> } <add> <add> /** <add> * Gets "cc" address. <add> * <add> * @return array <add> */ <add> public function getCc(): array <add> { <add> return $this->_cc; <add> } <add> <add> /** <add> * Add Cc <add> * <add> * @param string|array $email Null to get, String with email, <add> * Array with email as key, name as value or email as value (without name) <add> * @param string|null $name Name <add> * @return $this <add> */ <add> public function addCc($email, ?string $name = null): self <add> { <add> return $this->_addEmail('_cc', $email, $name); <add> } <add> <add> /** <add> * Sets "bcc" address. <add> * <add> * @param string|array $email String with email, <add> * Array with email as key, name as value or email as value (without name) <add> * @param string|null $name Name <add> * @return $this <add> */ <add> public function setBcc($email, ?string $name = null): self <add> { <add> return $this->_setEmail('_bcc', $email, $name); <add> } <add> <add> /** <add> * Gets "bcc" address. <add> * <add> * @return array <add> */ <add> public function getBcc(): array <add> { <add> return $this->_bcc; <add> } <add> <add> /** <add> * Add Bcc <add> * <add> * @param string|array $email Null to get, String with email, <add> * Array with email as key, name as value or email as value (without name) <add> * @param string|null $name Name <add> * @return $this <add> */ <add> public function addBcc($email, ?string $name = null): self <add> { <add> return $this->_addEmail('_bcc', $email, $name); <add> } <add> <add> /** <add> * Charset setter. <add> * <add> * @param string $charset Character set. <add> * @return $this <add> */ <add> public function setCharset(string $charset): self <add> { <add> $this->charset = $charset; <add> <add> return $this; <add> } <add> <add> /** <add> * Charset getter. <add> * <add> * @return string Charset <add> */ <add> public function getCharset(): string <add> { <add> return $this->charset; <add> } <add> <add> /** <add> * HeaderCharset setter. <add> * <add> * @param string|null $charset Character set. <add> * @return $this <add> */ <add> public function setHeaderCharset(?string $charset): self <add> { <add> $this->headerCharset = $charset; <add> <add> return $this; <add> } <add> <add> /** <add> * HeaderCharset getter. <add> * <add> * @return string Charset <add> */ <add> public function getHeaderCharset(): string <add> { <add> return $this->headerCharset ?: $this->charset; <add> } <add> <add> /** <add> * TransferEncoding setter. <add> * <add> * @param string|null $encoding Encoding set. <add> * @return $this <add> * @throws \InvalidArgumentException <add> */ <add> public function setTransferEncoding(?string $encoding): self <add> { <add> $encoding = strtolower($encoding); <add> if (!in_array($encoding, $this->_transferEncodingAvailable)) { <add> throw new InvalidArgumentException( <add> sprintf( <add> 'Transfer encoding not available. Can be : %s.', <add> implode(', ', $this->_transferEncodingAvailable) <add> ) <add> ); <add> } <add> $this->transferEncoding = $encoding; <add> <add> return $this; <add> } <add> <add> /** <add> * TransferEncoding getter. <add> * <add> * @return string|null Encoding <add> */ <add> public function getTransferEncoding(): ?string <add> { <add> return $this->transferEncoding; <add> } <add> <add> /** <add> * EmailPattern setter/getter <add> * <add> * @param string|null $regex The pattern to use for email address validation, <add> * null to unset the pattern and make use of filter_var() instead. <add> * @return $this <add> */ <add> public function setEmailPattern(?string $regex): self <add> { <add> $this->_emailPattern = $regex; <add> <add> return $this; <add> } <add> <add> /** <add> * EmailPattern setter/getter <add> * <add> * @return string|null <add> */ <add> public function getEmailPattern(): ?string <add> { <add> return $this->_emailPattern; <add> } <add> <add> /** <add> * Set email <add> * <add> * @param string $varName Property name <add> * @param string|array $email String with email, <add> * Array with email as key, name as value or email as value (without name) <add> * @param string|null $name Name <add> * @return $this <add> * @throws \InvalidArgumentException <add> */ <add> protected function _setEmail(string $varName, $email, ?string $name): self <add> { <add> if (!is_array($email)) { <add> $this->_validateEmail($email, $varName); <add> if ($name === null) { <add> $name = $email; <add> } <add> $this->{$varName} = [$email => $name]; <add> <add> return $this; <add> } <add> $list = []; <add> foreach ($email as $key => $value) { <add> if (is_int($key)) { <add> $key = $value; <add> } <add> $this->_validateEmail($key, $varName); <add> $list[$key] = $value; <add> } <add> $this->{$varName} = $list; <add> <add> return $this; <add> } <add> <add> /** <add> * Validate email address <add> * <add> * @param string $email Email address to validate <add> * @param string $context Which property was set <add> * @return void <add> * @throws \InvalidArgumentException If email address does not validate <add> */ <add> protected function _validateEmail(string $email, string $context): void <add> { <add> if ($this->_emailPattern === null) { <add> if (filter_var($email, FILTER_VALIDATE_EMAIL)) { <add> return; <add> } <add> } elseif (preg_match($this->_emailPattern, (string)$email)) { <add> return; <add> } <add> <add> $context = ltrim($context, '_'); <add> if ($email === '') { <add> throw new InvalidArgumentException(sprintf('The email set for "%s" is empty.', $context)); <add> } <add> throw new InvalidArgumentException(sprintf('Invalid email set for "%s". You passed "%s".', $context, $email)); <add> } <add> <add> /** <add> * Set only 1 email <add> * <add> * @param string $varName Property name <add> * @param string|array $email String with email, <add> * Array with email as key, name as value or email as value (without name) <add> * @param string|null $name Name <add> * @param string $throwMessage Exception message <add> * @return $this <add> * @throws \InvalidArgumentException <add> */ <add> protected function _setEmailSingle(string $varName, $email, ?string $name, string $throwMessage): self <add> { <add> if ($email === []) { <add> $this->{$varName} = $email; <add> <add> return $this; <add> } <add> <add> $current = $this->{$varName}; <add> $this->_setEmail($varName, $email, $name); <add> if (count($this->{$varName}) !== 1) { <add> $this->{$varName} = $current; <add> throw new InvalidArgumentException($throwMessage); <add> } <add> <add> return $this; <add> } <add> <add> /** <add> * Add email <add> * <add> * @param string $varName Property name <add> * @param string|array $email String with email, <add> * Array with email as key, name as value or email as value (without name) <add> * @param string|null $name Name <add> * @return $this <add> * @throws \InvalidArgumentException <add> */ <add> protected function _addEmail(string $varName, $email, ?string $name): self <add> { <add> if (!is_array($email)) { <add> $this->_validateEmail($email, $varName); <add> if ($name === null) { <add> $name = $email; <add> } <add> $this->{$varName}[$email] = $name; <add> <add> return $this; <add> } <add> $list = []; <add> foreach ($email as $key => $value) { <add> if (is_int($key)) { <add> $key = $value; <add> } <add> $this->_validateEmail($key, $varName); <add> $list[$key] = $value; <add> } <add> $this->{$varName} = array_merge($this->{$varName}, $list); <add> <add> return $this; <add> } <add> <add> /** <add> * Sets subject. <add> * <add> * @param string $subject Subject string. <add> * @return $this <add> */ <add> public function setSubject(string $subject): self <add> { <add> $this->_subject = $this->_encode($subject); <add> <add> return $this; <add> } <add> <add> /** <add> * Gets subject. <add> * <add> * @return string <add> */ <add> public function getSubject(): string <add> { <add> return $this->_subject; <add> } <add> <add> /** <add> * Get original subject without encoding <add> * <add> * @return string Original subject <add> */ <add> public function getOriginalSubject(): string <add> { <add> return $this->_decode($this->_subject); <add> } <add> <add> /** <add> * Sets headers for the message <add> * <add> * @param array $headers Associative array containing headers to be set. <add> * @return $this <add> */ <add> public function setHeaders(array $headers): self <add> { <add> $this->_headers = $headers; <add> <add> return $this; <add> } <add> <add> /** <add> * Add header for the message <add> * <add> * @param array $headers Headers to set. <add> * @return $this <add> */ <add> public function addHeaders(array $headers): self <add> { <add> $this->_headers = array_merge($this->_headers, $headers); <add> <add> return $this; <add> } <add> <add> /** <add> * Get list of headers <add> * <add> * ### Includes: <add> * <add> * - `from` <add> * - `replyTo` <add> * - `readReceipt` <add> * - `returnPath` <add> * - `to` <add> * - `cc` <add> * - `bcc` <add> * - `subject` <add> * <add> * @param array $include List of headers. <add> * @return array <add> */ <add> public function getHeaders(array $include = []): array <add> { <add> if ($include === array_values($include)) { <add> $include = array_fill_keys($include, true); <add> } <add> $defaults = array_fill_keys( <add> [ <add> 'from', 'sender', 'replyTo', 'readReceipt', 'returnPath', <add> 'to', 'cc', 'bcc', 'subject', <add> ], <add> false <add> ); <add> $include += $defaults; <add> <add> $headers = []; <add> $relation = [ <add> 'from' => 'From', <add> 'replyTo' => 'Reply-To', <add> 'readReceipt' => 'Disposition-Notification-To', <add> 'returnPath' => 'Return-Path', <add> ]; <add> foreach ($relation as $var => $header) { <add> if ($include[$var]) { <add> $var = '_' . $var; <add> $headers[$header] = current($this->_formatAddress($this->{$var})); <add> } <add> } <add> if ($include['sender']) { <add> if (key($this->_sender) === key($this->_from)) { <add> $headers['Sender'] = ''; <add> } else { <add> $headers['Sender'] = current($this->_formatAddress($this->_sender)); <add> } <add> } <add> <add> foreach (['to', 'cc', 'bcc'] as $var) { <add> if ($include[$var]) { <add> $classVar = '_' . $var; <add> $headers[ucfirst($var)] = implode(', ', $this->_formatAddress($this->{$classVar})); <add> } <add> } <add> <add> $headers += $this->_headers; <add> if (!isset($headers['Date'])) { <add> $headers['Date'] = date(DATE_RFC2822); <add> } <add> if ($this->_messageId !== false) { <add> if ($this->_messageId === true) { <add> $this->_messageId = '<' . str_replace('-', '', Text::uuid()) . '@' . $this->_domain . '>'; <add> } <add> <add> $headers['Message-ID'] = $this->_messageId; <add> } <add> <add> if ($this->_priority) { <add> $headers['X-Priority'] = $this->_priority; <add> } <add> <add> if ($include['subject']) { <add> $headers['Subject'] = $this->_subject; <add> } <add> <add> $headers['MIME-Version'] = '1.0'; <add> if ($this->_attachments) { <add> $headers['Content-Type'] = 'multipart/mixed; boundary="' . $this->_boundary . '"'; <add> } elseif ($this->_emailFormat === static::MESSAGE_BOTH) { <add> $headers['Content-Type'] = 'multipart/alternative; boundary="' . $this->_boundary . '"'; <add> } elseif ($this->_emailFormat === static::MESSAGE_TEXT) { <add> $headers['Content-Type'] = 'text/plain; charset=' . $this->getContentTypeCharset(); <add> } elseif ($this->_emailFormat === static::MESSAGE_HTML) { <add> $headers['Content-Type'] = 'text/html; charset=' . $this->getContentTypeCharset(); <add> } <add> $headers['Content-Transfer-Encoding'] = $this->getContentTransferEncoding(); <add> <add> return $headers; <add> } <add> <add> /** <add> * Format addresses <add> * <add> * If the address contains non alphanumeric/whitespace characters, it will <add> * be quoted as characters like `:` and `,` are known to cause issues <add> * in address header fields. <add> * <add> * @param array $address Addresses to format. <add> * @return array <add> */ <add> protected function _formatAddress(array $address): array <add> { <add> $return = []; <add> foreach ($address as $email => $alias) { <add> if ($email === $alias) { <add> $return[] = $email; <add> } else { <add> $encoded = $this->_encode($alias); <add> if ($encoded === $alias && preg_match('/[^a-z0-9 ]/i', $encoded)) { <add> $encoded = '"' . str_replace('"', '\"', $encoded) . '"'; <add> } <add> $return[] = sprintf('%s <%s>', $encoded, $email); <add> } <add> } <add> <add> return $return; <add> } <add> <add> /** <add> * Sets email format. <add> * <add> * @param string $format Formatting string. <add> * @return $this <add> * @throws \InvalidArgumentException <add> */ <add> public function setEmailFormat(string $format): self <add> { <add> if (!in_array($format, $this->_emailFormatAvailable)) { <add> throw new InvalidArgumentException('Format not available.'); <add> } <add> $this->_emailFormat = $format; <add> <add> return $this; <add> } <add> <add> /** <add> * Gets email format. <add> * <add> * @return string <add> */ <add> public function getEmailFormat(): string <add> { <add> return $this->_emailFormat; <add> } <add> <add> /** <add> * Sets message ID. <add> * <add> * @param bool|string $message True to generate a new Message-ID, False to ignore (not send in email), <add> * String to set as Message-ID. <add> * @return $this <add> * @throws \InvalidArgumentException <add> */ <add> public function setMessageId($message): self <add> { <add> if (is_bool($message)) { <add> $this->_messageId = $message; <add> } else { <add> if (!preg_match('/^\<.+@.+\>$/', $message)) { <add> throw new InvalidArgumentException( <add> 'Invalid format to Message-ID. The text should be something like "<uuid@server.com>"' <add> ); <add> } <add> $this->_messageId = $message; <add> } <add> <add> return $this; <add> } <add> <add> /** <add> * Gets message ID. <add> * <add> * @return bool|string <add> */ <add> public function getMessageId() <add> { <add> return $this->_messageId; <add> } <add> <add> /** <add> * Sets domain. <add> * <add> * Domain as top level (the part after @). <add> * <add> * @param string $domain Manually set the domain for CLI mailing. <add> * @return $this <add> */ <add> public function setDomain(string $domain): self <add> { <add> $this->_domain = $domain; <add> <add> return $this; <add> } <add> <add> /** <add> * Gets domain. <add> * <add> * @return string <add> */ <add> public function getDomain(): string <add> { <add> return $this->_domain; <add> } <add> <add> /** <add> * Add attachments to the email message <add> * <add> * Attachments can be defined in a few forms depending on how much control you need: <add> * <add> * Attach a single file: <add> * <add> * ``` <add> * $email->setAttachments('path/to/file'); <add> * ``` <add> * <add> * Attach a file with a different filename: <add> * <add> * ``` <add> * $email->setAttachments(['custom_name.txt' => 'path/to/file.txt']); <add> * ``` <add> * <add> * Attach a file and specify additional properties: <add> * <add> * ``` <add> * $email->setAttachments(['custom_name.png' => [ <add> * 'file' => 'path/to/file', <add> * 'mimetype' => 'image/png', <add> * 'contentId' => 'abc123', <add> * 'contentDisposition' => false <add> * ] <add> * ]); <add> * ``` <add> * <add> * Attach a file from string and specify additional properties: <add> * <add> * ``` <add> * $email->setAttachments(['custom_name.png' => [ <add> * 'data' => file_get_contents('path/to/file'), <add> * 'mimetype' => 'image/png' <add> * ] <add> * ]); <add> * ``` <add> * <add> * The `contentId` key allows you to specify an inline attachment. In your email text, you <add> * can use `<img src="cid:abc123" />` to display the image inline. <add> * <add> * The `contentDisposition` key allows you to disable the `Content-Disposition` header, this can improve <add> * attachment compatibility with outlook email clients. <add> * <add> * @param array $attachments Array of filenames. <add> * @return $this <add> * @throws \InvalidArgumentException <add> */ <add> public function setAttachments(array $attachments): self <add> { <add> $attach = []; <add> foreach ($attachments as $name => $fileInfo) { <add> if (!is_array($fileInfo)) { <add> $fileInfo = ['file' => $fileInfo]; <add> } <add> if (!isset($fileInfo['file'])) { <add> if (!isset($fileInfo['data'])) { <add> throw new InvalidArgumentException('No file or data specified.'); <add> } <add> if (is_int($name)) { <add> throw new InvalidArgumentException('No filename specified.'); <add> } <add> $fileInfo['data'] = chunk_split(base64_encode($fileInfo['data']), 76, "\r\n"); <add> } else { <add> $fileName = $fileInfo['file']; <add> $fileInfo['file'] = realpath($fileInfo['file']); <add> if ($fileInfo['file'] === false || !file_exists($fileInfo['file'])) { <add> throw new InvalidArgumentException(sprintf('File not found: "%s"', $fileName)); <add> } <add> if (is_int($name)) { <add> $name = basename($fileInfo['file']); <add> } <add> } <add> if (!isset($fileInfo['mimetype']) && isset($fileInfo['file']) && function_exists('mime_content_type')) { <add> $fileInfo['mimetype'] = mime_content_type($fileInfo['file']); <add> } <add> if (!isset($fileInfo['mimetype'])) { <add> $fileInfo['mimetype'] = 'application/octet-stream'; <add> } <add> $attach[$name] = $fileInfo; <add> } <add> $this->_attachments = $attach; <add> <add> return $this; <add> } <add> <add> /** <add> * Gets attachments to the email message. <add> * <add> * @return array Array of attachments. <add> */ <add> public function getAttachments(): array <add> { <add> return $this->_attachments; <add> } <add> <add> /** <add> * Add attachments <add> * <add> * @param array $attachments Array of filenames. <add> * @return $this <add> * @throws \InvalidArgumentException <add> * @see \Cake\Mailer\Email::setAttachments() <add> */ <add> public function addAttachments(array $attachments): self <add> { <add> $current = $this->_attachments; <add> $this->setAttachments($attachments); <add> $this->_attachments = array_merge($current, $this->_attachments); <add> <add> return $this; <add> } <add> <add> /** <add> * Get generated message (used by transport classes) <add> * <add> * @param string|null $type Use MESSAGE_* constants or null to return the full message as array <add> * @return string|array String if type is given, array if type is null <add> */ <add> public function message(?string $type = null) <add> { <add> switch ($type) { <add> case static::MESSAGE_HTML: <add> return $this->_htmlMessage; <add> case static::MESSAGE_TEXT: <add> return $this->_textMessage; <add> } <add> <add> return $this->_message; <add> } <add> <add> /** <add> * Sets priority. <add> * <add> * @param int|null $priority 1 (highest) to 5 (lowest) <add> * @return $this <add> */ <add> public function setPriority(?int $priority): self <add> { <add> $this->_priority = $priority; <add> <add> return $this; <add> } <add> <add> /** <add> * Gets priority. <add> * <add> * @return int|null <add> */ <add> public function getPriority(): ?int <add> { <add> return $this->_priority; <add> } <add> <add> /** <add> * Sets the configuration for this instance. <add> * <add> * @param array $config Config array. <add> * @return $this <add> */ <add> public function setConfig(array $config): self <add> { <add> $simpleMethods = [ <add> 'from', 'sender', 'to', 'replyTo', 'readReceipt', 'returnPath', <add> 'cc', 'bcc', 'messageId', 'domain', 'subject', 'attachments', <add> 'emailFormat', 'emailPattern', 'charset', 'headerCharset', <add> ]; <add> foreach ($simpleMethods as $method) { <add> if (isset($config[$method])) { <add> $this->{'set' . ucfirst($method)}($config[$method]); <add> } <add> } <add> <add> if (isset($config['headers'])) { <add> $this->setHeaders($config['headers']); <add> } <add> <add> return $this; <add> } <add> <add> /** <add> * Set message content. <add> * <add> * @param array $content Content array with keys: <add> * - `textMessage` <add> * - `htmlMessage` <add> * - `boundary` <add> * - `message` <add> * @return $this <add> */ <add> public function setContent(array $content) <add> { <add> $this->_message = $content['message']; <add> $this->_boundary = $content['boundary']; <add> $this->_textMessage = $content['textMessage']; <add> $this->_htmlMessage = $content['htmlMessage']; <add> <add> return $this; <add> } <add> <add> /** <add> * Reset all the internal variables to be able to send out a new email. <add> * <add> * @return $this <add> */ <add> public function reset(): self <add> { <add> $this->_to = []; <add> $this->_from = []; <add> $this->_sender = []; <add> $this->_replyTo = []; <add> $this->_readReceipt = []; <add> $this->_returnPath = []; <add> $this->_cc = []; <add> $this->_bcc = []; <add> $this->_messageId = true; <add> $this->_subject = ''; <add> $this->_headers = []; <add> $this->_textMessage = ''; <add> $this->_htmlMessage = ''; <add> $this->_message = []; <add> $this->_emailFormat = static::MESSAGE_TEXT; <add> $this->_priority = null; <add> $this->charset = 'utf-8'; <add> $this->headerCharset = null; <add> $this->transferEncoding = null; <add> $this->_attachments = []; <add> $this->_profile = []; <add> $this->_emailPattern = self::EMAIL_PATTERN; <add> <add> return $this; <add> } <add> <add> /** <add> * Encode the specified string using the current charset <add> * <add> * @param string $text String to encode <add> * @return string Encoded string <add> */ <add> protected function _encode(string $text): string <add> { <add> $restore = mb_internal_encoding(); <add> mb_internal_encoding($this->_appCharset); <add> $return = mb_encode_mimeheader($text, $this->getHeaderCharset(), 'B'); <add> mb_internal_encoding($restore); <add> <add> return $return; <add> } <add> <add> /** <add> * Decode the specified string <add> * <add> * @param string $text String to decode <add> * @return string Decoded string <add> */ <add> protected function _decode(string $text): string <add> { <add> $restore = mb_internal_encoding(); <add> mb_internal_encoding($this->_appCharset); <add> $return = mb_decode_mimeheader($text); <add> mb_internal_encoding($restore); <add> <add> return $return; <add> } <add> <add> /** <add> * Read the file contents and return a base64 version of the file contents. <add> * <add> * @param string $path The absolute path to the file to read. <add> * @return string File contents in base64 encoding <add> */ <add> protected function _readFile(string $path): string <add> { <add> return chunk_split(base64_encode((string)file_get_contents($path))); <add> } <add> <add> /** <add> * Return the Content-Transfer Encoding value based <add> * on the set transferEncoding or set charset. <add> * <add> * @return string <add> */ <add> public function getContentTransferEncoding(): string <add> { <add> if ($this->transferEncoding) { <add> return $this->transferEncoding; <add> } <add> <add> $charset = strtoupper($this->charset); <add> if (in_array($charset, $this->_charset8bit)) { <add> return '8bit'; <add> } <add> <add> return '7bit'; <add> } <add> <add> /** <add> * Return charset value for Content-Type. <add> * <add> * Checks fallback/compatibility types which include workarounds <add> * for legacy japanese character sets. <add> * <add> * @return string <add> */ <add> public function getContentTypeCharset(): string <add> { <add> $charset = strtoupper($this->charset); <add> if (array_key_exists($charset, $this->_contentTypeCharset)) { <add> return strtoupper($this->_contentTypeCharset[$charset]); <add> } <add> <add> return strtoupper($this->charset); <add> } <add> <add> /** <add> * Serializes the email object to a value that can be natively serialized and re-used <add> * to clone this email instance. <add> * <add> * @return array Serializable array of configuration properties. <add> * @throws \Exception When a view var object can not be properly serialized. <add> */ <add> public function jsonSerialize(): array <add> { <add> $properties = [ <add> '_to', '_from', '_sender', '_replyTo', '_cc', '_bcc', '_subject', <add> '_returnPath', '_readReceipt', '_emailFormat', '_emailPattern', '_domain', <add> '_attachments', '_messageId', '_headers', '_appCharset', 'charset', 'headerCharset', <add> ]; <add> <add> foreach ($properties as $property) { <add> $array[$property] = $this->{$property}; <add> } <add> <add> array_walk($array['_attachments'], function (&$item, $key) { <add> if (!empty($item['file'])) { <add> $item['data'] = $this->_readFile($item['file']); <add> unset($item['file']); <add> } <add> }); <add> <add> return array_filter($array, function ($i) { <add> return !is_array($i) && !is_null($i) && strlen($i) || !empty($i); <add> }); <add> } <add> <add> /** <add> * Configures an email instance object from serialized config. <add> * <add> * @param array $config Email configuration array. <add> * @return $this Configured email instance. <add> */ <add> public function createFromArray(array $config): self <add> { <add> foreach ($config as $property => $value) { <add> $this->{$property} = $value; <add> } <add> <add> return $this; <add> } <add> <add> /** <add> * Serializes the Email object. <add> * <add> * @return string <add> */ <add> public function serialize(): string <add> { <add> $array = $this->jsonSerialize(); <add> array_walk_recursive($array, function (&$item, $key) { <add> if ($item instanceof SimpleXMLElement) { <add> $item = json_decode(json_encode((array)$item), true); <add> } <add> }); <add> <add> return serialize($array); <add> } <add> <add> /** <add> * Unserializes the Email object. <add> * <add> * @param string $data Serialized string. <add> * @return static Configured email instance. <add> */ <add> public function unserialize($data): self <add> { <add> return $this->createFromArray(unserialize($data)); <add> } <add>} <ide><path>tests/TestCase/Mailer/EmailTest.php <ide> use Cake\TestSuite\TestCase; <ide> use Exception; <ide> use SimpleXmlElement; <del>use TestApp\Mailer\Email\TestEmail; <add>use TestApp\Mailer\TestEmail; <ide> <ide> /** <ide> * EmailTest class <ide> public function testEmptyTo() <ide> */ <ide> public function testFormatAddress() <ide> { <del> $result = $this->Email->formatAddress(['cake@cakephp.org' => 'cake@cakephp.org']); <add> $result = $this->Email->getMessage()->formatAddress(['cake@cakephp.org' => 'cake@cakephp.org']); <ide> $expected = ['cake@cakephp.org']; <ide> $this->assertSame($expected, $result); <ide> <del> $result = $this->Email->formatAddress(['cake@cakephp.org' => 'cake@cakephp.org', 'php@cakephp.org' => 'php@cakephp.org']); <add> $result = $this->Email->getMessage()->formatAddress([ <add> 'cake@cakephp.org' => 'cake@cakephp.org', <add> 'php@cakephp.org' => 'php@cakephp.org' <add> ]); <ide> $expected = ['cake@cakephp.org', 'php@cakephp.org']; <ide> $this->assertSame($expected, $result); <ide> <del> $result = $this->Email->formatAddress(['cake@cakephp.org' => 'CakePHP', 'php@cakephp.org' => 'Cake']); <add> $result = $this->Email->getMessage()->formatAddress([ <add> 'cake@cakephp.org' => 'CakePHP', <add> 'php@cakephp.org' => 'Cake' <add> ]); <ide> $expected = ['CakePHP <cake@cakephp.org>', 'Cake <php@cakephp.org>']; <ide> $this->assertSame($expected, $result); <ide> <del> $result = $this->Email->formatAddress(['me@example.com' => 'Last, First']); <add> $result = $this->Email->getMessage()->formatAddress(['me@example.com' => 'Last, First']); <ide> $expected = ['"Last, First" <me@example.com>']; <ide> $this->assertSame($expected, $result); <ide> <del> $result = $this->Email->formatAddress(['me@example.com' => '"Last" First']); <add> $result = $this->Email->getMessage()->formatAddress(['me@example.com' => '"Last" First']); <ide> $expected = ['"\"Last\" First" <me@example.com>']; <ide> $this->assertSame($expected, $result); <ide> <del> $result = $this->Email->formatAddress(['me@example.com' => 'Last First']); <add> $result = $this->Email->getMessage()->formatAddress(['me@example.com' => 'Last First']); <ide> $expected = ['Last First <me@example.com>']; <ide> $this->assertSame($expected, $result); <ide> <del> $result = $this->Email->formatAddress(['cake@cakephp.org' => 'ÄÖÜTest']); <add> $result = $this->Email->getMessage()->formatAddress(['cake@cakephp.org' => 'ÄÖÜTest']); <ide> $expected = ['=?UTF-8?B?w4TDlsOcVGVzdA==?= <cake@cakephp.org>']; <ide> $this->assertSame($expected, $result); <ide> <del> $result = $this->Email->formatAddress(['cake@cakephp.org' => '日本語Test']); <add> $result = $this->Email->getMessage()->formatAddress(['cake@cakephp.org' => '日本語Test']); <ide> $expected = ['=?UTF-8?B?5pel5pys6KqeVGVzdA==?= <cake@cakephp.org>']; <ide> $this->assertSame($expected, $result); <ide> } <ide> public function testFormatAddress() <ide> public function testFormatAddressJapanese() <ide> { <ide> $this->Email->setHeaderCharset('ISO-2022-JP'); <del> $result = $this->Email->formatAddress(['cake@cakephp.org' => '日本語Test']); <add> $result = $this->Email->getMessage()->formatAddress(['cake@cakephp.org' => '日本語Test']); <ide> $expected = ['=?ISO-2022-JP?B?GyRCRnxLXDhsGyhCVGVzdA==?= <cake@cakephp.org>']; <ide> $this->assertSame($expected, $result); <ide> <del> $result = $this->Email->formatAddress(['cake@cakephp.org' => '寿限無寿限無五劫の擦り切れ海砂利水魚の水行末雲来末風来末食う寝る処に住む処やぶら小路の藪柑子パイポパイポパイポのシューリンガンシューリンガンのグーリンダイグーリンダイのポンポコピーのポンポコナーの長久命の長助']); <add> $result = $this->Email->getMessage()->formatAddress(['cake@cakephp.org' => '寿限無寿限無五劫の擦り切れ海砂利水魚の水行末雲来末風来末食う寝る処に住む処やぶら小路の藪柑子パイポパイポパイポのシューリンガンシューリンガンのグーリンダイグーリンダイのポンポコピーのポンポコナーの長久命の長助']); <ide> $expected = ["=?ISO-2022-JP?B?GyRCPHc4Qkw1PHc4Qkw1OF45ZSROOyQkakBaJGwzJDo9TXg/ZTV7GyhC?=\r\n" . <ide> " =?ISO-2022-JP?B?GyRCJE4/ZTlUS3YxQE1oS3ZJd01oS3Y/KSQmPzIkaz1oJEs9OyRgGyhC?=\r\n" . <ide> " =?ISO-2022-JP?B?GyRCPWgkZCRWJGk+Lk8pJE5pLjQ7O1IlUSUkJV0lUSUkJV0lUSUkGyhC?=\r\n" . <ide> public function testResetWithCharset() <ide> $this->Email->reset(); <ide> <ide> $this->assertSame('utf-8', $this->Email->getCharset()); <del> $this->assertNull($this->Email->getHeaderCharset()); <add> $this->assertSame('utf-8', $this->Email->getHeaderCharset()); <ide> } <ide> <ide> /** <ide> protected function _checkContentTransferEncoding($message, $charset) <ide> public function testEncode() <ide> { <ide> $this->Email->setHeaderCharset('ISO-2022-JP'); <del> $result = $this->Email->encode('日本語'); <add> $result = $this->Email->getMessage()->encode('日本語'); <ide> $expected = '=?ISO-2022-JP?B?GyRCRnxLXDhsGyhC?='; <ide> $this->assertSame($expected, $result); <ide> <ide> $this->Email->setHeaderCharset('ISO-2022-JP'); <del> $result = $this->Email->encode('長い長い長いSubjectの場合はfoldingするのが正しいんだけどいったいどうなるんだろう?'); <add> $result = $this->Email->getMessage()->encode('長い長い長いSubjectの場合はfoldingするのが正しいんだけどいったいどうなるんだろう?'); <ide> $expected = "=?ISO-2022-JP?B?GyRCRDkkJEQ5JCREOSQkGyhCU3ViamVjdBskQiROPmw5ZyRPGyhCZm9s?=\r\n" . <ide> " =?ISO-2022-JP?B?ZGluZxskQiQ5JGskTiQsQDUkNyQkJHMkQCQxJEkkJCRDJD8kJCRJGyhC?=\r\n" . <ide> ' =?ISO-2022-JP?B?GyRCJCYkSiRrJHMkQCRtJCYhKRsoQg==?='; <ide> public function testEncode() <ide> public function testDecode() <ide> { <ide> $this->Email->setHeaderCharset('ISO-2022-JP'); <del> $result = $this->Email->decode('=?ISO-2022-JP?B?GyRCRnxLXDhsGyhC?='); <add> $result = $this->Email->getMessage()->decode('=?ISO-2022-JP?B?GyRCRnxLXDhsGyhC?='); <ide> $expected = '日本語'; <ide> $this->assertSame($expected, $result); <ide> <ide> $this->Email->setHeaderCharset('ISO-2022-JP'); <del> $result = $this->Email->decode("=?ISO-2022-JP?B?GyRCRDkkJEQ5JCREOSQkGyhCU3ViamVjdBskQiROPmw5ZyRPGyhCZm9s?=\r\n" . <add> $result = $this->Email->getMessage()->decode("=?ISO-2022-JP?B?GyRCRDkkJEQ5JCREOSQkGyhCU3ViamVjdBskQiROPmw5ZyRPGyhCZm9s?=\r\n" . <ide> " =?ISO-2022-JP?B?ZGluZxskQiQ5JGskTiQsQDUkNyQkJHMkQCQxJEkkJCRDJD8kJCRJGyhC?=\r\n" . <ide> ' =?ISO-2022-JP?B?GyRCJCYkSiRrJHMkQCRtJCYhKRsoQg==?='); <ide> $expected = '長い長い長いSubjectの場合はfoldingするのが正しいんだけどいったいどうなるんだろう?'; <ide> public function testJsonSerialize() <ide> '_domain' => 'foo.bar', <ide> '_appCharset' => 'UTF-8', <ide> 'charset' => 'utf-8', <del> 'headerCharset' => 'utf-8', <ide> 'viewConfig' => [ <ide> '_template' => 'default', <ide> '_layout' => 'test', <ide><path>tests/test_app/TestApp/Mailer/TestEmail.php <add><?php <add>declare(strict_types=1); <add>namespace TestApp\Mailer; <add> <add>use Cake\Mailer\Email; <add> <add>/** <add> * Help to test Email <add> */ <add>class TestEmail extends Email <add>{ <add> protected $messageClass = TestMessage::class; <add>} <add><path>tests/test_app/TestApp/Mailer/TestMessage.php <del><path>tests/test_app/TestApp/Mailer/Email/TestEmail.php <ide> <?php <ide> declare(strict_types=1); <del>namespace TestApp\Mailer\Email; <add>namespace TestApp\Mailer; <ide> <del>use Cake\Mailer\Email; <add>use Cake\Mailer\Message; <ide> <ide> /** <del> * Help to test Email <add> * Help to test Message <ide> */ <del>class TestEmail extends Email <add>class TestMessage extends Message <ide> { <ide> /** <ide> * Wrap to protected method
5
PHP
PHP
allow collection prepend with a key
7cdbd874d82d201e2a100b4684ec04e707a4184d
<ide><path>src/Illuminate/Support/Collection.php <ide> public function pop() <ide> * Push an item onto the beginning of the collection. <ide> * <ide> * @param mixed $value <add> * @param mixed $key <ide> * @return $this <ide> */ <del> public function prepend($value) <add> public function prepend($value, $key = null) <ide> { <del> array_unshift($this->items, $value); <add> if (is_null($key)) { <add> array_unshift($this->items, $value); <add> } else { <add> $this->items = [$key => $value] + $this->items; <add> } <ide> <ide> return $this; <ide> } <ide><path>tests/Support/SupportCollectionTest.php <ide> public function testPaginate() <ide> $this->assertEquals([], $c->forPage(3, 2)->all()); <ide> } <ide> <add> public function testPrepend() <add> { <add> $c = new Collection(['one', 'two', 'three', 'four']); <add> $this->assertEquals(['zero', 'one', 'two', 'three', 'four'], $c->prepend('zero')->all()); <add> <add> $c = new Collection(['one' => 1, 'two' => 2]); <add> $this->assertEquals(['zero' => 0, 'one' => 1, 'two' => 2], $c->prepend(0, 'zero')->all()); <add> } <add> <ide> public function testZip() <ide> { <ide> $c = new Collection([1, 2, 3]);
2
Text
Text
move the code of conduct to tsc repository
258494c2f8834d1401cc57db9ee434e1dacfa348
<ide><path>CODE_OF_CONDUCT.md <ide> # Code of Conduct <ide> <del>## Conduct <del> <del>* We are committed to providing a friendly, safe and welcoming <del> environment for all, regardless of level of experience, gender <del> identity and expression, sexual orientation, disability, <del> personal appearance, body size, race, ethnicity, age, religion, <del> nationality, or other similar characteristic. <del>* Please avoid using overtly sexual nicknames or other nicknames that <del> might detract from a friendly, safe and welcoming environment for <del> all. <del>* Please be kind and courteous. There's no need to be mean or rude. <del>* Respect that some individuals and cultures consider the casual use of <del> profanity and sexualized language offensive and off-putting. <del>* Respect that people have differences of opinion and that every <del> design or implementation choice carries a trade-off and numerous <del> costs. There is seldom a right answer. <del>* Please keep unstructured critique to a minimum. If you have solid <del> ideas you want to experiment with, make a fork and see how it works. <del>* We will exclude you from interaction if you insult, demean or harass <del> anyone. That is not welcome behavior. We interpret the term <del> "harassment" as including the definition in the [Citizen Code of <del> Conduct](http://citizencodeofconduct.org/); if you have any lack of <del> clarity about what might be included in that concept, please read <del> their definition. In particular, we don't tolerate behavior that <del> excludes people in socially marginalized groups. <del>* Private harassment is also unacceptable. No matter who you are, if <del> you feel you have been or are being harassed or made uncomfortable <del> by a community member, please contact one of the channel ops or any <del> of the TSC members immediately with a capture (log, photo, email) of <del> the harassment if possible. Whether you're a regular contributor or <del> a newcomer, we care about making this community a safe place for you <del> and we've got your back. <del>* Likewise any spamming, trolling, flaming, baiting or other <del> attention-stealing behavior is not welcome. <del>* Avoid the use of personal pronouns in code comments or <del> documentation. There is no need to address persons when explaining <del> code (e.g. "When the developer"). <del> <del>## Contact <del>Instances of abusive, harassing, or otherwise unacceptable behavior may be <del>reported by: <del> <del>* Emailing [report@nodejs.org](mailto:report@nodejs.org) (this will email all TSC members) <del>* Contacting [individual TSC members](https://nodejs.org/en/foundation/tsc/#current-members-of-the-technical-steering-committee). <del> <del>## Moderation <del>See the TSC's [moderation policy](https://github.com/nodejs/TSC/blob/master/Moderation-Policy.md) for details about moderation. <del> <del>## Attribution <del> <del>This Code of Conduct is adapted from [Rust's wonderful <del>CoC](http://www.rust-lang.org/conduct.html) as well as the <del>[Contributor Covenant v1.3.0](http://contributor-covenant.org/version/1/3/0/). <add>The Node.js Code of Conduct document has moved to <add>https://github.com/nodejs/TSC/blob/master/CODE_OF_CONDUCT.md. Please update <add>links to this document accordingly. <ide><path>README.md <ide> open source libraries in the world. <ide> The Node.js project is supported by the <ide> [Node.js Foundation](https://nodejs.org/en/foundation/). Contributions, <ide> policies, and releases are managed under an <del>[open governance model](./GOVERNANCE.md). We are also bound by a <del>[Code of Conduct](./CODE_OF_CONDUCT.md). <add>[open governance model](./GOVERNANCE.md). <add> <add>**This project is bound by a [Code of Conduct][].** <ide> <ide> If you need help using or installing Node.js, please use the <ide> [nodejs/help](https://github.com/nodejs/help) issue tracker. <ide> Information on the current Node.js Working Groups can be found in the <ide> [Node.js Moderation Policy]: https://github.com/nodejs/TSC/blob/master/Moderation-Policy.md <ide> [#node.js on chat.freenode.net]: https://webchat.freenode.net?channels=node.js&uio=d4 <ide> [#node-dev on chat.freenode.net]: https://webchat.freenode.net?channels=node-dev&uio=d4 <add>[Code of Conduct]: https://github.com/nodejs/TSC/blob/master/CODE_OF_CONDUCT.md
2
Javascript
Javascript
remove outdated file
c637ca0d031ac35b716303258e82a1a8eb8f7a27
<ide><path>packager/src/Cache/__mocks__/Cache.js <del>/** <del> * Copyright (c) 2015-present, Facebook, Inc. <del> * All rights reserved. <del> * <del> * This source code is licensed under the BSD-style license found in the <del> * LICENSE file in the root directory of this source tree. An additional grant <del> * of patent rights can be found in the PATENTS file in the same directory. <del> */ <del>'use strict'; <del> <del>const mockColor = () => { <del> return { <del> bold: () => { return { }; }, <del> }; <del>}; <del> <del>mockColor.bold = function() { <del> return {}; <del>}; <del> <del>module.exports = { <del> dim: s => s, <del> magenta: mockColor, <del> white: mockColor, <del> blue: mockColor, <del> yellow: mockColor, <del> green: mockColor, <del> bold: mockColor, <del> red: mockColor, <del> cyan: mockColor, <del> gray: mockColor, <del> black: mockColor, <del>};
1
Text
Text
remove lstm_benchmark from examples/readme.md
2abf10c3a429a7c8146925930d8111b7a71dbdba
<ide><path>examples/README.md <ide> Trains a FastText model on the IMDB sentiment classification task. <ide> [imdb_lstm.py](imdb_lstm.py) <ide> Trains an LSTM model on the IMDB sentiment classification task. <ide> <del>[lstm_benchmark.py](lstm_benchmark.py) <del>Compares different LSTM implementations on the IMDB sentiment classification task. <del> <ide> [lstm_text_generation.py](lstm_text_generation.py) <ide> Generates text from Nietzsche's writings. <ide>
1
Ruby
Ruby
handle location indicating the current dir
5e2f87f7ac860fc18105ef60a63c141b405ea0f8
<ide><path>Library/Homebrew/download_strategy.rb <ide> def resolve_url_basename_time(url) <ide> elsif location.start_with?("/") <ide> uri = URI(current_url) <ide> "#{uri.scheme}://#{uri.host}#{location}" <add> elsif location.start_with?("./") <add> uri = URI(current_url) <add> "#{uri.scheme}://#{uri.host}#{Pathname(uri.path).dirname/location}" <ide> else <ide> location <ide> end
1
Ruby
Ruby
add specs for `caskloader`
efbc1b0cb489ccc35110b4013145ded2abd3e03f
<ide><path>Library/Homebrew/test/cask/cask_loader/from_content_loader_spec.rb <add>describe Hbc::CaskLoader::FromContentLoader do <add> alias_matcher :be_able_to_load, :be_can_load <add> <add> describe "::can_load?" do <add> it "returns true for Casks specified with `cask \"token\" do … end`" do <add> expect(described_class).to be_able_to_load <<~EOS <add> cask "token" do <add> end <add> EOS <add> end <add> <add> it "returns true for Casks specified with `cask \"token\" do; end`" do <add> expect(described_class).to be_able_to_load <<~EOS <add> cask "token" do; end <add> EOS <add> end <add> <add> it "returns true for Casks specified with `cask 'token' do … end`" do <add> expect(described_class).to be_able_to_load <<~EOS <add> cask 'token' do <add> end <add> EOS <add> end <add> <add> it "returns true for Casks specified with `cask 'token' do; end`" do <add> expect(described_class).to be_able_to_load <<~EOS <add> cask 'token' do; end <add> EOS <add> end <add> <add> it "returns true for Casks specified with `cask(\"token\") { … }`" do <add> expect(described_class).to be_able_to_load <<~EOS <add> cask("token") { <add> } <add> EOS <add> end <add> <add> it "returns true for Casks specified with `cask(\"token\") {}`" do <add> expect(described_class).to be_able_to_load <<~EOS <add> cask("token") {} <add> EOS <add> end <add> <add> it "returns true for Casks specified with `cask('token') { … }`" do <add> expect(described_class).to be_able_to_load <<~EOS <add> cask('token') { <add> } <add> EOS <add> end <add> <add> it "returns true for Casks specified with `cask('token') {}`" do <add> expect(described_class).to be_able_to_load <<~EOS <add> cask('token') {} <add> EOS <add> end <add> end <add>end <ide><path>Library/Homebrew/test/cask/cask_loader/from_uri_loader_spec.rb <add>describe Hbc::CaskLoader::FromURILoader do <add> alias_matcher :be_able_to_load, :be_can_load <add> <add> describe "::can_load?" do <add> it "returns true when given an URI" do <add> expect(described_class).to be_able_to_load(URI("http://example.com/")) <add> end <add> <add> it "returns true when given a String which can be parsed to a URI" do <add> expect(described_class).to be_able_to_load("http://example.com/") <add> end <add> <add> it "returns false when given a String with Cask contents containing a URL" do <add> expect(described_class).not_to be_able_to_load <<~EOS <add> cask 'token' do <add> url 'http://example.com/' <add> end <add> EOS <add> end <add> end <add>end
2
Python
Python
add xlm-roberta to glue script
a26ce4dee116a1d5d9099c8a94e22d1e31ad631c
<ide><path>examples/run_glue.py <ide> AlbertConfig, <ide> AlbertForSequenceClassification, <ide> AlbertTokenizer, <add> XLMRobertaConfig, <add> XLMRobertaForSequenceClassification, <add> XLMRobertaTokenizer, <ide> ) <ide> <ide> from transformers import AdamW, get_linear_schedule_with_warmup <ide> 'xlm': (XLMConfig, XLMForSequenceClassification, XLMTokenizer), <ide> 'roberta': (RobertaConfig, RobertaForSequenceClassification, RobertaTokenizer), <ide> 'distilbert': (DistilBertConfig, DistilBertForSequenceClassification, DistilBertTokenizer), <del> 'albert': (AlbertConfig, AlbertForSequenceClassification, AlbertTokenizer) <add> 'albert': (AlbertConfig, AlbertForSequenceClassification, AlbertTokenizer), <add> 'xlmroberta': (XLMRobertaConfig, XLMRobertaForSequenceClassification, XLMRobertaTokenizer), <ide> } <ide> <ide> <ide> def load_and_cache_examples(args, task, tokenizer, evaluate=False): <ide> else: <ide> logger.info("Creating features from dataset file at %s", args.data_dir) <ide> label_list = processor.get_labels() <del> if task in ['mnli', 'mnli-mm'] and args.model_type in ['roberta']: <add> if task in ['mnli', 'mnli-mm'] and args.model_type in ['roberta', 'xlmroberta']: <ide> # HACK(label indices are swapped in RoBERTa pretrained model) <del> label_list[1], label_list[2] = label_list[2], label_list[1] <add> label_list[1], label_list[2] = label_list[2], label_list[1] <ide> examples = processor.get_dev_examples(args.data_dir) if evaluate else processor.get_train_examples(args.data_dir) <ide> features = convert_examples_to_features(examples, <ide> tokenizer,
1
Javascript
Javascript
use proper names for scroll metric properties
2aa5631e2eba008327b71f529fb9a975fecbcf99
<ide><path>src/event/synthetic/SyntheticMouseEvent.js <ide> var MouseEventInterface = { <ide> pageX: function(event) { <ide> return 'pageX' in event ? <ide> event.pageX : <del> event.clientX + ViewportMetrics.currentPageScrollLeft; <add> event.clientX + ViewportMetrics.currentScrollLeft; <ide> }, <ide> pageY: function(event) { <ide> return 'pageY' in event ? <ide> event.pageY : <del> event.clientY + ViewportMetrics.currentPageScrollTop; <add> event.clientY + ViewportMetrics.currentScrollTop; <ide> } <ide> }; <ide>
1
Text
Text
fix some errors in translation
889eeea46efb8fe9fefff9918b5e97a513997dcc
<ide><path>threejs/lessons/fr/threejs-lights.md <ide> Title: Lumières en Three.js <del>Description: Configuration des mulières <del>TOC: Lights <add>Description: Configuration des lumières <add>TOC: Lumières <ide> <ide> Cet article fait partie d'une série consacrée à Three.js. <ide> Le premier article s'intitule [Principes de base](threejs-fundamentals.html). Si vous ne l'avez pas encore lu, vous voudriez peut-être commencer par là ou aussi voir l'article sur [la configuartion de votre environnement](threejs-setup.html). L'
1
Go
Go
remove deprecated environment.daemonplatform()
18a771a761654e241ae8d1e85aa0c0a6164c5d27
<ide><path>integration-cli/docker_api_build_test.go <ide> func (s *DockerSuite) TestBuildAPIDockerFileRemote(c *check.C) { <ide> testRequires(c, NotUserNamespace) <ide> <ide> var testD string <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> testD = `FROM busybox <ide> RUN find / -name ba* <ide> RUN find /tmp/` <ide><path>integration-cli/docker_api_containers_test.go <ide> func (s *DockerSuite) TestContainerAPIWait(c *check.C) { <ide> name := "test-api-wait" <ide> <ide> sleepCmd := "/bin/sleep" <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> sleepCmd = "sleep" <ide> } <ide> dockerCmd(c, "run", "--name", name, "busybox", sleepCmd, "2") <ide> func (s *DockerSuite) TestContainerAPIDeleteRemoveVolume(c *check.C) { <ide> testRequires(c, SameHostDaemon) <ide> <ide> vol := "/testvolume" <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> vol = `c:\testvolume` <ide> } <ide> <ide> func (s *DockerSuite) TestContainersAPICreateMountsCreate(c *check.C) { <ide> var ( <ide> testImg string <ide> ) <del> if testEnv.DaemonPlatform() != "windows" { <add> if testEnv.OSType != "windows" { <ide> testImg = "test-mount-config" <ide> buildImageSuccessfully(c, testImg, build.WithDockerfile(` <ide> FROM busybox <ide> func (s *DockerSuite) TestContainersAPICreateMountsCreate(c *check.C) { <ide> } <ide> } <ide> <del> if testEnv.DaemonPlatform() != "windows" { // Windows does not support volume populate <add> if testEnv.OSType != "windows" { // Windows does not support volume populate <ide> cases = append(cases, []testCase{ <ide> { <ide> spec: mounttypes.Mount{Type: "volume", Target: destPath, VolumeOptions: &mounttypes.VolumeOptions{NoCopy: true}}, <ide><path>integration-cli/docker_api_images_test.go <ide> func (s *DockerSuite) TestAPIImagesDelete(c *check.C) { <ide> c.Assert(err, checker.IsNil) <ide> defer cli.Close() <ide> <del> if testEnv.DaemonPlatform() != "windows" { <add> if testEnv.OSType != "windows" { <ide> testRequires(c, Network) <ide> } <ide> name := "test-api-images-delete" <ide> func (s *DockerSuite) TestAPIImagesHistory(c *check.C) { <ide> c.Assert(err, checker.IsNil) <ide> defer cli.Close() <ide> <del> if testEnv.DaemonPlatform() != "windows" { <add> if testEnv.OSType != "windows" { <ide> testRequires(c, Network) <ide> } <ide> name := "test-api-images-history" <ide><path>integration-cli/docker_api_inspect_test.go <ide> func (s *DockerSuite) TestInspectAPIContainerResponse(c *check.C) { <ide> <ide> var cases []acase <ide> <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> cases = []acase{ <ide> {"v1.25", append(keysBase, "Mounts")}, <ide> } <ide><path>integration-cli/docker_api_stats_test.go <ide> func (s *DockerSuite) TestAPIStatsNoStreamGetCpu(c *check.C) { <ide> <ide> var cpuPercent = 0.0 <ide> <del> if testEnv.DaemonPlatform() != "windows" { <add> if testEnv.OSType != "windows" { <ide> cpuDelta := float64(v.CPUStats.CPUUsage.TotalUsage - v.PreCPUStats.CPUUsage.TotalUsage) <ide> systemDelta := float64(v.CPUStats.SystemUsage - v.PreCPUStats.SystemUsage) <ide> cpuPercent = (cpuDelta / systemDelta) * float64(len(v.CPUStats.CPUUsage.PercpuUsage)) * 100.0 <ide> func (s *DockerSuite) TestAPIStatsNetworkStats(c *check.C) { <ide> <ide> // Retrieve the container address <ide> net := "bridge" <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> net = "nat" <ide> } <ide> contIP := findContainerIP(c, id, net) <ide> func (s *DockerSuite) TestAPIStatsNetworkStats(c *check.C) { <ide> // On Linux, account for ARP. <ide> expRxPkts := preRxPackets + uint64(numPings) <ide> expTxPkts := preTxPackets + uint64(numPings) <del> if testEnv.DaemonPlatform() != "windows" { <add> if testEnv.OSType != "windows" { <ide> expRxPkts++ <ide> expTxPkts++ <ide> } <ide><path>integration-cli/docker_api_test.go <ide> func (s *DockerSuite) TestAPIGetEnabledCORS(c *check.C) { <ide> } <ide> <ide> func (s *DockerSuite) TestAPIClientVersionOldNotSupported(c *check.C) { <del> if testEnv.DaemonPlatform() != runtime.GOOS { <add> if testEnv.OSType != runtime.GOOS { <ide> c.Skip("Daemon platform doesn't match test platform") <ide> } <ide> if api.MinVersion == api.DefaultVersion { <ide><path>integration-cli/docker_cli_build_test.go <ide> func (s *DockerSuite) TestBuildJSONEmptyRun(c *check.C) { <ide> func (s *DockerSuite) TestBuildShCmdJSONEntrypoint(c *check.C) { <ide> name := "testbuildshcmdjsonentrypoint" <ide> expected := "/bin/sh -c echo test" <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> expected = "cmd /S /C echo test" <ide> } <ide> <ide> func (s *DockerSuite) TestBuildEnvironmentReplacementVolume(c *check.C) { <ide> <ide> var volumePath string <ide> <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> volumePath = "c:/quux" <ide> } else { <ide> volumePath = "/quux" <ide> func (s *DockerSuite) TestBuildEnvironmentReplacementWorkdir(c *check.C) { <ide> res := inspectFieldJSON(c, name, "Config.WorkingDir") <ide> <ide> expected := `"/work"` <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> expected = `"C:\\work"` <ide> } <ide> if res != expected { <ide> func (s *DockerSuite) TestBuildRelativeWorkdir(c *check.C) { <ide> expectedFinal string <ide> ) <ide> <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> expected1 = `C:/` <ide> expected2 = `C:/test1` <ide> expected3 = `C:/test2` <ide> func (s *DockerSuite) TestBuildWorkdirWithEnvVariables(c *check.C) { <ide> name := "testbuildworkdirwithenvvariables" <ide> <ide> var expected string <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> expected = `C:\test1\test2` <ide> } else { <ide> expected = `/test1/test2` <ide> func (s *DockerSuite) TestBuildRelativeCopy(c *check.C) { <ide> testRequires(c, NotUserNamespace) <ide> <ide> var expected string <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> expected = `C:/test1/test2` <ide> } else { <ide> expected = `/test1/test2` <ide> func (s *DockerSuite) TestBuildAddFileNotFound(c *check.C) { <ide> name := "testbuildaddnotfound" <ide> expected := "foo: no such file or directory" <ide> <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> expected = "foo: The system cannot find the file specified" <ide> } <ide> <ide> func (s *DockerSuite) TestBuildOnBuild(c *check.C) { <ide> // gh #2446 <ide> func (s *DockerSuite) TestBuildAddToSymlinkDest(c *check.C) { <ide> makeLink := `ln -s /foo /bar` <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> makeLink = `mklink /D C:\bar C:\foo` <ide> } <ide> name := "testbuildaddtosymlinkdest" <ide> func (s *DockerSuite) TestBuildCmdShDashC(c *check.C) { <ide> <ide> res := inspectFieldJSON(c, name, "Config.Cmd") <ide> expected := `["/bin/sh","-c","echo cmd"]` <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> expected = `["cmd","/S","/C","echo cmd"]` <ide> } <ide> if res != expected { <ide> func (s *DockerSuite) TestBuildEntrypointCanBeOverriddenByChildInspect(c *check. <ide> expected = `["/bin/sh","-c","echo quux"]` <ide> ) <ide> <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> expected = `["cmd","/S","/C","echo quux"]` <ide> } <ide> <ide> func (s *DockerSuite) TestBuildVerifySingleQuoteFails(c *check.C) { <ide> // it should barf on it. <ide> name := "testbuildsinglequotefails" <ide> expectedExitCode := 2 <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> expectedExitCode = 127 <ide> } <ide> <ide> func (s *DockerSuite) TestBuildVerboseOut(c *check.C) { <ide> name := "testbuildverboseout" <ide> expected := "\n123\n" <ide> <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> expected = "\n123\r\n" <ide> } <ide> <ide> func (s *DockerSuite) TestBuildWithTabs(c *check.C) { <ide> res := inspectFieldJSON(c, name, "ContainerConfig.Cmd") <ide> expected1 := `["/bin/sh","-c","echo\tone\t\ttwo"]` <ide> expected2 := `["/bin/sh","-c","echo\u0009one\u0009\u0009two"]` // syntactically equivalent, and what Go 1.3 generates <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> expected1 = `["cmd","/S","/C","echo\tone\t\ttwo"]` <ide> expected2 = `["cmd","/S","/C","echo\u0009one\u0009\u0009two"]` // syntactically equivalent, and what Go 1.3 generates <ide> } <ide> func (s *DockerSuite) TestBuildStderr(c *check.C) { <ide> result.Assert(c, icmd.Success) <ide> <ide> // Windows to non-Windows should have a security warning <del> if runtime.GOOS == "windows" && testEnv.DaemonPlatform() != "windows" && !strings.Contains(result.Stdout(), "SECURITY WARNING:") { <add> if runtime.GOOS == "windows" && testEnv.OSType != "windows" && !strings.Contains(result.Stdout(), "SECURITY WARNING:") { <ide> c.Fatalf("Stdout contains unexpected output: %q", result.Stdout()) <ide> } <ide> <ide> func (s *DockerSuite) TestBuildVolumesRetainContents(c *check.C) { <ide> volName = "/foo" <ide> ) <ide> <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> volName = "C:/foo" <ide> } <ide> <ide> RUN echo " \ <ide> <ide> expected := "\n foo \n" <ide> // Windows uses the builtin echo, which preserves quotes <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> expected = "\" foo \"" <ide> } <ide> <ide> func (s *DockerSuite) TestBuildMissingArgs(c *check.C) { <ide> "INSERT": {}, <ide> } <ide> <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> skipCmds = map[string]struct{}{ <ide> "CMD": {}, <ide> "RUN": {}, <ide> func (s *DockerSuite) TestBuildRUNErrMsg(c *check.C) { <ide> name := "testbuildbadrunerrmsg" <ide> shell := "/bin/sh -c" <ide> exitCode := 127 <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> shell = "cmd /S /C" <ide> // architectural - Windows has to start the container to determine the exe is bad, Linux does not <ide> exitCode = 1 <ide> func (s *DockerTrustSuite) TestTrustedBuildTagIgnoresOtherDelegationRoles(c *che <ide> func (s *DockerSuite) TestBuildNullStringInAddCopyVolume(c *check.C) { <ide> name := "testbuildnullstringinaddcopyvolume" <ide> volName := "nullvolume" <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> volName = `C:\\nullvolume` <ide> } <ide> <ide> func (s *DockerSuite) TestBuildBuildTimeArg(c *check.C) { <ide> envKey := "foo" <ide> envVal := "bar" <ide> var dockerfile string <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> // Bugs in Windows busybox port - use the default base image and native cmd stuff <ide> dockerfile = fmt.Sprintf(`FROM `+minimalBaseImage()+` <ide> ARG %s <ide> func (s *DockerSuite) TestBuildMultiStageUnusedArg(c *check.C) { <ide> func (s *DockerSuite) TestBuildNoNamedVolume(c *check.C) { <ide> volName := "testname:/foo" <ide> <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> volName = "testname:C:\\foo" <ide> } <ide> dockerCmd(c, "run", "-v", volName, "busybox", "sh", "-c", "touch /foo/oops") <ide> WORKDIR /foo/bar <ide> <ide> // The Windows busybox image has a blank `cmd` <ide> lookingFor := `["sh"]` <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> lookingFor = "null" <ide> } <ide> c.Assert(strings.TrimSpace(out), checker.Equals, lookingFor) <ide><path>integration-cli/docker_cli_commit_test.go <ide> func (s *DockerSuite) TestCommitChange(c *check.C) { <ide> // ENV. On windows, the container doesn't have a `PATH` ENV variable so <ide> // the ordering is the same as the cli. <ide> expectedEnv := "[PATH=/foo DEBUG=true test=1]" <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> expectedEnv = "[DEBUG=true test=1 PATH=/foo]" <ide> } <ide> <ide><path>integration-cli/docker_cli_create_test.go <ide> func (s *DockerSuite) TestCreateArgs(c *check.C) { <ide> // Make sure we can grow the container's rootfs at creation time. <ide> func (s *DockerSuite) TestCreateGrowRootfs(c *check.C) { <ide> // Windows and Devicemapper support growing the rootfs <del> if testEnv.DaemonPlatform() != "windows" { <add> if testEnv.OSType != "windows" { <ide> testRequires(c, Devicemapper) <ide> } <ide> out, _ := dockerCmd(c, "create", "--storage-opt", "size=120G", "busybox") <ide> func (s *DockerSuite) TestCreateLabelFromImage(c *check.C) { <ide> func (s *DockerSuite) TestCreateHostnameWithNumber(c *check.C) { <ide> image := "busybox" <ide> // Busybox on Windows does not implement hostname command <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> image = testEnv.PlatformDefaults.BaseImage <ide> } <ide> out, _ := dockerCmd(c, "run", "-h", "web.0", image, "hostname") <ide> func (s *DockerSuite) TestCreateWithWorkdir(c *check.C) { <ide> <ide> dockerCmd(c, "create", "--name", name, "-w", dir, "busybox") <ide> // Windows does not create the workdir until the container is started <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> dockerCmd(c, "start", name) <ide> } <ide> dockerCmd(c, "cp", fmt.Sprintf("%s:%s", name, dir), prefix+slash+"tmp") <ide><path>integration-cli/docker_cli_diff_test.go <ide> func (s *DockerSuite) TestDiffFilenameShownInOutput(c *check.C) { <ide> // a "Files/" prefix. <ide> containerID := strings.TrimSpace(out) <ide> lookingFor := "A /foo/bar" <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> cli.WaitExited(c, containerID, 60*time.Second) <ide> lookingFor = "C Files/foo/bar" <ide> } <ide><path>integration-cli/docker_cli_events_test.go <ide> func (s *DockerSuite) TestEventsContainerRestart(c *check.C) { <ide> <ide> // wait until test2 is auto removed. <ide> waitTime := 10 * time.Second <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> // Windows takes longer... <ide> waitTime = 90 * time.Second <ide> } <ide><path>integration-cli/docker_cli_info_test.go <ide> func (s *DockerSuite) TestInfoEnsureSucceeds(c *check.C) { <ide> "Live Restore Enabled:", <ide> } <ide> <del> if testEnv.DaemonPlatform() == "linux" { <add> if testEnv.OSType == "linux" { <ide> stringsToCheck = append(stringsToCheck, "Init Binary:", "Security Options:", "containerd version:", "runc version:", "init version:") <ide> } <ide> <ide><path>integration-cli/docker_cli_inspect_test.go <ide> func (s *DockerSuite) TestInspectStatus(c *check.C) { <ide> <ide> // Windows does not support pause/unpause on Windows Server Containers. <ide> // (RS1 does for Hyper-V Containers, but production CI is not setup for that) <del> if testEnv.DaemonPlatform() != "windows" { <add> if testEnv.OSType != "windows" { <ide> dockerCmd(c, "pause", out) <ide> inspectOut = inspectField(c, out, "State.Status") <ide> c.Assert(inspectOut, checker.Equals, "paused") <ide> func (s *DockerSuite) TestInspectContainerGraphDriver(c *check.C) { <ide> func (s *DockerSuite) TestInspectBindMountPoint(c *check.C) { <ide> modifier := ",z" <ide> prefix, slash := getPrefixAndSlashFromDaemonPlatform() <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> modifier = "" <ide> // Linux creates the host directory if it doesn't exist. Windows does not. <ide> os.Mkdir(`c:\data`, os.ModeDir) <ide> func (s *DockerSuite) TestInspectBindMountPoint(c *check.C) { <ide> c.Assert(m.Driver, checker.Equals, "") <ide> c.Assert(m.Source, checker.Equals, prefix+slash+"data") <ide> c.Assert(m.Destination, checker.Equals, prefix+slash+"data") <del> if testEnv.DaemonPlatform() != "windows" { // Windows does not set mode <add> if testEnv.OSType != "windows" { // Windows does not set mode <ide> c.Assert(m.Mode, checker.Equals, "ro"+modifier) <ide> } <ide> c.Assert(m.RW, checker.Equals, false) <ide><path>integration-cli/docker_cli_ps_test.go <ide> func (s *DockerSuite) TestPsListContainersFilterStatus(c *check.C) { <ide> }) <ide> <ide> // Windows doesn't support pausing of containers <del> if testEnv.DaemonPlatform() != "windows" { <add> if testEnv.OSType != "windows" { <ide> // pause running container <ide> out = cli.DockerCmd(c, "run", "-itd", "busybox").Combined() <ide> pausedID := strings.TrimSpace(out) <ide><path>integration-cli/docker_cli_rename_test.go <ide> func (s *DockerSuite) TestRenameAnonymousContainer(c *check.C) { <ide> dockerCmd(c, "start", "container1") <ide> <ide> count := "-c" <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> count = "-n" <ide> } <ide> <ide><path>integration-cli/docker_cli_restart_test.go <ide> func (s *DockerSuite) TestRestartContainerwithRestartPolicy(c *check.C) { <ide> id1 := strings.TrimSpace(string(out1)) <ide> id2 := strings.TrimSpace(string(out2)) <ide> waitTimeout := 15 * time.Second <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> waitTimeout = 150 * time.Second <ide> } <ide> err := waitInspect(id1, "{{ .State.Restarting }} {{ .State.Running }}", "false false", waitTimeout) <ide><path>integration-cli/docker_cli_rmi_test.go <ide> func (s *DockerSuite) TestRmiImgIDMultipleTag(c *check.C) { <ide> <ide> // Wait for it to exit as cannot commit a running container on Windows, and <ide> // it will take a few seconds to exit <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> cli.WaitExited(c, containerID, 60*time.Second) <ide> } <ide> <ide> func (s *DockerSuite) TestRmiImgIDForce(c *check.C) { <ide> <ide> // Wait for it to exit as cannot commit a running container on Windows, and <ide> // it will take a few seconds to exit <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> cli.WaitExited(c, containerID, 60*time.Second) <ide> } <ide> <ide><path>integration-cli/docker_cli_run_test.go <ide> func (s *DockerSuite) TestRunLeakyFileDescriptors(c *check.C) { <ide> // this will fail when Internet access is unavailable <ide> func (s *DockerSuite) TestRunLookupGoogleDNS(c *check.C) { <ide> testRequires(c, Network, NotArm) <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> // nslookup isn't present in Windows busybox. Is built-in. Further, <ide> // nslookup isn't present in nanoserver. Hence just use PowerShell... <ide> dockerCmd(c, "run", testEnv.PlatformDefaults.BaseImage, "powershell", "Resolve-DNSName", "google.com") <ide> func (s *DockerSuite) TestRunDetachedContainerIDPrinting(c *check.C) { <ide> func (s *DockerSuite) TestRunWorkingDirectory(c *check.C) { <ide> dir := "/root" <ide> image := "busybox" <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> dir = `C:/Windows` <ide> } <ide> <ide> func (s *DockerSuite) TestRunWorkingDirectory(c *check.C) { <ide> func (s *DockerSuite) TestRunWithoutNetworking(c *check.C) { <ide> count := "-c" <ide> image := "busybox" <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> count = "-n" <ide> image = testEnv.PlatformDefaults.BaseImage <ide> } <ide> func (s *DockerSuite) TestRunWithVolumesFromExited(c *check.C) { <ide> ) <ide> <ide> // Create a file in a volume <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> out, exitCode = dockerCmd(c, "run", "--name", "test-data", "--volume", `c:\some\dir`, testEnv.PlatformDefaults.BaseImage, "cmd", "/c", `echo hello > c:\some\dir\file`) <ide> } else { <ide> out, exitCode = dockerCmd(c, "run", "--name", "test-data", "--volume", "/some/dir", "busybox", "touch", "/some/dir/file") <ide> func (s *DockerSuite) TestRunWithVolumesFromExited(c *check.C) { <ide> } <ide> <ide> // Read the file from another container using --volumes-from to access the volume in the second container <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> out, exitCode = dockerCmd(c, "run", "--volumes-from", "test-data", testEnv.PlatformDefaults.BaseImage, "cmd", "/c", `type c:\some\dir\file`) <ide> } else { <ide> out, exitCode = dockerCmd(c, "run", "--volumes-from", "test-data", "busybox", "cat", "/some/dir/file") <ide> func (s *DockerSuite) TestRunCreateVolumesInSymlinkDir(c *check.C) { <ide> // In the case of Windows to Windows CI, if the machine is setup so that <ide> // the temp directory is not the C: drive, this test is invalid and will <ide> // not work. <del> if testEnv.DaemonPlatform() == "windows" && strings.ToLower(dir[:1]) != "c" { <add> if testEnv.OSType == "windows" && strings.ToLower(dir[:1]) != "c" { <ide> c.Skip("Requires TEMP to point to C: drive") <ide> } <ide> <ide> func (s *DockerSuite) TestRunCreateVolumesInSymlinkDir(c *check.C) { <ide> } <ide> f.Close() <ide> <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> dockerFile = fmt.Sprintf("FROM %s\nRUN mkdir %s\nRUN mklink /D c:\\test %s", testEnv.PlatformDefaults.BaseImage, dir, dir) <ide> containerPath = `c:\test\test` <ide> cmd = "tasklist" <ide> func (s *DockerSuite) TestRunCreateVolumesInSymlinkDir2(c *check.C) { <ide> testRequires(c, SameHostDaemon, DaemonIsLinux) <ide> name := "test-volume-symlink2" <ide> <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> dockerFile = fmt.Sprintf("FROM %s\nRUN mkdir c:\\%s\nRUN mklink /D c:\\test c:\\%s", testEnv.PlatformDefaults.BaseImage, name, name) <ide> containerPath = `c:\test\test` <ide> cmd = "tasklist" <ide> func (s *DockerSuite) TestRunVolumesFromInReadonlyModeFails(c *check.C) { <ide> volumeDir string <ide> fileInVol string <ide> ) <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> volumeDir = `c:/test` // Forward-slash as using busybox <ide> fileInVol = `c:/test/file` <ide> } else { <ide> func (s *DockerSuite) TestRunVolumesFromInReadWriteMode(c *check.C) { <ide> volumeDir string <ide> fileInVol string <ide> ) <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> volumeDir = `c:/test` // Forward-slash as using busybox <ide> fileInVol = `c:/test/file` <ide> } else { <ide> func (s *DockerSuite) TestRunVolumesFromInReadWriteMode(c *check.C) { <ide> func (s *DockerSuite) TestVolumesFromGetsProperMode(c *check.C) { <ide> testRequires(c, SameHostDaemon) <ide> prefix, slash := getPrefixAndSlashFromDaemonPlatform() <del> hostpath := RandomTmpDirPath("test", testEnv.DaemonPlatform()) <add> hostpath := RandomTmpDirPath("test", testEnv.OSType) <ide> if err := os.MkdirAll(hostpath, 0755); err != nil { <ide> c.Fatalf("Failed to create %s: %q", hostpath, err) <ide> } <ide> func (s *DockerSuite) TestVolumesFromGetsProperMode(c *check.C) { <ide> <ide> // Test for GH#10618 <ide> func (s *DockerSuite) TestRunNoDupVolumes(c *check.C) { <del> path1 := RandomTmpDirPath("test1", testEnv.DaemonPlatform()) <del> path2 := RandomTmpDirPath("test2", testEnv.DaemonPlatform()) <add> path1 := RandomTmpDirPath("test1", testEnv.OSType) <add> path2 := RandomTmpDirPath("test2", testEnv.OSType) <ide> <ide> someplace := ":/someplace" <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> // Windows requires that the source directory exists before calling HCS <ide> testRequires(c, SameHostDaemon) <ide> someplace = `:c:\someplace` <ide> func (s *DockerSuite) TestRunNoDupVolumes(c *check.C) { <ide> // Test for #1351 <ide> func (s *DockerSuite) TestRunApplyVolumesFromBeforeVolumes(c *check.C) { <ide> prefix := "" <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> prefix = `c:` <ide> } <ide> dockerCmd(c, "run", "--name", "parent", "-v", prefix+"/test", "busybox", "touch", prefix+"/test/foo") <ide> func (s *DockerSuite) TestRunApplyVolumesFromBeforeVolumes(c *check.C) { <ide> <ide> func (s *DockerSuite) TestRunMultipleVolumesFrom(c *check.C) { <ide> prefix := "" <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> prefix = `c:` <ide> } <ide> dockerCmd(c, "run", "--name", "parent1", "-v", prefix+"/test", "busybox", "touch", prefix+"/test/foo") <ide> func (s *DockerSuite) TestRunVerifyContainerID(c *check.C) { <ide> // Test that creating a container with a volume doesn't crash. Regression test for #995. <ide> func (s *DockerSuite) TestRunCreateVolume(c *check.C) { <ide> prefix := "" <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> prefix = `c:` <ide> } <ide> dockerCmd(c, "run", "-v", prefix+"/var/lib/data", "busybox", "true") <ide> func (s *DockerSuite) TestRunVolumesFromSymlinkPath(c *check.C) { <ide> RUN ln -s home /foo <ide> VOLUME ["/foo/bar"]` <ide> <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> prefix = `c:` <ide> dfContents = `FROM ` + testEnv.PlatformDefaults.BaseImage + ` <ide> RUN mkdir c:\home <ide> func (s *DockerSuite) TestRunExitCode(c *check.C) { <ide> <ide> func (s *DockerSuite) TestRunUserDefaults(c *check.C) { <ide> expected := "uid=0(root) gid=0(root)" <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> expected = "uid=1000(ContainerAdministrator) gid=1000(ContainerAdministrator)" <ide> } <ide> out, _ := dockerCmd(c, "run", "busybox", "id") <ide> func (s *DockerSuite) TestRunEnvironmentOverride(c *check.C) { <ide> } <ide> <ide> func (s *DockerSuite) TestRunContainerNetwork(c *check.C) { <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> // Windows busybox does not have ping. Use built in ping instead. <ide> dockerCmd(c, "run", testEnv.PlatformDefaults.BaseImage, "ping", "-n", "1", "127.0.0.1") <ide> } else { <ide> func (s *DockerSuite) TestRunModeHostname(c *check.C) { <ide> func (s *DockerSuite) TestRunRootWorkdir(c *check.C) { <ide> out, _ := dockerCmd(c, "run", "--workdir", "/", "busybox", "pwd") <ide> expected := "/\n" <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> expected = "C:" + expected <ide> } <ide> if out != expected { <ide> func (s *DockerSuite) TestRunRootWorkdir(c *check.C) { <ide> } <ide> <ide> func (s *DockerSuite) TestRunAllowBindMountingRoot(c *check.C) { <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> // Windows busybox will fail with Permission Denied on items such as pagefile.sys <ide> dockerCmd(c, "run", "-v", `c:\:c:\host`, testEnv.PlatformDefaults.BaseImage, "cmd", "-c", "dir", `c:\host`) <ide> } else { <ide> func (s *DockerSuite) TestRunAllowBindMountingRoot(c *check.C) { <ide> func (s *DockerSuite) TestRunDisallowBindMountingRootToRoot(c *check.C) { <ide> mount := "/:/" <ide> targetDir := "/host" <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> mount = `c:\:c\` <ide> targetDir = "c:/host" // Forward slash as using busybox <ide> } <ide> func (s *DockerSuite) TestRunCleanupCmdOnEntrypoint(c *check.C) { <ide> } <ide> out = strings.TrimSpace(out) <ide> expected := "root" <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> if strings.Contains(testEnv.PlatformDefaults.BaseImage, "windowsservercore") { <ide> expected = `user manager\containeradministrator` <ide> } else { <ide> func (s *DockerSuite) TestRunCleanupCmdOnEntrypoint(c *check.C) { <ide> func (s *DockerSuite) TestRunWorkdirExistsAndIsFile(c *check.C) { <ide> existingFile := "/bin/cat" <ide> expected := "not a directory" <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> existingFile = `\windows\system32\ntdll.dll` <ide> expected = `The directory name is invalid.` <ide> } <ide> func (s *DockerSuite) TestRunExitOnStdinClose(c *check.C) { <ide> <ide> meow := "/bin/cat" <ide> delay := 60 <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> meow = "cat" <ide> } <ide> runCmd := exec.Command(dockerBinary, "run", "--name", name, "-i", "busybox", meow) <ide> func (s *DockerSuite) TestRunEntrypoint(c *check.C) { <ide> <ide> func (s *DockerSuite) TestRunBindMounts(c *check.C) { <ide> testRequires(c, SameHostDaemon) <del> if testEnv.DaemonPlatform() == "linux" { <add> if testEnv.OSType == "linux" { <ide> testRequires(c, DaemonIsLinux, NotUserNamespace) <ide> } <ide> <ide> func (s *DockerSuite) TestRunBindMounts(c *check.C) { <ide> } <ide> <ide> // test writing to bind mount <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> dockerCmd(c, "run", "-v", fmt.Sprintf(`%s:c:\tmp:rw`, tmpDir), "busybox", "touch", "c:/tmp/holla") <ide> } else { <ide> dockerCmd(c, "run", "-v", fmt.Sprintf("%s:/tmp:rw", tmpDir), "busybox", "touch", "/tmp/holla") <ide> func (s *DockerSuite) TestRunBindMounts(c *check.C) { <ide> } <ide> <ide> // Windows does not (and likely never will) support mounting a single file <del> if testEnv.DaemonPlatform() != "windows" { <add> if testEnv.OSType != "windows" { <ide> // test mount a file <ide> dockerCmd(c, "run", "-v", fmt.Sprintf("%s/holla:/tmp/holla:rw", tmpDir), "busybox", "sh", "-c", "echo -n 'yotta' > /tmp/holla") <ide> content := readFile(path.Join(tmpDir, "holla"), c) // Will fail if the file doesn't exist <ide> func (s *DockerSuite) TestRunCidFileCleanupIfEmpty(c *check.C) { <ide> tmpCidFile := path.Join(tmpDir, "cid") <ide> <ide> image := "emptyfs" <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> // Windows can't support an emptyfs image. Just use the regular Windows image <ide> image = testEnv.PlatformDefaults.BaseImage <ide> } <ide> func (s *DockerSuite) TestRunCidFileCheckIDLength(c *check.C) { <ide> func (s *DockerSuite) TestRunSetMacAddress(c *check.C) { <ide> mac := "12:34:56:78:9a:bc" <ide> var out string <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> out, _ = dockerCmd(c, "run", "-i", "--rm", fmt.Sprintf("--mac-address=%s", mac), "busybox", "sh", "-c", "ipconfig /all | grep 'Physical Address' | awk '{print $12}'") <ide> mac = strings.Replace(strings.ToUpper(mac), ":", "-", -1) // To Windows-style MACs <ide> } else { <ide> func (s *DockerSuite) TestVolumesNoCopyData(c *check.C) { <ide> c.Fatalf("Data was copied on volumes-from but shouldn't be:\n%q", out) <ide> } <ide> <del> tmpDir := RandomTmpDirPath("docker_test_bind_mount_copy_data", testEnv.DaemonPlatform()) <add> tmpDir := RandomTmpDirPath("docker_test_bind_mount_copy_data", testEnv.OSType) <ide> if out, _, err := dockerCmdWithError("run", "-v", tmpDir+":/foo", "dataimage", "ls", "-lh", "/foo/bar"); err == nil || !strings.Contains(out, "No such file or directory") { <ide> c.Fatalf("Data was copied on bind mount but shouldn't be:\n%q", out) <ide> } <ide> func (s *DockerSuite) TestRunNonLocalMacAddress(c *check.C) { <ide> args := []string{"run", "--mac-address", addr} <ide> expected := addr <ide> <del> if testEnv.DaemonPlatform() != "windows" { <add> if testEnv.OSType != "windows" { <ide> args = append(args, "busybox", "ifconfig") <ide> } else { <ide> args = append(args, testEnv.PlatformDefaults.BaseImage, "ipconfig", "/all") <ide> func (s *DockerSuite) TestRunSetDefaultRestartPolicy(c *check.C) { <ide> func (s *DockerSuite) TestRunRestartMaxRetries(c *check.C) { <ide> out, _ := dockerCmd(c, "run", "-d", "--restart=on-failure:3", "busybox", "false") <ide> timeout := 10 * time.Second <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> timeout = 120 * time.Second <ide> } <ide> <ide> func (s *DockerSuite) TestVolumeFromMixedRWOptions(c *check.C) { <ide> dockerCmd(c, "run", "--volumes-from", "parent:ro", "--name", "test-volumes-1", "busybox", "true") <ide> dockerCmd(c, "run", "--volumes-from", "parent:rw", "--name", "test-volumes-2", "busybox", "true") <ide> <del> if testEnv.DaemonPlatform() != "windows" { <add> if testEnv.OSType != "windows" { <ide> mRO, err := inspectMountPoint("test-volumes-1", prefix+slash+"test") <ide> c.Assert(err, checker.IsNil, check.Commentf("failed to inspect mount point")) <ide> if mRO.RW { <ide> func (s *DockerSuite) TestRunLoopbackOnlyExistsWhenNetworkingDisabled(c *check.C <ide> <ide> // Issue #4681 <ide> func (s *DockerSuite) TestRunLoopbackWhenNetworkDisabled(c *check.C) { <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> dockerCmd(c, "run", "--net=none", testEnv.PlatformDefaults.BaseImage, "ping", "-n", "1", "127.0.0.1") <ide> } else { <ide> dockerCmd(c, "run", "--net=none", "busybox", "ping", "-c", "1", "127.0.0.1") <ide> func (s *DockerSuite) TestRunNonExistingCmd(c *check.C) { <ide> // as that's when the check is made (and yes, by its design...) <ide> func (s *DockerSuite) TestCmdCannotBeInvoked(c *check.C) { <ide> expected := 126 <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> expected = 127 <ide> } <ide> name := "testCmdCannotBeInvoked" <ide><path>integration-cli/docker_cli_top_test.go <ide> func (s *DockerSuite) TestTopMultipleArgs(c *check.C) { <ide> cleanedContainerID := strings.TrimSpace(out) <ide> <ide> var expected icmd.Expected <del> switch testEnv.DaemonPlatform() { <add> switch testEnv.OSType { <ide> case "windows": <ide> expected = icmd.Expected{ExitCode: 1, Err: "Windows does not support arguments to top"} <ide> default: <ide> func (s *DockerSuite) TestTopNonPrivileged(c *check.C) { <ide> // Windows will list the name of the launched executable which in this case is busybox.exe, without the parameters. <ide> // Linux will display the command executed in the container <ide> var lookingFor string <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> lookingFor = "busybox.exe" <ide> } else { <ide> lookingFor = "top" <ide><path>integration-cli/docker_cli_update_test.go <ide> import ( <ide> func (s *DockerSuite) TestUpdateRestartPolicy(c *check.C) { <ide> out := cli.DockerCmd(c, "run", "-d", "--restart=on-failure:3", "busybox", "sh", "-c", "sleep 1 && false").Combined() <ide> timeout := 60 * time.Second <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> timeout = 180 * time.Second <ide> } <ide> <ide><path>integration-cli/docker_deprecated_api_v124_test.go <ide> func (s *DockerSuite) TestDeprecatedContainerAPIStartVolumeBinds(c *check.C) { <ide> // TODO Windows CI: Investigate further why this fails on Windows to Windows CI. <ide> testRequires(c, DaemonIsLinux) <ide> path := "/foo" <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> path = `c:\foo` <ide> } <ide> name := "testing" <ide> func (s *DockerSuite) TestDeprecatedContainerAPIStartVolumeBinds(c *check.C) { <ide> c.Assert(err, checker.IsNil) <ide> c.Assert(res.StatusCode, checker.Equals, http.StatusCreated) <ide> <del> bindPath := RandomTmpDirPath("test", testEnv.DaemonPlatform()) <add> bindPath := RandomTmpDirPath("test", testEnv.OSType) <ide> config = map[string]interface{}{ <ide> "Binds": []string{bindPath + ":" + path}, <ide> } <ide> func (s *DockerSuite) TestDeprecatedContainerAPIStartDupVolumeBinds(c *check.C) <ide> c.Assert(err, checker.IsNil) <ide> c.Assert(res.StatusCode, checker.Equals, http.StatusCreated) <ide> <del> bindPath1 := RandomTmpDirPath("test1", testEnv.DaemonPlatform()) <del> bindPath2 := RandomTmpDirPath("test2", testEnv.DaemonPlatform()) <add> bindPath1 := RandomTmpDirPath("test1", testEnv.OSType) <add> bindPath2 := RandomTmpDirPath("test2", testEnv.OSType) <ide> <ide> config = map[string]interface{}{ <ide> "Binds": []string{bindPath1 + ":/tmp", bindPath2 + ":/tmp"}, <ide><path>integration-cli/environment/environment.go <ide> func New() (*Execution, error) { <ide> dockerBinary: dockerBinary, <ide> }, nil <ide> } <del> <del>// DaemonPlatform is held globally so that tests can make intelligent <del>// decisions on how to configure themselves according to the platform <del>// of the daemon. This is initialized in docker_utils by sending <del>// a version call to the daemon and examining the response header. <del>// Deprecated: use Execution.OSType <del>func (e *Execution) DaemonPlatform() string { <del> return e.OSType <del>} <ide><path>integration-cli/fixtures_linux_daemon_test.go <ide> func ensureSyscallTest(c *check.C) { <ide> <ide> // if no match, must build in docker, which is significantly slower <ide> // (slower mostly because of the vfs graphdriver) <del> if testEnv.DaemonPlatform() != runtime.GOOS { <add> if testEnv.OSType != runtime.GOOS { <ide> ensureSyscallTestBuild(c) <ide> return <ide> } <ide> func ensureSyscallTestBuild(c *check.C) { <ide> <ide> func ensureNNPTest(c *check.C) { <ide> defer testEnv.ProtectImage(c, "nnp-test:latest") <del> if testEnv.DaemonPlatform() != runtime.GOOS { <add> if testEnv.OSType != runtime.GOOS { <ide> ensureNNPTestBuild(c) <ide> return <ide> } <ide><path>integration-cli/test_vars_test.go <ide> package main <ide> // the command is for a sleeping container based on the daemon platform. <ide> // The Windows busybox image does not have a `top` command. <ide> func sleepCommandForDaemonPlatform() []string { <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> return []string{"sleep", "240"} <ide> } <ide> return []string{"top"} <ide><path>integration-cli/utils_test.go <ide> import ( <ide> ) <ide> <ide> func getPrefixAndSlashFromDaemonPlatform() (prefix, slash string) { <del> if testEnv.DaemonPlatform() == "windows" { <add> if testEnv.OSType == "windows" { <ide> return "c:", `\` <ide> } <ide> return "", "/"
25
Javascript
Javascript
add a bookmarklet to comment on questions
848a151ff815a242ba61e21c9fc384e0a6678934
<ide><path>bots/question-bookmarklet.js <add>javascript:(function(){$('#new_comment_field')[0].value='Hey and thanks for reporting this!\n\nThis issue looks like a question - please use [Stack Overflow](http://stackoverflow.com/questions/tagged/react-native) for questions. It\'s the best system for Q&A and the best way to get questions answered.\n\nMany people from the community hang out on Stack Overflow and will be able to see your question and be more likely to answer because of the reputation system. If after reading this you think your question is better suited for Stack Overflow, please consider closing this issue.';$('button.btn-primary:contains("Comment")').click()})() <ide>\ No newline at end of file
1
Javascript
Javascript
fix typo in listviewdatasource documentation
d16c6e926c02358cbd51a585daa413cd36099e27
<ide><path>Libraries/CustomComponents/ListView/ListViewDataSource.js <ide> class ListViewDataSource { <ide> * construction an extractor to get the interesting information was defined <ide> * (or the default was used). <ide> * <del> * The `rowIdentities` is is a 2D array of identifiers for rows. <add> * The `rowIdentities` is a 2D array of identifiers for rows. <ide> * ie. [['a1', 'a2'], ['b1', 'b2', 'b3'], ...]. If not provided, it's <ide> * assumed that the keys of the section data are the row identities. <ide> *
1
Javascript
Javascript
adjust globs for ts files
9a2f9fb33f0df89bcc1147a70155027f5db4eef4
<ide><path>.eslintrc.js <ide> module.exports = { <ide> }, <ide> { <ide> files: [ <del> 'packages/*/tests/**/*.js', <del> 'packages/@ember/*/tests/**/*.js', <del> 'packages/@ember/-internals/*/tests/**/*.js', <del> 'packages/internal-test-helpers/**/*.js', <add> 'packages/*/tests/**/*.[jt]s', <add> 'packages/@ember/*/tests/**/*.[jt]s', <add> 'packages/@ember/-internals/*/tests/**/*.[jt]s', <add> 'packages/internal-test-helpers/**/*.[jt]s', <ide> ], <ide> env: { <ide> qunit: true,
1
Ruby
Ruby
compare ruby version with correct way
0014790b2a8a7830685ec91b68d457ec37617f26
<ide><path>railties/lib/rails/ruby_version_check.rb <ide> # frozen_string_literal: true <ide> <del>if RUBY_VERSION < "2.4.1" && RUBY_ENGINE == "ruby" <add>if Gem::Version.new(RUBY_VERSION) < Gem::Version.new("2.4.1") && RUBY_ENGINE == "ruby" <ide> desc = defined?(RUBY_DESCRIPTION) ? RUBY_DESCRIPTION : "ruby #{RUBY_VERSION} (#{RUBY_RELEASE_DATE})" <ide> abort <<-end_message <ide>
1
PHP
PHP
use namespace imports
44c11585f127764278f979fa04307b805df58792
<ide><path>tests/Routing/RoutingUrlGeneratorTest.php <ide> <?php <ide> <add>use Illuminate\Http\Request; <add>use Illuminate\Routing\Route; <ide> use Illuminate\Routing\UrlGenerator; <add>use Illuminate\Routing\RouteCollection; <ide> use Illuminate\Contracts\Routing\UrlRoutable; <ide> <ide> class RoutingUrlGeneratorTest extends PHPUnit_Framework_TestCase <ide> { <ide> public function testBasicGeneration() <ide> { <ide> $url = new UrlGenerator( <del> $routes = new Illuminate\Routing\RouteCollection, <del> $request = Illuminate\Http\Request::create('http://www.foo.com/') <add> $routes = new RouteCollection, <add> $request = Request::create('http://www.foo.com/') <ide> ); <ide> <ide> $this->assertEquals('http://www.foo.com/foo/bar', $url->to('foo/bar')); <ide> public function testBasicGeneration() <ide> * Test HTTPS request URL generation... <ide> */ <ide> $url = new UrlGenerator( <del> $routes = new Illuminate\Routing\RouteCollection, <del> $request = Illuminate\Http\Request::create('https://www.foo.com/') <add> $routes = new RouteCollection, <add> $request = Request::create('https://www.foo.com/') <ide> ); <ide> <ide> $this->assertEquals('https://www.foo.com/foo/bar', $url->to('foo/bar')); <ide> public function testBasicGeneration() <ide> * Test asset URL generation... <ide> */ <ide> $url = new UrlGenerator( <del> $routes = new Illuminate\Routing\RouteCollection, <del> $request = Illuminate\Http\Request::create('http://www.foo.com/index.php/') <add> $routes = new RouteCollection, <add> $request = Request::create('http://www.foo.com/index.php/') <ide> ); <ide> <ide> $this->assertEquals('http://www.foo.com/foo/bar', $url->asset('foo/bar')); <ide> public function testBasicGeneration() <ide> public function testBasicRouteGeneration() <ide> { <ide> $url = new UrlGenerator( <del> $routes = new Illuminate\Routing\RouteCollection, <del> $request = Illuminate\Http\Request::create('http://www.foo.com/') <add> $routes = new RouteCollection, <add> $request = Request::create('http://www.foo.com/') <ide> ); <ide> <ide> /* <ide> * Empty Named Route <ide> */ <del> $route = new Illuminate\Routing\Route(['GET'], '/', ['as' => 'plain']); <add> $route = new Route(['GET'], '/', ['as' => 'plain']); <ide> $routes->add($route); <ide> <ide> /* <ide> * Named Routes <ide> */ <del> $route = new Illuminate\Routing\Route(['GET'], 'foo/bar', ['as' => 'foo']); <add> $route = new Route(['GET'], 'foo/bar', ['as' => 'foo']); <ide> $routes->add($route); <ide> <ide> /* <ide> * Parameters... <ide> */ <del> $route = new Illuminate\Routing\Route(['GET'], 'foo/bar/{baz}/breeze/{boom}', ['as' => 'bar']); <add> $route = new Route(['GET'], 'foo/bar/{baz}/breeze/{boom}', ['as' => 'bar']); <ide> $routes->add($route); <ide> <ide> /* <ide> * Single Parameter... <ide> */ <del> $route = new Illuminate\Routing\Route(['GET'], 'foo/bar/{baz}', ['as' => 'foobar']); <add> $route = new Route(['GET'], 'foo/bar/{baz}', ['as' => 'foobar']); <ide> $routes->add($route); <ide> <ide> /* <ide> * HTTPS... <ide> */ <del> $route = new Illuminate\Routing\Route(['GET'], 'foo/baz', ['as' => 'baz', 'https']); <add> $route = new Route(['GET'], 'foo/baz', ['as' => 'baz', 'https']); <ide> $routes->add($route); <ide> <ide> /* <ide> * Controller Route Route <ide> */ <del> $route = new Illuminate\Routing\Route(['GET'], 'foo/bam', ['controller' => 'foo@bar']); <add> $route = new Route(['GET'], 'foo/bam', ['controller' => 'foo@bar']); <ide> $routes->add($route); <ide> <ide> /* <ide> * Non ASCII routes <ide> */ <del> $route = new Illuminate\Routing\Route(['GET'], 'foo/bar/åαф/{baz}', ['as' => 'foobarbaz']); <add> $route = new Route(['GET'], 'foo/bar/åαф/{baz}', ['as' => 'foobarbaz']); <ide> $routes->add($route); <ide> <ide> /* <ide> * Fragments <ide> */ <del> $route = new Illuminate\Routing\Route(['GET'], 'foo/bar#derp', ['as' => 'fragment']); <add> $route = new Route(['GET'], 'foo/bar#derp', ['as' => 'fragment']); <ide> $routes->add($route); <ide> <ide> $this->assertEquals('/', $url->route('plain', [], false)); <ide> public function testBasicRouteGeneration() <ide> public function testFluentRouteNameDefinitions() <ide> { <ide> $url = new UrlGenerator( <del> $routes = new Illuminate\Routing\RouteCollection, <del> $request = Illuminate\Http\Request::create('http://www.foo.com/') <add> $routes = new RouteCollection, <add> $request = Request::create('http://www.foo.com/') <ide> ); <ide> <ide> /* <ide> * Named Routes <ide> */ <del> $route = new Illuminate\Routing\Route(['GET'], 'foo/bar', []); <add> $route = new Route(['GET'], 'foo/bar', []); <ide> $route->name('foo'); <ide> $routes->add($route); <ide> $routes->refreshNameLookups(); <ide> public function testFluentRouteNameDefinitions() <ide> public function testControllerRoutesWithADefaultNamespace() <ide> { <ide> $url = new UrlGenerator( <del> $routes = new Illuminate\Routing\RouteCollection, <del> $request = Illuminate\Http\Request::create('http://www.foo.com/') <add> $routes = new RouteCollection, <add> $request = Request::create('http://www.foo.com/') <ide> ); <ide> <ide> $url->setRootControllerNamespace('namespace'); <ide> <ide> /* <ide> * Controller Route Route <ide> */ <del> $route = new Illuminate\Routing\Route(['GET'], 'foo/bar', ['controller' => 'namespace\foo@bar']); <add> $route = new Route(['GET'], 'foo/bar', ['controller' => 'namespace\foo@bar']); <ide> $routes->add($route); <ide> <del> $route = new Illuminate\Routing\Route(['GET'], 'something/else', ['controller' => 'something\foo@bar']); <add> $route = new Route(['GET'], 'something/else', ['controller' => 'something\foo@bar']); <ide> $routes->add($route); <ide> <ide> $this->assertEquals('http://www.foo.com/foo/bar', $url->action('foo@bar')); <ide> public function testControllerRoutesWithADefaultNamespace() <ide> public function testControllerRoutesOutsideOfDefaultNamespace() <ide> { <ide> $url = new UrlGenerator( <del> $routes = new Illuminate\Routing\RouteCollection, <del> $request = Illuminate\Http\Request::create('http://www.foo.com/') <add> $routes = new RouteCollection, <add> $request = Request::create('http://www.foo.com/') <ide> ); <ide> <ide> $url->setRootControllerNamespace('namespace'); <ide> <del> $route = new Illuminate\Routing\Route(['GET'], 'root/namespace', ['controller' => '\root\namespace@foo']); <add> $route = new Route(['GET'], 'root/namespace', ['controller' => '\root\namespace@foo']); <ide> $routes->add($route); <ide> <ide> $this->assertEquals('http://www.foo.com/root/namespace', $url->action('\root\namespace@foo')); <ide> public function testControllerRoutesOutsideOfDefaultNamespace() <ide> public function testRoutableInterfaceRouting() <ide> { <ide> $url = new UrlGenerator( <del> $routes = new Illuminate\Routing\RouteCollection, <del> $request = Illuminate\Http\Request::create('http://www.foo.com/') <add> $routes = new RouteCollection, <add> $request = Request::create('http://www.foo.com/') <ide> ); <ide> <del> $route = new Illuminate\Routing\Route(['GET'], 'foo/{bar}', ['as' => 'routable']); <add> $route = new Route(['GET'], 'foo/{bar}', ['as' => 'routable']); <ide> $routes->add($route); <ide> <ide> $model = new RoutableInterfaceStub; <ide> public function testRoutableInterfaceRouting() <ide> public function testRoutableInterfaceRoutingWithSingleParameter() <ide> { <ide> $url = new UrlGenerator( <del> $routes = new Illuminate\Routing\RouteCollection, <del> $request = Illuminate\Http\Request::create('http://www.foo.com/') <add> $routes = new RouteCollection, <add> $request = Request::create('http://www.foo.com/') <ide> ); <ide> <del> $route = new Illuminate\Routing\Route(['GET'], 'foo/{bar}', ['as' => 'routable']); <add> $route = new Route(['GET'], 'foo/{bar}', ['as' => 'routable']); <ide> $routes->add($route); <ide> <ide> $model = new RoutableInterfaceStub; <ide> public function testRoutableInterfaceRoutingWithSingleParameter() <ide> public function testRoutesMaintainRequestScheme() <ide> { <ide> $url = new UrlGenerator( <del> $routes = new Illuminate\Routing\RouteCollection, <del> $request = Illuminate\Http\Request::create('https://www.foo.com/') <add> $routes = new RouteCollection, <add> $request = Request::create('https://www.foo.com/') <ide> ); <ide> <ide> /* <ide> * Named Routes <ide> */ <del> $route = new Illuminate\Routing\Route(['GET'], 'foo/bar', ['as' => 'foo']); <add> $route = new Route(['GET'], 'foo/bar', ['as' => 'foo']); <ide> $routes->add($route); <ide> <ide> $this->assertEquals('https://www.foo.com/foo/bar', $url->route('foo')); <ide> public function testRoutesMaintainRequestScheme() <ide> public function testHttpOnlyRoutes() <ide> { <ide> $url = new UrlGenerator( <del> $routes = new Illuminate\Routing\RouteCollection, <del> $request = Illuminate\Http\Request::create('https://www.foo.com/') <add> $routes = new RouteCollection, <add> $request = Request::create('https://www.foo.com/') <ide> ); <ide> <ide> /* <ide> * Named Routes <ide> */ <del> $route = new Illuminate\Routing\Route(['GET'], 'foo/bar', ['as' => 'foo', 'http']); <add> $route = new Route(['GET'], 'foo/bar', ['as' => 'foo', 'http']); <ide> $routes->add($route); <ide> <ide> $this->assertEquals('http://www.foo.com/foo/bar', $url->route('foo')); <ide> public function testHttpOnlyRoutes() <ide> public function testRoutesWithDomains() <ide> { <ide> $url = new UrlGenerator( <del> $routes = new Illuminate\Routing\RouteCollection, <del> $request = Illuminate\Http\Request::create('http://www.foo.com/') <add> $routes = new RouteCollection, <add> $request = Request::create('http://www.foo.com/') <ide> ); <ide> <del> $route = new Illuminate\Routing\Route(['GET'], 'foo/bar', ['as' => 'foo', 'domain' => 'sub.foo.com']); <add> $route = new Route(['GET'], 'foo/bar', ['as' => 'foo', 'domain' => 'sub.foo.com']); <ide> $routes->add($route); <ide> <ide> /* <ide> * Wildcards & Domains... <ide> */ <del> $route = new Illuminate\Routing\Route(['GET'], 'foo/bar/{baz}', ['as' => 'bar', 'domain' => 'sub.{foo}.com']); <add> $route = new Route(['GET'], 'foo/bar/{baz}', ['as' => 'bar', 'domain' => 'sub.{foo}.com']); <ide> $routes->add($route); <ide> <ide> $this->assertEquals('http://sub.foo.com/foo/bar', $url->route('foo')); <ide> public function testRoutesWithDomains() <ide> public function testRoutesWithDomainsAndPorts() <ide> { <ide> $url = new UrlGenerator( <del> $routes = new Illuminate\Routing\RouteCollection, <del> $request = Illuminate\Http\Request::create('http://www.foo.com:8080/') <add> $routes = new RouteCollection, <add> $request = Request::create('http://www.foo.com:8080/') <ide> ); <ide> <del> $route = new Illuminate\Routing\Route(['GET'], 'foo/bar', ['as' => 'foo', 'domain' => 'sub.foo.com']); <add> $route = new Route(['GET'], 'foo/bar', ['as' => 'foo', 'domain' => 'sub.foo.com']); <ide> $routes->add($route); <ide> <ide> /* <ide> * Wildcards & Domains... <ide> */ <del> $route = new Illuminate\Routing\Route(['GET'], 'foo/bar/{baz}', ['as' => 'bar', 'domain' => 'sub.{foo}.com']); <add> $route = new Route(['GET'], 'foo/bar/{baz}', ['as' => 'bar', 'domain' => 'sub.{foo}.com']); <ide> $routes->add($route); <ide> <ide> $this->assertEquals('http://sub.foo.com:8080/foo/bar', $url->route('foo')); <ide> public function testRoutesWithDomainsAndPorts() <ide> public function testHttpsRoutesWithDomains() <ide> { <ide> $url = new UrlGenerator( <del> $routes = new Illuminate\Routing\RouteCollection, <del> $request = Illuminate\Http\Request::create('https://foo.com/') <add> $routes = new RouteCollection, <add> $request = Request::create('https://foo.com/') <ide> ); <ide> <ide> /* <ide> * When on HTTPS, no need to specify 443 <ide> */ <del> $route = new Illuminate\Routing\Route(['GET'], 'foo/bar', ['as' => 'baz', 'domain' => 'sub.foo.com']); <add> $route = new Route(['GET'], 'foo/bar', ['as' => 'baz', 'domain' => 'sub.foo.com']); <ide> $routes->add($route); <ide> <ide> $this->assertEquals('https://sub.foo.com/foo/bar', $url->route('baz')); <ide> } <ide> <ide> public function testRoutesWithDomainsThroughProxy() <ide> { <del> Illuminate\Http\Request::setTrustedProxies(['10.0.0.1']); <add> Request::setTrustedProxies(['10.0.0.1']); <ide> <ide> $url = new UrlGenerator( <del> $routes = new Illuminate\Routing\RouteCollection, <del> $request = Illuminate\Http\Request::create('http://www.foo.com/', 'GET', [], [], [], ['REMOTE_ADDR' => '10.0.0.1', 'HTTP_X_FORWARDED_PORT' => '80']) <add> $routes = new RouteCollection, <add> $request = Request::create('http://www.foo.com/', 'GET', [], [], [], ['REMOTE_ADDR' => '10.0.0.1', 'HTTP_X_FORWARDED_PORT' => '80']) <ide> ); <ide> <del> $route = new Illuminate\Routing\Route(['GET'], 'foo/bar', ['as' => 'foo', 'domain' => 'sub.foo.com']); <add> $route = new Route(['GET'], 'foo/bar', ['as' => 'foo', 'domain' => 'sub.foo.com']); <ide> $routes->add($route); <ide> <ide> $this->assertEquals('http://sub.foo.com/foo/bar', $url->route('foo')); <ide> public function testRoutesWithDomainsThroughProxy() <ide> public function testUrlGenerationForControllers() <ide> { <ide> $url = new UrlGenerator( <del> $routes = new Illuminate\Routing\RouteCollection, <del> $request = Illuminate\Http\Request::create('http://www.foo.com:8080/') <add> $routes = new RouteCollection, <add> $request = Request::create('http://www.foo.com:8080/') <ide> ); <ide> <del> $route = new Illuminate\Routing\Route(['GET'], 'foo/{one}/{two?}/{three?}', ['as' => 'foo', function () {}]); <add> $route = new Route(['GET'], 'foo/{one}/{two?}/{three?}', ['as' => 'foo', function () {}]); <ide> $routes->add($route); <ide> <ide> $this->assertEquals('http://www.foo.com:8080/foo', $url->route('foo')); <ide> public function testUrlGenerationForControllers() <ide> public function testForceRootUrl() <ide> { <ide> $url = new UrlGenerator( <del> $routes = new Illuminate\Routing\RouteCollection, <del> $request = Illuminate\Http\Request::create('http://www.foo.com/') <add> $routes = new RouteCollection, <add> $request = Request::create('http://www.foo.com/') <ide> ); <ide> <ide> $url->forceRootUrl('https://www.bar.com'); <ide> public function testForceRootUrl() <ide> * Route Based... <ide> */ <ide> $url = new UrlGenerator( <del> $routes = new Illuminate\Routing\RouteCollection, <del> $request = Illuminate\Http\Request::create('http://www.foo.com/') <add> $routes = new RouteCollection, <add> $request = Request::create('http://www.foo.com/') <ide> ); <ide> <ide> $url->forceSchema('https'); <del> $route = new Illuminate\Routing\Route(['GET'], '/foo', ['as' => 'plain']); <add> $route = new Route(['GET'], '/foo', ['as' => 'plain']); <ide> $routes->add($route); <ide> <ide> $this->assertEquals('https://www.foo.com/foo', $url->route('plain')); <ide> public function testForceRootUrl() <ide> public function testPrevious() <ide> { <ide> $url = new UrlGenerator( <del> $routes = new Illuminate\Routing\RouteCollection, <del> $request = Illuminate\Http\Request::create('http://www.foo.com/') <add> $routes = new RouteCollection, <add> $request = Request::create('http://www.foo.com/') <ide> ); <ide> <ide> $url->getRequest()->headers->set('referer', 'http://www.bar.com/');
1
PHP
PHP
update response tests
fa998d716d6009538ac6167efd4bdf32b2980ed2
<ide><path>tests/TestCase/Network/ResponseTest.php <ide> public function testHttpCodes() <ide> { <ide> $response = new Response(); <ide> $result = $response->httpCodes(); <del> $this->assertEquals(40, count($result)); <add> $this->assertEquals(41, count($result)); <ide> <ide> $result = $response->httpCodes(100); <ide> $expected = [100 => 'Continue']; <ide> public function testHttpCodes() <ide> <ide> $result = $response->httpCodes($codes); <ide> $this->assertTrue($result); <del> $this->assertEquals(42, count($response->httpCodes())); <add> $this->assertEquals(43, count($response->httpCodes())); <ide> <ide> $result = $response->httpCodes(381); <ide> $expected = [381 => 'Unicorn Moved']; <ide> public function testHttpCodes() <ide> $codes = [404 => 'Sorry Bro']; <ide> $result = $response->httpCodes($codes); <ide> $this->assertTrue($result); <del> $this->assertEquals(42, count($response->httpCodes())); <add> $this->assertEquals(43, count($response->httpCodes())); <ide> <ide> $result = $response->httpCodes(404); <ide> $expected = [404 => 'Sorry Bro'];
1
Javascript
Javascript
set decodestrings to false, test
2ffc8ac3017eb2246deb99019aacd618e5c088c3
<ide><path>benchmark/http2/write.js <add>'use strict'; <add> <add>const common = require('../common.js'); <add>const PORT = common.PORT; <add> <add>var bench = common.createBenchmark(main, { <add> streams: [100, 200, 1000], <add> length: [64 * 1024, 128 * 1024, 256 * 1024, 1024 * 1024], <add>}, { flags: ['--expose-http2', '--no-warnings'] }); <add> <add>function main(conf) { <add> const m = +conf.streams; <add> const l = +conf.length; <add> const http2 = require('http2'); <add> const server = http2.createServer(); <add> server.on('stream', (stream) => { <add> stream.respond(); <add> stream.write('ü'.repeat(l)); <add> stream.end(); <add> }); <add> server.listen(PORT, () => { <add> bench.http({ <add> path: '/', <add> requests: 10000, <add> maxConcurrentStreams: m, <add> }, () => { server.close(); }); <add> }); <add>} <ide><path>lib/internal/http2/core.js <ide> class ClientHttp2Session extends Http2Session { <ide> <ide> function createWriteReq(req, handle, data, encoding) { <ide> switch (encoding) { <del> case 'latin1': <del> case 'binary': <del> return handle.writeLatin1String(req, data); <del> case 'buffer': <del> return handle.writeBuffer(req, data); <ide> case 'utf8': <ide> case 'utf-8': <ide> return handle.writeUtf8String(req, data); <ide> function createWriteReq(req, handle, data, encoding) { <ide> case 'utf16le': <ide> case 'utf-16le': <ide> return handle.writeUcs2String(req, data); <add> case 'latin1': <add> case 'binary': <add> return handle.writeLatin1String(req, data); <add> case 'buffer': <add> return handle.writeBuffer(req, data); <ide> default: <ide> return handle.writeBuffer(req, Buffer.from(data, encoding)); <ide> } <ide> function abort(stream) { <ide> class Http2Stream extends Duplex { <ide> constructor(session, options) { <ide> options.allowHalfOpen = true; <add> options.decodeStrings = false; <ide> super(options); <ide> this.cork(); <ide> this[kSession] = session; <ide><path>test/parallel/test-http2-createwritereq.js <add>// Flags: --expose-http2 <add>'use strict'; <add> <add>const common = require('../common'); <add>if (!common.hasCrypto) <add> common.skip('missing crypto'); <add>const assert = require('assert'); <add>const http2 = require('http2'); <add> <add>// Tests that write uses the correct encoding when writing <add>// using the helper function createWriteReq <add> <add>const testString = 'a\u00A1\u0100\uD83D\uDE00'; <add> <add>const encodings = { <add> 'buffer': 'utf8', <add> 'ascii': 'ascii', <add> 'latin1': 'latin1', <add> 'binary': 'latin1', <add> 'utf8': 'utf8', <add> 'utf-8': 'utf8', <add> 'ucs2': 'ucs2', <add> 'ucs-2': 'ucs2', <add> 'utf16le': 'ucs2', <add> 'utf-16le': 'ucs2', <add> 'UTF8': 'utf8' // should fall through to Buffer.from <add>}; <add> <add>const testsToRun = Object.keys(encodings).length; <add>let testsFinished = 0; <add> <add>const server = http2.createServer(common.mustCall((req, res) => { <add> const testEncoding = encodings[req.path.slice(1)]; <add> <add> req.on('data', common.mustCall((chunk) => assert.ok( <add> Buffer.from(testString, testEncoding).equals(chunk) <add> ))); <add> <add> req.on('end', () => res.end()); <add>}, Object.keys(encodings).length)); <add> <add>server.listen(0, common.mustCall(function() { <add> Object.keys(encodings).forEach((writeEncoding) => { <add> const client = http2.connect(`http://localhost:${this.address().port}`); <add> const req = client.request({ <add> ':path': `/${writeEncoding}`, <add> ':method': 'POST' <add> }); <add> <add> assert.strictEqual(req._writableState.decodeStrings, false); <add> req.write( <add> writeEncoding !== 'buffer' ? testString : Buffer.from(testString), <add> writeEncoding !== 'buffer' ? writeEncoding : undefined <add> ); <add> req.resume(); <add> <add> req.on('end', common.mustCall(function() { <add> client.destroy(); <add> testsFinished++; <add> <add> if (testsFinished === testsToRun) { <add> server.close(); <add> } <add> })); <add> <add> req.end(); <add> }); <add>}));
3
Text
Text
fix typographical errors in introductory texts
402ccb36f15777b18952104bc2f7afcd7f2ae30e
<ide><path>client/src/pages/learn/information-security-and-quality-assurance/advanced-node-and-express/index.md <ide> superBlock: Information Security and Quality Assurance <ide> <ide> *Authentication* is the process or action of verifying the identity of a user or process. Up to this point you have not been able to create an app utilizing this key concept. <ide> <del>The most common and easiest to use authentication middleware for Node.js is [Passport](http://passportjs.org/). It is easy to learn, light-weight, and extremely flexible allowing for many *strategies*, which we will talk about in later challenges. In addition to authentication we will also look at template engines which allow for use of *Pug* and web sockets which allow for real time communication between all your clients and your server. Working on these challenges will involve you writing your code on Glitch on our starter project. After completing each challenge you can copy your public glitch url (to the homepage of your app) into the challenge screen to test it! Optionally you may choose to write your project on another platform but it must be publicly visible for our testing. <add>The most common and easiest way to use authentication middleware for Node.js is [Passport](http://passportjs.org/). It is easy to learn, light-weight, and extremely flexible allowing for many *strategies*, which we will talk about in later challenges. In addition to authentication we will also look at template engines which allow for use of *Pug* and web sockets which allow for real time communication between all your clients and your server. Working on these challenges will involve you writing your code on Glitch on our starter project. After completing each challenge you can copy your public glitch url (to the homepage of your app) into the challenge screen to test it! Optionally you may choose to write your project on another platform but it must be publicly visible for our testing. <ide> <ide> Start this project on Glitch using [this link](https://glitch.com/edit/#!/remix/clone-from-repo?REPO_URL=https://github.com/freeCodeCamp/boilerplate-advancednode/) or clone [this repository](https://github.com/freeCodeCamp/boilerplate-advancednode/) on GitHub! If you use Glitch, remember to save the link to your project somewhere safe.
1
Python
Python
fix a logging issue
4d2c26f95aad62f2ea7fa6ad0e5b73def13cb874
<ide><path>official/vision/modeling/backbones/vit.py <ide> def build(self, inputs_shape): <ide> def _interpolate(self, pos_embedding: tf.Tensor, from_shape: Tuple[int, int], <ide> to_shape: Tuple[int, int]) -> tf.Tensor: <ide> """Interpolates the positional embeddings.""" <del> logging.info('Interpolating postional embedding from length: %d to %d', <add> logging.info('Interpolating postional embedding from length: %s to %s', <ide> from_shape, to_shape) <ide> grid_emb = tf.reshape(pos_embedding, [1] + list(from_shape) + [-1]) <ide> # NOTE: Using BILINEAR interpolation by default.
1
Text
Text
add link to 'pry' in debugging guide [ci skip]
a170304174133cafd2269423428042f68afe3a62
<ide><path>guides/source/debugging_rails_applications.md <ide> development that will end your tailing of development.log. Have all information <ide> about your Rails app requests in the browser — in the Developer Tools panel. <ide> Provides insight to db/rendering/total times, parameter list, rendered views and <ide> more. <add>* [Pry](https://github.com/pry/pry) An IRB alternative and runtime developer console. <ide> <ide> References <ide> ----------
1
Ruby
Ruby
rewrite conditions in more natural way
4489a8684f258c6a56d3e44397fae15bc6784ddb
<ide><path>Library/Homebrew/formula_installer.rb <ide> def check_install_sanity <ide> <ide> if f.installed? <ide> msg = "#{f}-#{f.installed_version} already installed" <del> msg << ", it's just not linked" if not f.linked_keg.symlink? and not f.keg_only? <add> msg << ", it's just not linked" unless f.linked_keg.symlink? or f.keg_only? <ide> raise FormulaAlreadyInstalledError, msg <ide> end <ide> <ide> def install_dependency dep <ide> end <ide> <ide> def caveats <del> if (not f.keg_only?) and ARGV.homebrew_developer? <add> if ARGV.homebrew_developer? and not f.keg_only? <ide> audit_bin <ide> audit_sbin <ide> audit_lib
1
Go
Go
drop side effect from registerlinks()
388fe4aea82a37f38ff96db5594643b14b3f73e8
<ide><path>daemon/daemon_unix.go <ide> func getUnmountOnShutdownPath(config *config.Config) string { <ide> return filepath.Join(config.ExecRoot, "unmount-on-shutdown") <ide> } <ide> <del>// registerLinks writes the links to a file. <add>// registerLinks registers network links between container and other containers <add>// with the daemon using the specification in hostConfig. <ide> func (daemon *Daemon) registerLinks(container *container.Container, hostConfig *containertypes.HostConfig) error { <ide> if hostConfig == nil || hostConfig.NetworkMode.IsUserDefined() { <ide> return nil <ide> func (daemon *Daemon) registerLinks(container *container.Container, hostConfig * <ide> } <ide> } <ide> <del> // After we load all the links into the daemon <del> // set them to nil on the hostconfig <del> _, err := container.WriteHostConfig() <del> return err <add> return nil <ide> } <ide> <ide> // conditionalMountOnStart is a platform specific helper function during the
1
Java
Java
predict specific object type in ehcachefactorybean
0690b58878f0e6c57a443720244049b16ba3cfd5
<ide><path>spring-context/src/main/java/org/springframework/cache/ehcache/EhCacheFactoryBean.java <ide> /* <del> * Copyright 2002-2011 the original author or authors. <add> * Copyright 2002-2012 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import net.sf.ehcache.constructs.blocking.UpdatingSelfPopulatingCache; <ide> import net.sf.ehcache.event.CacheEventListener; <ide> import net.sf.ehcache.store.MemoryStoreEvictionPolicy; <add> <ide> import org.apache.commons.logging.Log; <ide> import org.apache.commons.logging.LogFactory; <ide> <ide> public Ehcache getObject() { <ide> return this.cache; <ide> } <ide> <add> /** <add> * Predict the particular {@code Ehcache} implementation that will be returned from <add> * {@link #getObject()} based on logic in {@link #createCache()} and <add> * {@link #decorateCache(Ehcache)} as orchestrated by {@link #afterPropertiesSet()}. <add> */ <ide> public Class<? extends Ehcache> getObjectType() { <del> return (this.cache != null ? this.cache.getClass() : Ehcache.class); <add> if (this.cache != null) { <add> return this.cache.getClass(); <add> } <add> if (this.cacheEntryFactory != null) { <add> if (this.cacheEntryFactory instanceof UpdatingCacheEntryFactory) { <add> return UpdatingSelfPopulatingCache.class; <add> } <add> else { <add> return SelfPopulatingCache.class; <add> } <add> } <add> if (this.blocking) { <add> return BlockingCache.class; <add> } <add> return Cache.class; <ide> } <ide> <ide> public boolean isSingleton() { <ide><path>spring-context/src/test/java/org/springframework/cache/ehcache/EhCacheSupportTests.java <ide> /* <del> * Copyright 2002-2009 the original author or authors. <add> * Copyright 2002-2012 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> package org.springframework.cache.ehcache; <ide> <ide> import junit.framework.TestCase; <add> <ide> import net.sf.ehcache.Cache; <ide> import net.sf.ehcache.CacheManager; <ide> import net.sf.ehcache.Ehcache; <ide> private void doTestEhCacheFactoryBean(boolean useCacheManagerFb) throws Exceptio <ide> EhCacheManagerFactoryBean cacheManagerFb = null; <ide> try { <ide> EhCacheFactoryBean cacheFb = new EhCacheFactoryBean(); <del> assertEquals(Ehcache.class, cacheFb.getObjectType()); <add> Class<? extends Ehcache> objectType = cacheFb.getObjectType(); <add> assertTrue(Ehcache.class.isAssignableFrom(objectType)); <ide> assertTrue("Singleton property", cacheFb.isSingleton()); <ide> if (useCacheManagerFb) { <ide> cacheManagerFb = new EhCacheManagerFactoryBean(); <ide> private void doTestEhCacheFactoryBean(boolean useCacheManagerFb) throws Exceptio <ide> cacheFb.setCacheName("myCache1"); <ide> cacheFb.afterPropertiesSet(); <ide> cache = (Cache) cacheFb.getObject(); <add> Class<? extends Ehcache> objectType2 = cacheFb.getObjectType(); <add> assertSame(objectType, objectType2); <ide> CacheConfiguration config = cache.getCacheConfiguration(); <ide> assertEquals("myCache1", cache.getName()); <ide> if (useCacheManagerFb){ <ide> public void testEhCacheFactoryBeanWithBlockingCache() throws Exception { <ide> cacheFb.setCacheManager(cm); <ide> cacheFb.setCacheName("myCache1"); <ide> cacheFb.setBlocking(true); <add> assertEquals(cacheFb.getObjectType(), BlockingCache.class); <ide> cacheFb.afterPropertiesSet(); <ide> Ehcache myCache1 = cm.getEhcache("myCache1"); <ide> assertTrue(myCache1 instanceof BlockingCache); <ide> public Object createEntry(Object key) throws Exception { <ide> return key; <ide> } <ide> }); <add> assertEquals(cacheFb.getObjectType(), SelfPopulatingCache.class); <ide> cacheFb.afterPropertiesSet(); <ide> Ehcache myCache1 = cm.getEhcache("myCache1"); <ide> assertTrue(myCache1 instanceof SelfPopulatingCache); <ide> public Object createEntry(Object key) throws Exception { <ide> public void updateEntryValue(Object key, Object value) throws Exception { <ide> } <ide> }); <add> assertEquals(cacheFb.getObjectType(), UpdatingSelfPopulatingCache.class); <ide> cacheFb.afterPropertiesSet(); <ide> Ehcache myCache1 = cm.getEhcache("myCache1"); <ide> assertTrue(myCache1 instanceof UpdatingSelfPopulatingCache);
2
PHP
PHP
improve error handling and output messages display
ee684832b5d51fbab39d5befefa499c0a58595f9
<ide><path>src/Shell/Task/AssetsTask.php <ide> protected function _process() { <ide> <ide> $link = Inflector::underscore($plugin); <ide> $dir = WWW_ROOT; <del> if (file_exists($dir . $link)) { <del> $this->out($link . ' already exists'); <del> $this->out(); <del> continue; <del> } <ide> <ide> if (strpos('/', $link) !== false) { <ide> $parts = explode('/', $link); <ide> $link = array_pop($parts); <ide> $dir = WWW_ROOT . implode(DS, $parts) . DS; <ide> if (!is_dir($dir)) { <del> $this->out('Creating directory: ' . $dir); <del> $this->out(); <ide> $old = umask(0); <del> mkdir($dir, 0755, true); <add> // @codingStandardsIgnoreStart <add> $result = @mkdir($dir, 0755, true); <add> // @codingStandardsIgnoreEnd <ide> umask($old); <add> <add> if ($result) { <add> $this->out('Created directory ' . $dir); <add> } else { <add> $this->err('Failed creating directory ' . $dir); <add> continue; <add> } <ide> } <ide> } <ide> <del> $this->out('Creating symlink: ' . $dir); <del> $this->out(); <add> if (file_exists($dir . $link)) { <add> $this->out($link . ' already exists', 1, Shell::VERBOSE); <add> continue; <add> } <add> <ide> // @codingStandardsIgnoreStart <ide> $result = @symlink($path, $dir . $link); <ide> // @codingStandardsIgnoreEnd <ide> <del> if (!$result) { <del> $this->err('Symlink creation failed'); <del> $this->out('Copying to directory:' . $dir); <del> $this->out(); <del> $folder = new Folder($path); <del> $folder->copy(['to' => $dir . $link]); <add> if ($result) { <add> $this->out('Created symlink ' . $dir . $link); <add> continue; <add> } <add> <add> $folder = new Folder($path); <add> if ($folder->copy(['to' => $dir . $link])) { <add> $this->out('Copied assets to directory ' . $dir); <add> } else { <add> $this->err('Error copying assets to directory ' . $dir); <ide> } <ide> } <ide> <ide> $this->out(); <del> $this->out('Done.'); <add> $this->out('Done'); <ide> } <ide> <ide> }
1
Ruby
Ruby
avoid class_attrs for unused collection callbacks
bfcac1359e6a1848c07ced1b301a339b54fb260d
<ide><path>activerecord/lib/active_record/associations/builder/collection_association.rb <ide> def self.define_extensions(model, name, &block) <ide> def self.define_callback(model, callback_name, name, options) <ide> full_callback_name = "#{callback_name}_for_#{name}" <ide> <del> unless model.method_defined?(full_callback_name) <add> callback_values = Array(options[callback_name.to_sym]) <add> method_defined = model.respond_to?(full_callback_name) <add> <add> # If there are no callbacks, we must also check if a superclass had <add> # previously defined this association <add> return if callback_values.empty? && !method_defined <add> <add> unless method_defined <ide> model.class_attribute(full_callback_name, instance_accessor: false, instance_predicate: false) <ide> end <ide> <del> callbacks = Array(options[callback_name.to_sym]).map do |callback| <add> callbacks = callback_values.map do |callback| <ide> case callback <ide> when Symbol <ide> ->(method, owner, record) { owner.send(callback, record) } <ide><path>activerecord/lib/active_record/associations/collection_association.rb <ide> def callback(method, record) <ide> <ide> def callbacks_for(callback_name) <ide> full_callback_name = "#{callback_name}_for_#{reflection.name}" <del> owner.class.send(full_callback_name) <add> if owner.class.respond_to?(full_callback_name) <add> owner.class.send(full_callback_name) <add> else <add> [] <add> end <ide> end <ide> <ide> def include_in_memory?(record)
2
Javascript
Javascript
remove deprecated screen api from the cache
b2d3c569b6f11fb46d19750a0f02fb27141102f0
<ide><path>src/module-cache.js <ide> function registerBuiltins(devMode) { <ide> 'crash-reporter', <ide> 'ipc-renderer', <ide> 'remote', <del> 'screen' <add> //'screen' Deprecated https://www.electronjs.org/docs/breaking-changes#api-changed-electronscreen-in-the-renderer-process-should-be-accessed-via-remote <ide> ]; <ide> for (const builtin of rendererBuiltins) { <ide> cache.builtins[builtin] = path.join(rendererRoot, `${builtin}.js`);
1
Javascript
Javascript
update head-manager to compress better
513a7d5b5c44a1a288b68a9c06616e3356808098
<ide><path>packages/next/client/head-manager.js <ide> const DOMAttributeNames = { <ide> httpEquiv: 'http-equiv', <ide> } <ide> <del>export default class HeadManager { <del> constructor() { <del> this.updatePromise = null <del> } <del> <del> updateHead = head => { <del> const promise = (this.updatePromise = Promise.resolve().then(() => { <del> if (promise !== this.updatePromise) return <del> <del> this.updatePromise = null <del> this.doUpdateHead(head) <del> })) <del> } <del> <del> doUpdateHead(head) { <del> const tags = {} <del> head.forEach(h => { <del> const components = tags[h.type] || [] <del> components.push(h) <del> tags[h.type] = components <del> }) <del> <del> this.updateTitle(tags.title ? tags.title[0] : null) <del> <del> const types = ['meta', 'base', 'link', 'style', 'script'] <del> types.forEach(type => { <del> this.updateElements(type, tags[type] || []) <del> }) <del> } <del> <del> updateTitle(component) { <del> let title = '' <del> if (component) { <del> const { children } = component.props <del> title = typeof children === 'string' ? children : children.join('') <del> } <del> if (title !== document.title) document.title = title <del> } <del> <del> updateElements(type, components) { <del> const headEl = document.getElementsByTagName('head')[0] <del> const headCountEl = headEl.querySelector('meta[name=next-head-count]') <del> if (process.env.NODE_ENV !== 'production') { <del> if (!headCountEl) { <del> console.error( <del> 'Warning: next-head-count is missing. https://err.sh/next.js/next-head-count-missing' <del> ) <del> return <del> } <del> } <del> <del> const headCount = Number(headCountEl.content) <del> const oldTags = [] <del> <del> for ( <del> let i = 0, j = headCountEl.previousElementSibling; <del> i < headCount; <del> i++, j = j.previousElementSibling <del> ) { <del> if (j.tagName.toLowerCase() === type) { <del> oldTags.push(j) <del> } <del> } <del> const newTags = components.map(reactElementToDOM).filter(newTag => { <del> for (let k = 0, len = oldTags.length; k < len; k++) { <del> const oldTag = oldTags[k] <del> if (oldTag.isEqualNode(newTag)) { <del> oldTags.splice(k, 1) <del> return false <del> } <del> } <del> return true <del> }) <del> <del> oldTags.forEach(t => t.parentNode.removeChild(t)) <del> newTags.forEach(t => headEl.insertBefore(t, headCountEl)) <del> headCountEl.content = ( <del> headCount - <del> oldTags.length + <del> newTags.length <del> ).toString() <del> } <del>} <del> <ide> function reactElementToDOM({ type, props }) { <ide> const el = document.createElement(type) <ide> for (const p in props) { <ide> function reactElementToDOM({ type, props }) { <ide> } <ide> return el <ide> } <add> <add>function updateElements(type, components) { <add> const headEl = document.getElementsByTagName('head')[0] <add> const headCountEl = headEl.querySelector('meta[name=next-head-count]') <add> if (process.env.NODE_ENV !== 'production') { <add> if (!headCountEl) { <add> console.error( <add> 'Warning: next-head-count is missing. https://err.sh/next.js/next-head-count-missing' <add> ) <add> return <add> } <add> } <add> <add> const headCount = Number(headCountEl.content) <add> const oldTags = [] <add> <add> for ( <add> let i = 0, j = headCountEl.previousElementSibling; <add> i < headCount; <add> i++, j = j.previousElementSibling <add> ) { <add> if (j.tagName.toLowerCase() === type) { <add> oldTags.push(j) <add> } <add> } <add> const newTags = components.map(reactElementToDOM).filter(newTag => { <add> for (let k = 0, len = oldTags.length; k < len; k++) { <add> const oldTag = oldTags[k] <add> if (oldTag.isEqualNode(newTag)) { <add> oldTags.splice(k, 1) <add> return false <add> } <add> } <add> return true <add> }) <add> <add> oldTags.forEach(t => t.parentNode.removeChild(t)) <add> newTags.forEach(t => headEl.insertBefore(t, headCountEl)) <add> headCountEl.content = (headCount - oldTags.length + newTags.length).toString() <add>} <add> <add>export default function initHeadManager() { <add> let updatePromise = null <add> <add> return head => { <add> const promise = (updatePromise = Promise.resolve().then(() => { <add> if (promise !== updatePromise) return <add> <add> updatePromise = null <add> const tags = {} <add> <add> head.forEach(h => { <add> const components = tags[h.type] || [] <add> components.push(h) <add> tags[h.type] = components <add> }) <add> <add> const titleComponent = tags.title ? tags.title[0] : null <add> let title = '' <add> if (titleComponent) { <add> const { children } = titleComponent.props <add> title = typeof children === 'string' ? children : children.join('') <add> } <add> if (title !== document.title) document.title = title <add> ;['meta', 'base', 'link', 'style', 'script'].forEach(type => { <add> updateElements(type, tags[type] || []) <add> }) <add> })) <add> } <add>} <ide><path>packages/next/client/index.js <ide> /* global location */ <ide> import React from 'react' <ide> import ReactDOM from 'react-dom' <del>import HeadManager from './head-manager' <add>import initHeadManager from './head-manager' <ide> import { createRouter, makePublicRouterInstance } from 'next/router' <ide> import mitt from '../next-server/lib/mitt' <ide> import { loadGetInitialProps, getURL, ST } from '../next-server/lib/utils' <ide> if (window.__NEXT_P) { <ide> window.__NEXT_P = [] <ide> window.__NEXT_P.push = register <ide> <del>const headManager = new HeadManager() <add>const updateHead = initHeadManager() <ide> const appElement = document.getElementById('__next') <ide> <ide> let lastAppProps <ide> function AppContainer({ children }) { <ide> } <ide> > <ide> <RouterContext.Provider value={makePublicRouterInstance(router)}> <del> <HeadManagerContext.Provider value={headManager.updateHead}> <add> <HeadManagerContext.Provider value={updateHead}> <ide> {children} <ide> </HeadManagerContext.Provider> <ide> </RouterContext.Provider> <ide><path>test/integration/size-limit/test/index.test.js <ide> describe('Production response size', () => { <ide> ) <ide> <ide> // These numbers are without gzip compression! <del> const delta = responseSizesBytes - 238 * 1024 <add> const delta = responseSizesBytes - 237 * 1024 <ide> expect(delta).toBeLessThanOrEqual(1024) // don't increase size more than 1kb <ide> expect(delta).toBeGreaterThanOrEqual(-1024) // don't decrease size more than 1kb without updating target <ide> })
3
PHP
PHP
remove forgotten echo statement
e9952e5a07d4cbd664fdac743ede25f10b7abb1c
<ide><path>src/Illuminate/Foundation/Console/ServeCommand.php <ide> public function handle() <ide> return $this->handle(); <ide> } <ide> <del> echo $status; <del> <ide> return $status; <ide> } <ide>
1
Text
Text
use code markup/markdown in headers
fc949343bf1fd6ec1222e152414209c1881899d6
<ide><path>doc/api/inspector.md <ide> It can be accessed using: <ide> const inspector = require('inspector'); <ide> ``` <ide> <del>## inspector.close() <add>## `inspector.close()` <ide> <ide> Deactivate the inspector. Blocks until there are no active connections. <ide> <del>## inspector.console <add>## `inspector.console` <ide> <ide> * {Object} An object to send messages to the remote inspector console. <ide> <ide> require('inspector').console.log('a message'); <ide> The inspector console does not have API parity with Node.js <ide> console. <ide> <del>## inspector.open(\[port\[, host\[, wait\]\]\]) <add>## `inspector.open([port[, host[, wait]]])` <ide> <ide> * `port` {number} Port to listen on for inspector connections. Optional. <ide> **Default:** what was specified on the CLI. <ide> and flow control has been passed to the debugger client. <ide> See the [security warning](cli.html#inspector_security) regarding the `host` <ide> parameter usage. <ide> <del>## inspector.url() <add>## `inspector.url()` <ide> <ide> * Returns: {string|undefined} <ide> <ide> $ node -p 'inspector.url()' <ide> undefined <ide> ``` <ide> <del>## inspector.waitForDebugger() <add>## `inspector.waitForDebugger()` <ide> <!-- YAML <ide> added: v12.7.0 <ide> --> <ide> Blocks until a client (existing or connected later) has sent <ide> <ide> An exception will be thrown if there is no active inspector. <ide> <del>## Class: inspector.Session <add>## Class: `inspector.Session` <ide> <ide> * Extends: {EventEmitter} <ide> <ide> The `inspector.Session` is used for dispatching messages to the V8 inspector <ide> back-end and receiving message responses and notifications. <ide> <del>### Constructor: new inspector.Session() <add>### Constructor: `new inspector.Session()` <ide> <!-- YAML <ide> added: v8.0.0 <ide> --> <ide> Create a new instance of the `inspector.Session` class. The inspector session <ide> needs to be connected through [`session.connect()`][] before the messages <ide> can be dispatched to the inspector backend. <ide> <del>### Event: 'inspectorNotification' <add>### Event: `'inspectorNotification'` <ide> <!-- YAML <ide> added: v8.0.0 <ide> --> <ide> session.on('inspectorNotification', (message) => console.log(message.method)); <ide> <ide> It is also possible to subscribe only to notifications with specific method: <ide> <del>### Event: &lt;inspector-protocol-method&gt; <add>### Event: `<inspector-protocol-method>`; <ide> <!-- YAML <ide> added: v8.0.0 <ide> --> <ide> session.on('Debugger.paused', ({ params }) => { <ide> // [ '/the/file/that/has/the/breakpoint.js:11:0' ] <ide> ``` <ide> <del>### session.connect() <add>### `session.connect()` <ide> <!-- YAML <ide> added: v8.0.0 <ide> --> <ide> <ide> Connects a session to the inspector back-end. <ide> <del>### session.connectToMainThread() <add>### `session.connectToMainThread()` <ide> <!-- YAML <ide> added: v12.11.0 <ide> --> <ide> <ide> Connects a session to the main thread inspector back-end. An exception will <ide> be thrown if this API was not called on a Worker thread. <ide> <del>### session.disconnect() <add>### `session.disconnect()` <ide> <!-- YAML <ide> added: v8.0.0 <ide> --> <ide> with an error. [`session.connect()`][] will need to be called to be able to send <ide> messages again. Reconnected session will lose all inspector state, such as <ide> enabled agents or configured breakpoints. <ide> <del>### session.post(method\[, params\]\[, callback\]) <add>### `session.post(method[, params][, callback])` <ide> <!-- YAML <ide> added: v8.0.0 <ide> -->
1
Python
Python
update documentation for preprocessing layers
069e95a5c8075555b3bd2895bdbf34ed68bb3bba
<ide><path>keras/layers/preprocessing/category_encoding.py <ide> class CategoryEncoding(base_layer.Layer): <ide> `(..., num_tokens)`. <ide> - `"count"`: Like `"multi_hot"`, but the int array contains a count of <ide> the number of times the token at that index appeared in the sample. <add> For all output modes, currently only output up to rank 2 is supported. <ide> sparse: Boolean. If true, returns a `SparseTensor` instead of a dense <ide> `Tensor`. Defaults to `False`. <ide> <ide> Call arguments: <del> inputs: A 2D tensor `(samples, timesteps)`. <del> count_weights: A 2D tensor in the same shape as `inputs` indicating the <add> inputs: A 1D or 2D tensor of integer inputs. <add> count_weights: A tensor in the same shape as `inputs` indicating the <ide> weight for each sample value when summing up in `count` mode. Not used in <del> `"multi_hot"` mode. <add> `"multi_hot"` or `"one_hot"` modes. <ide> """ <ide> <ide> def __init__(self, <ide> num_tokens=None, <del> output_mode=MULTI_HOT, <add> output_mode="multi_hot", <ide> sparse=False, <ide> **kwargs): <ide> # max_tokens is an old name for the num_tokens arg we continue to support <ide><path>keras/layers/preprocessing/integer_lookup.py <ide> class IntegerLookup(index_lookup.IndexLookup): <ide> number of times the token at that index appeared in the sample. <ide> - `"tf_idf"`: As `"multi_hot"`, but the TF-IDF algorithm is applied to <ide> find the value in each token slot. <add> For `"int"` output, any shape of input and output is supported. For all <add> other output modes, currently only output up to rank 2 is supported. <ide> pad_to_max_tokens: Only applicable when `output_mode` is `"multi_hot"`, <ide> `"count"`, or `"tf_idf"`. If True, the output will have its feature axis <ide> padded to `max_tokens` even if the number of unique tokens in the <ide><path>keras/layers/preprocessing/string_lookup.py <ide> class StringLookup(index_lookup.IndexLookup): <ide> number of times the token at that index appeared in the sample. <ide> - `"tf_idf"`: As `"multi_hot"`, but the TF-IDF algorithm is applied to <ide> find the value in each token slot. <add> For `"int"` output, any shape of input and output is supported. For all <add> other output modes, currently only output up to rank 2 is supported. <ide> pad_to_max_tokens: Only applicable when `output_mode` is `"multi_hot"`, <ide> `"count"`, or `"tf_idf"`. If True, the output will have its feature axis <ide> padded to `max_tokens` even if the number of unique tokens in the <ide><path>keras/layers/preprocessing/text_vectorization.py <ide> class TextVectorization(base_preprocessing_layer.CombinerPreprocessingLayer): <ide> batch item. <ide> - `"tf_idf"`: Like `"multi_hot"`, but the TF-IDF algorithm is applied to <ide> find the value in each token slot. <add> For `"int"` output, any shape of input and output is supported. For all <add> other output modes, currently only rank 1 inputs (and rank 2 outputs after <add> splitting) are supported. <ide> output_sequence_length: Only valid in INT mode. If set, the output will have <ide> its time dimension padded or truncated to exactly `output_sequence_length` <ide> values, resulting in a tensor of shape
4
Python
Python
update openstack identity tests
688839519d2212f2849eac26985961515a6130ea
<ide><path>libcloud/test/common/test_openstack_identity.py <ide> def test_auth_url_is_correctly_assembled(self): <ide> ), <ide> ] <ide> <del> APPEND = 0 <del> NOTAPPEND = 1 <del> <ide> auth_urls = [ <del> ("https://auth.api.example.com", APPEND, ""), <del> ("https://auth.api.example.com/", NOTAPPEND, "/"), <del> ("https://auth.api.example.com/foo/bar", NOTAPPEND, "/foo/bar"), <del> ("https://auth.api.example.com/foo/bar/", NOTAPPEND, "/foo/bar/"), <add> ("https://auth.api.example.com", ""), <add> ("https://auth.api.example.com/", "/"), <add> ("https://auth.api.example.com/foo/bar", "/foo/bar"), <add> ("https://auth.api.example.com/foo/bar/", "/foo/bar/"), <ide> ] <ide> <ide> actions = { <del> "1.0": "/v1.0", <del> "1.1": "/v1.1/auth", <del> "2.0": "/v2.0/tokens", <del> "2.0_apikey": "/v2.0/tokens", <del> "2.0_password": "/v2.0/tokens", <del> "3.x_password": "/v3/auth/tokens", <del> "3.x_appcred": "/v3/auth/tokens", <del> "3.x_oidc_access_token": "/v3/OS-FEDERATION/identity_providers/user_name/protocols/tenant-name/auth", <add> "1.0": "{url_path}/v1.0", <add> "1.1": "{url_path}/v1.1/auth", <add> "2.0": "{url_path}/v2.0/tokens", <add> "2.0_apikey": "{url_path}/v2.0/tokens", <add> "2.0_password": "{url_path}/v2.0/tokens", <add> "3.x_password": "{url_path}/v3/auth/tokens", <add> "3.x_appcred": "{url_path}/v3/auth/tokens", <add> "3.x_oidc_access_token": "{url_path}/v3/OS-FEDERATION/identity_providers/user_name/protocols/tenant-name/auth", <ide> } <ide> <ide> user_id = OPENSTACK_PARAMS[0] <ide> key = OPENSTACK_PARAMS[1] <ide> <ide> for (auth_version, mock_http_class, kwargs) in tuples: <del> for (url, should_append_default_path, expected_path) in auth_urls: <add> for (url, url_path) in auth_urls: <ide> connection = self._get_mock_connection( <ide> mock_http_class=mock_http_class, auth_url=url <ide> ) <ide> def test_auth_url_is_correctly_assembled(self): <ide> except Exception: <ide> pass <ide> <del> if should_append_default_path == APPEND: <del> expected_path = actions[auth_version] <add> expected_path = ( <add> actions[auth_version].format(url_path=url_path).replace("//", "/") <add> ) <ide> <del> self.assertEqual(osa.action, expected_path) <add> self.assertEqual( <add> osa.action, <add> expected_path, <add> ) <ide> <ide> def test_basic_authentication(self): <ide> tuples = [
1
Python
Python
add batch dimension in encode
d6dde438eaf7117fa17de0c4ede3e5126989dfdf
<ide><path>examples/run_tf_glue.py <ide> tf_model.compile(optimizer=optimizer, loss=loss, metrics=['sparse_categorical_accuracy']) <ide> <ide> # Train and evaluate using tf.keras.Model.fit() <del>tf_model.fit(train_dataset, epochs=1, steps_per_epoch=115, validation_data=valid_dataset, validation_steps=7) <add>tf_model.fit(train_dataset, epochs=3, steps_per_epoch=115, validation_data=valid_dataset, validation_steps=7) <ide> <ide> # Save the model and load it in PyTorch <ide> tf_model.save_pretrained('./runs/') <del>pt_model = BertForSequenceClassification.from_pretrained('./runs/') <add>pt_model = BertForSequenceClassification.from_pretrained('./runs/', from_tf=True) <ide> <ide> # Quickly inspect a few predictions <del>inputs = tokenizer.encode_plus("I said the company is doing great", "The company has good results", add_special_tokens=True) <del>pred = pt_model(torch.tensor([tokens])) <del> <del># Divers <del>import torch <del> <del>import tensorflow as tf <del>import tensorflow_datasets <del>from pytorch_transformers import BertTokenizer, BertForSequenceClassification, TFBertForSequenceClassification, glue_convert_examples_to_features <del> <del># Load tokenizer, model, dataset <del>tokenizer = BertTokenizer.from_pretrained('bert-base-cased') <del>model = TFBertForSequenceClassification.from_pretrained('bert-base-cased') <del> <del>pt_train_dataset = torch.load('../../data/glue_data//MRPC/cached_train_bert-base-cased_128_mrpc') <del> <del>def gen(): <del> for el in pt_train_dataset: <del> yield ((el.input_ids, el.attention_mask, el.token_type_ids), (el.label,)) <del> <del>dataset = tf.data.Dataset.from_generator(gen, <del> ((tf.int32, tf.int32, tf.int32), (tf.int64,)), <del> ((tf.TensorShape([None]), tf.TensorShape([None]), tf.TensorShape([None])), <del> (tf.TensorShape([]),))) <del> <del>dataset = dataset.shuffle(100).batch(32) <del>next(iter(dataset)) <del> <del>learning_rate = tf.keras.optimizers.schedules.PolynomialDecay(2e-5, 345, 0) <del>loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True) <del>model.compile(optimizer=tf.keras.optimizers.Adam( <del> learning_rate=learning_rate, <del> epsilon=1e-08, <del> clipnorm=1.0), <del> loss=loss, <del> metrics=[['sparse_categorical_accuracy']]) <del> <del>tensorboard_cbk = tf.keras.callbacks.TensorBoard(log_dir='./runs/', update_freq=10, histogram_freq=1) <del> <del># Train model <del>model.fit(dataset, epochs=3, callbacks=[tensorboard_cbk]) <add>inputs = tokenizer.encode_plus("I said the company is doing great", "The company has good results", add_special_tokens=True, return_tensors='pt') <add>pred = pt_model(torch.tensor(tokens)) <ide><path>pytorch_transformers/tokenization_utils.py <ide> def prepare_for_model(self, ids, pair_ids=None, max_length=None, add_special_tok <ide> token_type_ids = [0] * len(ids) + ([1] * len(pair_ids) if pair else []) <ide> <ide> if return_tensors == 'tf' and is_tf_available(): <del> sequence = tf.constant(sequence) <del> token_type_ids = tf.constant(token_type_ids) <add> sequence = tf.constant([sequence]) <add> token_type_ids = tf.constant([token_type_ids]) <ide> elif return_tensors == 'pt' and is_torch_available(): <del> sequence = torch.tensor(sequence) <del> token_type_ids = torch.tensor(token_type_ids) <add> sequence = torch.tensor([sequence]) <add> token_type_ids = torch.tensor([token_type_ids]) <ide> elif return_tensors is not None: <ide> logger.warning("Unable to convert output to tensors format {}, PyTorch or TensorFlow is not available.".format(return_tensors)) <ide>
2
Java
Java
fix javadoc syntax
2980e592980e67dd41a0b2f5a079a8d82a252f87
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/BeanFactory.java <ide> * 1. BeanNameAware's {@code setBeanName}<br> <ide> * 2. BeanClassLoaderAware's {@code setBeanClassLoader}<br> <ide> * 3. BeanFactoryAware's {@code setBeanFactory}<br> <del> * 4. EnvironmentAware's {@code setEnvironment} <del> * 5. EmbeddedValueResolverAware's {@code setEmbeddedValueResolver} <add> * 4. EnvironmentAware's {@code setEnvironment}<br> <add> * 5. EmbeddedValueResolverAware's {@code setEmbeddedValueResolver}<br> <ide> * 6. ResourceLoaderAware's {@code setResourceLoader} <ide> * (only applicable when running in an application context)<br> <ide> * 7. ApplicationEventPublisherAware's {@code setApplicationEventPublisher}
1
Javascript
Javascript
use tabindex instead of tabindex
cb31d4cb6d2a9b8e4e04c6abb7729c74fb8f86a1
<ide><path>website/core/AlgoliaDocSearch.js <ide> var AlgoliaDocSearch = React.createClass({ <ide> render: function() { <ide> return ( <ide> <div className="algolia-search-wrapper"> <del> <input id="algolia-doc-search" tabindex="0" type="text" placeholder="Search docs..." /> <add> <input id="algolia-doc-search" tabIndex="0" type="text" placeholder="Search docs..." /> <ide> </div> <ide> ); <ide> }
1
PHP
PHP
remove extra whitespace
322f7fb15246956ae6decc6768cea239c84a4bd1
<ide><path>config/cache.php <ide> env('MEMCACHED_PASSWORD'), <ide> ], <ide> 'options' => [ <del> // Memcached::OPT_CONNECT_TIMEOUT => 2000, <add> // Memcached::OPT_CONNECT_TIMEOUT => 2000, <ide> ], <ide> 'servers' => [ <ide> [
1