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
Mixed
Go
extract api types to version packages
61634758c42014543e0ce429587bbba7fc6106ec
<ide><path>api/types/stats.go <ide> type Stats struct { <ide> BlkioStats BlkioStats `json:"blkio_stats,omitempty"` <ide> } <ide> <del>// StatsJSONPre121 is a backcompatibility struct along with ContainerConfig <del>type StatsJSONPre121 struct { <del> Stats <del> <del> // Network is for fallback stats where API Version < 1.21 <del> Network NetworkStats `json:"network,omitempty"` <del>} <del> <ide> // StatsJSON is newly used Networks <ide> type StatsJSON struct { <ide> Stats <ide><path>api/types/types.go <ide> type ContainerJSON struct { <ide> Config *runconfig.Config <ide> } <ide> <del>// ContainerJSON120 is a backcompatibility struct along with ContainerConfig120. <del>type ContainerJSON120 struct { <del> *ContainerJSONBase <del> Mounts []MountPoint <del> Config *ContainerConfig120 <del>} <del> <del>// ContainerJSONPre120 is a backcompatibility struct along with ContainerConfigPre120. <del>// Note this is not used by the Windows daemon. <del>type ContainerJSONPre120 struct { <del> *ContainerJSONBase <del> Volumes map[string]string <del> VolumesRW map[string]bool <del> Config *ContainerConfigPre120 <del>} <del> <del>// ContainerConfigPre120 is a backcompatibility struct used in ContainerJSONPre120 <del>type ContainerConfigPre120 struct { <del> *runconfig.Config <del> <del> // backward compatibility, they now live in HostConfig <del> VolumeDriver string <del> Memory int64 <del> MemorySwap int64 <del> CPUShares int64 `json:"CpuShares"` <del> CPUSet string `json:"CpuSet"` <del>} <del> <del>// ContainerConfig120 is a backcompatibility struct used in ContainerJSON120 <del>type ContainerConfig120 struct { <del> *runconfig.Config <del> // backward compatibility, it lives now in HostConfig <del> VolumeDriver string <del>} <del> <ide> // MountPoint represents a mount point configuration inside the container. <ide> type MountPoint struct { <ide> Name string `json:",omitempty"` <ide><path>api/types/versions/README.md <add>## Legacy API type versions <add> <add>This package includes types for legacy API versions. The stable version of the API types live in `api/types/*.go`. <add> <add>Consider moving a type here when you need to keep backwards compatibility in the API. This legacy types are organized by the latest API version they appear in. For instance, types in the `v1p19` package are valid for API versions below or equal `1.19`. Types in the `v1p20` package are valid for the API version `1.20`, since the versions below that will use the legacy types in `v1p19`. <add> <add>### Package name conventions <add> <add>The package name convention is to use `v` as a prefix for the version number and `p`(patch) as a separator. We use this nomenclature due to a few restrictions in the Go package name convention: <add> <add>1. We cannot use `.` because it's interpreted by the language, think of `v1.20.CallFunction`. <add>2. We cannot use `_` because golint complains abount it. The code is actually valid, but it looks probably more weird: `v1_20.CallFunction`. <add> <add>For instance, if you want to modify a type that was available in the version `1.21` of the API but it will have different fields in the version `1.22`, you want to create a new package under `api/types/versions/v1p21`. <ide><path>api/types/versions/v1p19/types.go <add>// Package v1p19 provides specific API types for the API version 1, patch 19. <add>package v1p19 <add> <add>import ( <add> "github.com/docker/docker/api/types" <add> "github.com/docker/docker/runconfig" <add>) <add> <add>// ContainerJSON is a backcompatibility struct for APIs prior to 1.20. <add>// Note this is not used by the Windows daemon. <add>type ContainerJSON struct { <add> *types.ContainerJSONBase <add> Volumes map[string]string <add> VolumesRW map[string]bool <add> Config *ContainerConfig <add>} <add> <add>// ContainerConfig is a backcompatibility struct for APIs prior to 1.20. <add>type ContainerConfig struct { <add> *runconfig.Config <add> <add> // backward compatibility, they now live in HostConfig <add> VolumeDriver string <add> Memory int64 <add> MemorySwap int64 <add> CPUShares int64 `json:"CpuShares"` <add> CPUSet string `json:"CpuSet"` <add>} <ide><path>api/types/versions/v1p20/types.go <add>// Package v1p20 provides specific API types for the API version 1, patch 20. <add>package v1p20 <add> <add>import ( <add> "github.com/docker/docker/api/types" <add> "github.com/docker/docker/runconfig" <add>) <add> <add>// ContainerJSON is a backcompatibility struct for the API 1.20 <add>type ContainerJSON struct { <add> *types.ContainerJSONBase <add> Mounts []types.MountPoint <add> Config *ContainerConfig <add>} <add> <add>// ContainerConfig is a backcompatibility struct used in ContainerJSON for the API 1.20 <add>type ContainerConfig struct { <add> *runconfig.Config <add> // backward compatibility, it lives now in HostConfig <add> VolumeDriver string <add>} <add> <add>// StatsJSON is a backcompatibility struct used in Stats for API prior to 1.21 <add>type StatsJSON struct { <add> types.Stats <add> Network types.NetworkStats `json:"network,omitempty"` <add>} <ide><path>daemon/inspect.go <ide> import ( <ide> "time" <ide> <ide> "github.com/docker/docker/api/types" <add> "github.com/docker/docker/api/types/versions/v1p20" <ide> ) <ide> <ide> // ContainerInspect returns low-level information about a <ide> func (daemon *Daemon) ContainerInspect(name string) (*types.ContainerJSON, error <ide> } <ide> <ide> // ContainerInspect120 serializes the master version of a container into a json type. <del>func (daemon *Daemon) ContainerInspect120(name string) (*types.ContainerJSON120, error) { <add>func (daemon *Daemon) ContainerInspect120(name string) (*v1p20.ContainerJSON, error) { <ide> container, err := daemon.Get(name) <ide> if err != nil { <ide> return nil, err <ide> func (daemon *Daemon) ContainerInspect120(name string) (*types.ContainerJSON120, <ide> } <ide> <ide> mountPoints := addMountPoints(container) <del> config := &types.ContainerConfig120{ <add> config := &v1p20.ContainerConfig{ <ide> container.Config, <ide> container.hostConfig.VolumeDriver, <ide> } <ide> <del> return &types.ContainerJSON120{base, mountPoints, config}, nil <add> return &v1p20.ContainerJSON{base, mountPoints, config}, nil <ide> } <ide> <ide> func (daemon *Daemon) getInspectData(container *Container) (*types.ContainerJSONBase, error) { <ide><path>daemon/inspect_unix.go <ide> <ide> package daemon <ide> <del>import "github.com/docker/docker/api/types" <add>import ( <add> "github.com/docker/docker/api/types" <add> "github.com/docker/docker/api/types/versions/v1p19" <add>) <ide> <ide> // This sets platform-specific fields <ide> func setPlatformSpecificContainerFields(container *Container, contJSONBase *types.ContainerJSONBase) *types.ContainerJSONBase { <ide> func setPlatformSpecificContainerFields(container *Container, contJSONBase *type <ide> } <ide> <ide> // ContainerInspectPre120 gets containers for pre 1.20 APIs. <del>func (daemon *Daemon) ContainerInspectPre120(name string) (*types.ContainerJSONPre120, error) { <add>func (daemon *Daemon) ContainerInspectPre120(name string) (*v1p19.ContainerJSON, error) { <ide> container, err := daemon.Get(name) <ide> if err != nil { <ide> return nil, err <ide> func (daemon *Daemon) ContainerInspectPre120(name string) (*types.ContainerJSONP <ide> volumesRW[m.Destination] = m.RW <ide> } <ide> <del> config := &types.ContainerConfigPre120{ <add> config := &v1p19.ContainerConfig{ <ide> container.Config, <ide> container.hostConfig.VolumeDriver, <ide> container.hostConfig.Memory, <ide> func (daemon *Daemon) ContainerInspectPre120(name string) (*types.ContainerJSONP <ide> container.hostConfig.CpusetCpus, <ide> } <ide> <del> return &types.ContainerJSONPre120{base, volumes, volumesRW, config}, nil <add> return &v1p19.ContainerJSON{base, volumes, volumesRW, config}, nil <ide> } <ide> <ide> func addMountPoints(container *Container) []types.MountPoint { <ide><path>daemon/stats.go <ide> import ( <ide> "io" <ide> <ide> "github.com/docker/docker/api/types" <add> "github.com/docker/docker/api/types/versions/v1p20" <ide> "github.com/docker/docker/daemon/execdriver" <ide> "github.com/docker/docker/pkg/version" <ide> "github.com/docker/libnetwork/osl" <ide> func (daemon *Daemon) ContainerStats(prefixOrName string, config *ContainerStats <ide> txErrors += v.TxErrors <ide> txDropped += v.TxDropped <ide> } <del> statsJSONPre121 := &types.StatsJSONPre121{ <add> statsJSONPre121 := &v1p20.StatsJSON{ <ide> Stats: statsJSON.Stats, <ide> Network: types.NetworkStats{ <ide> RxBytes: rxBytes,
8
Ruby
Ruby
avoid duplicate urls
bd4124c10fc5a281fe38cb7566b14dee14cb6368
<ide><path>Library/Homebrew/livecheck/livecheck.rb <ide> def checkable_urls(formula_or_cask) <ide> T.absurd(formula_or_cask) <ide> end <ide> <del> urls.compact <add> urls.compact.uniq <ide> end <ide> <ide> # Preprocesses and returns the URL used by livecheck. <ide> def latest_version( <ide> end <ide> end <ide> <add> checked_urls = [] <ide> # rubocop:disable Metrics/BlockLength <ide> urls.each_with_index do |original_url, i| <del> if debug <del> puts <del> if livecheck_url.is_a?(Symbol) <del> # This assumes the URL symbol will fit within the available space <del> puts "URL (#{livecheck_url}):".ljust(18, " ") + original_url <del> else <del> puts "URL: #{original_url}" <del> end <del> end <del> <ide> # Only preprocess the URL when it's appropriate <ide> url = if STRATEGY_SYMBOLS_TO_SKIP_PREPROCESS_URL.include?(livecheck_strategy) <ide> original_url <ide> else <ide> preprocess_url(original_url) <ide> end <add> next if checked_urls.include?(url) <ide> <ide> strategies = Strategy.from_url( <ide> url, <ide> def latest_version( <ide> strategy_name = livecheck_strategy_names[strategy] <ide> <ide> if debug <add> puts <add> if livecheck_url.is_a?(Symbol) <add> # This assumes the URL symbol will fit within the available space <add> puts "URL (#{livecheck_url}):".ljust(18, " ") + original_url <add> else <add> puts "URL: #{original_url}" <add> end <ide> puts "URL (processed): #{url}" if url != original_url <ide> if strategies.present? && verbose <ide> puts "Strategies: #{strategies.map { |s| livecheck_strategy_names[s] }.join(", ")}" <ide> def latest_version( <ide> match_version_map = strategy_data[:matches] <ide> regex = strategy_data[:regex] <ide> messages = strategy_data[:messages] <add> checked_urls << url <ide> <ide> if messages.is_a?(Array) && match_version_map.blank? <ide> puts messages unless json <ide><path>Library/Homebrew/test/livecheck/livecheck_spec.rb <ide> RUBY <ide> end <ide> <add> let(:f_duplicate_urls) do <add> formula("test_duplicate_urls") do <add> desc "Test formula with a duplicate URL" <add> homepage "https://github.com/Homebrew/brew.git" <add> url "https://brew.sh/test-0.0.1.tgz" <add> head "https://github.com/Homebrew/brew.git" <add> end <add> end <add> <ide> describe "::resolve_livecheck_reference" do <ide> context "when a formula/cask has a livecheck block without formula/cask methods" do <ide> it "returns [nil, []]" do <ide> it "returns the list of URLs to check" do <ide> expect(livecheck.checkable_urls(f)).to eq([stable_url, head_url, homepage_url]) <ide> expect(livecheck.checkable_urls(c)).to eq([cask_url, homepage_url]) <add> expect(livecheck.checkable_urls(f_duplicate_urls)).to eq([stable_url, head_url]) <ide> end <ide> end <ide>
2
Go
Go
change relative paths to absolute
687d6f25eeb8f4bc505dc9c6c0d9ea305c824e2d
<ide><path>client/client.go <ide> package client <ide> <ide> import ( <del> "../future" <del> "../rcli" <add> "github.com/dotcloud/docker/future" <add> "github.com/dotcloud/docker/rcli" <ide> "io" <ide> "io/ioutil" <ide> "log" <ide><path>container.go <ide> package docker <ide> <ide> import ( <del> "./fs" <add> "github.com/dotcloud/docker/fs" <ide> "encoding/json" <ide> "errors" <ide> "github.com/kr/pty" <ide><path>docker.go <ide> package docker <ide> <ide> import ( <del> "./fs" <add> "github.com/dotcloud/docker/fs" <ide> "container/list" <ide> "fmt" <ide> "io/ioutil" <ide><path>docker/docker.go <ide> package main <ide> <ide> import ( <del> "../client" <add> "github.com/dotcloud/docker/client" <ide> "flag" <ide> "log" <ide> "os" <ide><path>dockerd/dockerd.go <ide> package main <ide> <ide> import ( <del> ".." <del> "../server" <add> "github.com/dotcloud/docker" <add> "github.com/dotcloud/docker/server" <ide> "flag" <ide> "log" <ide> ) <ide><path>fs/layers.go <ide> package fs <ide> <ide> import ( <del> "../future" <add> "github.com/dotcloud/docker/future" <ide> "errors" <ide> "fmt" <ide> "io" <ide><path>fs/store_test.go <ide> package fs <ide> <ide> import ( <del> "../fake" <add> "github.com/dotcloud/docker/fake" <ide> "errors" <ide> "fmt" <ide> "io/ioutil" <ide><path>server/server.go <ide> package server <ide> <ide> import ( <del> ".." <del> "../fs" <del> "../future" <del> "../rcli" <add> "github.com/dotcloud/docker" <add> "github.com/dotcloud/docker/fs" <add> "github.com/dotcloud/docker/future" <add> "github.com/dotcloud/docker/rcli" <ide> "bufio" <ide> "bytes" <ide> "encoding/json"
8
Javascript
Javascript
handle more webcrypto errors with operationerror
73a51125832e3dcf50d1692814635e2daf0b3398
<ide><path>lib/internal/crypto/aes.js <ide> function asyncAesCtrCipher(mode, key, data, { counter, length }) { <ide> 'OperationError'); <ide> } <ide> <del> return jobPromise(new AESCipherJob( <add> return jobPromise(() => new AESCipherJob( <ide> kCryptoJobAsync, <ide> mode, <ide> key[kKeyObject][kHandle], <ide> function asyncAesCtrCipher(mode, key, data, { counter, length }) { <ide> function asyncAesCbcCipher(mode, key, data, { iv }) { <ide> iv = getArrayBufferOrView(iv, 'algorithm.iv'); <ide> validateByteLength(iv, 'algorithm.iv', 16); <del> return jobPromise(new AESCipherJob( <add> return jobPromise(() => new AESCipherJob( <ide> kCryptoJobAsync, <ide> mode, <ide> key[kKeyObject][kHandle], <ide> function asyncAesCbcCipher(mode, key, data, { iv }) { <ide> } <ide> <ide> function asyncAesKwCipher(mode, key, data) { <del> return jobPromise(new AESCipherJob( <add> return jobPromise(() => new AESCipherJob( <ide> kCryptoJobAsync, <ide> mode, <ide> key[kKeyObject][kHandle], <ide> function asyncAesGcmCipher( <ide> break; <ide> } <ide> <del> return jobPromise(new AESCipherJob( <add> return jobPromise(() => new AESCipherJob( <ide> kCryptoJobAsync, <ide> mode, <ide> key[kKeyObject][kHandle], <ide><path>lib/internal/crypto/cfrg.js <ide> async function cfrgGenerateKey(algorithm, extractable, keyUsages) { <ide> <ide> function cfrgExportKey(key, format) { <ide> emitExperimentalWarning(`The ${key.algorithm.name} Web Crypto API algorithm`); <del> return jobPromise(new ECKeyExportJob( <add> return jobPromise(() => new ECKeyExportJob( <ide> kCryptoJobAsync, <ide> format, <ide> key[kKeyObject][kHandle])); <ide> function eddsaSignVerify(key, data, { name, context }, signature) { <ide> } <ide> } <ide> <del> return jobPromise(new SignJob( <add> return jobPromise(() => new SignJob( <ide> kCryptoJobAsync, <ide> mode, <ide> key[kKeyObject][kHandle], <ide><path>lib/internal/crypto/diffiehellman.js <ide> async function ecdhDeriveBits(algorithm, baseKey, length) { <ide> throw lazyDOMException('Named curve mismatch', 'InvalidAccessError'); <ide> } <ide> <del> const bits = await jobPromise(new ECDHBitsJob( <add> const bits = await jobPromise(() => new ECDHBitsJob( <ide> kCryptoJobAsync, <ide> key.algorithm.name === 'ECDH' ? baseKey.algorithm.namedCurve : baseKey.algorithm.name, <ide> key[kKeyObject][kHandle], <ide><path>lib/internal/crypto/ec.js <ide> async function ecGenerateKey(algorithm, extractable, keyUsages) { <ide> } <ide> <ide> function ecExportKey(key, format) { <del> return jobPromise(new ECKeyExportJob( <add> return jobPromise(() => new ECKeyExportJob( <ide> kCryptoJobAsync, <ide> format, <ide> key[kKeyObject][kHandle])); <ide> function ecdsaSignVerify(key, data, { name, hash }, signature) { <ide> throw new ERR_MISSING_OPTION('algorithm.hash'); <ide> const hashname = normalizeHashName(hash.name); <ide> <del> return jobPromise(new SignJob( <add> return jobPromise(() => new SignJob( <ide> kCryptoJobAsync, <ide> mode, <ide> key[kKeyObject][kHandle], <ide><path>lib/internal/crypto/hash.js <ide> async function asyncDigest(algorithm, data) { <ide> case 'SHA-384': <ide> // Fall through <ide> case 'SHA-512': <del> return jobPromise(new HashJob( <add> return jobPromise(() => new HashJob( <ide> kCryptoJobAsync, <ide> normalizeHashName(algorithm.name), <ide> data, <ide><path>lib/internal/crypto/mac.js <ide> async function hmacImportKey( <ide> <ide> function hmacSignVerify(key, data, algorithm, signature) { <ide> const mode = signature === undefined ? kSignJobModeSign : kSignJobModeVerify; <del> return jobPromise(new HmacJob( <add> return jobPromise(() => new HmacJob( <ide> kCryptoJobAsync, <ide> mode, <ide> normalizeHashName(key.algorithm.hash.name), <ide><path>lib/internal/crypto/rsa.js <ide> function rsaOaepCipher(mode, key, data, { label }) { <ide> validateMaxBufferLength(label, 'algorithm.label'); <ide> } <ide> <del> return jobPromise(new RSACipherJob( <add> return jobPromise(() => new RSACipherJob( <ide> kCryptoJobAsync, <ide> mode, <ide> key[kKeyObject][kHandle], <ide> async function rsaKeyGenerate( <ide> } <ide> <ide> function rsaExportKey(key, format) { <del> return jobPromise(new RSAKeyExportJob( <add> return jobPromise(() => new RSAKeyExportJob( <ide> kCryptoJobAsync, <ide> format, <ide> key[kKeyObject][kHandle], <ide> function rsaSignVerify(key, data, { saltLength }, signature) { <ide> if (key.type !== type) <ide> throw lazyDOMException(`Key must be a ${type} key`, 'InvalidAccessError'); <ide> <del> return jobPromise(new SignJob( <add> return jobPromise(() => new SignJob( <ide> kCryptoJobAsync, <ide> signature === undefined ? kSignJobModeSign : kSignJobModeVerify, <ide> key[kKeyObject][kHandle], <ide><path>lib/internal/crypto/util.js <ide> function onDone(resolve, reject, err, result) { <ide> resolve(result); <ide> } <ide> <del>function jobPromise(job) { <add>function jobPromise(getJob) { <ide> return new Promise((resolve, reject) => { <del> job.ondone = FunctionPrototypeBind(onDone, job, resolve, reject); <del> job.run(); <add> try { <add> const job = getJob(); <add> job.ondone = FunctionPrototypeBind(onDone, job, resolve, reject); <add> job.run(); <add> } catch (err) { <add> onDone(resolve, reject, err); <add> } <ide> }); <ide> } <ide> <ide><path>test/parallel/test-webcrypto-digest.js <ide> Promise.all([1, [], {}, null, undefined].map((i) => <ide> // addition to the API, and is added as a support for future additional <ide> // hash algorithms that support variable digest output lengths. <ide> assert.rejects(subtle.digest({ name: 'SHA-512', length: 510 }, kData), { <del> message: /Digest method not supported/ <add> name: 'OperationError', <ide> }).then(common.mustCall()); <ide> <ide> const kSourceData = {
9
Text
Text
update reference document for secret and stack
7bb31f3168aa022a20c37b0b1cb1942fd553717f
<ide><path>docs/reference/commandline/index.md <ide> read the [`dockerd`](dockerd.md) reference page. <ide> | [service rm](service_rm.md) | Remove a service from the swarm | <ide> | [service scale](service_scale.md) | Set the number of replicas for the desired state of the service | <ide> | [service update](service_update.md) | Update the attributes of a service | <add> <add>### Swarm secret commands <add> <add>| Command | Description | <add>|:--------|:-------------------------------------------------------------------| <add>| [secret create](secret_create.md) | Create a secret from a file or STDIN as content | <add>| [secret inspect](service_inspect.md) | Inspect the specified secret | <add>| [secret ls](secret_ls.md) | List secrets in the swarm | <add>| [secret rm](secret_rm.md) | Remove the specified secrets from the swarm | <add> <add>### Swarm stack commands <add> <add>| Command | Description | <add>|:--------|:-------------------------------------------------------------------| <add>| [stack deploy](stack_deploy.md) | Deploy a new stack or update an existing stack | <add>| [stack ls](stack_ls.md) | List stacks in the swarm | <add>| [stack ps](stack_ps.md) | List the tasks in the stack | <add>| [stack rm](stack_rm.md) | Remove the stack from the swarm | <add>| [stack services](stack_services.md) | List the services in the stack | <ide>\ No newline at end of file <ide><path>docs/reference/commandline/stack_deploy.md <ide> axqh55ipl40h vossibility_vossibility-collector replicated 1/1 icecrime/ <ide> * [stack ps](stack_ps.md) <ide> * [stack rm](stack_rm.md) <ide> * [stack services](stack_services.md) <del>* [deploy](deploy.md) <ide><path>docs/reference/commandline/stack_ps.md <ide> The currently supported filters are: <ide> ## Related information <ide> <ide> * [stack deploy](stack_deploy.md) <del>* [stack rm](stack_ls.md) <add>* [stack ls](stack_ls.md) <ide> * [stack rm](stack_rm.md) <ide> * [stack services](stack_services.md)
3
Ruby
Ruby
reject build formula
5de162f71a288c7c4b2e02a7c1b99f720036d930
<ide><path>Library/Homebrew/installed_dependents.rb <ide> def find_some_installed_dependents(kegs, casks: []) <ide> dependent.missing_dependencies(hide: keg_names) <ide> when Cask::Cask <ide> # When checking for cask dependents, we don't care about missing dependencies <del> CaskDependent.new(dependent).runtime_dependencies(ignore_missing: true).map(&:to_formula) <add> CaskDependent.new(dependent).runtime_dependencies(ignore_missing: true).reject do |dependency| <add> dependency.tags.include?(:build) <add> end.map(&:to_formula) <ide> end <ide> <ide> required_kegs = required.map do |f|
1
PHP
PHP
fix breaking change
4415b94623358bfd1dc2e8f20e4deab0025d2d03
<ide><path>src/Illuminate/Queue/Console/RetryCommand.php <ide> protected function refreshRetryUntil($payload) <ide> { <ide> $payload = json_decode($payload, true); <ide> <add> if (! isset($payload['data']['command'])) { <add> return json_encode($payload); <add> } <add> <ide> $instance = unserialize($payload['data']['command']); <ide> <ide> if (is_object($instance) && method_exists($instance, 'retryUntil')) {
1
Javascript
Javascript
remove code that is never reached
2e59ccecde2a2d4a5a72b3372896427e28fc3265
<ide><path>lib/assert.js <ide> assert.AssertionError = function AssertionError(options) { <ide> util.inherits(assert.AssertionError, Error); <ide> <ide> function truncate(s, n) { <del> if (typeof s === 'string') { <del> return s.length < n ? s : s.slice(0, n); <del> } else { <del> return s; <del> } <add> return s.slice(0, n); <ide> } <ide> <ide> function getMessage(self) {
1
Text
Text
add the word "структур" to localetitle after "и"
a177e02988aa7e49e8f27f8366ec338a8a9bbf37
<ide><path>curriculum/challenges/russian/09-certificates/javascript-algorithms-and-data-structures-certificate/javascript-algorithms-and-data-structures-certificate.russian.md <ide> title: JavaScript Algorithms and Data Structures Certificate <ide> challengeType: 7 <ide> isPrivate: true <ide> videoUrl: '' <del>localeTitle: Сертификат алгоритмов JavaScript и данных <add>localeTitle: Сертификат алгоритмов JavaScript и структур данных <ide> --- <ide> <ide> ## Description
1
PHP
PHP
add tests for policy resolution
dee4d82e0259b270413573c7792d92d49b51fe2a
<ide><path>src/Illuminate/Auth/Access/Gate.php <ide> public function getPolicyFor($class) <ide> */ <ide> protected function guessPolicyName($class) <ide> { <del> return dirname(str_replace('\\', '/', $class)).'\\Policies\\'.class_basename($class).'Policy'; <add> return str_replace('/', '\\', dirname(str_replace('\\', '/', $class)).'\\Policies\\'.class_basename($class).'Policy'); <ide> } <ide> <ide> /** <ide><path>tests/Integration/Auth/Fixtures/Policies/AuthenticationTestUserPolicy.php <add><?php <add> <add>namespace Illuminate\Tests\Integration\Auth\Fixtures\Policies; <add> <add>class AuthenticationTestUserPolicy <add>{ <add> // <add>} <ide><path>tests/Integration/Auth/GatePolicyResolutionTest.php <add><?php <add> <add>namespace Illuminate\Tests\Integration\Auth; <add> <add>use Orchestra\Testbench\TestCase; <add>use Illuminate\Support\Facades\Gate; <add>use Illuminate\Tests\Integration\Auth\Fixtures\AuthenticationTestUser; <add>use Illuminate\Tests\Integration\Auth\Fixtures\Policies\AuthenticationTestUserPolicy; <add> <add>/** <add> * @group integration <add> */ <add>class GatePolicyResolutionTest extends TestCase <add>{ <add> public function testPolicyCanBeGuessedUsingClassConventions() <add> { <add> $this->assertInstanceOf( <add> AuthenticationTestUserPolicy::class, <add> Gate::getPolicyFor(AuthenticationTestUser::class) <add> ); <add> } <add>}
3
Javascript
Javascript
replace "hash" type with "object"
da3003c547a09132f5744c3325804e6dae7407ef
<ide><path>packages/ember-htmlbars/lib/helpers/bind-attr.js <ide> @method bind-attr <ide> @for Ember.Handlebars.helpers <ide> @deprecated <del> @param {Hash} options <add> @param {Object} options <ide> @return {String} HTML string <ide> */ <ide> <ide> @for Ember.Handlebars.helpers <ide> @deprecated <ide> @param {Function} context <del> @param {Hash} options <add> @param {Object} options <ide> @return {String} HTML string <ide> */ <ide><path>packages/ember-htmlbars/lib/helpers/with.js <ide> import shouldDisplay from "ember-views/streams/should_display"; <ide> <ide> @method with <ide> @for Ember.Handlebars.helpers <del> @param {Hash} options <add> @param {Object} options <ide> @return {String} HTML string <ide> */ <ide> <ide><path>packages/ember-metal/lib/computed.js <ide> ComputedPropertyPrototype.property = function() { <ide> via the `metaForProperty()` function. <ide> <ide> @method meta <del> @param {Hash} meta <add> @param {Object} meta <ide> @chainable <ide> */ <ide> <ide><path>packages/ember-metal/lib/core.js <ide> Ember.VERSION = 'VERSION_STRING_PLACEHOLDER'; <ide> hash must be created before loading Ember. <ide> <ide> @property ENV <del> @type Hash <add> @type Object <ide> */ <ide> <ide> if (Ember.ENV) { <ide><path>packages/ember-routing/lib/system/route.js <ide> var Route = EmberObject.extend(ActionHandler, Evented, { <ide> <ide> @property queryParams <ide> @for Ember.Route <del> @type Hash <add> @type Object <ide> */ <ide> queryParams: {}, <ide> <ide><path>packages/ember-runtime/lib/mixins/action_handler.js <ide> var ActionHandler = Mixin.create({ <ide> ``` <ide> <ide> @property actions <del> @type Hash <add> @type Object <ide> @default null <ide> */ <ide> <ide><path>packages/ember-runtime/lib/mixins/array.js <ide> export default Mixin.create(Enumerable, { <ide> <ide> @method addArrayObserver <ide> @param {Object} target The observer object. <del> @param {Hash} opts Optional hash of configuration options including <add> @param {Object} opts Optional hash of configuration options including <ide> `willChange` and `didChange` option. <ide> @return {Ember.Array} receiver <ide> */ <ide> export default Mixin.create(Enumerable, { <ide> <ide> @method removeArrayObserver <ide> @param {Object} target The object observing the array. <del> @param {Hash} opts Optional hash of configuration options including <add> @param {Object} opts Optional hash of configuration options including <ide> `willChange` and `didChange` option. <ide> @return {Ember.Array} receiver <ide> */ <ide><path>packages/ember-runtime/lib/mixins/enumerable.js <ide> export default Mixin.create({ <ide> <ide> @method addEnumerableObserver <ide> @param {Object} target <del> @param {Hash} [opts] <add> @param {Object} [opts] <ide> @return this <ide> */ <ide> addEnumerableObserver(target, opts) { <ide> export default Mixin.create({ <ide> <ide> @method removeEnumerableObserver <ide> @param {Object} target <del> @param {Hash} [opts] <add> @param {Object} [opts] <ide> @return this <ide> */ <ide> removeEnumerableObserver(target, opts) { <ide><path>packages/ember-runtime/lib/mixins/observable.js <ide> export default Mixin.create({ <ide> <ide> @method getProperties <ide> @param {String...|Array} list of keys to get <del> @return {Hash} <add> @return {Object} <ide> */ <ide> getProperties(...args) { <ide> return getProperties.apply(null, [this].concat(args)); <ide> export default Mixin.create({ <ide> ``` <ide> <ide> @method setProperties <del> @param {Hash} hash the hash of keys and values to set <add> @param {Object} hash the hash of keys and values to set <ide> @return {Ember.Observable} <ide> */ <ide> setProperties(hash) { <ide><path>packages/ember-runtime/lib/mixins/target_action_support.js <ide> var TargetActionSupport = Mixin.create({ <ide> ``` <ide> <ide> @method triggerAction <del> @param opts {Hash} (optional, with the optional keys action, target and/or actionContext) <add> @param opts {Object} (optional, with the optional keys action, target and/or actionContext) <ide> @return {Boolean} true if the action was sent successfully and did not return false <ide> */ <ide> triggerAction(opts) { <ide><path>packages/ember-runtime/lib/system/string.js <ide> function capitalize(str) { <ide> <ide> @property STRINGS <ide> @for Ember <del> @type Hash <add> @type Object <ide> */ <ide> Ember.STRINGS = {}; <ide> <ide><path>packages/ember-views/lib/mixins/view_child_views_support.js <ide> var ViewChildViewsSupport = Mixin.create({ <ide> <ide> @method createChildView <ide> @param {Class|String} viewClass <del> @param {Hash} [attrs] Attributes to add <add> @param {Object} [attrs] Attributes to add <ide> @return {Ember.View} new instance <ide> */ <ide> createChildView(maybeViewClass, _attrs) { <ide><path>packages/ember-views/lib/system/event_dispatcher.js <ide> export default EmberObject.extend({ <ide> <ide> @private <ide> @method setup <del> @param addedEvents {Hash} <add> @param addedEvents {Object} <ide> */ <ide> setup(addedEvents, rootElement) { <ide> var event; <ide><path>packages/ember-views/lib/views/collection_view.js <ide> var CollectionView = ContainerView.extend(EmptyViewSupport, { <ide> <ide> @method createChildView <ide> @param {Class} viewClass <del> @param {Hash} [attrs] Attributes to add <add> @param {Object} [attrs] Attributes to add <ide> @return {Ember.View} new instance <ide> */ <ide> createChildView(_view, attrs) { <ide> var CollectionView = ContainerView.extend(EmptyViewSupport, { <ide> a particular parent tag to default to a child tag. <ide> <ide> @property CONTAINER_MAP <del> @type Hash <add> @type Object <ide> @static <ide> @final <ide> */ <ide><path>packages/ember-views/lib/views/view.js <ide> Ember.warn("The VIEW_PRESERVES_CONTEXT flag has been removed and the functionali <ide> <ide> @property TEMPLATES <ide> @for Ember <del> @type Hash <add> @type Object <ide> */ <ide> Ember.TEMPLATES = {}; <ide> <ide> View.notifyMutationListeners = function() { <ide> <ide> @property views <ide> @static <del> @type Hash <add> @type Object <ide> */ <ide> View.views = {}; <ide>
15
Text
Text
add docs for babel 6
41fc5f21e59c899fdc41fd8bfe47925bea666a62
<ide><path>docs/docs/09-tooling-integration.md <ide> If you like using JSX, Babel provides an [in-browser ES6 and JSX transformer for <ide> <ide> ### Productionizing: Precompiled JSX <ide> <del>If you have [npm](https://www.npmjs.com/), you can run `npm install -g babel`. Babel has built-in support for React v0.12 and v0.13. Tags are automatically transformed to their equivalent `React.createElement(...)`, `displayName` is automatically inferred and added to all React.createClass calls. <add>If you have [npm](https://www.npmjs.com/), you can run `npm install -g babel`. Babel has built-in support for React v0.12+. Tags are automatically transformed to their equivalent `React.createElement(...)`, `displayName` is automatically inferred and added to all React.createClass calls. <ide> <ide> This tool will translate files that use JSX syntax to plain JavaScript files that can run directly in the browser. It will also watch directories for you and automatically transform files when they are changed; for example: `babel --watch src/ --out-dir lib/`. <ide> <add>> Note: <add>> <add>> If you are using babel 6.x, you will need to install the relevant preset/plugins. To get started, you can run `npm install -g babel babel-preset-react` and then run `babel --presets react --watch src/ --out-dir lib/`. For more information: check out the [babel 6 blog post](http://babeljs.io/blog/2015/10/29/6.0.0/) <add> <ide> By default JSX files with a `.js` extension are transformed. Run `babel --help` for more information on how to use Babel. <ide> <ide> Example output:
1
PHP
PHP
add additional useful tests for autolink()
ebc1bcb624811ad41141ebe0298b2b4f0450e71f
<ide><path>lib/Cake/Test/Case/View/Helper/TextHelperTest.php <ide> public function testAutoLinkUrlsOptions() { <ide> * @return void <ide> */ <ide> public function testAutoLinkUrlsEscape() { <add> $text = 'Text with a partial <a href="http://www.example.com">http://www.example.com</a> link'; <add> $expected = 'Text with a partial <a href="http://www.example.com">http://www.example.com</a> link'; <add> $result = $this->Text->autoLinkUrls($text, array('escape' => false)); <add> $this->assertEquals($expected, $result); <add> <add> $text = 'Text with a partial <a href="http://www.example.com">www.example.com</a> link'; <add> $expected = 'Text with a partial <a href="http://www.example.com">www.example.com</a> link'; <add> $result = $this->Text->autoLinkUrls($text, array('escape' => false)); <add> $this->assertEquals($expected, $result); <add> <ide> $text = 'Text with a partial <a href="http://www.cakephp.org">link</a> link'; <ide> $expected = 'Text with a partial <a href="http://www.cakephp.org">link</a> link'; <ide> $result = $this->Text->autoLinkUrls($text, array('escape' => false)); <ide> public function testAutoLinkUrlsEscape() { <ide> <ide> $text = 'Text with a url <a href="http://www.not-working-www.com">www.not-working-www.com</a> and more'; <ide> $expected = 'Text with a url &lt;a href=&quot;http://www.not-working-www.com&quot;&gt;www.not-working-www.com&lt;/a&gt; and more'; <del> $result = $this->Text->autoLinkUrls($text); <add> $result = $this->Text->autoLinkUrls($text, array('escape' => true)); <ide> $this->assertEquals($expected, $result); <ide> <ide> $text = 'Text with a url www.not-working-www.com and more'; <ide> $expected = 'Text with a url <a href="http://www.not-working-www.com">www.not-working-www.com</a> and more'; <del> $result = $this->Text->autoLinkUrls($text); <add> $result = $this->Text->autoLinkUrls($text, array('escape' => false)); <ide> $this->assertEquals($expected, $result); <ide> <ide> $text = 'Text with a url http://www.not-working-www.com and more'; <ide> $expected = 'Text with a url <a href="http://www.not-working-www.com">http://www.not-working-www.com</a> and more'; <del> $result = $this->Text->autoLinkUrls($text); <add> $result = $this->Text->autoLinkUrls($text, array('escape' => false)); <ide> $this->assertEquals($expected, $result); <ide> <ide> $text = 'Text with a url http://www.www.not-working-www.com and more'; <ide> $expected = 'Text with a url <a href="http://www.www.not-working-www.com">http://www.www.not-working-www.com</a> and more'; <del> $result = $this->Text->autoLinkUrls($text); <add> $result = $this->Text->autoLinkUrls($text, array('escape' => false)); <ide> $this->assertEquals($expected, $result); <ide> } <ide>
1
Python
Python
fix input_shape validation in concatenate.build
18935312a1a08f1f3bdcb50b402256bd7289b66a
<ide><path>keras/layers/merging/concatenate.py <ide> def __init__(self, axis=-1, **kwargs): <ide> @tf_utils.shape_type_conversion <ide> def build(self, input_shape): <ide> # Used purely for shape validation. <del> if not isinstance(input_shape[0], tuple) or len(input_shape) < 1: <add> if len(input_shape) < 1 or not isinstance(input_shape[0], tuple): <ide> raise ValueError( <ide> 'A `Concatenate` layer should be called on a list of ' <ide> f'at least 1 input. Received: input_shape={input_shape}')
1
Ruby
Ruby
add tests for reset_calbacks
37ca5b09662797928a4f74878595a4e577c5aedd
<ide><path>activesupport/test/callbacks_test.rb <ide> def test_proc_arity2 <ide> end <ide> end <ide> <add> class ResetCallbackTest < ActiveSupport::TestCase <add> def build_class(memo) <add> klass = Class.new { <add> include ActiveSupport::Callbacks <add> define_callbacks :foo <add> set_callback :foo, :before, :hello <add> def run; run_callbacks :foo; end <add> } <add> klass.class_eval { <add> define_method(:hello) { memo << :hi } <add> } <add> klass <add> end <add> <add> def test_reset_callbacks <add> events = [] <add> klass = build_class events <add> klass.new.run <add> assert_equal 1, events.length <add> <add> klass.reset_callbacks :foo <add> klass.new.run <add> assert_equal 1, events.length <add> end <add> <add> def test_reset_impacts_subclasses <add> events = [] <add> klass = build_class events <add> subclass = Class.new(klass) { set_callback :foo, :before, :world } <add> subclass.class_eval { define_method(:world) { events << :world } } <add> <add> subclass.new.run <add> assert_equal 2, events.length <add> <add> klass.reset_callbacks :foo <add> subclass.new.run <add> assert_equal 3, events.length <add> end <add> end <add> <ide> class CallbackTypeTest < ActiveSupport::TestCase <ide> def build_class(callback, n = 10) <ide> Class.new {
1
Javascript
Javascript
fix texture lod
a8179c989653149c4624413197fa691678eb30b9
<ide><path>src/renderers/webgl/WebGLProgram.js <ide> function WebGLProgram( renderer, extensions, code, material, shader, parameters, <ide> parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', <ide> parameters.logarithmicDepthBuffer && ( capabilities.isWebGL2 || extensions.get( 'EXT_frag_depth' ) ) ? '#define USE_LOGDEPTHBUF_EXT' : '', <ide> <del> parameters.envMap && ( capabilities.isWebGL2 || extensions.get( 'EXT_shader_texture_lod' ) ) ? '#define TEXTURE_LOD_EXT' : '', <add> ( ( material.extensions ? material.extensions.shaderTextureLOD : false ) || parameters.envMap ) && ( capabilities.isWebGL2 || extensions.get( 'EXT_shader_texture_lod' ) ) ? '#define TEXTURE_LOD_EXT' : '', <ide> <ide> 'uniform mat4 viewMatrix;', <ide> 'uniform vec3 cameraPosition;',
1
PHP
PHP
restore maintenance message on error page
bc53915ed5fa4d315ee6faa047c1762cc7d1454b
<ide><path>src/Illuminate/Foundation/Exceptions/views/503.blade.php <ide> <ide> @section('title', __('Service Unavailable')) <ide> @section('code', '503') <del>@section('message', __('Service Unavailable')) <add>@section('message', __($exception->getMessage() ?: 'Service Unavailable'))
1
Text
Text
remove redundant explanation of format
bccd7b8dacef7806b977a07caeae27328aadacd5
<ide><path>doc/api/url.md <ide> The legacy `urlObject` (`require('url').Url`) is created and returned by the <ide> The `auth` property is the username and password portion of the URL, also <ide> referred to as _userinfo_. This string subset follows the `protocol` and <ide> double slashes (if present) and precedes the `host` component, delimited by an <del>ASCII "at sign" (`@`). The format of the string is `{username}[:{password}]`, <del>with the `[:{password}]` portion being optional. <add>ASCII "at sign" (`@`). The string is either the username, or it is the username <add>and password separated by `:`. <ide> <ide> For example: `'user:pass'`. <ide>
1
PHP
PHP
remove security.level from core.php
51946ff8fd013a21514ed0e93e8d9245c38a3e31
<ide><path>app/Config/core.php <ide> 'defaults' => 'php' <ide> )); <ide> <del>/** <del> * The level of CakePHP security. <del> */ <del> Configure::write('Security.level', 'medium'); <del> <ide> /** <ide> * A random string used in security hashing methods. <ide> */ <ide><path>lib/Cake/Console/Templates/skel/Config/core.php <ide> 'defaults' => 'php' <ide> )); <ide> <del>/** <del> * The level of CakePHP security. <del> */ <del> Configure::write('Security.level', 'medium'); <del> <ide> /** <ide> * A random string used in security hashing methods. <ide> */ <ide><path>lib/Cake/Utility/Security.php <ide> class Security { <ide> /** <ide> * Get allowed minutes of inactivity based on security level. <ide> * <add> * @deprecated Exists for backwards compatibility only, not used by the core <ide> * @return integer Allowed inactivity in minutes <ide> */ <ide> public static function inactiveMins() {
3
Java
Java
add beforeconcurrenthandling support
1e62ad8665bb0f4138e140974108d693a20ee287
<ide><path>spring-web/src/main/java/org/springframework/web/context/request/async/CallableInterceptorChain.java <ide> * Assists with the invocation of {@link CallableProcessingInterceptor}'s. <ide> * <ide> * @author Rossen Stoyanchev <add> * @author Rob Winch <ide> * @since 3.2 <ide> */ <ide> class CallableInterceptorChain { <ide> public CallableInterceptorChain(List<CallableProcessingInterceptor> interceptors <ide> this.interceptors = interceptors; <ide> } <ide> <add> public void applyBeforeConcurrentHandling(NativeWebRequest request, Callable<?> task) throws Exception { <add> for (CallableProcessingInterceptor interceptor : this.interceptors) { <add> interceptor.beforeConcurrentHandling(request, task); <add> } <add> } <add> <ide> public void applyPreProcess(NativeWebRequest request, Callable<?> task) throws Exception { <ide> for (CallableProcessingInterceptor interceptor : this.interceptors) { <ide> interceptor.preProcess(request, task); <ide><path>spring-web/src/main/java/org/springframework/web/context/request/async/CallableProcessingInterceptor.java <ide> * can select a value to be used to resume processing. <ide> * <ide> * @author Rossen Stoyanchev <add> * @author Rob Winch <ide> * @since 3.2 <ide> */ <ide> public interface CallableProcessingInterceptor { <ide> public interface CallableProcessingInterceptor { <ide> <ide> static final Object RESPONSE_HANDLED = new Object(); <ide> <add> /** <add> * Invoked <em>before</em> the start of concurrent handling in the original <add> * thread in which the {@code Callable} is submitted for concurrent handling. <add> * <add> * <p> <add> * This is useful for capturing the state of the current thread just prior to <add> * invoking the {@link Callable}. Once the state is captured, it can then be <add> * transfered to the new {@link Thread} in <add> * {@link #preProcess(NativeWebRequest, Callable)}. Capturing the state of <add> * Spring Security's SecurityContextHolder and migrating it to the new Thread <add> * is a concrete example of where this is useful. <add> * </p> <add> * <add> * @param request the current request <add> * @param task the task for the current async request <add> * @throws Exception in case of errors <add> */ <add> <T> void beforeConcurrentHandling(NativeWebRequest request, Callable<T> task) throws Exception; <ide> <ide> /** <ide> * Invoked <em>after</em> the start of concurrent handling in the async <ide><path>spring-web/src/main/java/org/springframework/web/context/request/async/CallableProcessingInterceptorAdapter.java <ide> * for simplified implementation of individual methods. <ide> * <ide> * @author Rossen Stoyanchev <add> * @author Rob Winch <ide> * @since 3.2 <ide> */ <ide> public abstract class CallableProcessingInterceptorAdapter implements CallableProcessingInterceptor { <ide> <add> /** <add> * This implementation is empty. <add> */ <add> public <T> void beforeConcurrentHandling(NativeWebRequest request, Callable<T> task) throws Exception { <add> } <add> <ide> /** <ide> * This implementation is empty. <ide> */ <ide><path>spring-web/src/main/java/org/springframework/web/context/request/async/DeferredResultInterceptorChain.java <ide> public DeferredResultInterceptorChain(List<DeferredResultProcessingInterceptor> <ide> this.interceptors = interceptors; <ide> } <ide> <add> public void applyBeforeConcurrentHandling(NativeWebRequest request, DeferredResult<?> deferredResult) throws Exception { <add> for (DeferredResultProcessingInterceptor interceptor : this.interceptors) { <add> interceptor.beforeConcurrentHandling(request, deferredResult); <add> } <add> } <add> <ide> public void applyPreProcess(NativeWebRequest request, DeferredResult<?> deferredResult) throws Exception { <ide> for (DeferredResultProcessingInterceptor interceptor : this.interceptors) { <ide> interceptor.preProcess(request, deferredResult); <ide><path>spring-web/src/main/java/org/springframework/web/context/request/async/DeferredResultProcessingInterceptor.java <ide> * method can set the {@code DeferredResult} in order to resume processing. <ide> * <ide> * @author Rossen Stoyanchev <add> * @author Rob Winch <ide> * @since 3.2 <ide> */ <ide> public interface DeferredResultProcessingInterceptor { <ide> <add> /** <add> * Invoked immediately before the start of concurrent handling, in the same <add> * thread that started it. This method may be used to capture state just prior <add> * to the start of concurrent processing with the given {@code DeferredResult}. <add> * <add> * @param request the current request <add> * @param deferredResult the DeferredResult for the current request <add> * @throws Exception in case of errors <add> */ <add> <T> void beforeConcurrentHandling(NativeWebRequest request, DeferredResult<T> deferredResult) throws Exception; <add> <ide> /** <ide> * Invoked immediately after the start of concurrent handling, in the same <ide> * thread that started it. This method may be used to detect the start of <ide><path>spring-web/src/main/java/org/springframework/web/context/request/async/DeferredResultProcessingInterceptorAdapter.java <ide> * interface for simplified implementation of individual methods. <ide> * <ide> * @author Rossen Stoyanchev <add> * @author Rob Winch <ide> * @since 3.2 <ide> */ <ide> public abstract class DeferredResultProcessingInterceptorAdapter implements DeferredResultProcessingInterceptor { <ide> <add> /** <add> * This implementation is empty. <add> */ <add> public <T> void beforeConcurrentHandling(NativeWebRequest request, DeferredResult<T> deferredResult) throws Exception { <add> } <add> <ide> /** <ide> * This implementation is empty. <ide> */ <ide><path>spring-web/src/main/java/org/springframework/web/context/request/async/WebAsyncManager.java <ide> public void clearConcurrentResult() { <ide> * @param callable a unit of work to be executed asynchronously <ide> * @param processingContext additional context to save that can be accessed <ide> * via {@link #getConcurrentResultContext()} <add> * @throws Exception If concurrent processing failed to start <ide> * <ide> * @see #getConcurrentResult() <ide> * @see #getConcurrentResultContext() <ide> */ <ide> @SuppressWarnings({ "rawtypes", "unchecked" }) <del> public void startCallableProcessing(final Callable<?> callable, Object... processingContext) { <add> public void startCallableProcessing(final Callable<?> callable, Object... processingContext) throws Exception { <ide> Assert.notNull(callable, "Callable must not be null"); <ide> startCallableProcessing(new WebAsyncTask(callable), processingContext); <ide> } <ide> public void startCallableProcessing(final Callable<?> callable, Object... proces <ide> * @param webAsyncTask an WebAsyncTask containing the target {@code Callable} <ide> * @param processingContext additional context to save that can be accessed <ide> * via {@link #getConcurrentResultContext()} <add> * @throws Exception If concurrent processing failed to start <ide> */ <del> public void startCallableProcessing(final WebAsyncTask<?> webAsyncTask, Object... processingContext) { <add> public void startCallableProcessing(final WebAsyncTask<?> webAsyncTask, Object... processingContext) throws Exception { <ide> Assert.notNull(webAsyncTask, "WebAsyncTask must not be null"); <ide> Assert.state(this.asyncWebRequest != null, "AsyncWebRequest must not be null"); <ide> <ide> public void run() { <ide> } <ide> }); <ide> <add> interceptorChain.applyBeforeConcurrentHandling(asyncWebRequest, callable); <add> <ide> startAsyncProcessing(processingContext); <ide> <ide> this.taskExecutor.submit(new Runnable() { <ide> private void setConcurrentResultAndDispatch(Object result) { <ide> * @param deferredResult the DeferredResult instance to initialize <ide> * @param processingContext additional context to save that can be accessed <ide> * via {@link #getConcurrentResultContext()} <add> * @throws Exception If concurrent processing failed to start <ide> * <ide> * @see #getConcurrentResult() <ide> * @see #getConcurrentResultContext() <ide> */ <ide> public void startDeferredResultProcessing( <del> final DeferredResult<?> deferredResult, Object... processingContext) { <add> final DeferredResult<?> deferredResult, Object... processingContext) throws Exception { <ide> <ide> Assert.notNull(deferredResult, "DeferredResult must not be null"); <ide> Assert.state(this.asyncWebRequest != null, "AsyncWebRequest must not be null"); <ide> public void run() { <ide> } <ide> }); <ide> <add> interceptorChain.applyBeforeConcurrentHandling(asyncWebRequest, deferredResult); <add> <ide> startAsyncProcessing(processingContext); <ide> <ide> try { <ide><path>spring-web/src/test/java/org/springframework/web/context/request/async/WebAsyncManagerTests.java <ide> public void setUp() { <ide> } <ide> <ide> @Test <del> public void startAsyncProcessingWithoutAsyncWebRequest() { <add> public void startAsyncProcessingWithoutAsyncWebRequest() throws Exception { <ide> WebAsyncManager manager = WebAsyncUtils.getAsyncManager(new MockHttpServletRequest()); <ide> <ide> try { <ide> public void startCallableProcessing() throws Exception { <ide> Callable<Object> task = new StubCallable(concurrentResult); <ide> <ide> CallableProcessingInterceptor interceptor = createStrictMock(CallableProcessingInterceptor.class); <add> interceptor.beforeConcurrentHandling(this.asyncWebRequest, task); <ide> interceptor.preProcess(this.asyncWebRequest, task); <ide> interceptor.postProcess(this.asyncWebRequest, task, new Integer(concurrentResult)); <ide> replay(interceptor); <ide> public void startCallableProcessingCallableException() throws Exception { <ide> Callable<Object> task = new StubCallable(concurrentResult); <ide> <ide> CallableProcessingInterceptor interceptor = createStrictMock(CallableProcessingInterceptor.class); <add> interceptor.beforeConcurrentHandling(this.asyncWebRequest, task); <ide> interceptor.preProcess(this.asyncWebRequest, task); <ide> interceptor.postProcess(this.asyncWebRequest, task, concurrentResult); <ide> replay(interceptor); <ide> public void startCallableProcessingCallableException() throws Exception { <ide> verify(interceptor, this.asyncWebRequest); <ide> } <ide> <add> @Test <add> public void startCallableProcessingBeforeConcurrentHandlingException() throws Exception { <add> Callable<Object> task = new StubCallable(21); <add> Exception exception = new Exception(); <add> <add> CallableProcessingInterceptor interceptor = createStrictMock(CallableProcessingInterceptor.class); <add> interceptor.beforeConcurrentHandling(this.asyncWebRequest, task); <add> expectLastCall().andThrow(exception); <add> replay(interceptor); <add> <add> this.asyncWebRequest.addTimeoutHandler((Runnable) notNull()); <add> this.asyncWebRequest.addCompletionHandler((Runnable) notNull()); <add> replay(this.asyncWebRequest); <add> <add> this.asyncManager.registerCallableInterceptor("interceptor", interceptor); <add> <add> try { <add> this.asyncManager.startCallableProcessing(task); <add> fail("Expected Exception"); <add> }catch(Exception e) { <add> assertEquals(exception, e); <add> } <add> <add> assertFalse(this.asyncManager.hasConcurrentResult()); <add> <add> verify(this.asyncWebRequest, interceptor); <add> } <add> <ide> @Test <ide> public void startCallableProcessingPreProcessException() throws Exception { <ide> <ide> Callable<Object> task = new StubCallable(21); <ide> Exception exception = new Exception(); <ide> <ide> CallableProcessingInterceptor interceptor = createStrictMock(CallableProcessingInterceptor.class); <add> interceptor.beforeConcurrentHandling(this.asyncWebRequest, task); <ide> interceptor.preProcess(this.asyncWebRequest, task); <ide> expectLastCall().andThrow(exception); <ide> replay(interceptor); <ide> public void startCallableProcessingPostProcessException() throws Exception { <ide> Exception exception = new Exception(); <ide> <ide> CallableProcessingInterceptor interceptor = createStrictMock(CallableProcessingInterceptor.class); <add> interceptor.beforeConcurrentHandling(this.asyncWebRequest, task); <ide> interceptor.preProcess(this.asyncWebRequest, task); <ide> interceptor.postProcess(this.asyncWebRequest, task, 21); <ide> expectLastCall().andThrow(exception); <ide> public void startCallableProcessingPostProcessContinueAfterException() throws Ex <ide> Exception exception = new Exception(); <ide> <ide> CallableProcessingInterceptor interceptor1 = createMock(CallableProcessingInterceptor.class); <add> interceptor1.beforeConcurrentHandling(this.asyncWebRequest, task); <ide> interceptor1.preProcess(this.asyncWebRequest, task); <ide> interceptor1.postProcess(this.asyncWebRequest, task, 21); <ide> replay(interceptor1); <ide> <ide> CallableProcessingInterceptor interceptor2 = createMock(CallableProcessingInterceptor.class); <add> interceptor2.beforeConcurrentHandling(this.asyncWebRequest, task); <ide> interceptor2.preProcess(this.asyncWebRequest, task); <ide> interceptor2.postProcess(this.asyncWebRequest, task, 21); <ide> expectLastCall().andThrow(exception); <ide> public void startCallableProcessingPostProcessContinueAfterException() throws Ex <ide> } <ide> <ide> @Test <del> public void startCallableProcessingWithAsyncTask() { <add> public void startCallableProcessingWithAsyncTask() throws Exception { <ide> <ide> AsyncTaskExecutor executor = createMock(AsyncTaskExecutor.class); <ide> expect(executor.submit((Runnable) notNull())).andReturn(null); <ide> public void startCallableProcessingWithAsyncTask() { <ide> } <ide> <ide> @Test <del> public void startCallableProcessingNullInput() { <add> public void startCallableProcessingNullInput() throws Exception { <ide> try { <ide> this.asyncManager.startCallableProcessing((Callable<?>) null); <ide> fail("Expected exception"); <ide> public void startDeferredResultProcessing() throws Exception { <ide> String concurrentResult = "abc"; <ide> <ide> DeferredResultProcessingInterceptor interceptor = createStrictMock(DeferredResultProcessingInterceptor.class); <add> interceptor.beforeConcurrentHandling(this.asyncWebRequest, deferredResult); <ide> interceptor.preProcess(this.asyncWebRequest, deferredResult); <ide> interceptor.postProcess(asyncWebRequest, deferredResult, concurrentResult); <ide> replay(interceptor); <ide> public void startDeferredResultProcessing() throws Exception { <ide> verify(this.asyncWebRequest, interceptor); <ide> } <ide> <add> @Test <add> public void startDeferredResultProcessingBeforeConcurrentHandlingException() throws Exception { <add> <add> DeferredResult<Integer> deferredResult = new DeferredResult<Integer>(); <add> Exception exception = new Exception(); <add> <add> DeferredResultProcessingInterceptor interceptor = createStrictMock(DeferredResultProcessingInterceptor.class); <add> interceptor.beforeConcurrentHandling(this.asyncWebRequest, deferredResult); <add> expectLastCall().andThrow(exception); <add> replay(interceptor); <add> <add> this.asyncWebRequest.addTimeoutHandler((Runnable) notNull()); <add> this.asyncWebRequest.addCompletionHandler((Runnable) notNull()); <add> replay(this.asyncWebRequest); <add> <add> this.asyncManager.registerDeferredResultInterceptor("interceptor", interceptor); <add> <add> try { <add> this.asyncManager.startDeferredResultProcessing(deferredResult); <add> fail("Expected Exception"); <add> } <add> catch(Exception success) { <add> assertEquals(exception, success); <add> } <add> <add> assertFalse(this.asyncManager.hasConcurrentResult()); <add> <add> verify(this.asyncWebRequest, interceptor); <add> } <add> <ide> @Test <ide> public void startDeferredResultProcessingPreProcessException() throws Exception { <ide> <ide> DeferredResult<Integer> deferredResult = new DeferredResult<Integer>(); <ide> Exception exception = new Exception(); <ide> <ide> DeferredResultProcessingInterceptor interceptor = createStrictMock(DeferredResultProcessingInterceptor.class); <add> interceptor.beforeConcurrentHandling(this.asyncWebRequest, deferredResult); <ide> interceptor.preProcess(this.asyncWebRequest, deferredResult); <ide> expectLastCall().andThrow(exception); <ide> replay(interceptor); <ide> public void startDeferredResultProcessingPostProcessException() throws Exception <ide> Exception exception = new Exception(); <ide> <ide> DeferredResultProcessingInterceptor interceptor = createStrictMock(DeferredResultProcessingInterceptor.class); <add> interceptor.beforeConcurrentHandling(this.asyncWebRequest, deferredResult); <ide> interceptor.preProcess(this.asyncWebRequest, deferredResult); <ide> interceptor.postProcess(this.asyncWebRequest, deferredResult, 25); <ide> expectLastCall().andThrow(exception); <ide> public void startDeferredResultProcessingPostProcessException() throws Exception <ide> } <ide> <ide> @Test <del> public void startDeferredResultProcessingNullInput() { <add> public void startDeferredResultProcessingNullInput() throws Exception { <ide> try { <ide> this.asyncManager.startDeferredResultProcessing((DeferredResult<?>) null); <ide> fail("Expected exception"); <ide><path>spring-web/src/test/java/org/springframework/web/context/request/async/WebAsyncManagerTimeoutTests.java <ide> public void startCallableProcessingTimeoutAndComplete() throws Exception { <ide> StubCallable callable = new StubCallable(); <ide> <ide> CallableProcessingInterceptor interceptor = createStrictMock(CallableProcessingInterceptor.class); <add> interceptor.beforeConcurrentHandling(this.asyncWebRequest, callable); <ide> expect(interceptor.handleTimeout(this.asyncWebRequest, callable)).andReturn(RESULT_NONE); <ide> interceptor.afterCompletion(this.asyncWebRequest, callable); <ide> replay(interceptor); <ide> public void startCallableProcessingTimeoutAndResumeThroughInterceptor() throws E <ide> StubCallable callable = new StubCallable(); <ide> <ide> CallableProcessingInterceptor interceptor = createStrictMock(CallableProcessingInterceptor.class); <add> interceptor.beforeConcurrentHandling(this.asyncWebRequest, callable); <ide> expect(interceptor.handleTimeout(this.asyncWebRequest, callable)).andReturn(22); <ide> replay(interceptor); <ide> <ide> public void startCallableProcessingAfterTimeoutException() throws Exception { <ide> Exception exception = new Exception(); <ide> <ide> CallableProcessingInterceptor interceptor = createStrictMock(CallableProcessingInterceptor.class); <add> interceptor.beforeConcurrentHandling(this.asyncWebRequest, callable); <ide> expect(interceptor.handleTimeout(this.asyncWebRequest, callable)).andThrow(exception); <ide> replay(interceptor); <ide> <ide> public void startDeferredResultProcessingTimeoutAndComplete() throws Exception { <ide> DeferredResult<Integer> deferredResult = new DeferredResult<Integer>(); <ide> <ide> DeferredResultProcessingInterceptor interceptor = createStrictMock(DeferredResultProcessingInterceptor.class); <add> interceptor.beforeConcurrentHandling(this.asyncWebRequest, deferredResult); <ide> interceptor.preProcess(this.asyncWebRequest, deferredResult); <ide> expect(interceptor.handleTimeout(this.asyncWebRequest, deferredResult)).andReturn(true); <ide> interceptor.afterCompletion(this.asyncWebRequest, deferredResult);
9
PHP
PHP
add default prefix to redisengine
b86aae4d8b21f08a549bf8b001c176bddc268dfc
<ide><path>lib/Cake/Cache/Engine/RedisEngine.php <ide> public function init($settings = array()) { <ide> } <ide> parent::init(array_merge(array( <ide> 'engine' => 'Redis', <del> 'prefix' => null, <add> 'prefix' => Inflector::slug(APP_DIR) . '_', <ide> 'server' => '127.0.0.1', <ide> 'database' => 0, <ide> 'port' => 6379, <ide><path>lib/Cake/Test/Case/Cache/Engine/RedisEngineTest.php <ide> public function testSettings() { <ide> 'persistent' => true, <ide> 'password' => false, <ide> 'database' => 0, <add> 'unix_socket' => false, <ide> ); <ide> $this->assertEquals($expecting, $settings); <ide> }
2
Python
Python
clarify documentation for transpose() (gh-15024)
95e570ca1de9a59e1fe478057c5921bbd6dd5f70
<ide><path>numpy/core/fromnumeric.py <ide> def _transpose_dispatcher(a, axes=None): <ide> @array_function_dispatch(_transpose_dispatcher) <ide> def transpose(a, axes=None): <ide> """ <del> Permute the dimensions of an array. <add> Reverse or permute the axes of an array; returns the modified array. <add> <add> For an array a with two axes, transpose(a) gives the matrix transpose. <ide> <ide> Parameters <ide> ---------- <ide> a : array_like <ide> Input array. <del> axes : list of ints, optional <del> By default, reverse the dimensions, otherwise permute the axes <del> according to the values given. <add> axes : tuple or list of ints, optional <add> If specified, it must be a tuple or list which contains a permutation of <add> [0,1,..,N-1] where N is the number of axes of a. The i'th axis of the <add> returned array will correspond to the axis numbered ``axes[i]`` of the <add> input. If not specified, defaults to ``range(a.ndim)[::-1]``, which <add> reverses the order of the axes. <ide> <ide> Returns <ide> ------- <ide> def argpartition(a, kth, axis=-1, kind='introselect', order=None): <ide> partition : Describes partition algorithms used. <ide> ndarray.partition : Inplace partition. <ide> argsort : Full indirect sort. <del> take_along_axis : Apply ``index_array`` from argpartition <add> take_along_axis : Apply ``index_array`` from argpartition <ide> to an array as if by calling partition. <ide> <ide> Notes <ide> def argsort(a, axis=-1, kind=None, order=None): <ide> lexsort : Indirect stable sort with multiple keys. <ide> ndarray.sort : Inplace sort. <ide> argpartition : Indirect partial sort. <del> take_along_axis : Apply ``index_array`` from argsort <add> take_along_axis : Apply ``index_array`` from argsort <ide> to an array as if by calling sort. <ide> <ide> Notes <ide> def argmax(a, axis=None, out=None): <ide> ndarray.argmax, argmin <ide> amax : The maximum value along a given axis. <ide> unravel_index : Convert a flat index into an index tuple. <del> take_along_axis : Apply ``np.expand_dims(index_array, axis)`` <add> take_along_axis : Apply ``np.expand_dims(index_array, axis)`` <ide> from argmax to an array as if by calling max. <ide> <ide> Notes <ide> def argmin(a, axis=None, out=None): <ide> ndarray.argmin, argmax <ide> amin : The minimum value along a given axis. <ide> unravel_index : Convert a flat index into an index tuple. <del> take_along_axis : Apply ``np.expand_dims(index_array, axis)`` <add> take_along_axis : Apply ``np.expand_dims(index_array, axis)`` <ide> from argmin to an array as if by calling min. <ide> <ide> Notes
1
Java
Java
accept non-generic type match as a fallback
085176673876afc9282af0a8f4f94ee6a36e9e4e
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/config/DependencyDescriptor.java <ide> public ResolvableType getResolvableType() { <ide> ResolvableType.forMethodParameter(this.methodParameter)); <ide> } <ide> <add> /** <add> * Return whether a fallback match is allowed. <add> * <p>This is {@code false} by default but may be overridden to return {@code true} in order <add> * to suggest to a {@link org.springframework.beans.factory.support.AutowireCandidateResolver} <add> * that a fallback match is acceptable as well. <add> */ <add> public boolean fallbackMatchAllowed() { <add> return false; <add> } <add> <add> /** <add> * Return a variant of this descriptor that is intended for a fallback match. <add> * @see #fallbackMatchAllowed() <add> */ <add> public DependencyDescriptor forFallbackMatch() { <add> return new DependencyDescriptor(this) { <add> @Override <add> public boolean fallbackMatchAllowed() { <add> return true; <add> } <add> }; <add> } <add> <ide> /** <ide> * Initialize parameter name discovery for the underlying method parameter, if any. <ide> * <p>This method does not actually try to retrieve the parameter name at <ide> public Class<?> getDependencyType() { <ide> if (this.nestingLevel > 1) { <ide> Type type = this.field.getGenericType(); <ide> if (type instanceof ParameterizedType) { <del> Type arg = ((ParameterizedType) type).getActualTypeArguments()[0]; <add> Type[] args = ((ParameterizedType) type).getActualTypeArguments(); <add> Type arg = args[args.length - 1]; <ide> if (arg instanceof Class) { <ide> return (Class) arg; <ide> } <ide><path>spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java <ide> protected Map<String, Object> findAutowireCandidates( <ide> result.put(candidateName, getBean(candidateName)); <ide> } <ide> } <add> if (result.isEmpty()) { <add> DependencyDescriptor fallbackDescriptor = descriptor.forFallbackMatch(); <add> for (String candidateName : candidateNames) { <add> if (!candidateName.equals(beanName) && isAutowireCandidate(candidateName, fallbackDescriptor)) { <add> result.put(candidateName, getBean(candidateName)); <add> } <add> } <add> } <ide> return result; <ide> } <ide> <ide><path>spring-beans/src/main/java/org/springframework/beans/factory/support/GenericTypeAwareAutowireCandidateResolver.java <ide> public boolean isAutowireCandidate(BeanDefinitionHolder bdHolder, DependencyDesc <ide> // if explicitly false, do not proceed with any other checks <ide> return false; <ide> } <del> return (descriptor == null || checkGenericTypeMatch(bdHolder, descriptor.getResolvableType())); <add> return (descriptor == null || checkGenericTypeMatch(bdHolder, descriptor)); <ide> } <ide> <ide> /** <ide> * Match the given dependency type with its generic type information <ide> * against the given candidate bean definition. <ide> */ <del> protected boolean checkGenericTypeMatch(BeanDefinitionHolder bdHolder, ResolvableType dependencyType) { <del> if (dependencyType.getType() instanceof Class) { <add> protected boolean checkGenericTypeMatch(BeanDefinitionHolder bdHolder, DependencyDescriptor descriptor) { <add> ResolvableType dependencyType = descriptor.getResolvableType(); <add> if (!dependencyType.hasGenerics()) { <ide> // No generic type -> we know it's a Class type-match, so no need to check again. <ide> return true; <ide> } <del> RootBeanDefinition bd = (RootBeanDefinition) bdHolder.getBeanDefinition(); <ide> ResolvableType targetType = null; <del> if (bd.getResolvedFactoryMethod() != null) { <add> RootBeanDefinition rbd = null; <add> if (bdHolder.getBeanDefinition() instanceof RootBeanDefinition) { <add> rbd = (RootBeanDefinition) bdHolder.getBeanDefinition(); <add> } <add> if (rbd != null && rbd.getResolvedFactoryMethod() != null) { <ide> // Should typically be set for any kind of factory method, since the BeanFactory <ide> // pre-resolves them before reaching out to the AutowireCandidateResolver... <del> targetType = ResolvableType.forMethodReturnType(bd.getResolvedFactoryMethod()); <add> targetType = ResolvableType.forMethodReturnType(rbd.getResolvedFactoryMethod()); <ide> } <ide> if (targetType == null) { <ide> // Regular case: straight bean instance, with BeanFactory available. <ide> protected boolean checkGenericTypeMatch(BeanDefinitionHolder bdHolder, Resolvabl <ide> } <ide> // Fallback: no BeanFactory set, or no type resolvable through it <ide> // -> best-effort match against the target class if applicable. <del> if (targetType == null && bd.hasBeanClass() && bd.getFactoryMethodName() == null) { <del> Class<?> beanClass = bd.getBeanClass(); <add> if (targetType == null && rbd != null && rbd.hasBeanClass() && rbd.getFactoryMethodName() == null) { <add> Class<?> beanClass = rbd.getBeanClass(); <ide> if (!FactoryBean.class.isAssignableFrom(beanClass)) { <ide> targetType = ResolvableType.forClass(ClassUtils.getUserClass(beanClass)); <ide> } <ide> } <ide> } <del> return (targetType == null || dependencyType.isAssignableFrom(targetType)); <add> if (targetType == null) { <add> return true; <add> } <add> if (descriptor.fallbackMatchAllowed() && targetType.hasUnresolvableGenerics()) { <add> return descriptor.getDependencyType().isAssignableFrom(targetType.getRawClass()); <add> } <add> return dependencyType.isAssignableFrom(targetType); <ide> } <ide> <ide> <ide><path>spring-beans/src/test/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessorTests.java <ide> public void testGenericsBasedConstructorInjection() { <ide> assertSame(ir, bean.integerRepositoryMap.get("integerRepo")); <ide> } <ide> <add> @Test <add> public void testGenericsBasedConstructorInjectionWithNonTypedTarget() { <add> DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); <add> bf.setAutowireCandidateResolver(new QualifierAnnotationAutowireCandidateResolver()); <add> AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor(); <add> bpp.setBeanFactory(bf); <add> bf.addBeanPostProcessor(bpp); <add> RootBeanDefinition bd = new RootBeanDefinition(RepositoryConstructorInjectionBean.class); <add> bd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE); <add> bf.registerBeanDefinition("annotatedBean", bd); <add> GenericRepository gr = new GenericRepository(); <add> bf.registerSingleton("genericRepo", gr); <add> <add> RepositoryConstructorInjectionBean bean = (RepositoryConstructorInjectionBean) bf.getBean("annotatedBean"); <add> assertSame(gr, bean.stringRepository); <add> assertSame(gr, bean.integerRepository); <add> assertSame(1, bean.stringRepositoryArray.length); <add> assertSame(1, bean.integerRepositoryArray.length); <add> assertSame(gr, bean.stringRepositoryArray[0]); <add> assertSame(gr, bean.integerRepositoryArray[0]); <add> assertSame(1, bean.stringRepositoryList.size()); <add> assertSame(1, bean.integerRepositoryList.size()); <add> assertSame(gr, bean.stringRepositoryList.get(0)); <add> assertSame(gr, bean.integerRepositoryList.get(0)); <add> assertSame(1, bean.stringRepositoryMap.size()); <add> assertSame(1, bean.integerRepositoryMap.size()); <add> assertSame(gr, bean.stringRepositoryMap.get("genericRepo")); <add> assertSame(gr, bean.integerRepositoryMap.get("genericRepo")); <add> } <add> <add> @Test <add> public void testGenericsBasedConstructorInjectionWithNonGenericTarget() { <add> DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); <add> bf.setAutowireCandidateResolver(new QualifierAnnotationAutowireCandidateResolver()); <add> AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor(); <add> bpp.setBeanFactory(bf); <add> bf.addBeanPostProcessor(bpp); <add> RootBeanDefinition bd = new RootBeanDefinition(RepositoryConstructorInjectionBean.class); <add> bd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE); <add> bf.registerBeanDefinition("annotatedBean", bd); <add> SimpleRepository ngr = new SimpleRepository(); <add> bf.registerSingleton("simpleRepo", ngr); <add> <add> RepositoryConstructorInjectionBean bean = (RepositoryConstructorInjectionBean) bf.getBean("annotatedBean"); <add> assertSame(ngr, bean.stringRepository); <add> assertSame(ngr, bean.integerRepository); <add> assertSame(1, bean.stringRepositoryArray.length); <add> assertSame(1, bean.integerRepositoryArray.length); <add> assertSame(ngr, bean.stringRepositoryArray[0]); <add> assertSame(ngr, bean.integerRepositoryArray[0]); <add> assertSame(1, bean.stringRepositoryList.size()); <add> assertSame(1, bean.integerRepositoryList.size()); <add> assertSame(ngr, bean.stringRepositoryList.get(0)); <add> assertSame(ngr, bean.integerRepositoryList.get(0)); <add> assertSame(1, bean.stringRepositoryMap.size()); <add> assertSame(1, bean.integerRepositoryMap.size()); <add> assertSame(ngr, bean.stringRepositoryMap.get("simpleRepo")); <add> assertSame(ngr, bean.integerRepositoryMap.get("simpleRepo")); <add> } <add> <add> @Test <add> public void testGenericsBasedConstructorInjectionWithMixedTargets() { <add> DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); <add> bf.setAutowireCandidateResolver(new QualifierAnnotationAutowireCandidateResolver()); <add> AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor(); <add> bpp.setBeanFactory(bf); <add> bf.addBeanPostProcessor(bpp); <add> RootBeanDefinition bd = new RootBeanDefinition(RepositoryConstructorInjectionBean.class); <add> bd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE); <add> bf.registerBeanDefinition("annotatedBean", bd); <add> StringRepository sr = new StringRepository(); <add> bf.registerSingleton("stringRepo", sr); <add> GenericRepository gr = new GenericRepositorySubclass(); <add> bf.registerSingleton("genericRepo", gr); <add> <add> RepositoryConstructorInjectionBean bean = (RepositoryConstructorInjectionBean) bf.getBean("annotatedBean"); <add> assertSame(sr, bean.stringRepository); <add> assertSame(gr, bean.integerRepository); <add> assertSame(1, bean.stringRepositoryArray.length); <add> assertSame(1, bean.integerRepositoryArray.length); <add> assertSame(sr, bean.stringRepositoryArray[0]); <add> assertSame(gr, bean.integerRepositoryArray[0]); <add> assertSame(1, bean.stringRepositoryList.size()); <add> assertSame(1, bean.integerRepositoryList.size()); <add> assertSame(sr, bean.stringRepositoryList.get(0)); <add> assertSame(gr, bean.integerRepositoryList.get(0)); <add> assertSame(1, bean.stringRepositoryMap.size()); <add> assertSame(1, bean.integerRepositoryMap.size()); <add> assertSame(sr, bean.stringRepositoryMap.get("stringRepo")); <add> assertSame(gr, bean.integerRepositoryMap.get("genericRepo")); <add> } <add> <add> @Test <add> public void testGenericsBasedConstructorInjectionWithMixedTargetsIncludingNonGeneric() { <add> DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); <add> bf.setAutowireCandidateResolver(new QualifierAnnotationAutowireCandidateResolver()); <add> AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor(); <add> bpp.setBeanFactory(bf); <add> bf.addBeanPostProcessor(bpp); <add> RootBeanDefinition bd = new RootBeanDefinition(RepositoryConstructorInjectionBean.class); <add> bd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE); <add> bf.registerBeanDefinition("annotatedBean", bd); <add> StringRepository sr = new StringRepository(); <add> bf.registerSingleton("stringRepo", sr); <add> SimpleRepository ngr = new SimpleRepositorySubclass(); <add> bf.registerSingleton("simpleRepo", ngr); <add> <add> RepositoryConstructorInjectionBean bean = (RepositoryConstructorInjectionBean) bf.getBean("annotatedBean"); <add> assertSame(sr, bean.stringRepository); <add> assertSame(ngr, bean.integerRepository); <add> assertSame(1, bean.stringRepositoryArray.length); <add> assertSame(1, bean.integerRepositoryArray.length); <add> assertSame(sr, bean.stringRepositoryArray[0]); <add> assertSame(ngr, bean.integerRepositoryArray[0]); <add> assertSame(1, bean.stringRepositoryList.size()); <add> assertSame(1, bean.integerRepositoryList.size()); <add> assertSame(sr, bean.stringRepositoryList.get(0)); <add> assertSame(ngr, bean.integerRepositoryList.get(0)); <add> assertSame(1, bean.stringRepositoryMap.size()); <add> assertSame(1, bean.integerRepositoryMap.size()); <add> assertSame(sr, bean.stringRepositoryMap.get("stringRepo")); <add> assertSame(ngr, bean.integerRepositoryMap.get("simpleRepo")); <add> } <add> <ide> <ide> public static class ResourceInjectionBean { <ide> <ide> public static class StringRepository implements Repository<String> { <ide> public static class IntegerRepository implements Repository<Integer> { <ide> } <ide> <add> public static class GenericRepository<T> implements Repository<T> { <add> } <add> <add> public static class GenericRepositorySubclass extends GenericRepository { <add> } <add> <add> public static class SimpleRepository implements Repository { <add> } <add> <add> public static class SimpleRepositorySubclass extends SimpleRepository { <add> } <add> <ide> <ide> public static class RepositoryFieldInjectionBean { <ide> <ide><path>spring-core/src/main/java/org/springframework/core/GenericTypeResolver.java <ide> public static Class[] resolveTypeArguments(Class<?> clazz, Class<?> genericIfc) <ide> /** <ide> * Resolve the specified generic type against the given TypeVariable map. <ide> * @param genericType the generic type to resolve <del> * @param typeVariableMap the TypeVariable Map to resolved against <add> * @param map the TypeVariable Map to resolved against <ide> * @return the type if it resolves to a Class, or {@code Object.class} otherwise <ide> * @deprecated as of Spring 4.0 in favor of {@link ResolvableType} <ide> */ <ide> @Deprecated <del> public static Class<?> resolveType(Type genericType, final Map<TypeVariable, Type> typeVariableMap) { <del> <del> ResolvableType.VariableResolver variableResolver = new ResolvableType.VariableResolver() { <del> @Override <del> public ResolvableType resolveVariable(TypeVariable<?> variable) { <del> Type type = typeVariableMap.get(variable); <del> return (type == null ? null : ResolvableType.forType(type)); <del> } <del> <del> @Override <del> public Object getSource() { <del> return typeVariableMap; <del> } <del> }; <del> <del> return ResolvableType.forType(genericType, variableResolver).resolve(Object.class); <add> public static Class<?> resolveType(Type genericType, Map<TypeVariable, Type> map) { <add> return ResolvableType.forType(genericType, new TypeVariableMapVariableResolver(map)).resolve(Object.class); <ide> } <ide> <ide> /** <ide> private static void buildTypeVariableMap(ResolvableType type, Map<TypeVariable, <ide> } <ide> } <ide> <add> <add> @SuppressWarnings("serial") <add> private static class TypeVariableMapVariableResolver implements ResolvableType.VariableResolver { <add> <add> private final Map<TypeVariable, Type> typeVariableMap; <add> <add> public TypeVariableMapVariableResolver(Map<TypeVariable, Type> typeVariableMap) { <add> this.typeVariableMap = typeVariableMap; <add> } <add> <add> @Override <add> public ResolvableType resolveVariable(TypeVariable<?> variable) { <add> Type type = this.typeVariableMap.get(variable); <add> return (type != null ? ResolvableType.forType(type) : null); <add> } <add> <add> @Override <add> public Object getSource() { <add> return this.typeVariableMap; <add> } <add> } <add> <ide> } <ide><path>spring-core/src/main/java/org/springframework/core/MethodParameter.java <ide> public Class<?> getNestedParameterType() { <ide> Type type = getGenericParameterType(); <ide> if (type instanceof ParameterizedType) { <ide> Integer index = getTypeIndexForCurrentLevel(); <del> Type arg = ((ParameterizedType) type).getActualTypeArguments()[index != null ? index : 0]; <add> Type[] args = ((ParameterizedType) type).getActualTypeArguments(); <add> Type arg = args[index != null ? index : args.length - 1]; <ide> if (arg instanceof Class) { <ide> return (Class) arg; <ide> } <ide><path>spring-core/src/main/java/org/springframework/core/ResolvableType.java <ide> public final class ResolvableType implements Serializable { <ide> private boolean isResolved = false; <ide> <ide> /** <del> * Late binding stored copy of the resolved value (valid when {@link #isResolved} is <del> * true). <add> * Late binding stored copy of the resolved value (valid when {@link #isResolved} is true). <ide> */ <ide> private Class<?> resolved; <ide> <ide> public final class ResolvableType implements Serializable { <ide> private final ResolvableType componentType; <ide> <ide> <del> <ide> /** <ide> * Private constructor used to create a new {@link ResolvableType}. <ide> * @param type the underlying java type (may only be {@code null} for {@link #NONE}) <ide> private ResolvableType(Type type, VariableResolver variableResolver, ResolvableT <ide> <ide> <ide> /** <del> * Return the underling java {@link Type} being managed. With the exception of <add> * Return the underling Java {@link Type} being managed. With the exception of <ide> * the {@link #NONE} constant, this method will never return {@code null}. <ide> */ <ide> public Type getType() { <ide> return this.type; <ide> } <ide> <add> /** <add> * Return the underlying Java {@link Class} being managed, if available; <add> * otherwise {@code null}. <add> */ <add> public Class<?> getRawClass() { <add> Type rawType = this.type; <add> if (rawType instanceof ParameterizedType) { <add> rawType = ((ParameterizedType) rawType).getRawType(); <add> } <add> return (rawType instanceof Class ? (Class) rawType : null); <add> } <add> <ide> /** <ide> * Determines if this {@code ResolvableType} is assignable from the specified <ide> * {@code type}. Attempts to follow the same rules as the Java compiler, considering <ide> private boolean isAssignableFrom(ResolvableType type, boolean checkingGeneric) { <ide> <ide> // Deal with array by delegating to the component type <ide> if (isArray()) { <del> return (type.isArray() && getComponentType().isAssignableFrom( <del> type.getComponentType())); <add> return (type.isArray() && getComponentType().isAssignableFrom(type.getComponentType())); <ide> } <ide> <ide> // Deal with wildcard bounds <ide> private boolean isAssignableFrom(ResolvableType type, boolean checkingGeneric) { <ide> <ide> // in the from X is assignable to <? extends Number> <ide> if (typeBounds != null) { <del> return (ourBounds != null && ourBounds.isSameKind(typeBounds) <del> && ourBounds.isAssignableFrom(typeBounds.getBounds())); <add> return (ourBounds != null && ourBounds.isSameKind(typeBounds) && <add> ourBounds.isAssignableFrom(typeBounds.getBounds())); <ide> } <ide> <ide> // in the form <? extends Number> is assignable to X ... <ide> private boolean isAssignableFrom(ResolvableType type, boolean checkingGeneric) { <ide> <ide> // Recursively check each generic <ide> for (int i = 0; i < getGenerics().length; i++) { <del> rtn &= getGeneric(i).isAssignableFrom( <del> type.as(resolve(Object.class)).getGeneric(i), true); <add> rtn &= getGeneric(i).isAssignableFrom(type.as(resolve(Object.class)).getGeneric(i), true); <ide> } <ide> <ide> return rtn; <ide> public ResolvableType getComponentType() { <ide> return forType(componentType, this.variableResolver); <ide> } <ide> if (this.type instanceof GenericArrayType) { <del> return forType(((GenericArrayType) this.type).getGenericComponentType(), <del> this.variableResolver); <add> return forType(((GenericArrayType) this.type).getGenericComponentType(), this.variableResolver); <ide> } <ide> return resolveType().getComponentType(); <ide> } <ide> public ResolvableType as(Class<?> type) { <ide> * @see #getInterfaces() <ide> */ <ide> public ResolvableType getSuperType() { <del> final Class<?> resolved = resolve(); <add> Class<?> resolved = resolve(); <ide> if (resolved == null || resolved.getGenericSuperclass() == null) { <ide> return NONE; <ide> } <ide> public ResolvableType getSuperType() { <ide> * @see #getSuperType() <ide> */ <ide> public ResolvableType[] getInterfaces() { <del> final Class<?> resolved = resolve(); <add> Class<?> resolved = resolve(); <ide> if (resolved == null || ObjectUtils.isEmpty(resolved.getGenericInterfaces())) { <ide> return EMPTY_TYPES_ARRAY; <ide> } <ide> public boolean hasGenerics() { <ide> return (getGenerics().length > 0); <ide> } <ide> <add> /** <add> * Determine whether the underlying type has unresolvable generics: <add> * either through an unresolvable type variable on the type itself <add> * or through implementing a generic interface in a raw fashion, <add> * i.e. without substituting that interface's type variables. <add> * The result will be {@code true} only in those two scenarios. <add> */ <add> public boolean hasUnresolvableGenerics() { <add> ResolvableType[] generics = getGenerics(); <add> for (ResolvableType generic : generics) { <add> if (generic.resolve() == null) { <add> return true; <add> } <add> } <add> Class<?> resolved = resolve(); <add> Type[] ifcs = resolved.getGenericInterfaces(); <add> for (Type ifc : ifcs) { <add> if (ifc instanceof Class) { <add> if (forClass((Class) ifc).hasGenerics()) { <add> return true; <add> } <add> } <add> } <add> if (resolved.getGenericSuperclass() != null) { <add> return getSuperType().hasUnresolvableGenerics(); <add> } <add> return false; <add> } <add> <ide> /** <ide> * Return a {@link ResolvableType} for the specified nesting level. See <ide> * {@link #getNested(int, Map)} for details. <ide> public ResolvableType getNested(int nestingLevel, Map<Integer, Integer> typeInde <ide> while (result != ResolvableType.NONE && !result.hasGenerics()) { <ide> result = result.getSuperType(); <ide> } <del> Integer index = (typeIndexesPerLevel == null ? null <del> : typeIndexesPerLevel.get(i)); <add> Integer index = (typeIndexesPerLevel != null ? typeIndexesPerLevel.get(i) : null); <ide> index = (index == null ? result.getGenerics().length - 1 : index); <ide> result = result.getGeneric(index); <ide> } <ide> private Class<?> resolveClass() { <ide> * it cannot be serialized. <ide> */ <ide> ResolvableType resolveType() { <del> <ide> if (this.type instanceof ParameterizedType) { <del> return forType(((ParameterizedType) this.type).getRawType(), <del> this.variableResolver); <add> return forType(((ParameterizedType) this.type).getRawType(), this.variableResolver); <ide> } <ide> <ide> if (this.type instanceof WildcardType) { <ide> ResolvableType resolveType() { <ide> // Try default variable resolution <ide> if (this.variableResolver != null) { <ide> ResolvableType resolved = this.variableResolver.resolveVariable(variable); <del> if(resolved != null) { <add> if (resolved != null) { <ide> return resolved; <ide> } <ide> } <ide> private Type resolveBounds(Type[] bounds) { <ide> } <ide> <ide> private ResolvableType resolveVariable(TypeVariable<?> variable) { <del> <ide> if (this.type instanceof TypeVariable) { <ide> return resolveType().resolveVariable(variable); <ide> } <ide> private ResolvableType resolveVariable(TypeVariable<?> variable) { <ide> } <ide> <ide> if (parameterizedType.getOwnerType() != null) { <del> return forType(parameterizedType.getOwnerType(), <del> this.variableResolver).resolveVariable(variable); <add> return forType(parameterizedType.getOwnerType(), this.variableResolver).resolveVariable(variable); <ide> } <ide> } <ide> <ide> public int hashCode() { <ide> } <ide> <ide> /** <del> * Custom serialization support for {@value #NONE}. <add> * Custom serialization support for {@link #NONE}. <ide> */ <ide> private Object readResolve() throws ObjectStreamException { <ide> return (this.type == null ? NONE : this); <ide> VariableResolver asVariableResolver() { <ide> if (this == NONE) { <ide> return null; <ide> } <del> <del> return new VariableResolver() { <del> <del> private static final long serialVersionUID = 1L; <del> <del> <del> @Override <del> public ResolvableType resolveVariable(TypeVariable<?> variable) { <del> return ResolvableType.this.resolveVariable(variable); <del> } <del> <del> @Override <del> public Object getSource() { <del> return ResolvableType.this; <del> } <del> }; <add> return new DefaultVariableResolver(); <ide> } <ide> <ide> private static boolean variableResolverSourceEquals(VariableResolver o1, VariableResolver o2) { <ide> public static ResolvableType forMethodParameter(Method method, int parameterInde <ide> * @see #forMethodParameter(Method, int, Class) <ide> * @see #forMethodParameter(MethodParameter) <ide> */ <del> public static ResolvableType forMethodParameter(Method method, int parameterIndex, <del> Class<?> implementationClass) { <add> public static ResolvableType forMethodParameter(Method method, int parameterIndex, Class<?> implementationClass) { <ide> Assert.notNull(method, "Method must not be null"); <ide> MethodParameter methodParameter = new MethodParameter(method, parameterIndex); <ide> methodParameter.setContainingClass(implementationClass); <ide> public static ResolvableType forMethodParameter(Method method, int parameterInde <ide> */ <ide> public static ResolvableType forMethodParameter(MethodParameter methodParameter) { <ide> Assert.notNull(methodParameter, "MethodParameter must not be null"); <del> ResolvableType owner = forType(methodParameter.getContainingClass()).as( <del> methodParameter.getDeclaringClass()); <add> ResolvableType owner = forType(methodParameter.getContainingClass()).as(methodParameter.getDeclaringClass()); <ide> return forType(SerializableTypeWrapper.forMethodParameter(methodParameter), <ide> owner.asVariableResolver()).getNested(methodParameter.getNestingLevel(), <ide> methodParameter.typeIndexesPerLevel); <ide> public static ResolvableType forArrayComponent(final ResolvableType componentTyp <ide> } <ide> <ide> /** <del> * Return a {@link ResolvableType} for the specified {@link Class} with pre-declared <del> * generics. <add> * Return a {@link ResolvableType} for the specified {@link Class} with pre-declared generics. <ide> * @param sourceClass the source class <ide> * @param generics the generics of the class <ide> * @return a {@link ResolvableType} for the specific class and generics <ide> * @see #forClassWithGenerics(Class, ResolvableType...) <ide> */ <del> public static ResolvableType forClassWithGenerics(Class<?> sourceClass, <del> Class<?>... generics) { <add> public static ResolvableType forClassWithGenerics(Class<?> sourceClass, Class<?>... generics) { <ide> Assert.notNull(sourceClass, "Source class must not be null"); <ide> Assert.notNull(generics, "Generics must not be null"); <ide> ResolvableType[] resolvableGenerics = new ResolvableType[generics.length]; <ide> public static ResolvableType forClassWithGenerics(Class<?> sourceClass, <ide> } <ide> <ide> /** <del> * Return a {@link ResolvableType} for the specified {@link Class} with pre-declared <del> * generics. <add> * Return a {@link ResolvableType} for the specified {@link Class} with pre-declared generics. <ide> * @param sourceClass the source class <ide> * @param generics the generics of the class <ide> * @return a {@link ResolvableType} for the specific class and generics <ide> * @see #forClassWithGenerics(Class, Class...) <ide> */ <del> public static ResolvableType forClassWithGenerics(Class<?> sourceClass, <del> final ResolvableType... generics) { <add> public static ResolvableType forClassWithGenerics(Class<?> sourceClass, ResolvableType... generics) { <ide> Assert.notNull(sourceClass, "Source class must not be null"); <ide> Assert.notNull(generics, "Generics must not be null"); <del> final TypeVariable<?>[] typeVariables = sourceClass.getTypeParameters(); <del> Assert.isTrue(typeVariables.length == generics.length, <del> "Missmatched number of generics specified"); <del> <del> <del> VariableResolver variableResolver = new VariableResolver() { <del> <del> private static final long serialVersionUID = 1L; <del> <del> <del> @Override <del> public ResolvableType resolveVariable(TypeVariable<?> variable) { <del> for (int i = 0; i < typeVariables.length; i++) { <del> if(typeVariables[i].equals(variable)) { <del> return generics[i]; <del> } <del> } <del> return null; <del> } <del> <del> @Override <del> public Object getSource() { <del> return generics; <del> } <del> }; <del> <del> return forType(sourceClass, variableResolver); <add> TypeVariable<?>[] typeVariables = sourceClass.getTypeParameters(); <add> return forType(sourceClass, new TypeVariablesVariableResolver(typeVariables, generics)); <ide> } <ide> <ide> /** <ide> public static ResolvableType forType(Type type) { <ide> } <ide> <ide> /** <del> * Return a {@link ResolvableType} for the specified {@link Type} backed by the <del> * given owner type. NOTE: The resulting {@link ResolvableType} may not be <del> * {@link Serializable}. <add> * Return a {@link ResolvableType} for the specified {@link Type} backed by the given <add> * owner type. NOTE: The resulting {@link ResolvableType} may not be {@link Serializable}. <ide> * @param type the source type or {@code null} <ide> * @param owner the owner type used to resolve variables <ide> * @return a {@link ResolvableType} for the specified {@link Type} and owner <ide> public static ResolvableType forType(Type type, ResolvableType owner) { <ide> * @return a {@link ResolvableType} for the specified {@link Type} and {@link VariableResolver} <ide> */ <ide> static ResolvableType forType(Type type, VariableResolver variableResolver) { <del> if(type == null) { <add> if (type == null) { <ide> return NONE; <ide> } <ide> // Check the cache, we may have a ResolvableType that may have already been resolved <ide> static interface VariableResolver extends Serializable { <ide> * @return the resolved variable or {@code null} <ide> */ <ide> ResolvableType resolveVariable(TypeVariable<?> variable); <add> } <add> <add> <add> @SuppressWarnings("serial") <add> private class DefaultVariableResolver implements VariableResolver { <add> <add> @Override <add> public ResolvableType resolveVariable(TypeVariable<?> variable) { <add> return ResolvableType.this.resolveVariable(variable); <add> } <add> <add> @Override <add> public Object getSource() { <add> return ResolvableType.this; <add> } <add> } <add> <add> <add> @SuppressWarnings("serial") <add> private static class TypeVariablesVariableResolver implements VariableResolver { <add> <add> private final TypeVariable[] typeVariables; <add> <add> private final ResolvableType[] generics; <add> <add> public TypeVariablesVariableResolver(TypeVariable[] typeVariables, ResolvableType[] generics) { <add> Assert.isTrue(typeVariables.length == generics.length, "Mismatched number of generics specified"); <add> this.typeVariables = typeVariables; <add> this.generics = generics; <add> } <ide> <add> @Override <add> public ResolvableType resolveVariable(TypeVariable<?> variable) { <add> for (int i = 0; i < this.typeVariables.length; i++) { <add> if (this.typeVariables[i].equals(variable)) { <add> return this.generics[i]; <add> } <add> } <add> return null; <add> } <add> <add> @Override <add> public Object getSource() { <add> return this.generics; <add> } <ide> } <ide> <ide> <ide> private static class WildcardBounds { <ide> private final ResolvableType[] bounds; <ide> <ide> /** <del> * Private constructor to create a new {@link WildcardBounds} instance. <add> * Internal constructor to create a new {@link WildcardBounds} instance. <ide> * @param kind the kind of bounds <ide> * @param bounds the bounds <ide> * @see #get(ResolvableType) <ide> */ <del> private WildcardBounds(Kind kind, ResolvableType[] bounds) { <add> public WildcardBounds(Kind kind, ResolvableType[] bounds) { <ide> this.kind = kind; <ide> this.bounds = bounds; <ide> } <ide> public static WildcardBounds get(ResolvableType type) { <ide> Type[] bounds = boundsType == Kind.UPPER ? wildcardType.getUpperBounds() : wildcardType.getLowerBounds(); <ide> ResolvableType[] resolvableBounds = new ResolvableType[bounds.length]; <ide> for (int i = 0; i < bounds.length; i++) { <del> resolvableBounds[i] = ResolvableType.forType(bounds[i], <del> type.variableResolver); <add> resolvableBounds[i] = ResolvableType.forType(bounds[i], type.variableResolver); <ide> } <ide> return new WildcardBounds(boundsType, resolvableBounds); <ide> } <ide> public static WildcardBounds get(ResolvableType type) { <ide> * The various kinds of bounds. <ide> */ <ide> static enum Kind {UPPER, LOWER} <del> <ide> } <ide> <ide> } <ide><path>spring-core/src/test/java/org/springframework/core/ResolvableTypeTests.java <ide> import org.mockito.ArgumentCaptor; <ide> import org.mockito.Captor; <ide> import org.mockito.runners.MockitoJUnitRunner; <add> <ide> import org.springframework.core.ResolvableType.VariableResolver; <ide> import org.springframework.util.MultiValueMap; <ide> <del>import static org.mockito.BDDMockito.*; <del>import static org.mockito.Mockito.*; <ide> import static org.hamcrest.Matchers.*; <ide> import static org.junit.Assert.*; <add>import static org.mockito.BDDMockito.*; <ide> <ide> /** <del> * Tests for {@link ResolvableType}. <del> * <ide> * @author Phillip Webb <ide> */ <ide> @SuppressWarnings("rawtypes") <ide> @RunWith(MockitoJUnitRunner.class) <ide> public class ResolvableTypeTests { <ide> <del> <ide> @Rule <ide> public ExpectedException thrown = ExpectedException.none(); <ide> <ide> public void classWithGenericsAs() throws Exception { <ide> @Test <ide> public void forClassWithMismatchedGenerics() throws Exception { <ide> thrown.expect(IllegalArgumentException.class); <del> thrown.expectMessage("Missmatched number of generics specified"); <add> thrown.expectMessage("Mismatched number of generics specified"); <ide> ResolvableType.forClassWithGenerics(Map.class, Integer.class); <ide> } <ide>
8
PHP
PHP
allow int as type for value in pluck
1a81bc74ecac5c1f587b8af85fdd49a135e47a9d
<ide><path>src/Illuminate/Collections/Collection.php <ide> public function last(callable $callback = null, $default = null) <ide> /** <ide> * Get the values of a given key. <ide> * <del> * @param string|array<array-key, string> $value <add> * @param string|int|array<array-key, string> $value <ide> * @param string|null $key <ide> * @return static<int, mixed> <ide> */
1
Ruby
Ruby
add support for templates for rails plugin new
bcd414fd10a0e401cfb1de95cc9b2940b1df0ff6
<ide><path>railties/lib/rails/generators/app_base.rb <ide> def create_root <ide> valid_const? <ide> <ide> empty_directory '.' <add> set_default_accessors! <ide> FileUtils.cd(destination_root) unless options[:pretend] <ide> end <add> <add> def apply_rails_template <add> apply rails_template if rails_template <add> rescue Thor::Error, LoadError, Errno::ENOENT => e <add> raise Error, "The template [#{rails_template}] could not be loaded. Error: #{e}" <add> end <add> <add> def set_default_accessors! <add> self.rails_template = case options[:template] <add> when /^http:\/\// <add> options[:template] <add> when String <add> File.expand_path(options[:template], Dir.pwd) <add> else <add> options[:template] <add> end <add> end <ide> end <ide> end <ide> end <ide><path>railties/lib/rails/generators/rails/app/app_generator.rb <ide> def initialize(*args) <ide> end <ide> <ide> def create_root <del> set_default_accessors! <ide> super <ide> end <ide> <ide> def finish_template <ide> end <ide> <ide> def apply_rails_template <del> apply rails_template if rails_template <del> rescue Thor::Error, LoadError, Errno::ENOENT => e <del> raise Error, "The template [#{rails_template}] could not be loaded. Error: #{e}" <add> super <ide> end <ide> <ide> def bundle_if_dev_or_edge <ide> def build(meth, *args) <ide> builder.send(meth, *args) if builder.respond_to?(meth) <ide> end <ide> <del> def set_default_accessors! <del> self.rails_template = case options[:template] <del> when /^http:\/\// <del> options[:template] <del> when String <del> File.expand_path(options[:template], Dir.pwd) <del> else <del> options[:template] <del> end <del> end <del> <ide> # Define file as an alias to create_file for backwards compatibility. <ide> def file(*args, &block) <ide> create_file(*args, &block) <ide><path>railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb <ide> class PluginNewGenerator < AppBase <ide> class_option :builder, :type => :string, :aliases => "-b", <ide> :desc => "Path to a plugin builder (can be a filesystem path or URL)" <ide> <add> class_option :template, :type => :string, :aliases => "-m", <add> :desc => "Path to an application template (can be a filesystem path or URL)" <add> <ide> class_option :skip_gemfile, :type => :boolean, :default => false, <ide> :desc => "Don't create a Gemfile" <ide> <ide> def remove_uneeded_rails_files <ide> build(:test_dummy_clean) <ide> end <ide> <add> def finish_template <add> build(:leftovers) <add> end <add> <add> def apply_rails_template <add> super <add> end <add> <ide> protected <ide> <ide> def self.banner <ide><path>railties/test/generators/plugin_new_generator_test.rb <ide> def test_ensure_that_plugin_options_are_not_passed_app_generator <ide> assert_match /STEP 2.*create Gemfile/m, output <ide> end <ide> <add> def test_template_from_dir_pwd <add> FileUtils.cd(Rails.root) <add> assert_match /It works from file!/, run_generator([destination_root, "-m", "lib/template.rb"]) <add> end <add> <add> def test_template_raises_an_error_with_invalid_path <add> content = capture(:stderr){ run_generator([destination_root, "-m", "non/existant/path"]) } <add> assert_match /The template \[.*\] could not be loaded/, content <add> assert_match /non\/existant\/path/, content <add> end <add> <add> def test_template_is_executed_when_supplied <add> path = "http://gist.github.com/103208.txt" <add> template = %{ say "It works!" } <add> template.instance_eval "def read; self; end" # Make the string respond to read <add> <add> generator([destination_root], :template => path).expects(:open).with(path, 'Accept' => 'application/x-thor-template').returns(template) <add> assert_match /It works!/, silence(:stdout){ generator.invoke_all } <add> end <add> <ide> protected <ide> <ide> def action(*args, &block)
4
Javascript
Javascript
use a proper tty test
a52f59b437d669138e27a9d04880c71b5c79a9cf
<ide><path>lib/readline.js <ide> function Interface (output, completer) { <ide> <ide> this.setPrompt("> "); <ide> <del> this.enabled = output.fd < 3; // Looks like a TTY. <add> this.enabled = stdio.isatty(output.fd); <ide> <ide> if (parseInt(process.env['NODE_NO_READLINE'], 10)) { <ide> this.enabled = false; <add><path>test/disabled/test-readline.js <del><path>test/simple/test-readline.js <add>// Can't test this when 'make test' doesn't assign a tty to the stdout. <add>// Yet another use-case for require('tty').spawn ? <ide> common = require("../common"); <ide> assert = common.assert; <ide> var readline = require("readline");
2
Text
Text
address first round of feedback
510ff7898e5603015e8c3b8292daa2e84f80f6ab
<ide><path>guides/source/getting_started.md <ide> we defined it as an instance variable. <ide> <ide> A concern is any module that contains methods you would like to be able to share across multiple controllers or models. In other frameworks they are often known as mixins. They are a good way to keep your controllers and models small and keep your code DRY. <ide> <del> You can use concerns in your controller or model the same way you would use any module. When you first created your app with `rails new blog` , two folders were created within `apps/` along with the rest: <add> You can use concerns in your controller or model the same way you would use any module. When you first created your app with `rails new blog` , two folders were created within `app/` along with the rest: <ide> <ide> ``` <ide> app/controllers/concerns <ide> app/models/concerns <ide> ``` <ide> <del>A given blog article might have various statuses - for instance, it may be `public` (visible to everyone), or `private` (only visible by the author, perhaps if an author wants to save a draft). It may also be `archived`, which means it is hidden from the author. A comment, similarly, may be `public`, `private`, or `archived`. For any given article, in the controller you might want to verify that an article is public before rendering it. <add>A given blog article might have various statuses - for instance, it might be visible to everyone (i.e. `public`), or only visible to the author (i.e. `private`). It may also be hidden to all but still retrievable (i.e. `archived`). Comments may similarly be hidden or visible. This could be represented using a `status` column in each model. <ide> <ide> Within the `article` model, after running a migration to add a `status` column, you might add: <ide> <ide> Then, in our `index` action template (`app/views/articles/index.html.erb`) we wo <ide> <ide> However, if you look again at our models now, you can see that the logic is duplicated. If in future we increase the functionality of our blog - to include private messages, for instance - we might find ourselves duplicating the logic yet again. This is where concerns come in handy. <ide> <del>Let's call our new concern (module) `Statusable`, a module to use for any model that has a status. We can create a new file inside `app/models/concerns` called `statuslike.rb` , and store all of the status methods that were duplicated in the models. <add>Let's call our new concern (module) `Visible`, a module to use for any model that has a status. We can create a new file inside `app/models/concerns` called `visible.rb` , and store all of the status methods that were duplicated in the models. <ide> <del>`app/models/concerns/statuslike.rb` <add>`app/models/concerns/visible.rb` <ide> <ide> ```ruby <del>module Statuslike <add>module Visible <ide> def archived? <ide> status == 'archived' <ide> end <ide> end <ide> ``` <ide> <del>To include the duplicated validations, we will want to extend `ActiveSupport::Concern` . This module allows us to write validations and other Active Model methods in the module as if we were writing them within the original models (or controllers, if writing a concern for controllers). You can read more about this in the [API Guide](https://api.rubyonrails.org/classes/ActiveSupport/Concern.html): <add>We can add our status validation to the concern, but this is slightly more complex as validations are methods called at the class level. The `ActiveSupport::Concern` ([API Guide](https://api.rubyonrails.org/classes/ActiveSupport/Concern.html)) gives us a simpler way to include them: <ide> <ide> ```ruby <del>module Statuslike <add>module Visible <ide> extends ActiveSupport::Concern <ide> <ide> included do <ide> module Statuslike <ide> end <ide> ``` <ide> <del>Now, we can remove the duplicated logic from each model and instead include our new `Statusable` module: <add>Now, we can remove the duplicated logic from each model and instead include our new `Visible` module: <ide> <ide> <ide> In `app/models/article.rb`: <ide> ```ruby <ide> class Article < ApplicationRecord <del> includes Statusable <add> include Visible <ide> has_many :comments <ide> <ide> validates :title, presence: true, <ide> and in `app/models/comment.rb`: <ide> <ide> ```ruby <ide> class Comment < ApplicationRecord <del> includes Statusable <add> include Visible <ide> belongs_to :article <ide> end <ide> ``` <ide> <del>Our app contains `app/models/concerns` and `app/controllers/concerns` in its `autoload_paths` so you don't need to `require` the concern. If your app is having trouble finding your concern module, you may need to check your `autoload_paths`. You can learn about how to do so [here](http://guides.rubyonrails.org/autoloading_and_reloading_constants.html#autoload-paths). <add>Class methods can also added to concerns. If we want a count of public articles or comments to display on our main page, we might add a class method to Visible as follows: <add> <add>```ruby <add>module Visible <add> extends ActiveSupport::Concern <add> <add> VALID_STATUSES = ['public', 'private', 'archived'] <add> <add> included do <add> validates :status, in: VALID_STATUSES <add> end <add> <add> class_methods do <add> def public_count <add> self.where(status: 'public') <add> end <add> end <add> <add> def archived? <add> status == 'archived' <add> end <add>end <add>``` <add> <add>Then in the view, you can call it like any class method: <add> <add>```html+erb <add><h1>Listing Articles</h1> <add>Our blog has <%= Article.public_count %> articles and counting! Add yours now. <add><%= link_to 'New article', new_article_path %> <add><table> <add> <tr> <add> <th>Title</th> <add> <th>Text</th> <add> <th colspan="3"></th> <add> </tr> <add> <add> <% @articles.each do |article| %> <add> <% unless article.archived? %> <add> <tr> <add> <td><%= article.title %></td> <add> <td><%= article.text %></td> <add> <td><%= link_to 'Show', article_path(article) %></td> <add> <td><%= link_to 'Edit', edit_article_path(article) %></td> <add> <td><%= link_to 'Destroy', article_path(article), <add> method: :delete, <add> data: { confirm: 'Are you sure?' } %></td> <add> </tr> <add> <% end %> <add> <% end %> <add></table> <add>``` <ide> <ide> Deleting Comments <ide> ----------------- <ide> Article model, `app/models/article.rb`, as follows: <ide> <ide> ```ruby <ide> class Article < ApplicationRecord <del> includes Statusable <add> include Visible <ide> <ide> has_many :comments, dependent: :destroy <ide> validates :title, presence: true,
1
Javascript
Javascript
remove flag for test-addon-uv-handle-leak
7ed790e9dbf7827056b2859a57e9ad72863c1d50
<ide><path>test/abort/test-addon-uv-handle-leak.js <del>// Flags: --experimental-worker <ide> 'use strict'; <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide> const fs = require('fs'); <ide> const path = require('path'); <ide> const cp = require('child_process'); <del>const { Worker } = require('worker_threads'); <ide> const { spawnSync } = require('child_process'); <ide> <ide> // This is a sibling test to test/addons/uv-handle-leak. <ide> if (!fs.existsSync(bindingPath)) <ide> <ide> if (process.argv[2] === 'child') { <ide> <add> const { Worker } = require('worker_threads'); <add> <ide> // The worker thread loads and then unloads `bindingPath`. Because of this the <ide> // symbols in `bindingPath` are lost when the worker thread quits, but the <ide> // number of open handles in the worker thread's event loop is assessed in the
1
Javascript
Javascript
replace var to let in cli_table.js
78b7ddff1b0e20e326d18a198525300f254276e9
<ide><path>lib/internal/cli_table.js <ide> const tableChars = { <ide> <ide> const renderRow = (row, columnWidths) => { <ide> let out = tableChars.left; <del> for (var i = 0; i < row.length; i++) { <add> for (let i = 0; i < row.length; i++) { <ide> const cell = row[i]; <ide> const len = getStringWidth(cell); <ide> const needed = (columnWidths[i] - len) / 2; <ide> const table = (head, columns) => { <ide> const columnWidths = head.map((h) => getStringWidth(h)); <ide> const longestColumn = columns.reduce((n, a) => Math.max(n, a.length), 0); <ide> <del> for (var i = 0; i < head.length; i++) { <add> for (let i = 0; i < head.length; i++) { <ide> const column = columns[i]; <del> for (var j = 0; j < longestColumn; j++) { <add> for (let j = 0; j < longestColumn; j++) { <ide> if (rows[j] === undefined) <ide> rows[j] = []; <ide> const value = rows[j][i] =
1
Javascript
Javascript
add matrix3 unit tests
2eb06eeaaaf68d62aa850f9fd995faf1eff263c5
<ide><path>test/unit/src/math/Matrix3.tests.js <ide> export default QUnit.module( 'Maths', () => { <ide> } ); <ide> <ide> // PUBLIC STUFF <del> QUnit.todo( "isMatrix3", ( assert ) => { <add> QUnit.test( "isMatrix3", ( assert ) => { <ide> <del> assert.ok( false, "everything's gonna be alright" ); <add> var a = new Matrix3(); <add> assert.ok( a.isMatrix3 === true, "Passed!" ); <add> <add> var b = new Matrix4(); <add> assert.ok( ! b.isMatrix3, "Passed!" ); <ide> <ide> } ); <ide> <ide> export default QUnit.module( 'Maths', () => { <ide> <ide> } ); <ide> <del> QUnit.todo( "setFromMatrix4", ( assert ) => { <add> QUnit.test( "setFromMatrix4", ( assert ) => { <add> <ide> <del> assert.ok( false, "everything's gonna be alright" ); <add> var a = new Matrix4().set( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ); <add> var b = new Matrix3(); <add> var c = new Matrix3().set( 0, 1, 2, 4, 5, 6, 8, 9, 10 ); <add> b.setFromMatrix4( a ); <add> assert.ok( b.equals( c ) ); <ide> <ide> } ); <ide> <ide> export default QUnit.module( 'Maths', () => { <ide> <ide> } ); <ide> <del> QUnit.todo( "transposeIntoArray", ( assert ) => { <add> QUnit.test( "transposeIntoArray", ( assert ) => { <ide> <del> assert.ok( false, "everything's gonna be alright" ); <add> var a = new Matrix3().set( 0, 1, 2, 3, 4, 5, 6, 7, 8 ); <add> var b = []; <add> a.transposeIntoArray( b ); <add> <add> assert.ok( b[ 0 ] == 0 ); <add> assert.ok( b[ 1 ] == 1 ); <add> assert.ok( b[ 2 ] == 2 ); <add> assert.ok( b[ 3 ] == 3 ); <add> assert.ok( b[ 4 ] == 4 ); <add> assert.ok( b[ 5 ] == 5 ); <add> assert.ok( b[ 5 ] == 5 ); <add> assert.ok( b[ 6 ] == 6 ); <add> assert.ok( b[ 7 ] == 7 ); <add> assert.ok( b[ 8 ] == 8 ); <ide> <ide> } ); <ide> <ide> export default QUnit.module( 'Maths', () => { <ide> <ide> } ); <ide> <del> QUnit.todo( "fromArray", ( assert ) => { <add> QUnit.test( "fromArray", ( assert ) => { <add> <add> var b = new Matrix3(); <add> b.fromArray( [ 0, 1, 2, 3, 4, 5, 6, 7, 8 ] ); <add> <add> assert.ok( b.elements[ 0 ] == 0 ); <add> assert.ok( b.elements[ 1 ] == 1 ); <add> assert.ok( b.elements[ 2 ] == 2 ); <add> assert.ok( b.elements[ 3 ] == 3 ); <add> assert.ok( b.elements[ 4 ] == 4 ); <add> assert.ok( b.elements[ 5 ] == 5 ); <add> assert.ok( b.elements[ 6 ] == 6 ); <add> assert.ok( b.elements[ 7 ] == 7 ); <add> assert.ok( b.elements[ 8 ] == 8 ); <ide> <del> assert.ok( false, "everything's gonna be alright" ); <add> b = new Matrix3(); <add> b.fromArray( [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 ], 10 ); <add> <add> assert.ok( b.elements[ 0 ] == 10 ); <add> assert.ok( b.elements[ 1 ] == 11 ); <add> assert.ok( b.elements[ 2 ] == 12 ); <add> assert.ok( b.elements[ 3 ] == 13 ); <add> assert.ok( b.elements[ 4 ] == 14 ); <add> assert.ok( b.elements[ 5 ] == 15 ); <add> assert.ok( b.elements[ 6 ] == 16 ); <add> assert.ok( b.elements[ 7 ] == 17 ); <add> assert.ok( b.elements[ 8 ] == 18 ); <ide> <ide> } ); <ide>
1
Python
Python
improve aws sqs sensor
d28efbfb7780afd1ff13a258dc5dc3e3381ddabd
<ide><path>airflow/providers/amazon/aws/sensors/sqs.py <ide> # specific language governing permissions and limitations <ide> # under the License. <ide> """Reads and then deletes the message from SQS queue""" <del>from typing import Optional <add>import json <add>from typing import Any, Optional <add> <add>from jsonpath_ng import parse <add>from typing_extensions import Literal <ide> <ide> from airflow.exceptions import AirflowException <ide> from airflow.providers.amazon.aws.hooks.sqs import SQSHook <ide> class SQSSensor(BaseSensorOperator): <ide> :type max_messages: int <ide> :param wait_time_seconds: The time in seconds to wait for receiving messages (default: 1 second) <ide> :type wait_time_seconds: int <add> :param visibility_timeout: Visibility timeout, a period of time during which <add> Amazon SQS prevents other consumers from receiving and processing the message. <add> :type visibility_timeout: Optional[Int] <add> :param message_filtering: Specified how received messages should be filtered. Supported options are: <add> `None` (no filtering, default), `'literal'` (message Body literal match) or `'jsonpath'` <add> (message Body filtered using a JSONPath expression). <add> You may add further methods by overriding the relevant class methods. <add> :type message_filtering: Optional[Literal["literal", "jsonpath"]] <add> :param message_filtering_match_values: Optional value/s for the message filter to match on. <add> For example, with literal matching, if a message body matches any of the specified values <add> then it is included. For JSONPath matching, the result of the JSONPath expression is used <add> and may match any of the specified values. <add> :type message_filtering_match_values: Any <add> :param message_filtering_config: Additional configuration to pass to the message filter. <add> For example with JSONPath filtering you can pass a JSONPath expression string here, <add> such as `'foo[*].baz'`. Messages with a Body which does not match are ignored. <add> :type message_filtering_config: Any <ide> """ <ide> <del> template_fields = ('sqs_queue', 'max_messages') <add> template_fields = ('sqs_queue', 'max_messages', 'message_filtering_config') <ide> <ide> def __init__( <ide> self, <ide> def __init__( <ide> aws_conn_id: str = 'aws_default', <ide> max_messages: int = 5, <ide> wait_time_seconds: int = 1, <add> visibility_timeout: Optional[int] = None, <add> message_filtering: Optional[Literal["literal", "jsonpath"]] = None, <add> message_filtering_match_values: Any = None, <add> message_filtering_config: Any = None, <ide> **kwargs, <ide> ): <ide> super().__init__(**kwargs) <ide> self.sqs_queue = sqs_queue <ide> self.aws_conn_id = aws_conn_id <ide> self.max_messages = max_messages <ide> self.wait_time_seconds = wait_time_seconds <add> self.visibility_timeout = visibility_timeout <add> <add> self.message_filtering = message_filtering <add> <add> if message_filtering_match_values is not None: <add> if not isinstance(message_filtering_match_values, set): <add> message_filtering_match_values = set(message_filtering_match_values) <add> self.message_filtering_match_values = message_filtering_match_values <add> <add> if self.message_filtering == 'literal': <add> if self.message_filtering_match_values is None: <add> raise TypeError('message_filtering_match_values must be specified for literal matching') <add> <add> self.message_filtering_config = message_filtering_config <add> <ide> self.hook: Optional[SQSHook] = None <ide> <ide> def poke(self, context): <ide> def poke(self, context): <ide> <ide> self.log.info('SQSSensor checking for message on queue: %s', self.sqs_queue) <ide> <del> messages = sqs_conn.receive_message( <del> QueueUrl=self.sqs_queue, <del> MaxNumberOfMessages=self.max_messages, <del> WaitTimeSeconds=self.wait_time_seconds, <del> ) <add> receive_message_kwargs = { <add> 'QueueUrl': self.sqs_queue, <add> 'MaxNumberOfMessages': self.max_messages, <add> 'WaitTimeSeconds': self.wait_time_seconds, <add> } <add> if self.visibility_timeout is not None: <add> receive_message_kwargs['VisibilityTimeout'] = self.visibility_timeout <ide> <del> self.log.info("received message %s", str(messages)) <add> response = sqs_conn.receive_message(**receive_message_kwargs) <ide> <del> if 'Messages' in messages and messages['Messages']: <del> entries = [ <del> {'Id': message['MessageId'], 'ReceiptHandle': message['ReceiptHandle']} <del> for message in messages['Messages'] <del> ] <add> if "Messages" not in response: <add> return False <ide> <del> result = sqs_conn.delete_message_batch(QueueUrl=self.sqs_queue, Entries=entries) <add> messages = response['Messages'] <add> num_messages = len(messages) <add> self.log.info("Received %d messages", num_messages) <ide> <del> if 'Successful' in result: <del> context['ti'].xcom_push(key='messages', value=messages) <del> return True <del> else: <del> raise AirflowException( <del> 'Delete SQS Messages failed ' + str(result) + ' for messages ' + str(messages) <del> ) <add> if not num_messages: <add> return False <ide> <del> return False <add> if self.message_filtering: <add> messages = self.filter_messages(messages) <add> num_messages = len(messages) <add> self.log.info("There are %d messages left after filtering", num_messages) <add> <add> if not num_messages: <add> return False <add> <add> self.log.info("Deleting %d messages", num_messages) <add> <add> entries = [ <add> {'Id': message['MessageId'], 'ReceiptHandle': message['ReceiptHandle']} for message in messages <add> ] <add> response = sqs_conn.delete_message_batch(QueueUrl=self.sqs_queue, Entries=entries) <add> <add> if 'Successful' in response: <add> context['ti'].xcom_push(key='messages', value=messages) <add> return True <add> else: <add> raise AirflowException( <add> 'Delete SQS Messages failed ' + str(response) + ' for messages ' + str(messages) <add> ) <ide> <ide> def get_hook(self) -> SQSHook: <ide> """Create and return an SQSHook""" <ide> def get_hook(self) -> SQSHook: <ide> <ide> self.hook = SQSHook(aws_conn_id=self.aws_conn_id) <ide> return self.hook <add> <add> def filter_messages(self, messages): <add> if self.message_filtering == 'literal': <add> return self.filter_messages_literal(messages) <add> if self.message_filtering == 'jsonpath': <add> return self.filter_messages_jsonpath(messages) <add> else: <add> raise NotImplementedError('Override this method to define custom filters') <add> <add> def filter_messages_literal(self, messages): <add> filtered_messages = [] <add> for message in messages: <add> if message['Body'] in self.message_filtering_match_values: <add> filtered_messages.append(message) <add> return filtered_messages <add> <add> def filter_messages_jsonpath(self, messages): <add> jsonpath_expr = parse(self.message_filtering_config) <add> filtered_messages = [] <add> for message in messages: <add> body = message['Body'] <add> # Body is a string, deserialise to an object and then parse <add> body = json.loads(body) <add> results = jsonpath_expr.find(body) <add> if not results: <add> continue <add> if self.message_filtering_match_values is None: <add> filtered_messages.append(message) <add> continue <add> for result in results: <add> if result.value in self.message_filtering_match_values: <add> filtered_messages.append(message) <add> break <add> return filtered_messages <ide><path>setup.py <ide> def write_version(filename: str = os.path.join(*[my_dir, "airflow", "git_version <ide> amazon = [ <ide> 'boto3>=1.15.0,<1.18.0', <ide> 'watchtower~=1.0.6', <add> 'jsonpath_ng>=1.5.3', <ide> ] <ide> apache_beam = [ <ide> 'apache-beam>=2.20.0', <ide><path>tests/providers/amazon/aws/sensors/test_sqs.py <ide> # under the License. <ide> <ide> <add>import json <ide> import unittest <ide> from unittest import mock <ide> <ide> def test_poke_receive_raise_exception(self, mock_conn): <ide> self.sensor.poke(self.mock_context) <ide> <ide> assert 'test exception' in ctx.value.args[0] <add> <add> @mock.patch.object(SQSHook, 'get_conn') <add> def test_poke_visibility_timeout(self, mock_conn): <add> # Check without visibility_timeout parameter <add> self.sqs_hook.create_queue('test') <add> self.sqs_hook.send_message(queue_url='test', message_body='hello') <add> <add> self.sensor.poke(self.mock_context) <add> <add> calls_receive_message = [ <add> mock.call().receive_message(QueueUrl='test', MaxNumberOfMessages=5, WaitTimeSeconds=1) <add> ] <add> mock_conn.assert_has_calls(calls_receive_message) <add> # Check with visibility_timeout parameter <add> self.sensor = SQSSensor( <add> task_id='test_task2', <add> dag=self.dag, <add> sqs_queue='test', <add> aws_conn_id='aws_default', <add> visibility_timeout=42, <add> ) <add> self.sensor.poke(self.mock_context) <add> <add> calls_receive_message = [ <add> mock.call().receive_message( <add> QueueUrl='test', MaxNumberOfMessages=5, WaitTimeSeconds=1, VisibilityTimeout=42 <add> ) <add> ] <add> mock_conn.assert_has_calls(calls_receive_message) <add> <add> @mock_sqs <add> def test_poke_message_invalid_filtering(self): <add> self.sqs_hook.create_queue('test') <add> self.sqs_hook.send_message(queue_url='test', message_body='hello') <add> sensor = SQSSensor( <add> task_id='test_task2', <add> dag=self.dag, <add> sqs_queue='test', <add> aws_conn_id='aws_default', <add> message_filtering='invalid_option', <add> ) <add> with pytest.raises(NotImplementedError) as ctx: <add> sensor.poke(self.mock_context) <add> assert 'Override this method to define custom filters' in ctx.value.args[0] <add> <add> @mock.patch.object(SQSHook, "get_conn") <add> def test_poke_message_filtering_literal_values(self, mock_conn): <add> self.sqs_hook.create_queue('test') <add> matching = [{"id": 11, "body": "a matching message"}] <add> non_matching = [{"id": 12, "body": "a non-matching message"}] <add> all = matching + non_matching <add> <add> def mock_receive_message(**kwargs): <add> messages = [] <add> for message in all: <add> messages.append( <add> { <add> 'MessageId': message['id'], <add> 'ReceiptHandle': 100 + message['id'], <add> 'Body': message['body'], <add> } <add> ) <add> return {'Messages': messages} <add> <add> mock_conn.return_value.receive_message.side_effect = mock_receive_message <add> <add> def mock_delete_message_batch(**kwargs): <add> return {'Successful'} <add> <add> mock_conn.return_value.delete_message_batch.side_effect = mock_delete_message_batch <add> <add> # Test that messages are filtered <add> self.sensor.message_filtering = 'literal' <add> self.sensor.message_filtering_match_values = ["a matching message"] <add> result = self.sensor.poke(self.mock_context) <add> assert result <add> <add> # Test that only filtered messages are deleted <add> delete_entries = [{'Id': x['id'], 'ReceiptHandle': 100 + x['id']} for x in matching] <add> calls_delete_message_batch = [ <add> mock.call().delete_message_batch(QueueUrl='test', Entries=delete_entries) <add> ] <add> mock_conn.assert_has_calls(calls_delete_message_batch) <add> <add> @mock.patch.object(SQSHook, "get_conn") <add> def test_poke_message_filtering_jsonpath(self, mock_conn): <add> self.sqs_hook.create_queue('test') <add> matching = [ <add> {"id": 11, "key": {"matches": [1, 2]}}, <add> {"id": 12, "key": {"matches": [3, 4, 5]}}, <add> {"id": 13, "key": {"matches": [10]}}, <add> ] <add> non_matching = [ <add> {"id": 14, "key": {"nope": [5, 6]}}, <add> {"id": 15, "key": {"nope": [7, 8]}}, <add> ] <add> all = matching + non_matching <add> <add> def mock_receive_message(**kwargs): <add> messages = [] <add> for message in all: <add> messages.append( <add> { <add> 'MessageId': message['id'], <add> 'ReceiptHandle': 100 + message['id'], <add> 'Body': json.dumps(message), <add> } <add> ) <add> return {'Messages': messages} <add> <add> mock_conn.return_value.receive_message.side_effect = mock_receive_message <add> <add> def mock_delete_message_batch(**kwargs): <add> return {'Successful'} <add> <add> mock_conn.return_value.delete_message_batch.side_effect = mock_delete_message_batch <add> <add> # Test that messages are filtered <add> self.sensor.message_filtering = 'jsonpath' <add> self.sensor.message_filtering_config = 'key.matches[*]' <add> result = self.sensor.poke(self.mock_context) <add> assert result <add> <add> # Test that only filtered messages are deleted <add> delete_entries = [{'Id': x['id'], 'ReceiptHandle': 100 + x['id']} for x in matching] <add> calls_delete_message_batch = [ <add> mock.call().delete_message_batch(QueueUrl='test', Entries=delete_entries) <add> ] <add> mock_conn.assert_has_calls(calls_delete_message_batch) <add> <add> @mock.patch.object(SQSHook, "get_conn") <add> def test_poke_message_filtering_jsonpath_values(self, mock_conn): <add> self.sqs_hook.create_queue('test') <add> matching = [ <add> {"id": 11, "key": {"matches": [1, 2]}}, <add> {"id": 12, "key": {"matches": [1, 4, 5]}}, <add> {"id": 13, "key": {"matches": [4, 5]}}, <add> ] <add> non_matching = [ <add> {"id": 21, "key": {"matches": [10]}}, <add> {"id": 22, "key": {"nope": [5, 6]}}, <add> {"id": 23, "key": {"nope": [7, 8]}}, <add> ] <add> all = matching + non_matching <add> <add> def mock_receive_message(**kwargs): <add> messages = [] <add> for message in all: <add> messages.append( <add> { <add> 'MessageId': message['id'], <add> 'ReceiptHandle': 100 + message['id'], <add> 'Body': json.dumps(message), <add> } <add> ) <add> return {'Messages': messages} <add> <add> mock_conn.return_value.receive_message.side_effect = mock_receive_message <add> <add> def mock_delete_message_batch(**kwargs): <add> return {'Successful'} <add> <add> mock_conn.return_value.delete_message_batch.side_effect = mock_delete_message_batch <add> <add> # Test that messages are filtered <add> self.sensor.message_filtering = 'jsonpath' <add> self.sensor.message_filtering_config = 'key.matches[*]' <add> self.sensor.message_filtering_match_values = [1, 4] <add> result = self.sensor.poke(self.mock_context) <add> assert result <add> <add> # Test that only filtered messages are deleted <add> delete_entries = [{'Id': x['id'], 'ReceiptHandle': 100 + x['id']} for x in matching] <add> calls_delete_message_batch = [ <add> mock.call().delete_message_batch(QueueUrl='test', Entries=delete_entries) <add> ] <add> mock_conn.assert_has_calls(calls_delete_message_batch)
3
Java
Java
drop servlet 4 classpath check
16ea4692bab551800b9ba994ac08099e8acfd6cd
<ide><path>spring-web/src/main/java/org/springframework/web/util/ServletRequestPathUtils.java <ide> public static RequestPath parse(HttpServletRequest request) { <ide> if (requestUri == null) { <ide> requestUri = request.getRequestURI(); <ide> } <del> if (UrlPathHelper.servlet4Present) { <del> String servletPathPrefix = Servlet4Delegate.getServletPathPrefix(request); <del> if (StringUtils.hasText(servletPathPrefix)) { <del> if (servletPathPrefix.endsWith("/")) { <del> servletPathPrefix = servletPathPrefix.substring(0, servletPathPrefix.length() - 1); <del> } <del> return new ServletRequestPath(requestUri, request.getContextPath(), servletPathPrefix); <add> <add> String servletPathPrefix = Servlet4Delegate.getServletPathPrefix(request); <add> if (StringUtils.hasText(servletPathPrefix)) { <add> if (servletPathPrefix.endsWith("/")) { <add> servletPathPrefix = servletPathPrefix.substring(0, servletPathPrefix.length() - 1); <ide> } <add> return new ServletRequestPath(requestUri, request.getContextPath(), servletPathPrefix); <ide> } <add> <ide> return RequestPath.parse(requestUri, request.getContextPath()); <ide> } <ide> } <ide><path>spring-web/src/main/java/org/springframework/web/util/UrlPathHelper.java <ide> /* <del> * Copyright 2002-2021 the original author or authors. <add> * Copyright 2002-2022 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> <ide> import org.springframework.lang.Nullable; <ide> import org.springframework.util.Assert; <del>import org.springframework.util.ClassUtils; <ide> import org.springframework.util.CollectionUtils; <ide> import org.springframework.util.LinkedMultiValueMap; <ide> import org.springframework.util.MultiValueMap; <ide> public class UrlPathHelper { <ide> */ <ide> public static final String PATH_ATTRIBUTE = UrlPathHelper.class.getName() + ".PATH"; <ide> <del> static final boolean servlet4Present = <del> ClassUtils.hasMethod(HttpServletRequest.class, "getHttpServletMapping"); <del> <ide> /** <ide> * Special WebSphere request attribute, indicating the original request URI. <ide> * Preferable over the standard Servlet 2.4 forward attribute on WebSphere, <ide> public String getLookupPathForRequest(HttpServletRequest request) { <ide> * or if the servlet has been mapped to root; {@code false} otherwise <ide> */ <ide> private boolean skipServletPathDetermination(HttpServletRequest request) { <del> if (servlet4Present) { <del> return Servlet4Delegate.skipServletPathDetermination(request); <add> HttpServletMapping mapping = (HttpServletMapping) request.getAttribute(RequestDispatcher.INCLUDE_MAPPING); <add> if (mapping == null) { <add> mapping = request.getHttpServletMapping(); <ide> } <del> return false; <add> MappingMatch match = mapping.getMappingMatch(); <add> return (match != null && (!match.equals(MappingMatch.PATH) || mapping.getPattern().equals("/*"))); <ide> } <ide> <ide> /** <ide> public String removeSemicolonContent(String requestUri) { <ide> rawPathInstance.setReadOnly(); <ide> } <ide> <del> <del> /** <del> * Inner class to avoid a hard dependency on Servlet 4 {@link HttpServletMapping} <del> * and {@link MappingMatch} at runtime. <del> */ <del> private static class Servlet4Delegate { <del> <del> public static boolean skipServletPathDetermination(HttpServletRequest request) { <del> HttpServletMapping mapping = (HttpServletMapping) request.getAttribute(RequestDispatcher.INCLUDE_MAPPING); <del> if (mapping == null) { <del> mapping = request.getHttpServletMapping(); <del> } <del> MappingMatch match = mapping.getMappingMatch(); <del> return (match != null && (!match.equals(MappingMatch.PATH) || mapping.getPattern().equals("/*"))); <del> } <del> } <del> <ide> }
2
Go
Go
call udevwait() even in failure path
edc6df256d21eb1d1aa36b241dcc6d4b83d58d75
<ide><path>pkg/devicemapper/devmapper.go <ide> func CreatePool(poolName string, dataFile, metadataFile *os.File, poolBlockSize <ide> if err := task.SetCookie(&cookie, 0); err != nil { <ide> return fmt.Errorf("Can't set cookie %s", err) <ide> } <add> defer UdevWait(cookie) <ide> <ide> if err := task.Run(); err != nil { <ide> return fmt.Errorf("Error running DeviceCreate (CreatePool) %s", err) <ide> } <ide> <del> UdevWait(cookie) <del> <ide> return nil <ide> } <ide> <ide> func ResumeDevice(name string) error { <ide> if err := task.SetCookie(&cookie, 0); err != nil { <ide> return fmt.Errorf("Can't set cookie %s", err) <ide> } <add> defer UdevWait(cookie) <ide> <ide> if err := task.Run(); err != nil { <ide> return fmt.Errorf("Error running DeviceResume %s", err) <ide> } <ide> <del> UdevWait(cookie) <del> <ide> return nil <ide> } <ide> <ide> func ActivateDevice(poolName string, name string, deviceId int, size uint64) err <ide> return fmt.Errorf("Can't set cookie %s", err) <ide> } <ide> <add> defer UdevWait(cookie) <add> <ide> if err := task.Run(); err != nil { <ide> return fmt.Errorf("Error running DeviceCreate (ActivateDevice) %s", err) <ide> } <ide> <del> UdevWait(cookie) <del> <ide> return nil <ide> } <ide>
1
Text
Text
add instructions for available_locales [skip ci]
864ef6be9ea74b22e04297fa9d269897d729863c
<ide><path>guides/source/i18n.md <ide> I18n.l Time.now <ide> There are also attribute readers and writers for the following attributes: <ide> <ide> ```ruby <del>load_path # Announce your custom translation files <del>locale # Get and set the current locale <del>default_locale # Get and set the default locale <del>exception_handler # Use a different exception_handler <del>backend # Use a different backend <add>load_path # Announce your custom translation files <add>locale # Get and set the current locale <add>default_locale # Get and set the default locale <add>available_locales # Whitelist locales available for the application <add>enforce_available_locales # Enforce locale whitelisting (true or false) <add>exception_handler # Use a different exception_handler <add>backend # Use a different backend <ide> ``` <ide> <ide> So, let's internationalize a simple Rails application from the ground up in the next chapters! <ide> The load path must be specified before any translations are looked up. To change <ide> # Where the I18n library should search for translation files <ide> I18n.load_path += Dir[Rails.root.join('lib', 'locale', '*.{rb,yml}')] <ide> <add># Whitelist locales available for the application <add>I18n.available_locales = [:en, :pt] <add> <ide> # Set default locale to something other than :en <ide> I18n.default_locale = :pt <ide> ```
1
Java
Java
improve check for "broken pipe" error message
7e232f989ba5d947dc286104b44d0e9ce580a2af
<ide><path>spring-web/src/main/java/org/springframework/web/server/adapter/HttpWebHandlerAdapter.java <ide> else if (disconnectedClientLogger.isDebugEnabled()) { <ide> } <ide> <ide> private boolean indicatesDisconnectedClient(Throwable ex) { <del> return ("Broken pipe".equalsIgnoreCase(NestedExceptionUtils.getMostSpecificCause(ex).getMessage()) || <del> DISCONNECTED_CLIENT_EXCEPTIONS.contains(ex.getClass().getSimpleName())); <add> String message = NestedExceptionUtils.getMostSpecificCause(ex).getMessage(); <add> message = (message != null ? message.toLowerCase() : ""); <add> String className = ex.getClass().getSimpleName(); <add> return (message.contains("broken pipe") || DISCONNECTED_CLIENT_EXCEPTIONS.contains(className)); <ide> } <ide> <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/session/AbstractSockJsSession.java <ide> else if (disconnectedClientLogger.isDebugEnabled()) { <ide> } <ide> <ide> private boolean indicatesDisconnectedClient(Throwable ex) { <del> return ("Broken pipe".equalsIgnoreCase(NestedExceptionUtils.getMostSpecificCause(ex).getMessage()) || <del> DISCONNECTED_CLIENT_EXCEPTIONS.contains(ex.getClass().getSimpleName())); <add> String message = NestedExceptionUtils.getMostSpecificCause(ex).getMessage(); <add> message = (message != null ? message.toLowerCase() : ""); <add> String className = ex.getClass().getSimpleName(); <add> return (message.contains("broken pipe") || DISCONNECTED_CLIENT_EXCEPTIONS.contains(className)); <ide> } <ide> <ide>
2
PHP
PHP
return collect() and add missing ->filter()
4a2083bc25c37b44dc966161d4172f36a1215464
<ide><path>src/Illuminate/Console/Command.php <ide> protected function context() <ide> { <ide> $options = array_only($this->option(), ['no-interaction', 'ansi', 'no-ansi', 'quiet', 'verbose']); <ide> <del> collect($options)->mapWithKeys(function ($value, $key) { <add> return collect($options)->mapWithKeys(function ($value, $key) { <ide> return ["--{$key}" => $value]; <del> })->all(); <add> })->filter()->all(); <ide> } <ide> <ide> /**
1
Javascript
Javascript
change == to === in crypto test
7044065f1a955275335f6a9207f3321c790277c7
<ide><path>test/parallel/test-crypto-sign-verify.js <ide> const modSize = 1024; <ide> padding: crypto.constants.RSA_PKCS1_PSS_PADDING, <ide> saltLength: verifySaltLength <ide> }, s4); <del> const saltLengthCorrect = getEffectiveSaltLength(signSaltLength) == <add> const saltLengthCorrect = getEffectiveSaltLength(signSaltLength) === <ide> getEffectiveSaltLength(verifySaltLength); <ide> assert.strictEqual(verified, saltLengthCorrect, 'verify (PSS)'); <ide> });
1
Javascript
Javascript
fix global reexports for ember-utils
0667fd3d02f45a93cfd00a7e99192c630291127d
<ide><path>packages/container/lib/index.js <ide> export { <ide> default as Container, <ide> buildFakeContainerWithDeprecations <ide> } from './container'; <del>export { OWNER, getOwner, setOwner } from 'ember-utils'; <ide><path>packages/container/lib/registry.js <ide> import { dictionary, EmptyObject, assign, intern } from 'ember-utils'; <add>import { assert, deprecate } from 'ember-metal'; <ide> import Container from './container'; <ide> <ide> const VALID_FULL_NAME_REGEXP = /^[^:]+:[^:]+$/; <ide><path>packages/ember-metal/lib/index.js <ide> export { <ide> ComputedProperty <ide> } from './computed'; <ide> export { default as alias } from './alias'; <del>export { default as assign } from './assign'; <ide> export { default as merge } from './merge'; <ide> export { <ide> assert, <ide> export { <ide> subscribe as instrumentationSubscribe, <ide> unsubscribe as instrumentationUnsubscribe <ide> } from './instrumentation'; <del>export { <del> intern, <del> GUID_KEY, <del> GUID_KEY_PROPERTY, <del> applyStr, <del> canInvoke, <del> generateGuid, <del> guidFor, <del> inspect, <del> makeArray, <del> tryInvoke, <del> uuid, <del> wrap <del>} from 'ember-utils'; <ide> export { <ide> isTesting, <ide> setTesting <ide> export { <ide> export { <ide> isGlobalPath <ide> } from './path_cache'; <del>export { default as symbol } from './symbol'; <del>export { default as dictionary } from './dictionary'; <del>export { default as EmptyObject } from './empty_object'; <ide> export { default as InjectedProperty } from './injected_property'; <ide> export { <ide> setHasViews, <ide><path>packages/ember-runtime/lib/system/string.js <ide> */ <ide> import { <ide> deprecate, <del> inspect as emberInspect, <ide> Cache <ide> } from 'ember-metal'; <add>import { inspect } from 'ember-utils'; <ide> import { isArray } from '../utils'; <ide> import { <ide> get as getString <ide> function _fmt(str, formats) { <ide> return str.replace(/%@([0-9]+)?/g, function(s, argIndex) { <ide> argIndex = (argIndex) ? parseInt(argIndex, 10) - 1 : idx++; <ide> s = cachedFormats[argIndex]; <del> return (s === null) ? '(null)' : (s === undefined) ? '' : emberInspect(s); <add> return (s === null) ? '(null)' : (s === undefined) ? '' : inspect(s); <ide> }); <ide> } <ide> <ide><path>packages/ember-template-compiler/lib/index.js <del>import 'container'; <del> <ide> import _Ember, { FEATURES } from 'ember-metal'; <ide> import { ENV } from 'ember-environment'; <ide> import VERSION from 'ember/version'; <ide><path>packages/ember-utils/lib/owner.js <ide> @submodule ember-runtime <ide> */ <ide> <del>import { symbol } from 'ember-metal'; <add>import symbol from './symbol'; <ide> <ide> export const OWNER = symbol('OWNER'); <ide> <ide><path>packages/ember-utils/lib/symbol.js <del>import { GUID_KEY, intern } from './index'; <add>import { GUID_KEY } from './guid'; <add>import intern from './intern'; <ide> <ide> export default function symbol(debugName) { <ide> // TODO: Investigate using platform symbols, but we do not <ide><path>packages/ember-views/lib/system/utils.js <add>/* globals Element */ <ide> import { guidFor, symbol, getOwner } from 'ember-utils'; <ide> <ide> /** <ide><path>packages/ember/lib/index.js <del>import { getOwner, setOwner } from 'ember-utils'; <ide> import require, { has } from 'require'; <ide> <ide> // ****ember-environment**** <ide> import { ENV, context } from 'ember-environment'; <add>import * as utils from 'ember-utils'; <ide> <ide> import { Registry, Container } from 'container'; <ide> <ide> // ****ember-metal**** <ide> import Ember, * as metal from 'ember-metal'; <ide> <add>// ember-utils exports <add>Ember.getOwner = utils.getOwner; <add>Ember.setOwner = utils.setOwner; <add>Ember.generateGuid = utils.generateGuid; <add>Ember.GUID_KEY = utils.GUID_KEY; <add>Ember.guidFor = utils.guidFor; <add>Ember.inspect = utils.inspect; <add>Ember.makeArray = utils.makeArray; <add>Ember.canInvoke = utils.canInvoke; <add>Ember.tryInvoke = utils.tryInvoke; <add>Ember.wrap = utils.wrap; <add>Ember.applyStr = utils.applyStr; <add>Ember.uuid = utils.uuid; <add> <add>// container exports <add>Ember.Container = Container; <add>Ember.Registry = Registry; <add> <ide> // need to import this directly, to ensure the babel feature <ide> // flag plugin works properly <ide> import { <ide> Ember.Instrumentation = { <ide> reset: metal.instrumentationReset <ide> }; <ide> <del>Ember.generateGuid = metal.generateGuid; <del>Ember.GUID_KEY = metal.GUID_KEY; <del>Ember.guidFor = metal.guidFor; <del>Ember.inspect = metal.inspect; <del> <del>Ember.makeArray = metal.makeArray; <del>Ember.canInvoke = metal.canInvoke; <del>Ember.tryInvoke = metal.tryInvoke; <del>Ember.wrap = metal.wrap; <del>Ember.applyStr = metal.applyStr; <del>Ember.uuid = metal.uuid; <ide> Ember.Error = metal.Error; <ide> Ember.META_DESC = metal.META_DESC; <ide> Ember.meta = metal.meta; <ide> Ember.Backburner = function() { <ide> Ember._Backburner = Backburner; <ide> <ide> <del>Ember.Container = Container; <del>Ember.Registry = Registry; <del>Ember.getOwner = getOwner; <del>Ember.setOwner = setOwner; <del> <ide> import Logger from 'ember-console'; <ide> <ide> Ember.Logger = Logger; <ide><path>packages/ember/tests/reexports_test.js <ide> import { isFeatureEnabled } from 'ember-metal'; <ide> QUnit.module('ember reexports'); <ide> <ide> [ <add> // ember-utils <add> ['getOwner', 'ember-utils', 'getOwner'], <add> ['setOwner', 'ember-utils', 'setOwner'], <add> // ['assign', 'ember-metal'], TODO: fix this test, we use `Object.assign` if present <add> ['GUID_KEY', 'ember-utils'], <add> ['uuid', 'ember-utils'], <add> ['generateGuid', 'ember-utils'], <add> ['guidFor', 'ember-utils'], <add> ['inspect', 'ember-utils'], <add> ['makeArray', 'ember-utils'], <add> ['canInvoke', 'ember-utils'], <add> ['tryInvoke', 'ember-utils'], <add> ['wrap', 'ember-utils'], <add> ['applyStr', 'ember-utils'], <add> <ide> // ember-environment <ide> // ['ENV', 'ember-environment', 'ENV'], TODO: fix this, its failing because we are hitting the getter <ide> <ide> // container <del> ['getOwner', 'container', 'getOwner'], <del> ['setOwner', 'container', 'setOwner'], <ide> ['Registry', 'container', 'Registry'], <ide> ['Container', 'container', 'Container'], <ide> <ide> QUnit.module('ember reexports'); <ide> ['warn', 'ember-metal'], <ide> ['debug', 'ember-metal'], <ide> ['runInDebug', 'ember-metal'], <del> // ['assign', 'ember-metal'], TODO: fix this test, we use `Object.assign` if present <ide> ['merge', 'ember-metal'], <ide> ['instrument', 'ember-metal'], <ide> ['Instrumentation.instrument', 'ember-metal', 'instrument'], <ide> ['Instrumentation.subscribe', 'ember-metal', 'instrumentationSubscribe'], <ide> ['Instrumentation.unsubscribe', 'ember-metal', 'instrumentationUnsubscribe'], <ide> ['Instrumentation.reset', 'ember-metal', 'instrumentationReset'], <del> ['generateGuid', 'ember-metal'], <del> ['GUID_KEY', 'ember-metal'], <del> ['guidFor', 'ember-metal'], <del> ['inspect', 'ember-metal'], <del> ['makeArray', 'ember-metal'], <del> ['canInvoke', 'ember-metal'], <del> ['tryInvoke', 'ember-metal'], <del> ['wrap', 'ember-metal'], <del> ['applyStr', 'ember-metal'], <del> ['uuid', 'ember-metal'], <ide> ['testing', 'ember-metal', { get: 'isTesting', set: 'setTesting' }], <ide> ['onerror', 'ember-metal', { get: 'getOnerror', set: 'setOnerror' }], <ide> // ['create'], TODO: figure out what to do here
10
Ruby
Ruby
add examples to collectionassociation#concat
10d375efaa85cbfab11def8ddff7069b18da7064
<ide><path>activerecord/lib/active_record/associations/collection_association.rb <ide> def create!(attributes = {}, options = {}, &block) <ide> create_record(attributes, options, true, &block) <ide> end <ide> <del> # Add +records+ to this association. Returns +self+ so method calls may be chained. <del> # Since << flattens its argument list and inserts each record, +push+ and +concat+ behave identically. <add> # Add +records+ to this association. Returns +self+ so method calls may <add> # be chained. Since << flattens its argument list and inserts each record, <add> # +push+ and +concat+ behave identically. <add> # <add> # class Person < ActiveRecord::Base <add> # pets :has_many <add> # end <add> # <add> # person.pets << Person.new(name: 'Nemo') <add> # person.pets.concat(Person.new(name: 'Droopy')) <add> # person.pets.push(Person.new(name: 'Ren')) <add> # <add> # person.pets # => [#<Pet name: "Nemo">, #<Pet name: "Droopy">, #<Pet name: "Ren">] <ide> def concat(*records) <ide> load_target if owner.new_record? <ide> <ide> def transaction(*args) <ide> end <ide> end <ide> <del> # Remove all records from this association <add> # Remove all records from this association. <ide> # <ide> # See delete for more info. <ide> def delete_all
1
Text
Text
add example to test doc for clarity
fa3eefcb83c35a804a612a030313d6e2906038b6
<ide><path>BUILDING.md <ide> If you want to run the linter without running tests, use <ide> `make lint`/`vcbuild lint`. It will run both JavaScript linting and <ide> C++ linting. <ide> <del>If you are updating tests and just want to run a single test to check it: <add>If you are updating tests and want to run tests in a single test file <add>(e.g. `test/parallel/test-stream2-transform.js`): <ide> <ide> ```text <del>$ python tools/test.py -J --mode=release parallel/test-stream2-transform <add>$ python tools/test.py parallel/test-stream2-transform.js <ide> ``` <ide> <ide> You can execute the entire suite of tests for a given subsystem
1
Ruby
Ruby
remove useless conditional
ab0703eb59d42e2572a9cffbda5a63d5780f6ed4
<ide><path>actionpack/lib/action_controller/metal/head.rb <ide> def head(status, options = {}) <ide> <ide> if include_content?(self.response_code) <ide> self.content_type = content_type || (Mime[formats.first] if formats) <del> self.response.charset = false if self.response <add> self.response.charset = false <ide> end <ide> <ide> true
1
Text
Text
remove bug template for guides
2b7e41d3557d5e48176af6d21eabd7093fb8c3e0
<ide><path>.github/ISSUE_TEMPLATE/bug-report--issues-with-guide-articles.md <del>--- <del>name: 'Bug Report: Issues with Guide articles' <del>about: Reporting issue with a guide article, broken links, images, or content related <del> <del>--- <del> <del><!-- <del>NOTE: If you're reporting a security issue, don't create a GitHub issue. Instead, email [email protected]. We will look into it immediately. <del>--> <del>**Describe your problem and how to reproduce it:** <del> <del> <del>**Add a Link to the page with the problem:** <del> <del> <del>**Tell us about your browser and operating system:** <del>* Browser Name: <del>* Browser Version: <del>* Operating System: <del> <del> <del>**If possible, add a screenshot here (you can drag and drop, png, jpg, gif, etc. in this box):**
1
Ruby
Ruby
add more examples in performance script
61bacc4adaf1ed423ef4e4ca69b6ca90075d9ec3
<ide><path>activerecord/examples/performance.rb <ide> def self.feel(exhibits) exhibits.each { |e| e.feel } end <ide> ar { Exhibit.transaction { Exhibit.new } } <ide> end <ide> <add> report 'Model.find(id)' do <add> id = Exhibit.first.id <add> ar { Exhibit.find(id) } <add> end <add> <add> report 'Model.find_by_sql' do <add> ar { Exhibit.find_by_sql("SELECT * FROM exhibits WHERE id = #{(rand * 1000 + 1).to_i}").first } <add> end <add> <add> report 'Model.log', (TIMES * 10) do <add> ar { Exhibit.connection.send(:log, "hello", "world") {} } <add> end <add> <add> report 'AR.execute(query)', (TIMES / 2) do <add> ar { ActiveRecord::Base.connection.execute("Select * from exhibits where id = #{(rand * 1000 + 1).to_i}") } <add> end <add> <ide> summary 'Total' <ide> end <ide>
1
Text
Text
remove whitespace to test solution
db6d97142a450d7ece237e814a1c49292abf9799
<ide><path>curriculum/challenges/english/01-responsive-web-design/basic-html-and-html5/headline-with-the-h2-element.english.md <ide> tests: <ide> ## Solution <ide> <ide> <section id='solution'> <del> <add> <ide> ```html <ide> <h1>Hello World</h1> <ide> <h2>CatPhotoApp</h2>
1
Text
Text
add @rlr for thanks!
e4144b5b674cc8849c248727a09b82b82d1a01c9
<ide><path>docs/topics/credits.md <ide> The following people have helped make REST framework great. <ide> * Kevin Brown - [kevin-brown] <ide> * Rodrigo Martell - [coderigo] <ide> * James Rutherford - [jimr] <add>* ricky rosario - [rlr] <ide> <ide> Many thanks to everyone who's contributed to the project. <ide> <ide> You can also contact [@_tomchristie][twitter] directly on twitter. <ide> [willkg]: https://github.com/willkg <ide> [kevin-brown]: https://github.com/kevin-brown <ide> [jimr]: https://github.com/jimr <add>[rlr]: https://github.com/rlr
1
Ruby
Ruby
do relocation check while preparing bottle
36701a89bad15e02290e71da175e84868329edd9
<ide><path>Library/Homebrew/cmd/bottle.rb <ide> def bottle_formula f <ide> sha1 = nil <ide> <ide> prefix = HOMEBREW_PREFIX.to_s <del> tmp_prefix = '/tmp' <ide> cellar = HOMEBREW_CELLAR.to_s <del> tmp_cellar = '/tmp/Cellar' <ide> <ide> output = nil <ide> <ide> HOMEBREW_CELLAR.cd do <ide> ohai "Bottling #{filename}..." <ide> <ide> keg = Keg.new(f.prefix) <add> relocatable = false <ide> <ide> keg.lock do <ide> begin <ide> def bottle_formula f <ide> # Use gzip, faster to compress than bzip2, faster to uncompress than bzip2 <ide> # or an uncompressed tarball (and more bandwidth friendly). <ide> safe_system 'tar', 'czf', bottle_path, "#{f.name}/#{f.version}" <add> <add> if File.size?(bottle_path) > 1*1024*1024 <add> ohai "Detecting if #{filename} is relocatable..." <add> end <add> <add> if prefix == '/usr/local' <add> prefix_check = HOMEBREW_PREFIX/'opt' <add> else <add> prefix_check = HOMEBREW_PREFIX <add> end <add> <add> relocatable = !keg_contains(prefix_check, keg) <add> relocatable = !keg_contains(HOMEBREW_CELLAR, keg) if relocatable <ide> ensure <ide> keg.relocate_install_names Keg::PREFIX_PLACEHOLDER, prefix, <ide> Keg::CELLAR_PLACEHOLDER, cellar, :keg_only => f.keg_only? <ide> end <ide> end <ide> <ide> sha1 = bottle_path.sha1 <del> relocatable = false <del> <del> if File.size?(bottle_path) > 1*1024*1024 <del> ohai "Detecting if #{filename} is relocatable..." <del> end <del> <del> keg.lock do <del> # Relocate bottle library references before testing for built-in <del> # references to the Cellar e.g. Qt's QMake annoyingly does this. <del> keg.relocate_install_names prefix, tmp_prefix, cellar, tmp_cellar, :keg_only => f.keg_only? <del> <del> if prefix == '/usr/local' <del> prefix_check = HOMEBREW_PREFIX/'opt' <del> else <del> prefix_check = HOMEBREW_PREFIX <del> end <del> <del> relocatable = !keg_contains(prefix_check, keg) <del> relocatable = !keg_contains(HOMEBREW_CELLAR, keg) if relocatable <del> <del> # And do the same thing in reverse to change the library references <del> # back to how they were. <del> keg.relocate_install_names tmp_prefix, prefix, tmp_cellar, cellar <del> end <ide> <ide> bottle = Bottle.new <ide> bottle.prefix HOMEBREW_PREFIX
1
Ruby
Ruby
add collectionassociation hierarchy
e66c0fc04967a122cfec656e5473a57ab0223183
<ide><path>activerecord/lib/active_record/associations/collection_association.rb <ide> module Associations <ide> # <ide> # CollectionAssociation is an abstract class that provides common stuff to <ide> # ease the implementation of association proxies that represent <del> # collections. See the class hierarchy in AssociationProxy. <add> # collections. See the class hierarchy in AssociationProxy <add> # <add> # CollectionAssociation: <add> # HasAndBelongsToManyAssociation => has_and_belongs_to_many <add> # HasManyAssociation => has_many <add> # HasManyThroughAssociation + ThroughAssociation => has_many :through <ide> # <ide> # You need to be careful with assumptions regarding the target: The proxy <ide> # does not fetch records from the database until it needs them, but new <ide> def uniq(collection = load_target) <ide> # an ActiveRecord::AssociationTypeMismatch error: <ide> # <ide> # person.pets.replace(["doo", "ggie", "gaga"]) <del> # #=> ActiveRecord::AssociationTypeMismatch: Pet expected, got String <add> # # => ActiveRecord::AssociationTypeMismatch: Pet expected, got String <ide> def replace(other_array) <ide> other_array.each { |val| raise_on_type_mismatch(val) } <ide> original_target = load_target.dup
1
PHP
PHP
fix cs errors
f5bd76a784f1fb0b9a3c1f9ee16d8f52a0d7376c
<ide><path>tests/TestCase/View/Widget/DateTimeWidgetTest.php <ide> use Cake\TestSuite\TestCase; <ide> use Cake\View\StringTemplate; <ide> use Cake\View\Widget\DateTimeWidget; <del>use Cake\View\Widget\SelectBoxWidget; <ide> <ide> /** <ide> * DateTimeWidget test case <ide> public function testTimezoneOption() <ide> { <ide> $result = $this->DateTime->render([ <ide> 'val' => '2019-02-03 10:00:00', <del> 'timezone' => 'Asia/Kolkata' <add> 'timezone' => 'Asia/Kolkata', <ide> ], $this->context); <ide> $expected = [ <ide> 'input' => [ <ide> 'type' => 'datetime-local', <ide> 'name' => '', <del> 'value' => '2019-02-03T15:30:00' <add> 'value' => '2019-02-03T15:30:00', <ide> ], <ide> ]; <ide> $this->assertHtml($expected, $result);
1
Java
Java
provide rich type information to conversionservice
8c7658144284f2f47124c6ac8131f53320091551
<ide><path>spring-web-reactive/src/main/java/org/springframework/core/convert/support/PublisherToFluxConverter.java <del>/* <del> * Copyright 2002-2015 the original author or authors. <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> */ <del> <del>package org.springframework.core.convert.support; <del> <del>import java.util.LinkedHashSet; <del>import java.util.Set; <del> <del>import org.reactivestreams.Publisher; <del>import reactor.core.publisher.Flux; <del> <del>import org.springframework.core.convert.TypeDescriptor; <del>import org.springframework.core.convert.converter.GenericConverter; <del> <del>/** <del> * @author Sebastien Deleuze <del> */ <del>public class PublisherToFluxConverter implements GenericConverter { <del> <del> @Override <del> public Set<ConvertiblePair> getConvertibleTypes() { <del> Set<ConvertiblePair> pairs = new LinkedHashSet<>(); <del> pairs.add(new ConvertiblePair(Publisher.class, Flux.class)); <del> return pairs; <del> } <del> <del> @Override <del> public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { <del> if (source == null) { <del> return null; <del> } <del> else if (Publisher.class.isAssignableFrom(sourceType.getType())) { <del> return Flux.from((Publisher)source); <del> } <del> return null; <del> } <del> <del>} <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/config/WebReactiveConfiguration.java <ide> import org.springframework.context.ApplicationContextAware; <ide> import org.springframework.context.annotation.Bean; <ide> import org.springframework.context.annotation.Configuration; <del>import org.springframework.core.codec.Decoder; <del>import org.springframework.core.codec.Encoder; <ide> import org.springframework.core.codec.ByteBufferDecoder; <ide> import org.springframework.core.codec.ByteBufferEncoder; <del>import org.springframework.core.convert.support.PublisherToFluxConverter; <del>import org.springframework.http.codec.json.JacksonJsonDecoder; <del>import org.springframework.http.codec.json.JacksonJsonEncoder; <del>import org.springframework.http.codec.xml.Jaxb2Decoder; <del>import org.springframework.http.codec.xml.Jaxb2Encoder; <add>import org.springframework.core.codec.Decoder; <add>import org.springframework.core.codec.Encoder; <ide> import org.springframework.core.codec.StringDecoder; <ide> import org.springframework.core.codec.StringEncoder; <ide> import org.springframework.core.convert.converter.Converter; <del>import org.springframework.core.convert.converter.ConverterRegistry; <del>import org.springframework.core.convert.support.GenericConversionService; <ide> import org.springframework.core.convert.support.MonoToCompletableFutureConverter; <ide> import org.springframework.core.convert.support.ReactorToRxJava1Converter; <ide> import org.springframework.format.Formatter; <add>import org.springframework.format.FormatterRegistry; <add>import org.springframework.format.support.DefaultFormattingConversionService; <add>import org.springframework.format.support.FormattingConversionService; <ide> import org.springframework.http.MediaType; <ide> import org.springframework.http.codec.SseEventEncoder; <add>import org.springframework.http.codec.json.JacksonJsonDecoder; <add>import org.springframework.http.codec.json.JacksonJsonEncoder; <add>import org.springframework.http.codec.xml.Jaxb2Decoder; <add>import org.springframework.http.codec.xml.Jaxb2Encoder; <ide> import org.springframework.http.converter.reactive.CodecHttpMessageConverter; <ide> import org.springframework.http.converter.reactive.HttpMessageConverter; <ide> import org.springframework.http.converter.reactive.ResourceHttpMessageConverter; <ide> private static <T> HttpMessageConverter<T> converter(Encoder<T> encoder, Decoder <ide> protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) { <ide> } <ide> <del> // TODO: switch to DefaultFormattingConversionService <del> <ide> @Bean <del> public GenericConversionService mvcConversionService() { <del> GenericConversionService service = new GenericConversionService(); <add> public FormattingConversionService mvcConversionService() { <add> FormattingConversionService service = new DefaultFormattingConversionService(); <ide> addFormatters(service); <ide> return service; <ide> } <ide> <del> // TODO: switch to FormatterRegistry <del> <ide> /** <ide> * Override to add custom {@link Converter}s and {@link Formatter}s. <ide> * <p>By default this method method registers: <ide> public GenericConversionService mvcConversionService() { <ide> * <li>{@link ReactorToRxJava1Converter} <ide> * </ul> <ide> */ <del> protected void addFormatters(ConverterRegistry registry) { <add> protected void addFormatters(FormatterRegistry registry) { <ide> registry.addConverter(new MonoToCompletableFutureConverter()); <del> registry.addConverter(new PublisherToFluxConverter()); <ide> if (DependencyUtils.hasRxJava1()) { <ide> registry.addConverter(new ReactorToRxJava1Converter()); <ide> } <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/result/SimpleResultHandler.java <ide> <ide> import java.util.Optional; <ide> <add>import org.reactivestreams.Publisher; <ide> import reactor.core.publisher.Flux; <ide> import reactor.core.publisher.Mono; <ide> <ide> import org.springframework.core.Ordered; <ide> import org.springframework.core.ResolvableType; <ide> import org.springframework.core.convert.ConversionService; <add>import org.springframework.core.convert.TypeDescriptor; <ide> import org.springframework.util.Assert; <ide> import org.springframework.web.reactive.HandlerResult; <ide> import org.springframework.web.reactive.HandlerResultHandler; <ide> */ <ide> public class SimpleResultHandler implements Ordered, HandlerResultHandler { <ide> <add> protected static final TypeDescriptor MONO_TYPE = TypeDescriptor.valueOf(Mono.class); <add> <add> protected static final TypeDescriptor FLUX_TYPE = TypeDescriptor.valueOf(Flux.class); <add> <add> <ide> private ConversionService conversionService; <ide> <ide> private int order = Ordered.LOWEST_PRECEDENCE; <ide> public boolean supports(HandlerResult result) { <ide> if (Void.TYPE.equals(type.getRawClass())) { <ide> return true; <ide> } <del> if (getConversionService().canConvert(type.getRawClass(), Mono.class) || <del> getConversionService().canConvert(type.getRawClass(), Flux.class)) { <add> TypeDescriptor source = new TypeDescriptor(result.getReturnTypeSource()); <add> if (Publisher.class.isAssignableFrom(type.getRawClass()) || <add> canConvert(source, MONO_TYPE) || canConvert(source, FLUX_TYPE)) { <ide> Class<?> clazz = result.getReturnType().getGeneric(0).getRawClass(); <ide> return Void.class.equals(clazz); <ide> } <ide> return false; <ide> } <ide> <add> private boolean canConvert(TypeDescriptor source, TypeDescriptor target) { <add> return getConversionService().canConvert(source, target); <add> } <add> <ide> @SuppressWarnings("unchecked") <ide> @Override <ide> public Mono<Void> handleResult(ServerWebExchange exchange, HandlerResult result) { <ide> Optional<Object> optional = result.getReturnValue(); <ide> if (!optional.isPresent()) { <ide> return Mono.empty(); <ide> } <del> <del> Object returnValue = optional.get(); <del> if (returnValue instanceof Mono) { <del> return (Mono<Void>) returnValue; <del> } <del> <del> ResolvableType returnType = result.getReturnType(); <del> if (getConversionService().canConvert(returnType.getRawClass(), Mono.class)) { <del> return this.conversionService.convert(returnValue, Mono.class); <del> } <del> else { <del> return this.conversionService.convert(returnValue, Flux.class).single(); <add> Object value = optional.get(); <add> if (Publisher.class.isAssignableFrom(result.getReturnType().getRawClass())) { <add> return Mono.from((Publisher<?>) value).then(); <ide> } <add> TypeDescriptor source = new TypeDescriptor(result.getReturnTypeSource()); <add> return canConvert(source, MONO_TYPE) ? <add> ((Mono<Void>) getConversionService().convert(value, source, MONO_TYPE)) : <add> ((Flux<Void>) getConversionService().convert(value, source, FLUX_TYPE)).single(); <ide> } <ide> <ide> } <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/result/method/annotation/AbstractMessageConverterResultHandler.java <ide> import reactor.core.publisher.Flux; <ide> import reactor.core.publisher.Mono; <ide> <add>import org.springframework.core.MethodParameter; <ide> import org.springframework.core.ResolvableType; <ide> import org.springframework.core.convert.ConversionService; <add>import org.springframework.core.convert.TypeDescriptor; <ide> import org.springframework.http.MediaType; <ide> import org.springframework.http.converter.reactive.HttpMessageConverter; <ide> import org.springframework.http.server.reactive.ServerHttpResponse; <ide> */ <ide> public abstract class AbstractMessageConverterResultHandler extends ContentNegotiatingResultHandlerSupport { <ide> <add> protected static final TypeDescriptor MONO_TYPE = TypeDescriptor.valueOf(Mono.class); <add> <add> protected static final TypeDescriptor FLUX_TYPE = TypeDescriptor.valueOf(Flux.class); <add> <add> <ide> private final List<HttpMessageConverter<?>> messageConverters; <ide> <ide> <ide> public List<HttpMessageConverter<?>> getMessageConverters() { <ide> <ide> <ide> @SuppressWarnings("unchecked") <del> protected Mono<Void> writeBody(ServerWebExchange exchange, Object body, ResolvableType bodyType) { <del> <del> boolean convertToFlux = getConversionService().canConvert(bodyType.getRawClass(), Flux.class); <del> boolean convertToMono = getConversionService().canConvert(bodyType.getRawClass(), Mono.class); <add> protected Mono<Void> writeBody(ServerWebExchange exchange, Object body, <add> ResolvableType bodyType, MethodParameter bodyTypeParameter) { <ide> <del> ResolvableType elementType = convertToFlux || convertToMono ? bodyType.getGeneric(0) : bodyType; <add> Publisher<?> publisher = null; <add> ResolvableType elementType; <ide> <del> Publisher<?> publisher; <del> if (body == null) { <del> publisher = Mono.empty(); <add> if (Publisher.class.isAssignableFrom(bodyType.getRawClass())) { <add> publisher = (Publisher<?>) body; <ide> } <del> else if (convertToMono) { <del> publisher = getConversionService().convert(body, Mono.class); <add> else { <add> TypeDescriptor descriptor = new TypeDescriptor(bodyTypeParameter); <add> if (getConversionService().canConvert(descriptor, MONO_TYPE)) { <add> publisher = (Publisher<?>) getConversionService().convert(body, descriptor, MONO_TYPE); <add> } <add> else if (getConversionService().canConvert(descriptor, FLUX_TYPE)) { <add> publisher = (Publisher<?>) getConversionService().convert(body, descriptor, FLUX_TYPE); <add> } <ide> } <del> else if (convertToFlux) { <del> publisher = getConversionService().convert(body, Flux.class); <add> <add> if (publisher != null) { <add> elementType = bodyType.getGeneric(0); <ide> } <ide> else { <del> publisher = Mono.just(body); <add> elementType = bodyType; <add> publisher = Mono.justOrEmpty(body); <ide> } <ide> <del> if (Void.class.equals(elementType.getRawClass())) { <add> if (void.class == elementType.getRawClass() || Void.class == elementType.getRawClass()) { <ide> return Mono.from((Publisher<Void>) publisher); <ide> } <ide> <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/result/method/annotation/RequestBodyArgumentResolver.java <ide> import org.springframework.core.ResolvableType; <ide> import org.springframework.core.annotation.AnnotationUtils; <ide> import org.springframework.core.convert.ConversionService; <add>import org.springframework.core.convert.TypeDescriptor; <ide> import org.springframework.http.MediaType; <ide> import org.springframework.http.converter.reactive.HttpMessageConverter; <ide> import org.springframework.http.server.reactive.ServerHttpRequest; <ide> */ <ide> public class RequestBodyArgumentResolver implements HandlerMethodArgumentResolver { <ide> <add> private static final TypeDescriptor MONO_TYPE = TypeDescriptor.valueOf(Mono.class); <add> <add> private static final TypeDescriptor FLUX_TYPE = TypeDescriptor.valueOf(Flux.class); <add> <add> <ide> private final List<HttpMessageConverter<?>> messageConverters; <ide> <ide> private final ConversionService conversionService; <ide> public Mono<Object> resolveArgument(MethodParameter parameter, ModelMap model, <ide> <ide> ResolvableType type = ResolvableType.forMethodParameter(parameter); <ide> <del> boolean convertFromMono = getConversionService().canConvert(Mono.class, type.getRawClass()); <del> boolean convertFromFlux = getConversionService().canConvert(Flux.class, type.getRawClass()); <add> TypeDescriptor typeDescriptor = new TypeDescriptor(parameter); <add> boolean convertFromMono = getConversionService().canConvert(MONO_TYPE, typeDescriptor); <add> boolean convertFromFlux = getConversionService().canConvert(FLUX_TYPE, typeDescriptor); <ide> <ide> ResolvableType elementType = convertFromMono || convertFromFlux ? type.getGeneric(0) : type; <ide> <ide> public Mono<Object> resolveArgument(MethodParameter parameter, ModelMap model, <ide> if (this.validator != null) { <ide> flux = flux.map(applyValidationIfApplicable(parameter)); <ide> } <del> return Mono.just(this.conversionService.convert(flux, type.getRawClass())); <add> return Mono.just(getConversionService().convert(flux, FLUX_TYPE, typeDescriptor)); <ide> } <ide> else { <ide> Mono<?> mono = converter.readOne(elementType, request); <ide> public Mono<Object> resolveArgument(MethodParameter parameter, ModelMap model, <ide> if (!convertFromMono) { <ide> return mono.map(value-> value); // TODO: MonoToObjectConverter <ide> } <del> return Mono.just(this.conversionService.convert(mono, type.getRawClass())); <add> return Mono.just(getConversionService().convert(mono, MONO_TYPE, typeDescriptor)); <ide> } <ide> } <ide> } <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/result/method/annotation/ResponseBodyResultHandler.java <ide> else if (getConversionService().canConvert(returnType.getRawClass(), Mono.class) <ide> public Mono<Void> handleResult(ServerWebExchange exchange, HandlerResult result) { <ide> Object body = result.getReturnValue().orElse(null); <ide> ResolvableType bodyType = result.getReturnType(); <del> return writeBody(exchange, body, bodyType); <add> MethodParameter bodyTypeParameter = result.getReturnTypeSource(); <add> return writeBody(exchange, body, bodyType, bodyTypeParameter); <ide> } <ide> <ide> } <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/result/method/annotation/ResponseEntityResultHandler.java <ide> <ide> import reactor.core.publisher.Mono; <ide> <add>import org.springframework.core.MethodParameter; <ide> import org.springframework.core.ResolvableType; <ide> import org.springframework.core.convert.ConversionService; <ide> import org.springframework.http.HttpEntity; <ide> public boolean supports(HandlerResult result) { <ide> else if (getConversionService().canConvert(returnType.getRawClass(), Mono.class)) { <ide> ResolvableType genericType = result.getReturnType().getGeneric(0); <ide> return isSupportedType(genericType); <del> <ide> } <ide> return false; <ide> } <ide> private boolean isSupportedType(ResolvableType returnType) { <ide> public Mono<Void> handleResult(ServerWebExchange exchange, HandlerResult result) { <ide> <ide> ResolvableType returnType = result.getReturnType(); <del> Mono<?> returnValueMono; <add> <ide> ResolvableType bodyType; <add> MethodParameter bodyTypeParameter; <ide> <add> Mono<?> returnValueMono; <ide> Optional<Object> optional = result.getReturnValue(); <add> <ide> if (optional.isPresent() && getConversionService().canConvert(returnType.getRawClass(), Mono.class)) { <ide> returnValueMono = getConversionService().convert(optional.get(), Mono.class); <del> bodyType = returnType.getGeneric(0).getGeneric(0); <add> bodyType = returnType.getGeneric(0, 0); <add> bodyTypeParameter = new MethodParameter(result.getReturnTypeSource()); <add> bodyTypeParameter.increaseNestingLevel(); <add> bodyTypeParameter.increaseNestingLevel(); <ide> } <ide> else { <ide> returnValueMono = Mono.justOrEmpty(optional); <ide> bodyType = returnType.getGeneric(0); <add> bodyTypeParameter = new MethodParameter(result.getReturnTypeSource()); <add> bodyTypeParameter.increaseNestingLevel(); <ide> } <ide> <ide> return returnValueMono.then(returnValue -> { <ide> public Mono<Void> handleResult(ServerWebExchange exchange, HandlerResult result) <ide> .forEach(entry -> responseHeaders.put(entry.getKey(), entry.getValue())); <ide> } <ide> <del> return writeBody(exchange, httpEntity.getBody(), bodyType); <add> return writeBody(exchange, httpEntity.getBody(), bodyType, bodyTypeParameter); <ide> }); <ide> } <ide> <ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/result/SimpleResultHandlerTests.java <ide> <ide> package org.springframework.web.reactive.result; <ide> <add>import java.util.List; <ide> import java.util.concurrent.CompletableFuture; <ide> <ide> import org.junit.Before; <ide> <ide> import org.springframework.core.MethodParameter; <ide> import org.springframework.core.ResolvableType; <del>import org.springframework.core.convert.support.GenericConversionService; <ide> import org.springframework.core.convert.support.MonoToCompletableFutureConverter; <del>import org.springframework.core.convert.support.PublisherToFluxConverter; <ide> import org.springframework.core.convert.support.ReactorToRxJava1Converter; <add>import org.springframework.format.support.DefaultFormattingConversionService; <add>import org.springframework.format.support.FormattingConversionService; <ide> import org.springframework.web.reactive.HandlerResult; <ide> <ide> import static org.junit.Assert.assertEquals; <ide> public class SimpleResultHandlerTests { <ide> <ide> @Before <ide> public void setUp() throws Exception { <del> GenericConversionService conversionService = new GenericConversionService(); <del> conversionService.addConverter(new MonoToCompletableFutureConverter()); <del> conversionService.addConverter(new PublisherToFluxConverter()); <del> conversionService.addConverter(new ReactorToRxJava1Converter()); <del> this.resultHandler = new SimpleResultHandler(conversionService); <add> FormattingConversionService service = new DefaultFormattingConversionService(); <add> service.addConverter(new MonoToCompletableFutureConverter()); <add> service.addConverter(new ReactorToRxJava1Converter()); <add> this.resultHandler = new SimpleResultHandler(service); <ide> } <ide> <ide> <ide> @Test <del> public void supportsWithConversionService() throws NoSuchMethodException { <add> public void supports() throws NoSuchMethodException { <ide> testSupports(ResolvableType.forClass(void.class), true); <ide> testSupports(ResolvableType.forClassWithGenerics(Publisher.class, Void.class), true); <ide> testSupports(ResolvableType.forClassWithGenerics(Flux.class, Void.class), true); <ide> public void supportsWithConversionService() throws NoSuchMethodException { <ide> testSupports(ResolvableType.forClassWithGenerics(Publisher.class, String.class), false); <ide> } <ide> <add> @Test <add> public void supportsUsesGenericTypeInformation() throws Exception { <add> testSupports(ResolvableType.forClassWithGenerics(List.class, Void.class), false); <add> } <add> <ide> private void testSupports(ResolvableType type, boolean result) { <ide> MethodParameter param = ResolvableMethod.on(TestController.class).returning(type).resolveReturnType(); <ide> HandlerResult handlerResult = new HandlerResult(new TestController(), null, param); <ide> public void voidReturn() { } <ide> <ide> public Publisher<Void> publisher() { return null; } <ide> <add> public List<Void> list() { return null; } <add> <ide> } <ide> <ide> } <ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/result/method/annotation/MessageConverterResultHandlerTests.java <ide> import reactor.core.test.TestSubscriber; <ide> import rx.Observable; <ide> <add>import org.springframework.core.MethodParameter; <ide> import org.springframework.core.ResolvableType; <ide> import org.springframework.core.codec.ByteBufferEncoder; <ide> import org.springframework.core.codec.StringEncoder; <ide> import org.springframework.core.convert.support.GenericConversionService; <ide> import org.springframework.core.convert.support.MonoToCompletableFutureConverter; <del>import org.springframework.core.convert.support.PublisherToFluxConverter; <ide> import org.springframework.core.convert.support.ReactorToRxJava1Converter; <ide> import org.springframework.core.io.ClassPathResource; <ide> import org.springframework.core.io.Resource; <ide> import org.springframework.util.ObjectUtils; <ide> import org.springframework.web.reactive.accept.RequestedContentTypeResolver; <ide> import org.springframework.web.reactive.accept.RequestedContentTypeResolverBuilder; <add>import org.springframework.web.reactive.result.ResolvableMethod; <ide> import org.springframework.web.server.ServerWebExchange; <ide> import org.springframework.web.server.adapter.DefaultServerWebExchange; <ide> import org.springframework.web.server.session.MockWebSessionManager; <ide> public void setUp() throws Exception { <ide> @Test // SPR-12894 <ide> public void useDefaultContentType() throws Exception { <ide> Resource body = new ClassPathResource("logo.png", getClass()); <del> ResolvableType bodyType = ResolvableType.forType(Resource.class); <del> this.resultHandler.writeBody(this.exchange, body, bodyType).block(Duration.ofSeconds(5)); <add> ResolvableType type = ResolvableType.forType(Resource.class); <add> this.resultHandler.writeBody(this.exchange, body, type, returnType(type)).block(Duration.ofSeconds(5)); <ide> <ide> assertEquals("image/x-png", this.response.getHeaders().getFirst("Content-Type")); <ide> } <ide> public void useDefaultCharset() throws Exception { <ide> Collections.singleton(APPLICATION_JSON)); <ide> <ide> String body = "foo"; <del> ResolvableType bodyType = ResolvableType.forType(String.class); <del> this.resultHandler.writeBody(this.exchange, body, bodyType).block(Duration.ofSeconds(5)); <add> ResolvableType type = ResolvableType.forType(String.class); <add> this.resultHandler.writeBody(this.exchange, body, type, returnType(type)).block(Duration.ofSeconds(5)); <ide> <ide> assertEquals(APPLICATION_JSON_UTF8, this.response.getHeaders().getContentType()); <ide> } <ide> <ide> @Test <ide> public void voidReturnType() throws Exception { <del> testVoidReturnType(null, ResolvableType.forType(Void.class)); <add> testVoidReturnType(null, ResolvableType.forType(void.class)); <ide> testVoidReturnType(Mono.empty(), ResolvableType.forClassWithGenerics(Mono.class, Void.class)); <ide> testVoidReturnType(Flux.empty(), ResolvableType.forClassWithGenerics(Flux.class, Void.class)); <ide> testVoidReturnType(Observable.empty(), ResolvableType.forClassWithGenerics(Observable.class, Void.class)); <ide> } <ide> <del> private void testVoidReturnType(Object body, ResolvableType bodyType) { <del> this.resultHandler.writeBody(this.exchange, body, bodyType).block(Duration.ofSeconds(5)); <add> private void testVoidReturnType(Object body, ResolvableType type) { <add> this.resultHandler.writeBody(this.exchange, body, type, returnType(type)).block(Duration.ofSeconds(5)); <ide> <ide> assertNull(this.response.getHeaders().get("Content-Type")); <ide> assertNull(this.response.getBody()); <ide> private void testVoidReturnType(Object body, ResolvableType bodyType) { <ide> @Test // SPR-13135 <ide> public void unsupportedReturnType() throws Exception { <ide> ByteArrayOutputStream body = new ByteArrayOutputStream(); <del> ResolvableType bodyType = ResolvableType.forType(OutputStream.class); <add> ResolvableType type = ResolvableType.forType(OutputStream.class); <ide> <ide> HttpMessageConverter<?> converter = new CodecHttpMessageConverter<>(new ByteBufferEncoder()); <del> Mono<Void> mono = createResultHandler(converter).writeBody(this.exchange, body, bodyType); <add> Mono<Void> mono = createResultHandler(converter).writeBody(this.exchange, body, type, returnType(type)); <ide> <ide> TestSubscriber.subscribe(mono).assertError(IllegalStateException.class); <ide> } <ide> <ide> @Test // SPR-12811 <ide> public void jacksonTypeOfListElement() throws Exception { <ide> List<ParentClass> body = Arrays.asList(new Foo("foo"), new Bar("bar")); <del> ResolvableType bodyType = ResolvableType.forClassWithGenerics(List.class, ParentClass.class); <del> this.resultHandler.writeBody(this.exchange, body, bodyType).block(Duration.ofSeconds(5)); <add> ResolvableType type = ResolvableType.forClassWithGenerics(List.class, ParentClass.class); <add> this.resultHandler.writeBody(this.exchange, body, type, returnType(type)).block(Duration.ofSeconds(5)); <ide> <ide> assertEquals(APPLICATION_JSON_UTF8, this.response.getHeaders().getContentType()); <ide> assertResponseBody("[{\"type\":\"foo\",\"parentProperty\":\"foo\"}," + <ide> public void jacksonTypeOfListElement() throws Exception { <ide> @Ignore <ide> public void jacksonTypeWithSubType() throws Exception { <ide> SimpleBean body = new SimpleBean(123L, "foo"); <del> ResolvableType bodyType = ResolvableType.forClass(Identifiable.class); <del> this.resultHandler.writeBody(this.exchange, body, bodyType).block(Duration.ofSeconds(5)); <add> ResolvableType type = ResolvableType.forClass(Identifiable.class); <add> this.resultHandler.writeBody(this.exchange, body, type, returnType(type)).block(Duration.ofSeconds(5)); <ide> <ide> assertEquals(APPLICATION_JSON_UTF8, this.response.getHeaders().getContentType()); <ide> assertResponseBody("{\"id\":123,\"name\":\"foo\"}"); <ide> public void jacksonTypeWithSubType() throws Exception { <ide> @Ignore <ide> public void jacksonTypeWithSubTypeOfListElement() throws Exception { <ide> List<SimpleBean> body = Arrays.asList(new SimpleBean(123L, "foo"), new SimpleBean(456L, "bar")); <del> ResolvableType bodyType = ResolvableType.forClassWithGenerics(List.class, Identifiable.class); <del> this.resultHandler.writeBody(this.exchange, body, bodyType).block(Duration.ofSeconds(5)); <add> ResolvableType type = ResolvableType.forClassWithGenerics(List.class, Identifiable.class); <add> this.resultHandler.writeBody(this.exchange, body, type, returnType(type)).block(Duration.ofSeconds(5)); <ide> <ide> assertEquals(APPLICATION_JSON_UTF8, this.response.getHeaders().getContentType()); <ide> assertResponseBody("[{\"id\":123,\"name\":\"foo\"},{\"id\":456,\"name\":\"bar\"}]"); <ide> } <ide> <ide> <add> private MethodParameter returnType(ResolvableType bodyType) { <add> return ResolvableMethod.on(TestController.class).returning(bodyType).resolveReturnType(); <add> } <add> <ide> private AbstractMessageConverterResultHandler createResultHandler(HttpMessageConverter<?>... converters) { <ide> List<HttpMessageConverter<?>> converterList; <ide> if (ObjectUtils.isEmpty(converters)) { <ide> private AbstractMessageConverterResultHandler createResultHandler(HttpMessageCon <ide> <ide> GenericConversionService service = new GenericConversionService(); <ide> service.addConverter(new MonoToCompletableFutureConverter()); <del> service.addConverter(new PublisherToFluxConverter()); <ide> service.addConverter(new ReactorToRxJava1Converter()); <ide> <ide> RequestedContentTypeResolver resolver = new RequestedContentTypeResolverBuilder().build(); <ide> public String getName() { <ide> } <ide> } <ide> <add> @SuppressWarnings("unused") <add> private static class TestController { <add> <add> Resource resource() { return null; } <add> <add> String string() { return null; } <add> <add> void voidReturn() { } <add> <add> Mono<Void> monoVoid() { return null; } <add> <add> Flux<Void> fluxVoid() { return null; } <add> <add> Observable<Void> observableVoid() { return null; } <add> <add> OutputStream outputStream() { return null; } <add> <add> List<ParentClass> listParentClass() { return null; } <add> <add> Identifiable identifiable() { return null; } <add> <add> List<Identifiable> listIdentifiable() { return null; } <add> <add> } <add> <ide> } <ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestBodyArgumentResolverTests.java <ide> import org.springframework.core.ParameterNameDiscoverer; <ide> import org.springframework.core.annotation.SynthesizingMethodParameter; <ide> import org.springframework.core.codec.Decoder; <del>import org.springframework.core.convert.support.PublisherToFluxConverter; <del>import org.springframework.http.codec.json.JacksonJsonDecoder; <ide> import org.springframework.core.codec.StringDecoder; <del>import org.springframework.core.convert.support.GenericConversionService; <ide> import org.springframework.core.convert.support.MonoToCompletableFutureConverter; <ide> import org.springframework.core.convert.support.ReactorToRxJava1Converter; <ide> import org.springframework.core.io.buffer.DataBuffer; <ide> import org.springframework.core.io.buffer.DefaultDataBufferFactory; <add>import org.springframework.format.support.DefaultFormattingConversionService; <add>import org.springframework.format.support.FormattingConversionService; <ide> import org.springframework.http.HttpMethod; <ide> import org.springframework.http.MediaType; <add>import org.springframework.http.codec.json.JacksonJsonDecoder; <ide> import org.springframework.http.converter.reactive.CodecHttpMessageConverter; <ide> import org.springframework.http.converter.reactive.HttpMessageConverter; <ide> import org.springframework.http.server.reactive.MockServerHttpRequest; <ide> public void validateFluxTestBean() throws Exception { <ide> <ide> @SuppressWarnings("unchecked") <ide> private <T> T resolveValue(String paramName, Class<T> valueType, String body) { <add> <ide> this.request.getHeaders().setContentType(MediaType.APPLICATION_JSON); <ide> this.request.writeWith(Flux.just(dataBuffer(body))); <add> <ide> Mono<Object> result = this.resolver.resolveArgument(parameter(paramName), this.model, this.exchange); <ide> Object value = result.block(Duration.ofSeconds(5)); <add> <ide> assertNotNull(value); <ide> assertTrue("Actual type: " + value.getClass(), valueType.isAssignableFrom(value.getClass())); <add> <ide> return (T) value; <ide> } <ide> <ide> @SuppressWarnings("Convert2MethodRef") <ide> private RequestBodyArgumentResolver resolver(Decoder<?>... decoders) { <add> <ide> List<HttpMessageConverter<?>> converters = new ArrayList<>(); <ide> Arrays.asList(decoders).forEach(decoder -> converters.add(new CodecHttpMessageConverter<>(decoder))); <del> GenericConversionService service = new GenericConversionService(); <add> <add> FormattingConversionService service = new DefaultFormattingConversionService(); <ide> service.addConverter(new MonoToCompletableFutureConverter()); <del> service.addConverter(new PublisherToFluxConverter()); <ide> service.addConverter(new ReactorToRxJava1Converter()); <add> <ide> return new RequestBodyArgumentResolver(converters, service, new TestBeanValidator()); <ide> } <ide> <ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/result/method/annotation/ResponseBodyResultHandlerTests.java <ide> import org.springframework.core.codec.ByteBufferEncoder; <ide> import org.springframework.core.codec.StringEncoder; <ide> import org.springframework.core.convert.support.DefaultConversionService; <del>import org.springframework.core.convert.support.GenericConversionService; <ide> import org.springframework.core.convert.support.MonoToCompletableFutureConverter; <del>import org.springframework.core.convert.support.PublisherToFluxConverter; <ide> import org.springframework.core.convert.support.ReactorToRxJava1Converter; <add>import org.springframework.format.support.DefaultFormattingConversionService; <add>import org.springframework.format.support.FormattingConversionService; <ide> import org.springframework.http.HttpMethod; <ide> import org.springframework.http.ResponseEntity; <ide> import org.springframework.http.codec.json.JacksonJsonEncoder; <ide> private ResponseBodyResultHandler createHandler(HttpMessageConverter<?>... conve <ide> else { <ide> converterList = Arrays.asList(converters); <ide> } <del> GenericConversionService service = new GenericConversionService(); <add> FormattingConversionService service = new DefaultFormattingConversionService(); <ide> service.addConverter(new MonoToCompletableFutureConverter()); <del> service.addConverter(new PublisherToFluxConverter()); <ide> service.addConverter(new ReactorToRxJava1Converter()); <ide> RequestedContentTypeResolver resolver = new RequestedContentTypeResolverBuilder().build(); <ide> <ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/result/method/annotation/ResponseEntityResultHandlerTests.java <ide> import org.springframework.core.ResolvableType; <ide> import org.springframework.core.codec.ByteBufferEncoder; <ide> import org.springframework.core.codec.StringEncoder; <del>import org.springframework.core.convert.support.GenericConversionService; <ide> import org.springframework.core.convert.support.MonoToCompletableFutureConverter; <del>import org.springframework.core.convert.support.PublisherToFluxConverter; <ide> import org.springframework.core.convert.support.ReactorToRxJava1Converter; <ide> import org.springframework.core.io.buffer.support.DataBufferTestUtils; <add>import org.springframework.format.support.DefaultFormattingConversionService; <add>import org.springframework.format.support.FormattingConversionService; <ide> import org.springframework.http.HttpMethod; <ide> import org.springframework.http.HttpStatus; <ide> import org.springframework.http.ResponseEntity; <ide> private ResponseEntityResultHandler createHandler(HttpMessageConverter<?>... con <ide> else { <ide> converterList = Arrays.asList(converters); <ide> } <del> GenericConversionService service = new GenericConversionService(); <add> FormattingConversionService service = new DefaultFormattingConversionService(); <ide> service.addConverter(new MonoToCompletableFutureConverter()); <del> service.addConverter(new PublisherToFluxConverter()); <ide> service.addConverter(new ReactorToRxJava1Converter()); <ide> <ide> <ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/result/view/ViewResolutionResultHandlerTests.java <ide> import org.springframework.core.MethodParameter; <ide> import org.springframework.core.Ordered; <ide> import org.springframework.core.ResolvableType; <del>import org.springframework.core.convert.support.ConfigurableConversionService; <del>import org.springframework.core.convert.support.DefaultConversionService; <del>import org.springframework.core.convert.support.PublisherToFluxConverter; <add>import org.springframework.core.convert.support.MonoToCompletableFutureConverter; <ide> import org.springframework.core.convert.support.ReactorToRxJava1Converter; <ide> import org.springframework.core.io.buffer.DataBuffer; <ide> import org.springframework.core.io.buffer.DefaultDataBufferFactory; <ide> import org.springframework.core.io.buffer.support.DataBufferTestUtils; <add>import org.springframework.format.support.DefaultFormattingConversionService; <add>import org.springframework.format.support.FormattingConversionService; <ide> import org.springframework.http.HttpMethod; <ide> import org.springframework.http.MediaType; <ide> import org.springframework.http.server.reactive.MockServerHttpRequest; <ide> private ViewResolutionResultHandler createResultHandler(ViewResolver... resolver <ide> } <ide> <ide> private ViewResolutionResultHandler createResultHandler(List<View> defaultViews, ViewResolver... resolvers) { <del> ConfigurableConversionService service = new DefaultConversionService(); <add> <add> FormattingConversionService service = new DefaultFormattingConversionService(); <add> service.addConverter(new MonoToCompletableFutureConverter()); <ide> service.addConverter(new ReactorToRxJava1Converter()); <del> service.addConverter(new PublisherToFluxConverter()); <ide> List<ViewResolver> resolverList = Arrays.asList(resolvers); <add> <ide> ViewResolutionResultHandler handler = new ViewResolutionResultHandler(resolverList, service); <ide> handler.setDefaultViews(defaultViews); <ide> return handler;
13
Text
Text
improve text for console constructor
c3a997038c0e0c94801a6774bb2d374b7e981894
<ide><path>doc/api/console.md <ide> const { Console } = console; <ide> * `stdout` {Writable} <ide> * `stderr` {Writable} <ide> <del>Creates a new `Console` by passing one or two writable stream instances. <del>`stdout` is a writable stream to print log or info output. `stderr` <del>is used for warning or error output. If `stderr` is not passed, warning and error <del>output will be sent to `stdout`. <add>Creates a new `Console` with one or two writable stream instances. `stdout` is a <add>writable stream to print log or info output. `stderr` is used for warning or <add>error output. If `stderr` is not provided, `stdout` is used for `stderr`. <ide> <ide> ```js <ide> const output = fs.createWriteStream('./stdout.log');
1
Python
Python
return empty list if self.many==true
3c62f0efc3cff7c1d7da9f13e0b0629d963069cb
<ide><path>rest_framework/relations.py <ide> def _set_choices(self, value): <ide> <ide> def get_default_value(self): <ide> default = super(RelatedField, self).get_default_value() <del> return default or \ <del> [] if self.many else None <add> if self.many and default is None: <add> return [] <add> return default <ide> <ide> ### Regular serializer stuff... <ide>
1
Text
Text
clarify lgtm process to contributors
310a1742604173ac88a052b04f0b117772ab63ff
<ide><path>CONTRIBUTING.md <ide> name and email address match your git configuration. The AUTHORS file is <ide> regenerated occasionally from the git commit history, so a mismatch may result <ide> in your changes being overwritten. <ide> <add>### Approval <add> <add>Docker maintainers use LGTM (looks good to me) in comments on the code review <add>to indicate acceptance. <add> <add>A change requires LGTMs from an absolute majority of the maintainers of each <add>component affected. For example, if a change affects docs/ and registry/, it <add>needs an absolute majority from the maintainers of docs/ AND, separately, an <add>absolute majority of the maintainers of registry <add> <add>For more details see [MAINTAINERS.md](hack/MAINTAINERS.md) <ide> <ide> ### How can I become a maintainer? <ide>
1
Mixed
Javascript
add support for async iteration
2a7432dadec08bbe7063d84f1aa4a6396807305c
<ide><path>doc/api/readline.md <ide> rl.write(null, { ctrl: true, name: 'u' }); <ide> The `rl.write()` method will write the data to the `readline` `Interface`'s <ide> `input` *as if it were provided by the user*. <ide> <add>### rl\[Symbol.asyncIterator\]() <add><!-- YAML <add>added: REPLACEME <add>--> <add> <add>> Stability: 1 - Experimental <add> <add>* Returns: {AsyncIterator} <add> <add>Create an `AsyncIterator` object that iterates through each line in the input <add>stream as a string. This method allows asynchronous iteration of <add>`readline.Interface` objects through `for`-`await`-`of` loops. <add> <add>Errors in the input stream are not forwarded. <add> <add>If the loop is terminated with `break`, `throw`, or `return`, <add>[`rl.close()`][] will be called. In other words, iterating over a <add>`readline.Interface` will always consume the input stream fully. <add> <add>A caveat with using this experimental API is that the performance is <add>currently not on par with the traditional `'line'` event API, and thus it is <add>not recommended for performance-sensitive applications. We expect this <add>situation to improve in the future. <add> <add>```js <add>async function processLineByLine() { <add> const rl = readline.createInterface({ <add> // ... <add> }); <add> <add> for await (const line of rl) { <add> // Each line in the readline input will be successively available here as <add> // `line`. <add> } <add>} <add>``` <add> <ide> ## readline.clearLine(stream, dir) <ide> <!-- YAML <ide> added: v0.7.7 <ide> rl.on('line', (line) => { <ide> <ide> ## Example: Read File Stream Line-by-Line <ide> <del>A common use case for `readline` is to consume input from a filesystem <del>[Readable][] stream one line at a time: <add>A common use case for `readline` is to consume an input file one line at a <add>time. The easiest way to do so is leveraging the [`fs.ReadStream`][] API as <add>well as a `for`-`await`-`of` loop: <ide> <ide> ```js <add>const fs = require('fs'); <ide> const readline = require('readline'); <add> <add>async function processLineByLine() { <add> const fileStream = fs.createReadStream('input.txt'); <add> <add> const rl = readline.createInterface({ <add> input: fileStream, <add> crlfDelay: Infinity <add> }); <add> // Note: we use the crlfDelay option to recognize all instances of CR LF <add> // ('\r\n') in input.txt as a single line break. <add> <add> for await (const line of rl) { <add> // Each line in input.txt will be successively available here as `line`. <add> console.log(`Line from file: ${line}`); <add> } <add>} <add> <add>processLineByLine(); <add>``` <add> <add>Alternatively, one could use the [`'line'`][] event: <add> <add>```js <ide> const fs = require('fs'); <add>const readline = require('readline'); <ide> <ide> const rl = readline.createInterface({ <ide> input: fs.createReadStream('sample.txt'), <ide> rl.on('line', (line) => { <ide> <ide> [`'SIGCONT'`]: readline.html#readline_event_sigcont <ide> [`'SIGTSTP'`]: readline.html#readline_event_sigtstp <add>[`'line'`]: #readline_event_line <add>[`fs.ReadStream`]: fs.html#fs_class_fs_readstream <ide> [`process.stdin`]: process.html#process_process_stdin <ide> [`process.stdout`]: process.html#process_process_stdout <add>[`rl.close()`]: #readline_rl_close <ide> [Readable]: stream.html#stream_readable_streams <ide> [TTY]: tty.html <ide> [Writable]: stream.html#stream_writable_streams <ide><path>lib/readline.js <ide> const { <ide> ERR_INVALID_OPT_VALUE <ide> } = require('internal/errors').codes; <ide> const { debug, inherits } = require('util'); <add>const { emitExperimentalWarning } = require('internal/util'); <ide> const { Buffer } = require('buffer'); <ide> const EventEmitter = require('events'); <ide> const { <ide> const { <ide> // Lazy load StringDecoder for startup performance. <ide> let StringDecoder; <ide> <add>// Lazy load Readable for startup performance. <add>let Readable; <add> <ide> const kHistorySize = 30; <ide> const kMincrlfDelay = 100; <ide> // \r\n, \n, or \r followed by something other than \n <ide> const lineEnding = /\r?\n|\r(?!\n)/; <ide> <add>const kLineObjectStream = Symbol('line object stream'); <add> <ide> const KEYPRESS_DECODER = Symbol('keypress-decoder'); <ide> const ESCAPE_DECODER = Symbol('escape-decoder'); <ide> <ide> function Interface(input, output, completer, terminal) { <ide> self._refreshLine(); <ide> } <ide> <add> this[kLineObjectStream] = undefined; <add> <ide> if (!this.terminal) { <ide> function onSelfCloseWithoutTerminal() { <ide> input.removeListener('data', ondata); <ide> Interface.prototype._ttyWrite = function(s, key) { <ide> } <ide> }; <ide> <add>Interface.prototype[Symbol.asyncIterator] = function() { <add> emitExperimentalWarning('readline Interface [Symbol.asyncIterator]'); <add> <add> if (this[kLineObjectStream] === undefined) { <add> if (Readable === undefined) { <add> Readable = require('stream').Readable; <add> } <add> const readable = new Readable({ <add> objectMode: true, <add> read: () => { <add> this.resume(); <add> }, <add> destroy: (err, cb) => { <add> this.off('line', lineListener); <add> this.off('close', closeListener); <add> this.close(); <add> cb(err); <add> } <add> }); <add> const lineListener = (input) => { <add> if (!readable.push(input)) { <add> this.pause(); <add> } <add> }; <add> const closeListener = () => { <add> readable.push(null); <add> }; <add> this.on('line', lineListener); <add> this.on('close', closeListener); <add> this[kLineObjectStream] = readable; <add> } <add> <add> return this[kLineObjectStream][Symbol.asyncIterator](); <add>}; <add> <ide> /** <ide> * accepts a readable Stream instance and makes it emit "keypress" events <ide> */ <ide><path>test/parallel/test-readline-async-iterators-backpressure.js <add>'use strict'; <add> <add>const common = require('../common'); <add>const assert = require('assert'); <add>const { Readable } = require('stream'); <add>const readline = require('readline'); <add> <add>const CONTENT = 'content'; <add>const TOTAL_LINES = 18; <add> <add>(async () => { <add> const readable = new Readable({ read() {} }); <add> readable.push(`${CONTENT}\n`.repeat(TOTAL_LINES)); <add> <add> const rli = readline.createInterface({ <add> input: readable, <add> crlfDelay: Infinity <add> }); <add> <add> const it = rli[Symbol.asyncIterator](); <add> const highWaterMark = it.stream.readableHighWaterMark; <add> <add> // For this test to work, we have to queue up more than the number of <add> // highWaterMark items in rli. Make sure that is the case. <add> assert(TOTAL_LINES > highWaterMark); <add> <add> let iterations = 0; <add> let readableEnded = false; <add> for await (const line of it) { <add> assert.strictEqual(readableEnded, false); <add> <add> assert.strictEqual(line, CONTENT); <add> <add> const expectedPaused = TOTAL_LINES - iterations > highWaterMark; <add> assert.strictEqual(readable.isPaused(), expectedPaused); <add> <add> iterations += 1; <add> <add> // We have to end the input stream asynchronously for back pressure to work. <add> // Only end when we have reached the final line. <add> if (iterations === TOTAL_LINES) { <add> readable.push(null); <add> readableEnded = true; <add> } <add> } <add> <add> assert.strictEqual(iterations, TOTAL_LINES); <add>})().then(common.mustCall()); <ide><path>test/parallel/test-readline-async-iterators-destroy.js <add>'use strict'; <add> <add>const common = require('../common'); <add>const fs = require('fs'); <add>const { join } = require('path'); <add>const readline = require('readline'); <add>const assert = require('assert'); <add> <add>const tmpdir = require('../common/tmpdir'); <add>tmpdir.refresh(); <add> <add>const filename = join(tmpdir.path, 'test.txt'); <add> <add>const testContents = [ <add> '', <add> '\n', <add> 'line 1', <add> 'line 1\nline 2 南越国是前203年至前111年存在于岭南地区的一个国家\nline 3\ntrailing', <add> 'line 1\nline 2\nline 3 ends with newline\n' <add>]; <add> <add>async function testSimpleDestroy() { <add> for (const fileContent of testContents) { <add> fs.writeFileSync(filename, fileContent); <add> <add> const readable = fs.createReadStream(filename); <add> const rli = readline.createInterface({ <add> input: readable, <add> crlfDelay: Infinity <add> }); <add> <add> const iteratedLines = []; <add> for await (const k of rli) { <add> iteratedLines.push(k); <add> break; <add> } <add> <add> const expectedLines = fileContent.split('\n'); <add> if (expectedLines[expectedLines.length - 1] === '') { <add> expectedLines.pop(); <add> } <add> expectedLines.splice(1); <add> <add> assert.deepStrictEqual(iteratedLines, expectedLines); <add> } <add>} <add> <add>async function testMutualDestroy() { <add> for (const fileContent of testContents) { <add> fs.writeFileSync(filename, fileContent); <add> <add> const readable = fs.createReadStream(filename); <add> const rli = readline.createInterface({ <add> input: readable, <add> crlfDelay: Infinity <add> }); <add> <add> const expectedLines = fileContent.split('\n'); <add> if (expectedLines[expectedLines.length - 1] === '') { <add> expectedLines.pop(); <add> } <add> expectedLines.splice(2); <add> <add> const iteratedLines = []; <add> for await (const k of rli) { <add> iteratedLines.push(k); <add> for await (const l of rli) { <add> iteratedLines.push(l); <add> break; <add> } <add> assert.deepStrictEqual(iteratedLines, expectedLines); <add> } <add> <add> assert.deepStrictEqual(iteratedLines, expectedLines); <add> } <add>} <add> <add>testSimpleDestroy().then(testMutualDestroy).then(common.mustCall()); <ide><path>test/parallel/test-readline-async-iterators.js <add>'use strict'; <add> <add>const common = require('../common'); <add>const fs = require('fs'); <add>const { join } = require('path'); <add>const readline = require('readline'); <add>const assert = require('assert'); <add> <add>const tmpdir = require('../common/tmpdir'); <add>tmpdir.refresh(); <add> <add>const filename = join(tmpdir.path, 'test.txt'); <add> <add>const testContents = [ <add> '', <add> '\n', <add> 'line 1', <add> 'line 1\nline 2 南越国是前203年至前111年存在于岭南地区的一个国家\nline 3\ntrailing', <add> 'line 1\nline 2\nline 3 ends with newline\n' <add>]; <add> <add>async function testSimple() { <add> for (const fileContent of testContents) { <add> fs.writeFileSync(filename, fileContent); <add> <add> const readable = fs.createReadStream(filename); <add> const rli = readline.createInterface({ <add> input: readable, <add> crlfDelay: Infinity <add> }); <add> <add> const iteratedLines = []; <add> for await (const k of rli) { <add> iteratedLines.push(k); <add> } <add> <add> const expectedLines = fileContent.split('\n'); <add> if (expectedLines[expectedLines.length - 1] === '') { <add> expectedLines.pop(); <add> } <add> assert.deepStrictEqual(iteratedLines, expectedLines); <add> assert.strictEqual(iteratedLines.join(''), fileContent.replace(/\n/gm, '')); <add> } <add>} <add> <add>async function testMutual() { <add> for (const fileContent of testContents) { <add> fs.writeFileSync(filename, fileContent); <add> <add> const readable = fs.createReadStream(filename); <add> const rli = readline.createInterface({ <add> input: readable, <add> crlfDelay: Infinity <add> }); <add> <add> const expectedLines = fileContent.split('\n'); <add> if (expectedLines[expectedLines.length - 1] === '') { <add> expectedLines.pop(); <add> } <add> const iteratedLines = []; <add> let iterated = false; <add> for await (const k of rli) { <add> // This outer loop should only iterate once. <add> assert.strictEqual(iterated, false); <add> iterated = true; <add> <add> iteratedLines.push(k); <add> for await (const l of rli) { <add> iteratedLines.push(l); <add> } <add> assert.deepStrictEqual(iteratedLines, expectedLines); <add> } <add> assert.deepStrictEqual(iteratedLines, expectedLines); <add> } <add>} <add> <add>testSimple().then(testMutual).then(common.mustCall()); <ide><path>tools/doc/type-parser.js <ide> const customTypesMap = { <ide> <ide> 'this': `${jsDocPrefix}Reference/Operators/this`, <ide> <del> 'AsyncIterator': 'https://github.com/tc39/proposal-async-iteration', <add> 'AsyncIterator': 'https://tc39.github.io/ecma262/#sec-asynciterator-interface', <ide> <ide> 'bigint': 'https://github.com/tc39/proposal-bigint', <ide>
6
Javascript
Javascript
fix short circuit of logical and and or operators
e1ecc34edd19b95d51fbcb1351b04b9876c974c1
<ide><path>src/parser.js <ide> var OPERATORS = { <ide> 'true':function(self){return true;}, <ide> 'false':function(self){return false;}, <ide> $undefined:noop, <del> '+':function(self, a,b){return (isDefined(a)?a:0)+(isDefined(b)?b:0);}, <del> '-':function(self, a,b){return (isDefined(a)?a:0)-(isDefined(b)?b:0);}, <del> '*':function(self, a,b){return a*b;}, <del> '/':function(self, a,b){return a/b;}, <del> '%':function(self, a,b){return a%b;}, <del> '^':function(self, a,b){return a^b;}, <add> '+':function(self, a,b){a=a(self); b=b(self); return (isDefined(a)?a:0)+(isDefined(b)?b:0);}, <add> '-':function(self, a,b){a=a(self); b=b(self); return (isDefined(a)?a:0)-(isDefined(b)?b:0);}, <add> '*':function(self, a,b){return a(self)*b(self);}, <add> '/':function(self, a,b){return a(self)/b(self);}, <add> '%':function(self, a,b){return a(self)%b(self);}, <add> '^':function(self, a,b){return a(self)^b(self);}, <ide> '=':noop, <del> '==':function(self, a,b){return a==b;}, <del> '!=':function(self, a,b){return a!=b;}, <del> '<':function(self, a,b){return a<b;}, <del> '>':function(self, a,b){return a>b;}, <del> '<=':function(self, a,b){return a<=b;}, <del> '>=':function(self, a,b){return a>=b;}, <del> '&&':function(self, a,b){return a&&b;}, <del> '||':function(self, a,b){return a||b;}, <del> '&':function(self, a,b){return a&b;}, <add> '==':function(self, a,b){return a(self)==b(self);}, <add> '!=':function(self, a,b){return a(self)!=b(self);}, <add> '<':function(self, a,b){return a(self)<b(self);}, <add> '>':function(self, a,b){return a(self)>b(self);}, <add> '<=':function(self, a,b){return a(self)<=b(self);}, <add> '>=':function(self, a,b){return a(self)>=b(self);}, <add> '&&':function(self, a,b){return a(self)&&b(self);}, <add> '||':function(self, a,b){return a(self)||b(self);}, <add> '&':function(self, a,b){return a(self)&b(self);}, <ide> // '|':function(self, a,b){return a|b;}, <del> '|':function(self, a,b){return b(self, a);}, <del> '!':function(self, a){return !a;} <add> '|':function(self, a,b){return b(self)(self, a(self));}, <add> '!':function(self, a){return !a(self);} <ide> }; <ide> var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'}; <ide> <ide> function parser(text, json){ <ide> <ide> function unaryFn(fn, right) { <ide> return function(self) { <del> return fn(self, right(self)); <add> return fn(self, right); <ide> }; <ide> } <ide> <ide> function binaryFn(left, fn, right) { <ide> return function(self) { <del> return fn(self, left(self), right(self)); <add> return fn(self, left, right); <ide> }; <ide> } <ide> <ide><path>test/ParserSpec.js <ide> describe('parser', function() { <ide> expect(scope.a).not.toBeDefined(); <ide> }); <ide> <del> it('should allow assignment after array dereference', function(){ <add> it('should allow assignment after array dereference', function() { <ide> scope = angular.scope(); <ide> scope.obj = [{}]; <ide> scope.$eval('obj[0].name=1'); <ide> expect(scope.obj.name).toBeUndefined(); <ide> expect(scope.obj[0].name).toEqual(1); <ide> }); <ide> <del> describe('formatter', function(){ <add> it('should short-circuit AND operator', function() { <add> var scope = angular.scope(); <add> scope.run = function() { <add> throw "IT SHOULD NOT HAVE RUN"; <add> }; <add> expect(scope.$eval('false && run()')).toBe(false); <add> }); <add> <add> it('should short-circuit OR operator', function() { <add> var scope = angular.scope(); <add> scope.run = function() { <add> throw "IT SHOULD NOT HAVE RUN"; <add> }; <add> expect(scope.$eval('true || run()')).toBe(true); <add> }); <add> <add> describe('formatter', function() { <ide> it('should return no argument function', function() { <ide> var noop = parser('noop').formatter()(); <ide> expect(noop.format(null, 'abc')).toEqual('abc'); <ide> expect(noop.parse(null, '123')).toEqual('123'); <ide> }); <ide> <del> it('should delegate arguments', function(){ <add> it('should delegate arguments', function() { <ide> angularFormatter.myArgs = { <ide> parse: function(a, b){ return [a, b]; }, <ide> format: function(a, b){ return [a, b]; }
2
Python
Python
add max_ingestion_time to druidoperator docstring
f8c31b5bf787de662f73583ee6b65dad6addf453
<ide><path>airflow/providers/apache/druid/operators/druid.py <ide> class DruidOperator(BaseOperator): <ide> :param druid_ingest_conn_id: The connection id of the Druid overlord which <ide> accepts index jobs <ide> :type druid_ingest_conn_id: str <add> :param max_ingestion_time: The maximum ingestion time before assuming the job failed <add> :type max_ingestion_time: int <ide> """ <ide> <ide> template_fields = ('json_index_file',)
1
Mixed
Go
remove types and lib packages from the engine
c7d811c8161b1acc677b15f56b02c773824dfb87
<ide><path>api/client/lib/client.go <del>package lib <del> <del>import ( <del> "crypto/tls" <del> "fmt" <del> "net" <del> "net/http" <del> "net/url" <del> "os" <del> "path/filepath" <del> "strings" <del> "time" <del>) <del> <del>// Client is the API client that performs all operations <del>// against a docker server. <del>type Client struct { <del> // proto holds the client protocol i.e. unix. <del> proto string <del> // addr holds the client address. <del> addr string <del> // basePath holds the path to prepend to the requests <del> basePath string <del> // scheme holds the scheme of the client i.e. https. <del> scheme string <del> // tlsConfig holds the tls configuration to use in hijacked requests. <del> tlsConfig *tls.Config <del> // httpClient holds the client transport instance. Exported to keep the old code running. <del> httpClient *http.Client <del> // version of the server to talk to. <del> version string <del> // custom http headers configured by users <del> customHTTPHeaders map[string]string <del>} <del> <del>// NewEnvClient initializes a new API client based on environment variables. <del>// Use DOCKER_HOST to set the url to the docker server. <del>// Use DOCKER_API_VERSION to set the version of the API to reach, leave empty for latest. <del>// Use DOCKER_CERT_PATH to load the tls certificates from. <del>// Use DOCKER_TLS_VERIFY to enable or disable TLS verification, off by default. <del>func NewEnvClient() (*Client, error) { <del> var transport *http.Transport <del> if dockerCertPath := os.Getenv("DOCKER_CERT_PATH"); dockerCertPath != "" { <del> tlsc := &tls.Config{} <del> <del> cert, err := tls.LoadX509KeyPair(filepath.Join(dockerCertPath, "cert.pem"), filepath.Join(dockerCertPath, "key.pem")) <del> if err != nil { <del> return nil, fmt.Errorf("Error loading x509 key pair: %s", err) <del> } <del> <del> tlsc.Certificates = append(tlsc.Certificates, cert) <del> tlsc.InsecureSkipVerify = os.Getenv("DOCKER_TLS_VERIFY") == "" <del> transport = &http.Transport{ <del> TLSClientConfig: tlsc, <del> } <del> } <del> <del> return NewClient(os.Getenv("DOCKER_HOST"), os.Getenv("DOCKER_API_VERSION"), transport, nil) <del>} <del> <del>// NewClient initializes a new API client for the given host and API version. <del>// It won't send any version information if the version number is empty. <del>// It uses the transport to create a new http client. <del>// It also initializes the custom http headers to add to each request. <del>func NewClient(host string, version string, transport *http.Transport, httpHeaders map[string]string) (*Client, error) { <del> var ( <del> basePath string <del> tlsConfig *tls.Config <del> scheme = "http" <del> protoAddrParts = strings.SplitN(host, "://", 2) <del> proto, addr = protoAddrParts[0], protoAddrParts[1] <del> ) <del> <del> if proto == "tcp" { <del> parsed, err := url.Parse("tcp://" + addr) <del> if err != nil { <del> return nil, err <del> } <del> addr = parsed.Host <del> basePath = parsed.Path <del> } <del> <del> transport = configureTransport(transport, proto, addr) <del> if transport.TLSClientConfig != nil { <del> scheme = "https" <del> } <del> <del> return &Client{ <del> proto: proto, <del> addr: addr, <del> basePath: basePath, <del> scheme: scheme, <del> tlsConfig: tlsConfig, <del> httpClient: &http.Client{Transport: transport}, <del> version: version, <del> customHTTPHeaders: httpHeaders, <del> }, nil <del>} <del> <del>// getAPIPath returns the versioned request path to call the api. <del>// It appends the query parameters to the path if they are not empty. <del>func (cli *Client) getAPIPath(p string, query url.Values) string { <del> var apiPath string <del> if cli.version != "" { <del> v := strings.TrimPrefix(cli.version, "v") <del> apiPath = fmt.Sprintf("%s/v%s%s", cli.basePath, v, p) <del> } else { <del> apiPath = fmt.Sprintf("%s%s", cli.basePath, p) <del> } <del> if len(query) > 0 { <del> apiPath += "?" + query.Encode() <del> } <del> return apiPath <del>} <del> <del>// ClientVersion returns the version string associated with this <del>// instance of the Client. Note that this value can be changed <del>// via the DOCKER_API_VERSION env var. <del>func (cli *Client) ClientVersion() string { <del> return cli.version <del>} <del> <del>func configureTransport(tr *http.Transport, proto, addr string) *http.Transport { <del> if tr == nil { <del> tr = &http.Transport{} <del> } <del> <del> // Why 32? See https://github.com/docker/docker/pull/8035. <del> timeout := 32 * time.Second <del> if proto == "unix" { <del> // No need for compression in local communications. <del> tr.DisableCompression = true <del> tr.Dial = func(_, _ string) (net.Conn, error) { <del> return net.DialTimeout(proto, addr, timeout) <del> } <del> } else { <del> tr.Proxy = http.ProxyFromEnvironment <del> tr.Dial = (&net.Dialer{Timeout: timeout}).Dial <del> } <del> <del> return tr <del>} <ide><path>api/client/lib/client_test.go <del>package lib <del> <del>import ( <del> "net/url" <del> "testing" <del>) <del> <del>func TestGetAPIPath(t *testing.T) { <del> cases := []struct { <del> v string <del> p string <del> q url.Values <del> e string <del> }{ <del> {"", "/containers/json", nil, "/containers/json"}, <del> {"", "/containers/json", url.Values{}, "/containers/json"}, <del> {"", "/containers/json", url.Values{"s": []string{"c"}}, "/containers/json?s=c"}, <del> {"1.22", "/containers/json", nil, "/v1.22/containers/json"}, <del> {"1.22", "/containers/json", url.Values{}, "/v1.22/containers/json"}, <del> {"1.22", "/containers/json", url.Values{"s": []string{"c"}}, "/v1.22/containers/json?s=c"}, <del> {"v1.22", "/containers/json", nil, "/v1.22/containers/json"}, <del> {"v1.22", "/containers/json", url.Values{}, "/v1.22/containers/json"}, <del> {"v1.22", "/containers/json", url.Values{"s": []string{"c"}}, "/v1.22/containers/json?s=c"}, <del> } <del> <del> for _, cs := range cases { <del> c, err := NewClient("unix:///var/run/docker.sock", cs.v, nil, nil) <del> if err != nil { <del> t.Fatal(err) <del> } <del> g := c.getAPIPath(cs.p, cs.q) <del> if g != cs.e { <del> t.Fatalf("Expected %s, got %s", cs.e, g) <del> } <del> } <del>} <ide><path>api/client/lib/container_attach.go <del>package lib <del> <del>import ( <del> "net/url" <del> <del> "github.com/docker/engine-api/types" <del>) <del> <del>// ContainerAttach attaches a connection to a container in the server. <del>// It returns a types.HijackedConnection with the hijacked connection <del>// and the a reader to get output. It's up to the called to close <del>// the hijacked connection by calling types.HijackedResponse.Close. <del>func (cli *Client) ContainerAttach(options types.ContainerAttachOptions) (types.HijackedResponse, error) { <del> query := url.Values{} <del> if options.Stream { <del> query.Set("stream", "1") <del> } <del> if options.Stdin { <del> query.Set("stdin", "1") <del> } <del> if options.Stdout { <del> query.Set("stdout", "1") <del> } <del> if options.Stderr { <del> query.Set("stderr", "1") <del> } <del> if options.DetachKeys != "" { <del> query.Set("detachKeys", options.DetachKeys) <del> } <del> <del> headers := map[string][]string{"Content-Type": {"text/plain"}} <del> return cli.postHijacked("/containers/"+options.ContainerID+"/attach", query, nil, headers) <del>} <ide><path>api/client/lib/container_commit.go <del>package lib <del> <del>import ( <del> "encoding/json" <del> "net/url" <del> <del> "github.com/docker/engine-api/types" <del>) <del> <del>// ContainerCommit applies changes into a container and creates a new tagged image. <del>func (cli *Client) ContainerCommit(options types.ContainerCommitOptions) (types.ContainerCommitResponse, error) { <del> query := url.Values{} <del> query.Set("container", options.ContainerID) <del> query.Set("repo", options.RepositoryName) <del> query.Set("tag", options.Tag) <del> query.Set("comment", options.Comment) <del> query.Set("author", options.Author) <del> for _, change := range options.Changes { <del> query.Add("changes", change) <del> } <del> if options.Pause != true { <del> query.Set("pause", "0") <del> } <del> <del> var response types.ContainerCommitResponse <del> resp, err := cli.post("/commit", query, options.Config, nil) <del> if err != nil { <del> return response, err <del> } <del> defer ensureReaderClosed(resp) <del> <del> if err := json.NewDecoder(resp.body).Decode(&response); err != nil { <del> return response, err <del> } <del> <del> return response, nil <del>} <ide><path>api/client/lib/container_create.go <del>package lib <del> <del>import ( <del> "encoding/json" <del> "net/url" <del> "strings" <del> <del> "github.com/docker/engine-api/types" <del> "github.com/docker/engine-api/types/container" <del>) <del> <del>type configWrapper struct { <del> *container.Config <del> HostConfig *container.HostConfig <del>} <del> <del>// ContainerCreate creates a new container based in the given configuration. <del>// It can be associated with a name, but it's not mandatory. <del>func (cli *Client) ContainerCreate(config *container.Config, hostConfig *container.HostConfig, containerName string) (types.ContainerCreateResponse, error) { <del> var response types.ContainerCreateResponse <del> query := url.Values{} <del> if containerName != "" { <del> query.Set("name", containerName) <del> } <del> <del> body := configWrapper{ <del> Config: config, <del> HostConfig: hostConfig, <del> } <del> <del> serverResp, err := cli.post("/containers/create", query, body, nil) <del> if err != nil { <del> if serverResp != nil && serverResp.statusCode == 404 && strings.Contains(err.Error(), config.Image) { <del> return response, imageNotFoundError{config.Image} <del> } <del> return response, err <del> } <del> <del> if serverResp.statusCode == 404 && strings.Contains(err.Error(), config.Image) { <del> return response, imageNotFoundError{config.Image} <del> } <del> <del> if err != nil { <del> return response, err <del> } <del> defer ensureReaderClosed(serverResp) <del> <del> if err := json.NewDecoder(serverResp.body).Decode(&response); err != nil { <del> return response, err <del> } <del> <del> return response, nil <del>} <ide><path>api/client/lib/container_inspect.go <del>package lib <del> <del>import ( <del> "bytes" <del> "encoding/json" <del> "io/ioutil" <del> "net/http" <del> "net/url" <del> <del> "github.com/docker/engine-api/types" <del>) <del> <del>// ContainerInspect returns the container information. <del>func (cli *Client) ContainerInspect(containerID string) (types.ContainerJSON, error) { <del> serverResp, err := cli.get("/containers/"+containerID+"/json", nil, nil) <del> if err != nil { <del> if serverResp.statusCode == http.StatusNotFound { <del> return types.ContainerJSON{}, containerNotFoundError{containerID} <del> } <del> return types.ContainerJSON{}, err <del> } <del> defer ensureReaderClosed(serverResp) <del> <del> var response types.ContainerJSON <del> err = json.NewDecoder(serverResp.body).Decode(&response) <del> return response, err <del>} <del> <del>// ContainerInspectWithRaw returns the container information and it's raw representation. <del>func (cli *Client) ContainerInspectWithRaw(containerID string, getSize bool) (types.ContainerJSON, []byte, error) { <del> query := url.Values{} <del> if getSize { <del> query.Set("size", "1") <del> } <del> serverResp, err := cli.get("/containers/"+containerID+"/json", query, nil) <del> if err != nil { <del> if serverResp.statusCode == http.StatusNotFound { <del> return types.ContainerJSON{}, nil, containerNotFoundError{containerID} <del> } <del> return types.ContainerJSON{}, nil, err <del> } <del> defer ensureReaderClosed(serverResp) <del> <del> body, err := ioutil.ReadAll(serverResp.body) <del> if err != nil { <del> return types.ContainerJSON{}, nil, err <del> } <del> <del> var response types.ContainerJSON <del> rdr := bytes.NewReader(body) <del> err = json.NewDecoder(rdr).Decode(&response) <del> return response, body, err <del>} <del> <del>func (cli *Client) containerInspectWithResponse(containerID string, query url.Values) (types.ContainerJSON, *serverResponse, error) { <del> serverResp, err := cli.get("/containers/"+containerID+"/json", nil, nil) <del> if err != nil { <del> return types.ContainerJSON{}, serverResp, err <del> } <del> <del> var response types.ContainerJSON <del> err = json.NewDecoder(serverResp.body).Decode(&response) <del> return response, serverResp, err <del>} <ide><path>api/client/lib/container_list.go <del>package lib <del> <del>import ( <del> "encoding/json" <del> "net/url" <del> "strconv" <del> <del> "github.com/docker/engine-api/types" <del> "github.com/docker/engine-api/types/filters" <del>) <del> <del>// ContainerList returns the list of containers in the docker host. <del>func (cli *Client) ContainerList(options types.ContainerListOptions) ([]types.Container, error) { <del> query := url.Values{} <del> <del> if options.All { <del> query.Set("all", "1") <del> } <del> <del> if options.Limit != -1 { <del> query.Set("limit", strconv.Itoa(options.Limit)) <del> } <del> <del> if options.Since != "" { <del> query.Set("since", options.Since) <del> } <del> <del> if options.Before != "" { <del> query.Set("before", options.Before) <del> } <del> <del> if options.Size { <del> query.Set("size", "1") <del> } <del> <del> if options.Filter.Len() > 0 { <del> filterJSON, err := filters.ToParam(options.Filter) <del> if err != nil { <del> return nil, err <del> } <del> <del> query.Set("filters", filterJSON) <del> } <del> <del> resp, err := cli.get("/containers/json", query, nil) <del> if err != nil { <del> return nil, err <del> } <del> defer ensureReaderClosed(resp) <del> <del> var containers []types.Container <del> err = json.NewDecoder(resp.body).Decode(&containers) <del> return containers, err <del>} <ide><path>api/client/lib/container_remove.go <del>package lib <del> <del>import ( <del> "net/url" <del> <del> "github.com/docker/engine-api/types" <del>) <del> <del>// ContainerRemove kills and removes a container from the docker host. <del>func (cli *Client) ContainerRemove(options types.ContainerRemoveOptions) error { <del> query := url.Values{} <del> if options.RemoveVolumes { <del> query.Set("v", "1") <del> } <del> if options.RemoveLinks { <del> query.Set("link", "1") <del> } <del> <del> if options.Force { <del> query.Set("force", "1") <del> } <del> <del> resp, err := cli.delete("/containers/"+options.ContainerID, query, nil) <del> ensureReaderClosed(resp) <del> return err <del>} <ide><path>api/client/lib/container_rename.go <del>package lib <del> <del>import "net/url" <del> <del>// ContainerRename changes the name of a given container. <del>func (cli *Client) ContainerRename(containerID, newContainerName string) error { <del> query := url.Values{} <del> query.Set("name", newContainerName) <del> resp, err := cli.post("/containers/"+containerID+"/rename", query, nil, nil) <del> ensureReaderClosed(resp) <del> return err <del>} <ide><path>api/client/lib/container_restart.go <del>package lib <del> <del>import ( <del> "net/url" <del> "strconv" <del>) <del> <del>// ContainerRestart stops and starts a container again. <del>// It makes the daemon to wait for the container to be up again for <del>// a specific amount of time, given the timeout. <del>func (cli *Client) ContainerRestart(containerID string, timeout int) error { <del> query := url.Values{} <del> query.Set("t", strconv.Itoa(timeout)) <del> resp, err := cli.post("/containers/"+containerID+"/restart", query, nil, nil) <del> ensureReaderClosed(resp) <del> return err <del>} <ide><path>api/client/lib/container_start.go <del>package lib <del> <del>// ContainerStart sends a request to the docker daemon to start a container. <del>func (cli *Client) ContainerStart(containerID string) error { <del> resp, err := cli.post("/containers/"+containerID+"/start", nil, nil, nil) <del> ensureReaderClosed(resp) <del> return err <del>} <ide><path>api/client/lib/container_stats.go <del>package lib <del> <del>import ( <del> "io" <del> "net/url" <del>) <del> <del>// ContainerStats returns near realtime stats for a given container. <del>// It's up to the caller to close the io.ReadCloser returned. <del>func (cli *Client) ContainerStats(containerID string, stream bool) (io.ReadCloser, error) { <del> query := url.Values{} <del> query.Set("stream", "0") <del> if stream { <del> query.Set("stream", "1") <del> } <del> <del> resp, err := cli.get("/containers/"+containerID+"/stats", query, nil) <del> if err != nil { <del> return nil, err <del> } <del> return resp.body, err <del>} <ide><path>api/client/lib/container_stop.go <del>package lib <del> <del>import ( <del> "net/url" <del> "strconv" <del>) <del> <del>// ContainerStop stops a container without terminating the process. <del>// The process is blocked until the container stops or the timeout expires. <del>func (cli *Client) ContainerStop(containerID string, timeout int) error { <del> query := url.Values{} <del> query.Set("t", strconv.Itoa(timeout)) <del> resp, err := cli.post("/containers/"+containerID+"/stop", query, nil, nil) <del> ensureReaderClosed(resp) <del> return err <del>} <ide><path>api/client/lib/container_top.go <del>package lib <del> <del>import ( <del> "encoding/json" <del> "net/url" <del> "strings" <del> <del> "github.com/docker/engine-api/types" <del>) <del> <del>// ContainerTop shows process information from within a container. <del>func (cli *Client) ContainerTop(containerID string, arguments []string) (types.ContainerProcessList, error) { <del> var response types.ContainerProcessList <del> query := url.Values{} <del> if len(arguments) > 0 { <del> query.Set("ps_args", strings.Join(arguments, " ")) <del> } <del> <del> resp, err := cli.get("/containers/"+containerID+"/top", query, nil) <del> if err != nil { <del> return response, err <del> } <del> defer ensureReaderClosed(resp) <del> <del> err = json.NewDecoder(resp.body).Decode(&response) <del> return response, err <del>} <ide><path>api/client/lib/container_unpause.go <del>package lib <del> <del>// ContainerUnpause resumes the process execution within a container <del>func (cli *Client) ContainerUnpause(containerID string) error { <del> resp, err := cli.post("/containers/"+containerID+"/unpause", nil, nil, nil) <del> ensureReaderClosed(resp) <del> return err <del>} <ide><path>api/client/lib/container_update.go <del>package lib <del> <del>import ( <del> "github.com/docker/engine-api/types/container" <del>) <del> <del>// ContainerUpdate updates resources of a container <del>func (cli *Client) ContainerUpdate(containerID string, hostConfig container.HostConfig) error { <del> resp, err := cli.post("/containers/"+containerID+"/update", nil, hostConfig, nil) <del> ensureReaderClosed(resp) <del> return err <del>} <ide><path>api/client/lib/copy.go <del>package lib <del> <del>import ( <del> "encoding/base64" <del> "encoding/json" <del> "fmt" <del> "io" <del> "net/http" <del> "net/url" <del> "path/filepath" <del> "strings" <del> <del> "github.com/docker/engine-api/types" <del>) <del> <del>// ContainerStatPath returns Stat information about a path inside the container filesystem. <del>func (cli *Client) ContainerStatPath(containerID, path string) (types.ContainerPathStat, error) { <del> query := url.Values{} <del> query.Set("path", filepath.ToSlash(path)) // Normalize the paths used in the API. <del> <del> urlStr := fmt.Sprintf("/containers/%s/archive", containerID) <del> response, err := cli.head(urlStr, query, nil) <del> if err != nil { <del> return types.ContainerPathStat{}, err <del> } <del> defer ensureReaderClosed(response) <del> return getContainerPathStatFromHeader(response.header) <del>} <del> <del>// CopyToContainer copies content into the container filesystem. <del>func (cli *Client) CopyToContainer(options types.CopyToContainerOptions) error { <del> query := url.Values{} <del> query.Set("path", filepath.ToSlash(options.Path)) // Normalize the paths used in the API. <del> // Do not allow for an existing directory to be overwritten by a non-directory and vice versa. <del> if !options.AllowOverwriteDirWithFile { <del> query.Set("noOverwriteDirNonDir", "true") <del> } <del> <del> path := fmt.Sprintf("/containers/%s/archive", options.ContainerID) <del> <del> response, err := cli.putRaw(path, query, options.Content, nil) <del> if err != nil { <del> return err <del> } <del> defer ensureReaderClosed(response) <del> <del> if response.statusCode != http.StatusOK { <del> return fmt.Errorf("unexpected status code from daemon: %d", response.statusCode) <del> } <del> <del> return nil <del>} <del> <del>// CopyFromContainer get the content from the container and return it as a Reader <del>// to manipulate it in the host. It's up to the caller to close the reader. <del>func (cli *Client) CopyFromContainer(containerID, srcPath string) (io.ReadCloser, types.ContainerPathStat, error) { <del> query := make(url.Values, 1) <del> query.Set("path", filepath.ToSlash(srcPath)) // Normalize the paths used in the API. <del> <del> apiPath := fmt.Sprintf("/containers/%s/archive", containerID) <del> response, err := cli.get(apiPath, query, nil) <del> if err != nil { <del> return nil, types.ContainerPathStat{}, err <del> } <del> <del> if response.statusCode != http.StatusOK { <del> return nil, types.ContainerPathStat{}, fmt.Errorf("unexpected status code from daemon: %d", response.statusCode) <del> } <del> <del> // In order to get the copy behavior right, we need to know information <del> // about both the source and the destination. The response headers include <del> // stat info about the source that we can use in deciding exactly how to <del> // copy it locally. Along with the stat info about the local destination, <del> // we have everything we need to handle the multiple possibilities there <del> // can be when copying a file/dir from one location to another file/dir. <del> stat, err := getContainerPathStatFromHeader(response.header) <del> if err != nil { <del> return nil, stat, fmt.Errorf("unable to get resource stat from response: %s", err) <del> } <del> return response.body, stat, err <del>} <del> <del>func getContainerPathStatFromHeader(header http.Header) (types.ContainerPathStat, error) { <del> var stat types.ContainerPathStat <del> <del> encodedStat := header.Get("X-Docker-Container-Path-Stat") <del> statDecoder := base64.NewDecoder(base64.StdEncoding, strings.NewReader(encodedStat)) <del> <del> err := json.NewDecoder(statDecoder).Decode(&stat) <del> if err != nil { <del> err = fmt.Errorf("unable to decode container path stat header: %s", err) <del> } <del> <del> return stat, err <del>} <ide><path>api/client/lib/diff.go <del>package lib <del> <del>import ( <del> "encoding/json" <del> "net/url" <del> <del> "github.com/docker/engine-api/types" <del>) <del> <del>// ContainerDiff shows differences in a container filesystem since it was started. <del>func (cli *Client) ContainerDiff(containerID string) ([]types.ContainerChange, error) { <del> var changes []types.ContainerChange <del> <del> serverResp, err := cli.get("/containers/"+containerID+"/changes", url.Values{}, nil) <del> if err != nil { <del> return changes, err <del> } <del> defer ensureReaderClosed(serverResp) <del> <del> if err := json.NewDecoder(serverResp.body).Decode(&changes); err != nil { <del> return changes, err <del> } <del> <del> return changes, nil <del>} <ide><path>api/client/lib/errors.go <del>package lib <del> <del>import ( <del> "errors" <del> "fmt" <del>) <del> <del>// ErrConnectionFailed is a error raised when the connection between the client and the server failed. <del>var ErrConnectionFailed = errors.New("Cannot connect to the Docker daemon. Is the docker daemon running on this host?") <del> <del>// imageNotFoundError implements an error returned when an image is not in the docker host. <del>type imageNotFoundError struct { <del> imageID string <del>} <del> <del>// Error returns a string representation of an imageNotFoundError <del>func (i imageNotFoundError) Error() string { <del> return fmt.Sprintf("Error: No such image: %s", i.imageID) <del>} <del> <del>// IsErrImageNotFound returns true if the error is caused <del>// when an image is not found in the docker host. <del>func IsErrImageNotFound(err error) bool { <del> _, ok := err.(imageNotFoundError) <del> return ok <del>} <del> <del>// containerNotFoundError implements an error returned when a container is not in the docker host. <del>type containerNotFoundError struct { <del> containerID string <del>} <del> <del>// Error returns a string representation of an containerNotFoundError <del>func (e containerNotFoundError) Error() string { <del> return fmt.Sprintf("Error: No such container: %s", e.containerID) <del>} <del> <del>// IsErrContainerNotFound returns true if the error is caused <del>// when a container is not found in the docker host. <del>func IsErrContainerNotFound(err error) bool { <del> _, ok := err.(containerNotFoundError) <del> return ok <del>} <del> <del>// networkNotFoundError implements an error returned when a network is not in the docker host. <del>type networkNotFoundError struct { <del> networkID string <del>} <del> <del>// Error returns a string representation of an networkNotFoundError <del>func (e networkNotFoundError) Error() string { <del> return fmt.Sprintf("Error: No such network: %s", e.networkID) <del>} <del> <del>// IsErrNetworkNotFound returns true if the error is caused <del>// when a network is not found in the docker host. <del>func IsErrNetworkNotFound(err error) bool { <del> _, ok := err.(networkNotFoundError) <del> return ok <del>} <del> <del>// volumeNotFoundError implements an error returned when a volume is not in the docker host. <del>type volumeNotFoundError struct { <del> volumeID string <del>} <del> <del>// Error returns a string representation of an networkNotFoundError <del>func (e volumeNotFoundError) Error() string { <del> return fmt.Sprintf("Error: No such volume: %s", e.volumeID) <del>} <del> <del>// IsErrVolumeNotFound returns true if the error is caused <del>// when a volume is not found in the docker host. <del>func IsErrVolumeNotFound(err error) bool { <del> _, ok := err.(networkNotFoundError) <del> return ok <del>} <del> <del>// unauthorizedError represents an authorization error in a remote registry. <del>type unauthorizedError struct { <del> cause error <del>} <del> <del>// Error returns a string representation of an unauthorizedError <del>func (u unauthorizedError) Error() string { <del> return u.cause.Error() <del>} <del> <del>// IsErrUnauthorized returns true if the error is caused <del>// when an the remote registry authentication fails <del>func IsErrUnauthorized(err error) bool { <del> _, ok := err.(unauthorizedError) <del> return ok <del>} <ide><path>api/client/lib/events.go <del>package lib <del> <del>import ( <del> "io" <del> "net/url" <del> "time" <del> <del> "github.com/docker/engine-api/types" <del> "github.com/docker/engine-api/types/filters" <del> timetypes "github.com/docker/engine-api/types/time" <del>) <del> <del>// Events returns a stream of events in the daemon in a ReadCloser. <del>// It's up to the caller to close the stream. <del>func (cli *Client) Events(options types.EventsOptions) (io.ReadCloser, error) { <del> query := url.Values{} <del> ref := time.Now() <del> <del> if options.Since != "" { <del> ts, err := timetypes.GetTimestamp(options.Since, ref) <del> if err != nil { <del> return nil, err <del> } <del> query.Set("since", ts) <del> } <del> if options.Until != "" { <del> ts, err := timetypes.GetTimestamp(options.Until, ref) <del> if err != nil { <del> return nil, err <del> } <del> query.Set("until", ts) <del> } <del> if options.Filters.Len() > 0 { <del> filterJSON, err := filters.ToParam(options.Filters) <del> if err != nil { <del> return nil, err <del> } <del> query.Set("filters", filterJSON) <del> } <del> <del> serverResponse, err := cli.get("/events", query, nil) <del> if err != nil { <del> return nil, err <del> } <del> return serverResponse.body, nil <del>} <ide><path>api/client/lib/exec.go <del>package lib <del> <del>import ( <del> "encoding/json" <del> <del> "github.com/docker/engine-api/types" <del>) <del> <del>// ContainerExecCreate creates a new exec configuration to run an exec process. <del>func (cli *Client) ContainerExecCreate(config types.ExecConfig) (types.ContainerExecCreateResponse, error) { <del> var response types.ContainerExecCreateResponse <del> resp, err := cli.post("/containers/"+config.Container+"/exec", nil, config, nil) <del> if err != nil { <del> return response, err <del> } <del> defer ensureReaderClosed(resp) <del> err = json.NewDecoder(resp.body).Decode(&response) <del> return response, err <del>} <del> <del>// ContainerExecStart starts an exec process already create in the docker host. <del>func (cli *Client) ContainerExecStart(execID string, config types.ExecStartCheck) error { <del> resp, err := cli.post("/exec/"+execID+"/start", nil, config, nil) <del> ensureReaderClosed(resp) <del> return err <del>} <del> <del>// ContainerExecAttach attaches a connection to an exec process in the server. <del>// It returns a types.HijackedConnection with the hijacked connection <del>// and the a reader to get output. It's up to the called to close <del>// the hijacked connection by calling types.HijackedResponse.Close. <del>func (cli *Client) ContainerExecAttach(execID string, config types.ExecConfig) (types.HijackedResponse, error) { <del> headers := map[string][]string{"Content-Type": {"application/json"}} <del> return cli.postHijacked("/exec/"+execID+"/start", nil, config, headers) <del>} <del> <del>// ContainerExecInspect returns information about a specific exec process on the docker host. <del>func (cli *Client) ContainerExecInspect(execID string) (types.ContainerExecInspect, error) { <del> var response types.ContainerExecInspect <del> resp, err := cli.get("/exec/"+execID+"/json", nil, nil) <del> if err != nil { <del> return response, err <del> } <del> defer ensureReaderClosed(resp) <del> <del> err = json.NewDecoder(resp.body).Decode(&response) <del> return response, err <del>} <ide><path>api/client/lib/export.go <del>package lib <del> <del>import ( <del> "io" <del> "net/url" <del>) <del> <del>// ContainerExport retrieves the raw contents of a container <del>// and returns them as a io.ReadCloser. It's up to the caller <del>// to close the stream. <del>func (cli *Client) ContainerExport(containerID string) (io.ReadCloser, error) { <del> serverResp, err := cli.get("/containers/"+containerID+"/export", url.Values{}, nil) <del> if err != nil { <del> return nil, err <del> } <del> <del> return serverResp.body, nil <del>} <ide><path>api/client/lib/hijack.go <del>package lib <del> <del>import ( <del> "crypto/tls" <del> "errors" <del> "fmt" <del> "net" <del> "net/http/httputil" <del> "net/url" <del> "strings" <del> "time" <del> <del> "github.com/docker/engine-api/types" <del>) <del> <del>// tlsClientCon holds tls information and a dialed connection. <del>type tlsClientCon struct { <del> *tls.Conn <del> rawConn net.Conn <del>} <del> <del>func (c *tlsClientCon) CloseWrite() error { <del> // Go standard tls.Conn doesn't provide the CloseWrite() method so we do it <del> // on its underlying connection. <del> if conn, ok := c.rawConn.(types.CloseWriter); ok { <del> return conn.CloseWrite() <del> } <del> return nil <del>} <del> <del>// postHijacked sends a POST request and hijacks the connection. <del>func (cli *Client) postHijacked(path string, query url.Values, body interface{}, headers map[string][]string) (types.HijackedResponse, error) { <del> bodyEncoded, err := encodeData(body) <del> if err != nil { <del> return types.HijackedResponse{}, err <del> } <del> <del> req, err := cli.newRequest("POST", path, query, bodyEncoded, headers) <del> if err != nil { <del> return types.HijackedResponse{}, err <del> } <del> req.Host = cli.addr <del> <del> req.Header.Set("Connection", "Upgrade") <del> req.Header.Set("Upgrade", "tcp") <del> <del> conn, err := dial(cli.proto, cli.addr, cli.tlsConfig) <del> if err != nil { <del> if strings.Contains(err.Error(), "connection refused") { <del> return types.HijackedResponse{}, fmt.Errorf("Cannot connect to the Docker daemon. Is 'docker daemon' running on this host?") <del> } <del> return types.HijackedResponse{}, err <del> } <del> <del> // When we set up a TCP connection for hijack, there could be long periods <del> // of inactivity (a long running command with no output) that in certain <del> // network setups may cause ECONNTIMEOUT, leaving the client in an unknown <del> // state. Setting TCP KeepAlive on the socket connection will prohibit <del> // ECONNTIMEOUT unless the socket connection truly is broken <del> if tcpConn, ok := conn.(*net.TCPConn); ok { <del> tcpConn.SetKeepAlive(true) <del> tcpConn.SetKeepAlivePeriod(30 * time.Second) <del> } <del> <del> clientconn := httputil.NewClientConn(conn, nil) <del> defer clientconn.Close() <del> <del> // Server hijacks the connection, error 'connection closed' expected <del> clientconn.Do(req) <del> <del> rwc, br := clientconn.Hijack() <del> <del> return types.HijackedResponse{Conn: rwc, Reader: br}, nil <del>} <del> <del>func tlsDial(network, addr string, config *tls.Config) (net.Conn, error) { <del> return tlsDialWithDialer(new(net.Dialer), network, addr, config) <del>} <del> <del>// We need to copy Go's implementation of tls.Dial (pkg/cryptor/tls/tls.go) in <del>// order to return our custom tlsClientCon struct which holds both the tls.Conn <del>// object _and_ its underlying raw connection. The rationale for this is that <del>// we need to be able to close the write end of the connection when attaching, <del>// which tls.Conn does not provide. <del>func tlsDialWithDialer(dialer *net.Dialer, network, addr string, config *tls.Config) (net.Conn, error) { <del> // We want the Timeout and Deadline values from dialer to cover the <del> // whole process: TCP connection and TLS handshake. This means that we <del> // also need to start our own timers now. <del> timeout := dialer.Timeout <del> <del> if !dialer.Deadline.IsZero() { <del> deadlineTimeout := dialer.Deadline.Sub(time.Now()) <del> if timeout == 0 || deadlineTimeout < timeout { <del> timeout = deadlineTimeout <del> } <del> } <del> <del> var errChannel chan error <del> <del> if timeout != 0 { <del> errChannel = make(chan error, 2) <del> time.AfterFunc(timeout, func() { <del> errChannel <- errors.New("") <del> }) <del> } <del> <del> rawConn, err := dialer.Dial(network, addr) <del> if err != nil { <del> return nil, err <del> } <del> // When we set up a TCP connection for hijack, there could be long periods <del> // of inactivity (a long running command with no output) that in certain <del> // network setups may cause ECONNTIMEOUT, leaving the client in an unknown <del> // state. Setting TCP KeepAlive on the socket connection will prohibit <del> // ECONNTIMEOUT unless the socket connection truly is broken <del> if tcpConn, ok := rawConn.(*net.TCPConn); ok { <del> tcpConn.SetKeepAlive(true) <del> tcpConn.SetKeepAlivePeriod(30 * time.Second) <del> } <del> <del> colonPos := strings.LastIndex(addr, ":") <del> if colonPos == -1 { <del> colonPos = len(addr) <del> } <del> hostname := addr[:colonPos] <del> <del> // If no ServerName is set, infer the ServerName <del> // from the hostname we're connecting to. <del> if config.ServerName == "" { <del> // Make a copy to avoid polluting argument or default. <del> c := *config <del> c.ServerName = hostname <del> config = &c <del> } <del> <del> conn := tls.Client(rawConn, config) <del> <del> if timeout == 0 { <del> err = conn.Handshake() <del> } else { <del> go func() { <del> errChannel <- conn.Handshake() <del> }() <del> <del> err = <-errChannel <del> } <del> <del> if err != nil { <del> rawConn.Close() <del> return nil, err <del> } <del> <del> // This is Docker difference with standard's crypto/tls package: returned a <del> // wrapper which holds both the TLS and raw connections. <del> return &tlsClientCon{conn, rawConn}, nil <del>} <del> <del>func dial(proto, addr string, tlsConfig *tls.Config) (net.Conn, error) { <del> if tlsConfig != nil && proto != "unix" { <del> // Notice this isn't Go standard's tls.Dial function <del> return tlsDial(proto, addr, tlsConfig) <del> } <del> return net.Dial(proto, addr) <del>} <ide><path>api/client/lib/history.go <del>package lib <del> <del>import ( <del> "encoding/json" <del> "net/url" <del> <del> "github.com/docker/engine-api/types" <del>) <del> <del>// ImageHistory returns the changes in an image in history format. <del>func (cli *Client) ImageHistory(imageID string) ([]types.ImageHistory, error) { <del> var history []types.ImageHistory <del> serverResp, err := cli.get("/images/"+imageID+"/history", url.Values{}, nil) <del> if err != nil { <del> return history, err <del> } <del> defer ensureReaderClosed(serverResp) <del> <del> if err := json.NewDecoder(serverResp.body).Decode(&history); err != nil { <del> return history, err <del> } <del> return history, nil <del>} <ide><path>api/client/lib/image_build.go <del>package lib <del> <del>import ( <del> "encoding/base64" <del> "encoding/json" <del> "net/http" <del> "net/url" <del> "regexp" <del> "strconv" <del> "strings" <del> <del> "github.com/docker/engine-api/types" <del> "github.com/docker/engine-api/types/container" <del>) <del> <del>var headerRegexp = regexp.MustCompile(`\ADocker/.+\s\((.+)\)\z`) <del> <del>// ImageBuild sends request to the daemon to build images. <del>// The Body in the response implement an io.ReadCloser and it's up to the caller to <del>// close it. <del>func (cli *Client) ImageBuild(options types.ImageBuildOptions) (types.ImageBuildResponse, error) { <del> query, err := imageBuildOptionsToQuery(options) <del> if err != nil { <del> return types.ImageBuildResponse{}, err <del> } <del> <del> headers := http.Header(make(map[string][]string)) <del> buf, err := json.Marshal(options.AuthConfigs) <del> if err != nil { <del> return types.ImageBuildResponse{}, err <del> } <del> headers.Add("X-Registry-Config", base64.URLEncoding.EncodeToString(buf)) <del> headers.Set("Content-Type", "application/tar") <del> <del> serverResp, err := cli.postRaw("/build", query, options.Context, headers) <del> if err != nil { <del> return types.ImageBuildResponse{}, err <del> } <del> <del> osType := getDockerOS(serverResp.header.Get("Server")) <del> <del> return types.ImageBuildResponse{ <del> Body: serverResp.body, <del> OSType: osType, <del> }, nil <del>} <del> <del>func imageBuildOptionsToQuery(options types.ImageBuildOptions) (url.Values, error) { <del> query := url.Values{ <del> "t": options.Tags, <del> } <del> if options.SuppressOutput { <del> query.Set("q", "1") <del> } <del> if options.RemoteContext != "" { <del> query.Set("remote", options.RemoteContext) <del> } <del> if options.NoCache { <del> query.Set("nocache", "1") <del> } <del> if options.Remove { <del> query.Set("rm", "1") <del> } else { <del> query.Set("rm", "0") <del> } <del> <del> if options.ForceRemove { <del> query.Set("forcerm", "1") <del> } <del> <del> if options.PullParent { <del> query.Set("pull", "1") <del> } <del> <del> if !container.IsolationLevel.IsDefault(options.IsolationLevel) { <del> query.Set("isolation", string(options.IsolationLevel)) <del> } <del> <del> query.Set("cpusetcpus", options.CPUSetCPUs) <del> query.Set("cpusetmems", options.CPUSetMems) <del> query.Set("cpushares", strconv.FormatInt(options.CPUShares, 10)) <del> query.Set("cpuquota", strconv.FormatInt(options.CPUQuota, 10)) <del> query.Set("cpuperiod", strconv.FormatInt(options.CPUPeriod, 10)) <del> query.Set("memory", strconv.FormatInt(options.Memory, 10)) <del> query.Set("memswap", strconv.FormatInt(options.MemorySwap, 10)) <del> query.Set("cgroupparent", options.CgroupParent) <del> query.Set("shmsize", strconv.FormatInt(options.ShmSize, 10)) <del> query.Set("dockerfile", options.Dockerfile) <del> <del> ulimitsJSON, err := json.Marshal(options.Ulimits) <del> if err != nil { <del> return query, err <del> } <del> query.Set("ulimits", string(ulimitsJSON)) <del> <del> buildArgsJSON, err := json.Marshal(options.BuildArgs) <del> if err != nil { <del> return query, err <del> } <del> query.Set("buildargs", string(buildArgsJSON)) <del> <del> return query, nil <del>} <del> <del>func getDockerOS(serverHeader string) string { <del> var osType string <del> matches := headerRegexp.FindStringSubmatch(serverHeader) <del> if len(matches) > 0 { <del> osType = matches[1] <del> } <del> return osType <del>} <del> <del>// convertKVStringsToMap converts ["key=value"] to {"key":"value"} <del>func convertKVStringsToMap(values []string) map[string]string { <del> result := make(map[string]string, len(values)) <del> for _, value := range values { <del> kv := strings.SplitN(value, "=", 2) <del> if len(kv) == 1 { <del> result[kv[0]] = "" <del> } else { <del> result[kv[0]] = kv[1] <del> } <del> } <del> <del> return result <del>} <ide><path>api/client/lib/image_build_test.go <del>package lib <del> <del>import "testing" <del> <del>func TestGetDockerOS(t *testing.T) { <del> cases := map[string]string{ <del> "Docker/v1.22 (linux)": "linux", <del> "Docker/v1.22 (windows)": "windows", <del> "Foo/v1.22 (bar)": "", <del> } <del> for header, os := range cases { <del> g := getDockerOS(header) <del> if g != os { <del> t.Fatalf("Expected %s, got %s", os, g) <del> } <del> } <del>} <ide><path>api/client/lib/image_create.go <del>package lib <del> <del>import ( <del> "io" <del> "net/url" <del> <del> "github.com/docker/engine-api/types" <del>) <del> <del>// ImageCreate creates a new image based in the parent options. <del>// It returns the JSON content in the response body. <del>func (cli *Client) ImageCreate(options types.ImageCreateOptions) (io.ReadCloser, error) { <del> query := url.Values{} <del> query.Set("fromImage", options.Parent) <del> query.Set("tag", options.Tag) <del> resp, err := cli.tryImageCreate(query, options.RegistryAuth) <del> if err != nil { <del> return nil, err <del> } <del> return resp.body, nil <del>} <del> <del>func (cli *Client) tryImageCreate(query url.Values, registryAuth string) (*serverResponse, error) { <del> headers := map[string][]string{"X-Registry-Auth": {registryAuth}} <del> return cli.post("/images/create", query, nil, headers) <del>} <ide><path>api/client/lib/image_import.go <del>package lib <del> <del>import ( <del> "io" <del> "net/url" <del> <del> "github.com/docker/engine-api/types" <del>) <del> <del>// ImageImport creates a new image based in the source options. <del>// It returns the JSON content in the response body. <del>func (cli *Client) ImageImport(options types.ImageImportOptions) (io.ReadCloser, error) { <del> query := url.Values{} <del> query.Set("fromSrc", options.SourceName) <del> query.Set("repo", options.RepositoryName) <del> query.Set("tag", options.Tag) <del> query.Set("message", options.Message) <del> for _, change := range options.Changes { <del> query.Add("changes", change) <del> } <del> <del> resp, err := cli.postRaw("/images/create", query, options.Source, nil) <del> if err != nil { <del> return nil, err <del> } <del> return resp.body, nil <del>} <ide><path>api/client/lib/image_inspect.go <del>package lib <del> <del>import ( <del> "bytes" <del> "encoding/json" <del> "io/ioutil" <del> "net/http" <del> "net/url" <del> <del> "github.com/docker/engine-api/types" <del>) <del> <del>// ImageInspectWithRaw returns the image information and it's raw representation. <del>func (cli *Client) ImageInspectWithRaw(imageID string, getSize bool) (types.ImageInspect, []byte, error) { <del> query := url.Values{} <del> if getSize { <del> query.Set("size", "1") <del> } <del> serverResp, err := cli.get("/images/"+imageID+"/json", query, nil) <del> if err != nil { <del> if serverResp.statusCode == http.StatusNotFound { <del> return types.ImageInspect{}, nil, imageNotFoundError{imageID} <del> } <del> return types.ImageInspect{}, nil, err <del> } <del> defer ensureReaderClosed(serverResp) <del> <del> body, err := ioutil.ReadAll(serverResp.body) <del> if err != nil { <del> return types.ImageInspect{}, nil, err <del> } <del> <del> var response types.ImageInspect <del> rdr := bytes.NewReader(body) <del> err = json.NewDecoder(rdr).Decode(&response) <del> return response, body, err <del>} <ide><path>api/client/lib/image_list.go <del>package lib <del> <del>import ( <del> "encoding/json" <del> "net/url" <del> <del> "github.com/docker/engine-api/types" <del> "github.com/docker/engine-api/types/filters" <del>) <del> <del>// ImageList returns a list of images in the docker host. <del>func (cli *Client) ImageList(options types.ImageListOptions) ([]types.Image, error) { <del> var images []types.Image <del> query := url.Values{} <del> <del> if options.Filters.Len() > 0 { <del> filterJSON, err := filters.ToParam(options.Filters) <del> if err != nil { <del> return images, err <del> } <del> query.Set("filters", filterJSON) <del> } <del> if options.MatchName != "" { <del> // FIXME rename this parameter, to not be confused with the filters flag <del> query.Set("filter", options.MatchName) <del> } <del> if options.All { <del> query.Set("all", "1") <del> } <del> <del> serverResp, err := cli.get("/images/json", query, nil) <del> if err != nil { <del> return images, err <del> } <del> defer ensureReaderClosed(serverResp) <del> <del> err = json.NewDecoder(serverResp.body).Decode(&images) <del> return images, err <del>} <ide><path>api/client/lib/image_load.go <del>package lib <del> <del>import ( <del> "io" <del> "net/url" <del> <del> "github.com/docker/engine-api/types" <del>) <del> <del>// ImageLoad loads an image in the docker host from the client host. <del>// It's up to the caller to close the io.ReadCloser returned by <del>// this function. <del>func (cli *Client) ImageLoad(input io.Reader) (types.ImageLoadResponse, error) { <del> resp, err := cli.postRaw("/images/load", url.Values{}, input, nil) <del> if err != nil { <del> return types.ImageLoadResponse{}, err <del> } <del> return types.ImageLoadResponse{ <del> Body: resp.body, <del> JSON: resp.header.Get("Content-Type") == "application/json", <del> }, nil <del>} <ide><path>api/client/lib/image_pull.go <del>package lib <del> <del>import ( <del> "io" <del> "net/http" <del> "net/url" <del> <del> "github.com/docker/engine-api/types" <del>) <del> <del>// ImagePull request the docker host to pull an image from a remote registry. <del>// It executes the privileged function if the operation is unauthorized <del>// and it tries one more time. <del>// It's up to the caller to handle the io.ReadCloser and close it properly. <del>func (cli *Client) ImagePull(options types.ImagePullOptions, privilegeFunc RequestPrivilegeFunc) (io.ReadCloser, error) { <del> query := url.Values{} <del> query.Set("fromImage", options.ImageID) <del> if options.Tag != "" { <del> query.Set("tag", options.Tag) <del> } <del> <del> resp, err := cli.tryImageCreate(query, options.RegistryAuth) <del> if resp.statusCode == http.StatusUnauthorized { <del> newAuthHeader, privilegeErr := privilegeFunc() <del> if privilegeErr != nil { <del> return nil, privilegeErr <del> } <del> resp, err = cli.tryImageCreate(query, newAuthHeader) <del> } <del> if err != nil { <del> return nil, err <del> } <del> return resp.body, nil <del>} <ide><path>api/client/lib/image_push.go <del>package lib <del> <del>import ( <del> "io" <del> "net/http" <del> "net/url" <del> <del> "github.com/docker/engine-api/types" <del>) <del> <del>// ImagePush request the docker host to push an image to a remote registry. <del>// It executes the privileged function if the operation is unauthorized <del>// and it tries one more time. <del>// It's up to the caller to handle the io.ReadCloser and close it properly. <del>func (cli *Client) ImagePush(options types.ImagePushOptions, privilegeFunc RequestPrivilegeFunc) (io.ReadCloser, error) { <del> query := url.Values{} <del> query.Set("tag", options.Tag) <del> <del> resp, err := cli.tryImagePush(options.ImageID, query, options.RegistryAuth) <del> if resp.statusCode == http.StatusUnauthorized { <del> newAuthHeader, privilegeErr := privilegeFunc() <del> if privilegeErr != nil { <del> return nil, privilegeErr <del> } <del> resp, err = cli.tryImagePush(options.ImageID, query, newAuthHeader) <del> } <del> if err != nil { <del> return nil, err <del> } <del> return resp.body, nil <del>} <del> <del>func (cli *Client) tryImagePush(imageID string, query url.Values, registryAuth string) (*serverResponse, error) { <del> headers := map[string][]string{"X-Registry-Auth": {registryAuth}} <del> return cli.post("/images/"+imageID+"/push", query, nil, headers) <del>} <ide><path>api/client/lib/image_remove.go <del>package lib <del> <del>import ( <del> "encoding/json" <del> "net/url" <del> <del> "github.com/docker/engine-api/types" <del>) <del> <del>// ImageRemove removes an image from the docker host. <del>func (cli *Client) ImageRemove(options types.ImageRemoveOptions) ([]types.ImageDelete, error) { <del> query := url.Values{} <del> <del> if options.Force { <del> query.Set("force", "1") <del> } <del> if !options.PruneChildren { <del> query.Set("noprune", "1") <del> } <del> <del> resp, err := cli.delete("/images/"+options.ImageID, query, nil) <del> if err != nil { <del> return nil, err <del> } <del> defer ensureReaderClosed(resp) <del> <del> var dels []types.ImageDelete <del> err = json.NewDecoder(resp.body).Decode(&dels) <del> return dels, err <del>} <ide><path>api/client/lib/image_save.go <del>package lib <del> <del>import ( <del> "io" <del> "net/url" <del>) <del> <del>// ImageSave retrieves one or more images from the docker host as a io.ReadCloser. <del>// It's up to the caller to store the images and close the stream. <del>func (cli *Client) ImageSave(imageIDs []string) (io.ReadCloser, error) { <del> query := url.Values{ <del> "names": imageIDs, <del> } <del> <del> resp, err := cli.get("/images/get", query, nil) <del> if err != nil { <del> return nil, err <del> } <del> return resp.body, nil <del>} <ide><path>api/client/lib/image_search.go <del>package lib <del> <del>import ( <del> "encoding/json" <del> "net/http" <del> "net/url" <del> <del> "github.com/docker/engine-api/types" <del> "github.com/docker/engine-api/types/registry" <del>) <del> <del>// ImageSearch makes the docker host to search by a term in a remote registry. <del>// The list of results is not sorted in any fashion. <del>func (cli *Client) ImageSearch(options types.ImageSearchOptions, privilegeFunc RequestPrivilegeFunc) ([]registry.SearchResult, error) { <del> var results []registry.SearchResult <del> query := url.Values{} <del> query.Set("term", options.Term) <del> <del> resp, err := cli.tryImageSearch(query, options.RegistryAuth) <del> if resp.statusCode == http.StatusUnauthorized { <del> newAuthHeader, privilegeErr := privilegeFunc() <del> if privilegeErr != nil { <del> return results, privilegeErr <del> } <del> resp, err = cli.tryImageSearch(query, newAuthHeader) <del> } <del> if err != nil { <del> return results, err <del> } <del> defer ensureReaderClosed(resp) <del> <del> err = json.NewDecoder(resp.body).Decode(&results) <del> return results, err <del>} <del> <del>func (cli *Client) tryImageSearch(query url.Values, registryAuth string) (*serverResponse, error) { <del> headers := map[string][]string{"X-Registry-Auth": {registryAuth}} <del> return cli.get("/images/search", query, headers) <del>} <ide><path>api/client/lib/image_tag.go <del>package lib <del> <del>import ( <del> "net/url" <del> <del> "github.com/docker/engine-api/types" <del>) <del> <del>// ImageTag tags an image in the docker host <del>func (cli *Client) ImageTag(options types.ImageTagOptions) error { <del> query := url.Values{} <del> query.Set("repo", options.RepositoryName) <del> query.Set("tag", options.Tag) <del> if options.Force { <del> query.Set("force", "1") <del> } <del> <del> resp, err := cli.post("/images/"+options.ImageID+"/tag", query, nil, nil) <del> ensureReaderClosed(resp) <del> return err <del>} <ide><path>api/client/lib/info.go <del>package lib <del> <del>import ( <del> "encoding/json" <del> "fmt" <del> "net/url" <del> <del> "github.com/docker/engine-api/types" <del>) <del> <del>// Info returns information about the docker server. <del>func (cli *Client) Info() (types.Info, error) { <del> var info types.Info <del> serverResp, err := cli.get("/info", url.Values{}, nil) <del> if err != nil { <del> return info, err <del> } <del> defer ensureReaderClosed(serverResp) <del> <del> if err := json.NewDecoder(serverResp.body).Decode(&info); err != nil { <del> return info, fmt.Errorf("Error reading remote info: %v", err) <del> } <del> <del> return info, nil <del>} <ide><path>api/client/lib/kill.go <del>package lib <del> <del>import "net/url" <del> <del>// ContainerKill terminates the container process but does not remove the container from the docker host. <del>func (cli *Client) ContainerKill(containerID, signal string) error { <del> query := url.Values{} <del> query.Set("signal", signal) <del> <del> resp, err := cli.post("/containers/"+containerID+"/kill", query, nil, nil) <del> ensureReaderClosed(resp) <del> return err <del>} <ide><path>api/client/lib/login.go <del>package lib <del> <del>import ( <del> "encoding/json" <del> "net/http" <del> "net/url" <del> <del> "github.com/docker/engine-api/types" <del>) <del> <del>// RegistryLogin authenticates the docker server with a given docker registry. <del>// It returns UnauthorizerError when the authentication fails. <del>func (cli *Client) RegistryLogin(auth types.AuthConfig) (types.AuthResponse, error) { <del> resp, err := cli.post("/auth", url.Values{}, auth, nil) <del> <del> if resp != nil && resp.statusCode == http.StatusUnauthorized { <del> return types.AuthResponse{}, unauthorizedError{err} <del> } <del> if err != nil { <del> return types.AuthResponse{}, err <del> } <del> defer ensureReaderClosed(resp) <del> <del> var response types.AuthResponse <del> err = json.NewDecoder(resp.body).Decode(&response) <del> return response, err <del>} <ide><path>api/client/lib/logs.go <del>package lib <del> <del>import ( <del> "io" <del> "net/url" <del> "time" <del> <del> "github.com/docker/engine-api/types" <del> timetypes "github.com/docker/engine-api/types/time" <del>) <del> <del>// ContainerLogs returns the logs generated by a container in an io.ReadCloser. <del>// It's up to the caller to close the stream. <del>func (cli *Client) ContainerLogs(options types.ContainerLogsOptions) (io.ReadCloser, error) { <del> query := url.Values{} <del> if options.ShowStdout { <del> query.Set("stdout", "1") <del> } <del> <del> if options.ShowStderr { <del> query.Set("stderr", "1") <del> } <del> <del> if options.Since != "" { <del> ts, err := timetypes.GetTimestamp(options.Since, time.Now()) <del> if err != nil { <del> return nil, err <del> } <del> query.Set("since", ts) <del> } <del> <del> if options.Timestamps { <del> query.Set("timestamps", "1") <del> } <del> <del> if options.Follow { <del> query.Set("follow", "1") <del> } <del> query.Set("tail", options.Tail) <del> <del> resp, err := cli.get("/containers/"+options.ContainerID+"/logs", query, nil) <del> if err != nil { <del> return nil, err <del> } <del> return resp.body, nil <del>} <ide><path>api/client/lib/network.go <del>package lib <del> <del>import ( <del> "encoding/json" <del> "net/http" <del> "net/url" <del> <del> "github.com/docker/engine-api/types" <del> "github.com/docker/engine-api/types/filters" <del>) <del> <del>// NetworkCreate creates a new network in the docker host. <del>func (cli *Client) NetworkCreate(options types.NetworkCreate) (types.NetworkCreateResponse, error) { <del> var response types.NetworkCreateResponse <del> serverResp, err := cli.post("/networks/create", nil, options, nil) <del> if err != nil { <del> return response, err <del> } <del> <del> json.NewDecoder(serverResp.body).Decode(&response) <del> ensureReaderClosed(serverResp) <del> return response, err <del>} <del> <del>// NetworkRemove removes an existent network from the docker host. <del>func (cli *Client) NetworkRemove(networkID string) error { <del> resp, err := cli.delete("/networks/"+networkID, nil, nil) <del> ensureReaderClosed(resp) <del> return err <del>} <del> <del>// NetworkConnect connects a container to an existent network in the docker host. <del>func (cli *Client) NetworkConnect(networkID, containerID string) error { <del> nc := types.NetworkConnect{Container: containerID} <del> resp, err := cli.post("/networks/"+networkID+"/connect", nil, nc, nil) <del> ensureReaderClosed(resp) <del> return err <del>} <del> <del>// NetworkDisconnect disconnects a container from an existent network in the docker host. <del>func (cli *Client) NetworkDisconnect(networkID, containerID string) error { <del> nc := types.NetworkConnect{Container: containerID} <del> resp, err := cli.post("/networks/"+networkID+"/disconnect", nil, nc, nil) <del> ensureReaderClosed(resp) <del> return err <del>} <del> <del>// NetworkList returns the list of networks configured in the docker host. <del>func (cli *Client) NetworkList(options types.NetworkListOptions) ([]types.NetworkResource, error) { <del> query := url.Values{} <del> if options.Filters.Len() > 0 { <del> filterJSON, err := filters.ToParam(options.Filters) <del> if err != nil { <del> return nil, err <del> } <del> <del> query.Set("filters", filterJSON) <del> } <del> var networkResources []types.NetworkResource <del> resp, err := cli.get("/networks", query, nil) <del> if err != nil { <del> return networkResources, err <del> } <del> defer ensureReaderClosed(resp) <del> err = json.NewDecoder(resp.body).Decode(&networkResources) <del> return networkResources, err <del>} <del> <del>// NetworkInspect returns the information for a specific network configured in the docker host. <del>func (cli *Client) NetworkInspect(networkID string) (types.NetworkResource, error) { <del> var networkResource types.NetworkResource <del> resp, err := cli.get("/networks/"+networkID, nil, nil) <del> if err != nil { <del> if resp.statusCode == http.StatusNotFound { <del> return networkResource, networkNotFoundError{networkID} <del> } <del> return networkResource, err <del> } <del> defer ensureReaderClosed(resp) <del> err = json.NewDecoder(resp.body).Decode(&networkResource) <del> return networkResource, err <del>} <ide><path>api/client/lib/pause.go <del>package lib <del> <del>// ContainerPause pauses the main process of a given container without terminating it. <del>func (cli *Client) ContainerPause(containerID string) error { <del> resp, err := cli.post("/containers/"+containerID+"/pause", nil, nil, nil) <del> ensureReaderClosed(resp) <del> return err <del>} <ide><path>api/client/lib/privileged.go <del>package lib <del> <del>// RequestPrivilegeFunc is a function interface that <del>// clients can supply to retry operations after <del>// getting an authorization error. <del>// This function returns the registry authentication <del>// header value in base 64 format, or an error <del>// if the privilege request fails. <del>type RequestPrivilegeFunc func() (string, error) <ide><path>api/client/lib/request.go <del>package lib <del> <del>import ( <del> "bytes" <del> "encoding/json" <del> "fmt" <del> "io" <del> "io/ioutil" <del> "net/http" <del> "net/url" <del> "strings" <del>) <del> <del>// serverResponse is a wrapper for http API responses. <del>type serverResponse struct { <del> body io.ReadCloser <del> header http.Header <del> statusCode int <del>} <del> <del>// head sends an http request to the docker API using the method HEAD. <del>func (cli *Client) head(path string, query url.Values, headers map[string][]string) (*serverResponse, error) { <del> return cli.sendRequest("HEAD", path, query, nil, headers) <del>} <del> <del>// get sends an http request to the docker API using the method GET. <del>func (cli *Client) get(path string, query url.Values, headers map[string][]string) (*serverResponse, error) { <del> return cli.sendRequest("GET", path, query, nil, headers) <del>} <del> <del>// post sends an http request to the docker API using the method POST. <del>func (cli *Client) post(path string, query url.Values, body interface{}, headers map[string][]string) (*serverResponse, error) { <del> return cli.sendRequest("POST", path, query, body, headers) <del>} <del> <del>// postRaw sends the raw input to the docker API using the method POST. <del>func (cli *Client) postRaw(path string, query url.Values, body io.Reader, headers map[string][]string) (*serverResponse, error) { <del> return cli.sendClientRequest("POST", path, query, body, headers) <del>} <del> <del>// put sends an http request to the docker API using the method PUT. <del>func (cli *Client) put(path string, query url.Values, body interface{}, headers map[string][]string) (*serverResponse, error) { <del> return cli.sendRequest("PUT", path, query, body, headers) <del>} <del> <del>// putRaw sends the raw input to the docker API using the method PUT. <del>func (cli *Client) putRaw(path string, query url.Values, body io.Reader, headers map[string][]string) (*serverResponse, error) { <del> return cli.sendClientRequest("PUT", path, query, body, headers) <del>} <del> <del>// delete sends an http request to the docker API using the method DELETE. <del>func (cli *Client) delete(path string, query url.Values, headers map[string][]string) (*serverResponse, error) { <del> return cli.sendRequest("DELETE", path, query, nil, headers) <del>} <del> <del>func (cli *Client) sendRequest(method, path string, query url.Values, body interface{}, headers map[string][]string) (*serverResponse, error) { <del> params, err := encodeData(body) <del> if err != nil { <del> return nil, err <del> } <del> <del> if body != nil { <del> if headers == nil { <del> headers = make(map[string][]string) <del> } <del> headers["Content-Type"] = []string{"application/json"} <del> } <del> <del> return cli.sendClientRequest(method, path, query, params, headers) <del>} <del> <del>func (cli *Client) sendClientRequest(method, path string, query url.Values, body io.Reader, headers map[string][]string) (*serverResponse, error) { <del> serverResp := &serverResponse{ <del> body: nil, <del> statusCode: -1, <del> } <del> <del> expectedPayload := (method == "POST" || method == "PUT") <del> if expectedPayload && body == nil { <del> body = bytes.NewReader([]byte{}) <del> } <del> <del> req, err := cli.newRequest(method, path, query, body, headers) <del> req.URL.Host = cli.addr <del> req.URL.Scheme = cli.scheme <del> <del> if expectedPayload && req.Header.Get("Content-Type") == "" { <del> req.Header.Set("Content-Type", "text/plain") <del> } <del> <del> resp, err := cli.httpClient.Do(req) <del> if resp != nil { <del> serverResp.statusCode = resp.StatusCode <del> } <del> <del> if err != nil { <del> if isTimeout(err) || strings.Contains(err.Error(), "connection refused") || strings.Contains(err.Error(), "dial unix") { <del> return serverResp, ErrConnectionFailed <del> } <del> <del> if cli.scheme == "http" && strings.Contains(err.Error(), "malformed HTTP response") { <del> return serverResp, fmt.Errorf("%v.\n* Are you trying to connect to a TLS-enabled daemon without TLS?", err) <del> } <del> if cli.scheme == "https" && strings.Contains(err.Error(), "remote 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) <del> } <del> <del> return serverResp, fmt.Errorf("An error occurred trying to connect: %v", err) <del> } <del> <del> if serverResp.statusCode < 200 || serverResp.statusCode >= 400 { <del> body, err := ioutil.ReadAll(resp.Body) <del> if err != nil { <del> return serverResp, err <del> } <del> if len(body) == 0 { <del> return serverResp, fmt.Errorf("Error: request returned %s for API route and version %s, check if the server supports the requested API version", http.StatusText(serverResp.statusCode), req.URL) <del> } <del> return serverResp, fmt.Errorf("Error response from daemon: %s", bytes.TrimSpace(body)) <del> } <del> <del> serverResp.body = resp.Body <del> serverResp.header = resp.Header <del> return serverResp, nil <del>} <del> <del>func (cli *Client) newRequest(method, path string, query url.Values, body io.Reader, headers map[string][]string) (*http.Request, error) { <del> apiPath := cli.getAPIPath(path, query) <del> req, err := http.NewRequest(method, apiPath, body) <del> if err != nil { <del> return nil, err <del> } <del> <del> // Add CLI Config's HTTP Headers BEFORE we set the Docker headers <del> // then the user can't change OUR headers <del> for k, v := range cli.customHTTPHeaders { <del> req.Header.Set(k, v) <del> } <del> <del> if headers != nil { <del> for k, v := range headers { <del> req.Header[k] = v <del> } <del> } <del> <del> return req, nil <del>} <del> <del>func encodeData(data interface{}) (*bytes.Buffer, error) { <del> params := bytes.NewBuffer(nil) <del> if data != nil { <del> if err := json.NewEncoder(params).Encode(data); err != nil { <del> return nil, err <del> } <del> } <del> return params, nil <del>} <del> <del>func ensureReaderClosed(response *serverResponse) { <del> if response != nil && response.body != nil { <del> response.body.Close() <del> } <del>} <del> <del>func isTimeout(err error) bool { <del> type timeout interface { <del> Timeout() bool <del> } <del> e := err <del> switch urlErr := err.(type) { <del> case *url.Error: <del> e = urlErr.Err <del> } <del> t, ok := e.(timeout) <del> return ok && t.Timeout() <del>} <ide><path>api/client/lib/resize.go <del>package lib <del> <del>import ( <del> "net/url" <del> "strconv" <del> <del> "github.com/docker/engine-api/types" <del>) <del> <del>// ContainerResize changes the size of the tty for a container. <del>func (cli *Client) ContainerResize(options types.ResizeOptions) error { <del> return cli.resize("/containers/"+options.ID, options.Height, options.Width) <del>} <del> <del>// ContainerExecResize changes the size of the tty for an exec process running inside a container. <del>func (cli *Client) ContainerExecResize(options types.ResizeOptions) error { <del> return cli.resize("/exec/"+options.ID, options.Height, options.Width) <del>} <del> <del>func (cli *Client) resize(basePath string, height, width int) error { <del> query := url.Values{} <del> query.Set("h", strconv.Itoa(height)) <del> query.Set("w", strconv.Itoa(width)) <del> <del> resp, err := cli.post(basePath+"/resize", query, nil, nil) <del> ensureReaderClosed(resp) <del> return err <del>} <ide><path>api/client/lib/version.go <del>package lib <del> <del>import ( <del> "encoding/json" <del> <del> "github.com/docker/engine-api/types" <del>) <del> <del>// ServerVersion returns information of the docker client and server host. <del>func (cli *Client) ServerVersion() (types.Version, error) { <del> resp, err := cli.get("/version", nil, nil) <del> if err != nil { <del> return types.Version{}, err <del> } <del> defer ensureReaderClosed(resp) <del> <del> var server types.Version <del> err = json.NewDecoder(resp.body).Decode(&server) <del> return server, err <del>} <ide><path>api/client/lib/volume.go <del>package lib <del> <del>import ( <del> "encoding/json" <del> "net/http" <del> "net/url" <del> <del> "github.com/docker/engine-api/types" <del> "github.com/docker/engine-api/types/filters" <del>) <del> <del>// VolumeList returns the volumes configured in the docker host. <del>func (cli *Client) VolumeList(filter filters.Args) (types.VolumesListResponse, error) { <del> var volumes types.VolumesListResponse <del> query := url.Values{} <del> <del> if filter.Len() > 0 { <del> filterJSON, err := filters.ToParam(filter) <del> if err != nil { <del> return volumes, err <del> } <del> query.Set("filters", filterJSON) <del> } <del> resp, err := cli.get("/volumes", query, nil) <del> if err != nil { <del> return volumes, err <del> } <del> defer ensureReaderClosed(resp) <del> <del> err = json.NewDecoder(resp.body).Decode(&volumes) <del> return volumes, err <del>} <del> <del>// VolumeInspect returns the information about a specific volume in the docker host. <del>func (cli *Client) VolumeInspect(volumeID string) (types.Volume, error) { <del> var volume types.Volume <del> resp, err := cli.get("/volumes/"+volumeID, nil, nil) <del> if err != nil { <del> if resp.statusCode == http.StatusNotFound { <del> return volume, volumeNotFoundError{volumeID} <del> } <del> return volume, err <del> } <del> defer ensureReaderClosed(resp) <del> err = json.NewDecoder(resp.body).Decode(&volume) <del> return volume, err <del>} <del> <del>// VolumeCreate creates a volume in the docker host. <del>func (cli *Client) VolumeCreate(options types.VolumeCreateRequest) (types.Volume, error) { <del> var volume types.Volume <del> resp, err := cli.post("/volumes/create", nil, options, nil) <del> if err != nil { <del> return volume, err <del> } <del> defer ensureReaderClosed(resp) <del> err = json.NewDecoder(resp.body).Decode(&volume) <del> return volume, err <del>} <del> <del>// VolumeRemove removes a volume from the docker host. <del>func (cli *Client) VolumeRemove(volumeID string) error { <del> resp, err := cli.delete("/volumes/"+volumeID, nil, nil) <del> ensureReaderClosed(resp) <del> return err <del>} <ide><path>api/client/lib/wait.go <del>package lib <del> <del>import ( <del> "encoding/json" <del> <del> "github.com/docker/engine-api/types" <del>) <del> <del>// ContainerWait pauses execution util a container is exits. <del>// It returns the API status code as response of its readiness. <del>func (cli *Client) ContainerWait(containerID string) (int, error) { <del> resp, err := cli.post("/containers/"+containerID+"/wait", nil, nil, nil) <del> if err != nil { <del> return -1, err <del> } <del> defer ensureReaderClosed(resp) <del> <del> var res types.ContainerWaitResponse <del> if err := json.NewDecoder(resp.body).Decode(&res); err != nil { <del> return -1, err <del> } <del> <del> return res.StatusCode, nil <del>} <ide><path>api/types/auth.go <del>package types <del> <del>// AuthConfig contains authorization information for connecting to a Registry <del>type AuthConfig struct { <del> Username string `json:"username,omitempty"` <del> Password string `json:"password,omitempty"` <del> Auth string `json:"auth"` <del> Email string `json:"email"` <del> ServerAddress string `json:"serveraddress,omitempty"` <del> RegistryToken string `json:"registrytoken,omitempty"` <del>} <ide><path>api/types/blkiodev/blkio.go <del>package blkiodev <del> <del>import "fmt" <del> <del>// WeightDevice is a structure that hold device:weight pair <del>type WeightDevice struct { <del> Path string <del> Weight uint16 <del>} <del> <del>func (w *WeightDevice) String() string { <del> return fmt.Sprintf("%s:%d", w.Path, w.Weight) <del>} <del> <del>// ThrottleDevice is a structure that hold device:rate_per_second pair <del>type ThrottleDevice struct { <del> Path string <del> Rate uint64 <del>} <del> <del>func (t *ThrottleDevice) String() string { <del> return fmt.Sprintf("%s:%d", t.Path, t.Rate) <del>} <ide><path>api/types/client.go <del>package types <del> <del>import ( <del> "bufio" <del> "io" <del> "net" <del> <del> "github.com/docker/engine-api/types/container" <del> "github.com/docker/engine-api/types/filters" <del> "github.com/docker/go-units" <del>) <del> <del>// ContainerAttachOptions holds parameters to attach to a container. <del>type ContainerAttachOptions struct { <del> ContainerID string <del> Stream bool <del> Stdin bool <del> Stdout bool <del> Stderr bool <del> DetachKeys string <del>} <del> <del>// ContainerCommitOptions holds parameters to commit changes into a container. <del>type ContainerCommitOptions struct { <del> ContainerID string <del> RepositoryName string <del> Tag string <del> Comment string <del> Author string <del> Changes []string <del> Pause bool <del> Config *container.Config <del>} <del> <del>// ContainerExecInspect holds information returned by exec inspect. <del>type ContainerExecInspect struct { <del> ExecID string <del> ContainerID string <del> Running bool <del> ExitCode int <del>} <del> <del>// ContainerListOptions holds parameters to list containers with. <del>type ContainerListOptions struct { <del> Quiet bool <del> Size bool <del> All bool <del> Latest bool <del> Since string <del> Before string <del> Limit int <del> Filter filters.Args <del>} <del> <del>// ContainerLogsOptions holds parameters to filter logs with. <del>type ContainerLogsOptions struct { <del> ContainerID string <del> ShowStdout bool <del> ShowStderr bool <del> Since string <del> Timestamps bool <del> Follow bool <del> Tail string <del>} <del> <del>// ContainerRemoveOptions holds parameters to remove containers. <del>type ContainerRemoveOptions struct { <del> ContainerID string <del> RemoveVolumes bool <del> RemoveLinks bool <del> Force bool <del>} <del> <del>// CopyToContainerOptions holds information <del>// about files to copy into a container <del>type CopyToContainerOptions struct { <del> ContainerID string <del> Path string <del> Content io.Reader <del> AllowOverwriteDirWithFile bool <del>} <del> <del>// EventsOptions hold parameters to filter events with. <del>type EventsOptions struct { <del> Since string <del> Until string <del> Filters filters.Args <del>} <del> <del>// NetworkListOptions holds parameters to filter the list of networks with. <del>type NetworkListOptions struct { <del> Filters filters.Args <del>} <del> <del>// HijackedResponse holds connection information for a hijacked request. <del>type HijackedResponse struct { <del> Conn net.Conn <del> Reader *bufio.Reader <del>} <del> <del>// Close closes the hijacked connection and reader. <del>func (h *HijackedResponse) Close() { <del> h.Conn.Close() <del>} <del> <del>// CloseWriter is an interface that implement structs <del>// that close input streams to prevent from writing. <del>type CloseWriter interface { <del> CloseWrite() error <del>} <del> <del>// CloseWrite closes a readWriter for writing. <del>func (h *HijackedResponse) CloseWrite() error { <del> if conn, ok := h.Conn.(CloseWriter); ok { <del> return conn.CloseWrite() <del> } <del> return nil <del>} <del> <del>// ImageBuildOptions holds the information <del>// necessary to build images. <del>type ImageBuildOptions struct { <del> Tags []string <del> SuppressOutput bool <del> RemoteContext string <del> NoCache bool <del> Remove bool <del> ForceRemove bool <del> PullParent bool <del> IsolationLevel container.IsolationLevel <del> CPUSetCPUs string <del> CPUSetMems string <del> CPUShares int64 <del> CPUQuota int64 <del> CPUPeriod int64 <del> Memory int64 <del> MemorySwap int64 <del> CgroupParent string <del> ShmSize int64 <del> Dockerfile string <del> Ulimits []*units.Ulimit <del> BuildArgs map[string]string <del> AuthConfigs map[string]AuthConfig <del> Context io.Reader <del>} <del> <del>// ImageBuildResponse holds information <del>// returned by a server after building <del>// an image. <del>type ImageBuildResponse struct { <del> Body io.ReadCloser <del> OSType string <del>} <del> <del>// ImageCreateOptions holds information to create images. <del>type ImageCreateOptions struct { <del> // Parent is the image to create this image from <del> Parent string <del> // Tag is the name to tag this image <del> Tag string <del> // RegistryAuth is the base64 encoded credentials for this server <del> RegistryAuth string <del>} <del> <del>// ImageImportOptions holds information to import images from the client host. <del>type ImageImportOptions struct { <del> // Source is the data to send to the server to create this image from <del> Source io.Reader <del> // Source is the name of the source to import this image from <del> SourceName string <del> // RepositoryName is the name of the repository to import this image <del> RepositoryName string <del> // Message is the message to tag the image with <del> Message string <del> // Tag is the name to tag this image <del> Tag string <del> // Changes are the raw changes to apply to the image <del> Changes []string <del>} <del> <del>// ImageListOptions holds parameters to filter the list of images with. <del>type ImageListOptions struct { <del> MatchName string <del> All bool <del> Filters filters.Args <del>} <del> <del>// ImageLoadResponse returns information to the client about a load process. <del>type ImageLoadResponse struct { <del> Body io.ReadCloser <del> JSON bool <del>} <del> <del>// ImagePullOptions holds information to pull images. <del>type ImagePullOptions struct { <del> ImageID string <del> Tag string <del> // RegistryAuth is the base64 encoded credentials for this server <del> RegistryAuth string <del>} <del> <del>//ImagePushOptions holds information to push images. <del>type ImagePushOptions ImagePullOptions <del> <del>// ImageRemoveOptions holds parameters to remove images. <del>type ImageRemoveOptions struct { <del> ImageID string <del> Force bool <del> PruneChildren bool <del>} <del> <del>// ImageSearchOptions holds parameters to search images with. <del>type ImageSearchOptions struct { <del> Term string <del> RegistryAuth string <del>} <del> <del>// ImageTagOptions holds parameters to tag an image <del>type ImageTagOptions struct { <del> ImageID string <del> RepositoryName string <del> Tag string <del> Force bool <del>} <del> <del>// ResizeOptions holds parameters to resize a tty. <del>// It can be used to resize container ttys and <del>// exec process ttys too. <del>type ResizeOptions struct { <del> ID string <del> Height int <del> Width int <del>} <del> <del>// VersionResponse holds version information for the client and the server <del>type VersionResponse struct { <del> Client *Version <del> Server *Version <del>} <del> <del>// ServerOK return true when the client could connect to the docker server <del>// and parse the information received. It returns false otherwise. <del>func (v VersionResponse) ServerOK() bool { <del> return v.Server != nil <del>} <ide><path>api/types/configs.go <del>package types <del> <del>import "github.com/docker/engine-api/types/container" <del> <del>// configs holds structs used for internal communication between the <del>// frontend (such as an http server) and the backend (such as the <del>// docker daemon). <del> <del>// ContainerCreateConfig is the parameter set to ContainerCreate() <del>type ContainerCreateConfig struct { <del> Name string <del> Config *container.Config <del> HostConfig *container.HostConfig <del> AdjustCPUShares bool <del>} <del> <del>// ContainerRmConfig holds arguments for the container remove <del>// operation. This struct is used to tell the backend what operations <del>// to perform. <del>type ContainerRmConfig struct { <del> ForceRemove, RemoveVolume, RemoveLink bool <del>} <del> <del>// ContainerCommitConfig contains build configs for commit operation, <del>// and is used when making a commit with the current state of the container. <del>type ContainerCommitConfig struct { <del> Pause bool <del> Repo string <del> Tag string <del> Author string <del> Comment string <del> // merge container config into commit config before commit <del> MergeConfigs bool <del> Config *container.Config <del>} <del> <del>// ExecConfig is a small subset of the Config struct that hold the configuration <del>// for the exec feature of docker. <del>type ExecConfig struct { <del> User string // User that will run the command <del> Privileged bool // Is the container in privileged mode <del> Tty bool // Attach standard streams to a tty. <del> Container string // Name of the container (to execute in) <del> AttachStdin bool // Attach the standard input, makes possible user interaction <del> AttachStderr bool // Attach the standard output <del> AttachStdout bool // Attach the standard error <del> Detach bool // Execute in detach mode <del> DetachKeys string // Escape keys for detach <del> Cmd []string // Execution commands and args <del>} <ide><path>api/types/container/config.go <del>package container <del> <del>import ( <del> "github.com/docker/engine-api/types/strslice" <del> "github.com/docker/go-connections/nat" <del>) <del> <del>// Config contains the configuration data about a container. <del>// It should hold only portable information about the container. <del>// Here, "portable" means "independent from the host we are running on". <del>// Non-portable information *should* appear in HostConfig. <del>// All fields added to this struct must be marked `omitempty` to keep getting <del>// predictable hashes from the old `v1Compatibility` configuration. <del>type Config struct { <del> Hostname string // Hostname <del> Domainname string // Domainname <del> User string // User that will run the command(s) inside the container <del> AttachStdin bool // Attach the standard input, makes possible user interaction <del> AttachStdout bool // Attach the standard output <del> AttachStderr bool // Attach the standard error <del> ExposedPorts map[nat.Port]struct{} `json:",omitempty"` // List of exposed ports <del> PublishService string `json:",omitempty"` // Name of the network service exposed by the container <del> Tty bool // Attach standard streams to a tty, including stdin if it is not closed. <del> OpenStdin bool // Open stdin <del> StdinOnce bool // If true, close stdin after the 1 attached client disconnects. <del> Env []string // List of environment variable to set in the container <del> Cmd *strslice.StrSlice // Command to run when starting the container <del> ArgsEscaped bool `json:",omitempty"` // True if command is already escaped (Windows specific) <del> Image string // Name of the image as it was passed by the operator (eg. could be symbolic) <del> Volumes map[string]struct{} // List of volumes (mounts) used for the container <del> WorkingDir string // Current directory (PWD) in the command will be launched <del> Entrypoint *strslice.StrSlice // Entrypoint to run when starting the container <del> NetworkDisabled bool `json:",omitempty"` // Is network disabled <del> MacAddress string `json:",omitempty"` // Mac Address of the container <del> OnBuild []string // ONBUILD metadata that were defined on the image Dockerfile <del> Labels map[string]string // List of labels set to this container <del> StopSignal string `json:",omitempty"` // Signal to stop a container <del>} <ide><path>api/types/container/host_config.go <del>package container <del> <del>import ( <del> "strings" <del> <del> "github.com/docker/engine-api/types/blkiodev" <del> "github.com/docker/engine-api/types/strslice" <del> "github.com/docker/go-connections/nat" <del> "github.com/docker/go-units" <del>) <del> <del>// NetworkMode represents the container network stack. <del>type NetworkMode string <del> <del>// IsolationLevel represents the isolation level of a container. The supported <del>// values are platform specific <del>type IsolationLevel string <del> <del>// IsDefault indicates the default isolation level of a container. On Linux this <del>// is the native driver. On Windows, this is a Windows Server Container. <del>func (i IsolationLevel) IsDefault() bool { <del> return strings.ToLower(string(i)) == "default" || string(i) == "" <del>} <del> <del>// IpcMode represents the container ipc stack. <del>type IpcMode string <del> <del>// IsPrivate indicates whether the container uses it's private ipc stack. <del>func (n IpcMode) IsPrivate() bool { <del> return !(n.IsHost() || n.IsContainer()) <del>} <del> <del>// IsHost indicates whether the container uses the host's ipc stack. <del>func (n IpcMode) IsHost() bool { <del> return n == "host" <del>} <del> <del>// IsContainer indicates whether the container uses a container's ipc stack. <del>func (n IpcMode) IsContainer() bool { <del> parts := strings.SplitN(string(n), ":", 2) <del> return len(parts) > 1 && parts[0] == "container" <del>} <del> <del>// Valid indicates whether the ipc stack is valid. <del>func (n IpcMode) Valid() bool { <del> parts := strings.Split(string(n), ":") <del> switch mode := parts[0]; mode { <del> case "", "host": <del> case "container": <del> if len(parts) != 2 || parts[1] == "" { <del> return false <del> } <del> default: <del> return false <del> } <del> return true <del>} <del> <del>// Container returns the name of the container ipc stack is going to be used. <del>func (n IpcMode) Container() string { <del> parts := strings.SplitN(string(n), ":", 2) <del> if len(parts) > 1 { <del> return parts[1] <del> } <del> return "" <del>} <del> <del>// UTSMode represents the UTS namespace of the container. <del>type UTSMode string <del> <del>// IsPrivate indicates whether the container uses it's private UTS namespace. <del>func (n UTSMode) IsPrivate() bool { <del> return !(n.IsHost()) <del>} <del> <del>// IsHost indicates whether the container uses the host's UTS namespace. <del>func (n UTSMode) IsHost() bool { <del> return n == "host" <del>} <del> <del>// Valid indicates whether the UTS namespace is valid. <del>func (n UTSMode) Valid() bool { <del> parts := strings.Split(string(n), ":") <del> switch mode := parts[0]; mode { <del> case "", "host": <del> default: <del> return false <del> } <del> return true <del>} <del> <del>// PidMode represents the pid stack of the container. <del>type PidMode string <del> <del>// IsPrivate indicates whether the container uses it's private pid stack. <del>func (n PidMode) IsPrivate() bool { <del> return !(n.IsHost()) <del>} <del> <del>// IsHost indicates whether the container uses the host's pid stack. <del>func (n PidMode) IsHost() bool { <del> return n == "host" <del>} <del> <del>// Valid indicates whether the pid stack is valid. <del>func (n PidMode) Valid() bool { <del> parts := strings.Split(string(n), ":") <del> switch mode := parts[0]; mode { <del> case "", "host": <del> default: <del> return false <del> } <del> return true <del>} <del> <del>// DeviceMapping represents the device mapping between the host and the container. <del>type DeviceMapping struct { <del> PathOnHost string <del> PathInContainer string <del> CgroupPermissions string <del>} <del> <del>// RestartPolicy represents the restart policies of the container. <del>type RestartPolicy struct { <del> Name string <del> MaximumRetryCount int <del>} <del> <del>// IsNone indicates whether the container has the "no" restart policy. <del>// This means the container will not automatically restart when exiting. <del>func (rp *RestartPolicy) IsNone() bool { <del> return rp.Name == "no" <del>} <del> <del>// IsAlways indicates whether the container has the "always" restart policy. <del>// This means the container will automatically restart regardless of the exit status. <del>func (rp *RestartPolicy) IsAlways() bool { <del> return rp.Name == "always" <del>} <del> <del>// IsOnFailure indicates whether the container has the "on-failure" restart policy. <del>// This means the contain will automatically restart of exiting with a non-zero exit status. <del>func (rp *RestartPolicy) IsOnFailure() bool { <del> return rp.Name == "on-failure" <del>} <del> <del>// IsUnlessStopped indicates whether the container has the <del>// "unless-stopped" restart policy. This means the container will <del>// automatically restart unless user has put it to stopped state. <del>func (rp *RestartPolicy) IsUnlessStopped() bool { <del> return rp.Name == "unless-stopped" <del>} <del> <del>// LogConfig represents the logging configuration of the container. <del>type LogConfig struct { <del> Type string <del> Config map[string]string <del>} <del> <del>// Resources contains container's resources (cgroups config, ulimits...) <del>type Resources struct { <del> // Applicable to all platforms <del> CPUShares int64 `json:"CpuShares"` // CPU shares (relative weight vs. other containers) <del> <del> // Applicable to UNIX platforms <del> CgroupParent string // Parent cgroup. <del> BlkioWeight uint16 // Block IO weight (relative weight vs. other containers) <del> BlkioWeightDevice []*blkiodev.WeightDevice <del> BlkioDeviceReadBps []*blkiodev.ThrottleDevice <del> BlkioDeviceWriteBps []*blkiodev.ThrottleDevice <del> BlkioDeviceReadIOps []*blkiodev.ThrottleDevice <del> BlkioDeviceWriteIOps []*blkiodev.ThrottleDevice <del> CPUPeriod int64 `json:"CpuPeriod"` // CPU CFS (Completely Fair Scheduler) period <del> CPUQuota int64 `json:"CpuQuota"` // CPU CFS (Completely Fair Scheduler) quota <del> CpusetCpus string // CpusetCpus 0-2, 0,1 <del> CpusetMems string // CpusetMems 0-2, 0,1 <del> Devices []DeviceMapping // List of devices to map inside the container <del> KernelMemory int64 // Kernel memory limit (in bytes) <del> Memory int64 // Memory limit (in bytes) <del> MemoryReservation int64 // Memory soft limit (in bytes) <del> MemorySwap int64 // Total memory usage (memory + swap); set `-1` to disable swap <del> MemorySwappiness *int64 // Tuning container memory swappiness behaviour <del> OomKillDisable bool // Whether to disable OOM Killer or not <del> Ulimits []*units.Ulimit // List of ulimits to be set in the container <del>} <del> <del>// HostConfig the non-portable Config structure of a container. <del>// Here, "non-portable" means "dependent of the host we are running on". <del>// Portable information *should* appear in Config. <del>type HostConfig struct { <del> // Applicable to all platforms <del> Binds []string // List of volume bindings for this container <del> ContainerIDFile string // File (path) where the containerId is written <del> LogConfig LogConfig // Configuration of the logs for this container <del> NetworkMode NetworkMode // Network mode to use for the container <del> PortBindings nat.PortMap // Port mapping between the exposed port (container) and the host <del> RestartPolicy RestartPolicy // Restart policy to be used for the container <del> VolumeDriver string // Name of the volume driver used to mount volumes <del> VolumesFrom []string // List of volumes to take from other container <del> <del> // Applicable to UNIX platforms <del> CapAdd *strslice.StrSlice // List of kernel capabilities to add to the container <del> CapDrop *strslice.StrSlice // List of kernel capabilities to remove from the container <del> DNS []string `json:"Dns"` // List of DNS server to lookup <del> DNSOptions []string `json:"DnsOptions"` // List of DNSOption to look for <del> DNSSearch []string `json:"DnsSearch"` // List of DNSSearch to look for <del> ExtraHosts []string // List of extra hosts <del> GroupAdd []string // List of additional groups that the container process will run as <del> IpcMode IpcMode // IPC namespace to use for the container <del> Links []string // List of links (in the name:alias form) <del> OomScoreAdj int // Container preference for OOM-killing <del> PidMode PidMode // PID namespace to use for the container <del> Privileged bool // Is the container in privileged mode <del> PublishAllPorts bool // Should docker publish all exposed port for the container <del> ReadonlyRootfs bool // Is the container root filesystem in read-only <del> SecurityOpt []string // List of string values to customize labels for MLS systems, such as SELinux. <del> Tmpfs map[string]string `json:",omitempty"` // List of tmpfs (mounts) used for the container <del> UTSMode UTSMode // UTS namespace to use for the container <del> ShmSize int64 // Total shm memory usage <del> <del> // Applicable to Windows <del> ConsoleSize [2]int // Initial console size <del> Isolation IsolationLevel // Isolation level of the container (eg default, hyperv) <del> <del> // Contains container's resources (cgroups, ulimits) <del> Resources <del>} <ide><path>api/types/container/hostconfig_unix.go <del>// +build !windows <del> <del>package container <del> <del>import "strings" <del> <del>// IsValid indicates is an isolation level is valid <del>func (i IsolationLevel) IsValid() bool { <del> return i.IsDefault() <del>} <del> <del>// IsPrivate indicates whether container uses it's private network stack. <del>func (n NetworkMode) IsPrivate() bool { <del> return !(n.IsHost() || n.IsContainer()) <del>} <del> <del>// IsDefault indicates whether container uses the default network stack. <del>func (n NetworkMode) IsDefault() bool { <del> return n == "default" <del>} <del> <del>// NetworkName returns the name of the network stack. <del>func (n NetworkMode) NetworkName() string { <del> if n.IsBridge() { <del> return "bridge" <del> } else if n.IsHost() { <del> return "host" <del> } else if n.IsContainer() { <del> return "container" <del> } else if n.IsNone() { <del> return "none" <del> } else if n.IsDefault() { <del> return "default" <del> } else if n.IsUserDefined() { <del> return n.UserDefined() <del> } <del> return "" <del>} <del> <del>// IsBridge indicates whether container uses the bridge network stack <del>func (n NetworkMode) IsBridge() bool { <del> return n == "bridge" <del>} <del> <del>// IsHost indicates whether container uses the host network stack. <del>func (n NetworkMode) IsHost() bool { <del> return n == "host" <del>} <del> <del>// IsContainer indicates whether container uses a container network stack. <del>func (n NetworkMode) IsContainer() bool { <del> parts := strings.SplitN(string(n), ":", 2) <del> return len(parts) > 1 && parts[0] == "container" <del>} <del> <del>// IsNone indicates whether container isn't using a network stack. <del>func (n NetworkMode) IsNone() bool { <del> return n == "none" <del>} <del> <del>// ConnectedContainer is the id of the container which network this container is connected to. <del>func (n NetworkMode) ConnectedContainer() string { <del> parts := strings.SplitN(string(n), ":", 2) <del> if len(parts) > 1 { <del> return parts[1] <del> } <del> return "" <del>} <del> <del>// IsUserDefined indicates user-created network <del>func (n NetworkMode) IsUserDefined() bool { <del> return !n.IsDefault() && !n.IsBridge() && !n.IsHost() && !n.IsNone() && !n.IsContainer() <del>} <del> <del>// IsPreDefinedNetwork indicates if a network is predefined by the daemon <del>func IsPreDefinedNetwork(network string) bool { <del> n := NetworkMode(network) <del> return n.IsBridge() || n.IsHost() || n.IsNone() <del>} <del> <del>//UserDefined indicates user-created network <del>func (n NetworkMode) UserDefined() string { <del> if n.IsUserDefined() { <del> return string(n) <del> } <del> return "" <del>} <ide><path>api/types/container/hostconfig_windows.go <del>package container <del> <del>import ( <del> "fmt" <del> "strings" <del>) <del> <del>// IsDefault indicates whether container uses the default network stack. <del>func (n NetworkMode) IsDefault() bool { <del> return n == "default" <del>} <del> <del>// IsHyperV indicates the use of a Hyper-V partition for isolation <del>func (i IsolationLevel) IsHyperV() bool { <del> return strings.ToLower(string(i)) == "hyperv" <del>} <del> <del>// IsProcess indicates the use of process isolation <del>func (i IsolationLevel) IsProcess() bool { <del> return strings.ToLower(string(i)) == "process" <del>} <del> <del>// IsValid indicates is an isolation level is valid <del>func (i IsolationLevel) IsValid() bool { <del> return i.IsDefault() || i.IsHyperV() || i.IsProcess() <del>} <del> <del>// DefaultDaemonNetworkMode returns the default network stack the daemon should <del>// use. <del>func DefaultDaemonNetworkMode() NetworkMode { <del> return NetworkMode("default") <del>} <del> <del>// NetworkName returns the name of the network stack. <del>func (n NetworkMode) NetworkName() string { <del> if n.IsDefault() { <del> return "default" <del> } <del> return "" <del>} <del> <del>// IsPreDefinedNetwork indicates if a network is predefined by the daemon <del>func IsPreDefinedNetwork(network string) bool { <del> return false <del>} <del> <del>// ValidateNetMode ensures that the various combinations of requested <del>// network settings are valid. <del>func ValidateNetMode(c *Config, hc *HostConfig) error { <del> // We may not be passed a host config, such as in the case of docker commit <del> if hc == nil { <del> return nil <del> } <del> parts := strings.Split(string(hc.NetworkMode), ":") <del> switch mode := parts[0]; mode { <del> case "default", "none": <del> default: <del> return fmt.Errorf("invalid --net: %s", hc.NetworkMode) <del> } <del> return nil <del>} <del> <del>// ValidateIsolationLevel performs platform specific validation of the <del>// isolation level in the hostconfig structure. Windows supports 'default' (or <del>// blank), 'process', or 'hyperv'. <del>func ValidateIsolationLevel(hc *HostConfig) error { <del> // We may not be passed a host config, such as in the case of docker commit <del> if hc == nil { <del> return nil <del> } <del> if !hc.Isolation.IsValid() { <del> return fmt.Errorf("invalid --isolation: %q. Windows supports 'default', 'process', or 'hyperv'", hc.Isolation) <del> } <del> return nil <del>} <ide><path>api/types/events/events.go <del>package events <del> <del>const ( <del> // ContainerEventType is the event type that containers generate <del> ContainerEventType = "container" <del> // ImageEventType is the event type that images generate <del> ImageEventType = "image" <del> // VolumeEventType is the event type that volumes generate <del> VolumeEventType = "volume" <del> // NetworkEventType is the event type that networks generate <del> NetworkEventType = "network" <del>) <del> <del>// Actor describes something that generates events, <del>// like a container, or a network, or a volume. <del>// It has a defined name and a set or attributes. <del>// The container attributes are its labels, other actors <del>// can generate these attributes from other properties. <del>type Actor struct { <del> ID string <del> Attributes map[string]string <del>} <del> <del>// Message represents the information an event contains <del>type Message struct { <del> // Deprecated information from JSONMessage. <del> // With data only in container events. <del> Status string `json:"status,omitempty"` <del> ID string `json:"id,omitempty"` <del> From string `json:"from,omitempty"` <del> <del> Type string <del> Action string <del> Actor Actor <del> <del> Time int64 `json:"time,omitempty"` <del> TimeNano int64 `json:"timeNano,omitempty"` <del>} <ide><path>api/types/filters/parse.go <del>// Package filters provides helper function to parse and handle command line <del>// filter, used for example in docker ps or docker images commands. <del>package filters <del> <del>import ( <del> "encoding/json" <del> "errors" <del> "fmt" <del> "regexp" <del> "strings" <del>) <del> <del>// Args stores filter arguments as map key:{array of values}. <del>// It contains a aggregation of the list of arguments (which are in the form <del>// of -f 'key=value') based on the key, and store values for the same key <del>// in an slice. <del>// e.g given -f 'label=label1=1' -f 'label=label2=2' -f 'image.name=ubuntu' <del>// the args will be {'label': {'label1=1','label2=2'}, 'image.name', {'ubuntu'}} <del>type Args struct { <del> fields map[string]map[string]bool <del>} <del> <del>// NewArgs initializes a new Args struct. <del>func NewArgs() Args { <del> return Args{fields: map[string]map[string]bool{}} <del>} <del> <del>// ParseFlag parses the argument to the filter flag. Like <del>// <del>// `docker ps -f 'created=today' -f 'image.name=ubuntu*'` <del>// <del>// If prev map is provided, then it is appended to, and returned. By default a new <del>// map is created. <del>func ParseFlag(arg string, prev Args) (Args, error) { <del> filters := prev <del> if len(arg) == 0 { <del> return filters, nil <del> } <del> <del> if !strings.Contains(arg, "=") { <del> return filters, ErrBadFormat <del> } <del> <del> f := strings.SplitN(arg, "=", 2) <del> <del> name := strings.ToLower(strings.TrimSpace(f[0])) <del> value := strings.TrimSpace(f[1]) <del> <del> filters.Add(name, value) <del> <del> return filters, nil <del>} <del> <del>// ErrBadFormat is an error returned in case of bad format for a filter. <del>var ErrBadFormat = errors.New("bad format of filter (expected name=value)") <del> <del>// ToParam packs the Args into an string for easy transport from client to server. <del>func ToParam(a Args) (string, error) { <del> // this way we don't URL encode {}, just empty space <del> if a.Len() == 0 { <del> return "", nil <del> } <del> <del> buf, err := json.Marshal(a.fields) <del> if err != nil { <del> return "", err <del> } <del> return string(buf), nil <del>} <del> <del>// FromParam unpacks the filter Args. <del>func FromParam(p string) (Args, error) { <del> if len(p) == 0 { <del> return NewArgs(), nil <del> } <del> <del> r := strings.NewReader(p) <del> d := json.NewDecoder(r) <del> <del> m := map[string]map[string]bool{} <del> if err := d.Decode(&m); err != nil { <del> r.Seek(0, 0) <del> <del> // Allow parsing old arguments in slice format. <del> // Because other libraries might be sending them in this format. <del> deprecated := map[string][]string{} <del> if deprecatedErr := d.Decode(&deprecated); deprecatedErr == nil { <del> m = deprecatedArgs(deprecated) <del> } else { <del> return NewArgs(), err <del> } <del> } <del> return Args{m}, nil <del>} <del> <del>// Get returns the list of values associates with a field. <del>// It returns a slice of strings to keep backwards compatibility with old code. <del>func (filters Args) Get(field string) []string { <del> values := filters.fields[field] <del> if values == nil { <del> return make([]string, 0) <del> } <del> slice := make([]string, 0, len(values)) <del> for key := range values { <del> slice = append(slice, key) <del> } <del> return slice <del>} <del> <del>// Add adds a new value to a filter field. <del>func (filters Args) Add(name, value string) { <del> if _, ok := filters.fields[name]; ok { <del> filters.fields[name][value] = true <del> } else { <del> filters.fields[name] = map[string]bool{value: true} <del> } <del>} <del> <del>// Del removes a value from a filter field. <del>func (filters Args) Del(name, value string) { <del> if _, ok := filters.fields[name]; ok { <del> delete(filters.fields[name], value) <del> } <del>} <del> <del>// Len returns the number of fields in the arguments. <del>func (filters Args) Len() int { <del> return len(filters.fields) <del>} <del> <del>// MatchKVList returns true if the values for the specified field matches the ones <del>// from the sources. <del>// e.g. given Args are {'label': {'label1=1','label2=1'}, 'image.name', {'ubuntu'}}, <del>// field is 'label' and sources are {'label1': '1', 'label2': '2'} <del>// it returns true. <del>func (filters Args) MatchKVList(field string, sources map[string]string) bool { <del> fieldValues := filters.fields[field] <del> <del> //do not filter if there is no filter set or cannot determine filter <del> if len(fieldValues) == 0 { <del> return true <del> } <del> <del> if sources == nil || len(sources) == 0 { <del> return false <del> } <del> <del> for name2match := range fieldValues { <del> testKV := strings.SplitN(name2match, "=", 2) <del> <del> v, ok := sources[testKV[0]] <del> if !ok { <del> return false <del> } <del> if len(testKV) == 2 && testKV[1] != v { <del> return false <del> } <del> } <del> <del> return true <del>} <del> <del>// Match returns true if the values for the specified field matches the source string <del>// e.g. given Args are {'label': {'label1=1','label2=1'}, 'image.name', {'ubuntu'}}, <del>// field is 'image.name' and source is 'ubuntu' <del>// it returns true. <del>func (filters Args) Match(field, source string) bool { <del> if filters.ExactMatch(field, source) { <del> return true <del> } <del> <del> fieldValues := filters.fields[field] <del> for name2match := range fieldValues { <del> match, err := regexp.MatchString(name2match, source) <del> if err != nil { <del> continue <del> } <del> if match { <del> return true <del> } <del> } <del> return false <del>} <del> <del>// ExactMatch returns true if the source matches exactly one of the filters. <del>func (filters Args) ExactMatch(field, source string) bool { <del> fieldValues, ok := filters.fields[field] <del> //do not filter if there is no filter set or cannot determine filter <del> if !ok || len(fieldValues) == 0 { <del> return true <del> } <del> <del> // try to march full name value to avoid O(N) regular expression matching <del> if fieldValues[source] { <del> return true <del> } <del> return false <del>} <del> <del>// FuzzyMatch returns true if the source matches exactly one of the filters, <del>// or the source has one of the filters as a prefix. <del>func (filters Args) FuzzyMatch(field, source string) bool { <del> if filters.ExactMatch(field, source) { <del> return true <del> } <del> <del> fieldValues := filters.fields[field] <del> for prefix := range fieldValues { <del> if strings.HasPrefix(source, prefix) { <del> return true <del> } <del> } <del> return false <del>} <del> <del>// Include returns true if the name of the field to filter is in the filters. <del>func (filters Args) Include(field string) bool { <del> _, ok := filters.fields[field] <del> return ok <del>} <del> <del>// Validate ensures that all the fields in the filter are valid. <del>// It returns an error as soon as it finds an invalid field. <del>func (filters Args) Validate(accepted map[string]bool) error { <del> for name := range filters.fields { <del> if !accepted[name] { <del> return fmt.Errorf("Invalid filter '%s'", name) <del> } <del> } <del> return nil <del>} <del> <del>// WalkValues iterates over the list of filtered values for a field. <del>// It stops the iteration if it finds an error and it returns that error. <del>func (filters Args) WalkValues(field string, op func(value string) error) error { <del> if _, ok := filters.fields[field]; !ok { <del> return nil <del> } <del> for v := range filters.fields[field] { <del> if err := op(v); err != nil { <del> return err <del> } <del> } <del> return nil <del>} <del> <del>func deprecatedArgs(d map[string][]string) map[string]map[string]bool { <del> m := map[string]map[string]bool{} <del> for k, v := range d { <del> values := map[string]bool{} <del> for _, vv := range v { <del> values[vv] = true <del> } <del> m[k] = values <del> } <del> return m <del>} <ide><path>api/types/filters/parse_test.go <del>package filters <del> <del>import ( <del> "fmt" <del> "testing" <del>) <del> <del>func TestParseArgs(t *testing.T) { <del> // equivalent of `docker ps -f 'created=today' -f 'image.name=ubuntu*' -f 'image.name=*untu'` <del> flagArgs := []string{ <del> "created=today", <del> "image.name=ubuntu*", <del> "image.name=*untu", <del> } <del> var ( <del> args = NewArgs() <del> err error <del> ) <del> for i := range flagArgs { <del> args, err = ParseFlag(flagArgs[i], args) <del> if err != nil { <del> t.Errorf("failed to parse %s: %s", flagArgs[i], err) <del> } <del> } <del> if len(args.Get("created")) != 1 { <del> t.Errorf("failed to set this arg") <del> } <del> if len(args.Get("image.name")) != 2 { <del> t.Errorf("the args should have collapsed") <del> } <del>} <del> <del>func TestParseArgsEdgeCase(t *testing.T) { <del> var filters Args <del> args, err := ParseFlag("", filters) <del> if err != nil { <del> t.Fatal(err) <del> } <del> if args.Len() != 0 { <del> t.Fatalf("Expected an empty Args (map), got %v", args) <del> } <del> if args, err = ParseFlag("anything", args); err == nil || err != ErrBadFormat { <del> t.Fatalf("Expected ErrBadFormat, got %v", err) <del> } <del>} <del> <del>func TestToParam(t *testing.T) { <del> fields := map[string]map[string]bool{ <del> "created": {"today": true}, <del> "image.name": {"ubuntu*": true, "*untu": true}, <del> } <del> a := Args{fields: fields} <del> <del> _, err := ToParam(a) <del> if err != nil { <del> t.Errorf("failed to marshal the filters: %s", err) <del> } <del>} <del> <del>func TestFromParam(t *testing.T) { <del> invalids := []string{ <del> "anything", <del> "['a','list']", <del> "{'key': 'value'}", <del> `{"key": "value"}`, <del> } <del> valid := map[*Args][]string{ <del> &Args{fields: map[string]map[string]bool{"key": {"value": true}}}: { <del> `{"key": ["value"]}`, <del> `{"key": {"value": true}}`, <del> }, <del> &Args{fields: map[string]map[string]bool{"key": {"value1": true, "value2": true}}}: { <del> `{"key": ["value1", "value2"]}`, <del> `{"key": {"value1": true, "value2": true}}`, <del> }, <del> &Args{fields: map[string]map[string]bool{"key1": {"value1": true}, "key2": {"value2": true}}}: { <del> `{"key1": ["value1"], "key2": ["value2"]}`, <del> `{"key1": {"value1": true}, "key2": {"value2": true}}`, <del> }, <del> } <del> <del> for _, invalid := range invalids { <del> if _, err := FromParam(invalid); err == nil { <del> t.Fatalf("Expected an error with %v, got nothing", invalid) <del> } <del> } <del> <del> for expectedArgs, matchers := range valid { <del> for _, json := range matchers { <del> args, err := FromParam(json) <del> if err != nil { <del> t.Fatal(err) <del> } <del> if args.Len() != expectedArgs.Len() { <del> t.Fatalf("Expected %v, go %v", expectedArgs, args) <del> } <del> for key, expectedValues := range expectedArgs.fields { <del> values := args.Get(key) <del> <del> if len(values) != len(expectedValues) { <del> t.Fatalf("Expected %v, go %v", expectedArgs, args) <del> } <del> <del> for _, v := range values { <del> if !expectedValues[v] { <del> t.Fatalf("Expected %v, go %v", expectedArgs, args) <del> } <del> } <del> } <del> } <del> } <del>} <del> <del>func TestEmpty(t *testing.T) { <del> a := Args{} <del> v, err := ToParam(a) <del> if err != nil { <del> t.Errorf("failed to marshal the filters: %s", err) <del> } <del> v1, err := FromParam(v) <del> if err != nil { <del> t.Errorf("%s", err) <del> } <del> if a.Len() != v1.Len() { <del> t.Errorf("these should both be empty sets") <del> } <del>} <del> <del>func TestArgsMatchKVListEmptySources(t *testing.T) { <del> args := NewArgs() <del> if !args.MatchKVList("created", map[string]string{}) { <del> t.Fatalf("Expected true for (%v,created), got true", args) <del> } <del> <del> args = Args{map[string]map[string]bool{"created": {"today": true}}} <del> if args.MatchKVList("created", map[string]string{}) { <del> t.Fatalf("Expected false for (%v,created), got true", args) <del> } <del>} <del> <del>func TestArgsMatchKVList(t *testing.T) { <del> // Not empty sources <del> sources := map[string]string{ <del> "key1": "value1", <del> "key2": "value2", <del> "key3": "value3", <del> } <del> <del> matches := map[*Args]string{ <del> &Args{}: "field", <del> &Args{map[string]map[string]bool{ <del> "created": map[string]bool{"today": true}, <del> "labels": map[string]bool{"key1": true}}, <del> }: "labels", <del> &Args{map[string]map[string]bool{ <del> "created": map[string]bool{"today": true}, <del> "labels": map[string]bool{"key1=value1": true}}, <del> }: "labels", <del> } <del> <del> for args, field := range matches { <del> if args.MatchKVList(field, sources) != true { <del> t.Fatalf("Expected true for %v on %v, got false", sources, args) <del> } <del> } <del> <del> differs := map[*Args]string{ <del> &Args{map[string]map[string]bool{ <del> "created": map[string]bool{"today": true}}, <del> }: "created", <del> &Args{map[string]map[string]bool{ <del> "created": map[string]bool{"today": true}, <del> "labels": map[string]bool{"key4": true}}, <del> }: "labels", <del> &Args{map[string]map[string]bool{ <del> "created": map[string]bool{"today": true}, <del> "labels": map[string]bool{"key1=value3": true}}, <del> }: "labels", <del> } <del> <del> for args, field := range differs { <del> if args.MatchKVList(field, sources) != false { <del> t.Fatalf("Expected false for %v on %v, got true", sources, args) <del> } <del> } <del>} <del> <del>func TestArgsMatch(t *testing.T) { <del> source := "today" <del> <del> matches := map[*Args]string{ <del> &Args{}: "field", <del> &Args{map[string]map[string]bool{ <del> "created": map[string]bool{"today": true}}, <del> }: "today", <del> &Args{map[string]map[string]bool{ <del> "created": map[string]bool{"to*": true}}, <del> }: "created", <del> &Args{map[string]map[string]bool{ <del> "created": map[string]bool{"to(.*)": true}}, <del> }: "created", <del> &Args{map[string]map[string]bool{ <del> "created": map[string]bool{"tod": true}}, <del> }: "created", <del> &Args{map[string]map[string]bool{ <del> "created": map[string]bool{"anyting": true, "to*": true}}, <del> }: "created", <del> } <del> <del> for args, field := range matches { <del> if args.Match(field, source) != true { <del> t.Fatalf("Expected true for %v on %v, got false", source, args) <del> } <del> } <del> <del> differs := map[*Args]string{ <del> &Args{map[string]map[string]bool{ <del> "created": map[string]bool{"tomorrow": true}}, <del> }: "created", <del> &Args{map[string]map[string]bool{ <del> "created": map[string]bool{"to(day": true}}, <del> }: "created", <del> &Args{map[string]map[string]bool{ <del> "created": map[string]bool{"tom(.*)": true}}, <del> }: "created", <del> &Args{map[string]map[string]bool{ <del> "created": map[string]bool{"tom": true}}, <del> }: "created", <del> &Args{map[string]map[string]bool{ <del> "created": map[string]bool{"today1": true}, <del> "labels": map[string]bool{"today": true}}, <del> }: "created", <del> } <del> <del> for args, field := range differs { <del> if args.Match(field, source) != false { <del> t.Fatalf("Expected false for %v on %v, got true", source, args) <del> } <del> } <del>} <del> <del>func TestAdd(t *testing.T) { <del> f := NewArgs() <del> f.Add("status", "running") <del> v := f.fields["status"] <del> if len(v) != 1 || !v["running"] { <del> t.Fatalf("Expected to include a running status, got %v", v) <del> } <del> <del> f.Add("status", "paused") <del> if len(v) != 2 || !v["paused"] { <del> t.Fatalf("Expected to include a paused status, got %v", v) <del> } <del>} <del> <del>func TestDel(t *testing.T) { <del> f := NewArgs() <del> f.Add("status", "running") <del> f.Del("status", "running") <del> v := f.fields["status"] <del> if v["running"] { <del> t.Fatalf("Expected to not include a running status filter, got true") <del> } <del>} <del> <del>func TestLen(t *testing.T) { <del> f := NewArgs() <del> if f.Len() != 0 { <del> t.Fatalf("Expected to not include any field") <del> } <del> f.Add("status", "running") <del> if f.Len() != 1 { <del> t.Fatalf("Expected to include one field") <del> } <del>} <del> <del>func TestExactMatch(t *testing.T) { <del> f := NewArgs() <del> <del> if !f.ExactMatch("status", "running") { <del> t.Fatalf("Expected to match `running` when there are no filters, got false") <del> } <del> <del> f.Add("status", "running") <del> f.Add("status", "pause*") <del> <del> if !f.ExactMatch("status", "running") { <del> t.Fatalf("Expected to match `running` with one of the filters, got false") <del> } <del> <del> if f.ExactMatch("status", "paused") { <del> t.Fatalf("Expected to not match `paused` with one of the filters, got true") <del> } <del>} <del> <del>func TestInclude(t *testing.T) { <del> f := NewArgs() <del> if f.Include("status") { <del> t.Fatalf("Expected to not include a status key, got true") <del> } <del> f.Add("status", "running") <del> if !f.Include("status") { <del> t.Fatalf("Expected to include a status key, got false") <del> } <del>} <del> <del>func TestValidate(t *testing.T) { <del> f := NewArgs() <del> f.Add("status", "running") <del> <del> valid := map[string]bool{ <del> "status": true, <del> "dangling": true, <del> } <del> <del> if err := f.Validate(valid); err != nil { <del> t.Fatal(err) <del> } <del> <del> f.Add("bogus", "running") <del> if err := f.Validate(valid); err == nil { <del> t.Fatalf("Expected to return an error, got nil") <del> } <del>} <del> <del>func TestWalkValues(t *testing.T) { <del> f := NewArgs() <del> f.Add("status", "running") <del> f.Add("status", "paused") <del> <del> f.WalkValues("status", func(value string) error { <del> if value != "running" && value != "paused" { <del> t.Fatalf("Unexpected value %s", value) <del> } <del> return nil <del> }) <del> <del> err := f.WalkValues("status", func(value string) error { <del> return fmt.Errorf("return") <del> }) <del> if err == nil { <del> t.Fatalf("Expected to get an error, got nil") <del> } <del> <del> err = f.WalkValues("foo", func(value string) error { <del> return fmt.Errorf("return") <del> }) <del> if err != nil { <del> t.Fatalf("Expected to not iterate when the field doesn't exist, got %v", err) <del> } <del>} <del> <del>func TestFuzzyMatch(t *testing.T) { <del> f := NewArgs() <del> f.Add("container", "foo") <del> <del> cases := map[string]bool{ <del> "foo": true, <del> "foobar": true, <del> "barfoo": false, <del> "bar": false, <del> } <del> for source, match := range cases { <del> got := f.FuzzyMatch("container", source) <del> if got != match { <del> t.Fatalf("Expected %v, got %v: %s", match, got, source) <del> } <del> } <del>} <ide><path>api/types/network/network.go <del>package network <del> <del>// Address represents an IP address <del>type Address struct { <del> Addr string <del> PrefixLen int <del>} <del> <del>// IPAM represents IP Address Management <del>type IPAM struct { <del> Driver string <del> Config []IPAMConfig <del>} <del> <del>// IPAMConfig represents IPAM configurations <del>type IPAMConfig struct { <del> Subnet string `json:",omitempty"` <del> IPRange string `json:",omitempty"` <del> Gateway string `json:",omitempty"` <del> AuxAddress map[string]string `json:"AuxiliaryAddresses,omitempty"` <del>} <del> <del>// EndpointSettings stores the network endpoint details <del>type EndpointSettings struct { <del> EndpointID string <del> Gateway string <del> IPAddress string <del> IPPrefixLen int <del> IPv6Gateway string <del> GlobalIPv6Address string <del> GlobalIPv6PrefixLen int <del> MacAddress string <del>} <ide><path>api/types/registry/registry.go <del>package registry <del> <del>import ( <del> "encoding/json" <del> "net" <del>) <del> <del>// ServiceConfig stores daemon registry services configuration. <del>type ServiceConfig struct { <del> InsecureRegistryCIDRs []*NetIPNet `json:"InsecureRegistryCIDRs"` <del> IndexConfigs map[string]*IndexInfo `json:"IndexConfigs"` <del> Mirrors []string <del>} <del> <del>// NetIPNet is the net.IPNet type, which can be marshalled and <del>// unmarshalled to JSON <del>type NetIPNet net.IPNet <del> <del>// MarshalJSON returns the JSON representation of the IPNet <del>func (ipnet *NetIPNet) MarshalJSON() ([]byte, error) { <del> return json.Marshal((*net.IPNet)(ipnet).String()) <del>} <del> <del>// UnmarshalJSON sets the IPNet from a byte array of JSON <del>func (ipnet *NetIPNet) UnmarshalJSON(b []byte) (err error) { <del> var ipnetStr string <del> if err = json.Unmarshal(b, &ipnetStr); err == nil { <del> var cidr *net.IPNet <del> if _, cidr, err = net.ParseCIDR(ipnetStr); err == nil { <del> *ipnet = NetIPNet(*cidr) <del> } <del> } <del> return <del>} <del> <del>// IndexInfo contains information about a registry <del>// <del>// RepositoryInfo Examples: <del>// { <del>// "Index" : { <del>// "Name" : "docker.io", <del>// "Mirrors" : ["https://registry-2.docker.io/v1/", "https://registry-3.docker.io/v1/"], <del>// "Secure" : true, <del>// "Official" : true, <del>// }, <del>// "RemoteName" : "library/debian", <del>// "LocalName" : "debian", <del>// "CanonicalName" : "docker.io/debian" <del>// "Official" : true, <del>// } <del>// <del>// { <del>// "Index" : { <del>// "Name" : "127.0.0.1:5000", <del>// "Mirrors" : [], <del>// "Secure" : false, <del>// "Official" : false, <del>// }, <del>// "RemoteName" : "user/repo", <del>// "LocalName" : "127.0.0.1:5000/user/repo", <del>// "CanonicalName" : "127.0.0.1:5000/user/repo", <del>// "Official" : false, <del>// } <del>type IndexInfo struct { <del> // Name is the name of the registry, such as "docker.io" <del> Name string <del> // Mirrors is a list of mirrors, expressed as URIs <del> Mirrors []string <del> // Secure is set to false if the registry is part of the list of <del> // insecure registries. Insecure registries accept HTTP and/or accept <del> // HTTPS with certificates from unknown CAs. <del> Secure bool <del> // Official indicates whether this is an official registry <del> Official bool <del>} <del> <del>// SearchResult describes a search result returned from a registry <del>type SearchResult struct { <del> // StarCount indicates the number of stars this repository has <del> StarCount int `json:"star_count"` <del> // IsOfficial indicates whether the result is an official repository or not <del> IsOfficial bool `json:"is_official"` <del> // Name is the name of the repository <del> Name string `json:"name"` <del> // IsOfficial indicates whether the result is trusted <del> IsTrusted bool `json:"is_trusted"` <del> // IsAutomated indicates whether the result is automated <del> IsAutomated bool `json:"is_automated"` <del> // Description is a textual description of the repository <del> Description string `json:"description"` <del>} <del> <del>// SearchResults lists a collection search results returned from a registry <del>type SearchResults struct { <del> // Query contains the query string that generated the search results <del> Query string `json:"query"` <del> // NumResults indicates the number of results the query returned <del> NumResults int `json:"num_results"` <del> // Results is a slice containing the actual results for the search <del> Results []SearchResult `json:"results"` <del>} <ide><path>api/types/stats.go <del>// Package types is used for API stability in the types and response to the <del>// consumers of the API stats endpoint. <del>package types <del> <del>import "time" <del> <del>// ThrottlingData stores CPU throttling stats of one running container <del>type ThrottlingData struct { <del> // Number of periods with throttling active <del> Periods uint64 `json:"periods"` <del> // Number of periods when the container hit its throttling limit. <del> ThrottledPeriods uint64 `json:"throttled_periods"` <del> // Aggregate time the container was throttled for in nanoseconds. <del> ThrottledTime uint64 `json:"throttled_time"` <del>} <del> <del>// CPUUsage stores All CPU stats aggregated since container inception. <del>type CPUUsage struct { <del> // Total CPU time consumed. <del> // Units: nanoseconds. <del> TotalUsage uint64 `json:"total_usage"` <del> // Total CPU time consumed per core. <del> // Units: nanoseconds. <del> PercpuUsage []uint64 `json:"percpu_usage"` <del> // Time spent by tasks of the cgroup in kernel mode. <del> // Units: nanoseconds. <del> UsageInKernelmode uint64 `json:"usage_in_kernelmode"` <del> // Time spent by tasks of the cgroup in user mode. <del> // Units: nanoseconds. <del> UsageInUsermode uint64 `json:"usage_in_usermode"` <del>} <del> <del>// CPUStats aggregates and wraps all CPU related info of container <del>type CPUStats struct { <del> CPUUsage CPUUsage `json:"cpu_usage"` <del> SystemUsage uint64 `json:"system_cpu_usage"` <del> ThrottlingData ThrottlingData `json:"throttling_data,omitempty"` <del>} <del> <del>// MemoryStats aggregates All memory stats since container inception <del>type MemoryStats struct { <del> // current res_counter usage for memory <del> Usage uint64 `json:"usage"` <del> // maximum usage ever recorded. <del> MaxUsage uint64 `json:"max_usage"` <del> // TODO(vishh): Export these as stronger types. <del> // all the stats exported via memory.stat. <del> Stats map[string]uint64 `json:"stats"` <del> // number of times memory usage hits limits. <del> Failcnt uint64 `json:"failcnt"` <del> Limit uint64 `json:"limit"` <del>} <del> <del>// BlkioStatEntry is one small entity to store a piece of Blkio stats <del>// TODO Windows: This can be factored out <del>type BlkioStatEntry struct { <del> Major uint64 `json:"major"` <del> Minor uint64 `json:"minor"` <del> Op string `json:"op"` <del> Value uint64 `json:"value"` <del>} <del> <del>// BlkioStats stores All IO service stats for data read and write <del>// TODO Windows: This can be factored out <del>type BlkioStats struct { <del> // number of bytes transferred to and from the block device <del> IoServiceBytesRecursive []BlkioStatEntry `json:"io_service_bytes_recursive"` <del> IoServicedRecursive []BlkioStatEntry `json:"io_serviced_recursive"` <del> IoQueuedRecursive []BlkioStatEntry `json:"io_queue_recursive"` <del> IoServiceTimeRecursive []BlkioStatEntry `json:"io_service_time_recursive"` <del> IoWaitTimeRecursive []BlkioStatEntry `json:"io_wait_time_recursive"` <del> IoMergedRecursive []BlkioStatEntry `json:"io_merged_recursive"` <del> IoTimeRecursive []BlkioStatEntry `json:"io_time_recursive"` <del> SectorsRecursive []BlkioStatEntry `json:"sectors_recursive"` <del>} <del> <del>// NetworkStats aggregates All network stats of one container <del>// TODO Windows: This will require refactoring <del>type NetworkStats struct { <del> RxBytes uint64 `json:"rx_bytes"` <del> RxPackets uint64 `json:"rx_packets"` <del> RxErrors uint64 `json:"rx_errors"` <del> RxDropped uint64 `json:"rx_dropped"` <del> TxBytes uint64 `json:"tx_bytes"` <del> TxPackets uint64 `json:"tx_packets"` <del> TxErrors uint64 `json:"tx_errors"` <del> TxDropped uint64 `json:"tx_dropped"` <del>} <del> <del>// Stats is Ultimate struct aggregating all types of stats of one container <del>type Stats struct { <del> Read time.Time `json:"read"` <del> PreCPUStats CPUStats `json:"precpu_stats,omitempty"` <del> CPUStats CPUStats `json:"cpu_stats,omitempty"` <del> MemoryStats MemoryStats `json:"memory_stats,omitempty"` <del> BlkioStats BlkioStats `json:"blkio_stats,omitempty"` <del>} <del> <del>// StatsJSON is newly used Networks <del>type StatsJSON struct { <del> Stats <del> <del> // Networks request version >=1.21 <del> Networks map[string]NetworkStats `json:"networks,omitempty"` <del>} <ide><path>api/types/strslice/strslice.go <del>package strslice <del> <del>import ( <del> "encoding/json" <del> "strings" <del>) <del> <del>// StrSlice represents a string or an array of strings. <del>// We need to override the json decoder to accept both options. <del>type StrSlice struct { <del> parts []string <del>} <del> <del>// MarshalJSON Marshals (or serializes) the StrSlice into the json format. <del>// This method is needed to implement json.Marshaller. <del>func (e *StrSlice) MarshalJSON() ([]byte, error) { <del> if e == nil { <del> return []byte{}, nil <del> } <del> return json.Marshal(e.Slice()) <del>} <del> <del>// UnmarshalJSON decodes the byte slice whether it's a string or an array of strings. <del>// This method is needed to implement json.Unmarshaler. <del>func (e *StrSlice) UnmarshalJSON(b []byte) error { <del> if len(b) == 0 { <del> return nil <del> } <del> <del> p := make([]string, 0, 1) <del> if err := json.Unmarshal(b, &p); err != nil { <del> var s string <del> if err := json.Unmarshal(b, &s); err != nil { <del> return err <del> } <del> p = append(p, s) <del> } <del> <del> e.parts = p <del> return nil <del>} <del> <del>// Len returns the number of parts of the StrSlice. <del>func (e *StrSlice) Len() int { <del> if e == nil { <del> return 0 <del> } <del> return len(e.parts) <del>} <del> <del>// Slice gets the parts of the StrSlice as a Slice of string. <del>func (e *StrSlice) Slice() []string { <del> if e == nil { <del> return nil <del> } <del> return e.parts <del>} <del> <del>// ToString gets space separated string of all the parts. <del>func (e *StrSlice) ToString() string { <del> s := e.Slice() <del> if s == nil { <del> return "" <del> } <del> return strings.Join(s, " ") <del>} <del> <del>// New creates an StrSlice based on the specified parts (as strings). <del>func New(parts ...string) *StrSlice { <del> return &StrSlice{parts} <del>} <ide><path>api/types/strslice/strslice_test.go <del>package strslice <del> <del>import ( <del> "encoding/json" <del> "reflect" <del> "testing" <del>) <del> <del>func TestStrSliceMarshalJSON(t *testing.T) { <del> strss := map[*StrSlice]string{ <del> nil: "", <del> &StrSlice{}: "null", <del> &StrSlice{[]string{"/bin/sh", "-c", "echo"}}: `["/bin/sh","-c","echo"]`, <del> } <del> <del> for strs, expected := range strss { <del> data, err := strs.MarshalJSON() <del> if err != nil { <del> t.Fatal(err) <del> } <del> if string(data) != expected { <del> t.Fatalf("Expected %v, got %v", expected, string(data)) <del> } <del> } <del>} <del> <del>func TestStrSliceUnmarshalJSON(t *testing.T) { <del> parts := map[string][]string{ <del> "": {"default", "values"}, <del> "[]": {}, <del> `["/bin/sh","-c","echo"]`: {"/bin/sh", "-c", "echo"}, <del> } <del> for json, expectedParts := range parts { <del> strs := &StrSlice{ <del> []string{"default", "values"}, <del> } <del> if err := strs.UnmarshalJSON([]byte(json)); err != nil { <del> t.Fatal(err) <del> } <del> <del> actualParts := strs.Slice() <del> if len(actualParts) != len(expectedParts) { <del> t.Fatalf("Expected %v parts, got %v (%v)", len(expectedParts), len(actualParts), expectedParts) <del> } <del> for index, part := range actualParts { <del> if part != expectedParts[index] { <del> t.Fatalf("Expected %v, got %v", expectedParts, actualParts) <del> break <del> } <del> } <del> } <del>} <del> <del>func TestStrSliceUnmarshalString(t *testing.T) { <del> var e *StrSlice <del> echo, err := json.Marshal("echo") <del> if err != nil { <del> t.Fatal(err) <del> } <del> if err := json.Unmarshal(echo, &e); err != nil { <del> t.Fatal(err) <del> } <del> <del> slice := e.Slice() <del> if len(slice) != 1 { <del> t.Fatalf("expected 1 element after unmarshal: %q", slice) <del> } <del> <del> if slice[0] != "echo" { <del> t.Fatalf("expected `echo`, got: %q", slice[0]) <del> } <del>} <del> <del>func TestStrSliceUnmarshalSlice(t *testing.T) { <del> var e *StrSlice <del> echo, err := json.Marshal([]string{"echo"}) <del> if err != nil { <del> t.Fatal(err) <del> } <del> if err := json.Unmarshal(echo, &e); err != nil { <del> t.Fatal(err) <del> } <del> <del> slice := e.Slice() <del> if len(slice) != 1 { <del> t.Fatalf("expected 1 element after unmarshal: %q", slice) <del> } <del> <del> if slice[0] != "echo" { <del> t.Fatalf("expected `echo`, got: %q", slice[0]) <del> } <del>} <del> <del>func TestStrSliceToString(t *testing.T) { <del> slices := map[*StrSlice]string{ <del> New(""): "", <del> New("one"): "one", <del> New("one", "two"): "one two", <del> } <del> for s, expected := range slices { <del> toString := s.ToString() <del> if toString != expected { <del> t.Fatalf("Expected %v, got %v", expected, toString) <del> } <del> } <del>} <del> <del>func TestStrSliceLen(t *testing.T) { <del> var emptyStrSlice *StrSlice <del> slices := map[*StrSlice]int{ <del> New(""): 1, <del> New("one"): 1, <del> New("one", "two"): 2, <del> emptyStrSlice: 0, <del> } <del> for s, expected := range slices { <del> if s.Len() != expected { <del> t.Fatalf("Expected %d, got %d", s.Len(), expected) <del> } <del> } <del>} <del> <del>func TestStrSliceSlice(t *testing.T) { <del> var emptyStrSlice *StrSlice <del> slices := map[*StrSlice][]string{ <del> New("one"): {"one"}, <del> New("one", "two"): {"one", "two"}, <del> emptyStrSlice: nil, <del> } <del> for s, expected := range slices { <del> if !reflect.DeepEqual(s.Slice(), expected) { <del> t.Fatalf("Expected %v, got %v", s.Slice(), expected) <del> } <del> } <del>} <ide><path>api/types/time/timestamp.go <del>package time <del> <del>import ( <del> "fmt" <del> "math" <del> "strconv" <del> "strings" <del> "time" <del>) <del> <del>// These are additional predefined layouts for use in Time.Format and Time.Parse <del>// with --since and --until parameters for `docker logs` and `docker events` <del>const ( <del> rFC3339Local = "2006-01-02T15:04:05" // RFC3339 with local timezone <del> rFC3339NanoLocal = "2006-01-02T15:04:05.999999999" // RFC3339Nano with local timezone <del> dateWithZone = "2006-01-02Z07:00" // RFC3339 with time at 00:00:00 <del> dateLocal = "2006-01-02" // RFC3339 with local timezone and time at 00:00:00 <del>) <del> <del>// GetTimestamp tries to parse given string as golang duration, <del>// then RFC3339 time and finally as a Unix timestamp. If <del>// any of these were successful, it returns a Unix timestamp <del>// as string otherwise returns the given value back. <del>// In case of duration input, the returned timestamp is computed <del>// as the given reference time minus the amount of the duration. <del>func GetTimestamp(value string, reference time.Time) (string, error) { <del> if d, err := time.ParseDuration(value); value != "0" && err == nil { <del> return strconv.FormatInt(reference.Add(-d).Unix(), 10), nil <del> } <del> <del> var format string <del> var parseInLocation bool <del> <del> // if the string has a Z or a + or three dashes use parse otherwise use parseinlocation <del> parseInLocation = !(strings.ContainsAny(value, "zZ+") || strings.Count(value, "-") == 3) <del> <del> if strings.Contains(value, ".") { <del> if parseInLocation { <del> format = rFC3339NanoLocal <del> } else { <del> format = time.RFC3339Nano <del> } <del> } else if strings.Contains(value, "T") { <del> // we want the number of colons in the T portion of the timestamp <del> tcolons := strings.Count(value, ":") <del> // if parseInLocation is off and we have a +/- zone offset (not Z) then <del> // there will be an extra colon in the input for the tz offset subtract that <del> // colon from the tcolons count <del> if !parseInLocation && !strings.ContainsAny(value, "zZ") && tcolons > 0 { <del> tcolons-- <del> } <del> if parseInLocation { <del> switch tcolons { <del> case 0: <del> format = "2006-01-02T15" <del> case 1: <del> format = "2006-01-02T15:04" <del> default: <del> format = rFC3339Local <del> } <del> } else { <del> switch tcolons { <del> case 0: <del> format = "2006-01-02T15Z07:00" <del> case 1: <del> format = "2006-01-02T15:04Z07:00" <del> default: <del> format = time.RFC3339 <del> } <del> } <del> } else if parseInLocation { <del> format = dateLocal <del> } else { <del> format = dateWithZone <del> } <del> <del> var t time.Time <del> var err error <del> <del> if parseInLocation { <del> t, err = time.ParseInLocation(format, value, time.FixedZone(time.Now().Zone())) <del> } else { <del> t, err = time.Parse(format, value) <del> } <del> <del> if err != nil { <del> // if there is a `-` then its an RFC3339 like timestamp otherwise assume unixtimestamp <del> if strings.Contains(value, "-") { <del> return "", err // was probably an RFC3339 like timestamp but the parser failed with an error <del> } <del> return value, nil // unixtimestamp in and out case (meaning: the value passed at the command line is already in the right format for passing to the server) <del> } <del> <del> return fmt.Sprintf("%d.%09d", t.Unix(), int64(t.Nanosecond())), nil <del>} <del> <del>// ParseTimestamps returns seconds and nanoseconds from a timestamp that has the <del>// format "%d.%09d", time.Unix(), int64(time.Nanosecond())) <del>// if the incoming nanosecond portion is longer or shorter than 9 digits it is <del>// converted to nanoseconds. The expectation is that the seconds and <del>// seconds will be used to create a time variable. For example: <del>// seconds, nanoseconds, err := ParseTimestamp("1136073600.000000001",0) <del>// if err == nil since := time.Unix(seconds, nanoseconds) <del>// returns seconds as def(aultSeconds) if value == "" <del>func ParseTimestamps(value string, def int64) (int64, int64, error) { <del> if value == "" { <del> return def, 0, nil <del> } <del> sa := strings.SplitN(value, ".", 2) <del> s, err := strconv.ParseInt(sa[0], 10, 64) <del> if err != nil { <del> return s, 0, err <del> } <del> if len(sa) != 2 { <del> return s, 0, nil <del> } <del> n, err := strconv.ParseInt(sa[1], 10, 64) <del> if err != nil { <del> return s, n, err <del> } <del> // should already be in nanoseconds but just in case convert n to nanoseonds <del> n = int64(float64(n) * math.Pow(float64(10), float64(9-len(sa[1])))) <del> return s, n, nil <del>} <ide><path>api/types/time/timestamp_test.go <del>package time <del> <del>import ( <del> "fmt" <del> "testing" <del> "time" <del>) <del> <del>func TestGetTimestamp(t *testing.T) { <del> now := time.Now() <del> cases := []struct { <del> in, expected string <del> expectedErr bool <del> }{ <del> // Partial RFC3339 strings get parsed with second precision <del> {"2006-01-02T15:04:05.999999999+07:00", "1136189045.999999999", false}, <del> {"2006-01-02T15:04:05.999999999Z", "1136214245.999999999", false}, <del> {"2006-01-02T15:04:05.999999999", "1136214245.999999999", false}, <del> {"2006-01-02T15:04:05Z", "1136214245.000000000", false}, <del> {"2006-01-02T15:04:05", "1136214245.000000000", false}, <del> {"2006-01-02T15:04:0Z", "", true}, <del> {"2006-01-02T15:04:0", "", true}, <del> {"2006-01-02T15:04Z", "1136214240.000000000", false}, <del> {"2006-01-02T15:04+00:00", "1136214240.000000000", false}, <del> {"2006-01-02T15:04-00:00", "1136214240.000000000", false}, <del> {"2006-01-02T15:04", "1136214240.000000000", false}, <del> {"2006-01-02T15:0Z", "", true}, <del> {"2006-01-02T15:0", "", true}, <del> {"2006-01-02T15Z", "1136214000.000000000", false}, <del> {"2006-01-02T15+00:00", "1136214000.000000000", false}, <del> {"2006-01-02T15-00:00", "1136214000.000000000", false}, <del> {"2006-01-02T15", "1136214000.000000000", false}, <del> {"2006-01-02T1Z", "1136163600.000000000", false}, <del> {"2006-01-02T1", "1136163600.000000000", false}, <del> {"2006-01-02TZ", "", true}, <del> {"2006-01-02T", "", true}, <del> {"2006-01-02+00:00", "1136160000.000000000", false}, <del> {"2006-01-02-00:00", "1136160000.000000000", false}, <del> {"2006-01-02-00:01", "1136160060.000000000", false}, <del> {"2006-01-02Z", "1136160000.000000000", false}, <del> {"2006-01-02", "1136160000.000000000", false}, <del> {"2015-05-13T20:39:09Z", "1431549549.000000000", false}, <del> <del> // unix timestamps returned as is <del> {"1136073600", "1136073600", false}, <del> {"1136073600.000000001", "1136073600.000000001", false}, <del> // Durations <del> {"1m", fmt.Sprintf("%d", now.Add(-1*time.Minute).Unix()), false}, <del> {"1.5h", fmt.Sprintf("%d", now.Add(-90*time.Minute).Unix()), false}, <del> {"1h30m", fmt.Sprintf("%d", now.Add(-90*time.Minute).Unix()), false}, <del> <del> // String fallback <del> {"invalid", "invalid", false}, <del> } <del> <del> for _, c := range cases { <del> o, err := GetTimestamp(c.in, now) <del> if o != c.expected || <del> (err == nil && c.expectedErr) || <del> (err != nil && !c.expectedErr) { <del> t.Errorf("wrong value for '%s'. expected:'%s' got:'%s' with error: `%s`", c.in, c.expected, o, err) <del> t.Fail() <del> } <del> } <del>} <del> <del>func TestParseTimestamps(t *testing.T) { <del> cases := []struct { <del> in string <del> def, expectedS, expectedN int64 <del> expectedErr bool <del> }{ <del> // unix timestamps <del> {"1136073600", 0, 1136073600, 0, false}, <del> {"1136073600.000000001", 0, 1136073600, 1, false}, <del> {"1136073600.0000000010", 0, 1136073600, 1, false}, <del> {"1136073600.00000001", 0, 1136073600, 10, false}, <del> {"foo.bar", 0, 0, 0, true}, <del> {"1136073600.bar", 0, 1136073600, 0, true}, <del> {"", -1, -1, 0, false}, <del> } <del> <del> for _, c := range cases { <del> s, n, err := ParseTimestamps(c.in, c.def) <del> if s != c.expectedS || <del> n != c.expectedN || <del> (err == nil && c.expectedErr) || <del> (err != nil && !c.expectedErr) { <del> t.Errorf("wrong values for input `%s` with default `%d` expected:'%d'seconds and `%d`nanosecond got:'%d'seconds and `%d`nanoseconds with error: `%s`", c.in, c.def, c.expectedS, c.expectedN, s, n, err) <del> t.Fail() <del> } <del> } <del>} <ide><path>api/types/types.go <del>package types <del> <del>import ( <del> "os" <del> "time" <del> <del> "github.com/docker/engine-api/types/container" <del> "github.com/docker/engine-api/types/network" <del> "github.com/docker/engine-api/types/registry" <del> "github.com/docker/go-connections/nat" <del>) <del> <del>// ContainerCreateResponse contains the information returned to a client on the <del>// creation of a new container. <del>type ContainerCreateResponse struct { <del> // ID is the ID of the created container. <del> ID string `json:"Id"` <del> <del> // Warnings are any warnings encountered during the creation of the container. <del> Warnings []string `json:"Warnings"` <del>} <del> <del>// ContainerExecCreateResponse contains response of Remote API: <del>// POST "/containers/{name:.*}/exec" <del>type ContainerExecCreateResponse struct { <del> // ID is the exec ID. <del> ID string `json:"Id"` <del>} <del> <del>// ContainerUpdateResponse contains response of Remote API: <del>// POST /containers/{name:.*}/update <del>type ContainerUpdateResponse struct { <del> // Warnings are any warnings encountered during the updating of the container. <del> Warnings []string `json:"Warnings"` <del>} <del> <del>// AuthResponse contains response of Remote API: <del>// POST "/auth" <del>type AuthResponse struct { <del> // Status is the authentication status <del> Status string `json:"Status"` <del>} <del> <del>// ContainerWaitResponse contains response of Remote API: <del>// POST "/containers/"+containerID+"/wait" <del>type ContainerWaitResponse struct { <del> // StatusCode is the status code of the wait job <del> StatusCode int `json:"StatusCode"` <del>} <del> <del>// ContainerCommitResponse contains response of Remote API: <del>// POST "/commit?container="+containerID <del>type ContainerCommitResponse struct { <del> ID string `json:"Id"` <del>} <del> <del>// ContainerChange contains response of Remote API: <del>// GET "/containers/{name:.*}/changes" <del>type ContainerChange struct { <del> Kind int <del> Path string <del>} <del> <del>// ImageHistory contains response of Remote API: <del>// GET "/images/{name:.*}/history" <del>type ImageHistory struct { <del> ID string `json:"Id"` <del> Created int64 <del> CreatedBy string <del> Tags []string <del> Size int64 <del> Comment string <del>} <del> <del>// ImageDelete contains response of Remote API: <del>// DELETE "/images/{name:.*}" <del>type ImageDelete struct { <del> Untagged string `json:",omitempty"` <del> Deleted string `json:",omitempty"` <del>} <del> <del>// Image contains response of Remote API: <del>// GET "/images/json" <del>type Image struct { <del> ID string `json:"Id"` <del> ParentID string `json:"ParentId"` <del> RepoTags []string <del> RepoDigests []string <del> Created int64 <del> Size int64 <del> VirtualSize int64 <del> Labels map[string]string <del>} <del> <del>// GraphDriverData returns Image's graph driver config info <del>// when calling inspect command <del>type GraphDriverData struct { <del> Name string <del> Data map[string]string <del>} <del> <del>// ImageInspect contains response of Remote API: <del>// GET "/images/{name:.*}/json" <del>type ImageInspect struct { <del> ID string `json:"Id"` <del> RepoTags []string <del> RepoDigests []string <del> Parent string <del> Comment string <del> Created string <del> Container string <del> ContainerConfig *container.Config <del> DockerVersion string <del> Author string <del> Config *container.Config <del> Architecture string <del> Os string <del> Size int64 <del> VirtualSize int64 <del> GraphDriver GraphDriverData <del>} <del> <del>// Port stores open ports info of container <del>// e.g. {"PrivatePort": 8080, "PublicPort": 80, "Type": "tcp"} <del>type Port struct { <del> IP string `json:",omitempty"` <del> PrivatePort int <del> PublicPort int `json:",omitempty"` <del> Type string <del>} <del> <del>// Container contains response of Remote API: <del>// GET "/containers/json" <del>type Container struct { <del> ID string `json:"Id"` <del> Names []string <del> Image string <del> ImageID string <del> Command string <del> Created int64 <del> Ports []Port <del> SizeRw int64 `json:",omitempty"` <del> SizeRootFs int64 `json:",omitempty"` <del> Labels map[string]string <del> Status string <del> HostConfig struct { <del> NetworkMode string `json:",omitempty"` <del> } <del> NetworkSettings *SummaryNetworkSettings <del>} <del> <del>// CopyConfig contains request body of Remote API: <del>// POST "/containers/"+containerID+"/copy" <del>type CopyConfig struct { <del> Resource string <del>} <del> <del>// ContainerPathStat is used to encode the header from <del>// GET "/containers/{name:.*}/archive" <del>// "Name" is the file or directory name. <del>type ContainerPathStat struct { <del> Name string `json:"name"` <del> Size int64 `json:"size"` <del> Mode os.FileMode `json:"mode"` <del> Mtime time.Time `json:"mtime"` <del> LinkTarget string `json:"linkTarget"` <del>} <del> <del>// ContainerProcessList contains response of Remote API: <del>// GET "/containers/{name:.*}/top" <del>type ContainerProcessList struct { <del> Processes [][]string <del> Titles []string <del>} <del> <del>// Version contains response of Remote API: <del>// GET "/version" <del>type Version struct { <del> Version string <del> APIVersion string `json:"ApiVersion"` <del> GitCommit string <del> GoVersion string <del> Os string <del> Arch string <del> KernelVersion string `json:",omitempty"` <del> Experimental bool `json:",omitempty"` <del> BuildTime string `json:",omitempty"` <del>} <del> <del>// Info contains response of Remote API: <del>// GET "/info" <del>type Info struct { <del> ID string <del> Containers int <del> Images int <del> Driver string <del> DriverStatus [][2]string <del> Plugins PluginsInfo <del> MemoryLimit bool <del> SwapLimit bool <del> CPUCfsPeriod bool `json:"CpuCfsPeriod"` <del> CPUCfsQuota bool `json:"CpuCfsQuota"` <del> CPUShares bool <del> CPUSet bool <del> IPv4Forwarding bool <del> BridgeNfIptables bool <del> BridgeNfIP6tables bool `json:"BridgeNfIp6tables"` <del> Debug bool <del> NFd int <del> OomKillDisable bool <del> NGoroutines int <del> SystemTime string <del> ExecutionDriver string <del> LoggingDriver string <del> NEventsListener int <del> KernelVersion string <del> OperatingSystem string <del> OSType string <del> Architecture string <del> IndexServerAddress string <del> RegistryConfig *registry.ServiceConfig <del> InitSha1 string <del> InitPath string <del> NCPU int <del> MemTotal int64 <del> DockerRootDir string <del> HTTPProxy string `json:"HttpProxy"` <del> HTTPSProxy string `json:"HttpsProxy"` <del> NoProxy string <del> Name string <del> Labels []string <del> ExperimentalBuild bool <del> ServerVersion string <del> ClusterStore string <del> ClusterAdvertise string <del>} <del> <del>// PluginsInfo is temp struct holds Plugins name <del>// registered with docker daemon. It used by Info struct <del>type PluginsInfo struct { <del> // List of Volume plugins registered <del> Volume []string <del> // List of Network plugins registered <del> Network []string <del> // List of Authorization plugins registered <del> Authorization []string <del>} <del> <del>// ExecStartCheck is a temp struct used by execStart <del>// Config fields is part of ExecConfig in runconfig package <del>type ExecStartCheck struct { <del> // ExecStart will first check if it's detached <del> Detach bool <del> // Check if there's a tty <del> Tty bool <del>} <del> <del>// ContainerState stores container's running state <del>// it's part of ContainerJSONBase and will return by "inspect" command <del>type ContainerState struct { <del> Status string <del> Running bool <del> Paused bool <del> Restarting bool <del> OOMKilled bool <del> Dead bool <del> Pid int <del> ExitCode int <del> Error string <del> StartedAt string <del> FinishedAt string <del>} <del> <del>// ContainerJSONBase contains response of Remote API: <del>// GET "/containers/{name:.*}/json" <del>type ContainerJSONBase struct { <del> ID string `json:"Id"` <del> Created string <del> Path string <del> Args []string <del> State *ContainerState <del> Image string <del> ResolvConfPath string <del> HostnamePath string <del> HostsPath string <del> LogPath string <del> Name string <del> RestartCount int <del> Driver string <del> MountLabel string <del> ProcessLabel string <del> AppArmorProfile string <del> ExecIDs []string <del> HostConfig *container.HostConfig <del> GraphDriver GraphDriverData <del> SizeRw *int64 `json:",omitempty"` <del> SizeRootFs *int64 `json:",omitempty"` <del>} <del> <del>// ContainerJSON is newly used struct along with MountPoint <del>type ContainerJSON struct { <del> *ContainerJSONBase <del> Mounts []MountPoint <del> Config *container.Config <del> NetworkSettings *NetworkSettings <del>} <del> <del>// NetworkSettings exposes the network settings in the api <del>type NetworkSettings struct { <del> NetworkSettingsBase <del> DefaultNetworkSettings <del> Networks map[string]*network.EndpointSettings <del>} <del> <del>// SummaryNetworkSettings provides a summary of container's networks <del>// in /containers/json <del>type SummaryNetworkSettings struct { <del> Networks map[string]*network.EndpointSettings <del>} <del> <del>// NetworkSettingsBase holds basic information about networks <del>type NetworkSettingsBase struct { <del> Bridge string <del> SandboxID string <del> HairpinMode bool <del> LinkLocalIPv6Address string <del> LinkLocalIPv6PrefixLen int <del> Ports nat.PortMap <del> SandboxKey string <del> SecondaryIPAddresses []network.Address <del> SecondaryIPv6Addresses []network.Address <del>} <del> <del>// DefaultNetworkSettings holds network information <del>// during the 2 release deprecation period. <del>// It will be removed in Docker 1.11. <del>type DefaultNetworkSettings struct { <del> EndpointID string <del> Gateway string <del> GlobalIPv6Address string <del> GlobalIPv6PrefixLen int <del> IPAddress string <del> IPPrefixLen int <del> IPv6Gateway string <del> MacAddress string <del>} <del> <del>// MountPoint represents a mount point configuration inside the container. <del>type MountPoint struct { <del> Name string `json:",omitempty"` <del> Source string <del> Destination string <del> Driver string `json:",omitempty"` <del> Mode string <del> RW bool <del> Propagation string <del>} <del> <del>// Volume represents the configuration of a volume for the remote API <del>type Volume struct { <del> Name string // Name is the name of the volume <del> Driver string // Driver is the Driver name used to create the volume <del> Mountpoint string // Mountpoint is the location on disk of the volume <del>} <del> <del>// VolumesListResponse contains the response for the remote API: <del>// GET "/volumes" <del>type VolumesListResponse struct { <del> Volumes []*Volume // Volumes is the list of volumes being returned <del> Warnings []string // Warnings is a list of warnings that occurred when getting the list from the volume drivers <del>} <del> <del>// VolumeCreateRequest contains the response for the remote API: <del>// POST "/volumes/create" <del>type VolumeCreateRequest struct { <del> Name string // Name is the requested name of the volume <del> Driver string // Driver is the name of the driver that should be used to create the volume <del> DriverOpts map[string]string // DriverOpts holds the driver specific options to use for when creating the volume. <del>} <del> <del>// NetworkResource is the body of the "get network" http response message <del>type NetworkResource struct { <del> Name string <del> ID string `json:"Id"` <del> Scope string <del> Driver string <del> IPAM network.IPAM <del> Containers map[string]EndpointResource <del> Options map[string]string <del>} <del> <del>// EndpointResource contains network resources allocated and used for a container in a network <del>type EndpointResource struct { <del> Name string <del> EndpointID string <del> MacAddress string <del> IPv4Address string <del> IPv6Address string <del>} <del> <del>// NetworkCreate is the expected body of the "create network" http request message <del>type NetworkCreate struct { <del> Name string <del> CheckDuplicate bool <del> Driver string <del> IPAM network.IPAM <del> Options map[string]string <del>} <del> <del>// NetworkCreateResponse is the response message sent by the server for network create call <del>type NetworkCreateResponse struct { <del> ID string `json:"Id"` <del> Warning string <del>} <del> <del>// NetworkConnect represents the data to be used to connect a container to the network <del>type NetworkConnect struct { <del> Container string <del>} <del> <del>// NetworkDisconnect represents the data to be used to disconnect a container from the network <del>type NetworkDisconnect struct { <del> Container string <del>} <ide><path>api/types/versions/README.md <del>## Legacy API type versions <del> <del>This package includes types for legacy API versions. The stable version of the API types live in `api/types/*.go`. <del> <del>Consider moving a type here when you need to keep backwards compatibility in the API. This legacy types are organized by the latest API version they appear in. For instance, types in the `v1p19` package are valid for API versions below or equal `1.19`. Types in the `v1p20` package are valid for the API version `1.20`, since the versions below that will use the legacy types in `v1p19`. <del> <del>### Package name conventions <del> <del>The package name convention is to use `v` as a prefix for the version number and `p`(patch) as a separator. We use this nomenclature due to a few restrictions in the Go package name convention: <del> <del>1. We cannot use `.` because it's interpreted by the language, think of `v1.20.CallFunction`. <del>2. We cannot use `_` because golint complains abount it. The code is actually valid, but it looks probably more weird: `v1_20.CallFunction`. <del> <del>For instance, if you want to modify a type that was available in the version `1.21` of the API but it will have different fields in the version `1.22`, you want to create a new package under `api/types/versions/v1p21`. <ide><path>api/types/versions/v1p19/types.go <del>// Package v1p19 provides specific API types for the API version 1, patch 19. <del>package v1p19 <del> <del>import ( <del> "github.com/docker/engine-api/types" <del> "github.com/docker/engine-api/types/container" <del> "github.com/docker/engine-api/types/versions/v1p20" <del> "github.com/docker/go-connections/nat" <del>) <del> <del>// ContainerJSON is a backcompatibility struct for APIs prior to 1.20. <del>// Note this is not used by the Windows daemon. <del>type ContainerJSON struct { <del> *types.ContainerJSONBase <del> Volumes map[string]string <del> VolumesRW map[string]bool <del> Config *ContainerConfig <del> NetworkSettings *v1p20.NetworkSettings <del>} <del> <del>// ContainerConfig is a backcompatibility struct for APIs prior to 1.20. <del>type ContainerConfig struct { <del> *container.Config <del> <del> MacAddress string <del> NetworkDisabled bool <del> ExposedPorts map[nat.Port]struct{} <del> <del> // backward compatibility, they now live in HostConfig <del> VolumeDriver string <del> Memory int64 <del> MemorySwap int64 <del> CPUShares int64 `json:"CpuShares"` <del> CPUSet string `json:"Cpuset"` <del>} <ide><path>api/types/versions/v1p20/types.go <del>// Package v1p20 provides specific API types for the API version 1, patch 20. <del>package v1p20 <del> <del>import ( <del> "github.com/docker/engine-api/types" <del> "github.com/docker/engine-api/types/container" <del> "github.com/docker/go-connections/nat" <del>) <del> <del>// ContainerJSON is a backcompatibility struct for the API 1.20 <del>type ContainerJSON struct { <del> *types.ContainerJSONBase <del> Mounts []types.MountPoint <del> Config *ContainerConfig <del> NetworkSettings *NetworkSettings <del>} <del> <del>// ContainerConfig is a backcompatibility struct used in ContainerJSON for the API 1.20 <del>type ContainerConfig struct { <del> *container.Config <del> <del> MacAddress string <del> NetworkDisabled bool <del> ExposedPorts map[nat.Port]struct{} <del> <del> // backward compatibility, they now live in HostConfig <del> VolumeDriver string <del>} <del> <del>// StatsJSON is a backcompatibility struct used in Stats for API prior to 1.21 <del>type StatsJSON struct { <del> types.Stats <del> Network types.NetworkStats `json:"network,omitempty"` <del>} <del> <del>// NetworkSettings is a backward compatible struct for APIs prior to 1.21 <del>type NetworkSettings struct { <del> types.NetworkSettingsBase <del> types.DefaultNetworkSettings <del>}
71
PHP
PHP
remove empty array
0db867ad26e0b20962c30d98504e08c9929f2d96
<ide><path>src/Illuminate/Redis/Connectors/PhpRedisConnector.php <ide> protected function createRedisClusterInstance(array $servers, array $options) <ide> } <ide> <ide> if (version_compare(phpversion('redis'), '5.3.2', '>=')) { <del> $parameters[] = Arr::get($options, 'context', []); <add> $parameters[] = Arr::get($options, 'context'); <ide> } <ide> <ide> return tap(new RedisCluster(...$parameters), function ($client) use ($options) {
1
Go
Go
use hijack for logs instead of stream
b419699ab8f79f4826ec94583c6f7a46f74eeaa2
<ide><path>api.go <ide> func createRouter(srv *Server, logging bool) (*mux.Router, error) { <ide> localFct := fct <ide> f := func(w http.ResponseWriter, r *http.Request) { <ide> utils.Debugf("Calling %s %s", localMethod, localRoute) <add> <ide> if logging { <ide> log.Println(r.Method, r.RequestURI) <ide> } <ide> func createRouter(srv *Server, logging bool) (*mux.Router, error) { <ide> w.WriteHeader(http.StatusNotFound) <ide> return <ide> } <add> <ide> if err := localFct(srv, version, w, r, mux.Vars(r)); err != nil { <ide> httpError(w, err) <ide> } <ide><path>commands.go <ide> func (cli *DockerCli) CmdLogs(args ...string) error { <ide> return nil <ide> } <ide> <del> if err := cli.stream("POST", "/containers/"+cmd.Arg(0)+"/attach?logs=1&stdout=1", nil, os.Stdout); err != nil { <add> if err := cli.hijack("POST", "/containers/"+cmd.Arg(0)+"/attach?logs=1&stdout=1", false, nil, os.Stdout); err != nil { <ide> return err <ide> } <del> if err := cli.stream("POST", "/containers/"+cmd.Arg(0)+"/attach?logs=1&stderr=1", nil, os.Stderr); err != nil { <add> if err := cli.hijack("POST", "/containers/"+cmd.Arg(0)+"/attach?logs=1&stderr=1", false, nil, os.Stderr); err != nil { <ide> return err <ide> } <ide> return nil <ide> func (cli *DockerCli) stream(method, path string, in io.Reader, out io.Writer) e <ide> return err <ide> } <ide> defer resp.Body.Close() <add> <ide> if resp.StatusCode < 200 || resp.StatusCode >= 400 { <ide> body, err := ioutil.ReadAll(resp.Body) <ide> if err != nil { <ide> func (cli *DockerCli) stream(method, path string, in io.Reader, out io.Writer) e <ide> } <ide> <ide> func (cli *DockerCli) hijack(method, path string, setRawTerminal bool, in *os.File, out io.Writer) error { <add> <ide> req, err := http.NewRequest(method, fmt.Sprintf("/v%g%s", APIVERSION, path), nil) <ide> if err != nil { <ide> return err <ide> } <add> req.Header.Set("User-Agent", "Docker-Client/"+VERSION) <ide> req.Header.Set("Content-Type", "plain/text") <add> <ide> dial, err := net.Dial(cli.proto, cli.addr) <ide> if err != nil { <ide> return err <ide> } <ide> clientconn := httputil.NewClientConn(dial, nil) <del> clientconn.Do(req) <ide> defer clientconn.Close() <ide> <add> // Server hijacks the connection, error 'connection closed' expected <add> clientconn.Do(req) <add> <ide> rwc, br := clientconn.Hijack() <ide> defer rwc.Close() <ide> <ide><path>server.go <ide> func (srv *Server) ContainerAttach(name string, logs, stream, stdin, stdout, std <ide> if stdout { <ide> cLog, err := container.ReadLog("stdout") <ide> if err != nil { <del> utils.Debugf(err.Error()) <add> utils.Debugf("Error reading logs (stdout): %s", err) <ide> } else if _, err := io.Copy(out, cLog); err != nil { <del> utils.Debugf(err.Error()) <add> utils.Debugf("Error streaming logs (stdout): %s", err) <ide> } <ide> } <ide> if stderr { <ide> cLog, err := container.ReadLog("stderr") <ide> if err != nil { <del> utils.Debugf(err.Error()) <add> utils.Debugf("Error reading logs (stderr): %s", err) <ide> } else if _, err := io.Copy(out, cLog); err != nil { <del> utils.Debugf(err.Error()) <add> utils.Debugf("Error streaming logs (stderr): %s", err) <ide> } <ide> } <ide> }
3
PHP
PHP
remove second param from json structure
da46df36cd6ca2cba2710c8ba577aae377e710d0
<ide><path>src/Illuminate/Foundation/Testing/TestResponse.php <ide> public function assertExactJson(array $data) <ide> * Assert that the response has a given JSON structure. <ide> * <ide> * @param array|null $structure <del> * @param array|null $responseData <ide> * @return $this <ide> */ <del> public function assertJsonStructure(array $structure = null, $responseData = null) <add> public function assertJsonStructure(array $structure = null) <ide> { <ide> if (is_null($structure)) { <ide> return $this->assertJson(); <ide> } <ide> <del> if (is_null($responseData)) { <del> $responseData = $this->decodeResponseJson(); <del> } <add> $responseData = $this->decodeResponseJson(); <ide> <ide> foreach ($structure as $key => $value) { <ide> if (is_array($value) && $key === '*') {
1
Javascript
Javascript
add support for reflectivity in loader.js
04658393de0f78dc8d537c9409c0bb78c9a060ec
<ide><path>src/loaders/Loader.js <ide> THREE.Loader.prototype = { <ide> if ( value === true ) json.vertexColors = THREE.VertexColors; <ide> if ( value === 'face' ) json.vertexColors = THREE.FaceColors; <ide> break; <add> case 'reflectivity': <add> json.reflectivity = value; <add> break; <ide> default: <ide> console.error( 'THREE.Loader.createMaterial: Unsupported', name, value ); <ide> break;
1
Text
Text
update changelog for 2.9.0
c4f331aa3fe9d9bb80715a54180adec995d5386a
<ide><path>CHANGELOG.md <ide> Changelog <ide> ========= <ide> <add>### 2.9.0 [See full changelog](https://gist.github.com/ichernev/0c9a9b49951111a27ce7) <add> <add>languages: <add>* [2104](https://github.com/moment/moment/issues/2104) Frisian (fy) language file with unit test <add>* [2097](https://github.com/moment/moment/issues/2097) add ar-tn locale <add> <add>deprecations: <add>* [2074](https://github.com/moment/moment/issues/2074) Implement `moment.fn.utcOffset`, deprecate `momen.fn.zone` <add> <add>features: <add>* [2088](https://github.com/moment/moment/issues/2088) add moment.fn.isBetween <add>* [2054](https://github.com/moment/moment/issues/2054) Call updateOffset when creating moment (needed for default timezone in <add> moment-timezone) <add>* [1893](https://github.com/moment/moment/issues/1893) Add moment.isDate method <add>* [1825](https://github.com/moment/moment/issues/1825) Implement toJSON function on Duration <add>* [1809](https://github.com/moment/moment/issues/1809) Allowing moment.set() to accept a hash of units <add>* [2128](https://github.com/moment/moment/issues/2128) Add firstDayOfWeek, firstDayOfYear locale getters <add>* [2131](https://github.com/moment/moment/issues/2131) Add quarter diff support <add> <add>Some bugfixes and language improvements -- [full changelog](https://gist.github.com/ichernev/0c9a9b49951111a27ce7) <add> <ide> ### 2.8.4 [See full changelog](https://gist.github.com/ichernev/a4fcb0a46d74e4b9b996) <ide> <ide> Features:
1
Ruby
Ruby
add tests for explicit engines
f8bf1982dff9cf0f35fb7a121932c794ecdc1cb1
<ide><path>railties/lib/rails/application.rb <ide> module Rails <ide> class Application < Engine <ide> autoload :Bootstrap, 'rails/application/bootstrap' <add> autoload :Configurable, 'rails/application/configurable' <ide> autoload :Configuration, 'rails/application/configuration' <ide> autoload :Finisher, 'rails/application/finisher' <ide> autoload :Railties, 'rails/application/railties' <ide> def require_environment! <ide> require environment if environment <ide> end <ide> <del> def config <del> @config ||= Application::Configuration.new(self.class.find_root_with_flag("config.ru", Dir.pwd)) <del> end <del> <ide> def routes <ide> ::ActionController::Routing::Routes <ide> end <ide><path>railties/lib/rails/application/configurable.rb <add>module Rails <add> class Application <add> module Configurable <add> def self.included(base) <add> base.extend ClassMethods <add> end <add> <add> module ClassMethods <add> def inherited(base) <add> raise "You cannot inherit from a Rails::Application child" <add> end <add> end <add> <add> def config <add> @config ||= Application::Configuration.new(self.class.find_root_with_flag("config.ru", Dir.pwd)) <add> end <add> end <add> end <add>end <ide>\ No newline at end of file <ide><path>railties/lib/rails/railtie.rb <ide> def subclasses <ide> <ide> def inherited(base) <ide> unless abstract_railtie?(base) <del> base.send(:include, self::Configurable) if add_configurable?(base) <add> base.send(:include, self::Configurable) <ide> subclasses << base <ide> end <ide> end <ide> def generators(&blk) <ide> def abstract_railtie?(base) <ide> ABSTRACT_RAILTIES.include?(base.name) <ide> end <del> <del> # Just add configurable behavior if a Configurable module is defined <del> # and the class is a direct child from self. This is required to avoid <del> # application or plugins getting class configuration method from Railties <del> # and/or Engines. <del> def add_configurable?(base) <del> defined?(self::Configurable) && base.ancestors[1] == self <del> end <ide> end <ide> <ide> def rake_tasks <ide><path>railties/test/isolation/abstract_unit.rb <ide> def build_app(options = {}) <ide> end <ide> <ide> class Bukkit <add> attr_reader :path <add> <ide> def initialize(path) <ide> @path = path <ide> end <ide> def delete(file) <ide> def plugin(name, string = "") <ide> dir = "#{app_path}/vendor/plugins/#{name}" <ide> FileUtils.mkdir_p(dir) <add> <ide> File.open("#{dir}/init.rb", 'w') do |f| <ide> f.puts "::#{name.upcase} = 'loaded'" <ide> f.puts string <ide> end <add> <add> Bukkit.new(dir).tap do |bukkit| <add> yield bukkit if block_given? <add> end <add> end <add> <add> def engine(name) <add> dir = "#{app_path}/random/#{name}" <add> FileUtils.mkdir_p(dir) <add> <add> app = File.readlines("#{app_path}/config/application.rb") <add> app.insert(2, "$:.unshift(\"#{dir}/lib\")") <add> app.insert(3, "require #{name.inspect}") <add> <add> File.open("#{app_path}/config/application.rb", 'r+') do |f| <add> f.puts app <add> end <add> <ide> Bukkit.new(dir).tap do |bukkit| <ide> yield bukkit if block_given? <ide> end <ide><path>railties/test/railties/engine_test.rb <add>require "isolation/abstract_unit" <add>require "railties/shared_tests" <add> <add>module RailtiesTest <add> class EngineTest < Test::Unit::TestCase <add> include ActiveSupport::Testing::Isolation <add> include SharedTests <add> <add> def setup <add> build_app <add> <add> @plugin = engine "bukkits" do |plugin| <add> plugin.write "lib/bukkits.rb", <<-RUBY <add> class Bukkits <add> class Engine < ::Rails::Engine <add> end <add> end <add> RUBY <add> plugin.write "lib/another.rb", "class Another; end" <add> end <add> end <add> end <add>end <ide><path>railties/test/railties/plugin_test.rb <ide> require "railties/shared_tests" <ide> <ide> module RailtiesTest <del> class PluginSpecificTest < Test::Unit::TestCase <add> class PluginTest < Test::Unit::TestCase <ide> include ActiveSupport::Testing::Isolation <ide> include SharedTests <ide> <ide> def setup <ide> <ide> @plugin = plugin "bukkits", "::LEVEL = config.log_level" do |plugin| <ide> plugin.write "lib/bukkits.rb", "class Bukkits; end" <add> plugin.write "lib/another.rb", "class Another; end" <ide> end <ide> end <ide> <add> test "plugin can load the file with the same name in lib" do <add> boot_rails <add> require "bukkits" <add> assert_equal "Bukkits", Bukkits.name <add> end <add> <ide> test "it loads the plugin's init.rb file" do <ide> boot_rails <ide> assert_equal "loaded", BUKKITS <ide> def setup <ide> assert_equal :debug, LEVEL <ide> end <ide> <add> test "plugin_init_is_ran_before_application_ones" do <add> plugin "foo", "$foo = true" do |plugin| <add> plugin.write "lib/foo.rb", "module Foo; end" <add> end <add> <add> app_file 'config/initializers/foo.rb', <<-RUBY <add> raise "no $foo" unless $foo <add> raise "no Foo" unless Foo <add> RUBY <add> <add> boot_rails <add> assert $foo <add> end <add> <ide> test "plugin should work without init.rb" do <ide> @plugin.delete("init.rb") <ide> <ide> class Engine < Rails::Engine <ide> <ide> assert rescued, "Expected boot rails to fail" <ide> end <add> <add> test "deprecated tasks are also loaded" do <add> $executed = false <add> @plugin.write "tasks/foo.rake", <<-RUBY <add> task :foo do <add> $executed = true <add> end <add> RUBY <add> <add> boot_rails <add> require 'rake' <add> require 'rake/rdoctask' <add> require 'rake/testtask' <add> Rails.application.load_tasks <add> Rake::Task[:foo].invoke <add> assert $executed <add> end <add> <ide> end <ide> end <ide><path>railties/test/railties/shared_tests.rb <ide> def app <ide> <ide> def test_plugin_puts_its_lib_directory_on_load_path <ide> boot_rails <del> require "bukkits" <del> assert_equal "Bukkits", Bukkits.name <del> end <del> <del> def test_plugin_init_is_ran_before_application_ones <del> plugin "foo", "$foo = true" do |plugin| <del> plugin.write "lib/foo.rb", "module Foo; end" <del> end <del> <del> app_file 'config/initializers/foo.rb', <<-RUBY <del> raise "no $foo" unless $foo <del> raise "no Foo" unless Foo <del> RUBY <del> <del> boot_rails <del> assert $foo <add> require "another" <add> assert_equal "Another", Another.name <ide> end <ide> <ide> def test_plugin_paths_get_added_to_as_dependency_list <ide> boot_rails <del> assert_equal "Bukkits", Bukkits.name <add> assert_equal "Another", Another.name <ide> end <ide> <ide> def test_plugins_constants_are_not_reloaded_by_default <ide> boot_rails <del> assert_equal "Bukkits", Bukkits.name <add> assert_equal "Another", Another.name <ide> ActiveSupport::Dependencies.clear <del> @plugin.delete("lib/bukkits.rb") <del> assert_nothing_raised { Bukkits } <add> @plugin.delete("lib/another.rb") <add> assert_nothing_raised { Another } <ide> end <ide> <ide> def test_plugin_constants_get_reloaded_if_config_reload_plugins <ide> def test_plugin_constants_get_reloaded_if_config_reload_plugins <ide> <ide> boot_rails <ide> <del> assert_equal "Bukkits", Bukkits.name <add> assert_equal "Another", Another.name <ide> ActiveSupport::Dependencies.clear <del> @plugin.delete("lib/bukkits.rb") <del> assert_raises(NameError) { Bukkits } <add> @plugin.delete("lib/another.rb") <add> assert_raises(NameError) { Another } <ide> end <ide> <ide> def test_plugin_puts_its_models_directory_on_load_path <ide> def test_rake_tasks_lib_tasks_are_loaded <ide> assert $executed <ide> end <ide> <del> def test_deprecated_tasks_are_also_loaded <del> $executed = false <del> @plugin.write "tasks/foo.rake", <<-RUBY <del> task :foo do <del> $executed = true <del> end <del> RUBY <del> <del> boot_rails <del> require 'rake' <del> require 'rake/rdoctask' <del> require 'rake/testtask' <del> Rails.application.load_tasks <del> Rake::Task[:foo].invoke <del> assert $executed <del> end <del> <ide> def test_i18n_files_have_lower_priority_than_application_ones <ide> add_to_config <<-RUBY <ide> config.i18n.load_path << "#{app_path}/app/locales/en.yml" <ide> def test_i18n_files_have_lower_priority_than_application_ones <ide> #{RAILS_FRAMEWORK_ROOT}/activemodel/lib/active_model/locale/en.yml <ide> #{RAILS_FRAMEWORK_ROOT}/activerecord/lib/active_record/locale/en.yml <ide> #{RAILS_FRAMEWORK_ROOT}/actionpack/lib/action_view/locale/en.yml <del> #{app_path}/vendor/plugins/bukkits/config/locales/en.yml <add> #{@plugin.path}/config/locales/en.yml <ide> #{app_path}/config/locales/en.yml <ide> #{app_path}/app/locales/en.yml <ide> ).map { |path| File.expand_path(path) }, I18n.load_path.map { |path| File.expand_path(path) }
7
Text
Text
update id selector with basic information.
77d2e5e755a234f9b4cfcd2db6e126799b1be323
<ide><path>guide/english/css/selectors/general/id/index.md <ide> --- <ide> title: Id <ide> --- <del>## Id <ide> <del>This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/css/selectors/general/id/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>. <add># ID <ide> <del><a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>. <add>the "id" selector is used within a html/css file in order to style a unique element on a page. Unlike other kinds of selectors such as attributes or class selectors, an id can only be used on a single element in a page. <ide> <del><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds --> <add>## Using an Id selector <ide> <del>#### More Information: <del><!-- Please add any articles you think might be helpful to read before writing the article --> <add>### HTML example <add>To use an Id selector within an HTML file, you must simply assign the id within the opening tags of an html attribute like shown below. Not that the Id should not include spaces and should be surrounded by quotes. <add>```html <add><p id="company-motto">To do our best!</p> <add>``` <add>### CSS example <add>Once you have added a unique Id selector to your page, you can add specific styling to the id you've selected using CSS as shown below. <add>```css <add>#company-motto { <add> font-weight: 900; <add>} <add>``` <ide> <add>## Notable features <add>When one or more elements with the same Id are present within the same html file, only the first instance of the the Id will have the style. Additionally because Ids are unique selectors, they should only be used when an element absolutely has to have a specific style and therefore has a high specificity in order for its styling to take precedence over other possible selectors. <ide>
1
Javascript
Javascript
set better defaults for datatexture
d0148758941fe5b20368ef22c53c197d7959cd9a
<ide><path>examples/js/Ocean.js <ide> THREE.Ocean.prototype.generateSeedPhaseTexture = function() { <ide> } <ide> <ide> this.pingPhaseTexture = new THREE.DataTexture( phaseArray, this.resolution, this.resolution, THREE.RGBAFormat ); <del> this.pingPhaseTexture.minFilter = THREE.NearestFilter; <del> this.pingPhaseTexture.magFilter = THREE.NearestFilter; <ide> this.pingPhaseTexture.wrapS = THREE.ClampToEdgeWrapping; <ide> this.pingPhaseTexture.wrapT = THREE.ClampToEdgeWrapping; <ide> this.pingPhaseTexture.type = THREE.FloatType; <ide><path>examples/js/SimulationRenderer.js <ide> function SimulationRenderer( WIDTH, renderer ) { <ide> texture.minFilter = THREE.NearestFilter; <ide> texture.magFilter = THREE.NearestFilter; <ide> texture.needsUpdate = true; <del> texture.flipY = false; <ide> <ide> return texture; <ide> <ide> function SimulationRenderer( WIDTH, renderer ) { <ide> texture.minFilter = THREE.NearestFilter; <ide> texture.magFilter = THREE.NearestFilter; <ide> texture.needsUpdate = true; <del> texture.flipY = false; <ide> <ide> return texture; <ide> <ide><path>examples/js/postprocessing/GlitchPass.js <ide> THREE.GlitchPass.prototype = { <ide> texture.minFilter = THREE.NearestFilter; <ide> texture.magFilter = THREE.NearestFilter; <ide> texture.needsUpdate = true; <del> texture.flipY = false; <ide> return texture; <ide> <ide> } <ide><path>src/objects/Skeleton.js <ide> THREE.Skeleton = function ( bones, boneInverses, useVertexTexture ) { <ide> <ide> this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel <ide> this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType ); <del> this.boneTexture.minFilter = THREE.NearestFilter; <del> this.boneTexture.magFilter = THREE.NearestFilter; <del> this.boneTexture.generateMipmaps = false; <del> this.boneTexture.flipY = false; <ide> <ide> } else { <ide> <ide><path>src/textures/DataTexture.js <ide> */ <ide> <ide> THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) { <add> <add> if ( magFilter === undefined ) { <add> <add> magFilter = THREE.NearestFilter; <add> <add> } <add> <add> if ( minFilter === undefined ) { <add> <add> minFilter = THREE.NearestFilter; <add> <add> } <ide> <ide> THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); <ide> <ide> this.image = { data: data, width: width, height: height }; <add> <add> this.flipY = false; <add> this.generateMipmaps = false; <ide> <ide> }; <ide>
5
PHP
PHP
return fake objects from facades
81895941a5ee83e89c1e707cdd5d06515d276b4d
<ide><path>src/Illuminate/Support/Facades/Bus.php <ide> class Bus extends Facade <ide> /** <ide> * Replace the bound instance with a fake. <ide> * <del> * @return void <add> * @return BusFake <ide> */ <ide> public static function fake() <ide> { <del> static::swap(new BusFake); <add> static::swap($fake = new BusFake); <add> <add> return $fake; <ide> } <ide> <ide> /** <ide><path>src/Illuminate/Support/Facades/Event.php <ide> class Event extends Facade <ide> * Replace the bound instance with a fake. <ide> * <ide> * @param array|string $eventsToFake <del> * @return void <add> * @return EventFake <ide> */ <ide> public static function fake($eventsToFake = []) <ide> { <ide> static::swap($fake = new EventFake(static::getFacadeRoot(), $eventsToFake)); <ide> <ide> Model::setEventDispatcher($fake); <add> <add> return $fake; <ide> } <ide> <ide> /** <ide><path>src/Illuminate/Support/Facades/Mail.php <ide> class Mail extends Facade <ide> /** <ide> * Replace the bound instance with a fake. <ide> * <del> * @return void <add> * @return MailFake <ide> */ <ide> public static function fake() <ide> { <del> static::swap(new MailFake); <add> static::swap($fake = new MailFake); <add> <add> return $fake; <ide> } <ide> <ide> /** <ide><path>src/Illuminate/Support/Facades/Queue.php <ide> class Queue extends Facade <ide> /** <ide> * Replace the bound instance with a fake. <ide> * <del> * @return void <add> * @return QueueFake <ide> */ <ide> public static function fake() <ide> { <del> static::swap(new QueueFake(static::getFacadeApplication())); <add> static::swap($fake = new QueueFake(static::getFacadeApplication())); <add> <add> return $fake; <ide> } <ide> <ide> /** <ide><path>src/Illuminate/Support/Facades/Storage.php <ide> class Storage extends Facade <ide> * <ide> * @param string|null $disk <ide> * <del> * @return void <add> * @return Filesystem <ide> */ <ide> public static function fake($disk = null) <ide> { <ide> public static function fake($disk = null) <ide> $root = storage_path('framework/testing/disks/'.$disk) <ide> ); <ide> <del> static::set($disk, self::createLocalDriver(['root' => $root])); <add> static::set($disk, $fake = self::createLocalDriver(['root' => $root])); <add> <add> return $fake; <ide> } <ide> <ide> /** <ide> * Replace the given disk with a persistent local testing disk. <ide> * <ide> * @param string|null $disk <del> * @return void <add> * @return Filesystem <ide> */ <ide> public static function persistentFake($disk = null) <ide> { <ide> $disk = $disk ?: self::$app['config']->get('filesystems.default'); <ide> <del> static::set($disk, self::createLocalDriver([ <add> static::set($disk, $fake = self::createLocalDriver([ <ide> 'root' => storage_path('framework/testing/disks/'.$disk), <ide> ])); <add> <add> return $fake; <ide> } <ide> <ide> /**
5
Text
Text
fix wrong response.end() at request.socket
019a2c4f8460548ececa4225f1c7a6d11eb8bd25
<ide><path>doc/api/http.md <ide> added: v0.3.0 <ide> <ide> Reference to the underlying socket. Usually users will not want to access <ide> this property. In particular, the socket will not emit `'readable'` events <del>because of how the protocol parser attaches to the socket. After <del>`response.end()`, the property is nulled. The `socket` may also be accessed <del>via `request.connection`. <add>because of how the protocol parser attaches to the socket. The `socket` <add>may also be accessed via `request.connection`. <ide> <ide> Example: <ide>
1
Ruby
Ruby
join relation qualification
d1e5265a1db424e7361878772d32ae4ec39babe2
<ide><path>lib/sql_algebra/relations/join_relation.rb <ide> def ==(other) <ide> ((relation1 == other.relation1 and relation2 == other.relation2) or <ide> (relation2 == other.relation1 and relation1 == other.relation2)) <ide> end <add> <add> def qualify <add> JoinRelation.new(relation1.qualify, relation2.qualify, *predicates.collect(&:qualify)) <add> end <ide> <add> protected <ide> def joins <ide> relation1.joins + relation2.joins + [Join.new(relation1, relation2, predicates, join_type)] <ide> end <ide> def attribute(name) <ide> relation1[name] || relation2[name] <ide> end <ide> <del> protected <ide> delegate :table, :to => :relation1 <ide> end <ide>\ No newline at end of file <ide><path>spec/predicates/binary_predicate_spec.rb <ide> def predicate_name <ide> end <ide> <ide> describe '#qualify' do <del> it "manufactures an equality predicate with qualified attributes" do <add> it "distributes over the predicates and attributes" do <ide> ConcreteBinaryPredicate.new(@attribute1, @attribute2).qualify. \ <ide> should == ConcreteBinaryPredicate.new(@attribute1.qualify, @attribute2.qualify) <ide> end <ide><path>spec/relations/join_relation_spec.rb <ide> require File.join(File.dirname(__FILE__), '..', 'spec_helper') <ide> <del>describe 'between two relations' do <add>describe JoinRelation do <ide> before do <ide> @relation1 = TableRelation.new(:foo) <ide> @relation2 = TableRelation.new(:bar) <ide> end <ide> end <ide> <add> describe '#qualify' do <add> it 'distributes over the relations and predicates' do <add> JoinRelation.new(@relation1, @relation2, @predicate).qualify. \ <add> should == JoinRelation.new(@relation1.qualify, @relation2.qualify, @predicate.qualify) <add> end <add> end <add> <ide> describe '#to_sql' do <ide> before do <ide> @relation1 = @relation1.select(@relation1[:id] == @relation2[:foo_id]) <ide><path>spec/relations/order_relation_spec.rb <ide> end <ide> <ide> describe '#qualify' do <del> it "manufactures an order relation with qualified attributes and qualified relation" do <add> it "distributes over the relation and attributes" do <ide> OrderRelation.new(@relation1, @attribute1).qualify. \ <ide> should == OrderRelation.new(@relation1.qualify, @attribute1.qualify) <ide> end <ide><path>spec/relations/projection_relation_spec.rb <ide> end <ide> <ide> describe '#qualify' do <del> it "manufactures a projection relation with qualified attributes and qualified relation" do <add> it "distributes over teh relation and attributes" do <ide> ProjectionRelation.new(@relation1, @attribute1).qualify. \ <ide> should == ProjectionRelation.new(@relation1.qualify, @attribute1.qualify) <ide> end <ide><path>spec/relations/range_relation_spec.rb <ide> end <ide> <ide> describe '#qualify' do <del> it "manufactures a range relation with a qualified relation and a qualified range" do <add> it "distributes over the relation and attributes" do <ide> pending <ide> end <ide> end <ide><path>spec/relations/rename_relation_spec.rb <ide> should == RenameRelation.new(RenameRelation.new(@relation, @relation[:id] => :humpty), @relation[:name] => :dumpty) <ide> end <ide> <del> it "make this test less brittle wrt/ hash order" do <del> pending <del> end <del> <ide> it "raises an exception if the alias provided is already used" do <ide> pending <ide> end <ide> end <ide> <ide> describe '#qualify' do <del> it "manufactures a rename relation with an identical attribute and alias, but with a qualified relation" do <add> it "distributes over the relation and renames" do <ide> RenameRelation.new(@relation, @relation[:id] => :schmid).qualify. \ <ide> should == RenameRelation.new(@relation.qualify, @relation[:id].qualify => :schmid) <ide> end <ide><path>spec/relations/selection_relation_spec.rb <ide> end <ide> <ide> describe '#qualify' do <del> it "manufactures a selection relation with qualified predicates and qualified relation" do <add> it "distributes over the relation and predicates" do <ide> SelectionRelation.new(@relation1, @predicate1).qualify. \ <ide> should == SelectionRelation.new(@relation1.qualify, @predicate1.qualify) <ide> end
8
Ruby
Ruby
push a failing test for issues [] and []
67582f08bf86ec71a27363554bc550e929a007f7
<ide><path>activerecord/test/cases/named_scope_test.rb <ide> def test_named_scopes_are_reset_on_association_reload <ide> assert before.object_id != post.comments.containing_the_letter_e.object_id, "AssociationCollection##{method} should reset the named scopes cache" <ide> end <ide> end <add> <add> def test_named_scoped_are_lazy_loaded_if_table_still_does_not_exist <add> assert_nothing_raised do <add> require "models/without_table" <add> end <add> end <ide> end <ide> <ide> class DynamicScopeMatchTest < ActiveRecord::TestCase <ide><path>activerecord/test/models/without_table.rb <add>class WithoutTable < ActiveRecord::Base <add> default_scope where(:published => true) <add>end <ide>\ No newline at end of file <ide><path>railties/test/application/loading_test.rb <ide> def app <ide> @app ||= Rails.application <ide> end <ide> <del> def test_load_should_load_constants <add> def test_constants_in_app_are_autoloaded <ide> app_file "app/models/post.rb", <<-MODEL <ide> class Post < ActiveRecord::Base <ide> validates_acceptance_of :title, :accept => "omg" <ide> class Post < ActiveRecord::Base <ide> assert_equal 'omg', p.title <ide> end <ide> <add> def test_models_without_table_do_not_panic_on_scope_definitions_when_loaded <add> app_file "app/models/user.rb", <<-MODEL <add> class User < ActiveRecord::Base <add> default_scope where(:published => true) <add> end <add> MODEL <add> <add> require "#{rails_root}/config/environment" <add> setup_ar! <add> <add> User <add> end <add> <ide> def test_descendants_are_cleaned_on_each_request_without_cache_classes <ide> add_to_config <<-RUBY <ide> config.cache_classes = false
3
Python
Python
update arg parsing
3583ea84d8fb6979d068c23816c0994dab5f81a4
<ide><path>spacy/cli/_util.py <ide> def parse_config_overrides(args: List[str]) -> Dict[str, Any]: <ide> if "." not in opt: <ide> msg.fail(f"{err}: can't override top-level section", exits=1) <ide> if not args or args[0].startswith("--"): # flag with no value <del> value = True <add> value = "true" <ide> else: <ide> value = args.pop(0) <ide> # Just like we do in the config, we're calling json.loads on the <ide> # values. But since they come from the CLI, it'd b unintuitive to <ide> # explicitly mark strings with escaped quotes. So we're working <ide> # around that here by falling back to a string if parsing fails. <add> # TODO: improve logic to handle simple types like list of strings? <ide> try: <ide> result[opt] = srsly.json_loads(value) <ide> except ValueError:
1
Python
Python
refer warmup_ratio when setting warmup_num_steps.
037bdf82d382d70ba91afcbe491b6e98b0e9e35c
<ide><path>src/transformers/deepspeed.py <ide> def trainer_config_process(self, args): <ide> <ide> self.fill_only("scheduler.params.warmup_min_lr", 0) # not a trainer arg <ide> self.fill_match("scheduler.params.warmup_max_lr", args.learning_rate, "learning_rate") <del> self.fill_match("scheduler.params.warmup_num_steps", args.warmup_steps, "warmup_steps") <ide> # total_num_steps - will get set in trainer_config_finalize <ide> <ide> # fp16 <ide> def trainer_config_finalize(self, args, model, num_training_steps): <ide> <ide> # scheduler <ide> self.fill_match("scheduler.params.total_num_steps", num_training_steps, "num_training_steps (calculated)") <add> self.fill_match("scheduler.params.warmup_num_steps", args.get_warmup_steps(num_training_steps), "warmup_steps") <ide> <ide> if len(self.mismatches) > 0: <ide> mismatches = "\n".join(self.mismatches) <ide><path>src/transformers/trainer.py <ide> def create_scheduler(self, num_training_steps: int): <ide> num_training_steps (int): The number of training steps to do. <ide> """ <ide> if self.lr_scheduler is None: <del> warmup_steps = ( <del> self.args.warmup_steps <del> if self.args.warmup_steps > 0 <del> else math.ceil(num_training_steps * self.args.warmup_ratio) <del> ) <del> <ide> self.lr_scheduler = get_scheduler( <ide> self.args.lr_scheduler_type, <ide> self.optimizer, <del> num_warmup_steps=warmup_steps, <add> num_warmup_steps=self.args.get_warmup_steps(num_training_steps), <ide> num_training_steps=num_training_steps, <ide> ) <ide> <ide><path>src/transformers/training_args.py <ide> <ide> import contextlib <ide> import json <add>import math <ide> import os <ide> import warnings <ide> from dataclasses import asdict, dataclass, field <ide> def main_process_first(self, local=True, desc="work"): <ide> else: <ide> yield <ide> <add> def get_warmup_steps(self, num_training_steps: int): <add> """ <add> Get number of steps used for a linear warmup. <add> """ <add> warmup_steps = ( <add> self.warmup_steps <add> if self.warmup_steps > 0 <add> else math.ceil(num_training_steps * self.warmup_ratio) <add> ) <add> return warmup_steps <add> <ide> def to_dict(self): <ide> """ <ide> Serializes this instance while replace `Enum` by their values (for JSON serialization support).
3
PHP
PHP
remove encrpytion features from individual cookies
7cc569332d211e0c525e3d4d88f81d3cd89c2786
<ide><path>src/Http/Cookie/Cookie.php <ide> class Cookie implements CookieInterface <ide> { <ide> <del> use CookieCryptTrait; <del> <ide> /** <ide> * Expires attribute format. <ide> * <ide> public function read($path = null) <ide> return Hash::get($this->value, $path); <ide> } <ide> <del> /** <del> * Encrypts the cookie value <del> * <del> * @param string|null $key Encryption key <del> * @return $this <del> */ <del> public function encrypt($key = null) <del> { <del> if ($key !== null) { <del> $this->setEncryptionKey($key); <del> } <del> <del> $this->value = $this->_encrypt($this->value); <del> <del> return $this; <del> } <del> <del> /** <del> * Decrypts the cookie value <del> * <del> * @param string|null $key Encryption key <del> * @return $this <del> */ <del> public function decrypt($key = null) <del> { <del> if ($key !== null) { <del> $this->setEncryptionKey($key); <del> } <del> <del> $this->value = $this->_decrypt($this->value); <del> <del> return $this; <del> } <del> <ide> /** <ide> * Checks if the cookie value was expanded <ide> * <ide><path>src/Http/Cookie/CookieCryptTrait.php <del><?php <del>/** <del> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <del> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <del> * <del> * Licensed under The MIT License <del> * For full copyright and license information, please see the LICENSE.txt <del> * Redistributions of files must retain the above copyright notice. <del> * <del> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <del> * @link http://cakephp.org CakePHP(tm) Project <del> * @since 3.5.0 <del> * @license http://www.opensource.org/licenses/mit-license.php MIT License <del> */ <del>namespace Cake\Http\Cookie; <del> <del>use Cake\Utility\Security; <del>use RuntimeException; <del> <del>/** <del> * Cookie Crypt Trait. <del> * <del> * Provides the encrypt/decrypt logic. <del> */ <del>trait CookieCryptTrait <del>{ <del> <del> /** <del> * Valid cipher names for encrypted cookies. <del> * <del> * @var array <del> */ <del> protected $_validCiphers = [ <del> 'aes' <del> ]; <del> <del> /** <del> * Encryption cipher <del> * <del> * @param string|bool <del> */ <del> protected $encryptionCipher = 'aes'; <del> <del> /** <del> * The key for encrypting and decrypting the cookie <del> * <del> * @var string <del> */ <del> protected $encryptionKey = ''; <del> <del> /** <del> * Prefix of the encrypted string <del> * <del> * @var string <del> */ <del> protected $encryptedStringPrefix = 'Q2FrZQ==.'; <del> <del> /** <del> * Sets the encryption cipher <del> * <del> * @param string $cipher Cipher <del> * @return $this <del> */ <del> public function setEncryptionCipher($cipher) <del> { <del> $this->checkCipher($cipher); <del> $this->encryptionCipher = $cipher; <del> <del> return $this; <del> } <del> <del> /** <del> * Check if encryption is enabled <del> * <del> * @return bool <del> */ <del> public function isEncryptionEnabled() <del> { <del> return is_string($this->encryptionCipher); <del> } <del> <del> /** <del> * Disables the encryption <del> * <del> * @return $this <del> */ <del> public function disableEncryption() <del> { <del> $this->encryptionCipher = false; <del> <del> return $this; <del> } <del> <del> /** <del> * Sets the encryption key <del> * <del> * @param string $key Encryption key <del> * @return $this <del> */ <del> public function setEncryptionKey($key) <del> { <del> $this->encryptionKey = $key; <del> <del> return $this; <del> } <del> <del> /** <del> * Returns the encryption key to be used. <del> * <del> * @return string <del> */ <del> public function getEncryptionKey() <del> { <del> if ($this->encryptionKey === null) { <del> return Security::getSalt(); <del> } <del> <del> return $this->encryptionKey; <del> } <del> <del> /** <del> * Encrypts $value using public $type method in Security class <del> * <del> * @param string|array $value Value to encrypt <del> * @return string Encoded values <del> */ <del> protected function _encrypt($value) <del> { <del> if (is_array($value)) { <del> $value = $this->_flatten($value); <del> } <del> <del> $encrypt = $this->encryptionCipher; <del> if ($encrypt === false) { <del> throw new RuntimeException('Encryption is disabled, no cipher provided.'); <del> } <del> <del> $cipher = null; <del> $key = $this->getEncryptionKey(); <del> <del> if ($encrypt === 'aes') { <del> $cipher = Security::encrypt($value, $key); <del> } <del> <del> return $this->encryptedStringPrefix . base64_encode($cipher); <del> } <del> <del> /** <del> * Helper method for validating encryption cipher names. <del> * <del> * @param string $encrypt The cipher name. <del> * @return void <del> * @throws \RuntimeException When an invalid cipher is provided. <del> */ <del> protected function checkCipher($encrypt) <del> { <del> if (!in_array($encrypt, $this->_validCiphers)) { <del> $msg = sprintf( <del> 'Invalid encryption cipher. Must be one of %s.', <del> implode(', ', $this->_validCiphers) <del> ); <del> throw new RuntimeException($msg); <del> } <del> } <del> <del> /** <del> * Decrypts $value using public $type method in Security class <del> * <del> * @param string|array $values Values to decrypt <del> * @return string|array Decrypted values <del> */ <del> protected function _decrypt($values) <del> { <del> if (is_string($values)) { <del> return $this->_decode($values); <del> } <del> <del> $decrypted = []; <del> foreach ($values as $name => $value) { <del> $decrypted[$name] = $this->_decode($value); <del> } <del> <del> return $decrypted; <del> } <del> <del> /** <del> * Decodes and decrypts a single value. <del> * <del> * @param string $value The value to decode & decrypt. <del> * @return string|array Decoded values. <del> */ <del> protected function _decode($value) <del> { <del> if (!$this->isEncryptionEnabled()) { <del> return $this->_expand($value); <del> } <del> <del> $key = $this->getEncryptionKey(); <del> $encrypt = $this->encryptionCipher; <del> <del> $value = base64_decode(substr($value, strlen($this->encryptedStringPrefix))); <del> <del> if ($encrypt === 'aes') { <del> $value = Security::decrypt($value, $key); <del> } <del> <del> return $this->_expand($value); <del> } <del>} <ide><path>src/Http/Cookie/RequestCookies.php <del><?php <del>/** <del> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <del> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <del> * <del> * Licensed under The MIT License <del> * Redistributions of files must retain the above copyright notice. <del> * <del> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <del> * @link http://cakephp.org CakePHP(tm) Project <del> * @since 3.5.0 <del> * @license http://www.opensource.org/licenses/mit-license.php MIT License <del> */ <del>namespace Cake\Http\Cookie; <del> <del>use InvalidArgumentException; <del>use Psr\Http\Message\ServerRequestInterface; <del> <del>class RequestCookies extends CookieCollection <del>{ <del> <del> /** <del> * Create instance from a server request. <del> * <del> * @param \Psr\Http\Message\ServerRequestInterface $request Request object <del> * @param string $cookieClass Cookie class to use for the cookies <del> * @return \Cake\Http\Cookie\RequestCookies <del> */ <del> public static function createFromRequest(ServerRequestInterface $request, $cookieClass = Cookie::class) <del> { <del> $cookies = []; <del> $cookieParams = $request->getCookieParams(); <del> <del> foreach ($cookieParams as $name => $value) { <del> $cookies[] = new $cookieClass($name, $value); <del> } <del> <del> return new static($cookies); <del> } <del>} <ide><path>src/Http/Cookie/ResponseCookies.php <del><?php <del>/** <del> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <del> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <del> * <del> * Licensed under The MIT License <del> * Redistributions of files must retain the above copyright notice. <del> * <del> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <del> * @link http://cakephp.org CakePHP(tm) Project <del> * @since 3.5.0 <del> * @license http://www.opensource.org/licenses/mit-license.php MIT License <del> */ <del>namespace Cake\Http\Cookie; <del> <del>use Psr\Http\Message\ResponseInterface; <del> <del>class ResponseCookies extends CookieCollection <del>{ <del> <del> /** <del> * Adds the cookies to the response <del> * <del> * @param \Psr\Http\Message\ResponseInterface $response Response object. <del> * @return \Psr\Http\Message\ResponseInterface <del> */ <del> public function addToResponse(ResponseInterface $response) <del> { <del> $header = []; <del> foreach ($this->cookies as $setCookie) { <del> $header[] = $setCookie->toHeaderValue(); <del> } <del> <del> return $response->withAddedHeader('Set-Cookie', $header); <del> } <del>} <ide><path>tests/TestCase/Http/Cookie/CookieTest.php <ide> class CookieTest extends TestCase <ide> { <ide> <del> /** <del> * Encryption key used in the tests <del> * <del> * @var string <del> */ <del> protected $encryptionKey = 'someverysecretkeythatisatleast32charslong'; <del> <ide> /** <ide> * Generate invalid cookie names. <ide> * <ide> public function testValidateNameEmptyName() <ide> new Cookie('', ''); <ide> } <ide> <del> /** <del> * Test decrypting the cookie <del> * <del> * @return void <del> */ <del> public function testDecrypt() <del> { <del> $value = 'cakephp-rocks-and-is-awesome'; <del> $cookie = new Cookie('cakephp', $value); <del> $cookie->encrypt($this->encryptionKey); <del> $this->assertTextStartsWith('Q2FrZQ==.', $cookie->getValue()); <del> $cookie->decrypt($this->encryptionKey); <del> $this->assertSame($value, $cookie->getValue()); <del> } <del> <del> /** <del> * Testing encrypting the cookie <del> * <del> * @return void <del> */ <del> public function testEncrypt() <del> { <del> $value = 'cakephp-rocks-and-is-awesome'; <del> <del> $cookie = new Cookie('cakephp', $value); <del> $cookie->encrypt($this->encryptionKey); <del> <del> $this->assertNotEquals($value, $cookie->getValue()); <del> $this->assertNotEmpty($cookie->getValue()); <del> } <del> <ide> /** <ide> * Tests the header value <ide> * <ide><path>tests/TestCase/Http/Cookie/RequestCookiesTest.php <del><?php <del>/** <del> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <del> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <del> * Licensed under The MIT License <del> * Redistributions of files must retain the above copyright notice. <del> * <del> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <del> * @link http://cakephp.org CakePHP(tm) Project <del> * @since 3.5.0 <del> * @license http://www.opensource.org/licenses/mit-license.php MIT License <del> */ <del>namespace Cake\Test\TestCase\Http\Cookie; <del> <del>use Cake\Http\Cookie\Cookie; <del>use Cake\Http\Cookie\RequestCookies; <del>use Cake\Http\ServerRequest; <del>use Cake\TestSuite\TestCase; <del> <del>/** <del> * HTTP cookies test. <del> */ <del>class RequestCookiesTest extends TestCase <del>{ <del> <del> /** <del> * Server Request <del> * <del> * @var \Cake\Http\ServerRequest <del> */ <del> public $request; <del> <del> /** <del> * @inheritDoc <del> */ <del> public function setUp() <del> { <del> $this->request = new ServerRequest([ <del> 'cookies' => [ <del> 'remember_me' => 'test', <del> 'something' => 'test2' <del> ] <del> ]); <del> } <del> <del> /** <del> * Test testCreateFromRequest <del> * <del> * @return null <del> */ <del> public function testCreateFromRequest() <del> { <del> $result = RequestCookies::createFromRequest($this->request); <del> $this->assertInstanceOf(RequestCookies::class, $result); <del> $this->assertInstanceOf(Cookie::class, $result->get('remember_me')); <del> $this->assertInstanceOf(Cookie::class, $result->get('something')); <del> <del> $this->assertTrue($result->has('remember_me')); <del> $this->assertTrue($result->has('something')); <del> $this->assertFalse($result->has('does-not-exist')); <del> } <del>} <ide><path>tests/TestCase/Http/Cookie/ResponseCookiesTest.php <del><?php <del>/** <del> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <del> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <del> * Licensed under The MIT License <del> * Redistributions of files must retain the above copyright notice. <del> * <del> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <del> * @link http://cakephp.org CakePHP(tm) Project <del> * @since 3.5.0 <del> * @license http://www.opensource.org/licenses/mit-license.php MIT License <del> */ <del>namespace Cake\Test\TestCase\Http\Cookie; <del> <del>use Cake\Http\Client\Response; <del>use Cake\Http\Cookie\Cookie; <del>use Cake\Http\Cookie\ResponseCookies; <del>use Cake\TestSuite\TestCase; <del> <del>/** <del> * Response Cookies Test <del> */ <del>class ResponseCookiesTest extends TestCase <del>{ <del> <del> /** <del> * testAddToResponse <del> * <del> * @return void <del> */ <del> public function testAddToResponse() <del> { <del> $cookies = [ <del> new Cookie('one', 'one'), <del> new Cookie('two', 'two') <del> ]; <del> <del> $responseCookies = new ResponseCookies($cookies); <del> <del> $response = new Response(); <del> $response = $responseCookies->addToResponse($response); <del> <del> $expected = [ <del> 'Set-Cookie' => [ <del> 'one=one', <del> 'two=two' <del> ] <del> ]; <del> $this->assertEquals($expected, $response->getHeaders()); <del> } <del>}
7
PHP
PHP
apply fixes from styleci
08f8ef951e3f54e43bb9829c47393e9975b0a9ff
<ide><path>src/Illuminate/Routing/Router.php <ide> public function __construct(Dispatcher $events, Container $container = null) <ide> public function head($uri, $action = null) <ide> { <ide> return $this->addRoute('HEAD', $uri, $action); <del> } <add> } <ide> <ide> /** <ide> * Register a new GET route with the router.
1
PHP
PHP
remove unneeded method existence check
5b40d09d0f4e29e3412fb90677f4819b81a42caa
<ide><path>src/Mailer/Email.php <ide> protected function _constructTransport($name) <ide> if (!$className) { <ide> throw new InvalidArgumentException(sprintf('Transport class "%s" not found.', $config['className'])); <ide> } <del> if (!method_exists($className, 'send')) { <del> throw new InvalidArgumentException(sprintf('The "%s" does not have a send() method.', $className)); <del> } <ide> <ide> unset($config['className']); <ide>
1
Ruby
Ruby
use class_eval with a string when it's possible
450f7cf01b855b536416fc048a92c4309da2492e
<ide><path>activemodel/lib/active_model/attribute_methods.rb <ide> def define_attr_method(name, value=nil, &block) <ide> if block_given? <ide> sing.send :define_method, name, &block <ide> else <del> value = value.to_s if value <del> sing.send(:define_method, name) { value } <add> if name =~ /^[a-zA-Z_]\w*[!?=]?$/ <add> sing.class_eval <<-eorb, __FILE__, __LINE__ + 1 <add> def #{name}; #{value.nil? ? 'nil' : value.to_s.inspect}; end <add> eorb <add> else <add> value = value.to_s if value <add> sing.send(:define_method, name) { value } <add> end <ide> end <ide> end <ide> <ide><path>activerecord/lib/active_record/attribute_methods/read.rb <ide> def define_read_method(symbol, attr_name, column) <ide> if cache_attribute?(attr_name) <ide> access_code = "@attributes_cache['#{attr_name}'] ||= (#{access_code})" <ide> end <del> generated_attribute_methods.module_eval do <del> define_method("_#{symbol}") { eval(access_code) } <del> alias_method(symbol, "_#{symbol}") <add> if symbol =~ /^[a-zA-Z_]\w*[!?=]?$/ <add> generated_attribute_methods.module_eval("def _#{symbol}; #{access_code}; end; alias #{symbol} _#{symbol}", __FILE__, __LINE__) <add> else <add> generated_attribute_methods.module_eval do <add> define_method("_#{symbol}") { eval(access_code) } <add> alias_method(symbol, "_#{symbol}") <add> end <ide> end <ide> end <ide> end <ide><path>activerecord/lib/active_record/attribute_methods/write.rb <ide> module Write <ide> module ClassMethods <ide> protected <ide> def define_method_attribute=(attr_name) <del> generated_attribute_methods.send(:define_method, "#{attr_name}=") do |new_value| <del> write_attribute(attr_name, new_value) <add> if attr_name =~ /^[a-zA-Z_]\w*[!?=]?$/ <add> generated_attribute_methods.module_eval("def #{attr_name}=(new_value); write_attribute('#{attr_name}', new_value); end", __FILE__, __LINE__) <add> else <add> generated_attribute_methods.send(:define_method, "#{attr_name}=") do |new_value| <add> write_attribute(attr_name, new_value) <add> end <ide> end <ide> end <ide> end
3
Ruby
Ruby
remove code duplication
a26dcb62714cfe1d23358c5753f9aad26c27fe29
<ide><path>actionpack/lib/action_view/helpers/date_helper.rb <ide> def select_year(date, options = {}, html_options = {}) <ide> # <time datetime="2010-11-04" pubdate="pubdate">November 04, 2010</time> <ide> # <ide> # <%= time_tag Time.now do %> <del> # <span>Right now</span> <add> # <span>Right now</span> <ide> # <% end %> <ide> # # => <time datetime="2010-11-04T17:55:45+01:00"><span>Right now</span></time> <ide> # <ide> def select_datetime <ide> @options[:discard_minute] ||= true if @options[:discard_hour] <ide> @options[:discard_second] ||= true unless @options[:include_seconds] && !@options[:discard_minute] <ide> <del> # If the day is hidden, the day should be set to the 1st so all month and year choices are valid. Otherwise, <del> # February 31st or February 29th, 2011 can be selected, which are invalid. <del> if @datetime && @options[:discard_day] <del> @datetime = @datetime.change(:day => 1) <del> end <add> set_day_if_discarded <ide> <ide> if @options[:tag] && @options[:ignore_date] <ide> select_time <ide> def select_date <ide> @options[:discard_month] ||= true unless order.include?(:month) <ide> @options[:discard_day] ||= true if @options[:discard_month] || !order.include?(:day) <ide> <del> # If the day is hidden, the day should be set to the 1st so all month and year choices are valid. Otherwise, <del> # February 31st or February 29th, 2011 can be selected, which are invalid. <del> if @datetime && @options[:discard_day] <del> @datetime = @datetime.change(:day => 1) <del> end <add> set_day_if_discarded <ide> <ide> [:day, :month, :year].each { |o| order.unshift(o) unless order.include?(o) } <ide> <ide> def select_year <ide> end <ide> end <ide> <add> # If the day is hidden, the day should be set to the 1st so all month and year choices are <add> # valid. Otherwise, February 31st or February 29th, 2011 can be selected, which are invalid. <add> def set_day_if_discarded <add> if @datetime && @options[:discard_day] <add> @datetime = @datetime.change(:day => 1) <add> end <add> end <add> <ide> # Returns translated month names, but also ensures that a custom month <ide> # name array has a leading nil element. <ide> def month_names
1
Java
Java
fix copyright dates
46a37b447c328cef6cc09ac839b985d7db133f75
<ide><path>spring-aop/src/main/java/org/springframework/aop/framework/AopProxyUtils.java <ide> /* <del> * Copyright 2002-2017 the original author or authors. <add> * Copyright 2002-2019 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-aop/src/main/java/org/springframework/aop/framework/ProxyFactoryBean.java <ide> /* <del> * Copyright 2002-2018 the original author or authors. <add> * Copyright 2002-2019 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-expression/src/main/java/org/springframework/expression/spel/standard/Tokenizer.java <ide> /* <del> * Copyright 2002-2018 the original author or authors. <add> * Copyright 2002-2019 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.
3
Text
Text
make contributing guide consistent about bug fixes
65d878a33e916d11724b6edf739af5082b817066
<ide><path>guides/source/contributing_to_ruby_on_rails.md <ide> For example, if you modify Active Storage's image analyzer to add a new metadata <ide> <ide> The CHANGELOG is an important part of every release. It keeps the list of changes for every Rails version. <ide> <del>You should add an entry **to the top** of the CHANGELOG of the framework you modified if you're adding or removing a feature, committing a bug fix, or adding deprecation notices. Refactorings and documentation changes generally should not go to the CHANGELOG. <add>You should add an entry **to the top** of the CHANGELOG of the framework you modified if you're adding or removing a feature, or adding deprecation notices. Refactorings, minor bug fixes, and documentation changes generally should not go to the CHANGELOG. <ide> <ide> A CHANGELOG entry should summarize what was changed and should end with the author's name. You can use multiple lines if you need more space, and you can attach code examples indented with 4 spaces. If a change is related to a specific issue, you should attach the issue's number. Here is an example CHANGELOG entry: <ide>
1
Python
Python
fix doc bug
985bba90961803c0f83dcb20d3139c0d4a9bcee3
<ide><path>src/transformers/file_utils.py <ide> def _prepare_output_docstrings(output_type, config_class): <ide> >>> import tensorflow as tf <ide> <ide> >>> tokenizer = {tokenizer_class}.from_pretrained('{checkpoint}') <del> >>> model = {model_class}.from_pretrained('{checkpoint}', return_dict=True)) <add> >>> model = {model_class}.from_pretrained('{checkpoint}', return_dict=True) <ide> <ide> >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="tf") <ide> >>> input_ids = inputs["input_ids"] <ide> def _prepare_output_docstrings(output_type, config_class): <ide> >>> import tensorflow as tf <ide> <ide> >>> tokenizer = {tokenizer_class}.from_pretrained('{checkpoint}') <del> >>> model = {model_class}.from_pretrained('{checkpoint}', return_dict=True)) <add> >>> model = {model_class}.from_pretrained('{checkpoint}', return_dict=True) <ide> <ide> >>> question, text = "Who was Jim Henson?", "Jim Henson was a nice puppet" <ide> >>> input_dict = tokenizer(question, text, return_tensors='tf') <ide> def _prepare_output_docstrings(output_type, config_class): <ide> >>> import tensorflow as tf <ide> <ide> >>> tokenizer = {tokenizer_class}.from_pretrained('{checkpoint}') <del> >>> model = {model_class}.from_pretrained('{checkpoint}', return_dict=True)) <add> >>> model = {model_class}.from_pretrained('{checkpoint}', return_dict=True) <ide> <ide> >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="tf") <ide> >>> inputs["labels"] = tf.reshape(tf.constant(1), (-1, 1)) # Batch size 1 <ide> def _prepare_output_docstrings(output_type, config_class): <ide> >>> import tensorflow as tf <ide> <ide> >>> tokenizer = {tokenizer_class}.from_pretrained('{checkpoint}') <del> >>> model = {model_class}.from_pretrained('{checkpoint}', return_dict=True)) <add> >>> model = {model_class}.from_pretrained('{checkpoint}', return_dict=True) <ide> <ide> >>> inputs = tokenizer("The capital of France is {mask}.", return_tensors="tf") <ide> >>> inputs["labels"] = tokenizer("The capital of France is Paris.", return_tensors="tf")["input_ids"] <ide> def _prepare_output_docstrings(output_type, config_class): <ide> >>> import tensorflow as tf <ide> <ide> >>> tokenizer = {tokenizer_class}.from_pretrained('{checkpoint}') <del> >>> model = {model_class}.from_pretrained('{checkpoint}', return_dict=True)) <add> >>> model = {model_class}.from_pretrained('{checkpoint}', return_dict=True) <ide> <ide> >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="tf") <ide> >>> outputs = model(inputs) <ide> def _prepare_output_docstrings(output_type, config_class): <ide> >>> import tensorflow as tf <ide> <ide> >>> tokenizer = {tokenizer_class}.from_pretrained('{checkpoint}') <del> >>> model = {model_class}.from_pretrained('{checkpoint}', return_dict=True)) <add> >>> model = {model_class}.from_pretrained('{checkpoint}', return_dict=True) <ide> <ide> >>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced." <ide> >>> choice0 = "It is eaten with a fork and a knife." <ide> def _prepare_output_docstrings(output_type, config_class): <ide> >>> import tensorflow as tf <ide> <ide> >>> tokenizer = {tokenizer_class}.from_pretrained('{checkpoint}') <del> >>> model = {model_class}.from_pretrained('{checkpoint}', return_dict=True)) <add> >>> model = {model_class}.from_pretrained('{checkpoint}', return_dict=True) <ide> <ide> >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="tf") <ide> >>> outputs = model(inputs)
1
Javascript
Javascript
call event.stoppropagation in the click handler "
15ff8f7242cc908717ccf730c239157bdd4ed1f9
<ide><path>src/js/control-bar/play-toggle.js <ide> class PlayToggle extends Button { <ide> } else { <ide> this.player_.pause(); <ide> } <del> event.stopPropagation(); <ide> } <ide> <ide> /**
1
Ruby
Ruby
move x11 check
71f9d74adf93dc8294c345f13036a1bb817ba06a
<ide><path>Library/Homebrew/brew_doctor.rb <ide> def check_for_stray_dylibs <ide> end <ide> end <ide> <add>def check_for_x11 <add> unless File.exists? '/usr/X11/lib/libpng.dylib' <add> puts "You don't have X11 installed as part of your Xcode installation." <add> puts "This isn't required for all formula. But it is expected by some." <add> end <add>end <add> <ide> def brew_doctor <ide> read, write = IO.pipe <ide> <ide> def brew_doctor <ide> puts <ide> end <ide> <del> unless File.exists? '/usr/X11/lib/libpng.dylib' <del> puts "You don't have X11 installed as part of your Xcode installation." <del> puts "This isn't required for all formula. But it is expected by some." <del> end <add> check_for_x11 <ide> <ide> exit! 0 <ide> else
1
Javascript
Javascript
expose asset content
1f8d1002ef991b66f4cac8d8b8689f27a244ac4d
<ide><path>Libraries/Image/AssetRegistry.js <ide> <ide> <ide> export type PackagerAsset = { <del> __packager_asset: boolean, <del> fileSystemLocation: string, <del> httpServerLocation: string, <del> width: number, <del> height: number, <del> scales: Array<number>, <del> hash: string, <del> name: string, <del> type: string, <add> +__packager_asset: boolean, <add> +fileSystemLocation: string, <add> +httpServerLocation: string, <add> +width: ?number, <add> +height: ?number, <add> +scales: Array<number>, <add> +hash: string, <add> +name: string, <add> +type: string, <ide> }; <ide> <ide> <ide><path>Libraries/Image/AssetSourceResolver.js <ide> <ide> export type ResolvedAssetSource = { <ide> __packager_asset: boolean, <del> width: number, <del> height: number, <add> width: ?number, <add> height: ?number, <ide> uri: string, <ide> scale: number, <ide> }; <ide><path>local-cli/bundle/getAssetDestPathAndroid.js <ide> * This source code is licensed under the BSD-style license found in the <ide> * LICENSE file in the root directory of this source tree. An additional grant <ide> * of patent rights can be found in the PATENTS file in the same directory. <add> * <add> * @flow <ide> */ <add> <ide> 'use strict'; <ide> <ide> const assetPathUtils = require('./assetPathUtils'); <ide> const path = require('path'); <ide> <del>function getAssetDestPathAndroid(asset, scale) { <add>import type {PackagerAsset} from '../../Libraries/Image/AssetRegistry'; <add> <add>function getAssetDestPathAndroid(asset: PackagerAsset, scale: number): string { <ide> const androidFolder = assetPathUtils.getAndroidDrawableFolderName(asset, scale); <ide> const fileName = assetPathUtils.getAndroidResourceIdentifier(asset); <ide> return path.join(androidFolder, fileName + '.' + asset.type); <ide><path>local-cli/bundle/getAssetDestPathIOS.js <ide> * This source code is licensed under the BSD-style license found in the <ide> * LICENSE file in the root directory of this source tree. An additional grant <ide> * of patent rights can be found in the PATENTS file in the same directory. <add> * <add> * @flow <ide> */ <add> <ide> 'use strict'; <ide> <ide> const path = require('path'); <ide> <del>function getAssetDestPathIOS(asset, scale) { <add>import type {PackagerAsset} from '../../Libraries/Image/AssetRegistry'; <add> <add>function getAssetDestPathIOS(asset: PackagerAsset, scale: number): string { <ide> const suffix = scale === 1 ? '' : '@' + scale + 'x'; <ide> const fileName = asset.name + suffix + '.' + asset.type; <ide> return path.join(asset.httpServerLocation.substr(1), fileName); <ide><path>packager/src/Bundler/index.js <ide> export type GetTransformOptions = ( <ide> getDependenciesOf: string => Promise<Array<string>>, <ide> ) => Promise<ExtraTransformOptions>; <ide> <del>type AssetDescriptor = { <add>export type AssetDescriptor = { <ide> +__packager_asset: boolean, <ide> +httpServerLocation: string, <ide> +width: ?number, <ide> type AssetDescriptor = { <ide> +type: string, <ide> }; <ide> <del>type ExtendedAssetDescriptor = AssetDescriptor & { <add>export type ExtendedAssetDescriptor = AssetDescriptor & { <ide> +fileSystemLocation: string, <ide> +files: Array<string>, <ide> }; <ide><path>packager/src/ModuleGraph/types.flow.js <ide> export type LibraryOptions = {| <ide> platform?: string, <ide> root: string, <ide> |}; <add> <add>export type Base64Content = string; <add> <add>export type Library = {| <add> files: Array<TransformedFile>, <add> /* cannot be a Map because it's JSONified later on */ <add> assets: {[destFilePath: string]: Base64Content}, <add>|};
6
Java
Java
update @since tag due to backport
5b96c9b87e0744ef4011cec403f5470ce017315e
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/method/annotation/ModelAttributeMethodArgumentResolver.java <ide> public Mono<Object> resolveArgument( <ide> /** <ide> * Determine if binding should be disabled for the supplied {@link MethodParameter}, <ide> * based on the {@link ModelAttribute#binding} annotation attribute. <del> * @since 5.3.7 <add> * @since 5.2.15 <ide> */ <ide> private boolean bindingDisabled(MethodParameter parameter) { <ide> ModelAttribute modelAttribute = parameter.getParameterAnnotation(ModelAttribute.class);
1
Python
Python
allow project specific config files in keras
50411ccb0e7059ad2bd9286b64ffc2cda8957025
<ide><path>keras/backend/__init__.py <ide> from .common import image_data_format <ide> from .common import set_image_data_format <ide> <del># Obtain Keras base dir path: either ~/.keras or /tmp. <del>_keras_base_dir = os.path.expanduser('~') <del>if not os.access(_keras_base_dir, os.W_OK): <del> _keras_base_dir = '/tmp' <del>_keras_dir = os.path.join(_keras_base_dir, '.keras') <add># Set Keras base dir path given KERAS_HOME env variable, if applicable. <add># Otherwise either ~/.keras or /tmp. <add>if 'KERAS_HOME' in os.environ: <add> _keras_dir = os.environ.get('KERAS_HOME') <add>else: <add> _keras_base_dir = os.path.expanduser('~') <add> if not os.access(_keras_base_dir, os.W_OK): <add> _keras_base_dir = '/tmp' <add> _keras_dir = os.path.join(_keras_base_dir, '.keras') <ide> <ide> # Default backend: TensorFlow. <ide> _BACKEND = 'tensorflow'
1
Javascript
Javascript
replace var with let/const
ecfebee90f9ee900b1dac60b30624ed5e4dff665
<ide><path>lib/internal/process/stdio.js <ide> function dummyDestroy(err, cb) { <ide> } <ide> <ide> function getMainThreadStdio() { <del> var stdin; <del> var stdout; <del> var stderr; <add> let stdin; <add> let stdout; <add> let stderr; <ide> <ide> function getStdout() { <ide> if (stdout) return stdout; <ide> function getMainThreadStdio() { <ide> <ide> switch (guessHandleType(fd)) { <ide> case 'TTY': <del> var tty = require('tty'); <add> const tty = require('tty'); <ide> stdin = new tty.ReadStream(fd, { <ide> highWaterMark: 0, <ide> readable: true, <ide> function getMainThreadStdio() { <ide> break; <ide> <ide> case 'FILE': <del> var fs = require('fs'); <add> const fs = require('fs'); <ide> stdin = new fs.ReadStream(null, { fd: fd, autoClose: false }); <ide> break; <ide> <ide> case 'PIPE': <ide> case 'TCP': <del> var net = require('net'); <add> const net = require('net'); <ide> <ide> // It could be that process has been started with an IPC channel <ide> // sitting on fd=0, in such case the pipe for this fd is already <ide> function getMainThreadStdio() { <ide> } <ide> <ide> function createWritableStdioStream(fd) { <del> var stream; <add> let stream; <ide> // Note stream._type is used for test-module-load-list.js <ide> switch (guessHandleType(fd)) { <ide> case 'TTY': <del> var tty = require('tty'); <add> const tty = require('tty'); <ide> stream = new tty.WriteStream(fd); <ide> stream._type = 'tty'; <ide> break; <ide> function createWritableStdioStream(fd) { <ide> <ide> case 'PIPE': <ide> case 'TCP': <del> var net = require('net'); <add> const net = require('net'); <ide> <ide> // If fd is already being used for the IPC channel, libuv will return <ide> // an error when trying to use it again. In that case, create the socket
1
PHP
PHP
add stackframe information to deprecation message
65c6e1c91e339da6eda7fd927b0e7a824af1b86f
<ide><path>src/Core/functions.php <ide> function env($key, $default = null) <ide> * Helper method for outputting deprecation warnings <ide> * <ide> * @param string $message The message to output as a deprecation warning. <add> * @param int $stackFrame The stack frame to include in the error. Defaults to 2 <add> * as that should point to application/plugin code. <ide> * @return void <ide> */ <del> function deprecationWarning($message) <add> function deprecationWarning($message, $stackFrame = 2) <ide> { <add> if (!Configure::read('debug')) { <add> return; <add> } <add> $trace = debug_backtrace(); <add> if (isset($trace[$stackFrame])) { <add> $frame = $trace[$stackFrame]; <add> $frame += ['file' => '[internal]', 'line' => '??']; <add> <add> $message = sprintf( <add> '%s - %s, line: %s', <add> $message, <add> $frame['file'], <add> $frame['line'] <add> ); <add> } <add> <ide> trigger_error($message, E_USER_DEPRECATED); <ide> } <ide> } <ide><path>tests/TestCase/Core/FunctionsTest.php <ide> */ <ide> namespace Cake\Test\TestCase\Core; <ide> <add>use Cake\Core\Configure; <ide> use Cake\TestSuite\TestCase; <ide> <ide> /** <ide> public function testEnv() <ide> } <ide> <ide> /** <add> * Test error messages coming out when debug is on <add> * <ide> * @expectedException PHPUnit\Framework\Error\Deprecated <del> * @expectedExceptionMessage This is going away <add> * @expectedExceptionMessage This is going away - [internal], line: ?? <ide> */ <del> public function testDeprecationWarning() <add> public function testDeprecationWarningDebugEnabled() <ide> { <add> Configure::write('debug', true); <add> error_reporting(E_ALL); <add> deprecationWarning('This is going away', 1); <add> } <add> <add> /** <add> * Test error messages coming out when debug is on <add> * <add> * @expectedException PHPUnit\Framework\Error\Deprecated <add> * @expectedExceptionMessageRegExp /This is going away - (.*?)\/TestCase.php, line\: \d+/ <add> */ <add> public function testDeprecationWarningDebugEnabledDefaultFrame() <add> { <add> Configure::write('debug', true); <ide> error_reporting(E_ALL); <ide> deprecationWarning('This is going away'); <ide> } <add> <add> /** <add> * Test no error when debug is off. <add> * <add> * @return void <add> */ <add> public function testDeprecationWarningDebugDisabled() <add> { <add> Configure::write('debug', false); <add> error_reporting(E_ALL); <add> $this->assertNull(deprecationWarning('This is going away')); <add> } <ide> }
2
Javascript
Javascript
support press reentry for pointer events
339366c461acca41d12ce15264181bc94aaa0eb4
<ide><path>packages/react-events/src/Press.js <ide> type PressState = { <ide> top: number, <ide> |}>, <ide> ignoreEmulatedMouseEvents: boolean, <add> allowPressReentry: boolean, <ide> }; <ide> <ide> type PressEventType = <ide> function dispatchPressEndEvents( <ide> deactivate(context, props, state); <ide> } <ide> } <del> removeRootEventTypes(context, state); <ide> } <ide> <ide> function isAnchorTagElement(eventTarget: EventTarget): boolean { <ide> function unmountResponder( <ide> state: PressState, <ide> ): void { <ide> if (state.isPressed) { <add> removeRootEventTypes(context, state); <ide> dispatchPressEndEvents(context, props, state); <ide> } <ide> } <ide> function dispatchCancel( <ide> (nativeEvent: any).preventDefault(); <ide> } else { <ide> state.ignoreEmulatedMouseEvents = false; <add> removeRootEventTypes(context, state); <ide> dispatchPressEndEvents(context, props, state); <ide> } <add> } else if (state.allowPressReentry) { <add> removeRootEventTypes(context, state); <ide> } <ide> } <ide> <ide> function removeRootEventTypes( <ide> ): void { <ide> if (state.addedRootEvents) { <ide> state.addedRootEvents = false; <add> state.allowPressReentry = false; <ide> context.removeRootEventTypes(rootEventTypes); <ide> } <ide> } <ide> const PressResponder = { <ide> responderRegionOnActivation: null, <ide> responderRegionOnDeactivation: null, <ide> ignoreEmulatedMouseEvents: false, <add> allowPressReentry: false, <ide> }; <ide> }, <ide> stopLocalPropagation: true, <ide> const PressResponder = { <ide> const {target, type} = event; <ide> <ide> if (props.disabled) { <add> removeRootEventTypes(context, state); <ide> dispatchPressEndEvents(context, props, state); <ide> state.ignoreEmulatedMouseEvents = false; <ide> return; <ide> const PressResponder = { <ide> return; <ide> } <ide> <add> state.allowPressReentry = true; <ide> state.pointerType = pointerType; <ide> state.pressTarget = getEventCurrentTarget(event, context); <ide> state.responderRegionOnActivation = calculateResponderRegion( <ide> const PressResponder = { <ide> case 'pointermove': <ide> case 'mousemove': <ide> case 'touchmove': { <del> if (state.isPressed) { <add> if (state.isPressed || state.allowPressReentry) { <ide> // Ignore emulated events (pointermove will dispatch touch and mouse events) <ide> // Ignore pointermove events during a keyboard press. <ide> if (state.pointerType !== pointerType) { <ide> const PressResponder = { <ide> ); <ide> <ide> if (state.isPressWithinResponderRegion) { <del> if (props.onPressMove) { <del> dispatchEvent(context, state, 'pressmove', props.onPressMove, { <del> discrete: false, <del> }); <add> if (state.isPressed) { <add> if (props.onPressMove) { <add> dispatchEvent(context, state, 'pressmove', props.onPressMove, { <add> discrete: false, <add> }); <add> } <add> } else { <add> dispatchPressStartEvents(context, props, state); <ide> } <ide> } else { <add> if (!state.allowPressReentry) { <add> removeRootEventTypes(context, state); <add> } <ide> dispatchPressEndEvents(context, props, state); <ide> } <ide> } <ide> break; <ide> } <del> <ide> // END <ide> case 'pointerup': <ide> case 'keyup': <ide> const PressResponder = { <ide> } <ide> <ide> const wasLongPressed = state.isLongPressed; <add> removeRootEventTypes(context, state); <ide> dispatchPressEndEvents(context, props, state); <ide> <ide> if (state.pressTarget !== null && props.onPress) { <ide> const PressResponder = { <ide> } <ide> } else if (type === 'mouseup' && state.ignoreEmulatedMouseEvents) { <ide> state.ignoreEmulatedMouseEvents = false; <add> } else if (state.allowPressReentry) { <add> removeRootEventTypes(context, state); <ide> } <ide> break; <ide> } <ide><path>packages/react-events/src/__tests__/Press-test.internal.js <ide> describe('Event responder: Press', () => { <ide> expect(events).toEqual([]); <ide> }); <ide> }); <add> <add> it('"onPress" is not called on release with mouse', () => { <add> let events = []; <add> const ref = React.createRef(); <add> const createEventHandler = msg => () => { <add> events.push(msg); <add> }; <add> <add> const element = ( <add> <Press <add> onPress={createEventHandler('onPress')} <add> onPressChange={createEventHandler('onPressChange')} <add> onPressMove={createEventHandler('onPressMove')} <add> onPressStart={createEventHandler('onPressStart')} <add> onPressEnd={createEventHandler('onPressEnd')}> <add> <div ref={ref} /> <add> </Press> <add> ); <add> <add> ReactDOM.render(element, container); <add> <add> ref.current.getBoundingClientRect = getBoundingClientRectMock; <add> ref.current.dispatchEvent( <add> createPointerEvent('pointerdown', { <add> pointerType: 'mouse', <add> }), <add> ); <add> ref.current.dispatchEvent( <add> createPointerEvent('pointermove', { <add> ...coordinatesInside, <add> pointerType: 'mouse', <add> }), <add> ); <add> container.dispatchEvent( <add> createPointerEvent('pointermove', { <add> ...coordinatesOutside, <add> pointerType: 'mouse', <add> }), <add> ); <add> container.dispatchEvent( <add> createPointerEvent('pointerup', { <add> ...coordinatesOutside, <add> pointerType: 'mouse', <add> }), <add> ); <add> jest.runAllTimers(); <add> <add> expect(events).toEqual([ <add> 'onPressStart', <add> 'onPressChange', <add> 'onPressMove', <add> 'onPressEnd', <add> 'onPressChange', <add> ]); <add> }); <add> <add> it('"onPress" is called on re-entry to hit rect for mouse', () => { <add> let events = []; <add> const ref = React.createRef(); <add> const createEventHandler = msg => () => { <add> events.push(msg); <add> }; <add> <add> const element = ( <add> <Press <add> onPress={createEventHandler('onPress')} <add> onPressChange={createEventHandler('onPressChange')} <add> onPressMove={createEventHandler('onPressMove')} <add> onPressStart={createEventHandler('onPressStart')} <add> onPressEnd={createEventHandler('onPressEnd')}> <add> <div ref={ref} /> <add> </Press> <add> ); <add> <add> ReactDOM.render(element, container); <add> <add> ref.current.getBoundingClientRect = getBoundingClientRectMock; <add> ref.current.dispatchEvent( <add> createPointerEvent('pointerdown', { <add> pointerType: 'mouse', <add> }), <add> ); <add> ref.current.dispatchEvent( <add> createPointerEvent('pointermove', { <add> ...coordinatesInside, <add> pointerType: 'mouse', <add> }), <add> ); <add> container.dispatchEvent( <add> createPointerEvent('pointermove', { <add> ...coordinatesOutside, <add> pointerType: 'mouse', <add> }), <add> ); <add> container.dispatchEvent( <add> createPointerEvent('pointermove', { <add> ...coordinatesInside, <add> pointerType: 'mouse', <add> }), <add> ); <add> container.dispatchEvent( <add> createPointerEvent('pointerup', { <add> ...coordinatesInside, <add> pointerType: 'mouse', <add> }), <add> ); <add> jest.runAllTimers(); <add> <add> expect(events).toEqual([ <add> 'onPressStart', <add> 'onPressChange', <add> 'onPressMove', <add> 'onPressEnd', <add> 'onPressChange', <add> 'onPressStart', <add> 'onPressChange', <add> 'onPressEnd', <add> 'onPressChange', <add> 'onPress', <add> ]); <add> }); <add> <add> it('"onPress" is called on re-entry to hit rect for touch', () => { <add> let events = []; <add> const ref = React.createRef(); <add> const createEventHandler = msg => () => { <add> events.push(msg); <add> }; <add> <add> const element = ( <add> <Press <add> onPress={createEventHandler('onPress')} <add> onPressChange={createEventHandler('onPressChange')} <add> onPressMove={createEventHandler('onPressMove')} <add> onPressStart={createEventHandler('onPressStart')} <add> onPressEnd={createEventHandler('onPressEnd')}> <add> <div ref={ref} /> <add> </Press> <add> ); <add> <add> ReactDOM.render(element, container); <add> <add> ref.current.getBoundingClientRect = getBoundingClientRectMock; <add> ref.current.dispatchEvent( <add> createPointerEvent('pointerdown', { <add> pointerType: 'touch', <add> }), <add> ); <add> ref.current.dispatchEvent( <add> createPointerEvent('pointermove', { <add> ...coordinatesInside, <add> pointerType: 'touch', <add> }), <add> ); <add> container.dispatchEvent( <add> createPointerEvent('pointermove', { <add> ...coordinatesOutside, <add> pointerType: 'touch', <add> }), <add> ); <add> container.dispatchEvent( <add> createPointerEvent('pointermove', { <add> ...coordinatesInside, <add> pointerType: 'touch', <add> }), <add> ); <add> container.dispatchEvent( <add> createPointerEvent('pointerup', { <add> ...coordinatesInside, <add> pointerType: 'touch', <add> }), <add> ); <add> jest.runAllTimers(); <add> <add> expect(events).toEqual([ <add> 'onPressStart', <add> 'onPressChange', <add> 'onPressMove', <add> 'onPressEnd', <add> 'onPressChange', <add> 'onPressStart', <add> 'onPressChange', <add> 'onPressEnd', <add> 'onPressChange', <add> 'onPress', <add> ]); <add> }); <ide> }); <ide> <ide> describe('delayed and multiple events', () => {
2
Python
Python
fix svn revision parsing under win32
5032b52732b2e8e6d60be09646d65bf0051a3161
<ide><path>setup.py <ide> def svn_version(): <ide> def _minimal_ext_cmd(cmd): <ide> # construct minimal environment <ide> env = {} <del> path = os.environ.get('PATH') <del> if path is not None: <del> env['PATH'] = path <add> for k in ['SYSTEMROOT', 'PATH']: <add> v = os.environ.get(k) <add> if v is not None: <add> env[k] = v <ide> # LANGUAGE is used on win32 <ide> env['LANGUAGE'] = 'C' <ide> env['LANG'] = 'C'
1
Python
Python
fix mypy errors for apache druid provider.
64a902d3e006e2ecec4c882184a71a09b10243fa
<ide><path>airflow/providers/apache/druid/hooks/druid.py <ide> # under the License. <ide> <ide> import time <del>from typing import Any, Dict, Iterable, Optional, Tuple <add>from typing import Any, Dict, Iterable, Optional, Tuple, Union <ide> <ide> import requests <ide> from pydruid.db import connect <ide> def get_auth(self) -> Optional[requests.auth.HTTPBasicAuth]: <ide> else: <ide> return None <ide> <del> def submit_indexing_job(self, json_index_spec: Dict[str, Any]) -> None: <add> def submit_indexing_job(self, json_index_spec: Union[Dict[str, Any], str]) -> None: <ide> """Submit Druid ingestion job""" <ide> url = self.get_conn_url() <ide> <ide> def get_uri(self) -> str: <ide> endpoint = conn.extra_dejson.get('endpoint', 'druid/v2/sql') <ide> return f'{conn_type}://{host}/{endpoint}' <ide> <del> def set_autocommit(self, conn: connect, autocommit: bool) -> NotImplemented: <add> def set_autocommit(self, conn: connect, autocommit: bool) -> NotImplementedError: <ide> raise NotImplementedError() <ide> <ide> def insert_rows( <ide> def insert_rows( <ide> commit_every: int = 1000, <ide> replace: bool = False, <ide> **kwargs: Any, <del> ) -> NotImplemented: <add> ) -> NotImplementedError: <ide> raise NotImplementedError()
1
Ruby
Ruby
use keg#uninstall to clean up kegs
def6b1eaf74cab3be2c807ca5609df3fa98bb8c9
<ide><path>Library/Homebrew/cmd/cleanup.rb <ide> def cleanup_keg keg <ide> puts "Would remove: #{keg}" <ide> else <ide> puts "Removing: #{keg}..." <del> keg.rmtree <add> keg.uninstall <ide> end <ide> end <ide>
1
Ruby
Ruby
use more semantic method to check password
a928928c9668f02735707b4e6edf2632fe191814
<ide><path>activemodel/lib/active_model/secure_password.rb <ide> module InstanceMethodsOnActivation <ide> # user.authenticate('notright') # => false <ide> # user.authenticate('mUc3m00RsqyRe') # => user <ide> def authenticate(unencrypted_password) <del> BCrypt::Password.new(password_digest) == unencrypted_password && self <add> BCrypt::Password.new(password_digest).is_password?(unencrypted_password) && self <ide> end <ide> <ide> attr_reader :password
1
Javascript
Javascript
generate a warning when using a not defined rule
c66b4b6a133f7215d50c23db516986cfc1f0a985
<ide><path>src/ng/directive/ngPluralize.js <ide> * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder <ide> * for <span ng-non-bindable>{{numberExpression}}</span>. <ide> * <add> * If no rule is defined for a category, then an empty string is displayed and a warning is generated. <add> * Note that some locales define more categories than `one` and `other`. For example, fr-fr defines `few` and `many`. <add> * <ide> * # Configuring ngPluralize with offset <ide> * The `offset` attribute allows further customization of pluralized text, which can result in <ide> * a better user experience. For example, instead of the message "4 people are viewing this document", <ide> </file> <ide> </example> <ide> */ <del>var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interpolate) { <add>var ngPluralizeDirective = ['$locale', '$interpolate', '$log', function($locale, $interpolate, $log) { <ide> var BRACE = /{}/g, <ide> IS_WHEN = /^when(Minus)?(.+)$/; <ide> <ide> var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interp <ide> // In JS `NaN !== NaN`, so we have to exlicitly check. <ide> if ((count !== lastCount) && !(countIsNaN && isNaN(lastCount))) { <ide> watchRemover(); <del> watchRemover = scope.$watch(whensExpFns[count], updateElementText); <add> var whenExpFn = whensExpFns[count]; <add> if (isUndefined(whenExpFn)) { <add> $log.debug("ngPluralize: no rule defined for '" + count + "' in " + whenExp); <add> watchRemover = noop; <add> updateElementText(); <add> } else { <add> watchRemover = scope.$watch(whenExpFn, updateElementText); <add> } <ide> lastCount = count; <ide> } <ide> }); <ide><path>test/ng/directive/ngPluralizeSpec.js <ide> describe('ngPluralize', function() { <ide> })); <ide> }); <ide> <add> describe('undefined rule cases', function() { <add> var $locale, $log; <add> beforeEach(inject(function(_$locale_, _$log_) { <add> $locale = _$locale_; <add> $log = _$log_; <add> })); <add> afterEach(inject(function($log) { <add> $log.reset(); <add> })); <add> <add> it('should generate a warning when being asked to use a rule that is not defined', <add> inject(function($rootScope, $compile) { <add> element = $compile( <add> '<ng:pluralize count="email"' + <add> "when=\"{'0': 'Zero'," + <add> "'one': 'Some text'," + <add> "'other': 'Some text'}\">" + <add> '</ng:pluralize>')($rootScope); <add> $locale.pluralCat = function() {return "few";}; <add> <add> $rootScope.email = '3'; <add> expect($log.debug.logs).toEqual([]); <add> $rootScope.$digest(); <add> expect(element.text()).toBe(''); <add> expect($log.debug.logs.shift()) <add> .toEqual(["ngPluralize: no rule defined for 'few' in {'0': 'Zero','one': 'Some text','other': 'Some text'}"]); <add> })); <add> <add> it('should empty the element content when using a rule that is not defined', <add> inject(function($rootScope, $compile) { <add> element = $compile( <add> '<ng:pluralize count="email"' + <add> "when=\"{'0': 'Zero'," + <add> "'one': 'Some text'," + <add> "'other': 'Some text'}\">" + <add> '</ng:pluralize>')($rootScope); <add> $locale.pluralCat = function(count) {return count === 1 ? "one" : "few";}; <add> <add> $rootScope.email = '0'; <add> $rootScope.$digest(); <add> expect(element.text()).toBe('Zero'); <add> <add> $rootScope.email = '3'; <add> $rootScope.$digest(); <add> expect(element.text()).toBe(''); <add> <add> $rootScope.email = '1'; <add> $rootScope.$digest(); <add> expect(element.text()).toBe('Some text'); <add> })); <add> }); <ide> <ide> describe('deal with pluralized strings with offset', function() { <ide> it('should show single/plural strings with offset', inject(function($rootScope, $compile) {
2
Text
Text
add backticks [ci skip]
72e1c4229ab0af6a76c1635adff76fc02fa7fe71
<ide><path>activerecord/CHANGELOG.md <ide> <ide> *Eugene Kenny* <ide> <del>* Prevent errors raised by sql.active_record notification subscribers from being converted into <del> ActiveRecord::StatementInvalid exceptions. <add>* Prevent errors raised by `sql.active_record` notification subscribers from being converted into <add> `ActiveRecord::StatementInvalid` exceptions. <ide> <ide> *Dennis Taylor* <ide>
1
Javascript
Javascript
improve raf logic
708764f47b0c8de152bbb444d0f608db558b76ed
<ide><path>src/effects.js <ide> function raf() { <ide> } <ide> } <ide> <del>// Will get false negative for old browsers which is okay <del>function isDocumentHidden() { <del> return "hidden" in document && document.hidden; <del>} <del> <ide> // Animations created synchronously will run synchronously <ide> function createFxNow() { <ide> setTimeout(function() { <ide> jQuery.speed = function( speed, easing, fn ) { <ide> easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing <ide> }; <ide> <del> opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : <del> opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; <add> // Go to the end state if fx are off or if document is hidden <add> if ( jQuery.fx.off || document.hidden ) { <add> opt.duration = 0; <add> <add> } else { <add> opt.duration = typeof opt.duration === "number" ? <add> opt.duration : opt.duration in jQuery.fx.speeds ? <add> jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; <add> } <ide> <ide> // Normalize opt.queue - true/undefined/null -> "fx" <ide> if ( opt.queue == null || opt.queue === true ) { <ide> jQuery.speed = function( speed, easing, fn ) { <ide> <ide> jQuery.fn.extend({ <ide> fadeTo: function( speed, to, easing, callback ) { <del> if ( isDocumentHidden() ) { <del> return this; <del> } <ide> <ide> // Show any hidden elements after setting opacity to 0 <ide> return this.filter( isHidden ).css( "opacity", 0 ).show() <ide> jQuery.fn.extend({ <ide> .end().animate({ opacity: to }, speed, easing, callback ); <ide> }, <ide> animate: function( prop, speed, easing, callback ) { <del> if ( isDocumentHidden() ) { <del> return this; <del> } <del> <ide> var empty = jQuery.isEmptyObject( prop ), <ide> optall = jQuery.speed( speed, easing, callback ), <ide> doAnimation = function() { <ide> jQuery.fx.timer = function( timer ) { <ide> jQuery.fx.interval = 13; <ide> jQuery.fx.start = function() { <ide> if ( !timerId ) { <del> if ( window.requestAnimationFrame ) { <del> timerId = true; <del> window.requestAnimationFrame( raf ); <del> } else { <del> timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); <del> } <add> timerId = window.requestAnimationFrame ? <add> window.requestAnimationFrame( raf ) : <add> setInterval( jQuery.fx.tick, jQuery.fx.interval ); <ide> } <ide> }; <ide> <ide> jQuery.fx.stop = function() { <del> clearInterval( timerId ); <add> if ( window.cancelAnimationFrame ) { <add> window.cancelAnimationFrame( timerId ); <add> } else { <add> clearInterval( timerId ); <add> } <add> <ide> timerId = null; <ide> }; <ide> <ide><path>test/unit/effects.js <ide> test( "Respect display value on inline elements (#14824)", 2, function() { <ide> clock.tick( 800 ); <ide> }); <ide> <add>test( "Animation should go to its end state if document.hidden = true", 1, function() { <add> var height; <add> if ( Object.defineProperty ) { <add> <add> // Can't rewrite document.hidden property if its host property <add> try { <add> Object.defineProperty( document, "hidden", { <add> get: function() { <add> return true; <add> } <add> }); <add> } catch ( e ) {} <add> } else { <add> document.hidden = true; <add> } <add> <add> if ( document.hidden ) { <add> height = jQuery( "#qunit-fixture" ).animate({ height: 500 } ).height(); <add> <add> equal( height, 500, "Animation should happen immediately if document.hidden = true" ); <add> jQuery( document ).removeProp( "hidden" ); <add> <add> } else { <add> ok( true, "Can't run the test since we can't reproduce correct environment for it" ); <add> } <add>}); <add> <add> <ide> })();
2
Go
Go
add more women
7808886744595af509b7b144890900674ea5ccfd
<ide><path>pkg/namesgenerator/names-generator.go <ide> var ( <ide> // Docker 0.7.x generates names from notable scientists and hackers. <ide> // <ide> // Ada Lovelace invented the first algorithm. http://en.wikipedia.org/wiki/Ada_Lovelace (thanks James Turnbull) <add> // Ada Yonath - an Israeli crystallographer, the first woman from the Middle East to win a Nobel prize in the sciences. http://en.wikipedia.org/wiki/Ada_Yonath <add> // Adele Goldstine, born Adele Katz, wrote the complete technical description for the first electronic digital computer, ENIAC. http://en.wikipedia.org/wiki/Adele_Goldstine <ide> // Alan Turing was a founding father of computer science. http://en.wikipedia.org/wiki/Alan_Turing. <ide> // Albert Einstein invented the general theory of relativity. http://en.wikipedia.org/wiki/Albert_Einstein <ide> // Ambroise Pare invented modern surgery. http://en.wikipedia.org/wiki/Ambroise_Par%C3%A9 <ide> // Archimedes was a physicist, engineer and mathematician who invented too many things to list them here. http://en.wikipedia.org/wiki/Archimedes <add> // Barbara McClintock - a distinguished American cytogeneticist, 1983 Nobel Laureate in Physiology or Medicine for discovering transposons. http://en.wikipedia.org/wiki/Barbara_McClintock <ide> // Benjamin Franklin is famous for his experiments in electricity and the invention of the lightning rod. <ide> // Charles Babbage invented the concept of a programmable computer. http://en.wikipedia.org/wiki/Charles_Babbage. <ide> // Charles Darwin established the principles of natural evolution. http://en.wikipedia.org/wiki/Charles_Darwin. <ide> // Dennis Ritchie and Ken Thompson created UNIX and the C programming language. http://en.wikipedia.org/wiki/Dennis_Ritchie http://en.wikipedia.org/wiki/Ken_Thompson <ide> // Douglas Engelbart gave the mother of all demos: http://en.wikipedia.org/wiki/Douglas_Engelbart <add> // Elizabeth Blackwell - American doctor and first American woman to receive a medical degree - http://en.wikipedia.org/wiki/Elizabeth_Blackwell <ide> // Emmett Brown invented time travel. http://en.wikipedia.org/wiki/Emmett_Brown (thanks Brian Goff) <ide> // Enrico Fermi invented the first nuclear reactor. http://en.wikipedia.org/wiki/Enrico_Fermi. <add> // Erna Schneider Hoover revolutionized modern communication by inventing a computerized telephon switching method. http://en.wikipedia.org/wiki/Erna_Schneider_Hoover <ide> // Euclid invented geometry. http://en.wikipedia.org/wiki/Euclid <add> // Françoise Barré-Sinoussi - French virologist and Nobel Prize Laureate in Physiology or Medicine; her work was fundamental in identifying HIV as the cause of AIDS. http://en.wikipedia.org/wiki/Fran%C3%A7oise_Barr%C3%A9-Sinoussi <ide> // Galileo was a founding father of modern astronomy, and faced politics and obscurantism to establish scientific truth. http://en.wikipedia.org/wiki/Galileo_Galilei <add> // Gertrude Elion - American biochemist, pharmacologist and the 1988 recipient of the Nobel Prize in Medicine - http://en.wikipedia.org/wiki/Gertrude_Elion <add> // Grace Hopper developed the first compiler for a computer programming language and is credited with popularizing the term "debugging" for fixing computer glitches. http://en.wikipedia.org/wiki/Grace_Hopper <ide> // Henry Poincare made fundamental contributions in several fields of mathematics. http://en.wikipedia.org/wiki/Henri_Poincar%C3%A9 <add> // Hypatia - Greek Alexandrine Neoplatonist philosopher in Egypt who was one of the earliest mothers of mathematics - http://en.wikipedia.org/wiki/Hypatia <ide> // Isaac Newton invented classic mechanics and modern optics. http://en.wikipedia.org/wiki/Isaac_Newton <add> // Jane Colden - American botanist widely considered the first female American botanist - http://en.wikipedia.org/wiki/Jane_Colden <add> // Jane Goodall - British primatologist, ethologist, and anthropologist who is considered to be the world's foremost expert on chimpanzees - http://en.wikipedia.org/wiki/Jane_Goodall <add> // Jean Bartik, born Betty Jean Jennings, was one of the original programmers for the ENIAC computer. http://en.wikipedia.org/wiki/Jean_Bartik <add> // Jean E. Sammet developed FORMAC, the first widely used computer language for symbolic manipulation of mathematical formulas. http://en.wikipedia.org/wiki/Jean_E._Sammet <add> // Johanna Mestorf - German prehistoric archaeologist and first female museum director in Germany - http://en.wikipedia.org/wiki/Johanna_Mestorf <ide> // John McCarthy invented LISP: http://en.wikipedia.org/wiki/John_McCarthy_(computer_scientist) <add> // June Almeida - Scottish virologist who took the first pictures of the rubella virus - http://en.wikipedia.org/wiki/June_Almeida <add> // Karen Spärck Jones came up with the concept of inverse document frequency, which is used in most search engines today. http://en.wikipedia.org/wiki/Karen_Sp%C3%A4rck_Jones <ide> // Leonardo Da Vinci invented too many things to list here. http://en.wikipedia.org/wiki/Leonardo_da_Vinci. <ide> // Linus Torvalds invented Linux and Git. http://en.wikipedia.org/wiki/Linus_Torvalds <add> // Lise Meitner - Austrian/Swedish physicist who was involved in the discovery of nuclear fission. The element meitnerium is named after her - http://en.wikipedia.org/wiki/Lise_Meitner <ide> // Louis Pasteur discovered vaccination, fermentation and pasteurization. http://en.wikipedia.org/wiki/Louis_Pasteur. <ide> // Malcolm McLean invented the modern shipping container: http://en.wikipedia.org/wiki/Malcom_McLean <add> // Maria Ardinghelli - Italian translator, mathematician and physicist - http://en.wikipedia.org/wiki/Maria_Ardinghelli <add> // Maria Kirch - German astronomer and first woman to discover a comet - http://en.wikipedia.org/wiki/Maria_Margarethe_Kirch <add> // Maria Mayer - American theoretical physicist and Nobel laureate in Physics for proposing the nuclear shell model of the atomic nucleus - http://en.wikipedia.org/wiki/Maria_Mayer <ide> // Marie Curie discovered radioactivity. http://en.wikipedia.org/wiki/Marie_Curie. <add> // Marie-Jeanne de Lalande - French astronomer, mathematician and cataloguer of stars - http://en.wikipedia.org/wiki/Marie-Jeanne_de_Lalande <add> // Mary Leakey - British paleoanthropologist who discovered the first fossilized Proconsul skull - http://en.wikipedia.org/wiki/Mary_Leakey <ide> // Muhammad ibn Jābir al-Ḥarrānī al-Battānī was a founding father of astronomy. http://en.wikipedia.org/wiki/Mu%E1%B8%A5ammad_ibn_J%C4%81bir_al-%E1%B8%A4arr%C4%81n%C4%AB_al-Batt%C4%81n%C4%AB <ide> // Niels Bohr is the father of quantum theory. http://en.wikipedia.org/wiki/Niels_Bohr. <ide> // Nikola Tesla invented the AC electric system and every gaget ever used by a James Bond villain. http://en.wikipedia.org/wiki/Nikola_Tesla <ide> // Pierre de Fermat pioneered several aspects of modern mathematics. http://en.wikipedia.org/wiki/Pierre_de_Fermat <add> // Rachel Carson - American marine biologist and conservationist, her book Silent Spring and other writings are credited with advancing the global environmental movement. http://en.wikipedia.org/wiki/Rachel_Carson <add> // Radia Perlman is a software designer and network engineer and most famous for her invention of the spanning-tree protocol (STP). http://en.wikipedia.org/wiki/Radia_Perlman <ide> // Richard Feynman was a key contributor to quantum mechanics and particle physics. http://en.wikipedia.org/wiki/Richard_Feynman <ide> // Rob Pike was a key contributor to Unix, Plan 9, the X graphic system, utf-8, and the Go programming language. http://en.wikipedia.org/wiki/Rob_Pike <add> // Rosalind Franklin - British biophysicist and X-ray crystallographer whose research was critical to the understanding of DNA - http://en.wikipedia.org/wiki/Rosalind_Franklin <add> // Sophie Kowalevski - Russian mathematician responsible for important original contributions to analysis, differential equations and mechanics - http://en.wikipedia.org/wiki/Sofia_Kovalevskaya <add> // Sophie Wilson designed the first Acorn Micro-Computer and the instruction set for ARM processors. http://en.wikipedia.org/wiki/Sophie_Wilson <ide> // Stephen Hawking pioneered the field of cosmology by combining general relativity and quantum mechanics. http://en.wikipedia.org/wiki/Stephen_Hawking <ide> // Steve Wozniak invented the Apple I and Apple II. http://en.wikipedia.org/wiki/Steve_Wozniak <ide> // Werner Heisenberg was a founding father of quantum mechanics. http://en.wikipedia.org/wiki/Werner_Heisenberg <ide> // William Shockley, Walter Houser Brattain and John Bardeen co-invented the transistor (thanks Brian Goff). <ide> // http://en.wikipedia.org/wiki/John_Bardeen <ide> // http://en.wikipedia.org/wiki/Walter_Houser_Brattain <ide> // http://en.wikipedia.org/wiki/William_Shockley <del> right = [...]string{"lovelace", "franklin", "tesla", "einstein", "bohr", "davinci", "pasteur", "nobel", "curie", "darwin", "turing", "ritchie", "torvalds", "pike", "thompson", "wozniak", "galileo", "euclid", "newton", "fermat", "archimedes", "poincare", "heisenberg", "feynman", "hawking", "fermi", "pare", "mccarthy", "engelbart", "babbage", "albattani", "ptolemy", "bell", "wright", "lumiere", "morse", "mclean", "brown", "bardeen", "brattain", "shockley"} <add> right = [...]string{"lovelace", "franklin", "tesla", "einstein", "bohr", "davinci", "pasteur", "nobel", "curie", "darwin", "turing", "ritchie", "torvalds", "pike", "thompson", "wozniak", "galileo", "euclid", "newton", "fermat", "archimedes", "poincare", "heisenberg", "feynman", "hawking", "fermi", "pare", "mccarthy", "engelbart", "babbage", "albattani", "ptolemy", "bell", "wright", "lumiere", "morse", "mclean", "brown", "bardeen", "brattain", "shockley", "goldstine", "hoover", "hopper", "bartik", "sammet", "jones", "perlman", "wilson", "kowalevski", "hypatia", "goodall", "mayer", "elion", "blackwell", "lalande", "kirch", "ardinghelli", "colden", "almeida", "leakey", "meitner", "mestorf", "rosalind", "sinoussi", "carson", "mcmclintock", "yonath"} <ide> ) <ide> <ide> func GenerateRandomName(checker NameChecker) (string, error) {
1
Go
Go
prevent flag grouping with --
cb3d27d01bbf696929b4d77d10e47eca2693e3fa
<ide><path>pkg/mflag/flag.go <ide> func (f *FlagSet) parseOne() (bool, string, error) { <ide> f.usage() <ide> return false, "", ErrHelp <ide> } <add> if len(name) > 0 && name[0] == '-' { <add> return false, "", f.failf("flag provided but not defined: -%s", name) <add> } <ide> return false, name, ErrRetry <ide> } <ide> if fv, ok := flag.Value.(boolFlag); ok && fv.IsBoolFlag() { // special case: doesn't need an arg
1
Go
Go
increase timeout for local store client
1685e48b035b47c16fe42908fead96a5173752bd
<ide><path>libnetwork/datastore/datastore.go <ide> import ( <ide> "reflect" <ide> "strings" <ide> "sync" <add> "time" <ide> <ide> "github.com/docker/libkv" <ide> "github.com/docker/libkv/store" <ide> func makeDefaultScopes() map[string]*ScopeCfg { <ide> Provider: string(store.BOLTDB), <ide> Address: defaultPrefix + "/local-kv.db", <ide> Config: &store.Config{ <del> Bucket: "libnetwork", <add> Bucket: "libnetwork", <add> ConnectionTimeout: time.Minute, <ide> }, <ide> }, <ide> }
1
PHP
PHP
change method order
ab0801cf08df7d448b1047892eabec07407739f6
<ide><path>src/Illuminate/Contracts/Translation/Translator.php <ide> public function trans($key, array $replace = [], $locale = null); <ide> public function transChoice($key, $number, array $replace = [], $locale = null); <ide> <ide> /** <del> * Set the default locale. <add> * Get the default locale being used. <ide> * <del> * @param string $locale <del> * @return void <add> * @return string <ide> */ <del> public function setLocale($locale); <add> public function getLocale(); <ide> <ide> /** <del> * Get the default locale being used. <add> * Set the default locale. <ide> * <del> * @return string <add> * @param string $locale <add> * @return void <ide> */ <del> public function getLocale(); <add> public function setLocale($locale); <ide> }
1
Javascript
Javascript
simplify morph target parsing
ac1c328b8769f7dcf462219b9f1ed0147081b70f
<ide><path>examples/js/loaders/FBXLoader.js <ide> <ide> targetRelationships.children.forEach( function ( child ) { <ide> <del> <del> if ( child.relationship === 'DeformPercent' ) { // animation info for morph target <del> <del> var animConnections = connections.get( child.ID ); <del> // parent relationship 'DeformPercent' === morphTargetNode /2605340465664 <del> // parent relationship 'undefined' === AnimationLayer /2606600117184 <del> // child relationship 'd|DeformPercent' === AnimationCurve /2606284032736 <del> <del> rawMorphTarget.weightCurveID = child.ID; <del> <del> animConnections.parents.forEach( function ( parent ) { <del> <del> if ( parent.relationship === undefined ) { <del> <del> // assuming each morph target is in a single animation layer for now <del> rawMorphTarget.animationLayerID = parent.ID; <del> <del> } <del> <del> } ); <del> <del> // assuming each morph target has a single animation curve for now <del> rawMorphTarget.animationCurveID = animConnections.children[ 0 ].ID; <del> <del> } else { <del> <del> rawMorphTarget.geoID = child.ID; <del> <del> } <add> if ( child.relationship === undefined ) rawMorphTarget.geoID = child.ID; <ide> <ide> } ); <ide>
1
Javascript
Javascript
fix typo on messages
5765061652eee9726c4e44d783b13af96b3880b4
<ide><path>src/ngMessages/messages.js <ide> * <ide> * Whenever the `ngMessages` directive contains one or more visible messages then the `.ng-active` CSS <ide> * class will be added to the element. The `.ng-inactive` CSS class will be applied when there are no <del> * animations present. Therefore, CSS transitions and keyframes as well as JavaScript animations can <add> * messages present. Therefore, CSS transitions and keyframes as well as JavaScript animations can <ide> * hook into the animations whenever these classes are added/removed. <ide> * <ide> * Let's say that our HTML code for our messages container looks like so:
1
Ruby
Ruby
use instanceof? in eql?
439a2f4fae2e5ddae40a808246f28b5b4e7961f6
<ide><path>Library/Homebrew/dependency.rb <ide> def ==(other) <ide> end <ide> <ide> def eql?(other) <del> other.is_a?(self.class) && hash == other.hash <add> instance_of?(other.class) && hash == other.hash <ide> end <ide> <ide> def hash
1