content_type
stringclasses 8
values | main_lang
stringclasses 7
values | message
stringlengths 1
50
| sha
stringlengths 40
40
| patch
stringlengths 52
962k
| file_count
int64 1
300
|
|---|---|---|---|---|---|
Javascript
|
Javascript
|
fix build to add class to code blocks
|
519e74d868c5bb8b05e862ee811d67fb520f721f
|
<ide><path>build/js/build.js
<ide> const Builder = function(outBaseDir, options) {
<ide> const info = extractHandlebars(content);
<ide> let html = marked(info.content);
<ide> // HACK! :-(
<add> // There's probably a way to do this in marked
<add> html = html.replace(/<pre><code/g, '<pre class="prettyprint"><code');
<add> // HACK! :-(
<ide> if (opt_extra && opt_extra.home && opt_extra.home.length > 1) {
<ide> html = hackRelLinks(html, pageUrl);
<ide> }
| 1
|
Text
|
Text
|
add the climate corporation to user list
|
b26017d84b24660b434b836f0ed73fe0b5ef6154
|
<ide><path>README.md
<ide> Currently **officially** using Airflow:
<ide> 1. [Telia Company](https://www.teliacompany.com/en)
<ide> 1. [Ternary Data](https://ternarydata.com/) [[@mhousley](https://github.com/mhousley), [@JoeReis](https://github.com/JoeReis)]
<ide> 1. [Tesla](https://www.tesla.com/) [[@thoralf-gutierrez](https://github.com/thoralf-gutierrez)]
<add>1. [The Climate Corporation](https://climate.com/)[[@jmelching](https://github.com/jmelching)]
<ide> 1. [The Home Depot](https://www.homedepot.com/)[[@apekshithr](https://github.com/apekshithr)]
<ide> 1. [THE ICONIC](https://www.theiconic.com.au/) [[@revathijay](https://github.com/revathijay)] [[@ilikedata](https://github.com/ilikedata)]
<ide> 1. [Thinking Machines](https://thinkingmachin.es) [[@marksteve](https://github.com/marksteve)]
| 1
|
Mixed
|
Javascript
|
use esm syntax for wasi example
|
88a5426e9c390b619ea966798bf8380c88cda81c
|
<ide><path>.eslintrc.js
<ide> module.exports = {
<ide> 'doc/api/module.md',
<ide> 'doc/api/modules.md',
<ide> 'doc/api/packages.md',
<add> 'doc/api/wasi.md',
<ide> 'test/es-module/test-esm-type-flag.js',
<ide> 'test/es-module/test-esm-type-flag-alias.js',
<ide> '*.mjs',
<ide><path>doc/api/wasi.md
<ide> specification. WASI gives sandboxed WebAssembly applications access to the
<ide> underlying operating system via a collection of POSIX-like functions.
<ide>
<ide> ```js
<del>'use strict';
<del>const fs = require('fs');
<del>const { WASI } = require('wasi');
<add>import fs from 'fs';
<add>import { WASI } from 'wasi';
<add>
<ide> const wasi = new WASI({
<ide> args: process.argv,
<ide> env: process.env,
<ide> const wasi = new WASI({
<ide> });
<ide> const importObject = { wasi_snapshot_preview1: wasi.wasiImport };
<ide>
<del>(async () => {
<del> const wasm = await WebAssembly.compile(fs.readFileSync('./demo.wasm'));
<del> const instance = await WebAssembly.instantiate(wasm, importObject);
<add>const wasm = await WebAssembly.compile(fs.readFileSync('./demo.wasm'));
<add>const instance = await WebAssembly.instantiate(wasm, importObject);
<ide>
<del> wasi.start(instance);
<del>})();
<add>wasi.start(instance);
<ide> ```
<ide>
<ide> To run the above example, create a new WebAssembly text format file named
| 2
|
Ruby
|
Ruby
|
remove duplicated logic
|
9effe3cc18182abbcf0a8b01635a34ca77b67e02
|
<ide><path>activerecord/lib/active_record/associations.rb
<ide> def remove_duplicate_results!(base, records, associations)
<ide> case associations
<ide> when Symbol, String
<ide> reflection = base.reflections[associations]
<del> if reflection && reflection.collection?
<del> records.each { |record| record.send(reflection.name).target.uniq! }
<del> end
<add> remove_uniq_by_reflection(reflection, records)
<ide> when Array
<ide> associations.each do |association|
<ide> remove_duplicate_results!(base, records, association)
<ide> end
<ide> when Hash
<ide> associations.keys.each do |name|
<ide> reflection = base.reflections[name]
<del>
<del> if records.any? && reflection.options && reflection.options[:uniq]
<del> records.each { |record| record.send(reflection.name).target.uniq! }
<del> end
<add> remove_uniq_by_reflection(reflection, records)
<ide>
<ide> parent_records = []
<ide> records.each do |record|
<ide> def remove_duplicate_results!(base, records, associations)
<ide> end
<ide>
<ide> protected
<add>
<ide> def build(associations, parent = nil, join_class = Arel::InnerJoin)
<ide> parent ||= @joins.last
<ide> case associations
<ide> def build(associations, parent = nil, join_class = Arel::InnerJoin)
<ide> end
<ide> end
<ide>
<add> def remove_uniq_by_reflection(reflection, records)
<add> if reflection && reflection.collection?
<add> records.each { |record| record.send(reflection.name).target.uniq! }
<add> end
<add> end
<add>
<ide> def build_join_association(reflection, parent)
<ide> JoinAssociation.new(reflection, self, parent)
<ide> end
| 1
|
Text
|
Text
|
fix a tiny typo
|
2b787763aa755f2c2d84d0d3cbfb6586ce29e692
|
<ide><path>laravel/documentation/database/redis.md
<ide> Great! Now that we have an instance of the Redis client, we may issue any of the
<ide>
<ide> $values = $redis->lrange('names', 5, 10);
<ide>
<del>Notice the arguments to the comment are simply passed into the magic method. Of course, you are not required to use the magic methods, you may also pass commands to the server using the **run** method:
<add>Notice the arguments to the command are simply passed into the magic method. Of course, you are not required to use the magic methods, you may also pass commands to the server using the **run** method:
<ide>
<ide> $values = $redis->run('lrange', array(5, 10));
<ide>
| 1
|
Text
|
Text
|
improve accessibility in copy
|
4ca38304d95c94f23f4dd9ac4910890f5eb3d3c4
|
<ide><path>guide/english/android-development/index.md
<ide> From simple games and utility apps to full-blown music players, there are many o
<ide>
<ide> There is definitely a learning curve to get used to the Android framework, but once you understand the core components that make up the app, the rest will come naturally.
<ide>
<del>The learning curve involved in Android has a relatively smaller slope compared to learning other technologies such as NodeJS. It is also relatively easier to understand and make contributions towards Android Open Source Project(AOSP) hosted by Google. The project can be found [here](https://source.android.com/)
<add>The learning curve involved in Android has a relatively smaller slope compared to learning other technologies such as NodeJS. It is also relatively easier to understand and make contributions to the [Android Open Source Project](https://source.android.com) (AOSP) hosted by Google.
<ide>
<ide> ## Getting started
<ide> Check out the guides in this folder to learn about the 4 [core components](core-components/index.md) that make up an Android app and how you can get started with a sample app, and then delve into the more advanced topics such as fragments and the Gradle build system. Then check out the material design specifications guide as well to learn how to make your apps beautiful and user-friendly.
<ide>
<ide> ### Setting Up and Getting Started with Android Studio
<del>Visit this [link](https://www.oracle.com/technetwork/java/javase/downloads/index.html) and install the latest JDK.
<del>Now download the Android Studio and SDK tools bundle from [here](https://developer.android.com/studio/).
<add>Go to the [Java SE Download page](https://www.oracle.com/technetwork/java/javase/downloads/index.html) and install the latest JDK.
<add>
<add>Download the Android Studio and SDK tools bundle from the [Android Studio Download page](https://developer.android.com/studio/).
<add>
<add>Install the Android Studio and SDK following the set up. Keep note of the SDK location.
<ide>
<del>Install the Android Studio and SDK following the setup. Keep note of the SDK location.
<ide> If you face any error go to settings later to solve it.
<ide>
<ide> Lastly, learn to integrate 3rd party libraries and Firebase services to add numerous functionalities to your app. It would be helpful if you go through the official documentation for each component.
| 1
|
Ruby
|
Ruby
|
extract constant strings
|
c7685d2b70d4e6fc7ac5bbc77791687d4d0d4d98
|
<ide><path>Library/Homebrew/test/test_patching.rb
<ide> require 'testball'
<ide>
<ide> class PatchingTests < Test::Unit::TestCase
<add> PATCH_URL_A = "file:///#{TEST_FOLDER}/patches/noop-a.diff"
<add> PATCH_URL_B = "file:///#{TEST_FOLDER}/patches/noop-b.diff"
<add>
<ide> def formula(&block)
<ide> super do
<ide> url "file:///#{TEST_FOLDER}/tarballs/testball-0.1.tbz"
<ide> def test_single_patch
<ide> shutup do
<ide> formula do
<ide> def patches
<del> "file:///#{TEST_FOLDER}/patches/noop-a.diff"
<add> PATCH_URL_A
<ide> end
<ide> end.brew { assert_patched 'libexec/NOOP' }
<ide> end
<ide> def test_single_patch_dsl
<ide> shutup do
<ide> formula do
<ide> patch do
<del> url "file:///#{TEST_FOLDER}/patches/noop-a.diff"
<add> url PATCH_URL_A
<ide> sha1 "fa8af2e803892e523fdedc6b758117c45e5749a2"
<ide> end
<ide> end.brew { assert_patched 'libexec/NOOP' }
<ide> def test_single_patch_dsl_with_strip
<ide> shutup do
<ide> formula do
<ide> patch :p1 do
<del> url "file:///#{TEST_FOLDER}/patches/noop-a.diff"
<add> url PATCH_URL_A
<ide> sha1 "fa8af2e803892e523fdedc6b758117c45e5749a2"
<ide> end
<ide> end.brew { assert_patched 'libexec/NOOP' }
<ide> def test_single_patch_dsl_with_incorrect_strip
<ide> shutup do
<ide> formula do
<ide> patch :p0 do
<del> url "file:///#{TEST_FOLDER}/patches/noop-a.diff"
<add> url PATCH_URL_A
<ide> sha1 "fa8af2e803892e523fdedc6b758117c45e5749a2"
<ide> end
<ide> end.brew { }
<ide> def test_patch_p0_dsl
<ide> shutup do
<ide> formula do
<ide> patch :p0 do
<del> url "file:///#{TEST_FOLDER}/patches/noop-b.diff"
<add> url PATCH_URL_B
<ide> sha1 "3b54bd576f998ef6d6623705ee023b55062b9504"
<ide> end
<ide> end.brew { assert_patched 'libexec/NOOP' }
<ide> def test_patch_p0
<ide> shutup do
<ide> formula do
<ide> def patches
<del> { :p0 => "file:///#{TEST_FOLDER}/patches/noop-b.diff" }
<add> { :p0 => PATCH_URL_B }
<ide> end
<ide> end.brew { assert_patched 'libexec/NOOP' }
<ide> end
<ide> def test_patch_array
<ide> shutup do
<ide> formula do
<ide> def patches
<del> ["file:///#{TEST_FOLDER}/patches/noop-a.diff"]
<add> [PATCH_URL_A]
<ide> end
<ide> end.brew { assert_patched 'libexec/noop' }
<ide> end
<ide> def test_patch_hash
<ide> shutup do
<ide> formula do
<ide> def patches
<del> { :p1 => "file:///#{TEST_FOLDER}/patches/noop-a.diff" }
<add> { :p1 => PATCH_URL_A }
<ide> end
<ide> end.brew { assert_patched 'libexec/noop' }
<ide> end
<ide> def test_patch_hash_array
<ide> shutup do
<ide> formula do
<ide> def patches
<del> { :p1 => ["file:///#{TEST_FOLDER}/patches/noop-a.diff"] }
<add> { :p1 => [PATCH_URL_A] }
<ide> end
<ide> end.brew { assert_patched 'libexec/noop' }
<ide> end
| 1
|
Text
|
Text
|
add learntocode rpg
|
eb83f393adbe3ed11745f54483b80a27a44722cb
|
<ide><path>docs/how-to-translate-files.md
<ide> Translating our contributing documentation is a similar flow to translating our
<ide> > [!NOTE]
<ide> > Our contributing documentation is powered by `docsify`, and we have special parsing for message boxes like this one. If you see strings that start with `[!NOTE]`, `[!WARNING]`, or `[!TIP]`, these words should NOT be translated.
<ide>
<add>## Translate the LearnToCode RPG
<add>
<add>The LearnToCode RPG runs on Ren'Py, which uses special syntax for translated strings: (See [Ren'Py Text documentation](https://www.renpy.org/doc/html/text.html))
<add>
<add>- The sentences to be translated are always between `""`. These are dialogues or UI strings. The keywords that come before or after the dialogue are game engine control keywords and will be explained in details in subsequent rules. Please note that this first rule governs all subsequent rules listed.
<add>- In case of `new "..."` Do not translate the `new` keyword.
<add>- Prefixes like `player`, `annika`, `layla`, `marco` (or variants like `player happy`, `player @ happy`) should not be translated. These are control keywords to correctly display the character sprite in the game.
<add>- Postfixes like `nointeract` should not be translated.
<add>- Do not translate things between `[]` and `{}`. These are variable interpolations and text tags. These must remain halfwidth parentheses `[]` and `{}` instead of their fullwidth counterparts `【】` and `「」`
<add>- Do not translate the `nointeract` keyword at the end of the sentence.
<add>- If we try to use fullwidth parentheses `()`, a QA warning will show. To avoid the QA warning, use halfwidth parentheses `()`
<add>
<add>### Examples
<add>
<add>---
<add>
<add>#### Before translation
<add>
<add>```renpy
<add># "[player_name]? What a coincidence! Our VIP team member {a=[vip_profile_url]}[player_name]{/a} will be honored to hear that."
<add>"[player_name]? What a coincidence! Our VIP team member {a=[vip_profile_url]}[player_name]{/a} will be honored to hear that." <--- this is the line that needs to be translated. see translation below
<add>```
<add>
<add>#### After translation
<add>
<add>```renpy
<add># "[player_name]? What a coincidence! Our VIP team member {a=[vip_profile_url]}[player_name]{/a} will be honored to hear that."
<add>"[player_name]?好巧,我们的VIP队友{a=[vip_profile_url]}[player_name]{/a}会很高兴的。"
<add>```
<add>
<add>Note: The `[]` and `{}` tags should be left intact.
<add>
<add>---
<add>
<add>#### Before translation
<add>
<add>```renpy
<add>old "{icon=icon-fast-forward} Skip"
<add>new "{icon=icon-fast-forward} Skip" <-- translate this line, see below
<add>```
<add>
<add>#### After translation
<add>
<add>```renpy
<add>old "{icon=icon-fast-forward} Skip"
<add>new "{icon=icon-fast-forward} 跳过"
<add>```
<add>
<add>Note: Again, the `new` prefix and the `{icon=icon-fast-forward}` tag should be left intact.
<add>
<add>---
<add>
<add>#### Before translation
<add>
<add>```renpy
<add># layla @ neutral "Hehe, [player_name], you are a fun one. I'm sure you will enjoy your work as a developer."
<add>layla @ neutral "Hehe, [player_name], you are a fun one. I'm sure you will enjoy your work as a developer."
<add>```
<add>
<add>#### After translation
<add>
<add>```renpy
<add># layla @ neutral "Hehe, [player_name], you are a fun one. I'm sure you will enjoy your work as a developer."
<add>layla @ neutral "哈哈,[player_name],你真有趣。我相信你一定会喜欢你的开发者工作的。"
<add>```
<add>
<add>Note: `layla @ neutral` and `[player_name]` are left unchanged.
<add>
<add>---
<add>
<add>#### Before translation
<add>
<add>```renpy
<add># player "Maybe this is all a dream?" nointeract
<add>player "Maybe this is all a dream?" nointeract
<add>```
<add>
<add>#### After translation
<add>
<add>```renpy
<add># player "Maybe this is all a dream?" nointeract
<add>player "也许这都是一场梦?" nointeract
<add>```
<add>
<add>---
<add>
<add>### A Note on How Crowdin Segments a Sentence
<add>
<add>Pay attention to how Crowdin segments a line of dialogue wrapped between opening and closing quotes `""`. When we are translating the dialogue, we need to make sure to retain the opening and closing quotes, even if the quotes appear in different segments.
<add>
<add>This is the line to be translated:
<add>
<add>```renpy
<add>player @ surprised "{b}Full-stack{/b}... What is that? I better take notes so I can learn more about it."
<add>```
<add>
<add>Crowdin segments it into three parts like below:
<add>
<add><img width="836" alt="Screen Shot 2022-01-23 at 10 36 43" src="https://user-images.githubusercontent.com/35674052/150693962-d3b091e5-2432-44d0-9d24-195ea7d7aeda.png">
<add>
<add>```renpy
<add># original
<add>player @ surprised "{b}Full-stack{/b}
<add># translated, keeping the opening quotes `"`
<add>player @ surprised "{b}全栈{/b}
<add>```
<add>
<add><img width="750" alt="Screen Shot 2022-01-23 at 10 36 49" src="https://user-images.githubusercontent.com/35674052/150693965-15411504-791a-4db3-8b14-bc9177be6375.png">
<add>
<add>```renpy
<add># original
<add>What is that?
<add># translated, no quotes on either side
<add>这是什么?
<add>```
<add>
<add><img width="857" alt="Screen Shot 2022-01-23 at 10 36 54" src="https://user-images.githubusercontent.com/35674052/150693969-062e3268-580f-4ad2-97db-cab6240b6095.png">
<add>
<add>```renpy
<add># original
<add>I better take notes so I can learn more about it."
<add># translated, keeping the closing quotes `"`
<add>我最好做笔记,这样我可以学习更多东西。"
<add>```
<add>
<ide> ## Rate Translations
<ide>
<ide> Crowdin allows you to rate the existing proposed translations. If you attempt to save a translation, you may see a message indicating that you cannot save a duplicate translation - this means another contributor has proposed that identical translation. If you agree with that translation, click the `+` button to "upvote" the translation.
| 1
|
Ruby
|
Ruby
|
fix dependency option handling
|
f7f15673a8e8ecb6817435c7bd51c7e8077220e4
|
<ide><path>Library/Homebrew/dependency.rb
<ide> def satisfied?(inherited_options)
<ide> end
<ide>
<ide> def missing_options(inherited_options)
<del> required = options | inherited_options
<del> required - Tab.for_formula(to_formula).used_options
<add> formula = to_formula
<add> required = options
<add> required |= inherited_options
<add> required &= formula.options.to_a
<add> required -= Tab.for_formula(formula).used_options
<add> required
<ide> end
<ide>
<ide> def modify_build_environment
<ide><path>Library/Homebrew/formula_installer.rb
<ide> def install
<ide>
<ide> @@attempted << formula
<ide>
<del> pour_bottle = pour_bottle?(warn: true)
<del> if pour_bottle
<add> if pour_bottle?(warn: true)
<ide> begin
<ide> pour
<ide> rescue Exception => e
<ide> def install
<ide> onoe e.message
<ide> opoo "Bottle installation failed: building from source."
<ide> raise BuildToolsError, [formula] unless DevelopmentTools.installed?
<add> compute_and_install_dependencies unless skip_deps_check?
<ide> else
<del> puts_requirement_messages
<ide> @poured_bottle = true
<ide> end
<ide> end
<ide>
<add> puts_requirement_messages
<add>
<ide> build_bottle_preinstall if build_bottle?
<ide>
<ide> unless @poured_bottle
<del> not_pouring = !pour_bottle || @pour_failed
<del> compute_and_install_dependencies if not_pouring && !ignore_deps?
<del> puts_requirement_messages
<ide> build
<ide> clean
<ide>
<ide> def install_dependency(dep, inherited_options)
<ide>
<ide> fi = DependencyInstaller.new(df)
<ide> fi.options |= tab.used_options
<add> fi.options |= Tab.remap_deprecated_options(df.deprecated_options, dep.options)
<ide> fi.options |= inherited_options
<ide> fi.options &= df.options
<ide> fi.build_from_source = ARGV.build_formula_from_source?(df)
| 2
|
Go
|
Go
|
fix some spelling issues
|
101ff26eb56b7493e10fd90dd552e3930aaef6dc
|
<ide><path>integration-cli/docker_api_containers_test.go
<ide> func (s *DockerSuite) TestContainerAPIWait(c *testing.T) {
<ide> assert.NilError(c, err)
<ide> defer cli.Close()
<ide>
<del> waitresC, errC := cli.ContainerWait(context.Background(), name, "")
<add> waitResC, errC := cli.ContainerWait(context.Background(), name, "")
<ide>
<ide> select {
<ide> case err = <-errC:
<ide> assert.NilError(c, err)
<del> case waitres := <-waitresC:
<del> assert.Equal(c, waitres.StatusCode, int64(0))
<add> case waitRes := <-waitResC:
<add> assert.Equal(c, waitRes.StatusCode, int64(0))
<ide> }
<ide> }
<ide>
<ide><path>integration/container/wait_test.go
<ide> func TestWaitNonBlocked(t *testing.T) {
<ide> containerID := container.Run(ctx, t, cli, container.WithCmd("sh", "-c", tc.cmd))
<ide> poll.WaitOn(t, container.IsInState(ctx, cli, containerID, "exited"), poll.WithTimeout(30*time.Second), poll.WithDelay(100*time.Millisecond))
<ide>
<del> waitresC, errC := cli.ContainerWait(ctx, containerID, "")
<add> waitResC, errC := cli.ContainerWait(ctx, containerID, "")
<ide> select {
<ide> case err := <-errC:
<ide> assert.NilError(t, err)
<del> case waitres := <-waitresC:
<del> assert.Check(t, is.Equal(tc.expectedCode, waitres.StatusCode))
<add> case waitRes := <-waitResC:
<add> assert.Check(t, is.Equal(tc.expectedCode, waitRes.StatusCode))
<ide> }
<ide> })
<ide> }
<ide> func TestWaitBlocked(t *testing.T) {
<ide> containerID := container.Run(ctx, t, cli, container.WithCmd("sh", "-c", tc.cmd))
<ide> poll.WaitOn(t, container.IsInState(ctx, cli, containerID, "running"), poll.WithTimeout(30*time.Second), poll.WithDelay(100*time.Millisecond))
<ide>
<del> waitresC, errC := cli.ContainerWait(ctx, containerID, "")
<add> waitResC, errC := cli.ContainerWait(ctx, containerID, "")
<ide>
<ide> err := cli.ContainerStop(ctx, containerID, nil)
<ide> assert.NilError(t, err)
<ide>
<ide> select {
<ide> case err := <-errC:
<ide> assert.NilError(t, err)
<del> case waitres := <-waitresC:
<del> assert.Check(t, is.Equal(tc.expectedCode, waitres.StatusCode))
<add> case waitRes := <-waitResC:
<add> assert.Check(t, is.Equal(tc.expectedCode, waitRes.StatusCode))
<ide> case <-time.After(2 * time.Second):
<ide> t.Fatal("timeout waiting for `docker wait`")
<ide> }
<ide><path>testutil/environment/environment.go
<ide> type PlatformDefaults struct {
<ide> }
<ide>
<ide> // New creates a new Execution struct
<del>// This is configured useing the env client (see client.FromEnv)
<add>// This is configured using the env client (see client.FromEnv)
<ide> func New() (*Execution, error) {
<ide> c, err := client.NewClientWithOpts(client.FromEnv)
<ide> if err != nil {
| 3
|
Ruby
|
Ruby
|
check undeclared dependencies for `--test`"
|
454645263d3380dfa8d699bd1c42fa907076645f
|
<ide><path>Library/Homebrew/dev-cmd/linkage.rb
<ide>
<ide> module Homebrew
<ide> def linkage
<add> found_broken_dylibs = false
<ide> ARGV.kegs.each do |keg|
<ide> ohai "Checking #{keg.name} linkage" if ARGV.kegs.size > 1
<ide> result = LinkageChecker.new(keg)
<ide> if ARGV.include?("--test")
<ide> result.display_test_output
<del> if result.broken_dylibs? || result.undeclared_deps?
<del> Homebrew.failed = true
<del> end
<ide> elsif ARGV.include?("--reverse")
<ide> result.display_reverse_output
<ide> else
<ide> result.display_normal_output
<ide> end
<add> found_broken_dylibs = true unless result.broken_dylibs.empty?
<add> end
<add> if ARGV.include?("--test") && found_broken_dylibs
<add> exit 1
<ide> end
<ide> end
<ide>
<ide> class LinkageChecker
<ide> attr_reader :keg
<del> attr_reader :brewed_dylibs, :system_dylibs, :broken_dylibs, :variable_dylibs
<del> attr_reader :undeclared_deps, :reverse_links
<add> attr_reader :broken_dylibs
<ide>
<ide> def initialize(keg)
<ide> @keg = keg
<ide> @brewed_dylibs = Hash.new { |h, k| h[k] = Set.new }
<ide> @system_dylibs = Set.new
<ide> @broken_dylibs = Set.new
<ide> @variable_dylibs = Set.new
<del> @undeclared_deps = []
<ide> @reverse_links = Hash.new { |h, k| h[k] = Set.new }
<ide> check_dylibs
<ide> end
<ide> def check_dylibs
<ide> @undeclared_deps -= [f.name]
<ide> rescue FormulaUnavailableError
<ide> opoo "Formula unavailable: #{keg.name}"
<add> @undeclared_deps = []
<ide> end
<ide> end
<ide>
<ide> def display_reverse_output
<ide> def display_test_output
<ide> display_items "Missing libraries", @broken_dylibs
<ide> puts "No broken dylib links" if @broken_dylibs.empty?
<del> display_items "Possible undeclared dependencies", @undeclared_deps
<del> puts "No undeclared dependencies" if @undeclared_deps.empty?
<del> end
<del>
<del> def broken_dylibs?
<del> !@broken_dylibs.empty?
<del> end
<del>
<del> def undeclared_deps?
<del> !@undeclared_deps.empty?
<ide> end
<ide>
<ide> private
| 1
|
Javascript
|
Javascript
|
remove reacttypes from fbsource and react sync
|
8bbb2ca44b60d1eca97b07d502c5f235b77c0319
|
<ide><path>Libraries/Renderer/shims/ReactTypes.js
<del>/**
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<del> *
<del> * This source code is licensed under the MIT license found in the
<del> * LICENSE file in the root directory of this source tree.
<del> *
<del> * @flow
<del> */
<del>
<del>export type ReactNode =
<del> | React$Element<any>
<del> | ReactPortal
<del> | ReactText
<del> | ReactFragment
<del> | ReactProvider<any>
<del> | ReactConsumer<any>;
<del>
<del>export type ReactEmpty = null | void | boolean;
<del>
<del>export type ReactFragment = ReactEmpty | Iterable<React$Node>;
<del>
<del>export type ReactNodeList = ReactEmpty | React$Node;
<del>
<del>export type ReactText = string | number;
<del>
<del>export type ReactProvider<T> = {
<del> $$typeof: Symbol | number,
<del> type: ReactProviderType<T>,
<del> key: null | string,
<del> ref: null,
<del> props: {
<del> value: T,
<del> children?: ReactNodeList,
<del> ...
<del> },
<del> ...
<del>};
<del>
<del>export type ReactProviderType<T> = {
<del> $$typeof: Symbol | number,
<del> _context: ReactContext<T>,
<del> ...
<del>};
<del>
<del>export type ReactConsumer<T> = {
<del> $$typeof: Symbol | number,
<del> type: ReactContext<T>,
<del> key: null | string,
<del> ref: null,
<del> props: {
<del> children: (value: T) => ReactNodeList,
<del> unstable_observedBits?: number,
<del> ...
<del> },
<del> ...
<del>};
<del>
<del>export type ReactContext<T> = {
<del> $$typeof: Symbol | number,
<del> Consumer: ReactContext<T>,
<del> Provider: ReactProviderType<T>,
<del> _calculateChangedBits: ((a: T, b: T) => number) | null,
<del> _currentValue: T,
<del> _currentValue2: T,
<del> _threadCount: number,
<del> // DEV only
<del> _currentRenderer?: Object | null,
<del> _currentRenderer2?: Object | null,
<del> // This value may be added by application code
<del> // to improve DEV tooling display names
<del> displayName?: string,
<del> ...
<del>};
<del>
<del>export type ReactPortal = {
<del> $$typeof: Symbol | number,
<del> key: null | string,
<del> containerInfo: any,
<del> children: ReactNodeList,
<del> // TODO: figure out the API for cross-renderer implementation.
<del> implementation: any,
<del> ...
<del>};
<del>
<del>export type RefObject = {|
<del> current: any,
<del>|};
<del>
<del>export type ReactEventResponderInstance<E, C> = {|
<del> fiber: Object,
<del> props: Object,
<del> responder: ReactEventResponder<E, C>,
<del> rootEventTypes: null | Set<string>,
<del> state: Object,
<del>|};
<del>
<del>export type ReactEventResponderListener<E, C> = {|
<del> props: Object,
<del> responder: ReactEventResponder<E, C>,
<del>|};
<del>
<del>export type ReactEventResponder<E, C> = {
<del> $$typeof: Symbol | number,
<del> displayName: string,
<del> targetEventTypes: null | Array<string>,
<del> targetPortalPropagation: boolean,
<del> rootEventTypes: null | Array<string>,
<del> getInitialState: null | ((props: Object) => Object),
<del> onEvent:
<del> | null
<del> | ((event: E, context: C, props: Object, state: Object) => void),
<del> onRootEvent:
<del> | null
<del> | ((event: E, context: C, props: Object, state: Object) => void),
<del> onMount: null | ((context: C, props: Object, state: Object) => void),
<del> onUnmount: null | ((context: C, props: Object, state: Object) => void),
<del> ...
<del>};
<del>
<del>export type EventPriority = 0 | 1 | 2;
<del>
<del>export const DiscreteEvent: EventPriority = 0;
<del>export const UserBlockingEvent: EventPriority = 1;
<del>export const ContinuousEvent: EventPriority = 2;
<del>
<del>export type ReactFundamentalComponentInstance<C, H> = {|
<del> currentFiber: mixed,
<del> instance: mixed,
<del> prevProps: null | Object,
<del> props: Object,
<del> impl: ReactFundamentalImpl<C, H>,
<del> state: Object,
<del>|};
<del>
<del>export type ReactFundamentalImpl<C, H> = {
<del> displayName: string,
<del> reconcileChildren: boolean,
<del> getInitialState?: (props: Object) => Object,
<del> getInstance: (context: C, props: Object, state: Object) => H,
<del> getServerSideString?: (context: C, props: Object) => string,
<del> getServerSideStringClose?: (context: C, props: Object) => string,
<del> onMount: (context: C, instance: mixed, props: Object, state: Object) => void,
<del> shouldUpdate?: (
<del> context: C,
<del> prevProps: null | Object,
<del> nextProps: Object,
<del> state: Object,
<del> ) => boolean,
<del> onUpdate?: (
<del> context: C,
<del> instance: mixed,
<del> prevProps: null | Object,
<del> nextProps: Object,
<del> state: Object,
<del> ) => void,
<del> onUnmount?: (
<del> context: C,
<del> instance: mixed,
<del> props: Object,
<del> state: Object,
<del> ) => void,
<del> onHydrate?: (context: C, props: Object, state: Object) => boolean,
<del> onFocus?: (context: C, props: Object, state: Object) => boolean,
<del> ...
<del>};
<del>
<del>export type ReactFundamentalComponent<C, H> = {|
<del> $$typeof: Symbol | number,
<del> impl: ReactFundamentalImpl<C, H>,
<del>|};
<del>
<del>export type ReactScope = {|
<del> $$typeof: Symbol | number,
<del>|};
<del>
<del>export type ReactScopeQuery = (
<del> type: string,
<del> props: {[string]: mixed, ...},
<del> instance: mixed,
<del>) => boolean;
<del>
<del>export type ReactScopeMethods = {|
<del> DO_NOT_USE_queryAllNodes(ReactScopeQuery): null | Array<Object>,
<del> DO_NOT_USE_queryFirstNode(ReactScopeQuery): null | Object,
<del> containsNode(Object): boolean,
<del> getChildContextValues: <T>(context: ReactContext<T>) => Array<T>,
<del>|};
<del>
<del>export type ReactScopeInstance = {|
<del> fiber: Object,
<del> methods: null | ReactScopeMethods,
<del>|};
| 1
|
PHP
|
PHP
|
remove int check
|
8dfae2aab8d0371ecfd6ea239e19ce784528e25f
|
<ide><path>src/Illuminate/Cache/Repository.php
<ide> public function pull($key, $default = null)
<ide> */
<ide> public function put($key, $value, $minutes = null)
<ide> {
<del> if (is_array($key) && filter_var($value, FILTER_VALIDATE_FLOAT) !== false) {
<add> if (is_array($key)) {
<ide> return $this->putMany($key, $value);
<ide> }
<ide>
| 1
|
Text
|
Text
|
update tooling docs to suggest babel
|
009902bcd08a58e6a019e4a26a6e8b69a5ba8b63
|
<ide><path>docs/docs/09-tooling-integration.md
<ide> We have instructions for building from `master` [in our GitHub repository](https
<ide>
<ide> ### In-browser JSX Transform
<ide>
<del>If you like using JSX, we provide an in-browser JSX transformer for development [on our download page](/react/downloads.html). Simply include a `<script type="text/jsx">` tag to engage the JSX transformer.
<add>If you like using JSX, babel provides an [in-browser ES6 and JSX transformer for development](http://babeljs.io/docs/usage/browser/) called browser.js that can be included from a `babel-core` npm release or from [CDNJS](http://cdnjs.com/libraries/babel-core). Include a `<script type="text/babel">` tag to engage the JSX transformer.
<ide>
<ide> > Note:
<ide> >
<ide> If you like using JSX, we provide an in-browser JSX transformer for development
<ide>
<ide> ### Productionizing: Precompiled JSX
<ide>
<del>If you have [npm](https://www.npmjs.com/), you can simply run `npm install -g react-tools` to install our command-line `jsx` tool. 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: `jsx --watch src/ build/`.
<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 and v0.13. Tags are automatically transformed to their equivalent `React.createElement(...)`, `displayName` is automatically inferred and added to all React.createClass calls.
<ide>
<del>By default JSX files with a `.js` extension are transformed. Use `jsx --extension jsx src/ build/` to transform files with a `.jsx` extension.
<add>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>
<del>Run `jsx --help` for more information on how to use this tool.
<add>By default JSX files with a `.js` extension are transformed. Run `babel --help` for more information on how to use `babel`.
<add>
<add>Example output:
<add>
<add>```
<add>$ cat test.jsx
<add>var HelloMessage = React.createClass({
<add> render: function() {
<add> return <div>Hello {this.props.name}</div>;
<add> }
<add>});
<add>
<add>React.render(<HelloMessage name="John" />, mountNode);
<add>$ babel test.jsx
<add>"use strict";
<add>
<add>var HelloMessage = React.createClass({
<add> displayName: "HelloMessage",
<add>
<add> render: function render() {
<add> return React.createElement(
<add> "div",
<add> null,
<add> "Hello ",
<add> this.props.name
<add> );
<add> }
<add>});
<add>
<add>React.render(React.createElement(HelloMessage, { name: "John" }), mountNode);
<add>```
<ide>
<ide>
<ide> ### Helpful Open-Source Projects
| 1
|
Text
|
Text
|
add changelogs for url
|
c9bfa9cc0c0242bda7e14d70c370dab06f3f310d
|
<ide><path>doc/api/url.md
<ide> object.
<ide> ## url.resolve(from, to)
<ide> <!-- YAML
<ide> added: v0.1.25
<add>changes:
<add> - version: v6.6.0
<add> pr-url: https://github.com/nodejs/node/pull/8215
<add> description: The `auth` fields are now kept intact when `from` and `to`
<add> refer to the same host.
<add> - version: v6.5.0, v4.6.2
<add> pr-url: https://github.com/nodejs/node/pull/8214
<add> description: The `port` field is copied correctly now.
<add> - version: v6.0.0
<add> pr-url: https://github.com/nodejs/node/pull/1480
<add> description: The `auth` fields is cleared now the `to` parameter
<add> contains a hostname.
<ide> -->
<ide>
<ide> * `from` {String} The Base URL being resolved against.
| 1
|
PHP
|
PHP
|
fix inflection when baking models
|
205ad14aa866241c9ed2b976198566a588f273b4
|
<ide><path>src/Core/ConventionsTrait.php
<ide> protected function _modelKey($name) {
<ide> */
<ide> protected function _modelNameFromKey($key) {
<ide> $key = str_replace('_id', '', $key);
<del> return Inflector::pluralize(Inflector::classify($key));
<add> return Inflector::classify(Inflector::pluralize($key));
<ide> }
<ide>
<ide> /**
| 1
|
Ruby
|
Ruby
|
determine version from a formula instance
|
016a508c7a8a1456a52a32ad4330d811d1a043aa
|
<ide><path>Library/Homebrew/cmd/versions.rb
<ide> require 'formula'
<ide>
<ide> module Homebrew extend self
<del>
<del> module Versions
<del> # yields version, sha for all versions in the git history
<del> def self.old_versions f
<del> yielded = []
<del> f.rev_list.each do |sha|
<del> version = f.version_for_sha sha
<del> unless yielded.include? version or version.nil?
<del> yield version, sha
<del> yielded << version
<del> end
<del> end
<del> end
<del> end
<del>
<ide> def versions
<ide> raise "Please `brew install git` first" unless system "/usr/bin/which -s git"
<ide>
<ide> ARGV.formulae.all? do |f|
<del> old_versions = Versions.old_versions f do |version, sha|
<add> f.versions do |version, sha|
<ide> print Tty.white
<ide> print "#{version.ljust(8)} "
<ide> print Tty.reset
<ide> puts "git checkout #{sha} #{f.pretty_relative_path}"
<ide> end
<ide> end
<ide> end
<del>
<ide> end
<ide>
<ide>
<ide> class Formula
<del> def rev_list
<del> Dir.chdir HOMEBREW_REPOSITORY do
<del> `git rev-list --abbrev-commit HEAD Library/Formula/#{name}.rb`.split
<add> def versions
<add> versions = []
<add> rev_list.each do |sha|
<add> version = version_for_sha sha
<add> unless versions.include? version or version.nil?
<add> yield version, sha if block_given?
<add> versions << version
<add> end
<ide> end
<add> return versions
<ide> end
<ide>
<del> def sha_for_version version
<del> revlist.find{ |sha| version == version_for(sha) }
<add> def pretty_relative_path
<add> if Pathname.pwd == HOMEBREW_REPOSITORY
<add> "Library/Formula/#{name}.rb"
<add> else
<add> "#{HOMEBREW_REPOSITORY}/Library/Formula/#{name}.rb"
<add> end
<ide> end
<ide>
<del> def version_for_sha sha
<del> # TODO really we should open a new ruby instance and parse the formula
<del> # class and then get the version but this would be too slow (?)
<del>
<del> code = Dir.chdir(HOMEBREW_REPOSITORY) do
<del> `git show #{sha}:Library/Formula/#{name}.rb`
<add> private
<add> def rev_list
<add> HOMEBREW_REPOSITORY.cd do
<add> `git rev-list --abbrev-commit HEAD -- Library/Formula/#{name}.rb`.split
<add> end
<ide> end
<ide>
<del> version = code.match(/class #{Formula.class_s name} < ?Formula.*?(?:version\s|@version\s*=)\s*(?:'|")(.+?)(?:'|").*?end\s/m)
<del> return version[1] unless version.nil?
<del>
<del> url = code.match(/class #{Formula.class_s name} < ?Formula.*?(?:url\s|@url\s*=)\s*(?:'|")(.+?)(?:'|").*?end\s/m)
<del> unless url.nil?
<del> version = Pathname.new(url[1]).version
<del> return version unless version.to_s.empty?
<add> def text_from_sha sha
<add> HOMEBREW_REPOSITORY.cd do
<add> `git cat-file blob #{sha}:Library/Formula/#{name}.rb`
<add> end
<ide> end
<ide>
<del> head = code.match(/class #{Formula.class_s name} < ?Formula.*?head\s'(.*?)'.*?end\s\s/m)
<del> return 'HEAD' unless head.nil?
<del>
<del> opoo "Version of #{name} could not be determined for #{sha}."
<del> end
<add> def sha_for_version version
<add> rev_list.find{ |sha| version == version_for_sha(sha) }
<add> end
<ide>
<del> def pretty_relative_path
<del> if Pathname.pwd == HOMEBREW_REPOSITORY
<del> "Library/Formula/#{name}.rb"
<del> else
<del> "#{HOMEBREW_REPOSITORY}/Library/Formula/#{name}.rb"
<add> def version_for_sha sha
<add> begin
<add> version = mktemp do
<add> path = Pathname.new(Pathname.pwd+"#{name}.rb")
<add> path.write text_from_sha(sha)
<add> Formula.factory(path).version
<add> end
<add> rescue
<add> opoo "Version of #{name} could not be determined for #{sha}."
<add> end
<ide> end
<del> end
<ide> end
| 1
|
PHP
|
PHP
|
use hmac for digest nonces
|
82ac89808d2eaee97fee19197f9e96d5c544fcec
|
<ide><path>src/Auth/DigestAuthenticate.php
<ide> use Cake\Controller\ComponentRegistry;
<ide> use Cake\Core\Configure;
<ide> use Cake\Http\ServerRequest;
<add>use Cake\Utility\Security;
<ide>
<ide> /**
<ide> * Digest Authentication adapter for AuthComponent.
<ide> public function loginHeaders(ServerRequest $request)
<ide> protected function generateNonce()
<ide> {
<ide> $expiryTime = microtime(true) + $this->getConfig('nonceLifetime');
<del> $signatureValue = md5($expiryTime . ':' . $this->getConfig('secret'));
<add> $signatureValue = hash_hmac('sha256', $expiryTime . ':' . $this->getConfig('secret'), Security::getSalt());
<ide> $nonceValue = $expiryTime . ':' . $signatureValue;
<ide>
<ide> return base64_encode($nonceValue);
<ide> protected function validNonce($nonce)
<ide> if ($expires < microtime(true)) {
<ide> return false;
<ide> }
<add> $check = hash_hmac('sha1', $expires . ':' . $this->getConfig('secret'), $this->getConfig('secret'));
<ide>
<del> return md5($expires . ':' . $this->getConfig('secret')) === $checksum;
<add> return hash_equals($check, $checksum);
<ide> }
<ide> }
<ide><path>tests/TestCase/Auth/DigestAuthenticateTest.php
<ide> protected function generateNonce($secret = null, $expires = 300, $time = null)
<ide> $secret = $secret ?: Configure::read('Security.salt');
<ide> $time = $time ?: microtime(true);
<ide> $expiryTime = $time + $expires;
<del> $signatureValue = md5($expiryTime . ':' . $secret);
<add> $signatureValue = hash_hmac('sha1', $expiryTime . ':' . $secret, $secret);
<ide> $nonceValue = $expiryTime . ':' . $signatureValue;
<ide>
<ide> return base64_encode($nonceValue);
| 2
|
Python
|
Python
|
fix mypy in providers/aws/hooks
|
341b461e4fbd9ae5961ef9448c8f08e1686ee5e4
|
<ide><path>airflow/providers/amazon/aws/hooks/athena.py
<ide> def get_output_location(self, query_execution_id: str) -> str:
<ide> except KeyError:
<ide> self.log.error("Error retrieving OutputLocation")
<ide> raise
<add> else:
<add> raise
<ide> else:
<ide> raise ValueError("Invalid Query execution id")
<ide>
<ide><path>airflow/providers/amazon/aws/hooks/base_aws.py
<ide> def __init__(self, conn: Connection, region_name: Optional[str], config: Config)
<ide> self.region_name = region_name
<ide> self.config = config
<ide> self.extra_config = self.conn.extra_dejson
<add>
<ide> self.basic_session: Optional[boto3.session.Session] = None
<ide> self.role_arn: Optional[str] = None
<ide>
<ide> def _create_session_with_assume_role(self, session_kwargs: Dict[str, Any]) -> bo
<ide> )
<ide> session = botocore.session.get_session()
<ide> session._credentials = credentials
<add>
<ide> if self.basic_session is None:
<ide> raise RuntimeError("The basic session should be created here!")
<add>
<ide> region_name = self.basic_session.region_name
<ide> session.set_config_variable("region", region_name)
<add>
<ide> return boto3.session.Session(botocore_session=session, **session_kwargs)
<ide>
<ide> def _refresh_credentials(self) -> Dict[str, Any]:
<ide> self.log.info('Refreshing credentials')
<ide> assume_role_method = self.extra_config.get('assume_role_method', 'assume_role')
<ide> sts_session = self.basic_session
<add>
<add> if sts_session is None:
<add> raise RuntimeError(
<add> "Session should be initialized when refresh credentials with assume_role is used!"
<add> )
<add>
<add> sts_client = sts_session.client("sts", config=self.config)
<add>
<ide> if assume_role_method == 'assume_role':
<del> if sts_session is None:
<del> raise RuntimeError(
<del> "Session should be initialized when refresh credentials with assume_role is used!"
<del> )
<del> sts_client = sts_session.client("sts", config=self.config)
<ide> sts_response = self._assume_role(sts_client=sts_client)
<ide> elif assume_role_method == 'assume_role_with_saml':
<del> if sts_session is None:
<del> raise RuntimeError(
<del> "Session should be initialized when refresh "
<del> "credentials with assume_role_with_saml is used!"
<del> )
<del> sts_client = sts_session.client("sts", config=self.config)
<ide> sts_response = self._assume_role_with_saml(sts_client=sts_client)
<ide> else:
<ide> raise NotImplementedError(f'assume_role_method={assume_role_method} not expected')
<ide><path>airflow/providers/amazon/aws/hooks/ec2.py
<ide>
<ide> import functools
<ide> import time
<add>from typing import List, Optional
<ide>
<ide> from airflow.exceptions import AirflowException
<ide> from airflow.providers.amazon.aws.hooks.base_aws import AwsBaseHook
<ide> def __init__(self, api_type="resource_type", *args, **kwargs) -> None:
<ide>
<ide> super().__init__(*args, **kwargs)
<ide>
<del> def get_instance(self, instance_id: str, filters: list = None):
<add> def get_instance(self, instance_id: str, filters: Optional[List] = None):
<ide> """
<ide> Get EC2 instance by id and return it.
<ide>
<ide> def terminate_instances(self, instance_ids: list) -> dict:
<ide> return self.conn.terminate_instances(InstanceIds=instance_ids)
<ide>
<ide> @only_client_type
<del> def describe_instances(self, filters: list = None, instance_ids: list = None):
<add> def describe_instances(self, filters: Optional[List] = None, instance_ids: Optional[List] = None):
<ide> """
<ide> Describe EC2 instances, optionally applying filters and selective instance ids
<ide>
<ide> def describe_instances(self, filters: list = None, instance_ids: list = None):
<ide> return self.conn.describe_instances(Filters=filters, InstanceIds=instance_ids)
<ide>
<ide> @only_client_type
<del> def get_instances(self, filters: list = None, instance_ids: list = None) -> list:
<add> def get_instances(self, filters: Optional[List] = None, instance_ids: Optional[List] = None) -> list:
<ide> """
<ide> Get list of instance details, optionally applying filters and selective instance ids
<ide>
<ide> def get_instances(self, filters: list = None, instance_ids: list = None) -> list
<ide> ]
<ide>
<ide> @only_client_type
<del> def get_instance_ids(self, filters: list = None) -> list:
<add> def get_instance_ids(self, filters: Optional[List] = None) -> list:
<ide> """
<ide> Get list of instance ids, optionally applying filters to fetch selective instances
<ide>
<ide><path>airflow/providers/amazon/aws/hooks/eks.py
<ide> def get_cluster_state(self, clusterName: str) -> ClusterStates:
<ide> except ClientError as ex:
<ide> if ex.response.get("Error").get("Code") == "ResourceNotFoundException":
<ide> return ClusterStates.NONEXISTENT
<add> raise
<ide>
<ide> def get_fargate_profile_state(self, clusterName: str, fargateProfileName: str) -> FargateProfileStates:
<ide> """
<ide> def get_fargate_profile_state(self, clusterName: str, fargateProfileName: str) -
<ide> except ClientError as ex:
<ide> if ex.response.get("Error").get("Code") == "ResourceNotFoundException":
<ide> return FargateProfileStates.NONEXISTENT
<add> raise
<ide>
<ide> def get_nodegroup_state(self, clusterName: str, nodegroupName: str) -> NodegroupStates:
<ide> """
<ide> def get_nodegroup_state(self, clusterName: str, nodegroupName: str) -> Nodegroup
<ide> except ClientError as ex:
<ide> if ex.response.get("Error").get("Code") == "ResourceNotFoundException":
<ide> return NodegroupStates.NONEXISTENT
<add> raise
<ide>
<ide> def list_clusters(
<ide> self,
<ide> def _list_all(self, api_call: Callable, response_key: str, verbose: bool) -> Lis
<ide> :return: A List of the combined results of the provided API call.
<ide> :rtype: List
<ide> """
<del> name_collection = []
<add> name_collection: List = []
<ide> token = DEFAULT_PAGINATION_TOKEN
<ide>
<ide> while token is not None:
<ide><path>airflow/providers/amazon/aws/hooks/emr.py
<ide> class EmrContainerHook(AwsBaseHook):
<ide> )
<ide> SUCCESS_STATES = ("COMPLETED",)
<ide>
<del> def __init__(self, *args: Any, virtual_cluster_id: str = None, **kwargs: Any) -> None:
<add> def __init__(self, *args: Any, virtual_cluster_id: Optional[str] = None, **kwargs: Any) -> None:
<ide> super().__init__(client_type="emr-containers", *args, **kwargs) # type: ignore
<ide> self.virtual_cluster_id = virtual_cluster_id
<ide>
| 5
|
Javascript
|
Javascript
|
maintain order of timer callbacks
|
9dac1651604ee44ef99672107d8ad0286583400e
|
<ide><path>lib/timers.js
<ide> function TimersList(msecs, unrefed) {
<ide> this._timer = new TimerWrap();
<ide> this._unrefed = unrefed;
<ide> this.msecs = msecs;
<add> this.nextTick = false;
<ide> }
<ide>
<ide> function listOnTimeout() {
<ide> var list = this._list;
<ide> var msecs = list.msecs;
<ide>
<add> if (list.nextTick) {
<add> list.nextTick = false;
<add> process.nextTick(listOnTimeoutNT, list);
<add> return;
<add> }
<add>
<ide> debug('timeout callback %d', msecs);
<ide>
<ide> var now = TimerWrap.now();
<ide> function tryOnTimeout(timer, list) {
<ide> } finally {
<ide> if (!threw) return;
<ide>
<add> // Postpone all later list events to next tick. We need to do this
<add> // so that the events are called in the order they were created.
<add> const lists = list._unrefed === true ? unrefedLists : refedLists;
<add> for (var key in lists) {
<add> if (key > list.msecs) {
<add> lists[key].nextTick = true;
<add> }
<add> }
<ide> // We need to continue processing after domain error handling
<ide> // is complete, but not by using whatever domain was left over
<ide> // when the timeout threw its exception.
<ide><path>test/parallel/test-domain-timers-uncaught-exception.js
<add>'use strict';
<add>const common = require('../common');
<add>
<add>// This test ensures that the timer callbacks are called in the order in which
<add>// they were created in the event of an unhandled exception in the domain.
<add>
<add>const domain = require('domain').create();
<add>const assert = require('assert');
<add>
<add>let first = false;
<add>
<add>domain.run(function() {
<add> setTimeout(() => { throw new Error('FAIL'); }, 1);
<add> setTimeout(() => { first = true; }, 1);
<add> setTimeout(() => { assert.strictEqual(first, true); }, 2);
<add>
<add> // Ensure that 2 ms have really passed
<add> let i = 1e6;
<add> while (i--);
<add>});
<add>
<add>domain.once('error', common.mustCall((err) => {
<add> assert(err);
<add> assert.strictEqual(err.message, 'FAIL');
<add>}));
| 2
|
PHP
|
PHP
|
support collection#countby($key)
|
5682bdbc2a14cd982c50981dadfe0df4634084da
|
<ide><path>src/Illuminate/Support/LazyCollection.php
<ide> public function crossJoin(...$arrays)
<ide> */
<ide> public function countBy($countBy = null)
<ide> {
<del> if (is_null($countBy)) {
<del> $countBy = $this->identity();
<del> }
<add> $countBy = is_null($countBy)
<add> ? $this->identity()
<add> : $this->valueRetriever($countBy);
<ide>
<ide> return new static(function () use ($countBy) {
<ide> $counts = [];
<ide><path>tests/Support/SupportCollectionTest.php
<ide> public function testCountable($collection)
<ide> /**
<ide> * @dataProvider collectionClassProvider
<ide> */
<del> public function testCountableByWithoutPredicate($collection)
<add> public function testCountByStandalone($collection)
<ide> {
<ide> $c = new $collection(['foo', 'foo', 'foo', 'bar', 'bar', 'foobar']);
<ide> $this->assertEquals(['foo' => 3, 'bar' => 2, 'foobar' => 1], $c->countBy()->all());
<ide> public function testCountableByWithoutPredicate($collection)
<ide> /**
<ide> * @dataProvider collectionClassProvider
<ide> */
<del> public function testCountableByWithPredicate($collection)
<add> public function testCountByWithKey($collection)
<add> {
<add> $c = new $collection([
<add> ['key' => 'a'], ['key' => 'a'], ['key' => 'a'], ['key' => 'a'],
<add> ['key' => 'b'], ['key' => 'b'], ['key' => 'b'],
<add> ]);
<add> $this->assertEquals(['a' => 4, 'b' => 3], $c->countBy('key')->all());
<add> }
<add>
<add> /**
<add> * @dataProvider collectionClassProvider
<add> */
<add> public function testCountableByWithCallback($collection)
<ide> {
<ide> $c = new $collection(['alice', 'aaron', 'bob', 'carla']);
<ide> $this->assertEquals(['a' => 2, 'b' => 1, 'c' => 1], $c->countBy(function ($name) {
| 2
|
Ruby
|
Ruby
|
connect 1.105 (migrate from boneyard)
|
b896629da40177a1a9c6c0c6ed05889110fef817
|
<ide><path>Library/Homebrew/tap_migrations.rb
<ide> "clusterit" => "homebrew/x11",
<ide> "cmucl" => "homebrew/binary",
<ide> "comparepdf" => "homebrew/boneyard",
<del> "connect" => "homebrew/boneyard",
<ide> "coremod" => "homebrew/boneyard",
<ide> "curlftpfs" => "homebrew/x11",
<ide> "cwm" => "homebrew/x11",
| 1
|
Javascript
|
Javascript
|
use promise to update head (#574)
|
f7ee50323daa65b4d14a3398507b56b3a032674a
|
<ide><path>client/head-manager.js
<ide> const DOMAttributeNames = {
<ide>
<ide> export default class HeadManager {
<ide> constructor () {
<del> this.requestId = null
<add> this.updatePromise = null
<ide> }
<ide>
<ide> updateHead (head) {
<del> // perform batch update
<del> window.cancelAnimationFrame(this.requestId)
<del> this.requestId = window.requestAnimationFrame(() => {
<del> this.requestId = null
<add> const promise = this.updatePromise = Promise.resolve().then(() => {
<add> if (promise !== this.updatePromise) return
<add>
<add> this.updatePromise = null
<ide> this.doUpdateHead(head)
<ide> })
<ide> }
| 1
|
Python
|
Python
|
add new import paths to mnist_tpu.py
|
cb1567e87cd92ab0394a0f7b0d5c1cb226a2cbde
|
<ide><path>official/mnist/mnist_tpu.py
<ide> from __future__ import division
<ide> from __future__ import print_function
<ide>
<add>import os
<add>import sys
<add>
<ide> import tensorflow as tf # pylint: disable=g-bad-import-order
<ide>
<del>from official.mnist import dataset
<del>from official.mnist import mnist
<add># For open source environment, add grandparent directory for import
<add>sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(sys.path[0]))))
<add>
<add>from official.mnist import dataset # pylint: disable=wrong-import-position
<add>from official.mnist import mnist # pylint: disable=wrong-import-position
<ide>
<ide> # Cloud TPU Cluster Resolver flags
<ide> tf.flags.DEFINE_string(
| 1
|
Text
|
Text
|
fix some syntax highlighting
|
a86640b309e8881e10cef9ac1150eff78308c6ce
|
<ide><path>docs/deployment.md
<ide> You can link your project in [GitHub](https://zeit.co/new), [GitLab](https://zei
<ide>
<ide> You can install the command line tool using npm:
<ide>
<del>```
<add>```bash
<ide> npm install -g now
<ide> ```
<ide>
<ide> You can deploy your application by running the following command in the root of the project directory:
<ide>
<del>```
<add>```bash
<ide> now
<ide> ```
<ide>
| 1
|
Javascript
|
Javascript
|
improve examples and explanations
|
3eb2fbf74533639a376c572d4aad767e80d2c209
|
<ide><path>src/auto/injector.js
<ide> function annotate(fn) {
<ide> * a service. The Provider can have additional methods which would allow for configuration of the provider.
<ide> *
<ide> * <pre>
<del> * function GreetProvider() {
<del> * var salutation = 'Hello';
<del> *
<del> * this.salutation = function(text) {
<del> * salutation = text;
<del> * };
<del> *
<del> * this.$get = function() {
<del> * return function (name) {
<del> * return salutation + ' ' + name + '!';
<add> * function TrackingProvider() {
<add> * this.$get = function($http) {
<add> * var observed = {};
<add> * return {
<add> * event: function(event) {
<add> * var current = observed[event];
<add> * return observed[event] = current ? current + 1 : 1;
<add> * },
<add> * save: function() {
<add> * $http.post("/track",observed);
<add> * }
<ide> * };
<ide> * };
<ide> * }
<ide> *
<del> * describe('Greeter', function(){
<del> *
<add> * describe('Tracking', function() {
<add> * var mocked;
<ide> * beforeEach(module(function($provide) {
<del> * $provide.provider('greet', GreetProvider);
<add> * $provide.provider('tracking', TrackingProvider);
<add> * mocked = {post: jasmine.createSpy('postSpy')};
<add> * $provide.value('$http',mocked);
<ide> * }));
<del> *
<del> * it('should greet', inject(function(greet) {
<del> * expect(greet('angular')).toEqual('Hello angular!');
<add> * it('allows events to be tracked', inject(function(tracking) {
<add> * expect(tracking.event('login')).toEqual(1);
<add> * expect(tracking.event('login')).toEqual(2);
<ide> * }));
<ide> *
<del> * it('should allow configuration of salutation', function() {
<del> * module(function(greetProvider) {
<del> * greetProvider.salutation('Ahoj');
<del> * });
<del> * inject(function(greet) {
<del> * expect(greet('angular')).toEqual('Ahoj angular!');
<del> * });
<del> * });
<add> * it('posts to save', inject(function(tracking) {
<add> * tracking.save();
<add> * expect(mocked.post.callCount).toEqual(1);
<add> * }));
<add> * });
<ide> * </pre>
<add> *
<add> * There are also shorthand methods to define services that don't need to be configured beyond their `$get()` method.
<add> *
<add> * `service()` registers a constructor function which will be invoked with `new` to create the instance. You can specify services that will be provided by the injector.
<add> *
<add> * <pre>
<add> * function TrackingProvider($http) {
<add> * var observed = {};
<add> * this.event = function(event) {
<add> * var current = observed[event];
<add> * return observed[event] = current ? current + 1 : 1;
<add> * };
<add> * this.save = function() {
<add> * $http.post("/track",observed);
<add> * };
<add> * }
<add> * $provider.service('tracking',TrackingProvider);
<add> * </pre>
<add> *
<add> * `factory()` registers a function whose return value is the instance. Again, you can specify services that will be provided by the injector.
<add> *
<add> * <pre>
<add> * function TrackingProvider($http) {
<add> * var observed = {};
<add> * return {
<add> * event: function(event) {
<add> * var current = observed[event];
<add> * return observed[event] = current ? current + 1 : 1;
<add> * },
<add> * save: function() {
<add> * $http.post("/track",observed);
<add> * }
<add> * };
<add> * }
<add> * $provider.factory('tracking',TrackingProvider);
<add> * </pre>
<add> *
<ide> */
<ide>
<ide> /**
<ide> function annotate(fn) {
<ide> * @methodOf AUTO.$provide
<ide> * @description
<ide> *
<del> * A short hand for configuring services if only `$get` method is required.
<add> * A service whose instance is the return value of `$getFn`. Short hand for configuring services if only `$get` method is required.
<ide> *
<ide> * @param {string} name The name of the instance.
<ide> * @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand for
<ide> function annotate(fn) {
<ide> * @methodOf AUTO.$provide
<ide> * @description
<ide> *
<del> * A short hand for registering service of given class.
<add> * A service whose instance is created by invoking `constructor` with `new`. A short hand for registering services which use a constructor.
<ide> *
<ide> * @param {string} name The name of the instance.
<ide> * @param {Function} constructor A class (constructor function) that will be instantiated.
<ide> function createInjector(modulesToLoad) {
<ide> };
<ide> }
<ide> }
<add>
| 1
|
PHP
|
PHP
|
add test for bindmodel + containable
|
a64099168cb05a1e3c5f4bf87ae3b8b54c2000b2
|
<ide><path>cake/tests/cases/libs/model/behaviors/containable.test.php
<ide> function testResetMultipleHabtmAssociations() {
<ide> $this->assertEqual($expected, $this->Article->hasAndBelongsToMany);
<ide> }
<ide>
<add>/**
<add> * test that bindModel and unbindModel work with find() calls in between.
<add> */
<add> function testBindMultipleTimesWithFind() {
<add> $binding = array(
<add> 'hasOne' => array(
<add> 'ArticlesTag' => array(
<add> 'foreignKey' => false,
<add> 'type' => 'INNER',
<add> 'conditions' => array(
<add> 'ArticlesTag.article_id = Article.id'
<add> )
<add> ),
<add> 'Tag' => array(
<add> 'type' => 'INNER',
<add> 'foreignKey' => false,
<add> 'conditions' => array(
<add> 'ArticlesTag.tag_id = Tag.id'
<add> )
<add> )
<add> )
<add> );
<add> $this->Article->unbindModel(array('hasAndBelongsToMany' => array('Tag')));
<add> $this->Article->bindModel($binding);
<add> $result = $this->Article->find('all', array('limit' => 1, 'contain' => array('ArticlesTag', 'Tag')));
<add>
<add> $this->Article->unbindModel(array('hasAndBelongsToMany' => array('Tag')));
<add> $this->Article->bindModel($binding);
<add> $result = $this->Article->find('all', array('limit' => 1, 'contain' => array('ArticlesTag', 'Tag')));
<add>
<add> $associated = $this->Article->getAssociated();
<add> $this->assertEqual('hasAndBelongsToMany', $associated['Tag']);
<add> $this->assertFalse(isset($associated['ArticleTag']));
<add> }
<add>
<ide> /**
<ide> * test that autoFields doesn't splice in fields from other databases.
<ide> *
| 1
|
Python
|
Python
|
add aspp for kerascv
|
bc7c670f85c24c9baadafac2e5eba6c07b901a35
|
<ide><path>official/vision/keras_cv/__init__.py
<ide> # ==============================================================================
<ide> """Keras-CV package definition."""
<ide> # pylint: disable=wildcard-import
<add>from official.vision.keras_cv import layers
<ide> from official.vision.keras_cv import losses
<ide> from official.vision.keras_cv import ops
<ide><path>official/vision/keras_cv/layers/__init__.py
<add># Copyright 2020 The TensorFlow Authors. All Rights Reserved.
<add>#
<add># Licensed under the Apache License, Version 2.0 (the "License");
<add># you may not use this file except in compliance with the License.
<add># You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing, software
<add># distributed under the License is distributed on an "AS IS" BASIS,
<add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add># See the License for the specific language governing permissions and
<add># limitations under the License.
<add># ==============================================================================
<add>"""Keras-CV layers package definition."""
<add>from official.vision.keras_cv.layers.deeplab import ASPP
<ide><path>official/vision/keras_cv/layers/deeplab.py
<add># Copyright 2020 The TensorFlow Authors. All Rights Reserved.
<add>#
<add># Licensed under the Apache License, Version 2.0 (the "License");
<add># you may not use this file except in compliance with the License.
<add># You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing, software
<add># distributed under the License is distributed on an "AS IS" BASIS,
<add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add># See the License for the specific language governing permissions and
<add># limitations under the License.
<add># ==============================================================================
<add>"""Layers for DeepLabV3."""
<add>
<add>import tensorflow as tf
<add>
<add>
<add>@tf.keras.utils.register_keras_serializable(package='keras_cv')
<add>class ASPP(tf.keras.layers.Layer):
<add> """Implements the Atrous Spatial Pyramid Pooling.
<add>
<add> Reference:
<add> [Rethinking Atrous Convolution for Semantic Image Segmentation](
<add> https://arxiv.org/pdf/1706.05587.pdf)
<add> """
<add>
<add> def __init__(
<add> self,
<add> output_channels,
<add> dilation_rates,
<add> batchnorm_momentum=0.99,
<add> dropout=0.5,
<add> kernel_initializer='glorot_uniform',
<add> kernel_regularizer=None,
<add> interpolation='bilinear',
<add> **kwargs):
<add> """Initializes `ASPP`.
<add>
<add> Arguments:
<add> output_channels: Number of channels produced by ASPP.
<add> dilation_rates: A list of integers for parallel dilated conv.
<add> batchnorm_momentum: A float for the momentum in BatchNorm. Defaults to
<add> 0.99.
<add> dropout: A float for the dropout rate before output. Defaults to 0.5.
<add> kernel_initializer: Kernel initializer for conv layers. Defaults to
<add> `glorot_uniform`.
<add> kernel_regularizer: Kernel regularizer for conv layers. Defaults to None.
<add> interpolation: The interpolation method for upsampling. Defaults to
<add> `bilinear`.
<add> **kwargs: Other keyword arguments for the layer.
<add> """
<add> super(ASPP, self).__init__(**kwargs)
<add>
<add> self.output_channels = output_channels
<add> self.dilation_rates = dilation_rates
<add> self.batchnorm_momentum = batchnorm_momentum
<add> self.dropout = dropout
<add> self.kernel_initializer = tf.keras.initializers.get(kernel_initializer)
<add> self.kernel_regularizer = tf.keras.regularizers.get(kernel_regularizer)
<add> self.interpolation = interpolation
<add> self.input_spec = tf.keras.layers.InputSpec(ndim=4)
<add>
<add> def build(self, input_shape):
<add> height = input_shape[1]
<add> width = input_shape[2]
<add> channels = input_shape[3]
<add>
<add> self.aspp_layers = []
<add>
<add> conv_sequential = tf.keras.Sequential([
<add> tf.keras.layers.Conv2D(
<add> filters=self.output_channels, kernel_size=(1, 1),
<add> kernel_initializer=self.kernel_initializer,
<add> kernel_regularizer=self.kernel_regularizer, use_bias=False),
<add> tf.keras.layers.BatchNormalization(momentum=self.batchnorm_momentum),
<add> tf.keras.layers.Activation('relu')])
<add> self.aspp_layers.append(conv_sequential)
<add>
<add> for dilation_rate in self.dilation_rates:
<add> conv_sequential = tf.keras.Sequential([
<add> tf.keras.layers.Conv2D(
<add> filters=self.output_channels, kernel_size=(3, 3),
<add> padding='same', kernel_regularizer=self.kernel_regularizer,
<add> kernel_initializer=self.kernel_initializer,
<add> dilation_rate=dilation_rate, use_bias=False),
<add> tf.keras.layers.BatchNormalization(momentum=self.batchnorm_momentum),
<add> tf.keras.layers.Activation('relu')])
<add> self.aspp_layers.append(conv_sequential)
<add>
<add> pool_sequential = tf.keras.Sequential([
<add> tf.keras.layers.GlobalAveragePooling2D(),
<add> tf.keras.layers.Reshape((1, 1, channels)),
<add> tf.keras.layers.Conv2D(
<add> filters=self.output_channels, kernel_size=(1, 1),
<add> kernel_initializer=self.kernel_initializer,
<add> kernel_regularizer=self.kernel_regularizer, use_bias=False),
<add> tf.keras.layers.BatchNormalization(momentum=self.batchnorm_momentum),
<add> tf.keras.layers.Activation('relu'),
<add> tf.keras.layers.experimental.preprocessing.Resizing(
<add> height, width, interpolation=self.interpolation)])
<add> self.aspp_layers.append(pool_sequential)
<add>
<add> self.projection = tf.keras.Sequential([
<add> tf.keras.layers.Conv2D(
<add> filters=self.output_channels, kernel_size=(1, 1),
<add> kernel_initializer=self.kernel_initializer,
<add> kernel_regularizer=self.kernel_regularizer, use_bias=False),
<add> tf.keras.layers.BatchNormalization(momentum=self.batchnorm_momentum),
<add> tf.keras.layers.Activation('relu'),
<add> tf.keras.layers.Dropout(rate=self.dropout)])
<add>
<add> def call(self, inputs, training=None):
<add> if training is None:
<add> training = tf.keras.backend.learning_phase()
<add> result = []
<add> for layer in self.aspp_layers:
<add> result.append(layer(inputs, training=training))
<add> result = tf.concat(result, axis=-1)
<add> result = self.projection(result, training=training)
<add> return result
<add>
<add> def get_config(self):
<add> config = {
<add> 'output_channels': self.output_channels,
<add> 'dilation_rates': self.dilation_rates,
<add> 'batchnorm_momentum': self.batchnorm_momentum,
<add> 'dropout': self.dropout,
<add> 'kernel_initializer': tf.keras.initializers.serialize(
<add> self.kernel_initializer),
<add> 'kernel_regularizer': tf.keras.regularizers.serialize(
<add> self.kernel_regularizer),
<add> 'interpolation': self.interpolation,
<add> }
<add> base_config = super(ASPP, self).get_config()
<add> return dict(list(base_config.items()) + list(config.items()))
<ide><path>official/vision/keras_cv/layers/deeplab_test.py
<add># Copyright 2020 The TensorFlow Authors. All Rights Reserved.
<add>#
<add># Licensed under the Apache License, Version 2.0 (the "License");
<add># you may not use this file except in compliance with the License.
<add># You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing, software
<add># distributed under the License is distributed on an "AS IS" BASIS,
<add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add># See the License for the specific language governing permissions and
<add># limitations under the License.
<add># ==============================================================================
<add>"""Tests for ASPP."""
<add>
<add>import tensorflow as tf
<add>
<add>from tensorflow.python.keras import keras_parameterized
<add>from official.vision.keras_cv.layers import deeplab
<add>
<add>
<add>@keras_parameterized.run_all_keras_modes
<add>class DeeplabTest(keras_parameterized.TestCase):
<add>
<add> def test_aspp(self):
<add> inputs = tf.keras.Input(shape=(64, 64, 128), dtype=tf.float32)
<add> layer = deeplab.ASPP(output_channels=256, dilation_rates=[6, 12, 18])
<add> output = layer(inputs)
<add> self.assertAllEqual([None, 64, 64, 256], output.shape)
<add>
<add> def test_aspp_invalid_shape(self):
<add> inputs = tf.keras.Input(shape=(64, 64), dtype=tf.float32)
<add> layer = deeplab.ASPP(output_channels=256, dilation_rates=[6, 12, 18])
<add> with self.assertRaises(ValueError):
<add> _ = layer(inputs)
<add>
<add> def test_config_with_custom_name(self):
<add> layer = deeplab.ASPP(256, [5], name='aspp')
<add> config = layer.get_config()
<add> layer_1 = deeplab.ASPP.from_config(config)
<add> self.assertEqual(layer_1.name, layer.name)
<add>
<add>
<add>if __name__ == '__main__':
<add> tf.test.main()
| 4
|
Javascript
|
Javascript
|
replace fixturesdir with fixtures module
|
5e93df684052bde146992bce4898e6d583345bb3
|
<ide><path>test/parallel/test-repl-syntax-error-stack.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>const fixtures = require('../common/fixtures');
<ide> const assert = require('assert');
<del>const path = require('path');
<ide> const repl = require('repl');
<ide> let found = false;
<ide>
<ide> common.ArrayStream.prototype.write = function(output) {
<ide>
<ide> const putIn = new common.ArrayStream();
<ide> repl.start('', putIn);
<del>let file = path.join(common.fixturesDir, 'syntax', 'bad_syntax');
<add>let file = fixtures.path('syntax', 'bad_syntax');
<ide>
<ide> if (common.isWindows)
<ide> file = file.replace(/\\/g, '\\\\');
| 1
|
Go
|
Go
|
add daemon options required by buildkit tests
|
b96a0c775400821d80972619fbfe6a2070f3e9ba
|
<ide><path>testutil/daemon/daemon.go
<ide> type nopLog struct{}
<ide>
<ide> func (nopLog) Logf(string, ...interface{}) {}
<ide>
<del>const defaultDockerdBinary = "dockerd"
<del>const containerdSocket = "/var/run/docker/containerd/containerd.sock"
<add>const (
<add> defaultDockerdBinary = "dockerd"
<add> defaultContainerdSocket = "/var/run/docker/containerd/containerd.sock"
<add>)
<ide>
<ide> var errDaemonNotStarted = errors.New("daemon not started")
<ide>
<ide> type Daemon struct {
<ide> log LogT
<ide> pidFile string
<ide> args []string
<add> containerdSocket string
<ide>
<ide> // swarm related field
<ide> swarmListenAddr string
<ide> func NewDaemon(workingDir string, ops ...Option) (*Daemon, error) {
<ide> storageDriver: storageDriver,
<ide> userlandProxy: userlandProxy,
<ide> // dxr stands for docker-execroot (shortened for avoiding unix(7) path length limitation)
<del> execRoot: filepath.Join(os.TempDir(), "dxr", id),
<del> dockerdBinary: defaultDockerdBinary,
<del> swarmListenAddr: defaultSwarmListenAddr,
<del> SwarmPort: DefaultSwarmPort,
<del> log: nopLog{},
<add> execRoot: filepath.Join(os.TempDir(), "dxr", id),
<add> dockerdBinary: defaultDockerdBinary,
<add> swarmListenAddr: defaultSwarmListenAddr,
<add> SwarmPort: DefaultSwarmPort,
<add> log: nopLog{},
<add> containerdSocket: defaultContainerdSocket,
<ide> }
<ide>
<ide> for _, op := range ops {
<ide> func (d *Daemon) StartWithLogFile(out *os.File, providedArgs ...string) error {
<ide> d.pidFile = filepath.Join(d.Folder, "docker.pid")
<ide> }
<ide>
<del> d.args = append(d.GlobalFlags,
<del> "--containerd", containerdSocket,
<del> "--data-root", d.Root,
<add> d.args = append(d.GlobalFlags, "--data-root", d.Root)
<add> if d.containerdSocket != "" {
<add> d.args = append(d.args, "--containerd", d.containerdSocket)
<add> }
<add> d.args = append(d.args,
<ide> "--exec-root", d.execRoot,
<ide> "--pidfile", d.pidFile,
<ide> fmt.Sprintf("--userland-proxy=%t", d.userlandProxy),
<ide> "--containerd-namespace", d.id,
<ide> "--containerd-plugins-namespace", d.id+"p",
<ide> )
<add>
<ide> if d.defaultCgroupNamespaceMode != "" {
<del> d.args = append(d.args, []string{"--default-cgroupns-mode", d.defaultCgroupNamespaceMode}...)
<add> d.args = append(d.args, "--default-cgroupns-mode", d.defaultCgroupNamespaceMode)
<ide> }
<ide> if d.experimental {
<ide> d.args = append(d.args, "--experimental")
<ide> func (d *Daemon) StartWithLogFile(out *os.File, providedArgs ...string) error {
<ide> d.args = append(d.args, "--init")
<ide> }
<ide> if !(d.UseDefaultHost || d.UseDefaultTLSHost) {
<del> d.args = append(d.args, []string{"--host", d.Sock()}...)
<add> d.args = append(d.args, "--host", d.Sock())
<ide> }
<ide> if root := os.Getenv("DOCKER_REMAP_ROOT"); root != "" {
<del> d.args = append(d.args, []string{"--userns-remap", root}...)
<add> d.args = append(d.args, "--userns-remap", root)
<ide> }
<ide>
<ide> // If we don't explicitly set the log-level or debug flag(-D) then
<ide><path>testutil/daemon/ops.go
<ide> import (
<ide> // Option is used to configure a daemon.
<ide> type Option func(*Daemon)
<ide>
<add>// WithContainerdSocket sets the --containerd option on the daemon.
<add>// Use an empty string to remove the option.
<add>//
<add>// If unset the --containerd option will be used with a default value.
<add>func WithContainerdSocket(socket string) Option {
<add> return func(d *Daemon) {
<add> d.containerdSocket = socket
<add> }
<add>}
<add>
<ide> // WithDefaultCgroupNamespaceMode sets the default cgroup namespace mode for the daemon
<ide> func WithDefaultCgroupNamespaceMode(mode string) Option {
<ide> return func(d *Daemon) {
| 2
|
Ruby
|
Ruby
|
add pretoken composite
|
700b5e2738fad9aa576df25d494e1d7e69962326
|
<ide><path>Library/Homebrew/test/version_spec.rb
<ide> expect(Version.create("1.2.3beta2")).to be < Version.create("1.2.3-p34")
<ide> end
<ide>
<add> specify "comparing pre versions" do
<add> expect(Version.create("1.2.3pre9")).to be == Version.create("1.2.3PRE9")
<add> expect(Version.create("1.2.3pre9")).to be > Version.create("1.2.3pre8")
<add> expect(Version.create("1.2.3pre8")).to be < Version.create("1.2.3pre9")
<add> expect(Version.create("1.2.3pre9")).to be < Version.create("1.2.3pre10")
<add>
<add> expect(Version.create("1.2.3pre3")).to be > Version.create("1.2.3alpha2")
<add> expect(Version.create("1.2.3pre3")).to be > Version.create("1.2.3alpha4")
<add> expect(Version.create("1.2.3pre3")).to be > Version.create("1.2.3beta3")
<add> expect(Version.create("1.2.3pre3")).to be > Version.create("1.2.3beta5")
<add> expect(Version.create("1.2.3pre3")).to be < Version.create("1.2.3rc2")
<add> expect(Version.create("1.2.3pre3")).to be < Version.create("1.2.3")
<add> expect(Version.create("1.2.3pre3")).to be < Version.create("1.2.3-p2")
<add> end
<add>
<ide> specify "comparing RC versions" do
<ide> expect(Version.create("1.2.3rc3")).to be == Version.create("1.2.3RC3")
<ide> expect(Version.create("1.2.3rc3")).to be > Version.create("1.2.3rc2")
<ide><path>Library/Homebrew/version.rb
<ide> def <=>(other)
<ide> 0
<ide> when NumericToken
<ide> other.value.zero? ? 0 : -1
<del> when AlphaToken, BetaToken, RCToken
<add> when AlphaToken, BetaToken, PreToken, RCToken
<ide> 1
<ide> else
<ide> -1
<ide> def <=>(other)
<ide> case other
<ide> when AlphaToken
<ide> rev <=> other.rev
<add> when BetaToken, RCToken, PreToken, PatchToken
<add> -1
<ide> else
<ide> super
<ide> end
<ide> def <=>(other)
<ide> rev <=> other.rev
<ide> when AlphaToken
<ide> 1
<add> when PreToken, RCToken, PatchToken
<add> -1
<add> else
<add> super
<add> end
<add> end
<add> end
<add>
<add> class PreToken < CompositeToken
<add> PATTERN = /pre[0-9]*/i
<add>
<add> def <=>(other)
<add> case other
<add> when PreToken
<add> rev <=> other.rev
<add> when AlphaToken, BetaToken
<add> 1
<ide> when RCToken, PatchToken
<ide> -1
<ide> else
<ide> def <=>(other)
<ide> case other
<ide> when RCToken
<ide> rev <=> other.rev
<del> when AlphaToken, BetaToken
<add> when AlphaToken, BetaToken, PreToken
<ide> 1
<ide> when PatchToken
<ide> -1
<ide> def <=>(other)
<ide> case other
<ide> when PatchToken
<ide> rev <=> other.rev
<del> when AlphaToken, BetaToken, RCToken
<add> when AlphaToken, BetaToken, RCToken, PreToken
<ide> 1
<ide> else
<ide> super
<ide> def <=>(other)
<ide> SCAN_PATTERN = Regexp.union(
<ide> AlphaToken::PATTERN,
<ide> BetaToken::PATTERN,
<add> PreToken::PATTERN,
<ide> RCToken::PATTERN,
<ide> PatchToken::PATTERN,
<ide> NumericToken::PATTERN,
<ide> def tokenize
<ide> when /\A#{AlphaToken::PATTERN}\z/o then AlphaToken
<ide> when /\A#{BetaToken::PATTERN}\z/o then BetaToken
<ide> when /\A#{RCToken::PATTERN}\z/o then RCToken
<add> when /\A#{PreToken::PATTERN}\z/o then PreToken
<ide> when /\A#{PatchToken::PATTERN}\z/o then PatchToken
<ide> when /\A#{NumericToken::PATTERN}\z/o then NumericToken
<ide> when /\A#{StringToken::PATTERN}\z/o then StringToken
| 2
|
Ruby
|
Ruby
|
add docs for `insert_all` with scopes
|
08f3dfeaee84dd14399427abb1e44d8a391893ed
|
<ide><path>activerecord/lib/active_record/persistence.rb
<ide> def insert(attributes, returning: nil, unique_by: nil)
<ide> # { id: 1, title: "Rework", author: "David" },
<ide> # { id: 1, title: "Eloquent Ruby", author: "Russ" }
<ide> # ])
<add> #
<add> # # insert_all works on chained scopes, and you can use create_with
<add> # # to set default attributes for all inserted records.
<add> #
<add> # author.books.create_with(created_at: Time.now).insert_all([
<add> # { id: 1, title: "Rework" },
<add> # { id: 2, title: "Eloquent Ruby" }
<add> # ])
<ide> def insert_all(attributes, returning: nil, unique_by: nil)
<ide> InsertAll.new(self, attributes, on_duplicate: :skip, returning: returning, unique_by: unique_by).execute
<ide> end
| 1
|
Javascript
|
Javascript
|
add an eachcomputedproperty iterator
|
2bdc696ab6f16977336785ed4cae865263ad0423
|
<ide><path>packages/ember-runtime/lib/system/core_object.js
<ide> var ClassMixin = Ember.Mixin.create({
<ide>
<ide> ember_assert("metaForProperty() could not find a computed property with key '"+key+"'.", !!desc && desc instanceof Ember.ComputedProperty);
<ide> return desc._meta || {};
<add> },
<add>
<add> /**
<add> Iterate over each computed property for the class, passing its name
<add> and any associated metadata (see `metaForProperty`) to the callback.
<add> */
<add> eachComputedProperty: function(callback, binding) {
<add> var proto = get(this, 'proto'),
<add> descs = meta(proto).descs,
<add> empty = {},
<add> property;
<add>
<add> for (var name in descs) {
<add> property = descs[name];
<add>
<add> if (property instanceof Ember.ComputedProperty) {
<add> callback.call(binding || this, name, property._meta || empty);
<add> }
<add> }
<ide> }
<ide>
<ide> });
<ide><path>packages/ember-runtime/tests/system/object/computed_test.js
<ide> test("can retrieve metadata for a computed property", function() {
<ide> ClassWithNoMetadata.metaForProperty('staticProperty');
<ide> }, Error, "throws an error if metadata for a non-computed property is requested");
<ide> });
<add>
<add>testBoth("can iterate over a list of computed properties for a class", function(get, set) {
<add> var MyClass = Ember.Object.extend({
<add> foo: Ember.computed(function() {
<add>
<add> }),
<add>
<add> fooDidChange: Ember.observer(function() {
<add>
<add> }, 'foo'),
<add>
<add> bar: Ember.computed(function() {
<add>
<add> })
<add> });
<add>
<add> var SubClass = MyClass.extend({
<add> baz: Ember.computed(function() {
<add>
<add> })
<add> });
<add>
<add> SubClass.reopen({
<add> bat: Ember.computed(function() {
<add>
<add> }).meta({ iAmBat: true })
<add> });
<add>
<add> var list = [];
<add>
<add> MyClass.eachComputedProperty(function(name) {
<add> list.push(name);
<add> });
<add>
<add> deepEqual(list.sort(), ['bar', 'foo'], "watched and unwatched computed properties are iterated");
<add>
<add> list = [];
<add>
<add> SubClass.eachComputedProperty(function(name, meta) {
<add> list.push(name);
<add>
<add> if (name === 'bat') {
<add> deepEqual(meta, { iAmBat: true });
<add> } else {
<add> deepEqual(meta, {});
<add> }
<add> });
<add>
<add> deepEqual(list.sort(), ['bar', 'bat', 'baz', 'foo'], "all inherited properties are included");
<add>});
| 2
|
Ruby
|
Ruby
|
move some serialization stuff out of base
|
6c63f1aa44780c887dd3e52765e86588911c2802
|
<ide><path>activerecord/lib/active_record/attribute_methods/serialization.rb
<ide> module AttributeMethods
<ide> module Serialization
<ide> extend ActiveSupport::Concern
<ide>
<add> included do
<add> # Returns a hash of all the attributes that have been specified for serialization as
<add> # keys and their class restriction as values.
<add> class_attribute :serialized_attributes
<add> self.serialized_attributes = {}
<add> end
<add>
<ide> module ClassMethods
<add> # If you have an attribute that needs to be saved to the database as an object, and retrieved as the same object,
<add> # then specify the name of that attribute using this method and it will be handled automatically.
<add> # The serialization is done through YAML. If +class_name+ is specified, the serialized object must be of that
<add> # class on retrieval or SerializationTypeMismatch will be raised.
<add> #
<add> # ==== Parameters
<add> #
<add> # * +attr_name+ - The field name that should be serialized.
<add> # * +class_name+ - Optional, class name that the object type should be equal to.
<add> #
<add> # ==== Example
<add> # # Serialize a preferences attribute
<add> # class User < ActiveRecord::Base
<add> # serialize :preferences
<add> # end
<add> def serialize(attr_name, class_name = Object)
<add> coder = if [:load, :dump].all? { |x| class_name.respond_to?(x) }
<add> class_name
<add> else
<add> Coders::YAMLColumn.new(class_name)
<add> end
<add>
<add> # merge new serialized attribute and create new hash to ensure that each class in inheritance hierarchy
<add> # has its own hash of own serialized attributes
<add> self.serialized_attributes = serialized_attributes.merge(attr_name.to_s => coder)
<add> end
<add>
<ide> def define_method_attribute(attr_name)
<ide> if serialized_attributes.include?(attr_name)
<ide> generated_attribute_methods.module_eval(<<-CODE, __FILE__, __LINE__)
<ide> def cacheable_column?(column)
<ide> end
<ide> end
<ide>
<add> def set_serialized_attributes
<add> sattrs = self.class.serialized_attributes
<add>
<add> sattrs.each do |key, coder|
<add> @attributes[key] = coder.load @attributes[key] if @attributes.key?(key)
<add> end
<add> end
<add>
<ide> def type_cast_attribute(column, value)
<ide> coder = self.class.serialized_attributes[column.name]
<ide>
<ide><path>activerecord/lib/active_record/base.rb
<ide> class Base
<ide> class_attribute :default_scopes, :instance_writer => false
<ide> self.default_scopes = []
<ide>
<del> # Returns a hash of all the attributes that have been specified for serialization as
<del> # keys and their class restriction as values.
<del> class_attribute :serialized_attributes
<del> self.serialized_attributes = {}
<del>
<ide> class_attribute :_attr_readonly, :instance_writer => false
<ide> self._attr_readonly = []
<ide>
<ide> def readonly_attributes
<ide> self._attr_readonly
<ide> end
<ide>
<del> # If you have an attribute that needs to be saved to the database as an object, and retrieved as the same object,
<del> # then specify the name of that attribute using this method and it will be handled automatically.
<del> # The serialization is done through YAML. If +class_name+ is specified, the serialized object must be of that
<del> # class on retrieval or SerializationTypeMismatch will be raised.
<del> #
<del> # ==== Parameters
<del> #
<del> # * +attr_name+ - The field name that should be serialized.
<del> # * +class_name+ - Optional, class name that the object type should be equal to.
<del> #
<del> # ==== Example
<del> # # Serialize a preferences attribute
<del> # class User < ActiveRecord::Base
<del> # serialize :preferences
<del> # end
<del> def serialize(attr_name, class_name = Object)
<del> coder = if [:load, :dump].all? { |x| class_name.respond_to?(x) }
<del> class_name
<del> else
<del> Coders::YAMLColumn.new(class_name)
<del> end
<del>
<del> # merge new serialized attribute and create new hash to ensure that each class in inheritance hierarchy
<del> # has its own hash of own serialized attributes
<del> self.serialized_attributes = serialized_attributes.merge(attr_name.to_s => coder)
<del> end
<del>
<ide> def deprecated_property_setter(property, value, block) #:nodoc:
<ide> if block
<ide> ActiveSupport::Deprecation.warn(
<ide> def to_ary # :nodoc:
<ide> nil
<ide> end
<ide>
<del> def set_serialized_attributes
<del> sattrs = self.class.serialized_attributes
<del>
<del> sattrs.each do |key, coder|
<del> @attributes[key] = coder.load @attributes[key] if @attributes.key?(key)
<del> end
<del> end
<del>
<ide> # Sets the attribute used for single table inheritance to this class name if this is not the
<ide> # ActiveRecord::Base descendant.
<ide> # Considering the hierarchy Reply < Message < ActiveRecord::Base, this makes it possible to
| 2
|
Text
|
Text
|
remove unfinished sentence
|
36e35324759482744e97265e8b89768f4311cb1a
|
<ide><path>website/docs/usage/adding-languages.md
<ide> categorizer is to use the [`spacy train`](/api/cli#train) command-line utility.
<ide> In order to use this, you'll need training and evaluation data in the
<ide> [JSON format](/api/annotation#json-input) spaCy expects for training.
<ide>
<del>You can now train the model using a corpus for your language annotated with If
<del>your data is in one of the supported formats, the easiest solution might be to
<del>use the [`spacy convert`](/api/cli#convert) command-line utility. This supports
<del>several popular formats, including the IOB format for named entity recognition,
<del>the JSONL format produced by our annotation tool [Prodigy](https://prodi.gy),
<del>and the [CoNLL-U](http://universaldependencies.org/docs/format.html) format used
<del>by the [Universal Dependencies](http://universaldependencies.org/) corpus.
<add>If your data is in one of the supported formats, the easiest solution might be
<add>to use the [`spacy convert`](/api/cli#convert) command-line utility. This
<add>supports several popular formats, including the IOB format for named entity
<add>recognition, the JSONL format produced by our annotation tool
<add>[Prodigy](https://prodi.gy), and the
<add>[CoNLL-U](http://universaldependencies.org/docs/format.html) format used by the
<add>[Universal Dependencies](http://universaldependencies.org/) corpus.
<ide>
<ide> One thing to keep in mind is that spaCy expects to train its models from **whole
<ide> documents**, not just single sentences. If your corpus only contains single
| 1
|
Python
|
Python
|
fix ldap error messages when login fails
|
3e0310aa994e65d962abbcbc9e1451a0c976f676
|
<ide><path>airflow/contrib/auth/backends/ldap_auth.py
<ide> def get_ldap_connection(dn=None, password=None):
<ide>
<ide> if not conn.bind():
<ide> LOG.error("Cannot bind to ldap server: %s ", conn.last_error)
<del> raise AuthenticationError("Username or password incorrect")
<add> raise AuthenticationError("Cannot bind to ldap server")
<ide>
<ide> return conn
<ide>
<ide> def try_login(username, password):
<ide> entry = conn.response[0]
<ide>
<ide> conn.unbind()
<add>
<add> if not 'dn' in entry:
<add> # The search fitler for the user did not return any values, so an
<add> # invalid user was used for credentials.
<add> raise AuthenticationError("Invalid username or password")
<add>
<ide> try:
<ide> conn = get_ldap_connection(entry['dn'], password)
<ide> except KeyError as e:
| 1
|
PHP
|
PHP
|
make use of modifiable $options from beforemarshal
|
b9db56d90865cc3c29b71396e700f92f89091fc4
|
<ide><path>src/ORM/Marshaller.php
<ide> protected function _buildPropertyMap($options)
<ide> */
<ide> public function one(array $data, array $options = [])
<ide> {
<del> $options += ['validate' => true];
<add> list($data, $options) = $this->_prepareDataAndOptions($data, $options);
<add>
<ide> $propertyMap = $this->_buildPropertyMap($options);
<ide>
<ide> $schema = $this->_table->schema();
<ide> public function one(array $data, array $options = [])
<ide> }
<ide> }
<ide>
<del> $data = $this->_prepareData($data, $options);
<del>
<ide> $errors = $this->_validate($data, $options, true);
<ide> $primaryKey = $schema->primaryKey();
<ide> $properties = [];
<ide> protected function _validate($data, $options, $isNew)
<ide> }
<ide>
<ide> /**
<del> * Returns data prepared to validate and marshall.
<add> * Returns data and options prepared to validate and marshall.
<ide> *
<ide> * @param array $data The data to prepare.
<ide> * @param array $options The options passed to this marshaller.
<del> * @return array Prepared data.
<add> * @return array An array containing prepared data and options.
<ide> */
<del> protected function _prepareData($data, $options)
<add> protected function _prepareDataAndOptions($data, $options)
<ide> {
<del> $tableName = $this->_table->alias();
<add> $options += ['validate' => true];
<ide>
<add> $tableName = $this->_table->alias();
<ide> if (isset($data[$tableName])) {
<ide> $data = $data[$tableName];
<ide> }
<ide>
<del> $dataObject = new \ArrayObject($data);
<add> $data = new \ArrayObject($data);
<ide> $options = new \ArrayObject($options);
<del> $this->_table->dispatchEvent('Model.beforeMarshal', compact('dataObject', 'options'));
<add> $this->_table->dispatchEvent('Model.beforeMarshal', compact('data', 'options'));
<ide>
<del> return (array)$dataObject;
<add> return [(array)$data, (array)$options];
<ide> }
<ide>
<ide> /**
<ide> protected function _loadBelongsToMany($assoc, $ids)
<ide> */
<ide> public function merge(EntityInterface $entity, array $data, array $options = [])
<ide> {
<del> $options += ['validate' => true];
<add> list($data, $options) = $this->_prepareDataAndOptions($data, $options);
<add>
<ide> $propertyMap = $this->_buildPropertyMap($options);
<ide> $isNew = $entity->isNew();
<ide> $keys = [];
<ide> public function merge(EntityInterface $entity, array $data, array $options = [])
<ide> $keys = $entity->extract((array)$this->_table->primaryKey());
<ide> }
<ide>
<del> $data = $this->_prepareData($data, $options);
<del>
<ide> $errors = $this->_validate($data + $keys, $options, $isNew);
<ide> $schema = $this->_table->schema();
<ide> $properties = [];
<ide> public function merge(EntityInterface $entity, array $data, array $options = [])
<ide> $value = $converter->marshal($value);
<ide> $isObject = is_object($value);
<ide> if ((!$isObject && $original === $value) ||
<del> ($isObject && $original == $value)
<add> ($isObject && $original == $value)
<ide> ) {
<ide> continue;
<ide> }
<ide><path>tests/TestCase/ORM/MarshallerTest.php
<ide> public function testBeforeMarshalEvent()
<ide>
<ide> $marshall = new Marshaller($this->articles);
<ide>
<del> $this->articles->eventManager()->attach(function ($e, $data) {
<add> $this->articles->eventManager()->attach(function ($e, $data, $options) {
<ide> $data['title'] = 'Modified title';
<ide> $data['user']['username'] = 'robert';
<add>
<add> $options['associated'] = ['Users'];
<ide> }, 'Model.beforeMarshal');
<ide>
<del> $entity = $marshall->one($data, [
<del> 'associated' => ['Users']
<del> ]);
<add> $entity = $marshall->one($data);
<ide>
<ide> $this->assertEquals('Modified title', $entity->title);
<ide> $this->assertEquals('My content', $entity->body);
| 2
|
Go
|
Go
|
create daemon root with acl
|
46ec4c1ae2700ed638072fd7fb326afc10eded20
|
<ide><path>cmd/dockerd/daemon.go
<ide> import (
<ide> "io"
<ide> "os"
<ide> "path/filepath"
<add> "runtime"
<ide> "strings"
<ide> "time"
<ide>
<ide> func NewDaemonCli() *DaemonCli {
<ide> return &DaemonCli{}
<ide> }
<ide>
<del>func migrateKey() (err error) {
<add>func migrateKey(config *daemon.Config) (err error) {
<add> // No migration necessary on Windows
<add> if runtime.GOOS == "windows" {
<add> return nil
<add> }
<add>
<ide> // Migrate trust key if exists at ~/.docker/key.json and owned by current user
<ide> oldPath := filepath.Join(cliconfig.ConfigDir(), cliflags.DefaultTrustKeyFile)
<del> newPath := filepath.Join(getDaemonConfDir(), cliflags.DefaultTrustKeyFile)
<add> newPath := filepath.Join(getDaemonConfDir(config.Root), cliflags.DefaultTrustKeyFile)
<ide> if _, statErr := os.Stat(newPath); os.IsNotExist(statErr) && currentUserIsOwner(oldPath) {
<ide> defer func() {
<ide> // Ensure old path is removed if no error occurred
<ide> func migrateKey() (err error) {
<ide> }
<ide> }()
<ide>
<del> if err := system.MkdirAll(getDaemonConfDir(), os.FileMode(0644)); err != nil {
<add> if err := system.MkdirAll(getDaemonConfDir(config.Root), os.FileMode(0644)); err != nil {
<ide> return fmt.Errorf("Unable to create daemon configuration directory: %s", err)
<ide> }
<ide>
<ide> func (cli *DaemonCli) start(opts daemonOptions) (err error) {
<ide>
<ide> opts.common.SetDefaultOptions(opts.flags)
<ide>
<del> if opts.common.TrustKey == "" {
<del> opts.common.TrustKey = filepath.Join(
<del> getDaemonConfDir(),
<del> cliflags.DefaultTrustKeyFile)
<del> }
<ide> if cli.Config, err = loadDaemonCliConfig(opts); err != nil {
<ide> return err
<ide> }
<ide> cli.configFile = &opts.configFile
<ide> cli.flags = opts.flags
<ide>
<add> if opts.common.TrustKey == "" {
<add> opts.common.TrustKey = filepath.Join(
<add> getDaemonConfDir(cli.Config.Root),
<add> cliflags.DefaultTrustKeyFile)
<add> }
<add>
<ide> if cli.Config.Debug {
<ide> utils.EnableDebug()
<ide> }
<ide> func (cli *DaemonCli) start(opts daemonOptions) (err error) {
<ide> }
<ide> }
<ide>
<add> // Create the daemon root before we create ANY other files (PID, or migrate keys)
<add> // to ensure the appropriate ACL is set (particularly relevant on Windows)
<add> if err := daemon.CreateDaemonRoot(cli.Config); err != nil {
<add> return err
<add> }
<add>
<ide> if cli.Pidfile != "" {
<ide> pf, err := pidfile.New(cli.Pidfile)
<ide> if err != nil {
<ide> func (cli *DaemonCli) start(opts daemonOptions) (err error) {
<ide> api.Accept(addr, ls...)
<ide> }
<ide>
<del> if err := migrateKey(); err != nil {
<add> if err := migrateKey(cli.Config); err != nil {
<ide> return err
<ide> }
<add>
<ide> // FIXME: why is this down here instead of with the other TrustKey logic above?
<ide> cli.TrustKeyPath = opts.common.TrustKey
<ide>
<ide><path>cmd/dockerd/daemon_solaris.go
<ide> func setDefaultUmask() error {
<ide> return nil
<ide> }
<ide>
<del>func getDaemonConfDir() string {
<add>func getDaemonConfDir(_ string) string {
<ide> return "/etc/docker"
<ide> }
<ide>
<ide><path>cmd/dockerd/daemon_unix.go
<ide> func setDefaultUmask() error {
<ide> return nil
<ide> }
<ide>
<del>func getDaemonConfDir() string {
<add>func getDaemonConfDir(_ string) string {
<ide> return "/etc/docker"
<ide> }
<ide>
<ide><path>cmd/dockerd/daemon_windows.go
<ide> import (
<ide> "fmt"
<ide> "net"
<ide> "os"
<add> "path/filepath"
<ide> "syscall"
<ide>
<ide> "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/libcontainerd"
<ide> "github.com/docker/docker/pkg/system"
<ide> )
<ide>
<del>var defaultDaemonConfigFile = os.Getenv("programdata") + string(os.PathSeparator) + "docker" + string(os.PathSeparator) + "config" + string(os.PathSeparator) + "daemon.json"
<add>var defaultDaemonConfigFile = ""
<ide>
<ide> // currentUserIsOwner checks whether the current user is the owner of the given
<ide> // file.
<ide> func setDefaultUmask() error {
<ide> return nil
<ide> }
<ide>
<del>func getDaemonConfDir() string {
<del> return os.Getenv("PROGRAMDATA") + `\docker\config`
<add>func getDaemonConfDir(root string) string {
<add> return filepath.Join(root, `\config`)
<ide> }
<ide>
<ide> // notifySystem sends a message to the host when the server is ready to be used
<ide><path>cmd/dockerd/docker.go
<ide> func runDaemon(opts daemonOptions) error {
<ide>
<ide> daemonCli := NewDaemonCli()
<ide>
<del> // On Windows, if there's no explicit pidfile set, set to under the daemon root
<del> if runtime.GOOS == "windows" && opts.daemonConfig.Pidfile == "" {
<del> opts.daemonConfig.Pidfile = filepath.Join(opts.daemonConfig.Root, "docker.pid")
<add> // Windows specific settings as these are not defaulted.
<add> if runtime.GOOS == "windows" {
<add> if opts.daemonConfig.Pidfile == "" {
<add> opts.daemonConfig.Pidfile = filepath.Join(opts.daemonConfig.Root, "docker.pid")
<add> }
<add> if opts.configFile == "" {
<add> opts.configFile = filepath.Join(opts.daemonConfig.Root, `config\daemon.json`)
<add> }
<ide> }
<ide>
<ide> // On Windows, this may be launching as a service or with an option to
<ide><path>daemon/daemon.go
<ide> func NewDaemon(config *Config, registryService registry.Service, containerdRemot
<ide> return nil, err
<ide> }
<ide>
<del> // get the canonical path to the Docker root directory
<del> var realRoot string
<del> if _, err := os.Stat(config.Root); err != nil && os.IsNotExist(err) {
<del> realRoot = config.Root
<del> } else {
<del> realRoot, err = fileutils.ReadSymlinkedDirectory(config.Root)
<del> if err != nil {
<del> return nil, fmt.Errorf("Unable to get the full path to root (%s): %s", config.Root, err)
<del> }
<del> }
<del>
<del> if err := setupDaemonRoot(config, realRoot, rootUID, rootGID); err != nil {
<del> return nil, err
<del> }
<del>
<ide> if err := setupDaemonProcess(config); err != nil {
<ide> return nil, err
<ide> }
<ide> func NewDaemon(config *Config, registryService registry.Service, containerdRemot
<ide> }
<ide>
<ide> if runtime.GOOS == "windows" {
<del> if err := idtools.MkdirAllAs(filepath.Join(config.Root, "credentialspecs"), 0700, rootUID, rootGID); err != nil && !os.IsExist(err) {
<add> if err := system.MkdirAll(filepath.Join(config.Root, "credentialspecs"), 0); err != nil && !os.IsExist(err) {
<ide> return nil, err
<ide> }
<ide> }
<ide> func (daemon *Daemon) pluginShutdown() {
<ide> manager.Shutdown()
<ide> }
<ide> }
<add>
<add>// CreateDaemonRoot creates the root for the daemon
<add>func CreateDaemonRoot(config *Config) error {
<add> // get the canonical path to the Docker root directory
<add> var realRoot string
<add> if _, err := os.Stat(config.Root); err != nil && os.IsNotExist(err) {
<add> realRoot = config.Root
<add> } else {
<add> realRoot, err = fileutils.ReadSymlinkedDirectory(config.Root)
<add> if err != nil {
<add> return fmt.Errorf("Unable to get the full path to root (%s): %s", config.Root, err)
<add> }
<add> }
<add>
<add> uidMaps, gidMaps, err := setupRemappedRoot(config)
<add> if err != nil {
<add> return err
<add> }
<add> rootUID, rootGID, err := idtools.GetRootUIDGID(uidMaps, gidMaps)
<add> if err != nil {
<add> return err
<add> }
<add>
<add> if err := setupDaemonRoot(config, realRoot, rootUID, rootGID); err != nil {
<add> return err
<add> }
<add>
<add> return nil
<add>}
<ide><path>daemon/daemon_windows.go
<ide> func setupRemappedRoot(config *Config) ([]idtools.IDMap, []idtools.IDMap, error)
<ide> func setupDaemonRoot(config *Config, rootDir string, rootUID, rootGID int) error {
<ide> config.Root = rootDir
<ide> // Create the root directory if it doesn't exists
<del> if err := system.MkdirAll(config.Root, 0700); err != nil && !os.IsExist(err) {
<add> if err := system.MkdirAllWithACL(config.Root, 0); err != nil && !os.IsExist(err) {
<ide> return err
<ide> }
<ide> return nil
<ide><path>pkg/system/filesys.go
<ide> import (
<ide> "path/filepath"
<ide> )
<ide>
<add>// MkdirAllWithACL is a wrapper for MkdirAll that creates a directory
<add>// ACL'd for Builtin Administrators and Local System.
<add>func MkdirAllWithACL(path string, perm os.FileMode) error {
<add> return MkdirAll(path, perm)
<add>}
<add>
<ide> // MkdirAll creates a directory named path along with any necessary parents,
<ide> // with permission specified by attribute perm for all dir created.
<ide> func MkdirAll(path string, perm os.FileMode) error {
<ide><path>pkg/system/filesys_windows.go
<ide> import (
<ide> "regexp"
<ide> "strings"
<ide> "syscall"
<add> "unsafe"
<add>
<add> winio "github.com/Microsoft/go-winio"
<ide> )
<ide>
<add>// MkdirAllWithACL is a wrapper for MkdirAll that creates a directory
<add>// ACL'd for Builtin Administrators and Local System.
<add>func MkdirAllWithACL(path string, perm os.FileMode) error {
<add> return mkdirall(path, true)
<add>}
<add>
<ide> // MkdirAll implementation that is volume path aware for Windows.
<del>func MkdirAll(path string, perm os.FileMode) error {
<add>func MkdirAll(path string, _ os.FileMode) error {
<add> return mkdirall(path, false)
<add>}
<add>
<add>// mkdirall is a custom version of os.MkdirAll modified for use on Windows
<add>// so that it is both volume path aware, and can create a directory with
<add>// a DACL.
<add>func mkdirall(path string, adminAndLocalSystem bool) error {
<ide> if re := regexp.MustCompile(`^\\\\\?\\Volume{[a-z0-9-]+}$`); re.MatchString(path) {
<ide> return nil
<ide> }
<ide>
<del> // The rest of this method is copied from os.MkdirAll and should be kept
<add> // The rest of this method is largely copied from os.MkdirAll and should be kept
<ide> // as-is to ensure compatibility.
<ide>
<ide> // Fast path: if we can tell whether path is a directory or file, stop with success or error.
<ide> func MkdirAll(path string, perm os.FileMode) error {
<ide>
<ide> if j > 1 {
<ide> // Create parent
<del> err = MkdirAll(path[0:j-1], perm)
<add> err = mkdirall(path[0:j-1], false)
<ide> if err != nil {
<ide> return err
<ide> }
<ide> }
<ide>
<del> // Parent now exists; invoke Mkdir and use its result.
<del> err = os.Mkdir(path, perm)
<add> // Parent now exists; invoke os.Mkdir or mkdirWithACL and use its result.
<add> if adminAndLocalSystem {
<add> err = mkdirWithACL(path)
<add> } else {
<add> err = os.Mkdir(path, 0)
<add> }
<add>
<ide> if err != nil {
<ide> // Handle arguments like "foo/." by
<ide> // double-checking that directory doesn't exist.
<ide> func MkdirAll(path string, perm os.FileMode) error {
<ide> return nil
<ide> }
<ide>
<add>// mkdirWithACL creates a new directory. If there is an error, it will be of
<add>// type *PathError. .
<add>//
<add>// This is a modified and combined version of os.Mkdir and syscall.Mkdir
<add>// in golang to cater for creating a directory am ACL permitting full
<add>// access, with inheritance, to any subfolder/file for Built-in Administrators
<add>// and Local System.
<add>func mkdirWithACL(name string) error {
<add> sa := syscall.SecurityAttributes{Length: 0}
<add> sddl := "D:P(A;OICI;GA;;;BA)(A;OICI;GA;;;SY)"
<add> sd, err := winio.SddlToSecurityDescriptor(sddl)
<add> if err != nil {
<add> return &os.PathError{"mkdir", name, err}
<add> }
<add> sa.Length = uint32(unsafe.Sizeof(sa))
<add> sa.InheritHandle = 1
<add> sa.SecurityDescriptor = uintptr(unsafe.Pointer(&sd[0]))
<add>
<add> namep, err := syscall.UTF16PtrFromString(name)
<add> if err != nil {
<add> return &os.PathError{"mkdir", name, err}
<add> }
<add>
<add> e := syscall.CreateDirectory(namep, &sa)
<add> if e != nil {
<add> return &os.PathError{"mkdir", name, e}
<add> }
<add> return nil
<add>}
<add>
<ide> // IsAbs is a platform-specific wrapper for filepath.IsAbs. On Windows,
<ide> // golang filepath.IsAbs does not consider a path \windows\system32 as absolute
<ide> // as it doesn't start with a drive-letter/colon combination. However, in
| 9
|
Text
|
Text
|
use stronger language about security of vm
|
6d32d44cfe0a07580524105522510cb89340f83e
|
<ide><path>doc/api/vm.md
<ide> <!--name=vm-->
<ide>
<ide> The `vm` module provides APIs for compiling and running code within V8 Virtual
<del>Machine contexts.
<add>Machine contexts. **Note that the `vm` module is not a security mechanism. Do
<add>not use it to run untrusted code**. The term "sandbox" is used throughout these
<add>docs simply to refer to a separate context, and does not confer any security
<add>guarantees.
<ide>
<ide> JavaScript code can be compiled and run immediately or
<ide> compiled, saved, and run later.
<ide> console.log(sandbox.y); // 17
<ide> console.log(x); // 1; y is not defined.
<ide> ```
<ide>
<del>**The vm module is not a security mechanism. Do not use it to run untrusted
<del>code**.
<del>
<ide> ## Class: vm.SourceTextModule
<ide> <!-- YAML
<ide> added: v9.6.0
| 1
|
Go
|
Go
|
fix typo in devmapper driver_test
|
b3e7df48dfbf3d2300877d1e524132624e9493c3
|
<ide><path>graphdriver/devmapper/driver_test.go
<ide> func TestInit(t *testing.T) {
<ide> }
<ide> }()
<ide> }()
<del> // Put all tests in a funciton to make sure the garbage collection will
<add> // Put all tests in a function to make sure the garbage collection will
<ide> // occur.
<ide>
<ide> // Call GC to cleanup runtime.Finalizers
| 1
|
Javascript
|
Javascript
|
fix warnings script to work on node 4
|
fc1f324cc4c83e38b618a1cb076cd704bf8867ea
|
<ide><path>scripts/print-warnings/print-warnings.js
<ide> const sourcePaths = Bundles.bundles
<ide> bundle.bundleTypes.indexOf(Bundles.bundleTypes.FB_DEV) !== -1 ||
<ide> bundle.bundleTypes.indexOf(Bundles.bundleTypes.FB_PROD) !== -1
<ide> )
<del> .reduce((allPaths, bundle) => [...allPaths, ...bundle.paths], []);
<add> .reduce((allPaths, bundle) => allPaths.concat(bundle.paths), []);
<ide>
<ide> gs(sourcePaths).pipe(
<ide> through.obj(transform, cb => {
| 1
|
Javascript
|
Javascript
|
add basic unit tests for event aliases
|
e05c63e17a037d550e7dde5d805ee5c4214ee44b
|
<ide><path>test/unit/event.js
<ide> QUnit.test( "originalEvent property for Chrome, Safari, Fx & Edge of simulated e
<ide> jQuery( "#donor-input" ).trigger( "focus" );
<ide> } );
<ide>
<add>QUnit[ jQuery.fn.click ? "test" : "skip" ]( "Event aliases", function( assert ) {
<add>
<add> // Explicitly skipping focus/blur events due to their flakiness
<add> var $elem = jQuery( "<div />" ).appendTo( "#qunit-fixture" ),
<add> aliases = ( "resize scroll click dblclick mousedown mouseup " +
<add> "mousemove mouseover mouseout mouseenter mouseleave change " +
<add> "select submit keydown keypress keyup contextmenu" ).split( " " );
<add> assert.expect( aliases.length );
<add>
<add> jQuery.each( aliases, function( i, name ) {
<add>
<add> // e.g. $(elem).click(...).click();
<add> $elem[ name ]( function( event ) {
<add> assert.equal( event.type, name, "triggered " + name );
<add> } )[ name ]().off( name );
<add> } );
<add>} );
<add>
<ide> // These tests are unreliable in Firefox
<ide> if ( !( /firefox/i.test( window.navigator.userAgent ) ) ) {
<ide> QUnit.test( "Check order of focusin/focusout events", function( assert ) {
| 1
|
Mixed
|
Text
|
add etw logging driver plug-in
|
3fe60bbf95b60f1a1e847a48e1c9b9730e570dff
|
<ide><path>daemon/logdrivers_windows.go
<ide> import (
<ide> // Importing packages here only to make sure their init gets called and
<ide> // therefore they register themselves to the logdriver factory.
<ide> _ "github.com/docker/docker/daemon/logger/awslogs"
<add> _ "github.com/docker/docker/daemon/logger/etwlogs"
<ide> _ "github.com/docker/docker/daemon/logger/jsonfilelog"
<ide> _ "github.com/docker/docker/daemon/logger/splunk"
<ide> )
<ide><path>daemon/logger/etwlogs/etwlogs_windows.go
<add>// Package etwlogs provides a log driver for forwarding container logs
<add>// as ETW events.(ETW stands for Event Tracing for Windows)
<add>// A client can then create an ETW listener to listen for events that are sent
<add>// by the ETW provider that we register, using the provider's GUID "a3693192-9ed6-46d2-a981-f8226c8363bd".
<add>// Here is an example of how to do this using the logman utility:
<add>// 1. logman start -ets DockerContainerLogs -p {a3693192-9ed6-46d2-a981-f8226c8363bd} 0 0 -o trace.etl
<add>// 2. Run container(s) and generate log messages
<add>// 3. logman stop -ets DockerContainerLogs
<add>// 4. You can then convert the etl log file to XML using: tracerpt -y trace.etl
<add>//
<add>// Each container log message generates a ETW event that also contains:
<add>// the container name and ID, the timestamp, and the stream type.
<add>package etwlogs
<add>
<add>import (
<add> "errors"
<add> "fmt"
<add> "sync"
<add> "syscall"
<add> "unsafe"
<add>
<add> "github.com/Sirupsen/logrus"
<add> "github.com/docker/docker/daemon/logger"
<add>)
<add>
<add>type etwLogs struct {
<add> containerName string
<add> imageName string
<add> containerID string
<add> imageID string
<add>}
<add>
<add>const (
<add> name = "etwlogs"
<add> win32CallSuccess = 0
<add>)
<add>
<add>var win32Lib *syscall.DLL
<add>var providerHandle syscall.Handle
<add>var refCount int
<add>var mu sync.Mutex
<add>
<add>func init() {
<add> providerHandle = syscall.InvalidHandle
<add> if err := logger.RegisterLogDriver(name, New); err != nil {
<add> logrus.Fatal(err)
<add> }
<add>}
<add>
<add>// New creates a new etwLogs logger for the given container and registers the EWT provider.
<add>func New(ctx logger.Context) (logger.Logger, error) {
<add> if err := registerETWProvider(); err != nil {
<add> return nil, err
<add> }
<add> logrus.Debugf("logging driver etwLogs configured for container: %s.", ctx.ContainerID)
<add>
<add> return &etwLogs{
<add> containerName: fixContainerName(ctx.ContainerName),
<add> imageName: ctx.ContainerImageName,
<add> containerID: ctx.ContainerID,
<add> imageID: ctx.ContainerImageID,
<add> }, nil
<add>}
<add>
<add>// Log logs the message to the ETW stream.
<add>func (etwLogger *etwLogs) Log(msg *logger.Message) error {
<add> if providerHandle == syscall.InvalidHandle {
<add> // This should never be hit, if it is, it indicates a programming error.
<add> errorMessage := "ETWLogs cannot log the message, because the event provider has not been registered."
<add> logrus.Error(errorMessage)
<add> return errors.New(errorMessage)
<add> }
<add> return callEventWriteString(createLogMessage(etwLogger, msg))
<add>}
<add>
<add>// Close closes the logger by unregistering the ETW provider.
<add>func (etwLogger *etwLogs) Close() error {
<add> unregisterETWProvider()
<add> return nil
<add>}
<add>
<add>func (etwLogger *etwLogs) Name() string {
<add> return name
<add>}
<add>
<add>func createLogMessage(etwLogger *etwLogs, msg *logger.Message) string {
<add> return fmt.Sprintf("container_name: %s, image_name: %s, container_id: %s, image_id: %s, source: %s, log: %s",
<add> etwLogger.containerName,
<add> etwLogger.imageName,
<add> etwLogger.containerID,
<add> etwLogger.imageID,
<add> msg.Source,
<add> msg.Line)
<add>}
<add>
<add>// fixContainerName removes the initial '/' from the container name.
<add>func fixContainerName(cntName string) string {
<add> if len(cntName) > 0 && cntName[0] == '/' {
<add> cntName = cntName[1:]
<add> }
<add> return cntName
<add>}
<add>
<add>func registerETWProvider() error {
<add> mu.Lock()
<add> defer mu.Unlock()
<add> if refCount == 0 {
<add> var err error
<add> if win32Lib, err = syscall.LoadDLL("Advapi32.dll"); err != nil {
<add> return err
<add> }
<add> if err = callEventRegister(); err != nil {
<add> win32Lib.Release()
<add> win32Lib = nil
<add> return err
<add> }
<add> }
<add>
<add> refCount++
<add> return nil
<add>}
<add>
<add>func unregisterETWProvider() {
<add> mu.Lock()
<add> defer mu.Unlock()
<add> if refCount == 1 {
<add> if callEventUnregister() {
<add> refCount--
<add> providerHandle = syscall.InvalidHandle
<add> win32Lib.Release()
<add> win32Lib = nil
<add> }
<add> // Not returning an error if EventUnregister fails, because etwLogs will continue to work
<add> } else {
<add> refCount--
<add> }
<add>}
<add>
<add>func callEventRegister() error {
<add> proc, err := win32Lib.FindProc("EventRegister")
<add> if err != nil {
<add> return err
<add> }
<add> // The provider's GUID is {a3693192-9ed6-46d2-a981-f8226c8363bd}
<add> guid := syscall.GUID{
<add> 0xa3693192, 0x9ed6, 0x46d2,
<add> [8]byte{0xa9, 0x81, 0xf8, 0x22, 0x6c, 0x83, 0x63, 0xbd},
<add> }
<add>
<add> ret, _, _ := proc.Call(uintptr(unsafe.Pointer(&guid)), 0, 0, uintptr(unsafe.Pointer(&providerHandle)))
<add> if ret != win32CallSuccess {
<add> errorMessage := fmt.Sprintf("Failed to register ETW provider. Error: %d", ret)
<add> logrus.Error(errorMessage)
<add> return errors.New(errorMessage)
<add> }
<add> return nil
<add>}
<add>
<add>func callEventWriteString(message string) error {
<add> proc, err := win32Lib.FindProc("EventWriteString")
<add> if err != nil {
<add> return err
<add> }
<add> ret, _, _ := proc.Call(uintptr(providerHandle), 0, 0, uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(message))))
<add> if ret != win32CallSuccess {
<add> errorMessage := fmt.Sprintf("ETWLogs provider failed to log message. Error: %d", ret)
<add> logrus.Error(errorMessage)
<add> return errors.New(errorMessage)
<add> }
<add> return nil
<add>}
<add>
<add>func callEventUnregister() bool {
<add> proc, err := win32Lib.FindProc("EventUnregister")
<add> if err != nil {
<add> return false
<add> }
<add> ret, _, _ := proc.Call(uintptr(providerHandle))
<add> if ret != win32CallSuccess {
<add> return false
<add> }
<add> return true
<add>}
<ide><path>docs/admin/logging/etwlogs.md
<add><!--[metadata]>
<add>+++
<add>title = "ETW logging driver"
<add>description = "Describes how to use the etwlogs logging driver."
<add>keywords = ["ETW, docker, logging, driver"]
<add>[menu.main]
<add>parent = "smn_logging"
<add>weight=2
<add>+++
<add><![end-metadata]-->
<add>
<add>
<add># ETW logging driver
<add>
<add>The ETW logging driver forwards container logs as ETW events.
<add>ETW stands for Event Tracing in Windows, and is the common framework
<add>for tracing applications in Windows. Each ETW event contains a message
<add>with both the log and its context information. A client can then create
<add>an ETW listener to listen to these events.
<add>
<add>The ETW provider that this logging driver registers with Windows, has the
<add>GUID identifier of: `{a3693192-9ed6-46d2-a981-f8226c8363bd}`. A client creates an
<add>ETW listener and registers to listen to events from the logging driver's provider.
<add>It does not matter the order in which the provider and listener are created.
<add>A client can create their ETW listener and start listening for events from the provider,
<add>before the provider has been registered with the system.
<add>
<add>## Usage
<add>
<add>Here is an example of how to listen to these events using the logman utility program
<add>included in most installations of Windows:
<add>
<add> 1. `logman start -ets DockerContainerLogs -p {a3693192-9ed6-46d2-a981-f8226c8363bd} 0 0 -o trace.etl`
<add> 2. Run your container(s) with the etwlogs driver, by adding `--log-driver=etwlogs`
<add> to the Docker run command, and generate log messages.
<add> 3. `logman stop -ets DockerContainerLogs`
<add> 4. This will generate an etl file that contains the events. One way to convert this file into
<add> human-readable form is to run: `tracerpt -y trace.etl`.
<add>
<add>Each ETW event will contain a structured message string in this format:
<add>
<add> container_name: %s, image_name: %s, container_id: %s, image_id: %s, source: [stdout | stderr], log: %s
<add>
<add>Details on each item in the message can be found below:
<add>
<add>| Field | Description |
<add>-----------------------|-------------------------------------------------|
<add>| `container_name` | The container name at the time it was started. |
<add>| `image_name` | The name of the container's image. |
<add>| `container_id` | The full 64-character container ID. |
<add>| `image_id` | The full ID of the container's image. |
<add>| `source` | `stdout` or `stderr`. |
<add>| `log` | The container log message. |
<add>
<add>Here is an example event message:
<add>
<add> container_name: backstabbing_spence,
<add> image_name: windowsservercore,
<add> container_id: f14bb55aa862d7596b03a33251c1be7dbbec8056bbdead1da8ec5ecebbe29731,
<add> image_id: sha256:2f9e19bd998d3565b4f345ac9aaf6e3fc555406239a4fb1b1ba879673713824b,
<add> source: stdout,
<add> log: Hello world!
<add>
<add>A client can parse this message string to get both the log message, as well as its
<add>context information. Note that the time stamp is also available within the ETW event.
<add>
<add>**Note** This ETW provider emits only a message string, and not a specially
<add>structured ETW event. Therefore, it is not required to register a manifest file
<add>with the system to read and interpret its ETW events.
<ide><path>docs/admin/logging/index.md
<ide> weight=8
<ide> * [Journald logging driver](journald.md)
<ide> * [Amazon CloudWatch Logs logging driver](awslogs.md)
<ide> * [Splunk logging driver](splunk.md)
<add>* [ETW logging driver](etwlogs.md)
<ide><path>docs/admin/logging/overview.md
<ide> container's logging driver. The following options are supported:
<ide> | `fluentd` | Fluentd logging driver for Docker. Writes log messages to `fluentd` (forward input). |
<ide> | `awslogs` | Amazon CloudWatch Logs logging driver for Docker. Writes log messages to Amazon CloudWatch Logs. |
<ide> | `splunk` | Splunk logging driver for Docker. Writes log messages to `splunk` using HTTP Event Collector. |
<add>| `etwlogs` | ETW logging driver for Docker on Windows. Writes log messages as ETW events. |
<ide>
<ide> The `docker logs`command is available only for the `json-file` and `journald`
<ide> logging drivers.
<ide> The Splunk logging driver requires the following options:
<ide>
<ide> For detailed information about working with this logging driver, see the [Splunk logging driver](splunk.md)
<ide> reference documentation.
<add>
<add>## ETW logging driver options
<add>
<add>The etwlogs logging driver does not require any options to be specified. This logging driver will forward each log message
<add>as an ETW event. An ETW listener can then be created to listen for these events.
<add>
<add>For detailed information on working with this logging driver, see [the ETW logging driver](etwlogs.md) reference documentation.
<add>
<add>
<ide><path>docs/reference/api/docker_remote_api_v1.23.md
<ide> Json Parameters:
<ide> systems, such as SELinux.
<ide> - **LogConfig** - Log configuration for the container, specified as a JSON object in the form
<ide> `{ "Type": "<driver_name>", "Config": {"key1": "val1"}}`.
<del> Available types: `json-file`, `syslog`, `journald`, `gelf`, `awslogs`, `splunk`, `none`.
<add> Available types: `json-file`, `syslog`, `journald`, `gelf`, `fluentd`, `awslogs`, `splunk`, `etwlogs`, `none`.
<ide> `json-file` logging driver.
<ide> - **CgroupParent** - Path to `cgroups` under which the container's `cgroup` is created. If the path is not absolute, the path is considered to be relative to the `cgroups` path of the init process. Cgroups are created if they do not already exist.
<ide> - **VolumeDriver** - Driver that this container users to mount volumes.
<ide><path>man/docker-create.1.md
<ide> millions of trillions.
<ide> Add link to another container in the form of <name or id>:alias or just
<ide> <name or id> in which case the alias will match the name.
<ide>
<del>**--log-driver**="*json-file*|*syslog*|*journald*|*gelf*|*fluentd*|*awslogs*|*splunk*|*none*"
<add>**--log-driver**="*json-file*|*syslog*|*journald*|*gelf*|*fluentd*|*awslogs*|*splunk*|*etwlogs*|*none*"
<ide> Logging driver for container. Default is defined by daemon `--log-driver` flag.
<ide> **Warning**: the `docker logs` command works only for the `json-file` and
<ide> `journald` logging drivers.
<ide><path>man/docker-daemon.8.md
<ide> unix://[/path/to/socket] to use.
<ide> **--label**="[]"
<ide> Set key=value labels to the daemon (displayed in `docker info`)
<ide>
<del>**--log-driver**="*json-file*|*syslog*|*journald*|*gelf*|*fluentd*|*awslogs*|*none*"
<add>**--log-driver**="*json-file*|*syslog*|*journald*|*gelf*|*fluentd*|*awslogs*|*splunk*|*etwlogs*|*none*"
<ide> Default driver for container logs. Default is `json-file`.
<ide> **Warning**: `docker logs` command works only for `json-file` logging driver.
<ide>
<ide><path>man/docker-run.1.md
<ide> container can access the exposed port via a private networking interface. Docker
<ide> will set some environment variables in the client container to help indicate
<ide> which interface and port to use.
<ide>
<del>**--log-driver**="*json-file*|*syslog*|*journald*|*gelf*|*fluentd*|*awslogs*|*splunk*|*none*"
<add>**--log-driver**="*json-file*|*syslog*|*journald*|*gelf*|*fluentd*|*awslogs*|*splunk*|*etwlogs*|*none*"
<ide> Logging driver for container. Default is defined by daemon `--log-driver` flag.
<ide> **Warning**: the `docker logs` command works only for the `json-file` and
<ide> `journald` logging drivers.
| 9
|
Javascript
|
Javascript
|
remove old deprecation flag in map/orderedset
|
a1e3a9fbf2560ca77a4956780971d83b71eacb14
|
<ide><path>packages/ember-metal/lib/map.js
<ide> function copyMap(original, newObject) {
<ide> function OrderedSet() {
<ide> if (this instanceof OrderedSet) {
<ide> this.clear();
<del> this._silenceRemoveDeprecation = false;
<ide> } else {
<ide> missingNew('OrderedSet');
<ide> }
<ide> OrderedSet.prototype = {
<ide> let Constructor = this.constructor;
<ide> let set = new Constructor();
<ide>
<del> set._silenceRemoveDeprecation = this._silenceRemoveDeprecation;
<ide> set.presenceSet = copyNull(this.presenceSet);
<ide> set.list = this.toArray();
<ide> set.size = this.size;
<ide> OrderedSet.prototype = {
<ide> function Map() {
<ide> if (this instanceof Map) {
<ide> this._keys = OrderedSet.create();
<del> this._keys._silenceRemoveDeprecation = true;
<ide> this._values = Object.create(null);
<ide> this.size = 0;
<ide> } else {
| 1
|
Javascript
|
Javascript
|
fix moduletemplate.hooks.hash deprecation message
|
34c83102d823c63e538fe6aaf57a9c5278f931d4
|
<ide><path>lib/ModuleTemplate.js
<ide> class ModuleTemplate {
<ide> (options, fn) => {
<ide> compilation.hooks.fullHash.tap(options, fn);
<ide> },
<del> "ModuleTemplate.hooks.package is deprecated (use Compilation.hooks.fullHash instead)",
<add> "ModuleTemplate.hooks.hash is deprecated (use Compilation.hooks.fullHash instead)",
<ide> "DEP_MODULE_TEMPLATE_HASH"
<ide> )
<ide> }
| 1
|
Ruby
|
Ruby
|
use canonical_name to locate rack
|
df999067d69b660a978e52263eace80dc1786993
|
<ide><path>Library/Homebrew/extend/ARGV.rb
<ide> def resolved_formulae
<ide> end
<ide> f
<ide> else
<del> Formulary.from_rack(HOMEBREW_CELLAR/name, spec(default=nil))
<add> canonical_name = Formulary.canonical_name(name)
<add> Formulary.from_rack(HOMEBREW_CELLAR/canonical_name, spec(default=nil))
<ide> end
<ide> end
<ide> end
| 1
|
Ruby
|
Ruby
|
fix random ci fail due to auto-updating timestamp
|
056b252010f90210b608d3a950d43a994218c32f
|
<ide><path>activejob/test/cases/job_serialization_test.rb
<ide> class JobSerializationTest < ActiveSupport::TestCase
<ide> end
<ide>
<ide> test "serialize and deserialize are symmetric" do
<add> # Ensure `enqueued_at` does not change between serializations
<add> freeze_time
<add>
<ide> # Round trip a job in memory only
<ide> h1 = HelloJob.new("Rafael")
<ide> h2 = HelloJob.deserialize(h1.serialize)
| 1
|
PHP
|
PHP
|
improve sqlite command
|
69692647947f0bf2a685a71768d55f1003e8a684
|
<ide><path>src/Illuminate/Database/Schema/Grammars/SQLiteGrammar.php
<ide> public function compileCreate(Blueprint $blueprint, Fluent $command)
<ide> );
<ide> }
<ide>
<add> /**
<add> * Compile a get all tables command.
<add> *
<add> * @param string $schema
<add> * @return string
<add> */
<add> public function compileGetAllTables()
<add> {
<add> return "select name from sqlite_master where type='table'";
<add> }
<add>
<ide> /**
<ide> * Get the foreign key syntax for a table creation statement.
<ide> *
<ide> public function compileDropIfExists(Blueprint $blueprint, Fluent $command)
<ide> return 'drop table if exists '.$this->wrapTable($blueprint);
<ide> }
<ide>
<add> /**
<add> * Compile a drop all tables command.
<add> *
<add> * @return string
<add> */
<add> public function compileDropAllTables()
<add> {
<add> return "delete from sqlite_master where type in ('table', 'index', 'trigger')";
<add> }
<add>
<ide> /**
<ide> * Compile a drop column command.
<ide> *
<ide> public function compileDisableForeignKeyConstraints()
<ide> return 'PRAGMA foreign_keys = OFF;';
<ide> }
<ide>
<add> /**
<add> * Compile the command to enable a writable schema.
<add> *
<add> * @return string
<add> */
<add> public function compileEnableWriteableSchema()
<add> {
<add> return 'PRAGMA writable_schema = 1;';
<add> }
<add>
<add> /**
<add> * Compile the command to disable a writable schema.
<add> *
<add> * @return string
<add> */
<add> public function compileDisableWriteableSchema()
<add> {
<add> return 'PRAGMA writable_schema = 0;';
<add> }
<add>
<ide> /**
<ide> * Create the column definition for a char type.
<ide> *
<ide><path>src/Illuminate/Database/Schema/SQLiteBuilder.php
<ide> class SQLiteBuilder extends Builder
<ide> */
<ide> public function dropAllTables()
<ide> {
<del> $dbPath = $this->connection->getConfig('database');
<add> $this->connection->select($this->grammar->compileEnableWriteableSchema());
<ide>
<del> if (file_exists($dbPath)) {
<del> unlink($dbPath);
<del> }
<add> $this->connection->select($this->grammar->compileDropAllTables());
<ide>
<del> touch($dbPath);
<add> $this->connection->select($this->grammar->compileDisableWriteableSchema());
<ide> }
<ide> }
| 2
|
Python
|
Python
|
update deprecation versions
|
4024a4a89c18a1048b7496cf223c0b8c1e63c485
|
<ide><path>src/flask/app.py
<ide> def open_session(self, request):
<ide> we recommend replacing the :class:`session_interface`.
<ide>
<ide> .. deprecated: 1.0
<del> Will be removed in 1.1. Use ``session_interface.open_session``
<del> instead.
<add> Will be removed in 2.0. Use
<add> ``session_interface.open_session`` instead.
<ide>
<ide> :param request: an instance of :attr:`request_class`.
<ide> """
<ide>
<ide> warnings.warn(
<ide> DeprecationWarning(
<del> '"open_session" is deprecated and will be removed in 1.1. Use'
<del> ' "session_interface.open_session" instead.'
<add> '"open_session" is deprecated and will be removed in'
<add> ' 2.0. Use "session_interface.open_session" instead.'
<ide> )
<ide> )
<ide> return self.session_interface.open_session(self, request)
<ide> def save_session(self, session, response):
<ide> method we recommend replacing the :class:`session_interface`.
<ide>
<ide> .. deprecated: 1.0
<del> Will be removed in 1.1. Use ``session_interface.save_session``
<del> instead.
<add> Will be removed in 2.0. Use
<add> ``session_interface.save_session`` instead.
<ide>
<ide> :param session: the session to be saved (a
<ide> :class:`~werkzeug.contrib.securecookie.SecureCookie`
<ide> def save_session(self, session, response):
<ide>
<ide> warnings.warn(
<ide> DeprecationWarning(
<del> '"save_session" is deprecated and will be removed in 1.1. Use'
<del> ' "session_interface.save_session" instead.'
<add> '"save_session" is deprecated and will be removed in'
<add> ' 2.0. Use "session_interface.save_session" instead.'
<ide> )
<ide> )
<ide> return self.session_interface.save_session(self, session, response)
<ide> def make_null_session(self):
<ide> this method we recommend replacing the :class:`session_interface`.
<ide>
<ide> .. deprecated: 1.0
<del> Will be removed in 1.1. Use ``session_interface.make_null_session``
<del> instead.
<add> Will be removed in 2.0. Use
<add> ``session_interface.make_null_session`` instead.
<ide>
<ide> .. versionadded:: 0.7
<ide> """
<ide>
<ide> warnings.warn(
<ide> DeprecationWarning(
<del> '"make_null_session" is deprecated and will be removed in 1.1. Use'
<del> ' "session_interface.make_null_session" instead.'
<add> '"make_null_session" is deprecated and will be removed'
<add> ' in 2.0. Use "session_interface.make_null_session"'
<add> " instead."
<ide> )
<ide> )
<ide> return self.session_interface.make_null_session(self)
<ide><path>src/flask/testing.py
<ide> def make_test_environ_builder(*args, **kwargs):
<ide> """Create a :class:`flask.testing.EnvironBuilder`.
<ide>
<ide> .. deprecated: 1.1
<del> Will be removed in 1.2. Construct ``flask.testing.EnvironBuilder``
<del> directly instead.
<add> Will be removed in 2.0. Construct
<add> ``flask.testing.EnvironBuilder`` directly instead.
<ide> """
<ide> warnings.warn(
<ide> DeprecationWarning(
<del> '"make_test_environ_builder()" is deprecated and will be removed '
<del> 'in 1.2. Construct "flask.testing.EnvironBuilder" directly '
<del> "instead."
<add> '"make_test_environ_builder()" is deprecated and will be'
<add> ' removed in 2.0. Construct "flask.testing.EnvironBuilder"'
<add> " directly instead."
<ide> )
<ide> )
<ide> return EnvironBuilder(*args, **kwargs)
| 2
|
Javascript
|
Javascript
|
remove unused vars
|
bc39d6a3a61e9217839f2cecf0aab8a2f2a96077
|
<ide><path>test/addons/repl-domain-abort/test.js
<ide> var options = {
<ide> };
<ide>
<ide> // Run commands from fake REPL.
<del>var dummy = repl.start(options);
<add>repl.start(options);
<ide><path>test/debugger/test-debugger-pid.js
<ide> 'use strict';
<del>var common = require('../common');
<add>require('../common');
<ide> var assert = require('assert');
<ide> var spawn = require('child_process').spawn;
<ide>
<del>var port = common.PORT + 1337;
<ide> var buffer = '';
<del>var expected = [];
<del>var scriptToDebug = common.fixturesDir + '/empty.js';
<del>
<del>function fail() {
<del> assert(0); // `--debug-brk script.js` should not quit
<del>}
<ide>
<ide> // connect to debug agent
<ide> var interfacer = spawn(process.execPath, ['debug', '-p', '655555']);
<ide><path>test/debugger/test-debugger-remote.js
<ide> var common = require('../common');
<ide> var assert = require('assert');
<ide> var spawn = require('child_process').spawn;
<ide>
<del>var port = common.PORT + 1337;
<ide> var buffer = '';
<del>var expected = [];
<ide> var scriptToDebug = common.fixturesDir + '/empty.js';
<ide>
<ide> function fail() {
<ide><path>test/internet/test-dns.js
<ide> require('../common');
<ide> var assert = require('assert'),
<ide> dns = require('dns'),
<ide> net = require('net'),
<del> isIP = net.isIP,
<ide> isIPv4 = net.isIPv4,
<ide> isIPv6 = net.isIPv6;
<ide> var util = require('util');
<ide> TEST(function test_reverse_bogus(done) {
<ide> var error;
<ide>
<ide> try {
<del> var req = dns.reverse('bogus ip', function() {
<add> dns.reverse('bogus ip', function() {
<ide> assert.ok(false);
<ide> });
<ide> } catch (e) {
<ide> console.log('looking up nodejs.org...');
<ide>
<ide> var cares = process.binding('cares_wrap');
<ide> var req = new cares.GetAddrInfoReqWrap();
<del>var err = cares.getaddrinfo(req, 'nodejs.org', 4);
<add>cares.getaddrinfo(req, 'nodejs.org', 4);
<ide>
<ide> req.oncomplete = function(err, domains) {
<ide> assert.strictEqual(err, 0);
<ide><path>test/parallel/test-domain-exit-dispose-again.js
<ide> // to that domain, including those whose callbacks are called from within
<ide> // the same invocation of listOnTimeout, _are_ called.
<ide>
<del>var common = require('../common');
<add>require('../common');
<ide> var assert = require('assert');
<ide> var domain = require('domain');
<ide> var disposalFailed = false;
<ide><path>test/parallel/test-domain-implicit-fs.js
<ide> require('../common');
<ide> var assert = require('assert');
<ide> var domain = require('domain');
<del>var events = require('events');
<ide> var caught = 0;
<ide> var expectCaught = 1;
<ide>
<ide><path>test/parallel/test-http-agent-error-on-idle.js
<ide> function get(callback) {
<ide> return http.get(requestParams, callback);
<ide> }
<ide>
<del>var destroy_queue = {};
<ide> var server = http.createServer(function(req, res) {
<ide> res.end('hello world');
<ide> });
<ide><path>test/parallel/test-timers-throw-when-cb-not-function.js
<ide> 'use strict';
<del>const common = require('../common');
<add>require('../common');
<ide> const assert = require('assert');
<ide>
<ide> function doSetTimeout(callback, after) {
<ide><path>test/parallel/test-vm-create-context-arg.js
<ide> var assert = require('assert');
<ide> var vm = require('vm');
<ide>
<ide> assert.throws(function() {
<del> var ctx = vm.createContext('string is not supported');
<add> vm.createContext('string is not supported');
<ide> }, TypeError);
<ide>
<ide> assert.doesNotThrow(function() {
<del> var ctx = vm.createContext({ a: 1 });
<del> ctx = vm.createContext([0, 1, 2, 3]);
<add> vm.createContext({ a: 1 });
<add> vm.createContext([0, 1, 2, 3]);
<ide> });
<ide>
<ide> assert.doesNotThrow(function() {
<ide><path>test/parallel/test-vm-harmony-proxies.js
<ide> var vm = require('vm');
<ide> // src/node_contextify.cc filters out the Proxy object from the parent
<ide> // context. Make sure that the new context has a Proxy object of its own.
<ide> var sandbox = {};
<del>var result = vm.runInNewContext('this.Proxy = Proxy', sandbox);
<add>vm.runInNewContext('this.Proxy = Proxy', sandbox);
<ide> assert(typeof sandbox.Proxy === 'object');
<ide> assert(sandbox.Proxy !== Proxy);
<ide>
<ide> // Unless we copy the Proxy object explicitly, of course.
<ide> var sandbox = { Proxy: Proxy };
<del>var result = vm.runInNewContext('this.Proxy = Proxy', sandbox);
<add>vm.runInNewContext('this.Proxy = Proxy', sandbox);
<ide> assert(typeof sandbox.Proxy === 'object');
<ide> assert(sandbox.Proxy === Proxy);
<ide><path>test/parallel/test-vm-harmony-symbols.js
<ide> var vm = require('vm');
<ide>
<ide> // The sandbox should have its own Symbol constructor.
<ide> var sandbox = {};
<del>var result = vm.runInNewContext('this.Symbol = Symbol', sandbox);
<add>vm.runInNewContext('this.Symbol = Symbol', sandbox);
<ide> assert(typeof sandbox.Symbol === 'function');
<ide> assert(sandbox.Symbol !== Symbol);
<ide>
<ide> // Unless we copy the Symbol constructor explicitly, of course.
<ide> var sandbox = { Symbol: Symbol };
<del>var result = vm.runInNewContext('this.Symbol = Symbol', sandbox);
<add>vm.runInNewContext('this.Symbol = Symbol', sandbox);
<ide> assert(typeof sandbox.Symbol === 'function');
<ide> assert(sandbox.Symbol === Symbol);
<ide><path>test/parallel/test-vm-new-script-new-context.js
<ide> assert.throws(function() {
<ide>
<ide>
<ide> console.error('undefined reference');
<del>var error;
<ide> script = new Script('foo.bar = 5;');
<ide> assert.throws(function() {
<ide> script.runInNewContext();
<ide> code = 'foo = 1;' +
<ide> foo = 2;
<ide> obj = { foo: 0, baz: 3 };
<ide> script = new Script(code);
<add>/* eslint-disable no-unused-vars */
<ide> var baz = script.runInNewContext(obj);
<add>/* eslint-enable no-unused-vars */
<ide> assert.equal(1, obj.foo);
<ide> assert.equal(2, obj.bar);
<ide> assert.equal(2, foo);
<ide><path>test/parallel/test-vm-run-in-new-context.js
<ide> code = 'foo = 1;' +
<ide> 'if (baz !== 3) throw new Error(\'test fail\');';
<ide> foo = 2;
<ide> obj = { foo: 0, baz: 3 };
<add>/* eslint-disable no-unused-vars */
<ide> var baz = vm.runInNewContext(code, obj);
<add>/* eslint-enable no-unused-vars */
<ide> assert.equal(1, obj.foo);
<ide> assert.equal(2, obj.bar);
<ide> assert.equal(2, foo);
<ide><path>test/parallel/test-vm-static-this.js
<ide> code = 'foo = 1;' +
<ide> 'if (typeof baz !== \'undefined\') throw new Error(\'test fail\');';
<ide> foo = 2;
<ide> obj = { foo: 0, baz: 3 };
<add>/* eslint-disable no-unused-vars */
<ide> var baz = vm.runInThisContext(code);
<add>/* eslint-enable no-unused-vars */
<ide> assert.equal(0, obj.foo);
<ide> assert.equal(2, bar);
<ide> assert.equal(1, foo);
<ide><path>test/pummel/test-dtrace-jsstack.js
<ide> var doogle = function() {
<ide> };
<ide>
<ide> var spawn = require('child_process').spawn;
<del>var prefix = '/var/tmp/node';
<ide>
<ide> /*
<ide> * We're going to use DTrace to stop us, gcore us, and set us running again
<ide><path>test/pummel/test-fs-watch-file.js
<ide> var watchSeenTwo = 0;
<ide> var watchSeenThree = 0;
<ide> var watchSeenFour = 0;
<ide>
<del>var startDir = process.cwd();
<ide> var testDir = common.tmpDir;
<ide>
<ide> var filenameOne = 'watch.txt';
<ide><path>test/pummel/test-https-no-reader.js
<ide> var options = {
<ide> };
<ide>
<ide> var buf = new Buffer(1024 * 1024);
<del>var sent = 0;
<del>var received = 0;
<ide>
<ide> var server = https.createServer(options, function(req, res) {
<ide> res.writeHead(200);
<ide> var server = https.createServer(options, function(req, res) {
<ide> });
<ide>
<ide> server.listen(common.PORT, function() {
<del> var resumed = false;
<ide> var req = https.request({
<ide> method: 'POST',
<ide> port: common.PORT,
<ide><path>test/pummel/test-regress-GH-892.js
<ide> var https = require('https');
<ide>
<ide> var fs = require('fs');
<ide>
<del>var PORT = 8000;
<del>
<del>
<ide> var bytesExpected = 1024 * 1024 * 32;
<del>var gotResponse = false;
<ide>
<ide> var started = false;
<ide>
<ide><path>test/pummel/test-stream2-basic.js
<ide> test('pipe', function(t) {
<ide> 'xxxxx' ];
<ide>
<ide> var w = new TestWriter();
<del> var flush = true;
<ide>
<ide> w.on('end', function(received) {
<ide> t.same(received, expect);
<ide> test('adding readable triggers data flow', function(t) {
<ide> r.push(new Buffer('asdf'));
<ide> };
<ide>
<del> var called = false;
<ide> r.on('readable', function() {
<ide> onReadable = true;
<ide> r.read();
<ide><path>test/pummel/test-timers.js
<ide> function t() {
<ide> expectedTimeouts--;
<ide> }
<ide>
<del>var w = setTimeout(t, 200);
<del>var x = setTimeout(t, 200);
<add>setTimeout(t, 200);
<add>setTimeout(t, 200);
<ide> var y = setTimeout(t, 200);
<ide>
<ide> clearTimeout(y);
<del>var z = setTimeout(t, 200);
<add>setTimeout(t, 200);
<ide> clearTimeout(y);
<ide>
<ide>
<ide><path>test/pummel/test-watch-file.js
<ide> var fs = require('fs');
<ide> var path = require('path');
<ide>
<ide> var f = path.join(common.fixturesDir, 'x.txt');
<del>var f2 = path.join(common.fixturesDir, 'x2.txt');
<ide>
<ide> console.log('watching for changes of ' + f);
<ide>
<ide><path>test/sequential/test-stream2-fs.js
<ide> 'use strict';
<ide> var common = require('../common');
<del>var R = require('_stream_readable');
<ide> var assert = require('assert');
<ide>
<ide> var fs = require('fs');
<ide> var w = new TestWriter();
<ide> w.on('results', function(res) {
<ide> console.error(res, w.length);
<ide> assert.equal(w.length, size);
<del> var l = 0;
<ide> assert.deepEqual(res.map(function(c) {
<ide> return c.length;
<ide> }), expectLengths);
<ide><path>test/sequential/test-tcp-wrap-listen.js
<ide> assert.equal(0, r);
<ide>
<ide> server.listen(128);
<ide>
<del>var slice, sliceCount = 0, eofCount = 0;
<add>var sliceCount = 0, eofCount = 0;
<ide>
<ide> var writeCount = 0;
<ide> var recvCount = 0;
<ide><path>test/timers/test-timers-reliability.js
<ide> monoTimer.ontimeout = function() {
<ide>
<ide> monoTimer.start(300, 0);
<ide>
<del>var timer = setTimeout(function() {
<add>setTimeout(function() {
<ide> timerFired = true;
<ide> }, 200);
<ide>
| 24
|
Ruby
|
Ruby
|
improve error when encryptedfile key length wrong
|
0fc7448fc5ae8124a65f75b9fa79fc8346d243b9
|
<ide><path>activesupport/lib/active_support/encrypted_file.rb
<ide> def initialize(key_path:, env_key:)
<ide> end
<ide> end
<ide>
<add> class InvalidKeyLengthError < RuntimeError
<add> def initialize
<add> super "Encryption key must be exactly #{EncryptedFile.expected_key_length} characters."
<add> end
<add> end
<add>
<ide> CIPHER = "aes-128-gcm"
<ide>
<ide> def self.generate_key
<ide> SecureRandom.hex(ActiveSupport::MessageEncryptor.key_len(CIPHER))
<ide> end
<ide>
<add> def self.expected_key_length # :nodoc:
<add> @expected_key_length ||= generate_key.length
<add> end
<add>
<ide>
<ide> attr_reader :content_path, :key_path, :env_key, :raise_if_missing_key
<ide>
<ide> def writing(contents)
<ide>
<ide>
<ide> def encrypt(contents)
<add> check_key_length
<ide> encryptor.encrypt_and_sign contents
<ide> end
<ide>
<ide> def read_env_key
<ide> end
<ide>
<ide> def read_key_file
<del> key_path.binread.strip if key_path.exist?
<add> return @key_file_contents if defined?(@key_file_contents)
<add> @key_file_contents = (key_path.binread.strip if key_path.exist?)
<ide> end
<ide>
<ide> def handle_missing_key
<ide> raise MissingKeyError.new(key_path: key_path, env_key: env_key) if raise_if_missing_key
<ide> end
<add>
<add> def check_key_length
<add> raise InvalidKeyLengthError if key&.length != self.class.expected_key_length
<add> end
<ide> end
<ide> end
<ide><path>activesupport/test/encrypted_file_test.rb
<ide> class EncryptedFileTest < ActiveSupport::TestCase
<ide> end
<ide> end
<ide>
<add> test "raise InvalidKeyLengthError when key is too short" do
<add> File.write(@key_path, ActiveSupport::EncryptedFile.generate_key[0..-2])
<add>
<add> assert_raise ActiveSupport::EncryptedFile::InvalidKeyLengthError do
<add> @encrypted_file.write(@content)
<add> end
<add> end
<add>
<add> test "raise InvalidKeyLengthError when key is too long" do
<add> File.write(@key_path, ActiveSupport::EncryptedFile.generate_key + "0")
<add>
<add> assert_raise ActiveSupport::EncryptedFile::InvalidKeyLengthError do
<add> @encrypted_file.write(@content)
<add> end
<add> end
<add>
<ide> test "respects existing content_path symlink" do
<ide> @encrypted_file.write(@content)
<ide>
| 2
|
Python
|
Python
|
fix linting issues
|
3e20b0110cc30c112906cc473e04e837737ff4f5
|
<ide><path>tests/test_description.py
<ide> class that can be converted to a string.
<ide> class MockLazyStr(object):
<ide> def __init__(self, string):
<ide> self.s = string
<add>
<ide> def __str__(self):
<ide> return self.s
<add>
<ide> def __unicode__(self):
<ide> return self.s
<ide>
| 1
|
Ruby
|
Ruby
|
add tests for patches
|
9c28138889055f8a3af5e32bab4059b6a9a8a87f
|
<ide><path>Library/Homebrew/cmd/audit.rb
<ide> require 'formula'
<ide> require 'utils'
<add>require 'extend/ENV'
<add>
<add># Some formulae use ENV in patches, so set up an environment
<add>ENV.extend(HomebrewEnvExtension)
<add>ENV.setup_build_environment
<add>
<add>class Module
<add> def redefine_const(name, value)
<add> __send__(:remove_const, name) if const_defined?(name)
<add> const_set(name, value)
<add> end
<add>end
<ide>
<ide> def ff
<ide> return Formula.all if ARGV.named.empty?
<ide> def audit_formula_version f, text
<ide> return []
<ide> end
<ide>
<add>def audit_formula_patches f
<add> problems = []
<add> patches = Patches.new(f.patches)
<add> patches.each do |p|
<add> next unless p.external?
<add> if p.url =~ %r[raw\.github\.com]
<add> problems << " * Using raw GitHub URLs is not recommended:"
<add> problems << " * #{p.url}"
<add> end
<add> end
<add> return problems
<add>end
<add>
<ide> def audit_formula_urls f
<ide> problems = []
<ide>
<ide> def audit_formula_instance f
<ide> return problems
<ide> end
<ide>
<add># Formula extensions for auditing
<add>class Formula
<add> def head_only?
<add> @unstable and @standard.nil?
<add> end
<add>
<add> def formula_text
<add> File.open(@path, "r") { |afile| return afile.read }
<add> end
<add>end
<add>
<ide> module Homebrew extend self
<ide> def audit
<ide> errors = false
<ide> def audit
<ide> problem_count = 0
<ide>
<ide> ff.each do |f|
<del> problems = []
<del>
<del> if f.unstable and f.standard.nil?
<del> problems += [' * head-only formula']
<del> end
<add> # We need to do this in case the formula defines a patch that uses DATA.
<add> f.class.redefine_const :DATA, ""
<ide>
<add> problems = []
<add> problems += [' * head-only formula'] if f.head_only?
<ide> problems += audit_formula_instance f
<ide> problems += audit_formula_urls f
<add> problems += audit_formula_patches f
<ide>
<ide> perms = File.stat(f.path).mode
<ide> if perms.to_s(8) != "100644"
<ide> problems << " * permissions wrong; chmod 644 #{f.path}"
<ide> end
<ide>
<del> text = ""
<del> File.open(f.path, "r") { |afile| text = afile.read }
<add> text = f.formula_text
<ide>
<ide> # DATA with no __END__
<ide> if (text =~ /\bDATA\b/) and not (text =~ /^\s*__END__\s*$/)
| 1
|
Javascript
|
Javascript
|
optimize trig functions
|
848a6e201db1621e2ee0f3118a52a3264273cd8b
|
<ide><path>examples/js/loaders/SVGLoader.js
<ide> THREE.SVGLoader.prototype = {
<ide>
<ide> var rotation = createIdTransform();
<ide>
<del> rotation[ 0 ] = Math.cos( angle );
<del> rotation[ 1 ] = Math.sin( angle );
<del> rotation[ 2 ] = -Math.sin( angle );
<del> rotation[ 3 ] = Math.cos( angle );
<add> var c = Math.cos( angle );
<add> var s = Math.sin( angle );
<add>
<add> rotation[ 0 ] = c;
<add> rotation[ 1 ] = s;
<add> rotation[ 2 ] = - s;
<add> rotation[ 3 ] = c;
<ide>
<ide> return rotation;
<ide>
| 1
|
Python
|
Python
|
fix import problem
|
5e385c922b18cb35fc02f244bc59e9cdf96e9f6c
|
<ide><path>numpy/numarray/functions.py
<ide> __all__ += ['vdot', 'dot', 'matrixmultiply', 'ravel', 'indices',
<ide> 'arange', 'concatenate']
<ide>
<del>from numpy import dot as matrixmultiply, dot, vdot, ravel
<add>from numpy import dot as matrixmultiply, dot, vdot, ravel, concatenate
<ide>
<ide> def array(sequence=None, typecode=None, copy=1, savespace=0,
<ide> type=None, shape=None, dtype=None):
| 1
|
Text
|
Text
|
add windowsverbatimarguments docs
|
41611f9adbae7b846c16580ff9eb0f4a8a87a08b
|
<ide><path>doc/api/child_process.md
<ide> changes:
<ide> * `gid` {number} Sets the group identity of the process (see setgid(2)).
<ide> * `windowsHide` {boolean} Hide the subprocess console window that would
<ide> normally be created on Windows systems. **Default:** `false`.
<add> * `windowsVerbatimArguments` {boolean} No quoting or escaping of arguments is
<add> done on Windows. Ignored on Unix. **Default:** `false`.
<ide> * `callback` {Function} Called with the output when process terminates.
<ide> * `error` {Error}
<ide> * `stdout` {string|Buffer}
<ide> changes:
<ide> When this option is provided, it overrides `silent`. If the array variant
<ide> is used, it must contain exactly one item with value `'ipc'` or an error
<ide> will be thrown. For instance `[0, 1, 2, 'ipc']`.
<add> * `windowsVerbatimArguments` {boolean} No quoting or escaping of arguments is
<add> done on Windows. Ignored on Unix. **Default:** `false`.
<ide> * `uid` {number} Sets the user identity of the process (see setuid(2)).
<ide> * `gid` {number} Sets the group identity of the process (see setgid(2)).
<ide> * Returns: {ChildProcess}
<ide> changes:
<ide> `'/bin/sh'` on UNIX, and `process.env.ComSpec` on Windows. A different
<ide> shell can be specified as a string. See [Shell Requirements][] and
<ide> [Default Windows Shell][]. **Default:** `false` (no shell).
<add> * `windowsVerbatimArguments` {boolean} No quoting or escaping of arguments is
<add> done on Windows. Ignored on Unix. This is set to `true` automatically
<add> when `shell` is specified. **Default:** `false`.
<ide> * `windowsHide` {boolean} Hide the subprocess console window that would
<ide> normally be created on Windows systems. **Default:** `false`.
<ide> * Returns: {ChildProcess}
<ide> changes:
<ide> `'/bin/sh'` on UNIX, and `process.env.ComSpec` on Windows. A different
<ide> shell can be specified as a string. See [Shell Requirements][] and
<ide> [Default Windows Shell][]. **Default:** `false` (no shell).
<add> * `windowsVerbatimArguments` {boolean} No quoting or escaping of arguments is
<add> done on Windows. Ignored on Unix. This is set to `true` automatically
<add> when `shell` is specified. **Default:** `false`.
<ide> * `windowsHide` {boolean} Hide the subprocess console window that would
<ide> normally be created on Windows systems. **Default:** `false`.
<ide> * Returns: {Object}
| 1
|
Text
|
Text
|
consolidate ci sections
|
bcc68c36b6c53bb8af6b2523ae694718e1186810
|
<ide><path>doc/contributing/pull-requests.md
<ide> * [Notes](#notes)
<ide> * [Commit squashing](#commit-squashing)
<ide> * [Getting approvals for your pull request](#getting-approvals-for-your-pull-request)
<del> * [CI testing](#ci-testing)
<ide> * [Waiting until the pull request gets landed](#waiting-until-the-pull-request-gets-landed)
<ide> * [Check out the collaborator guide](#check-out-the-collaborator-guide)
<ide> * [Appendix: subsystems](#appendix-subsystems)
<ide> feedback.
<ide> All pull requests that contain changes to code must be run through
<ide> continuous integration (CI) testing at [https://ci.nodejs.org/][].
<ide>
<del>Only Node.js core collaborators with commit rights to the `nodejs/node`
<del>repository may start a CI testing run. The specific details of how to do
<del>this are included in the new collaborator [Onboarding guide][].
<add>Only Node.js core collaborators and triagers can start a CI testing run. The
<add>specific details of how to do this are included in the new collaborator
<add>[Onboarding guide][]. Usually, a collaborator or triager will start a CI
<add>test run for you as approvals for the pull request come in.
<add>If not, you can ask a collaborator or triager to start a CI run.
<ide>
<ide> Ideally, the code change will pass ("be green") on all platform configurations
<del>supported by Node.js (there are over 30 platform configurations currently).
<del>This means that all tests pass and there are no linting errors. In reality,
<del>however, it is not uncommon for the CI infrastructure itself to fail on
<del>specific platforms or for so-called "flaky" tests to fail ("be red"). It is
<del>vital to visually inspect the results of all failed ("red") tests to determine
<del>whether the failure was caused by the changes in the pull request.
<add>supported by Node.js. This means that all tests pass and there are no linting
<add>errors. In reality, however, it is not uncommon for the CI infrastructure itself
<add>to fail on specific platforms or for so-called "flaky" tests to fail ("be red").
<add>It is vital to visually inspect the results of all failed ("red") tests to
<add>determine whether the failure was caused by the changes in the pull request.
<ide>
<ide> ## Notes
<ide>
<ide> After you push new changes to your branch, you need to get
<ide> approval for these new changes again, even if GitHub shows "Approved"
<ide> because the reviewers have hit the buttons before.
<ide>
<del>### CI testing
<del>
<del>Every pull request needs to be tested
<del>to make sure that it works on the platforms that Node.js
<del>supports. This is done by running the code through the CI system.
<del>
<del>Only a collaborator can start a CI run. Usually one of them will do it
<del>for you as approvals for the pull request come in.
<del>If not, you can ask a collaborator to start a CI run.
<del>
<ide> ### Waiting until the pull request gets landed
<ide>
<ide> A pull request needs to stay open for at least 48 hours from when it is
<ide> You can find the full list of supported subsystems in the
<ide> More than one subsystem may be valid for any particular issue or pull request.
<ide>
<ide> [Building guide]: ../../BUILDING.md
<del>[CI (Continuous Integration) test run]: #ci-testing
<add>[CI (Continuous Integration) test run]: #continuous-integration-testing
<ide> [Code of Conduct]: https://github.com/nodejs/admin/blob/HEAD/CODE_OF_CONDUCT.md
<ide> [Onboarding guide]: ../../onboarding.md
<ide> [approved]: #getting-approvals-for-your-pull-request
| 1
|
PHP
|
PHP
|
use fqns in the validation exception docblocks
|
a416ceb1b77c0bfe7c86a7dbe1274f0cc53fe0ee
|
<ide><path>src/Illuminate/Contracts/Validation/ValidationException.php
<ide> class ValidationException extends RuntimeException {
<ide> /**
<ide> * The message provider implementation.
<ide> *
<del> * @var MessageProvider
<add> * @var \Illuminate\Contracts\Support\MessageProvider
<ide> */
<ide> protected $provider;
<ide>
<ide> /**
<ide> * Create a new validation exception instance.
<ide> *
<del> * @param MessageProvider $provider
<add> * @param \Illuminate\Contracts\Support\MessageProvider $provider
<ide> * @return void
<ide> */
<ide> public function __construct(MessageProvider $provider)
<ide> public function __construct(MessageProvider $provider)
<ide> /**
<ide> * Get the validation error message provider.
<ide> *
<del> * @return MessagesProvider
<add> * @return \Illuminate\Contracts\Support\MessageProvider
<ide> */
<ide> public function errors()
<ide> {
<ide> public function errors()
<ide> /**
<ide> * Get the validation error message provider.
<ide> *
<del> * @return MessagesProvider
<add> * @return \Illuminate\Contracts\Support\MessageProvider
<ide> */
<ide> public function getMessageProvider()
<ide> {
| 1
|
Text
|
Text
|
alter other reference to migrations
|
db4426fc35a92d2b0e263fd8a5702203cb3e06ed
|
<ide><path>docs/api-guide/authentication.md
<ide> To use the `TokenAuthentication` scheme you'll need to [configure the authentica
<ide>
<ide> ---
<ide>
<del>**Note:** Make sure to run `manage.py syncdb` after changing your settings. Both Django native (from v1.7) and South migrations for the `authtoken` database tables are provided. See [Schema migrations](#schema-migrations) below.
<add>**Note:** Make sure to run `manage.py syncdb` after changing your settings. The 'rest_framework.authtoken' provides both Django (from v1.7) and South database migrations. See [Schema migrations](#schema-migrations) below.
<ide>
<ide> ---
<ide>
| 1
|
Text
|
Text
|
fix a typo in the action pack changelog [ci skip]
|
08433f2fd0de84a260e794e10ecf4e1be9327886
|
<ide><path>actionpack/CHANGELOG.md
<del>* Introduce a new error page to when the implict render page is accessed in the browser.
<add>* Introduce a new error page to when the implicit render page is accessed in the browser.
<ide>
<ide> Now instead of showing an error page that with exception and backtraces we now show only
<ide> one informative page.
| 1
|
Go
|
Go
|
allow fallback on unknown errors
|
a21ba12f4e7f11c17e6d665716f3060b9923b11c
|
<ide><path>registry/registry.go
<ide> import (
<ide> "github.com/Sirupsen/logrus"
<ide> "github.com/docker/distribution/registry/api/errcode"
<ide> "github.com/docker/distribution/registry/api/v2"
<add> "github.com/docker/distribution/registry/client"
<ide> "github.com/docker/distribution/registry/client/transport"
<ide> "github.com/docker/docker/autogen/dockerversion"
<ide> "github.com/docker/docker/pkg/parsers/kernel"
<ide> func ContinueOnError(err error) bool {
<ide> return ContinueOnError(v.Err)
<ide> case errcode.Error:
<ide> return shouldV2Fallback(v)
<add> case *client.UnexpectedHTTPResponseError:
<add> return true
<ide> }
<del> return false
<add> // let's be nice and fallback if the error is a completely
<add> // unexpected one.
<add> // If new errors have to be handled in some way, please
<add> // add them to the switch above.
<add> return true
<ide> }
<ide>
<ide> // NewTransport returns a new HTTP transport. If tlsConfig is nil, it uses the
| 1
|
PHP
|
PHP
|
allow testing of a specific status code
|
b8729125dc52eaf5c9e190c594203e5dc887125b
|
<ide><path>src/TestSuite/IntegrationTestCase.php
<ide> public function assertResponseFailure() {
<ide> $this->_assertStatus(500, 505, 'Status code is not between 500 and 505');
<ide> }
<ide>
<add>/**
<add> * Assert a specific response status code.
<add> *
<add> * @return void
<add> */
<add> public function assertResponse($code) {
<add> $actual = $this->_response->statusCode();
<add> $this->_assertStatus($code, $code, 'Status code is not ' . $code . ' but ' . $actual);
<add> }
<add>
<ide> /**
<ide> * Helper method for status assertions.
<ide> *
| 1
|
PHP
|
PHP
|
add version to deprecations
|
50aef1c4f82897b8cb1c953ab0365c59f20905c9
|
<ide><path>src/ORM/Association.php
<ide> public function getName()
<ide> /**
<ide> * Sets the name for this association.
<ide> *
<del> * @deprecated Use setName()/getName() instead.
<add> * @deprecated 3.4.0 Use setName()/getName() instead.
<ide> * @param string|null $name Name to be assigned
<ide> * @return string
<ide> */
<ide> public function getCascadeCallbacks()
<ide> * Sets whether or not cascaded deletes should also fire callbacks. If no
<ide> * arguments are passed, the current configured value is returned
<ide> *
<del> * @deprecated Use setCascadeCallbacks()/getCascadeCallbacks() instead.
<add> * @deprecated 3.4.0 Use setCascadeCallbacks()/getCascadeCallbacks() instead.
<ide> * @param bool|null $cascadeCallbacks cascade callbacks switch value
<ide> * @return bool
<ide> */
<ide> public function getSource()
<ide> * Sets the table instance for the source side of the association. If no arguments
<ide> * are passed, the current configured table instance is returned
<ide> *
<del> * @deprecated Use setSource()/getSource() instead.
<add> * @deprecated 3.4.0 Use setSource()/getSource() instead.
<ide> * @param \Cake\ORM\Table|null $table the instance to be assigned as source side
<ide> * @return \Cake\ORM\Table
<ide> */
<ide> public function getTarget()
<ide> * Sets the table instance for the target side of the association. If no arguments
<ide> * are passed, the current configured table instance is returned
<ide> *
<del> * @deprecated Use setTable()/getTable() instead.
<add> * @deprecated 3.4.0 Use setTable()/getTable() instead.
<ide> * @param \Cake\ORM\Table|null $table the instance to be assigned as target side
<ide> * @return \Cake\ORM\Table
<ide> */
<ide> public function getConditions()
<ide> * Sets a list of conditions to be always included when fetching records from
<ide> * the target association. If no parameters are passed the current list is returned
<ide> *
<del> * @deprecated Use setConditions()/getConditions() instead.
<add> * @deprecated 3.4.0 Use setConditions()/getConditions() instead.
<ide> * @param array|null $conditions list of conditions to be used
<ide> * @see \Cake\Database\Query::where() for examples on the format of the array
<ide> * @return array
<ide> public function getBindingKey()
<ide> *
<ide> * If no parameters are passed the current field is returned
<ide> *
<del> * @deprecated Use setBindingKey()/getBindingKey() instead.
<add> * @deprecated 3.4.0 Use setBindingKey()/getBindingKey() instead.
<ide> * @param string|null $key the table field to be used to link both tables together
<ide> * @return string|array
<ide> */
<ide> public function setForeignKey($key)
<ide> * Sets the name of the field representing the foreign key to the target table.
<ide> * If no parameters are passed the current field is returned
<ide> *
<del> * @deprecated Use setForeignKey()/getForeignKey() instead.
<add> * @deprecated 3.4.0 Use setForeignKey()/getForeignKey() instead.
<ide> * @param string|null $key the key to be used to link both tables together
<ide> * @return string|array
<ide> */
<ide> public function getDependent()
<ide> *
<ide> * If no parameters are passed the current setting is returned.
<ide> *
<del> * @deprecated Use setDependent()/getDependent() instead.
<add> * @deprecated 3.4.0 Use setDependent()/getDependent() instead.
<ide> * @param bool|null $dependent Set the dependent mode. Use null to read the current state.
<ide> * @return bool
<ide> */
<ide> public function getJoinType()
<ide> * Sets the type of join to be used when adding the association to a query.
<ide> * If no arguments are passed, the currently configured type is returned.
<ide> *
<del> * @deprecated Use setJoinType()/getJoinType() instead.
<add> * @deprecated 3.4.0 Use setJoinType()/getJoinType() instead.
<ide> * @param string|null $type the join type to be used (e.g. INNER)
<ide> * @return string
<ide> */
<ide> public function getProperty()
<ide> * in the source table record.
<ide> * If no arguments are passed, the currently configured type is returned.
<ide> *
<del> * @deprecated Use setProperty()/getProperty() instead.
<add> * @deprecated 3.4.0 Use setProperty()/getProperty() instead.
<ide> * @param string|null $name The name of the association property. Use null to read the current value.
<ide> * @return string
<ide> */
<ide> public function getStrategy()
<ide> * rendering any changes to this setting void.
<ide> * If no arguments are passed, the currently configured strategy is returned.
<ide> *
<del> * @deprecated Use setStrategy()/getStrategy() instead.
<add> * @deprecated 3.4.0 Use setStrategy()/getStrategy() instead.
<ide> * @param string|null $name The strategy type. Use null to read the current value.
<ide> * @return string
<ide> * @throws \InvalidArgumentException When an invalid strategy is provided.
<ide> public function setFinder($finder)
<ide> * If no parameters are passed, it will return the currently configured
<ide> * finder name.
<ide> *
<del> * @deprecated Use setFinder()/getFinder() instead.
<add> * @deprecated 3.4.0 Use setFinder()/getFinder() instead.
<ide> * @param string|null $finder the finder name to use
<ide> * @return string
<ide> */
<ide><path>src/ORM/Association/BelongsTo.php
<ide> public function getForeignKey()
<ide> * Sets the name of the field representing the foreign key to the target table.
<ide> * If no parameters are passed current field is returned
<ide> *
<del> * @deprecated Use setForeignKey()/getForeignKey() instead.
<add> * @deprecated 3.4.0 Use setForeignKey()/getForeignKey() instead.
<ide> * @param string|null $key the key to be used to link both tables together
<ide> * @return string
<ide> */
<ide><path>src/ORM/Association/BelongsToMany.php
<ide> public function getTargetForeignKey()
<ide> * Sets the name of the field representing the foreign key to the target table.
<ide> * If no parameters are passed current field is returned
<ide> *
<del> * @deprecated Use setTargetForeignKey()/getTargetForeignKey() instead.
<add> * @deprecated 3.4.0 Use setTargetForeignKey()/getTargetForeignKey() instead.
<ide> * @param string|null $key the key to be used to link both tables together
<ide> * @return string
<ide> */
<ide> public function getSaveStrategy()
<ide> * Sets the strategy that should be used for saving. If called with no
<ide> * arguments, it will return the currently configured strategy
<ide> *
<del> * @deprecated Use setSaveStrategy()/getSaveStrategy() instead.
<add> * @deprecated 3.4.0 Use setSaveStrategy()/getSaveStrategy() instead.
<ide> * @param string|null $strategy the strategy name to be used
<ide> * @throws \InvalidArgumentException if an invalid strategy name is passed
<ide> * @return string the strategy to be used for saving
<ide> public function setConditions($conditions)
<ide>
<ide> /**
<ide> * {@inheritDoc}
<del> * @deprecated Use setConditions()/getConditions() instead.
<add> * @deprecated 3.4.0 Use setConditions()/getConditions() instead.
<ide> */
<ide> public function conditions($conditions = null)
<ide> {
<ide><path>src/ORM/Association/HasMany.php
<ide> public function getSaveStrategy()
<ide> * Sets the strategy that should be used for saving. If called with no
<ide> * arguments, it will return the currently configured strategy
<ide> *
<del> * @deprecated Use setSaveStrategy()/getSaveStrategy() instead.
<add> * @deprecated 3.4.0 Use setSaveStrategy()/getSaveStrategy() instead.
<ide> * @param string|null $strategy the strategy name to be used
<ide> * @throws \InvalidArgumentException if an invalid strategy name is passed
<ide> * @return string the strategy to be used for saving
<ide> public function getForeignKey()
<ide> * Sets the name of the field representing the foreign key to the source table.
<ide> * If no parameters are passed current field is returned
<ide> *
<del> * @deprecated Use setForeignKey()/getForeignKey() instead.
<add> * @deprecated 3.4.0 Use setForeignKey()/getForeignKey() instead.
<ide> * @param string|null $key the key to be used to link both tables together
<ide> * @return string
<ide> */
<ide> public function getSort()
<ide> * Sets the sort order in which target records should be returned.
<ide> * If no arguments are passed the currently configured value is returned
<ide> *
<del> * @deprecated Use setSort()/getSort() instead.
<add> * @deprecated 3.4.0 Use setSort()/getSort() instead.
<ide> * @param mixed $sort A find() compatible order clause
<ide> * @return mixed
<ide> */
<ide><path>src/ORM/Association/HasOne.php
<ide> public function getForeignKey()
<ide> * Sets the name of the field representing the foreign key to the target table.
<ide> * If no parameters are passed current field is returned
<ide> *
<del> * @deprecated Use setForeignKey()/getForeignKey() instead.
<add> * @deprecated 3.4.0 Use setForeignKey()/getForeignKey() instead.
<ide> * @param string|null $key the key to be used to link both tables together
<ide> * @return string
<ide> */
| 5
|
Javascript
|
Javascript
|
remove unnecessary finddomnode calls
|
e25d899d23972f0e99a7ed1068991dfa273786e5
|
<ide><path>docs/_js/live_editor.js
<ide> var CodeMirrorEditor = React.createClass({
<ide> componentDidMount: function() {
<ide> if (IS_MOBILE) return;
<ide>
<del> this.editor = CodeMirror.fromTextArea(ReactDOM.findDOMNode(this.refs.editor), {
<add> this.editor = CodeMirror.fromTextArea(this.refs.editor, {
<ide> mode: 'jsx',
<ide> lineNumbers: this.props.lineNumbers,
<ide> lineWrapping: true,
<ide> var ReactPlayground = React.createClass({
<ide> },
<ide>
<ide> executeCode: function() {
<del> var mountNode = ReactDOM.findDOMNode(this.refs.mount);
<add> var mountNode = this.refs.mount;
<ide>
<ide> try {
<ide> ReactDOM.unmountComponentAtNode(mountNode);
| 1
|
Python
|
Python
|
fix indentation in blender exporter script
|
66b101db3fe14ac3ca3efdc46723a8aadd0c56b5
|
<ide><path>utils/exporters/blender/2.65/scripts/addons/io_mesh_threejs/export_threejs.py
<ide> def generate_cameras(data):
<ide> "position" : generate_vec3([cameraobj.location[0], -cameraobj.location[1], cameraobj.location[2]], data["flipyz"]),
<ide> "target" : generate_vec3([0, 0, 0])
<ide> }
<del>
<del> elif camera.id_data.type == "ORTHO":
<add>
<add> elif camera.id_data.type == "ORTHO":
<ide>
<ide> camera_string = TEMPLATE_CAMERA_ORTHO % {
<ide> "camera_id" : generate_string(camera.name),
| 1
|
Javascript
|
Javascript
|
add test for wrapstream readstop
|
9702ac508819a443503867a5c73ae395f9773363
|
<ide><path>test/parallel/test-wrap-js-stream-read-stop.js
<add>// Flags: --expose-internals
<add>'use strict';
<add>
<add>require('../common');
<add>const assert = require('assert');
<add>const WrapStream = require('internal/wrap_js_stream');
<add>const Stream = require('stream');
<add>
<add>class FakeStream extends Stream {
<add> constructor() {
<add> super();
<add> this._paused = false;
<add> }
<add>
<add> pause() {
<add> this._paused = true;
<add> }
<add>
<add> resume() {
<add> this._paused = false;
<add> }
<add>
<add> isPaused() {
<add> return this._paused;
<add> }
<add>}
<add>
<add>const fakeStreamObj = new FakeStream();
<add>const wrappedStream = new WrapStream(fakeStreamObj);
<add>
<add>// Resume by wrapped stream upon construction
<add>assert.strictEqual(fakeStreamObj.isPaused(), false);
<add>
<add>fakeStreamObj.pause();
<add>
<add>assert.strictEqual(fakeStreamObj.isPaused(), true);
<add>
<add>fakeStreamObj.resume();
<add>
<add>assert.strictEqual(wrappedStream.readStop(), 0);
<add>
<add>assert.strictEqual(fakeStreamObj.isPaused(), true);
| 1
|
Python
|
Python
|
add speed log to examples/run_squad.py
|
0919389d9aa03c19bee2ae9bc9922ff15ec8381b
|
<ide><path>examples/run_squad.py
<ide> import os
<ide> import random
<ide> import glob
<add>import timeit
<ide>
<ide> import numpy as np
<ide> import torch
<ide> def evaluate(args, model, tokenizer, prefix=""):
<ide> logger.info(" Num examples = %d", len(dataset))
<ide> logger.info(" Batch size = %d", args.eval_batch_size)
<ide> all_results = []
<add> start_time = timeit.default_timer()
<ide> for batch in tqdm(eval_dataloader, desc="Evaluating"):
<ide> model.eval()
<ide> batch = tuple(t.to(args.device) for t in batch)
<ide> def evaluate(args, model, tokenizer, prefix=""):
<ide> end_logits = to_list(outputs[1][i]))
<ide> all_results.append(result)
<ide>
<add> evalTime = timeit.default_timer() - start_time
<add> logger.info(" Evaluation done in total %f secs (%f sec per example)", evalTime, evalTime / len(dataset))
<add>
<ide> # Compute predictions
<ide> output_prediction_file = os.path.join(args.output_dir, "predictions_{}.json".format(prefix))
<ide> output_nbest_file = os.path.join(args.output_dir, "nbest_predictions_{}.json".format(prefix))
| 1
|
Javascript
|
Javascript
|
fix redeclared vars in doc/json.js
|
c14c12e6baf0c5f4910fc0c33ec610dc5119a0d9
|
<ide><path>tools/doc/json.js
<ide> function processList(section) {
<ide> var type = tok.type;
<ide> if (type === 'space') return;
<ide> if (type === 'list_item_start') {
<add> var n = {};
<ide> if (!current) {
<del> var n = {};
<ide> values.push(n);
<ide> current = n;
<ide> } else {
<ide> current.options = current.options || [];
<ide> stack.push(current);
<del> var n = {};
<ide> current.options.push(n);
<ide> current = n;
<ide> }
<ide> function deepCopy(src, dest) {
<ide> function deepCopy_(src) {
<ide> if (!src) return src;
<ide> if (Array.isArray(src)) {
<del> var c = new Array(src.length);
<add> const c = new Array(src.length);
<ide> src.forEach(function(v, i) {
<ide> c[i] = deepCopy_(v);
<ide> });
<ide> return c;
<ide> }
<ide> if (typeof src === 'object') {
<del> var c = {};
<add> const c = {};
<ide> Object.keys(src).forEach(function(k) {
<ide> c[k] = deepCopy_(src[k]);
<ide> });
| 1
|
Python
|
Python
|
fix additional issue
|
8e3a2e88e905a517e3969f23ad200a5b258fc535
|
<ide><path>celery/backends/base.py
<ide> def fallback_chord_unlock(self, group_id, body, result=None,
<ide>
<ide> def apply_chord(self, header, partial_args, group_id, body,
<ide> options={}, **kwargs):
<del> options['task_id'] = group_id
<del> result = header(*partial_args, **options or {})
<add> fixed_options = dict((k,v) for k,v in options.items() if k!='task_id')
<add> result = header(*partial_args, task_id=group_id, **fixed_options or {})
<ide> self.fallback_chord_unlock(group_id, body, **kwargs)
<ide> return result
<ide>
| 1
|
Go
|
Go
|
make defaultservice.serviceconfig() more idiomatic
|
382b9865202062b2269d796c428c3cfa89a23846
|
<ide><path>registry/config.go
<ide> func newServiceConfig(options ServiceOptions) (*serviceConfig, error) {
<ide> return config, nil
<ide> }
<ide>
<add>// copy constructs a new ServiceConfig with a copy of the configuration in config.
<add>func (config *serviceConfig) copy() *registrytypes.ServiceConfig {
<add> ic := make(map[string]*registrytypes.IndexInfo)
<add> for key, value := range config.IndexConfigs {
<add> ic[key] = value
<add> }
<add> return ®istrytypes.ServiceConfig{
<add> AllowNondistributableArtifactsCIDRs: append([]*registrytypes.NetIPNet(nil), config.AllowNondistributableArtifactsCIDRs...),
<add> AllowNondistributableArtifactsHostnames: append([]string(nil), config.AllowNondistributableArtifactsHostnames...),
<add> InsecureRegistryCIDRs: append([]*registrytypes.NetIPNet(nil), config.InsecureRegistryCIDRs...),
<add> IndexConfigs: ic,
<add> Mirrors: append([]string(nil), config.Mirrors...),
<add> }
<add>}
<add>
<ide> // loadAllowNondistributableArtifacts loads allow-nondistributable-artifacts registries into config.
<ide> func (config *serviceConfig) loadAllowNondistributableArtifacts(registries []string) error {
<ide> cidrs := map[string]*registry.NetIPNet{}
<ide><path>registry/service.go
<ide> func NewService(options ServiceOptions) (Service, error) {
<ide> return &defaultService{config: config}, err
<ide> }
<ide>
<del>// ServiceConfig returns the public registry service configuration.
<add>// ServiceConfig returns a copy of the public registry service's configuration.
<ide> func (s *defaultService) ServiceConfig() *registry.ServiceConfig {
<ide> s.mu.RLock()
<ide> defer s.mu.RUnlock()
<del>
<del> servConfig := registry.ServiceConfig{
<del> AllowNondistributableArtifactsCIDRs: make([]*(registry.NetIPNet), 0),
<del> AllowNondistributableArtifactsHostnames: make([]string, 0),
<del> InsecureRegistryCIDRs: make([]*(registry.NetIPNet), 0),
<del> IndexConfigs: make(map[string]*(registry.IndexInfo)),
<del> Mirrors: make([]string, 0),
<del> }
<del>
<del> // construct a new ServiceConfig which will not retrieve s.Config directly,
<del> // and look up items in s.config with mu locked
<del> servConfig.AllowNondistributableArtifactsCIDRs = append(servConfig.AllowNondistributableArtifactsCIDRs, s.config.ServiceConfig.AllowNondistributableArtifactsCIDRs...)
<del> servConfig.AllowNondistributableArtifactsHostnames = append(servConfig.AllowNondistributableArtifactsHostnames, s.config.ServiceConfig.AllowNondistributableArtifactsHostnames...)
<del> servConfig.InsecureRegistryCIDRs = append(servConfig.InsecureRegistryCIDRs, s.config.ServiceConfig.InsecureRegistryCIDRs...)
<del>
<del> for key, value := range s.config.ServiceConfig.IndexConfigs {
<del> servConfig.IndexConfigs[key] = value
<del> }
<del>
<del> servConfig.Mirrors = append(servConfig.Mirrors, s.config.ServiceConfig.Mirrors...)
<del>
<del> return &servConfig
<add> return s.config.copy()
<ide> }
<ide>
<ide> // LoadAllowNondistributableArtifacts loads allow-nondistributable-artifacts registries for Service.
| 2
|
Text
|
Text
|
update document regarding symbols
|
bb7d8812da67d8117dda6ee5298273e03a58a119
|
<ide><path>docs/getting-started.md
<ide> FIXME: Describe https://github.com/atom/find-and-replace
<ide>
<ide> #### Navigating By Symbols
<ide>
<del>VERIFY: This seems to happen automatically now and cmd+shift+j doesn't seem to work.
<del>
<del>If you want to jump to a method, you can use the ctags-based symbols package.
<del>The `⌘-j` binding opens a list of all symbols in the current file. The
<del>`⌘-shift-j` binding opens a list of all symbols for the current project
<del>based on a tags file. `⌘-.` jumps to the tag for the word currently
<del>under the cursor.
<del>
<del>Make sure you have a tags file generated for the project for
<del>the latter of these two bindings to work. Also, if you're editing CoffeeScript,
<del>it's a good idea to update your `~/.ctags` file to understand the language. Here
<del>is [a good example](https://github.com/kevinsawicki/dotfiles/blob/master/.ctags).
<add>If you want to jump to a method, the `⌘-j` binding opens a list of all symbols
<add>in the current file. `⌘-.` jumps to the tag for the word currently under the cursor.
<add>
<add>To search for symbols across your project use `cmd-shift-j`, but you'll need to
<add>make sure you have a tags file generated for the project Also, if you're editing
<add>CoffeeScript, it's a good idea to update your `~/.ctags` file to understand the
<add>language. Here is [a good example](https://github.com/kevinsawicki/dotfiles/blob/master/.ctags).
<ide>
<ide> ### Split Panes
<ide>
| 1
|
Python
|
Python
|
add possibility to ignore imports in test_fecther
|
5f436238435e960f4172737c55f699db711361d3
|
<ide><path>src/transformers/tokenization_utils_base.py
<ide> def _from_pretrained(
<ide> init_kwargs = init_configuration
<ide>
<ide> if config_tokenizer_class is None:
<del> from .models.auto.configuration_auto import AutoConfig
<add> from .models.auto.configuration_auto import AutoConfig # tests_ignore
<ide>
<ide> # Second attempt. If we have not yet found tokenizer_class, let's try to use the config.
<ide> try:
<ide> def _from_pretrained(
<ide> if config_tokenizer_class is None:
<ide> # Third attempt. If we have not yet found the original type of the tokenizer,
<ide> # we are loading we see if we can infer it from the type of the configuration file
<del> from .models.auto.configuration_auto import CONFIG_MAPPING
<del> from .models.auto.tokenization_auto import TOKENIZER_MAPPING
<add> from .models.auto.configuration_auto import CONFIG_MAPPING # tests_ignore
<add> from .models.auto.tokenization_auto import TOKENIZER_MAPPING # tests_ignore
<ide>
<ide> if hasattr(config, "model_type"):
<ide> config_class = CONFIG_MAPPING.get(config.model_type)
<ide><path>utils/tests_fetcher.py
<ide> def get_module_dependencies(module_fname):
<ide> imported_modules = []
<ide>
<ide> # Let's start with relative imports
<del> relative_imports = re.findall(r"from\s+(\.+\S+)\s+import\s+\S+\s", content)
<add> relative_imports = re.findall(r"from\s+(\.+\S+)\s+import\s+([^\n]+)\n", content)
<add> relative_imports = [mod for mod, imp in relative_imports if "# tests_ignore" not in imp]
<ide> for imp in relative_imports:
<ide> level = 0
<ide> while imp.startswith("."):
<ide> def get_module_dependencies(module_fname):
<ide> # Let's continue with direct imports
<ide> # The import from the transformers module are ignored for the same reason we ignored the
<ide> # main init before.
<del> direct_imports = re.findall(r"from\s+transformers\.(\S+)\s+import\s+\S+\s", content)
<add> direct_imports = re.findall(r"from\s+transformers\.(\S+)\s+import\s+([^\n]+)\n", content)
<add> direct_imports = [mod for mod, imp in direct_imports if "# tests_ignore" not in imp]
<ide> for imp in direct_imports:
<ide> import_parts = imp.split(".")
<ide> dep_parts = ["src", "transformers"] + import_parts
| 2
|
Python
|
Python
|
add an emptygen option for f2py
|
c5cbb4ca9f1e531e44245bfc3ab564c609b8b804
|
<ide><path>numpy/f2py/f2py2e.py
<ide> import os
<ide> import pprint
<ide> import re
<add>from pathlib import Path
<ide>
<ide> from . import crackfortran
<ide> from . import rules
<ide>
<ide> --quiet Run quietly.
<ide> --verbose Run with extra verbosity.
<add> --empty-gen Ensure all possible output files are created
<ide> -v Print f2py version ID and exit.
<ide>
<ide>
<ide> def scaninputline(inputline):
<ide> files, skipfuncs, onlyfuncs, debug = [], [], [], []
<ide> f, f2, f3, f5, f6, f7, f8, f9, f10 = 1, 0, 0, 0, 0, 0, 0, 0, 0
<ide> verbose = 1
<add> emptygen = 0
<ide> dolc = -1
<ide> dolatexdoc = 0
<ide> dorestdoc = 0
<ide> def scaninputline(inputline):
<ide> f7 = 1
<ide> elif l[:15] in '--include-paths':
<ide> f7 = 1
<add> elif l == '--empty-gen':
<add> emptygen = 1
<ide> elif l[0] == '-':
<ide> errmess('Unknown option %s\n' % repr(l))
<ide> sys.exit()
<ide> def scaninputline(inputline):
<ide>
<ide> options['debug'] = debug
<ide> options['verbose'] = verbose
<add> options['emptygen'] = emptygen
<ide> if dolc == -1 and not signsfile:
<ide> options['do-lower'] = 0
<ide> else:
<ide> def callcrackfortran(files, options):
<ide> else:
<ide> for mod in postlist:
<ide> mod["f2py_wrapper_output"] = options["f2py_wrapper_output"]
<add> if options["emptygen"]:
<add> # Generate all possible outputs
<add> for mod in postlist:
<add> m_name = mod["name"]
<add> b_path = options["buildpath"]
<add> Path(f'{b_path}/{m_name}module.c').touch()
<add> Path(f'{b_path}/{m_name}-f2pywrappers.f').touch()
<add> Path(f'{b_path}/{m_name}-f2pywrappers2.f90').touch()
<add> outmess(f' Generating possibly empty wrappers "{m_name}-f2pywrappers.f" and "{m_name}-f2pywrappers2.f90"\n')
<ide> return postlist
<ide>
<ide>
| 1
|
Java
|
Java
|
add getrawstatuscode() to exchangeresult
|
955000699aa7675a698933057d607b4abd603d41
|
<ide><path>spring-test/src/main/java/org/springframework/mock/http/client/reactive/MockClientHttpResponse.java
<ide> public MockClientHttpResponse(HttpStatus status) {
<ide> }
<ide>
<ide> public MockClientHttpResponse(int status) {
<del> Assert.isTrue(status >= 100 && status < 600, "Status must be between 1xx and 5xx");
<add> Assert.isTrue(status > 99 && status < 1000, "Status must be between 100 and 999");
<ide> this.status = status;
<ide> }
<ide>
<ide><path>spring-test/src/main/java/org/springframework/test/web/reactive/server/ExchangeResult.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> public HttpStatus getStatus() {
<ide> return this.response.getStatusCode();
<ide> }
<ide>
<add> /**
<add> * Return the HTTP status code (potentially non-standard and not resolvable
<add> * through the {@link HttpStatus} enum) as an integer.
<add> * @since 5.1.10
<add> */
<add> public int getRawStatusCode() {
<add> return this.response.getRawStatusCode();
<add> }
<add>
<ide> /**
<ide> * Return the response headers received from the server.
<ide> */
<ide><path>spring-test/src/main/java/org/springframework/test/web/reactive/server/StatusAssertions.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> public WebTestClient.ResponseSpec isEqualTo(HttpStatus status) {
<ide> * Assert the response status as an integer.
<ide> */
<ide> public WebTestClient.ResponseSpec isEqualTo(int status) {
<del> int actual = this.exchangeResult.getStatus().value();
<add> int actual = this.exchangeResult.getRawStatusCode();
<ide> this.exchangeResult.assertWithDiagnostics(() -> AssertionErrors.assertEquals("Status", status, actual));
<ide> return this.responseSpec;
<ide> }
<ide><path>spring-test/src/test/java/org/springframework/test/web/reactive/server/StatusAssertionTests.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> public void isEqualTo() {
<ide> }
<ide> }
<ide>
<add> @Test // gh-23630
<add> public void isEqualToWithCustomStatus() {
<add> statusAssertions(600).isEqualTo(600);
<add> }
<add>
<ide> @Test
<ide> public void reasonEquals() {
<ide> StatusAssertions assertions = statusAssertions(HttpStatus.CONFLICT);
<ide> public void matches() {
<ide>
<ide>
<ide> private StatusAssertions statusAssertions(HttpStatus status) {
<add> return statusAssertions(status.value());
<add> }
<add>
<add> private StatusAssertions statusAssertions(int status) {
<ide> MockClientHttpRequest request = new MockClientHttpRequest(HttpMethod.GET, URI.create("/"));
<ide> MockClientHttpResponse response = new MockClientHttpResponse(status);
<ide>
| 4
|
Text
|
Text
|
fix description about the latest-codename
|
fde18b24f105d4a70cf1fda714f93a35722bf517
|
<ide><path>README.md
<ide> Binaries, installers, and source tarballs are available at
<ide> <https://nodejs.org/download/release/>, listed under their version strings.
<ide> The [latest](https://nodejs.org/download/release/latest/) directory is an
<ide> alias for the latest Stable release. The latest LTS release from an LTS
<del>line is available in the form: latest-lts-_codename_. For example:
<del><https://nodejs.org/download/release/latest-lts-argon>
<add>line is available in the form: latest-_codename_. For example:
<add><https://nodejs.org/download/release/latest-argon>
<ide>
<ide> **Nightly** builds are available at
<ide> <https://nodejs.org/download/nightly/>, listed under their version
| 1
|
Text
|
Text
|
update changelog with 1.2.27
|
5c611e898a1a62f1a7b1e0da7bb5a5b08d7f00f6
|
<ide><path>CHANGELOG.md
<add><a name="1.2.27"></a>
<add># 1.2.27 prime-factorization (2014-11-20)
<add>
<add>
<add>## Bug Fixes
<add>
<add>- **$animate:** clear the GCS cache even when no animation is detected
<add> ([f619d032](https://github.com/angular/angular.js/commit/f619d032c932752313c646b5295bad8a68ef3871),
<add> [#8813](https://github.com/angular/angular.js/issues/8813))
<add>- **$browser:**
<add> - Cache `location.href` only during page reload phase
<add> ([434d7a09](https://github.com/angular/angular.js/commit/434d7a09039151c1e627ac156213905d06b7df10),
<add> [#9235](https://github.com/angular/angular.js/issues/9235), [#9470](https://github.com/angular/angular.js/issues/9470))
<add> - don’t use history api when only the hash changes
<add> ([a6e6438d](https://github.com/angular/angular.js/commit/a6e6438dae1ed92b29608d0b8830b0a7fbb624ef),
<add> [#9423](https://github.com/angular/angular.js/issues/9423), [#9424](https://github.com/angular/angular.js/issues/9424))
<add> - handle async href on url change in <=IE9
<add> ([fe7d9ded](https://github.com/angular/angular.js/commit/fe7d9dedaa5ec3b3f56d9eb9c513cf99e40121ce),
<add> [#9235](https://github.com/angular/angular.js/issues/9235))
<add>- **$http:** add missing shortcut methods and missing docs
<add> ([ec4fe1bc](https://github.com/angular/angular.js/commit/ec4fe1bcab6f981103a10f860a3a00122aa78607),
<add> [#9180](https://github.com/angular/angular.js/issues/9180), [#9321](https://github.com/angular/angular.js/issues/9321))
<add>- **$location:**
<add> - revert erroneous logic and backport refactorings from master
<add> ([1ee9b4ef](https://github.com/angular/angular.js/commit/1ee9b4ef5e4a795061d3aa19adefdeb7e0209eeb),
<add> [#8492](https://github.com/angular/angular.js/issues/8492))
<add> - allow 0 in path() and hash()
<add> ([f807d7ab](https://github.com/angular/angular.js/commit/f807d7ab4ebd18899154528ea9ed50d5bc25c57a))
<add>- **$parse:** add quick check for Function constructor in fast path
<add> ([756640f5](https://github.com/angular/angular.js/commit/756640f5aa8f3fd0084bff50534e23976a6fff00))
<add>- **$parse, events:** prevent accidental misuse of properties on $event
<add> ([4d0614fd](https://github.com/angular/angular.js/commit/4d0614fd0da12c5783dfb4956c330edac87e62fe),
<add> [#9969](https://github.com/angular/angular.js/issues/9969))
<add>- **ngMock:** $httpBackend should match data containing Date objects correctly
<add> ([1426b029](https://github.com/angular/angular.js/commit/1426b02980badfd322eb960d71bfb1a14d657847),
<add> [#5127](https://github.com/angular/angular.js/issues/5127))
<add>- **orderBy:** sort by identity if no predicate is given
<add> ([45b896a1](https://github.com/angular/angular.js/commit/45b896a16abbcbfcdfb9a95c2d10c76a805b57cc),
<add> [#5847](https://github.com/angular/angular.js/issues/5847), [#4579](https://github.com/angular/angular.js/issues/4579), [#9403](https://github.com/angular/angular.js/issues/9403))
<add>- **select:** ensure the label attribute is updated in Internet Explorer
<add> ([16833d0f](https://github.com/angular/angular.js/commit/16833d0fb6585117e9978d1accc3ade83e22e797),
<add> [#9621](https://github.com/angular/angular.js/issues/9621), [#10042](https://github.com/angular/angular.js/issues/10042))
<add>
<add>
<add>## Performance Improvements
<add>
<add>- **orderBy:** copy array with slice instead of for loop
<add> ([409bcb38](https://github.com/angular/angular.js/commit/409bcb3810a1622178268f7ff7f4130887a1a3dc),
<add> [#9942](https://github.com/angular/angular.js/issues/9942))
<add>
<add>
<ide> <a name="1.3.3"></a>
<ide> # 1.3.3 undersea-arithmetic (2014-11-17)
<ide>
| 1
|
PHP
|
PHP
|
fix some route docblocks
|
f8114e342b010a454d3d68685bd279f0cf661144
|
<ide><path>src/Illuminate/Routing/Route.php
<ide> public function getUri()
<ide> * Set the URI that the route responds to.
<ide> *
<ide> * @param string $uri
<del> * @return \Illuminate\Routing\Route
<add> * @return $this
<ide> */
<ide> public function setUri($uri)
<ide> {
<ide> public function name($name)
<ide> * Set the handler for the route.
<ide> *
<ide> * @param \Closure|string $action
<del> * @return \Illuminate\Routing\Route
<add> * @return $this
<ide> */
<ide> public function uses($action)
<ide> {
| 1
|
Javascript
|
Javascript
|
add test for uglifyjsplugin
|
a417b80f2343b169ce129ce18aada4226bf22f49
|
<ide><path>test/UglifyJsPlugin.test.js
<add>"use strict";
<add>const should = require("should");
<add>const sinon = require("sinon");
<add>const UglifyJSPlugin = require("../lib/optimize/UglifyJSPlugin");
<add>const PluginEnvironment = require("./helpers/PluginEnvironment");
<add>const SourceMapSource = require("webpack-sources").SourceMapSource;
<add>const RawSource = require("webpack-sources").RawSource;
<add>
<add>describe("UglifyJSPlugin", function() {
<add> it("has apply function", function() {
<add> (new UglifyJSPlugin()).apply.should.be.a.Function();
<add> });
<add>
<add> describe("when applied with no options", function() {
<add> let eventBindings;
<add> let eventBinding;
<add>
<add> beforeEach(function() {
<add> const pluginEnvironment = new PluginEnvironment();
<add> const compilerEnv = pluginEnvironment.getEnvironmentStub();
<add> compilerEnv.context = "";
<add>
<add> const plugin = new UglifyJSPlugin();
<add> plugin.apply(compilerEnv);
<add> eventBindings = pluginEnvironment.getEventBindings();
<add> });
<add>
<add> it("binds one event handler", function() {
<add> eventBindings.length.should.be.exactly(1);
<add> });
<add>
<add> describe("compilation handler", function() {
<add> beforeEach(function() {
<add> eventBinding = eventBindings[0];
<add> });
<add>
<add> it("binds to compilation event", function() {
<add> eventBinding.name.should.be.exactly("compilation");
<add> });
<add>
<add> describe("when called", function() {
<add> let chunkPluginEnvironment;
<add> let compilationEventBindings;
<add> let compilationEventBinding;
<add> let compilation;
<add> let callback;
<add>
<add> beforeEach(function() {
<add> chunkPluginEnvironment = new PluginEnvironment();
<add> compilation = chunkPluginEnvironment.getEnvironmentStub();
<add> compilation.assets = {
<add> "test.js": {
<add> __UglifyJsPlugin: {}
<add> },
<add> "test1.js": "",
<add> "test2.js": {
<add> source: function() {
<add> return "invalid javascript";
<add> }
<add> },
<add> "test3.js": {
<add> source: function() {
<add> return "/** @preserve Foo Bar */ function foo(longVariableName) { longVariableName = 1; }";
<add> }
<add> }
<add> };
<add> compilation.errors = [];
<add>
<add> eventBinding.handler(compilation);
<add> compilationEventBindings = chunkPluginEnvironment.getEventBindings();
<add> });
<add>
<add> it("binds one event handler", function() {
<add> compilationEventBindings.length.should.be.exactly(1);
<add> });
<add>
<add> describe("optimize-chunk-assets handler", function() {
<add> beforeEach(function() {
<add> compilationEventBinding = compilationEventBindings[0];
<add> });
<add>
<add> it("binds to optimize-chunk-assets event", function() {
<add> compilationEventBinding.name.should.be.exactly("optimize-chunk-assets");
<add> });
<add>
<add> it("only calls callback once", function() {
<add> callback = sinon.spy();
<add> compilationEventBinding.handler([""], callback);
<add> callback.callCount.should.be.exactly(1);
<add> });
<add>
<add> it("default only parses filenames ending with .js", function() {
<add> compilationEventBinding.handler([{
<add> files: ["test", "test.js"]
<add> }], function() {
<add> Object.keys(compilation.assets).length.should.be.exactly(4);
<add> });
<add> });
<add>
<add> it("early returns if private property is already set", function() {
<add> compilationEventBinding.handler([{
<add> files: ["test.js"]
<add> }], function() {
<add> compilation.assets["test.js"].should.deepEqual({});
<add> });
<add> });
<add>
<add> it("outputs stack trace errors for invalid asset", function() {
<add> compilationEventBinding.handler([{
<add> files: ["test1.js"]
<add> }], function() {
<add> compilation.errors.length.should.be.exactly(1);
<add> compilation.errors[0].should.be.an.Error;
<add> compilation.errors[0].message.should.have.containEql("TypeError");
<add> });
<add> });
<add>
<add> it("outputs parsing errors for invalid javascript", function() {
<add> compilationEventBinding.handler([{
<add> files: ["test2.js"]
<add> }], function() {
<add> compilation.errors.length.should.be.exactly(1);
<add> compilation.errors[0].should.be.an.Error;
<add> compilation.errors[0].message.should.have.containEql("SyntaxError");
<add> compilation.errors[0].message.should.have.containEql("[test2.js:1,8]");
<add> });
<add> });
<add>
<add> it("outputs no errors for valid javascript", function() {
<add> compilationEventBinding.handler([{
<add> files: ["test3.js"]
<add> }], function() {
<add> compilation.errors.length.should.be.exactly(0);
<add> });
<add> });
<add>
<add> it("outputs RawSource for valid javascript", function() {
<add> compilationEventBinding.handler([{
<add> files: ["test3.js"]
<add> }], function() {
<add> compilation.assets["test3.js"].should.be.instanceof(RawSource);
<add> });
<add> });
<add>
<add> it("outputs mangled javascript", function() {
<add> compilationEventBinding.handler([{
<add> files: ["test3.js"]
<add> }], function() {
<add> compilation.assets["test3.js"]._value.should.not.containEql("longVariableName");
<add> });
<add> });
<add>
<add> it("compresses and does not output beautified javascript", function() {
<add> compilationEventBinding.handler([{
<add> files: ["test3.js"]
<add> }], function() {
<add> compilation.assets["test3.js"]._value.should.not.containEql("\n");
<add> });
<add> });
<add>
<add> it("preserves comments", function() {
<add> compilationEventBinding.handler([{
<add> files: ["test3.js"]
<add> }], function() {
<add> compilation.assets["test3.js"]._value.should.containEql("/**");
<add> });
<add> });
<add> });
<add> });
<add> });
<add> });
<add>
<add> describe("when applied with invalid options", function() {
<add> it("outputs uglify errors", function() {
<add> const pluginEnvironment = new PluginEnvironment();
<add> const compilerEnv = pluginEnvironment.getEnvironmentStub();
<add> compilerEnv.context = "";
<add>
<add> const plugin = new UglifyJSPlugin({
<add> output: {
<add> "invalid-option": true
<add> }
<add> });
<add> plugin.apply(compilerEnv);
<add> const eventBinding = pluginEnvironment.getEventBindings()[0];
<add>
<add> const chunkPluginEnvironment = new PluginEnvironment();
<add> const compilation = chunkPluginEnvironment.getEnvironmentStub();
<add> compilation.assets = {
<add> "test.js": {
<add> source: function() {
<add> return "var foo = 1;";
<add> }
<add> }
<add> };
<add> compilation.errors = [];
<add>
<add> eventBinding.handler(compilation);
<add> const compilationEventBinding = chunkPluginEnvironment.getEventBindings()[0];
<add>
<add> compilationEventBinding.handler([{
<add> files: ["test.js"]
<add> }], function() {
<add> compilation.errors.length.should.be.exactly(1);
<add> compilation.errors[0].message.should.have.containEql("supported option");
<add> });
<add> });
<add> });
<add>
<add> describe("when applied with all options", function() {
<add> let eventBindings;
<add> let eventBinding;
<add>
<add> beforeEach(function() {
<add> const pluginEnvironment = new PluginEnvironment();
<add> const compilerEnv = pluginEnvironment.getEnvironmentStub();
<add> compilerEnv.context = "";
<add>
<add> const plugin = new UglifyJSPlugin({
<add> sourceMap: true,
<add> compress: {
<add> warnings: true,
<add> },
<add> mangle: false,
<add> beautify: true,
<add> comments: false
<add> });
<add> plugin.apply(compilerEnv);
<add> eventBindings = pluginEnvironment.getEventBindings();
<add> });
<add>
<add> it("binds one event handler", function() {
<add> eventBindings.length.should.be.exactly(1);
<add> });
<add>
<add> describe("compilation handler", function() {
<add> beforeEach(function() {
<add> eventBinding = eventBindings[0];
<add> });
<add>
<add> it("binds to compilation event", function() {
<add> eventBinding.name.should.be.exactly("compilation");
<add> });
<add>
<add> describe("when called", function() {
<add> let chunkPluginEnvironment;
<add> let compilationEventBindings;
<add> let compilationEventBinding;
<add> let compilation;
<add>
<add> beforeEach(function() {
<add> chunkPluginEnvironment = new PluginEnvironment();
<add> compilation = chunkPluginEnvironment.getEnvironmentStub();
<add> compilation.assets = {
<add> "test.js": {
<add> source: function() {
<add> return "/** @preserve Foo Bar */ function foo(longVariableName) { longVariableName = 1; }";
<add> },
<add> map: function() {
<add> return {
<add> version: 3,
<add> sources: ["test.js"],
<add> names: ["foo", "longVariableName"],
<add> mappings: "AAAA,QAASA,KAAIC,kBACTA,iBAAmB"
<add> };
<add> }
<add> },
<add> "test1.js": {
<add> source: function() {
<add> return "invalid javascript";
<add> },
<add> map: function() {
<add> return {
<add> version: 3,
<add> sources: ["test1.js"],
<add> names: [""],
<add> mappings: "AAAA"
<add> };
<add> }
<add> },
<add> "test2.js": {
<add> source: function() {
<add> return "function foo(x) { if (x) { return bar(); not_called1(); } }";
<add> },
<add> map: function() {
<add> return {
<add> version: 3,
<add> sources: ["test1.js"],
<add> names: ["foo", "x", "bar", "not_called1"],
<add> mappings: "AAAA,QAASA,KAAIC,GACT,GAAIA,EAAG,CACH,MAAOC,MACPC"
<add> };
<add> }
<add> },
<add> "test3.js": {
<add> sourceAndMap: function() {
<add> return {
<add> source: "/** @preserve Foo Bar */ function foo(longVariableName) { longVariableName = 1; }",
<add> map: {
<add> version: 3,
<add> sources: ["test.js"],
<add> names: ["foo", "longVariableName"],
<add> mappings: "AAAA,QAASA,KAAIC,kBACTA,iBAAmB"
<add> }
<add> };
<add> },
<add> },
<add> };
<add> compilation.errors = [];
<add> compilation.warnings = [];
<add>
<add> eventBinding.handler(compilation);
<add> compilationEventBindings = chunkPluginEnvironment.getEventBindings();
<add> });
<add>
<add> it("binds two event handler", function() {
<add> compilationEventBindings.length.should.be.exactly(2);
<add> });
<add>
<add> describe("build-module handler", function() {
<add> beforeEach(function() {
<add> compilationEventBinding = compilationEventBindings[0];
<add> });
<add>
<add> it("binds to build-module event", function() {
<add> compilationEventBinding.name.should.be.exactly("build-module");
<add> });
<add>
<add> it("sets the useSourceMap flag", function() {
<add> const obj = {};
<add> compilationEventBinding.handler(obj);
<add> obj.useSourceMap.should.be.equal(true);
<add> });
<add> });
<add>
<add> describe("optimize-chunk-assets handler", function() {
<add> beforeEach(function() {
<add> compilationEventBinding = compilationEventBindings[1];
<add> });
<add>
<add> it("binds to optimize-chunk-assets event", function() {
<add> compilationEventBinding.name.should.be.exactly("optimize-chunk-assets");
<add> });
<add>
<add> it("outputs no errors for valid javascript", function() {
<add> compilationEventBinding.handler([{
<add> files: ["test.js"]
<add> }], function() {
<add> compilation.errors.length.should.be.exactly(0);
<add> });
<add> });
<add>
<add> it("outputs SourceMapSource for valid javascript", function() {
<add> compilationEventBinding.handler([{
<add> files: ["test.js"]
<add> }], function() {
<add> compilation.assets["test.js"].should.be.instanceof(SourceMapSource);
<add> });
<add> });
<add>
<add> it("does not output mangled javascript", function() {
<add> compilationEventBinding.handler([{
<add> files: ["test.js"]
<add> }], function() {
<add> compilation.assets["test.js"]._value.should.containEql("longVariableName");
<add> });
<add> });
<add>
<add> it("outputs beautified javascript", function() {
<add> compilationEventBinding.handler([{
<add> files: ["test.js"]
<add> }], function() {
<add> compilation.assets["test.js"]._value.should.containEql("\n");
<add> });
<add> });
<add>
<add> it("does not preserve comments", function() {
<add> compilationEventBinding.handler([{
<add> files: ["test.js"]
<add> }], function() {
<add> compilation.assets["test.js"]._value.should.not.containEql("/**");
<add> });
<add> });
<add>
<add> it("outputs parsing errors", function() {
<add> compilationEventBinding.handler([{
<add> files: ["test1.js"]
<add> }], function() {
<add> compilation.errors.length.should.be.exactly(1);
<add> compilation.errors[0].should.be.an.Error;
<add> compilation.errors[0].message.should.containEql("[test1.js:1,0][test1.js:1,8]");
<add> });
<add> });
<add>
<add> it("outputs warnings for unreachable code", function() {
<add> compilationEventBinding.handler([{
<add> files: ["test2.js"]
<add> }], function() {
<add> compilation.warnings.length.should.be.exactly(1);
<add> compilation.warnings[0].should.be.an.Error;
<add> compilation.warnings[0].message.should.containEql("Dropping unreachable code");
<add> });
<add> });
<add>
<add> it("works with sourceAndMap assets as well", function() {
<add> compilationEventBinding.handler([{
<add> files: ["test3.js"]
<add> }], function() {
<add> compilation.errors.length.should.be.exactly(0);
<add> compilation.assets["test3.js"].should.be.instanceof(SourceMapSource);
<add> });
<add> });
<add> });
<add> });
<add> });
<add> });
<add>});
| 1
|
Java
|
Java
|
add runtimehints predicates generator
|
9c9b2356cec4a74c685320c5b8b1b6eb283f9dc0
|
<ide><path>spring-beans/src/test/java/org/springframework/beans/factory/aot/BeanDefinitionPropertiesCodeGeneratorTests.java
<ide> import org.junit.jupiter.api.Test;
<ide>
<ide> import org.springframework.aot.generate.GeneratedMethods;
<del>import org.springframework.aot.hint.ExecutableMode;
<ide> import org.springframework.aot.hint.RuntimeHints;
<add>import org.springframework.aot.hint.RuntimeHintsPredicates;
<ide> import org.springframework.aot.test.generator.compile.Compiled;
<ide> import org.springframework.aot.test.generator.compile.TestCompiler;
<ide> import org.springframework.beans.factory.config.BeanDefinition;
<ide> void setDestroyMethodWhenMultipleDestroyMethods() {
<ide> }
<ide>
<ide> private void assertHasMethodInvokeHints(Class<?> beanType, String... methodNames) {
<del> assertThat(this.hints.reflection().getTypeHint(beanType)).satisfies(typeHint -> {
<del> for (String methodName : methodNames) {
<del> assertThat(typeHint.methods()).anySatisfy(methodHint -> {
<del> assertThat(methodHint.getName()).isEqualTo(methodName);
<del> assertThat(methodHint.getModes())
<del> .containsExactly(ExecutableMode.INVOKE);
<del> });
<del> }
<del> });
<add> assertThat(methodNames).allMatch(methodName ->
<add> RuntimeHintsPredicates.reflection().onMethod(beanType, methodName).invoke().test(this.hints));
<ide> }
<ide>
<ide> @Test
<ide><path>spring-context/src/test/java/org/springframework/context/aot/ReflectiveProcessorBeanRegistrationAotProcessorTests.java
<ide> import org.springframework.aot.generate.InMemoryGeneratedFiles;
<ide> import org.springframework.aot.hint.MemberCategory;
<ide> import org.springframework.aot.hint.RuntimeHints;
<add>import org.springframework.aot.hint.RuntimeHintsPredicates;
<ide> import org.springframework.aot.hint.TypeReference;
<ide> import org.springframework.aot.hint.annotation.Reflective;
<ide> import org.springframework.beans.factory.aot.BeanRegistrationAotContribution;
<ide> void shouldProcessAnnotationOnMethod() {
<ide> void shouldRegisterAnnotation() {
<ide> process(SampleMethodMetaAnnotatedBean.class);
<ide> RuntimeHints runtimeHints = this.generationContext.getRuntimeHints();
<del> assertThat(runtimeHints.reflection().getTypeHint(SampleInvoker.class)).satisfies(typeHint ->
<del> assertThat(typeHint.getMemberCategories()).containsOnly(MemberCategory.INVOKE_DECLARED_METHODS));
<add> assertThat(RuntimeHintsPredicates.reflection().onType(SampleInvoker.class).withMemberCategory(MemberCategory.INVOKE_DECLARED_METHODS)).accepts(runtimeHints);
<ide> assertThat(runtimeHints.proxies().jdkProxies()).isEmpty();
<ide> }
<ide>
<ide> @Test
<ide> void shouldRegisterAnnotationAndProxyWithAliasFor() {
<ide> process(SampleMethodMetaAnnotatedBeanWithAlias.class);
<ide> RuntimeHints runtimeHints = this.generationContext.getRuntimeHints();
<del> assertThat(runtimeHints.reflection().getTypeHint(RetryInvoker.class)).satisfies(typeHint ->
<del> assertThat(typeHint.getMemberCategories()).containsOnly(MemberCategory.INVOKE_DECLARED_METHODS));
<del> assertThat(runtimeHints.proxies().jdkProxies()).anySatisfy(jdkProxyHint ->
<del> assertThat(jdkProxyHint.getProxiedInterfaces()).containsExactly(
<del> TypeReference.of(RetryInvoker.class), TypeReference.of(SynthesizedAnnotation.class)));
<add> assertThat(RuntimeHintsPredicates.reflection().onType(RetryInvoker.class).withMemberCategory(MemberCategory.INVOKE_DECLARED_METHODS)).accepts(runtimeHints);
<add> assertThat(RuntimeHintsPredicates.proxies().forInterfaces(RetryInvoker.class, SynthesizedAnnotation.class)).accepts(runtimeHints);
<ide> }
<ide>
<ide> @Nullable
<ide> void notManaged() {
<ide>
<ide> }
<ide>
<del> @Target({ ElementType.METHOD, ElementType.ANNOTATION_TYPE })
<add> @Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
<ide> @Retention(RetentionPolicy.RUNTIME)
<ide> @Documented
<ide> @Reflective
<ide> void notManaged() {
<ide>
<ide> }
<ide>
<del> @Target({ ElementType.METHOD })
<add> @Target({ElementType.METHOD})
<ide> @Retention(RetentionPolicy.RUNTIME)
<ide> @Documented
<ide> @SampleInvoker
<ide><path>spring-core/src/main/java/org/springframework/aot/hint/ProxyHintsPredicates.java
<add>/*
<add> * Copyright 2002-2022 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.aot.hint;
<add>
<add>import java.util.Arrays;
<add>import java.util.function.Predicate;
<add>
<add>import org.springframework.util.Assert;
<add>
<add>/**
<add> * Generator of {@link ProxyHints} predicates, testing whether the given hints
<add> * match the expected behavior for proxies.
<add> * @author Brian Clozel
<add> * @since 6.0
<add> */
<add>public class ProxyHintsPredicates {
<add>
<add> ProxyHintsPredicates() {
<add> }
<add>
<add> /**
<add> * Return a predicate that checks whether a {@link org.springframework.aot.hint.JdkProxyHint}
<add> * is registered for the given interfaces.
<add> * <p>Note that the order in which interfaces are given matters.
<add> * @param interfaces the proxied interfaces
<add> * @return the {@link RuntimeHints} predicate
<add> * @see java.lang.reflect.Proxy
<add> */
<add> public Predicate<RuntimeHints> forInterfaces(Class<?>... interfaces) {
<add> Assert.notEmpty(interfaces, "'interfaces' should not be empty");
<add> return forInterfaces(Arrays.stream(interfaces).map(TypeReference::of).toArray(TypeReference[]::new));
<add> }
<add>
<add> /**
<add> * Return a predicate that checks whether a {@link org.springframework.aot.hint.JdkProxyHint}
<add> * is registered for the given interfaces.
<add> * <p>Note that the order in which interfaces are given matters.
<add> * @param interfaces the proxied interfaces as type references
<add> * @return the {@link RuntimeHints} predicate
<add> * @see java.lang.reflect.Proxy
<add> */
<add> public Predicate<RuntimeHints> forInterfaces(TypeReference... interfaces) {
<add> Assert.notEmpty(interfaces, "'interfaces' should not be empty");
<add> return hints -> hints.proxies().jdkProxies().anyMatch(proxyHint ->
<add> proxyHint.getProxiedInterfaces().equals(Arrays.asList(interfaces)));
<add> }
<add>}
<ide><path>spring-core/src/main/java/org/springframework/aot/hint/ReflectionHintsPredicates.java
<add>/*
<add> * Copyright 2002-2022 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.aot.hint;
<add>
<add>import java.lang.reflect.Constructor;
<add>import java.lang.reflect.Executable;
<add>import java.lang.reflect.Field;
<add>import java.lang.reflect.Method;
<add>import java.lang.reflect.Modifier;
<add>import java.util.Arrays;
<add>import java.util.List;
<add>import java.util.Set;
<add>import java.util.function.Predicate;
<add>
<add>import org.springframework.core.MethodIntrospector;
<add>import org.springframework.lang.Nullable;
<add>import org.springframework.util.Assert;
<add>import org.springframework.util.ReflectionUtils;
<add>
<add>/**
<add> * Generator of {@link ReflectionHints} predicates, testing whether the given hints
<add> * match the expected behavior for reflection.
<add> * @author Brian Clozel
<add> * @since 6.0
<add> */
<add>public class ReflectionHintsPredicates {
<add>
<add> ReflectionHintsPredicates() {
<add>
<add> }
<add>
<add> /**
<add> * Return a predicate that checks whether a reflection hint is registered for the given type.
<add> * <p>The returned type exposes additional methods that refine the predicate behavior.
<add> * @param typeReference the type
<add> * @return the {@link RuntimeHints} predicate
<add> */
<add> public TypeHintPredicate onType(TypeReference typeReference) {
<add> Assert.notNull(typeReference, "'typeReference' should not be null");
<add> return new TypeHintPredicate(typeReference);
<add> }
<add>
<add> /**
<add> * Return a predicate that checks whether a reflection hint is registered for the given type.
<add> * <p>The returned type exposes additional methods that refine the predicate behavior.
<add> * @param type the type
<add> * @return the {@link RuntimeHints} predicate
<add> */
<add> public TypeHintPredicate onType(Class<?> type) {
<add> Assert.notNull(type, "'type' should not be null");
<add> return new TypeHintPredicate(TypeReference.of(type));
<add> }
<add>
<add> /**
<add> * Return a predicate that checks whether a reflection hint is registered for the given constructor.
<add> * By default, both introspection and invocation hints match.
<add> * <p>The returned type exposes additional methods that refine the predicate behavior.
<add> * @param constructor the constructor
<add> * @return the {@link RuntimeHints} predicate
<add> */
<add> public ConstructorHintPredicate onConstructor(Constructor<?> constructor) {
<add> Assert.notNull(constructor, "'constructor' should not be null");
<add> return new ConstructorHintPredicate(constructor);
<add> }
<add>
<add> /**
<add> * Return a predicate that checks whether a reflection hint is registered for the given method.
<add> * By default, both introspection and invocation hints match.
<add> * <p>The returned type exposes additional methods that refine the predicate behavior.
<add> * @param method the method
<add> * @return the {@link RuntimeHints} predicate
<add> */
<add> public MethodHintPredicate onMethod(Method method) {
<add> Assert.notNull(method, "'method' should not be null");
<add> return new MethodHintPredicate(method);
<add> }
<add>
<add> /**
<add> * Return a predicate that checks whether a reflection hint is registered for the method that matches the given selector.
<add> * This looks up a method on the given type with the expected name, if unique.
<add> * By default, both introspection and invocation hints match.
<add> * <p>The returned type exposes additional methods that refine the predicate behavior.
<add> * @param type the type holding the method
<add> * @param methodName the method name
<add> * @return the {@link RuntimeHints} predicate
<add> * @throws IllegalArgumentException if the method cannot be found or if multiple methods are found with the same name.
<add> */
<add> public MethodHintPredicate onMethod(Class<?> type, String methodName) {
<add> Assert.notNull(type, "'type' should not be null");
<add> Assert.hasText(methodName, "'methodName' should not be null");
<add> return new MethodHintPredicate(getMethod(type, methodName));
<add> }
<add>
<add> private Method getMethod(Class<?> type, String methodName) {
<add> ReflectionUtils.MethodFilter selector = method -> methodName.equals(method.getName());
<add> Set<Method> methods = MethodIntrospector.selectMethods(type, selector);
<add> if (methods.size() == 1) {
<add> return methods.iterator().next();
<add> }
<add> else if (methods.size() > 1) {
<add> throw new IllegalArgumentException(String.format("Found multiple methods named '%s' on class %s", methodName, type.getName()));
<add> }
<add> else {
<add> throw new IllegalArgumentException("No method named '" + methodName + "' on class " + type.getName());
<add> }
<add> }
<add>
<add> /**
<add> * Return a predicate that checks whether a reflection hint is registered for the field that matches the given selector.
<add> * This looks up a field on the given type with the expected name, if present.
<add> * By default, unsafe or write access are not considered.
<add> * <p>The returned type exposes additional methods that refine the predicate behavior.
<add> * @param type the type holding the field
<add> * @param fieldName the field name
<add> * @return the {@link RuntimeHints} predicate
<add> * @throws IllegalArgumentException if a field cannot be found with the given name.
<add> */
<add> public FieldHintPredicate onField(Class<?> type, String fieldName) {
<add> Assert.notNull(type, "'type' should not be null");
<add> Assert.hasText(fieldName, "'fieldName' should not be empty");
<add> Field field = ReflectionUtils.findField(type, fieldName);
<add> if (field == null) {
<add> throw new IllegalArgumentException("No field named '" + fieldName + "' on class " + type.getName());
<add> }
<add> return new FieldHintPredicate(field);
<add> }
<add>
<add> /**
<add> * Return a predicate that checks whether a reflection hint is registered for the given field.
<add> * By default, unsafe or write access are not considered.
<add> * <p>The returned type exposes additional methods that refine the predicate behavior.
<add> * @param field the field
<add> * @return the {@link RuntimeHints} predicate
<add> */
<add> public FieldHintPredicate onField(Field field) {
<add> Assert.notNull(field, "'field' should not be null");
<add> return new FieldHintPredicate(field);
<add> }
<add>
<add> public static class TypeHintPredicate implements Predicate<RuntimeHints> {
<add>
<add> private final TypeReference type;
<add>
<add> TypeHintPredicate(TypeReference type) {
<add> this.type = type;
<add> }
<add>
<add> @Nullable
<add> private TypeHint getTypeHint(RuntimeHints hints) {
<add> return hints.reflection().getTypeHint(this.type);
<add> }
<add>
<add> @Override
<add> public boolean test(RuntimeHints hints) {
<add> return getTypeHint(hints) != null;
<add> }
<add>
<add>
<add> /**
<add> * Refine the current predicate to only match if the given {@link MemberCategory} is present.
<add> * @param memberCategory the member category
<add> * @return the refined {@link RuntimeHints} predicate
<add> */
<add> public Predicate<RuntimeHints> withMemberCategory(MemberCategory memberCategory) {
<add> Assert.notNull(memberCategory, "'memberCategory' should not be null");
<add> return this.and(hints -> getTypeHint(hints).getMemberCategories().contains(memberCategory));
<add> }
<add>
<add> /**
<add> * Refine the current predicate to match if any of the given {@link MemberCategory categories} is present.
<add> * @param memberCategories the member categories
<add> * @return the refined {@link RuntimeHints} predicate
<add> */
<add> public Predicate<RuntimeHints> withAnyMemberCategory(MemberCategory... memberCategories) {
<add> Assert.notEmpty(memberCategories, "'memberCategories' should not be empty");
<add> return this.and(hints -> Arrays.stream(memberCategories)
<add> .anyMatch(memberCategory -> getTypeHint(hints).getMemberCategories().contains(memberCategory)));
<add> }
<add>
<add> }
<add>
<add> public abstract static class ExecutableHintPredicate<T extends Executable> implements Predicate<RuntimeHints> {
<add>
<add> protected final T executable;
<add>
<add> protected ExecutableMode executableMode = ExecutableMode.INTROSPECT;
<add>
<add> ExecutableHintPredicate(T executable) {
<add> this.executable = executable;
<add> }
<add>
<add> /**
<add> * Refine the current predicate to match for reflection introspection on the current type.
<add> * @return the refined {@link RuntimeHints} predicate
<add> */
<add> public ExecutableHintPredicate<T> introspect() {
<add> this.executableMode = ExecutableMode.INTROSPECT;
<add> return this;
<add> }
<add>
<add> /**
<add> * Refine the current predicate to match for reflection invocation on the current type.
<add> * @return the refined {@link RuntimeHints} predicate
<add> */
<add> public ExecutableHintPredicate<T> invoke() {
<add> this.executableMode = ExecutableMode.INVOKE;
<add> return this;
<add> }
<add>
<add> @Override
<add> public boolean test(RuntimeHints runtimeHints) {
<add> return (new TypeHintPredicate(TypeReference.of(this.executable.getDeclaringClass()))
<add> .withAnyMemberCategory(getPublicMemberCategories())
<add> .and(hints -> Modifier.isPublic(this.executable.getModifiers())))
<add> .or(new TypeHintPredicate(TypeReference.of(this.executable.getDeclaringClass())).withAnyMemberCategory(getDeclaredMemberCategories()))
<add> .or(exactMatch()).test(runtimeHints);
<add> }
<add>
<add> abstract MemberCategory[] getPublicMemberCategories();
<add>
<add> abstract MemberCategory[] getDeclaredMemberCategories();
<add>
<add> abstract Predicate<RuntimeHints> exactMatch();
<add>
<add> /**
<add> * Indicate whether the first {@code ExecutableHint} covers the reflection needs for the other one.
<add> * For that, both hints must apply to the same member (same type, name and parameters)
<add> * and the configured {@code ExecutableMode} of the first must cover the second.
<add> */
<add> static boolean includes(ExecutableHint hint, ExecutableHint other) {
<add> return hint.getName().equals(other.getName())
<add> && hint.getParameterTypes().equals(other.getParameterTypes())
<add> && (hint.getModes().contains(ExecutableMode.INVOKE)
<add> || !other.getModes().contains(ExecutableMode.INVOKE));
<add> }
<add> }
<add>
<add> public static class ConstructorHintPredicate extends ExecutableHintPredicate<Constructor<?>> {
<add>
<add> ConstructorHintPredicate(Constructor<?> constructor) {
<add> super(constructor);
<add> }
<add>
<add> MemberCategory[] getPublicMemberCategories() {
<add> if (this.executableMode == ExecutableMode.INTROSPECT) {
<add> return new MemberCategory[] {MemberCategory.INTROSPECT_PUBLIC_CONSTRUCTORS,
<add> MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS};
<add> }
<add> return new MemberCategory[] {MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS};
<add> }
<add>
<add> MemberCategory[] getDeclaredMemberCategories() {
<add> if (this.executableMode == ExecutableMode.INTROSPECT) {
<add> return new MemberCategory[] {MemberCategory.INTROSPECT_DECLARED_CONSTRUCTORS,
<add> MemberCategory.INVOKE_DECLARED_CONSTRUCTORS};
<add> }
<add> return new MemberCategory[] {MemberCategory.INVOKE_DECLARED_CONSTRUCTORS};
<add> }
<add>
<add> @Override
<add> Predicate<RuntimeHints> exactMatch() {
<add> return hints -> hints.reflection().getTypeHint(this.executable.getDeclaringClass()).constructors().anyMatch(executableHint -> {
<add> List<TypeReference> parameters = Arrays.stream(this.executable.getParameterTypes()).map(TypeReference::of).toList();
<add> ExecutableHint syntheticHint = ExecutableHint.ofConstructor(parameters)
<add> .setModes(this.executableMode).build();
<add> return includes(executableHint, syntheticHint);
<add> });
<add> }
<add> }
<add>
<add> public static class MethodHintPredicate extends ExecutableHintPredicate<Method> {
<add>
<add>
<add> MethodHintPredicate(Method method) {
<add> super(method);
<add> }
<add>
<add> MemberCategory[] getPublicMemberCategories() {
<add> if (this.executableMode == ExecutableMode.INTROSPECT) {
<add> return new MemberCategory[] {MemberCategory.INTROSPECT_PUBLIC_METHODS,
<add> MemberCategory.INVOKE_PUBLIC_METHODS};
<add> }
<add> return new MemberCategory[] {MemberCategory.INVOKE_PUBLIC_METHODS};
<add> }
<add>
<add> MemberCategory[] getDeclaredMemberCategories() {
<add>
<add> if (this.executableMode == ExecutableMode.INTROSPECT) {
<add> return new MemberCategory[] {MemberCategory.INTROSPECT_DECLARED_METHODS,
<add> MemberCategory.INVOKE_DECLARED_METHODS};
<add> }
<add> return new MemberCategory[] {MemberCategory.INVOKE_DECLARED_METHODS};
<add> }
<add>
<add> @Override
<add> Predicate<RuntimeHints> exactMatch() {
<add> return hints -> (hints.reflection().getTypeHint(this.executable.getDeclaringClass()) != null) &&
<add> hints.reflection().getTypeHint(this.executable.getDeclaringClass()).methods().anyMatch(executableHint -> {
<add> List<TypeReference> parameters = Arrays.stream(this.executable.getParameterTypes()).map(TypeReference::of).toList();
<add> ExecutableHint syntheticHint = ExecutableHint.ofMethod(this.executable.getName(), parameters)
<add> .setModes(this.executableMode).build();
<add> return includes(executableHint, syntheticHint);
<add> });
<add> }
<add> }
<add>
<add> public static class FieldHintPredicate implements Predicate<RuntimeHints> {
<add>
<add> private final Field field;
<add>
<add> private boolean allowWrite;
<add>
<add> private boolean allowUnsafeAccess;
<add>
<add> FieldHintPredicate(Field field) {
<add> this.field = field;
<add> }
<add>
<add> /**
<add> * Refine the current predicate to match if write access is allowed on the field.
<add> * @return the refined {@link RuntimeHints} predicate
<add> * @see FieldHint#isAllowWrite()
<add> */
<add> public FieldHintPredicate allowWrite() {
<add> this.allowWrite = true;
<add> return this;
<add> }
<add>
<add> /**
<add> * Refine the current predicate to match if unsafe access is allowed on the field.
<add> * @return the refined {@link RuntimeHints} predicate
<add> * @see FieldHint#isAllowUnsafeAccess() ()
<add> */
<add> public FieldHintPredicate allowUnsafeAccess() {
<add> this.allowUnsafeAccess = true;
<add> return this;
<add> }
<add>
<add> @Override
<add> public boolean test(RuntimeHints runtimeHints) {
<add> TypeHint typeHint = runtimeHints.reflection().getTypeHint(this.field.getDeclaringClass());
<add> if (typeHint == null) {
<add> return false;
<add> }
<add> return memberCategoryMatch(typeHint) || exactMatch(typeHint);
<add> }
<add>
<add> private boolean memberCategoryMatch(TypeHint typeHint) {
<add> if (Modifier.isPublic(this.field.getModifiers())) {
<add> return typeHint.getMemberCategories().contains(MemberCategory.PUBLIC_FIELDS)
<add> || typeHint.getMemberCategories().contains(MemberCategory.DECLARED_FIELDS);
<add> }
<add> else {
<add> return typeHint.getMemberCategories().contains(MemberCategory.DECLARED_FIELDS);
<add> }
<add> }
<add>
<add> private boolean exactMatch(TypeHint typeHint) {
<add> return typeHint.fields().anyMatch(fieldHint ->
<add> this.field.getName().equals(fieldHint.getName())
<add> && (!this.allowWrite || this.allowWrite == fieldHint.isAllowWrite())
<add> && (!this.allowUnsafeAccess || this.allowUnsafeAccess == fieldHint.isAllowUnsafeAccess()));
<add> }
<add> }
<add>
<add>}
<ide><path>spring-core/src/main/java/org/springframework/aot/hint/ResourceHintsPredicates.java
<add>/*
<add> * Copyright 2002-2022 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.aot.hint;
<add>
<add>import java.util.function.Predicate;
<add>import java.util.regex.Pattern;
<add>
<add>import org.springframework.util.Assert;
<add>import org.springframework.util.ConcurrentLruCache;
<add>
<add>/**
<add> * Generator of {@link ResourceHints} predicates, testing whether the given hints
<add> * match the expected behavior for resources.
<add> * @author Brian Clozel
<add> * @since 6.0
<add> */
<add>public class ResourceHintsPredicates {
<add>
<add> private static final ConcurrentLruCache<String, Pattern> CACHED_RESOURCE_PATTERNS = new ConcurrentLruCache<>(32, Pattern::compile);
<add>
<add> ResourceHintsPredicates() {
<add> }
<add>
<add> /**
<add> * Return a predicate that checks whether a resource hint is registered for the given bundle name.
<add> * @param bundleName the resource bundle name
<add> * @return the {@link RuntimeHints} predicate
<add> */
<add> public Predicate<RuntimeHints> forBundle(String bundleName) {
<add> Assert.hasText(bundleName, "resource bundle name should not be empty");
<add> return runtimeHints -> runtimeHints.resources().resourceBundles()
<add> .anyMatch(bundleHint -> bundleName.equals(bundleHint.getBaseName()));
<add> }
<add>
<add> /**
<add> * Return a predicate that checks whether a resource hint is registered for the given
<add> * resource name, located in the given type's package.
<add> * <p>For example, {@code forResource(org.example.MyClass, "myResource.txt")}
<add> * will match for {@code "/org/example/myResource.txt"}.
<add> * @param type the type's package where to look for the resource
<add> * @param resourceName the resource name
<add> * @return the {@link RuntimeHints} predicate
<add> */
<add> public Predicate<RuntimeHints> forResource(TypeReference type, String resourceName) {
<add> String absoluteName = resolveAbsoluteResourceName(type, resourceName);
<add> return forResource(absoluteName);
<add> }
<add>
<add> private String resolveAbsoluteResourceName(TypeReference type, String resourceName) {
<add> if (resourceName.startsWith("/")) {
<add> return resourceName;
<add> }
<add> else {
<add> return "/" + type.getPackageName().replace('.', '/')
<add> + "/" + resourceName;
<add> }
<add> }
<add>
<add> /**
<add> * Return a predicate that checks whether a resource hint is registered for
<add> * the given resource name.
<add> * @param resourceName the full resource name
<add> * @return the {@link RuntimeHints} predicate
<add> */
<add> public Predicate<RuntimeHints> forResource(String resourceName) {
<add> return hints -> hints.resources().resourcePatterns().reduce(ResourcePatternHints::merge)
<add> .map(hint -> {
<add> boolean isExcluded = hint.getExcludes().stream()
<add> .anyMatch(excluded -> CACHED_RESOURCE_PATTERNS.get(excluded.getPattern()).matcher(resourceName).matches());
<add> if (isExcluded) {
<add> return false;
<add> }
<add> return hint.getIncludes().stream()
<add> .anyMatch(included -> CACHED_RESOURCE_PATTERNS.get(included.getPattern()).matcher(resourceName).matches());
<add> }).orElse(false);
<add> }
<add>
<add>}
<ide><path>spring-core/src/main/java/org/springframework/aot/hint/ResourcePatternHints.java
<ide> import java.util.List;
<ide> import java.util.Set;
<ide>
<add>import org.springframework.lang.Nullable;
<add>
<ide> /**
<ide> * A collection of {@link ResourcePatternHint} describing whether
<ide> * resources should be made available at runtime through a matching
<ide> private ResourcePatternHints(Builder builder) {
<ide> this.excludes = new ArrayList<>(builder.excludes);
<ide> }
<ide>
<add> private ResourcePatternHints(List<ResourcePatternHint> includes, List<ResourcePatternHint> excludes) {
<add> this.includes = includes;
<add> this.excludes = excludes;
<add> }
<add>
<ide> /**
<ide> * Return the include patterns to use to identify the resources to match.
<ide> * @return the include patterns
<ide> public List<ResourcePatternHint> getExcludes() {
<ide> return this.excludes;
<ide> }
<ide>
<add> ResourcePatternHints merge(ResourcePatternHints resourcePatternHints) {
<add> List<ResourcePatternHint> includes = new ArrayList<>();
<add> includes.addAll(this.includes);
<add> includes.addAll(resourcePatternHints.includes);
<add> List<ResourcePatternHint> excludes = new ArrayList<>();
<add> excludes.addAll(this.excludes);
<add> excludes.addAll(resourcePatternHints.excludes);
<add> return new ResourcePatternHints(includes, excludes);
<add> }
<add>
<ide>
<ide> /**
<ide> * Builder for {@link ResourcePatternHints}.
<ide> public static class Builder {
<ide> * @param includes the include patterns (see {@link ResourcePatternHint} documentation)
<ide> * @return {@code this}, to facilitate method chaining
<ide> */
<del> public Builder includes(TypeReference reachableType, String... includes) {
<add> public Builder includes(@Nullable TypeReference reachableType, String... includes) {
<ide> List<ResourcePatternHint> newIncludes = Arrays.stream(includes)
<ide> .map(include -> new ResourcePatternHint(include, reachableType)).toList();
<ide> this.includes.addAll(newIncludes);
<ide><path>spring-core/src/main/java/org/springframework/aot/hint/RuntimeHintsPredicates.java
<add>/*
<add> * Copyright 2002-2022 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.aot.hint;
<add>
<add>/**
<add> * Static generator of predicates that test whether the given {@link RuntimeHints}
<add> * instance matches the expected behavior for reflection, resource or proxy generation.
<add> * <p>This utility class can be used by {@link RuntimeHintsRegistrar} to conditionally
<add> * register hints depending on what's present already. This can also be used as a
<add> * testing utility for checking proper registration of hints:
<add> * <pre class="code">
<add> * Predicate<RuntimeHints> predicate = RuntimeHintsPredicates.reflection().onMethod(MyClass.class, "someMethod").invoke();
<add> * assertThat(predicate).accepts(runtimeHints);
<add> * </pre>
<add> * @author Brian Clozel
<add> * @since 6.0
<add> */
<add>public abstract class RuntimeHintsPredicates {
<add>
<add> private static final ReflectionHintsPredicates reflection = new ReflectionHintsPredicates();
<add>
<add> private static final ResourceHintsPredicates resource = new ResourceHintsPredicates();
<add>
<add> private static final ProxyHintsPredicates proxies = new ProxyHintsPredicates();
<add>
<add>
<add> private RuntimeHintsPredicates() {
<add>
<add> }
<add>
<add> /**
<add> * Return a predicate generator for {@link ReflectionHints reflection hints}.
<add> * @return the predicate generator
<add> */
<add> public static ReflectionHintsPredicates reflection() {
<add> return reflection;
<add> }
<add>
<add> /**
<add> * Return a predicate generator for {@link ResourceHints resource hints}.
<add> * @return the predicate generator
<add> */
<add> public static ResourceHintsPredicates resource() {
<add> return resource;
<add> }
<add>
<add> /**
<add> * Return a predicate generator for {@link ProxyHints proxy hints}.
<add> * @return the predicate generator
<add> */
<add> public static ProxyHintsPredicates proxies() {
<add> return proxies;
<add> }
<add>
<add>}
<ide><path>spring-core/src/test/java/org/springframework/aot/hint/ProxyHintsPredicatesTests.java
<add>/*
<add> * Copyright 2002-2022 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.aot.hint;
<add>
<add>import java.util.function.Predicate;
<add>
<add>import org.junit.jupiter.api.BeforeEach;
<add>import org.junit.jupiter.api.Test;
<add>
<add>import static org.assertj.core.api.Assertions.assertThat;
<add>import static org.assertj.core.api.Assertions.assertThatThrownBy;
<add>
<add>/**
<add> * Tests for {@link ProxyHintsPredicates}.
<add> *
<add> * @author Brian Clozel
<add> */
<add>class ProxyHintsPredicatesTests {
<add>
<add> private final ProxyHintsPredicates proxy = new ProxyHintsPredicates();
<add>
<add> private RuntimeHints runtimeHints;
<add>
<add> @BeforeEach
<add> void setup() {
<add> this.runtimeHints = new RuntimeHints();
<add> }
<add>
<add> @Test
<add> void shouldFailForEmptyInterfacesArray() {
<add> assertThatThrownBy(() -> this.proxy.forInterfaces(new Class<?>[] {})).isInstanceOf(IllegalArgumentException.class);
<add> }
<add>
<add> @Test
<add> void proxyForInterfacesMatchesProxyHint() {
<add> this.runtimeHints.proxies().registerJdkProxy(FirstTestInterface.class, SecondTestInterface.class);
<add> assertPredicateMatches(this.proxy.forInterfaces(FirstTestInterface.class, SecondTestInterface.class));
<add> }
<add>
<add> @Test
<add> void proxyForInterfacesDoesNotMatchProxyHintDifferentOrder() {
<add> this.runtimeHints.proxies().registerJdkProxy(SecondTestInterface.class, FirstTestInterface.class);
<add> assertPredicateDoesNotMatch(this.proxy.forInterfaces(FirstTestInterface.class, SecondTestInterface.class));
<add> }
<add>
<add> interface FirstTestInterface {
<add>
<add> }
<add>
<add> interface SecondTestInterface {
<add>
<add> }
<add>
<add> private void assertPredicateMatches(Predicate<RuntimeHints> predicate) {
<add> assertThat(predicate.test(this.runtimeHints)).isTrue();
<add> }
<add>
<add> private void assertPredicateDoesNotMatch(Predicate<RuntimeHints> predicate) {
<add> assertThat(predicate.test(this.runtimeHints)).isFalse();
<add> }
<add>
<add>}
<ide><path>spring-core/src/test/java/org/springframework/aot/hint/ReflectionHintsPredicatesTests.java
<add>/*
<add> * Copyright 2002-2022 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.aot.hint;
<add>
<add>
<add>import java.lang.reflect.Constructor;
<add>import java.util.Collections;
<add>import java.util.List;
<add>import java.util.function.Predicate;
<add>
<add>import org.junit.jupiter.api.BeforeAll;
<add>import org.junit.jupiter.api.BeforeEach;
<add>import org.junit.jupiter.api.Test;
<add>
<add>import static org.assertj.core.api.Assertions.assertThat;
<add>import static org.assertj.core.api.Assertions.assertThatThrownBy;
<add>
<add>/**
<add> * Tests for {@link ReflectionHintsPredicates}
<add> *
<add> * @author Brian Clozel
<add> */
<add>class ReflectionHintsPredicatesTests {
<add>
<add> private static Constructor<?> privateConstructor;
<add>
<add> private static Constructor<?> publicConstructor;
<add>
<add> private final ReflectionHintsPredicates reflection = new ReflectionHintsPredicates();
<add>
<add> private RuntimeHints runtimeHints;
<add>
<add>
<add> @BeforeAll
<add> static void setupAll() throws Exception {
<add> privateConstructor = SampleClass.class.getDeclaredConstructor(String.class);
<add> publicConstructor = SampleClass.class.getConstructor();
<add> }
<add>
<add> @BeforeEach
<add> void setup() {
<add> this.runtimeHints = new RuntimeHints();
<add> }
<add>
<add> // Reflection on type
<add>
<add> @Test
<add> void shouldFailForNullType() {
<add> assertThatThrownBy(() -> reflection.onType((TypeReference) null)).isInstanceOf(IllegalArgumentException.class);
<add> }
<add>
<add> @Test
<add> void reflectionOnClassShouldMatchIntrospection() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, builder -> {
<add> });
<add> assertPredicateMatches(reflection.onType(SampleClass.class));
<add> }
<add>
<add> @Test
<add> void reflectionOnTypeReferenceShouldMatchIntrospection() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, builder -> {
<add> });
<add> assertPredicateMatches(reflection.onType(TypeReference.of(SampleClass.class)));
<add> }
<add>
<add> @Test
<add> void reflectionOnDifferentClassShouldNotMatchIntrospection() {
<add> this.runtimeHints.reflection().registerType(Integer.class, builder -> {
<add> });
<add> assertPredicateDoesNotMatch(reflection.onType(TypeReference.of(SampleClass.class)));
<add> }
<add>
<add> @Test
<add> void typeWithMemberCategoryFailsWithNullCategory() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, builder -> builder.withMembers(MemberCategory.INTROSPECT_PUBLIC_METHODS));
<add> assertThatThrownBy(() -> reflection.onType(SampleClass.class).withMemberCategory(null)).isInstanceOf(IllegalArgumentException.class);
<add> }
<add>
<add> @Test
<add> void typeWithMemberCategoryMatchesCategory() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, builder -> builder.withMembers(MemberCategory.INTROSPECT_PUBLIC_METHODS));
<add> assertPredicateMatches(reflection.onType(SampleClass.class).withMemberCategory(MemberCategory.INTROSPECT_PUBLIC_METHODS));
<add> }
<add>
<add> @Test
<add> void typeWithMemberCategoryDoesNotMatchOtherCategory() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, builder -> builder.withMembers(MemberCategory.INTROSPECT_PUBLIC_METHODS));
<add> assertPredicateDoesNotMatch(reflection.onType(SampleClass.class).withMemberCategory(MemberCategory.INVOKE_PUBLIC_METHODS));
<add> }
<add>
<add> @Test
<add> void typeWithAnyMemberCategoryFailsWithNullCategories() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, builder -> builder.withMembers(MemberCategory.INTROSPECT_PUBLIC_METHODS));
<add> assertThatThrownBy(() -> reflection.onType(SampleClass.class).withAnyMemberCategory(new MemberCategory[]{})).isInstanceOf(IllegalArgumentException.class);
<add> }
<add>
<add> @Test
<add> void typeWithAnyMemberCategoryMatchesCategory() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, builder -> builder.withMembers(MemberCategory.INTROSPECT_PUBLIC_METHODS, MemberCategory.INVOKE_PUBLIC_METHODS));
<add> assertPredicateMatches(reflection.onType(SampleClass.class).withAnyMemberCategory(MemberCategory.INTROSPECT_PUBLIC_METHODS));
<add> }
<add>
<add> @Test
<add> void typeWithAnyMemberCategoryDoesNotMatchOtherCategory() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, builder -> builder.withMembers(MemberCategory.INTROSPECT_PUBLIC_METHODS, MemberCategory.INVOKE_PUBLIC_METHODS));
<add> assertPredicateDoesNotMatch(reflection.onType(SampleClass.class).withAnyMemberCategory(MemberCategory.INVOKE_DECLARED_METHODS));
<add> }
<add>
<add> // Reflection on constructor
<add>
<add> @Test
<add> void constructorIntrospectionMatchesConstructorHint() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withConstructor(Collections.emptyList(), constructorHint -> {
<add> }));
<add> assertPredicateMatches(reflection.onConstructor(publicConstructor).introspect());
<add> }
<add>
<add> @Test
<add> void constructorIntrospectionMatchesIntrospectPublicConstructors() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withMembers(MemberCategory.INTROSPECT_PUBLIC_CONSTRUCTORS));
<add> assertPredicateMatches(reflection.onConstructor(publicConstructor).introspect());
<add> }
<add>
<add> @Test
<add> void constructorIntrospectionMatchesInvokePublicConstructors() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withMembers(MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS));
<add> assertPredicateMatches(reflection.onConstructor(publicConstructor).introspect());
<add> }
<add>
<add> @Test
<add> void constructorIntrospectionMatchesIntrospectDeclaredConstructors() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withMembers(MemberCategory.INTROSPECT_DECLARED_CONSTRUCTORS));
<add> assertPredicateMatches(reflection.onConstructor(publicConstructor).introspect());
<add> }
<add>
<add> @Test
<add> void constructorIntrospectionMatchesInvokeDeclaredConstructors() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS));
<add> assertPredicateMatches(reflection.onConstructor(publicConstructor).introspect());
<add> }
<add>
<add> @Test
<add> void constructorInvocationDoesNotMatchConstructorHint() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withConstructor(Collections.emptyList(), constructorHint -> {
<add> }));
<add> assertPredicateDoesNotMatch(reflection.onConstructor(publicConstructor).invoke());
<add> }
<add>
<add> @Test
<add> void constructorInvocationMatchesConstructorInvocationHint() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withConstructor(Collections.emptyList(), constructorHint -> constructorHint.withMode(ExecutableMode.INVOKE)));
<add> assertPredicateMatches(reflection.onConstructor(publicConstructor).invoke());
<add> }
<add>
<add> @Test
<add> void constructorInvocationDoesNotMatchIntrospectPublicConstructors() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withMembers(MemberCategory.INTROSPECT_PUBLIC_CONSTRUCTORS));
<add> assertPredicateDoesNotMatch(reflection.onConstructor(publicConstructor).invoke());
<add> }
<add>
<add> @Test
<add> void constructorInvocationMatchesInvokePublicConstructors() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withMembers(MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS));
<add> assertPredicateMatches(reflection.onConstructor(publicConstructor).invoke());
<add> }
<add>
<add> @Test
<add> void constructorInvocationDoesNotMatchIntrospectDeclaredConstructors() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withMembers(MemberCategory.INTROSPECT_DECLARED_CONSTRUCTORS));
<add> assertPredicateDoesNotMatch(reflection.onConstructor(publicConstructor).invoke());
<add> }
<add>
<add> @Test
<add> void constructorInvocationMatchesInvokeDeclaredConstructors() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS));
<add> assertPredicateMatches(reflection.onConstructor(publicConstructor).invoke());
<add> }
<add>
<add> @Test
<add> void privateConstructorIntrospectionMatchesConstructorHint() {
<add> List<TypeReference> parameterTypes = Collections.singletonList(TypeReference.of(String.class));
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withConstructor(parameterTypes, constructorHint -> {
<add> }));
<add> assertPredicateMatches(reflection.onConstructor(privateConstructor).introspect());
<add> }
<add>
<add> @Test
<add> void privateConstructorIntrospectionDoesNotMatchIntrospectPublicConstructors() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withMembers(MemberCategory.INTROSPECT_PUBLIC_CONSTRUCTORS));
<add> assertPredicateDoesNotMatch(reflection.onConstructor(privateConstructor).introspect());
<add> }
<add>
<add> @Test
<add> void privateConstructorIntrospectionDoesNotMatchInvokePublicConstructors() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withMembers(MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS));
<add> assertPredicateDoesNotMatch(reflection.onConstructor(privateConstructor).introspect());
<add> }
<add>
<add> @Test
<add> void privateConstructorIntrospectionMatchesIntrospectDeclaredConstructors() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withMembers(MemberCategory.INTROSPECT_DECLARED_CONSTRUCTORS));
<add> assertPredicateMatches(reflection.onConstructor(privateConstructor).introspect());
<add> }
<add>
<add> @Test
<add> void privateConstructorIntrospectionMatchesInvokeDeclaredConstructors() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS));
<add> assertPredicateMatches(reflection.onConstructor(privateConstructor).introspect());
<add> }
<add>
<add> @Test
<add> void privateConstructorInvocationDoesNotMatchConstructorHint() {
<add> List<TypeReference> parameterTypes = Collections.singletonList(TypeReference.of(String.class));
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withConstructor(parameterTypes, constructorHint -> {
<add> }));
<add> assertPredicateDoesNotMatch(reflection.onConstructor(privateConstructor).invoke());
<add> }
<add>
<add> @Test
<add> void privateConstructorInvocationMatchesConstructorInvocationHint() {
<add> List<TypeReference> parameterTypes = Collections.singletonList(TypeReference.of(String.class));
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withConstructor(parameterTypes, constructorHint -> constructorHint.withMode(ExecutableMode.INVOKE)));
<add> assertPredicateMatches(reflection.onConstructor(privateConstructor).invoke());
<add> }
<add>
<add> @Test
<add> void privateConstructorInvocationDoesNotMatchIntrospectPublicConstructors() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withMembers(MemberCategory.INTROSPECT_PUBLIC_CONSTRUCTORS));
<add> assertPredicateDoesNotMatch(reflection.onConstructor(privateConstructor).invoke());
<add> }
<add>
<add> @Test
<add> void privateConstructorInvocationDoesNotMatchInvokePublicConstructors() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withMembers(MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS));
<add> assertPredicateDoesNotMatch(reflection.onConstructor(privateConstructor).invoke());
<add> }
<add>
<add> @Test
<add> void privateConstructorInvocationDoesNotMatchIntrospectDeclaredConstructors() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withMembers(MemberCategory.INTROSPECT_DECLARED_CONSTRUCTORS));
<add> assertPredicateDoesNotMatch(reflection.onConstructor(privateConstructor).invoke());
<add> }
<add>
<add> @Test
<add> void privateConstructorInvocationMatchesInvokeDeclaredConstructors() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS));
<add> assertPredicateMatches(reflection.onConstructor(privateConstructor).invoke());
<add> }
<add>
<add> // Reflection on method
<add>
<add> @Test
<add> void methodIntrospectionMatchesMethodHint() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withMethod("publicMethod", Collections.emptyList(), methodHint -> {
<add> }));
<add> assertPredicateMatches(reflection.onMethod(SampleClass.class, "publicMethod").introspect());
<add> }
<add>
<add> @Test
<add> void methodIntrospectionMatchesIntrospectPublicMethods() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withMembers(MemberCategory.INTROSPECT_PUBLIC_METHODS));
<add> assertPredicateMatches(reflection.onMethod(SampleClass.class, "publicMethod").introspect());
<add> }
<add>
<add> @Test
<add> void methodIntrospectionMatchesInvokePublicMethods() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withMembers(MemberCategory.INVOKE_PUBLIC_METHODS));
<add> assertPredicateMatches(reflection.onMethod(SampleClass.class, "publicMethod").introspect());
<add> }
<add>
<add> @Test
<add> void methodIntrospectionMatchesIntrospectDeclaredMethods() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withMembers(MemberCategory.INTROSPECT_DECLARED_METHODS));
<add> assertPredicateMatches(reflection.onMethod(SampleClass.class, "publicMethod").introspect());
<add> }
<add>
<add> @Test
<add> void methodIntrospectionMatchesInvokeDeclaredMethods() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withMembers(MemberCategory.INVOKE_DECLARED_METHODS));
<add> assertPredicateMatches(reflection.onMethod(SampleClass.class, "publicMethod").introspect());
<add> }
<add>
<add> @Test
<add> void methodInvocationDoesNotMatchMethodHint() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withMethod("publicMethod", Collections.emptyList(), methodHint -> {
<add> }));
<add> assertPredicateDoesNotMatch(reflection.onMethod(SampleClass.class, "publicMethod").invoke());
<add> }
<add>
<add> @Test
<add> void methodInvocationMatchesMethodInvocationHint() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withMethod("publicMethod", Collections.emptyList(), methodHint -> methodHint.withMode(ExecutableMode.INVOKE)));
<add> assertPredicateMatches(reflection.onMethod(SampleClass.class, "publicMethod").invoke());
<add> }
<add>
<add> @Test
<add> void methodInvocationDoesNotMatchIntrospectPublicMethods() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withMembers(MemberCategory.INTROSPECT_PUBLIC_METHODS));
<add> assertPredicateDoesNotMatch(reflection.onMethod(SampleClass.class, "publicMethod").invoke());
<add> }
<add>
<add> @Test
<add> void methodInvocationMatchesInvokePublicMethods() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withMembers(MemberCategory.INVOKE_PUBLIC_METHODS));
<add> assertPredicateMatches(reflection.onMethod(SampleClass.class, "publicMethod").invoke());
<add> }
<add>
<add> @Test
<add> void methodInvocationDoesNotMatchIntrospectDeclaredMethods() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withMembers(MemberCategory.INTROSPECT_DECLARED_METHODS));
<add> assertPredicateDoesNotMatch(reflection.onMethod(SampleClass.class, "publicMethod").invoke());
<add> }
<add>
<add> @Test
<add> void methodInvocationMatchesInvokeDeclaredMethods() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withMembers(MemberCategory.INVOKE_DECLARED_METHODS));
<add> assertPredicateMatches(reflection.onMethod(SampleClass.class, "publicMethod").invoke());
<add> }
<add>
<add> @Test
<add> void privateMethodIntrospectionMatchesMethodHint() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withMethod("privateMethod", Collections.emptyList(), methodHint -> {
<add> }));
<add> assertPredicateMatches(reflection.onMethod(SampleClass.class, "privateMethod").introspect());
<add> }
<add>
<add> @Test
<add> void privateMethodIntrospectionDoesNotMatchIntrospectPublicMethods() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withMembers(MemberCategory.INTROSPECT_PUBLIC_METHODS));
<add> assertPredicateDoesNotMatch(reflection.onMethod(SampleClass.class, "privateMethod").introspect());
<add> }
<add>
<add> @Test
<add> void privateMethodIntrospectionDoesNotMatchInvokePublicMethods() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withMembers(MemberCategory.INVOKE_PUBLIC_METHODS));
<add> assertPredicateDoesNotMatch(reflection.onMethod(SampleClass.class, "privateMethod").introspect());
<add> }
<add>
<add> @Test
<add> void privateMethodIntrospectionMatchesIntrospectDeclaredMethods() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withMembers(MemberCategory.INTROSPECT_DECLARED_METHODS));
<add> assertPredicateMatches(reflection.onMethod(SampleClass.class, "privateMethod").introspect());
<add> }
<add>
<add> @Test
<add> void privateMethodIntrospectionMatchesInvokeDeclaredMethods() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withMembers(MemberCategory.INVOKE_DECLARED_METHODS));
<add> assertPredicateMatches(reflection.onMethod(SampleClass.class, "privateMethod").introspect());
<add> }
<add>
<add> @Test
<add> void privateMethodInvocationDoesNotMatchMethodHint() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withMethod("privateMethod", Collections.emptyList(), methodHint -> {
<add> }));
<add> assertPredicateDoesNotMatch(reflection.onMethod(SampleClass.class, "privateMethod").invoke());
<add> }
<add>
<add> @Test
<add> void privateMethodInvocationMatchesMethodInvocationHint() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withMethod("privateMethod", Collections.emptyList(), methodHint -> methodHint.withMode(ExecutableMode.INVOKE)));
<add> assertPredicateMatches(reflection.onMethod(SampleClass.class, "privateMethod").invoke());
<add> }
<add>
<add> @Test
<add> void privateMethodInvocationDoesNotMatchIntrospectPublicMethods() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withMembers(MemberCategory.INTROSPECT_PUBLIC_METHODS));
<add> assertPredicateDoesNotMatch(reflection.onMethod(SampleClass.class, "privateMethod").invoke());
<add> }
<add>
<add> @Test
<add> void privateMethodInvocationDoesNotMatchInvokePublicMethods() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withMembers(MemberCategory.INVOKE_PUBLIC_METHODS));
<add> assertPredicateDoesNotMatch(reflection.onMethod(SampleClass.class, "privateMethod").invoke());
<add> }
<add>
<add> @Test
<add> void privateMethodInvocationDoesNotMatchIntrospectDeclaredMethods() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withMembers(MemberCategory.INTROSPECT_DECLARED_METHODS));
<add> assertPredicateDoesNotMatch(reflection.onMethod(SampleClass.class, "privateMethod").invoke());
<add> }
<add>
<add> @Test
<add> void privateMethodInvocationMatchesInvokeDeclaredMethods() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withMembers(MemberCategory.INVOKE_DECLARED_METHODS));
<add> assertPredicateMatches(reflection.onMethod(SampleClass.class, "privateMethod").invoke());
<add> }
<add>
<add> // Reflection on field
<add>
<add> @Test
<add> void shouldFailForMissingField() {
<add> assertThatThrownBy(() -> reflection.onField(SampleClass.class, "missingField")).isInstanceOf(IllegalArgumentException.class);
<add> }
<add>
<add> @Test
<add> void fieldReflectionMatchesFieldHint() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withField("publicField", fieldHint -> {
<add> }));
<add> assertPredicateMatches(reflection.onField(SampleClass.class, "publicField"));
<add> }
<add>
<add> @Test
<add> void fieldWriteReflectionDoesNotMatchFieldHint() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withField("publicField", fieldHint -> {
<add> }));
<add> assertPredicateDoesNotMatch(reflection.onField(SampleClass.class, "publicField").allowWrite());
<add> }
<add>
<add> @Test
<add> void fieldUnsafeReflectionDoesNotMatchFieldHint() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withField("publicField", fieldHint -> {
<add> }));
<add> assertPredicateDoesNotMatch(reflection.onField(SampleClass.class, "publicField").allowUnsafeAccess());
<add> }
<add>
<add> @Test
<add> void fieldWriteReflectionMatchesFieldHintWithWrite() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint ->
<add> typeHint.withField("publicField", fieldHint -> fieldHint.allowWrite(true)));
<add> assertPredicateMatches(reflection.onField(SampleClass.class, "publicField").allowWrite());
<add> }
<add>
<add> @Test
<add> void fieldUnsafeReflectionMatchesFieldHintWithUnsafe() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class,
<add> typeHint -> typeHint.withField("publicField", fieldHint -> fieldHint.allowUnsafeAccess(true)));
<add> assertPredicateMatches(reflection.onField(SampleClass.class, "publicField").allowUnsafeAccess());
<add> }
<add>
<add> @Test
<add> void fieldReflectionMatchesPublicFieldsHint() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withMembers(MemberCategory.PUBLIC_FIELDS));
<add> assertPredicateMatches(reflection.onField(SampleClass.class, "publicField"));
<add> }
<add>
<add> @Test
<add> void fieldReflectionMatchesDeclaredFieldsHint() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withMembers(MemberCategory.DECLARED_FIELDS));
<add> assertPredicateMatches(reflection.onField(SampleClass.class, "publicField"));
<add> }
<add>
<add> @Test
<add> void privateFieldReflectionMatchesFieldHint() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withField("privateField", fieldHint -> {
<add> }));
<add> assertPredicateMatches(reflection.onField(SampleClass.class, "privateField"));
<add> }
<add>
<add> @Test
<add> void privateFieldReflectionDoesNotMatchPublicFieldsHint() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withMembers(MemberCategory.PUBLIC_FIELDS));
<add> assertPredicateDoesNotMatch(reflection.onField(SampleClass.class, "privateField"));
<add> }
<add>
<add> @Test
<add> void privateFieldReflectionMatchesDeclaredFieldsHint() {
<add> this.runtimeHints.reflection().registerType(SampleClass.class, typeHint -> typeHint.withMembers(MemberCategory.DECLARED_FIELDS));
<add> assertPredicateMatches(reflection.onField(SampleClass.class, "privateField"));
<add> }
<add>
<add>
<add> private void assertPredicateMatches(Predicate<RuntimeHints> predicate) {
<add> assertThat(predicate).accepts(this.runtimeHints);
<add> }
<add>
<add> private void assertPredicateDoesNotMatch(Predicate<RuntimeHints> predicate) {
<add> assertThat(predicate).rejects(this.runtimeHints);
<add> }
<add>
<add>
<add> static class SampleClass {
<add>
<add> private String privateField;
<add>
<add> public String publicField;
<add>
<add> public SampleClass() {
<add>
<add> }
<add>
<add> private SampleClass(String message) {
<add>
<add> }
<add>
<add> public void publicMethod() {
<add>
<add> }
<add>
<add> private void privateMethod() {
<add>
<add> }
<add>
<add> }
<add>
<add>}
<ide><path>spring-core/src/test/java/org/springframework/aot/hint/ResourceHintsPredicatesTests.java
<add>/*
<add> * Copyright 2002-2022 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.aot.hint;
<add>
<add>import java.util.function.Predicate;
<add>
<add>import org.junit.jupiter.api.BeforeEach;
<add>import org.junit.jupiter.api.Test;
<add>
<add>import static org.assertj.core.api.Assertions.assertThat;
<add>
<add>/**
<add> * Tests for {@link ReflectionHintsPredicates}.
<add> *
<add> * @author Brian Clozel
<add> */
<add>class ResourceHintsPredicatesTests {
<add>
<add> private final ResourceHintsPredicates resources = new ResourceHintsPredicates();
<add>
<add> private RuntimeHints runtimeHints;
<add>
<add>
<add> @BeforeEach
<add> void setup() {
<add> this.runtimeHints = new RuntimeHints();
<add> }
<add>
<add> @Test
<add> void resourcePatternMatchesResourceName() {
<add> this.runtimeHints.resources().registerPattern("/test/spring.*");
<add> assertPredicateMatches(resources.forResource("/test/spring.properties"));
<add> }
<add>
<add> @Test
<add> void resourcePatternDoesNotMatchResourceName() {
<add> this.runtimeHints.resources().registerPattern("/test/spring.*");
<add> assertPredicateDoesNotMatch(resources.forResource("/test/other.properties"));
<add> }
<add>
<add> @Test
<add> void resourcePatternMatchesTypeAndResourceName() {
<add> this.runtimeHints.resources().registerPattern("/org/springframework/aot/hint/spring.*");
<add> assertPredicateMatches(resources.forResource(TypeReference.of(getClass()), "spring.properties"));
<add> }
<add>
<add> @Test
<add> void resourcePatternDoesNotMatchTypeAndResourceName() {
<add> this.runtimeHints.resources().registerPattern("/spring.*");
<add> assertPredicateDoesNotMatch(resources.forResource(TypeReference.of(getClass()), "spring.properties"));
<add> }
<add>
<add> @Test
<add> void resourceBundleMatchesBundleName() {
<add> this.runtimeHints.resources().registerResourceBundle("spring");
<add> assertPredicateMatches(resources.forBundle("spring"));
<add> }
<add>
<add> @Test
<add> void resourceBundleDoesNotMatchBundleName() {
<add> this.runtimeHints.resources().registerResourceBundle("spring");
<add> assertPredicateDoesNotMatch(resources.forBundle("other"));
<add> }
<add>
<add>
<add> private void assertPredicateMatches(Predicate<RuntimeHints> predicate) {
<add> assertThat(predicate.test(this.runtimeHints)).isTrue();
<add> }
<add>
<add> private void assertPredicateDoesNotMatch(Predicate<RuntimeHints> predicate) {
<add> assertThat(predicate.test(this.runtimeHints)).isFalse();
<add> }
<add>
<add>}
<ide><path>spring-core/src/test/java/org/springframework/aot/hint/support/CoreAnnotationsRuntimeHintsRegistrarTests.java
<ide>
<ide> import org.springframework.aot.hint.MemberCategory;
<ide> import org.springframework.aot.hint.RuntimeHints;
<add>import org.springframework.aot.hint.RuntimeHintsPredicates;
<ide> import org.springframework.aot.hint.RuntimeHintsRegistrar;
<del>import org.springframework.aot.hint.TypeReference;
<ide> import org.springframework.core.annotation.AliasFor;
<ide> import org.springframework.core.annotation.Order;
<ide> import org.springframework.core.io.support.SpringFactoriesLoader;
<ide> void setup() {
<ide>
<ide> @Test
<ide> void aliasForHasHints() {
<del> assertThat(this.hints.reflection().getTypeHint(TypeReference.of(AliasFor.class)))
<del> .satisfies(hint -> assertThat(hint.getMemberCategories())
<del> .containsExactly(MemberCategory.INVOKE_DECLARED_METHODS));
<add> assertThat(RuntimeHintsPredicates.reflection().onType(AliasFor.class)
<add> .withMemberCategory(MemberCategory.INVOKE_DECLARED_METHODS)).accepts(this.hints);
<ide> }
<ide>
<ide> @Test
<ide> void orderAnnotationHasHints() {
<del> assertThat(this.hints.reflection().getTypeHint(TypeReference.of(Order.class)))
<del> .satisfies(hint -> assertThat(hint.getMemberCategories())
<del> .containsExactly(MemberCategory.INVOKE_DECLARED_METHODS));
<add> assertThat(RuntimeHintsPredicates.reflection().onType(Order.class)
<add> .withMemberCategory(MemberCategory.INVOKE_DECLARED_METHODS)).accepts(this.hints);
<ide> }
<ide>
<ide> }
<ide><path>spring-core/src/test/java/org/springframework/aot/hint/support/SpringFactoriesLoaderRuntimeHintsRegistrarTests.java
<ide> import org.junit.jupiter.api.Test;
<ide>
<ide> import org.springframework.aot.hint.MemberCategory;
<del>import org.springframework.aot.hint.ResourcePatternHint;
<ide> import org.springframework.aot.hint.RuntimeHints;
<add>import org.springframework.aot.hint.RuntimeHintsPredicates;
<ide> import org.springframework.aot.hint.RuntimeHintsRegistrar;
<del>import org.springframework.aot.hint.TypeHint;
<del>import org.springframework.aot.hint.TypeReference;
<ide> import org.springframework.core.io.support.DummyFactory;
<ide> import org.springframework.core.io.support.MyDummyFactory1;
<ide> import org.springframework.core.io.support.SpringFactoriesLoader;
<ide> void setup() {
<ide>
<ide> @Test
<ide> void resourceLocationHasHints() {
<del> assertThat(this.hints.resources().resourcePatterns())
<del> .anySatisfy(hint -> assertThat(hint.getIncludes()).map(ResourcePatternHint::getPattern)
<del> .contains(SpringFactoriesLoader.FACTORIES_RESOURCE_LOCATION));
<add> assertThat(RuntimeHintsPredicates.resource().forResource(SpringFactoriesLoader.FACTORIES_RESOURCE_LOCATION)).accepts(this.hints);
<ide> }
<ide>
<ide> @Test
<ide> void factoryTypeHasHint() {
<del> TypeReference type = TypeReference.of(DummyFactory.class);
<del> assertThat(this.hints.reflection().getTypeHint(type))
<del> .satisfies(this::expectedHints);
<add> assertThat(RuntimeHintsPredicates.reflection().onType(DummyFactory.class)
<add> .withMemberCategory(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)).accepts(this.hints);
<ide> }
<ide>
<ide> @Test
<ide> void factoryImplementationHasHint() {
<del> TypeReference type = TypeReference.of(MyDummyFactory1.class);
<del> assertThat(this.hints.reflection().getTypeHint(type))
<del> .satisfies(this::expectedHints);
<del> }
<del>
<del> private void expectedHints(TypeHint hint) {
<del> assertThat(hint.getMemberCategories())
<del> .containsExactly(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS);
<add> assertThat(RuntimeHintsPredicates.reflection().onType(MyDummyFactory1.class)
<add> .withMemberCategory(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)).accepts(this.hints);
<ide> }
<ide>
<ide> }
<ide><path>spring-orm/src/test/java/org/springframework/orm/jpa/support/InjectionCodeGeneratorTests.java
<ide>
<ide> import org.junit.jupiter.api.Test;
<ide>
<del>import org.springframework.aot.hint.ExecutableMode;
<ide> import org.springframework.aot.hint.RuntimeHints;
<add>import org.springframework.aot.hint.RuntimeHintsPredicates;
<ide> import org.springframework.aot.test.generator.compile.Compiled;
<ide> import org.springframework.aot.test.generator.compile.TestCompiler;
<ide> import org.springframework.beans.testfixture.beans.TestBean;
<ide> void generateCodeWhenPrivateFieldAddsHint() {
<ide> TestBean bean = new TestBean();
<ide> Field field = ReflectionUtils.findField(bean.getClass(), "age");
<ide> this.generator.generateInjectionCode(field, INSTANCE_VARIABLE, CodeBlock.of("$L", 123));
<del> assertThat(this.hints.reflection().getTypeHint(TestBean.class))
<del> .satisfies(hint -> assertThat(hint.fields()).anySatisfy(fieldHint -> {
<del> assertThat(fieldHint.getName()).isEqualTo("age");
<del> assertThat(fieldHint.isAllowWrite()).isTrue();
<del> }));
<add> assertThat(RuntimeHintsPredicates.reflection().onField(TestBean.class, "age").allowWrite())
<add> .accepts(this.hints);
<ide> }
<ide>
<ide> @Test
<ide> void generateCodeWhenPrivateMethodAddsHint() {
<ide> TestBeanWithPrivateMethod bean = new TestBeanWithPrivateMethod();
<ide> Method method = ReflectionUtils.findMethod(bean.getClass(), "setAge", int.class);
<ide> this.generator.generateInjectionCode(method, INSTANCE_VARIABLE, CodeBlock.of("$L", 123));
<del> assertThat(this.hints.reflection().getTypeHint(TestBeanWithPrivateMethod.class))
<del> .satisfies(hint -> assertThat(hint.methods()).anySatisfy(methodHint -> {
<del> assertThat(methodHint.getName()).isEqualTo("setAge");
<del> assertThat(methodHint.getModes()).contains(ExecutableMode.INVOKE);
<del> }));
<add> assertThat(RuntimeHintsPredicates.reflection()
<add> .onMethod(TestBeanWithPrivateMethod.class, "setAge").invoke()).accepts(this.hints);
<ide> }
<ide>
<ide> @SuppressWarnings("unchecked")
| 13
|
Text
|
Text
|
update custom renderer docs
|
394b17eede14c97ceff3827b716ca016e805a094
|
<ide><path>packages/react-reconciler/README.md
<ide> This is an experimental package for creating custom React renderers.
<ide> ```js
<ide> var Reconciler = require('react-reconciler');
<ide>
<del>var ReconcilerConfig = {
<add>var HostConfig = {
<ide> // You'll need to implement some methods here.
<ide> // See below for more information and examples.
<ide> };
<ide>
<del>var MyRenderer = Reconciler(ReconcilerConfig);
<add>var MyRenderer = Reconciler(HostConfig);
<ide>
<ide> var RendererPublicAPI = {
<ide> render(element, container, callback) {
<ide> module.exports = RendererPublicAPI;
<ide>
<ide> ## Practical Examples
<ide>
<del>* [React ART](https://github.com/facebook/react/blob/master/packages/react-art/src/ReactART.js)
<del>* [React DOM](https://github.com/facebook/react/blob/master/packages/react-dom/src/client/ReactDOM.js)
<del>* [React Native](https://github.com/facebook/react/blob/master/packages/react-native-renderer/src/ReactNativeRenderer.js)
<add>A "host config" is an object that you need to provide, and that describes how to make something happen in the "host" environment (e.g. DOM, canvas, console, or whatever your rendering target is). It looks like this:
<ide>
<del>If these links break please file an issue and we’ll fix them. They intentionally link to the latest versions since the API is still evolving.
<add>```js
<add>var HostConfig = {
<add> createInstance(type, props) {
<add> // e.g. DOM renderer returns a DOM node
<add> },
<add> // ...
<add> supportsMutation: true, // it works by mutating nodes
<add> appendChild(parent, child) {
<add> // e.g. DOM renderer would call .appendChild() here
<add> },
<add> // ...
<add>};
<add>```
<add>
<add>The full list of supported methods [can be found here](https://github.com/facebook/react/blob/master/packages/react-reconciler/src/forks/ReactFiberHostConfig.custom.js). For their signatures, we recommend looking at specific examples below.
<add>
<add>The React repository includes several renderers. Each of them has its own host config.
<add>
<add>The examples in the React repository are declared a bit differently than a third-party renderer would be. In particular, the `HostConfig` object mentioned above is never explicitly declared, and instead is a *module* in our code. However, its exports correspond directly to properties on a `HostConfig` object you'd need to declare in your code:
<add>
<add>* [React ART](https://github.com/facebook/react/blob/master/packages/react-art/src/ReactART.js) and its [host config](https://github.com/facebook/react/blob/master/packages/react-art/src/ReactARTHostConfig.js)
<add>* [React DOM](https://github.com/facebook/react/blob/master/packages/react-dom/src/client/ReactDOM.js) and its [host config](https://github.com/facebook/react/blob/master/packages/react-dom/src/client/ReactDOMHostConfig.js)
<add>* [React Native](https://github.com/facebook/react/blob/master/packages/react-native-renderer/src/ReactNativeRenderer.js) and its [host config](https://github.com/facebook/react/blob/master/packages/react-native-renderer/src/ReactNativeHostConfig.js)
<ide>
<del>This [third-party tutorial](https://github.com/nitin42/Making-a-custom-React-renderer) is relatively up-to-date and may be helpful.
<add>If these links break please file an issue and we’ll fix them. They intentionally link to the latest versions since the API is still evolving. If you have more questions please file an issue and we’ll try to help!
| 1
|
Text
|
Text
|
add links to dataflow.md
|
f02a1cfb8d28f603aef7c477d9cd8128744e9d01
|
<ide><path>docs/basics/DataFlow.md
<ide> The data lifecycle in any Redux app follows these 4 steps:
<ide>
<ide> 1. **You call** [`store.dispatch(action)`](../api/Store.md#dispatch).
<ide>
<del> An action is a plain object describing *what happened*. For example:
<add> An [action](Actions.md) is a plain object describing *what happened*. For example:
<ide>
<ide> ```js
<ide> { type: 'LIKE_ARTICLE', articleId: 42 };
<ide> The data lifecycle in any Redux app follows these 4 steps:
<ide>
<ide> 2. **The Redux store calls the reducer function you gave it.**
<ide>
<del> The store will pass two arguments to the reducer, the current state tree and the action. For example, in the todo app, the root reducer might receive something like this:
<add> The [store](Store.md) will pass two arguments to the [reducer](Reducers.md): the current state tree and the action. For example, in the todo app, the root reducer might receive something like this:
<ide>
<ide> ```js
<ide> // The current application state (list of todos and chosen filter)
| 1
|
Javascript
|
Javascript
|
add htmlbars version of `makeboundhelper`
|
aceb1d6bd1cf3a40649241112f81a811eb7c1373
|
<ide><path>packages/ember-htmlbars/lib/compat/make-bound-helper.js
<add>import Ember from "ember-metal/core"; // Ember.FEATURES, Ember.assert, Ember.Handlebars, Ember.lookup
<add>import { IS_BINDING } from "ember-metal/mixin";
<add>import simpleBind from "ember-htmlbars/system/simple-bind";
<add>import merge from "ember-metal/merge";
<add>import Helper from "ember-htmlbars/system/helper";
<add>
<add>import Stream from "ember-metal/streams/stream";
<add>import {
<add> readArray,
<add> readHash
<add>} from "ember-metal/streams/read";
<add>
<add>/**
<add> A helper function used by `registerBoundHelper`. Takes the
<add> provided Handlebars helper function fn and returns it in wrapped
<add> bound helper form.
<add>
<add> The main use case for using this outside of `registerBoundHelper`
<add> is for registering helpers on the container:
<add>
<add> ```js
<add> var boundHelperFn = Ember.Handlebars.makeBoundHelper(function(word) {
<add> return word.toUpperCase();
<add> });
<add>
<add> container.register('helper:my-bound-helper', boundHelperFn);
<add> ```
<add>
<add> In the above example, if the helper function hadn't been wrapped in
<add> `makeBoundHelper`, the registered helper would be unbound.
<add>
<add> @method makeBoundHelper
<add> @for Ember.Handlebars
<add> @param {Function} function
<add> @param {String} dependentKeys*
<add> @since 1.2.0
<add>*/
<add>export default function makeBoundHelper(fn, compatMode) {
<add> var dependentKeys = [];
<add> for (var i = 1; i < arguments.length; i++) {
<add> dependentKeys.push(arguments[i]);
<add> }
<add>
<add> function helperFunc(params, hash, options, env) {
<add> var view = this;
<add> var numParams = params.length;
<add>
<add> Ember.assert("registerBoundHelper-generated helpers do not support use with Handlebars blocks.", !options.render);
<add>
<add> for (var prop in hash) {
<add> if (IS_BINDING.test(prop)) {
<add> hash[prop.slice(0, -7)] = view.getStream(hash[prop]);
<add> delete hash[prop];
<add> }
<add> }
<add>
<add> function valueFn() {
<add> var args = readArray(params);
<add>
<add> args.push({
<add> hash: readHash(hash),
<add> data: { properties: options._raw.params }
<add> });
<add> return fn.apply(view, args);
<add> }
<add>
<add> if (env.data.isUnbound) {
<add> return valueFn();
<add> } else {
<add> var lazyValue = new Stream(valueFn);
<add> var bindOptions = {
<add> escaped: !hash.unescaped,
<add> morph: options.morph
<add> };
<add>
<add> simpleBind.call(this, [lazyValue], {}, bindOptions);
<add>
<add> var param;
<add>
<add> for (i = 0; i < numParams; i++) {
<add> param = params[i];
<add> if (param && param.isStream) {
<add> param.subscribe(lazyValue.notify, lazyValue);
<add> }
<add> }
<add>
<add> for (prop in hash) {
<add> param = hash[prop];
<add> if (param && param.isStream) {
<add> param.subscribe(lazyValue.notify, lazyValue);
<add> }
<add> }
<add>
<add> if (numParams > 0) {
<add> var firstParam = params[0];
<add> // Only bother with subscriptions if the first argument
<add> // is a stream itself, and not a primitive.
<add> if (firstParam && firstParam.isStream) {
<add> var onDependentKeyNotify = function onDependentKeyNotify(stream) {
<add> stream.value();
<add> lazyValue.notify();
<add> };
<add> for (i = 0; i < dependentKeys.length; i++) {
<add> var childParam = firstParam.get(dependentKeys[i]);
<add> childParam.value();
<add> childParam.subscribe(onDependentKeyNotify);
<add> }
<add> }
<add> }
<add> }
<add> }
<add>
<add> function preprocessArguments(view, params, hash, options, env) {
<add> options._raw = {
<add> params: params.slice(),
<add> hash: merge({}, hash)
<add> };
<add> }
<add>
<add> return new Helper(helperFunc, preprocessArguments);
<add>}
<ide><path>packages/ember-htmlbars/lib/compat/register-bound-helper.js
<add>/**
<add>@module ember
<add>@submodule ember-htmlbars
<add>*/
<add>
<add>import helpers from "ember-htmlbars/helpers";
<add>import makeBoundHelper from "ember-htmlbars/compat/make-bound-helper";
<add>
<add>var slice = [].slice;
<add>
<add>/**
<add> Register a bound handlebars helper. Bound helpers behave similarly to regular
<add> handlebars helpers, with the added ability to re-render when the underlying data
<add> changes.
<add>
<add> ## Simple example
<add>
<add> ```javascript
<add> Ember.Handlebars.registerBoundHelper('capitalize', function(value) {
<add> return Ember.String.capitalize(value);
<add> });
<add> ```
<add>
<add> The above bound helper can be used inside of templates as follows:
<add>
<add> ```handlebars
<add> {{capitalize name}}
<add> ```
<add>
<add> In this case, when the `name` property of the template's context changes,
<add> the rendered value of the helper will update to reflect this change.
<add>
<add> ## Example with options
<add>
<add> Like normal handlebars helpers, bound helpers have access to the options
<add> passed into the helper call.
<add>
<add> ```javascript
<add> Ember.Handlebars.registerBoundHelper('repeat', function(value, options) {
<add> var count = options.hash.count;
<add> var a = [];
<add> while(a.length < count) {
<add> a.push(value);
<add> }
<add> return a.join('');
<add> });
<add> ```
<add>
<add> This helper could be used in a template as follows:
<add>
<add> ```handlebars
<add> {{repeat text count=3}}
<add> ```
<add>
<add> ## Example with bound options
<add>
<add> Bound hash options are also supported. Example:
<add>
<add> ```handlebars
<add> {{repeat text count=numRepeats}}
<add> ```
<add>
<add> In this example, count will be bound to the value of
<add> the `numRepeats` property on the context. If that property
<add> changes, the helper will be re-rendered.
<add>
<add> ## Example with extra dependencies
<add>
<add> The `Ember.Handlebars.registerBoundHelper` method takes a variable length
<add> third parameter which indicates extra dependencies on the passed in value.
<add> This allows the handlebars helper to update when these dependencies change.
<add>
<add> ```javascript
<add> Ember.Handlebars.registerBoundHelper('capitalizeName', function(value) {
<add> return value.get('name').toUpperCase();
<add> }, 'name');
<add> ```
<add>
<add> ## Example with multiple bound properties
<add>
<add> `Ember.Handlebars.registerBoundHelper` supports binding to
<add> multiple properties, e.g.:
<add>
<add> ```javascript
<add> Ember.Handlebars.registerBoundHelper('concatenate', function() {
<add> var values = Array.prototype.slice.call(arguments, 0, -1);
<add> return values.join('||');
<add> });
<add> ```
<add>
<add> Which allows for template syntax such as `{{concatenate prop1 prop2}}` or
<add> `{{concatenate prop1 prop2 prop3}}`. If any of the properties change,
<add> the helper will re-render. Note that dependency keys cannot be
<add> using in conjunction with multi-property helpers, since it is ambiguous
<add> which property the dependent keys would belong to.
<add>
<add> ## Use with unbound helper
<add>
<add> The `{{unbound}}` helper can be used with bound helper invocations
<add> to render them in their unbound form, e.g.
<add>
<add> ```handlebars
<add> {{unbound capitalize name}}
<add> ```
<add>
<add> In this example, if the name property changes, the helper
<add> will not re-render.
<add>
<add> ## Use with blocks not supported
<add>
<add> Bound helpers do not support use with Handlebars blocks or
<add> the addition of child views of any kind.
<add>
<add> @method registerBoundHelper
<add> @for Ember.Handlebars
<add> @param {String} name
<add> @param {Function} function
<add> @param {String} dependentKeys*
<add>*/
<add>export default function registerBoundHelper(name, fn) {
<add> var boundHelperArgs = slice.call(arguments, 1);
<add> var boundFn = makeBoundHelper.apply(this, boundHelperArgs);
<add>
<add> helpers[name] = boundFn;
<add>}
<ide><path>packages/ember-htmlbars/lib/helpers.js
<ide> export function helper(name, value) {
<ide> if (View.detect(value)) {
<ide> helpers[name] = makeViewHelper(value);
<ide> } else {
<del> // HTMLBars TODO: Support bound helpers
<del> // EmberHandlebars.registerBoundHelper.apply(null, arguments);
<del> throw new Error('unimplemented');
<add> throw new Error('registerBoundHelper not implemented yet.');
<ide> }
<ide> }
<ide>
<ide><path>packages/ember-htmlbars/lib/helpers/binding.js
<ide> import isNone from 'ember-metal/is_none';
<ide> import run from "ember-metal/run_loop";
<ide> import { get } from "ember-metal/property_get";
<ide> import SimpleStream from "ember-metal/streams/simple";
<add>import simpleBind from "ember-htmlbars/system/simple-bind";
<ide>
<ide> import BoundView from "ember-views/views/bound_view";
<del>import SimpleBoundView from "ember-views/views/simple_bound_view";
<ide>
<ide> function exists(value) {
<ide> return !isNone(value);
<ide> function bind(property, hash, options, env, preserveContext, shouldDisplay, valu
<ide> }));
<ide> }
<ide>
<del>function simpleBind(params, options, env) {
<del> var lazyValue = params[0];
<del>
<del> var view = new SimpleBoundView(
<del> lazyValue, options.escaped
<del> );
<del>
<del> view._parentView = this;
<del> view._morph = options.morph;
<del> this.appendChild(view);
<del>
<del> lazyValue.subscribe(this._wrapAsScheduled(function() {
<del> run.scheduleOnce('render', view, 'rerender');
<del> }));
<del>}
<del>
<ide> /**
<ide> `bind` can be used to display a value, then update that value if it
<ide> changes. For example, if you wanted to print the `title` property of
<ide> function bindHelper(params, hash, options, env) {
<ide> Ember.deprecate("The block form of bind, {{#bind foo}}{{/bind}}, has been deprecated and will be removed.");
<ide> bind.call(this, property, hash, options, env, false, exists);
<ide> } else {
<del> simpleBind.call(this, params, options, env);
<add> simpleBind.call(this, params, hash, options, env);
<ide> }
<ide> }
<ide>
<ide> export {
<ide> bind,
<del> simpleBind,
<ide> bindHelper
<ide> };
<ide><path>packages/ember-htmlbars/lib/system/simple-bind.js
<add>import run from "ember-metal/run_loop";
<add>import SimpleBoundView from "ember-views/views/simple_bound_view";
<add>
<add>export default function simpleBind(params, hash, options, env) {
<add> var lazyValue = params[0];
<add>
<add> var view = new SimpleBoundView(lazyValue, options.escaped);
<add>
<add> view._parentView = this;
<add> view._morph = options.morph;
<add> this.appendChild(view);
<add>
<add> lazyValue.subscribe(this._wrapAsScheduled(function() {
<add> run.scheduleOnce('render', view, 'rerender');
<add> }));
<add>}
<add><path>packages/ember-htmlbars/tests/compat/make_bound_helper_test.js
<del><path>packages/ember-handlebars/tests/helpers/bound_helper_test.js
<ide> import { get } from "ember-metal/property_get";
<ide> import { set } from "ember-metal/property_set";
<ide>
<ide> import EmberHandlebars from "ember-handlebars-compiler";
<del>var compile = EmberHandlebars.compile;
<add>import htmlbarsHelpers from "ember-htmlbars/helpers";
<add>import htmlbarsRegisterBoundHelper from "ember-htmlbars/compat/register-bound-helper";
<add>
<add>import EmberHandlebars from "ember-handlebars";
<add>import htmlbarsCompile from "ember-htmlbars/system/compile";
<add>
<add>var compile, helpers, helper;
<add>if (Ember.FEATURES.isEnabled('ember-htmlbars')) {
<add> compile = htmlbarsCompile;
<add> helpers = htmlbarsHelpers;
<add> helper = htmlbarsRegisterBoundHelper;
<add>} else {
<add> compile = EmberHandlebars.compile;
<add> helpers = EmberHandlebars.helpers;
<add> helper = EmberHandlebars.helper;
<add>}
<add>
<ide>
<ide> var view;
<ide>
<ide> function appendView() {
<ide> }
<ide>
<ide> function registerRepeatHelper() {
<del> EmberHandlebars.helper('repeat', function(value, options) {
<add> helper('repeat', function(value, options) {
<ide> var count = options.hash.count;
<ide> var a = [];
<ide> while(a.length < count) {
<ide> function registerRepeatHelper() {
<ide> });
<ide> }
<ide>
<del>QUnit.module("Handlebars bound helpers", {
<add>QUnit.module("ember-htmlbars: makeBoundHelper", {
<ide> setup: function() {
<ide> },
<ide> teardown: function() {
<ide> test("primitives should work correctly [DEPRECATED]", function() {
<ide> });
<ide>
<ide> test("should update bound helpers when properties change", function() {
<del> EmberHandlebars.helper('capitalize', function(value) {
<add> helper('capitalize', function(value) {
<ide> return value.toUpperCase();
<ide> });
<ide>
<ide> test("should update bound helpers when properties change", function() {
<ide> });
<ide>
<ide> test("should allow for computed properties with dependencies", function() {
<del> EmberHandlebars.helper('capitalizeName', function(value) {
<add> helper('capitalizeName', function(value) {
<ide> return get(value, 'name').toUpperCase();
<ide> }, 'name');
<ide>
<ide> test("bound helpers should support options", function() {
<ide> });
<ide>
<ide> test("bound helpers should support keywords", function() {
<del> EmberHandlebars.helper('capitalize', function(value) {
<add> helper('capitalize', function(value) {
<ide> return value.toUpperCase();
<ide> });
<ide>
<ide> test("bound helpers should support keywords", function() {
<ide> });
<ide>
<ide> test("bound helpers should support global paths [DEPRECATED]", function() {
<del> EmberHandlebars.helper('capitalize', function(value) {
<add> helper('capitalize', function(value) {
<ide> return value.toUpperCase();
<ide> });
<ide>
<ide> test("bound helpers should support global paths [DEPRECATED]", function() {
<ide> });
<ide>
<ide> test("bound helper should support this keyword", function() {
<del> EmberHandlebars.helper('capitalize', function(value) {
<add> helper('capitalize', function(value) {
<ide> return get(value, 'text').toUpperCase();
<ide> });
<ide>
<ide> test("bound helpers should support unquoted values as bound options", function()
<ide>
<ide> test("bound helpers should support multiple bound properties", function() {
<ide>
<del> EmberHandlebars.helper('concat', function() {
<add> helper('combine', function() {
<ide> return [].slice.call(arguments, 0, -1).join('');
<ide> });
<ide>
<ide> view = EmberView.create({
<ide> controller: EmberObject.create({thing1: 'ZOID', thing2: 'BERG'}),
<del> template: compile('{{concat thing1 thing2}}')
<add> template: compile('{{combine thing1 thing2}}')
<ide> });
<ide>
<ide> appendView();
<ide> test("bound helpers should support multiple bound properties", function() {
<ide> });
<ide>
<ide> test("bound helpers should expose property names in options.data.properties", function() {
<del> EmberHandlebars.helper('echo', function() {
<add> helper('echo', function() {
<ide> var options = arguments[arguments.length - 1];
<ide> var values = [].slice.call(arguments, 0, -1);
<ide> var a = [];
<ide> test("bound helpers should expose property names in options.data.properties", fu
<ide> });
<ide>
<ide> test("bound helpers can be invoked with zero args", function() {
<del> EmberHandlebars.helper('troll', function(options) {
<add> helper('troll', function(options) {
<ide> return options.hash.text || "TROLOLOL";
<ide> });
<ide>
<ide> test("should observe dependent keys passed to registerBoundHelper", function() {
<ide> })
<ide> });
<ide>
<del> EmberHandlebars.registerBoundHelper('fullName', function(value){
<add> helper('fullName', function(value){
<ide> return [
<ide> value.get('firstName'),
<ide> value.get('lastName'),
<ide> test("should observe dependent keys passed to registerBoundHelper", function() {
<ide>
<ide> equal(view.$().text(), 'Tom Owen 1692', 'render the helper after path change');
<ide> } finally {
<del> delete EmberHandlebars.helpers['fullName'];
<add> delete helpers['fullName'];
<ide> }
<ide> });
<ide>
<ide> test("shouldn't treat raw numbers as bound paths", function() {
<del> EmberHandlebars.helper('sum', function(a, b) {
<add> helper('sum', function(a, b) {
<ide> return a + b;
<ide> });
<ide>
<ide> test("shouldn't treat raw numbers as bound paths", function() {
<ide>
<ide> test("shouldn't treat quoted strings as bound paths", function() {
<ide> var helperCount = 0;
<del> EmberHandlebars.helper('concat', function(a, b, opt) {
<add> helper('combine', function(a, b, opt) {
<ide> helperCount++;
<ide> return a + b;
<ide> });
<ide>
<ide> view = EmberView.create({
<ide> controller: EmberObject.create({word: "jerkwater", loo: "unused"}),
<del> template: compile("{{concat word 'loo'}} {{concat '' word}} {{concat 'will' \"didi\"}}")
<add> template: compile("{{combine word 'loo'}} {{combine '' word}} {{combine 'will' \"didi\"}}")
<ide> });
<ide>
<ide> appendView();
<ide> test("shouldn't treat quoted strings as bound paths", function() {
<ide> });
<ide>
<ide> test("bound helpers can handle nulls in array (with primitives) [DEPRECATED]", function() {
<del> EmberHandlebars.helper('reverse', function(val) {
<add> helper('reverse', function(val) {
<ide> return val ? val.split('').reverse().join('') : "NOPE";
<ide> });
<ide>
<ide> test("bound helpers can handle nulls in array (with primitives) [DEPRECATED]", f
<ide> });
<ide>
<ide> test("bound helpers can handle nulls in array (with objects)", function() {
<del> EmberHandlebars.helper('print-foo', function(val) {
<add> helper('print-foo', function(val) {
<ide> return val ? get(val, 'foo') : "NOPE";
<ide> });
<ide>
<ide> test("bound helpers can handle nulls in array (with objects)", function() {
<ide>
<ide> test("bound helpers can handle `this` keyword when it's a non-object", function() {
<ide>
<del> EmberHandlebars.helper("shout", function(value) {
<add> helper("shout", function(value) {
<ide> return value + '!';
<ide> });
<ide>
<ide> test("bound helpers can handle `this` keyword when it's a non-object", function(
<ide> });
<ide>
<ide> test("should have correct argument types", function() {
<del> EmberHandlebars.helper('getType', function(value) {
<add> helper('getType', function(value) {
<ide> return typeof value;
<ide> });
<ide>
<ide> view = EmberView.create({
<ide> controller: EmberObject.create(),
<del> template: EmberHandlebars.compile('{{getType null}}, {{getType undefProp}}, {{getType "string"}}, {{getType 1}}, {{getType}}')
<add> template: compile('{{getType null}}, {{getType undefProp}}, {{getType "string"}}, {{getType 1}}, {{getType}}')
<ide> });
<ide>
<ide> appendView();
<ide><path>packages/ember-htmlbars/tests/helpers/unbound_test.js
<ide> import {
<ide>
<ide> import Container from 'ember-runtime/system/container';
<ide>
<del>import { makeBoundHelper } from 'ember-handlebars/ext';
<add>import {
<add> makeBoundHelper as handlebarsMakeBoundHelper
<add>} from 'ember-handlebars/ext';
<add>import htmlbarsMakeBoundHelper from "ember-htmlbars/compat/make-bound-helper";
<ide>
<del>var compile, helpers, registerBoundHelper;
<add>var compile, helpers, registerBoundHelper, makeBoundHelper;
<ide> if (Ember.FEATURES.isEnabled('ember-htmlbars')) {
<ide> compile = htmlbarsCompile;
<ide> registerBoundHelper = registerHTMLBarsHelper;
<add> makeBoundHelper = htmlbarsMakeBoundHelper;
<ide> helpers = htmlbarsHelpers;
<ide> } else {
<ide> compile = EmberHandlebars.compile;
<ide> registerBoundHelper = EmberHandlebars.registerBoundHelper;
<ide> helpers = EmberHandlebars.helpers;
<add> makeBoundHelper = handlebarsMakeBoundHelper;
<ide> }
<ide>
<ide> function appendView(view) {
<ide><path>packages/ember/tests/helpers/helper_registration_test.js
<ide> import "ember";
<ide> import EmberHandlebars from "ember-handlebars";
<ide> import htmlbarsCompile from "ember-htmlbars/system/compile";
<ide> import htmlbarsHelpers from "ember-htmlbars/helpers";
<add>import htmlbarsMakeBoundHelper from "ember-htmlbars/compat/make-bound-helper";
<ide>
<del>var compile, helpers;
<add>var compile, helpers, makeBoundHelper;
<ide> if (Ember.FEATURES.isEnabled('ember-htmlbars')) {
<ide> compile = htmlbarsCompile;
<ide> helpers = htmlbarsHelpers;
<add> makeBoundHelper = htmlbarsMakeBoundHelper;
<ide> } else {
<ide> compile = EmberHandlebars.compile;
<ide> helpers = EmberHandlebars.helpers;
<add> makeBoundHelper = EmberHandlebars.makeBoundHelper;
<ide> }
<ide>
<ide> var App, container;
<ide> test("Unbound dashed helpers registered on the container can be late-invoked", f
<ide> ok(!helpers['x-borf'], "Container-registered helper doesn't wind up on global helpers hash");
<ide> });
<ide>
<del>if (!Ember.FEATURES.isEnabled('ember-htmlbars')) {
<ide> // need to make `makeBoundHelper` for HTMLBars
<ide> test("Bound helpers registered on the container can be late-invoked", function() {
<ide>
<ide> test("Bound helpers registered on the container can be late-invoked", function()
<ide> container.register('controller:application', Ember.Controller.extend({
<ide> foo: "alex"
<ide> }));
<del> container.register('helper:x-reverse', Ember.Handlebars.makeBoundHelper(reverseHelper));
<add> container.register('helper:x-reverse', makeBoundHelper(reverseHelper));
<ide> });
<ide>
<ide> equal(Ember.$('#wrapper').text(), "-- xela", "The bound helper was invoked from the container");
<ide> ok(!helpers['x-reverse'], "Container-registered helper doesn't wind up on global helpers hash");
<ide> });
<ide>
<add>if (!Ember.FEATURES.isEnabled('ember-htmlbars')) {
<add>
<add> // we have unit tests for this in ember-htmlbars/tests/system/lookup-helper
<add> // and we are not going to recreate the handlebars helperMissing concept
<ide> test("Undashed helpers registered on the container can not (presently) be invoked", function() {
<ide>
<ide> var realHelperMissing = helpers.helperMissing;
<ide> test("Undashed helpers registered on the container can not (presently) be invoke
<ide> container.register('helper:omg', function() {
<ide> return "OMG";
<ide> });
<del> container.register('helper:yorp', Ember.Handlebars.makeBoundHelper(function() {
<add> container.register('helper:yorp', makeBoundHelper(function() {
<ide> return "YORP";
<ide> }));
<ide> });
| 8
|
PHP
|
PHP
|
fix failing test
|
4e9e1d8afb0ee0256b57a5316f179337c7c11b81
|
<ide><path>lib/Cake/Test/TestCase/Core/ConfigureTest.php
<ide> public function testDump() {
<ide> */
<ide> public function testDumpPartial() {
<ide> Configure::config('test_reader', new PhpReader(TMP));
<add> Configure::write('Error', ['test' => 'value']);
<ide>
<del> $result = Configure::dump('config_test.php', 'test_reader', array('Error'));
<add> $result = Configure::dump('config_test.php', 'test_reader', ['Error']);
<ide> $this->assertTrue($result > 0);
<ide> $result = file_get_contents(TMP . 'config_test.php');
<ide> $this->assertContains('<?php', $result);
| 1
|
Go
|
Go
|
simplify seccomp logic
|
a8e7115fca8db167d09d81d3b1d4aadcfcf4264b
|
<ide><path>daemon/seccomp_linux.go
<ide> import (
<ide> coci "github.com/containerd/containerd/oci"
<ide> "github.com/docker/docker/container"
<ide> "github.com/docker/docker/profiles/seccomp"
<del> specs "github.com/opencontainers/runtime-spec/specs-go"
<ide> "github.com/sirupsen/logrus"
<ide> )
<ide>
<ide> const supportsSeccomp = true
<ide> // WithSeccomp sets the seccomp profile
<ide> func WithSeccomp(daemon *Daemon, c *container.Container) coci.SpecOpts {
<ide> return func(ctx context.Context, _ coci.Client, _ *containers.Container, s *coci.Spec) error {
<del> var profile *specs.LinuxSeccomp
<del> var err error
<del>
<add> if c.SeccompProfile == "unconfined" {
<add> return nil
<add> }
<ide> if c.HostConfig.Privileged {
<ide> return nil
<ide> }
<del>
<ide> if !daemon.seccompEnabled {
<del> if c.SeccompProfile != "" && c.SeccompProfile != "unconfined" {
<add> if c.SeccompProfile != "" {
<ide> return fmt.Errorf("seccomp is not enabled in your kernel, cannot run a custom seccomp profile")
<ide> }
<ide> logrus.Warn("seccomp is not enabled in your kernel, running container without default profile")
<ide> c.SeccompProfile = "unconfined"
<del> }
<del> if c.SeccompProfile == "unconfined" {
<ide> return nil
<ide> }
<del> if c.SeccompProfile != "" {
<del> profile, err = seccomp.LoadProfile(c.SeccompProfile, s)
<del> if err != nil {
<del> return err
<del> }
<del> } else {
<del> if daemon.seccompProfile != nil {
<del> profile, err = seccomp.LoadProfile(string(daemon.seccompProfile), s)
<del> if err != nil {
<del> return err
<del> }
<del> } else {
<del> profile, err = seccomp.GetDefaultProfile(s)
<del> if err != nil {
<del> return err
<del> }
<del> }
<add> var err error
<add> switch {
<add> case c.SeccompProfile != "":
<add> s.Linux.Seccomp, err = seccomp.LoadProfile(c.SeccompProfile, s)
<add> case daemon.seccompProfile != nil:
<add> s.Linux.Seccomp, err = seccomp.LoadProfile(string(daemon.seccompProfile), s)
<add> default:
<add> s.Linux.Seccomp, err = seccomp.GetDefaultProfile(s)
<ide> }
<del>
<del> s.Linux.Seccomp = profile
<del> return nil
<add> return err
<ide> }
<ide> }
| 1
|
Ruby
|
Ruby
|
replace conditional assignment with an if-else
|
28227bd26b592d3c4ecb669a662750200938d734
|
<ide><path>Library/Homebrew/linkage_checker.rb
<ide> def unexpected_broken_libs
<ide> def broken_dylibs_with_expectations
<ide> output = {}
<ide> @broken_dylibs.each do |lib|
<del> output[lib] = (unexpected_broken_libs.include? lib) ? ["unexpected"] : ["expected"]
<add> output[lib] = if unexpected_broken_libs.include? lib
<add> ["unexpected"]
<add> else
<add> ["expected"]
<add> end
<ide> end
<ide> output
<ide> end
| 1
|
Python
|
Python
|
commit fix for listing public ip ranges
|
69a80e57852eae5cd08e94dffe9606dbc38d698d
|
<ide><path>libcloud/compute/drivers/azure_arm.py
<ide> def ex_list_public_ips(self, resource_group):
<ide> :rtype: ``list`` of :class:`.AzureIPAddress`
<ide> """
<ide>
<del> action = "/subscriptions/%s/providers/Microsoft.Network" \
<del> "/publicIPAddresses" % (self.subscription_id, resource_group)
<add> action = "/subscriptions/%s/resourceGroups/%s/" \
<add> "providers/Microsoft.Network/publicIPAddresses" \
<add> % (self.subscription_id, resource_group)
<ide> r = self.connection.request(action,
<ide> params={"api-version": "2015-06-15"})
<ide> return [self._to_ip_address(net) for net in r.object["value"]]
| 1
|
PHP
|
PHP
|
add stub methods to postgres + sqlite schemas
|
f31d30ba6356e4b7736ccdf61eec8eaf36a6bb0f
|
<ide><path>lib/Cake/Database/Schema/PostgresSchema.php
<ide> public function convertFieldDescription(Table $table, $row, $fieldParams = []) {
<ide> }
<ide> }
<ide>
<add>/**
<add> * Get the SQL to describe the indexes in a table.
<add> *
<add> * @param string $table The table name to get information on.
<add> * @return array An array of (sql, params) to execute.
<add> */
<add> public function describeIndexSql($table) {
<add> $sql = '';
<add> return [$sql, []];
<add> }
<add>
<add>/**
<add> * Convert an index into the abstract description.
<add> *
<add> * @param Cake\Database\Schema\Table $table The table object to append
<add> * an index or constraint to.
<add> * @param array $row The row data from describeIndexSql
<add> * @return void
<add> */
<add> public function convertIndexDescription(Table $table, $row) {
<add> }
<add>
<add>
<ide> /**
<ide> * Generate the SQL fragment for a single column.
<ide> *
<ide><path>lib/Cake/Database/Schema/SqliteSchema.php
<ide> public function convertFieldDescription(Table $table, $row, $fieldParams = []) {
<ide> }
<ide> }
<ide>
<add>/**
<add> * Get the SQL to describe the indexes in a table.
<add> *
<add> * @param string $table The table name to get information on.
<add> * @return array An array of (sql, params) to execute.
<add> */
<add> public function describeIndexSql($table) {
<add> $sql = '';
<add> return [$sql, []];
<add> }
<add>
<add>/**
<add> * Convert an index into the abstract description.
<add> *
<add> * @param Cake\Database\Schema\Table $table The table object to append
<add> * an index or constraint to.
<add> * @param array $row The row data from describeIndexSql
<add> * @return void
<add> */
<add> public function convertIndexDescription(Table $table, $row) {
<add> }
<add>
<ide> /**
<ide> * Generate the SQL fragment for a single column in Sqlite
<ide> *
| 2
|
Text
|
Text
|
update api reference
|
8d83cca7f705c4bae291be943e133291c6d34dc2
|
<ide><path>README.md
<ide> Compute the Voronoi diagram of a given set of points.
<ide>
<ide> * [d3.voronoi](https://github.com/d3/d3-voronoi#voronoi) - create a new Voronoi generator.
<ide> * [*voronoi*](https://github.com/d3/d3-voronoi#_voronoi) - generate a new Voronoi diagram for the given points.
<del>* [*voronoi*.cells](https://github.com/d3/d3-voronoi#voronoi_cells) - compute the Voronoi polygons for the given points.
<del>* [*voronoi*.links](https://github.com/d3/d3-voronoi#voronoi_links) - compute the Delaunay links for the given points.
<add>* [*voronoi*.polygons](https://github.com/d3/d3-voronoi#voronoi_polygons) - compute the Voronoi polygons for the given points.
<ide> * [*voronoi*.triangles](https://github.com/d3/d3-voronoi#voronoi_triangles) - compute the Delaunay triangles for the given points.
<add>* [*voronoi*.links](https://github.com/d3/d3-voronoi#voronoi_links) - compute the Delaunay links for the given points.
<ide> * [*voronoi*.x](https://github.com/d3/d3-voronoi#voronoi_x) - set the *x* accessor.
<ide> * [*voronoi*.y](https://github.com/d3/d3-voronoi#voronoi_y) - set the *y* accessor.
<ide> * [*voronoi*.extent](https://github.com/d3/d3-voronoi#voronoi_extent) - set the observed extent of points.
| 1
|
Go
|
Go
|
remove unused containeros argument
|
cae1dbee018b50a266376d7f32e04f37b4723932
|
<ide><path>daemon/delete.go
<ide> func (daemon *Daemon) cleanupContainer(container *container.Container, forceRemo
<ide> // When container creation fails and `RWLayer` has not been created yet, we
<ide> // do not call `ReleaseRWLayer`
<ide> if container.RWLayer != nil {
<del> err := daemon.imageService.ReleaseLayer(container.RWLayer, container.OS)
<add> err := daemon.imageService.ReleaseLayer(container.RWLayer)
<ide> if err != nil {
<ide> err = errors.Wrapf(err, "container %s", container.ID)
<ide> container.SetRemovalError(err)
<ide><path>daemon/export.go
<ide> func (daemon *Daemon) containerExport(container *container.Container) (arch io.R
<ide> }
<ide> defer func() {
<ide> if err != nil {
<del> daemon.imageService.ReleaseLayer(rwlayer, container.OS)
<add> daemon.imageService.ReleaseLayer(rwlayer)
<ide> }
<ide> }()
<ide>
<ide> func (daemon *Daemon) containerExport(container *container.Container) (arch io.R
<ide> arch = ioutils.NewReadCloserWrapper(archv, func() error {
<ide> err := archv.Close()
<ide> rwlayer.Unmount()
<del> daemon.imageService.ReleaseLayer(rwlayer, container.OS)
<add> daemon.imageService.ReleaseLayer(rwlayer)
<ide> return err
<ide> })
<ide> daemon.LogContainerEvent(container, "export")
<ide><path>daemon/images/service.go
<ide> func (i *ImageService) GraphDriverName() string {
<ide>
<ide> // ReleaseLayer releases a layer allowing it to be removed
<ide> // called from delete.go Daemon.cleanupContainer(), and Daemon.containerExport()
<del>func (i *ImageService) ReleaseLayer(rwlayer layer.RWLayer, containerOS string) error {
<add>func (i *ImageService) ReleaseLayer(rwlayer layer.RWLayer) error {
<ide> metadata, err := i.layerStore.ReleaseRWLayer(rwlayer)
<ide> layer.LogReleaseMetadata(metadata)
<ide> if err != nil && !errors.Is(err, layer.ErrMountDoesNotExist) && !errors.Is(err, os.ErrNotExist) {
| 3
|
PHP
|
PHP
|
fix failing tests in http package
|
2a6cb816b316e08f29d30f45f0d0a5436e7d76dd
|
<ide><path>src/Http/ServerRequestFactory.php
<ide> public static function fromGlobals(
<ide> array $files = null
<ide> ) {
<ide> $request = parent::fromGlobals($server, $query, $body, $cookies, $files);
<del> list($base, $webroot) = static::getBase($request->getUri(), $request->getServerParams());
<add> $uri = $request->getUri();
<ide>
<ide> $sessionConfig = (array)Configure::read('Session') + [
<ide> 'defaults' => 'php',
<del> 'cookiePath' => $webroot
<add> 'cookiePath' => $uri->webroot
<ide> ];
<ide> $session = Session::create($sessionConfig);
<del> $request = $request->withAttribute('base', $base)
<del> ->withAttribute('webroot', $webroot)
<add> $request = $request->withAttribute('base', $uri->base)
<add> ->withAttribute('webroot', $uri->webroot)
<ide> ->withAttribute('session', $session);
<ide>
<del> if ($base) {
<del> $request = static::updatePath($base, $request->getUri());
<del> }
<del>
<ide> return $request;
<ide> }
<ide>
<ide> public static function createUri(array $server = [])
<ide> $server += $_SERVER;
<ide> $server = static::normalizeServer($server);
<ide> $headers = static::marshalHeaders($server);
<add> return static::marshalUriFromServer($server, $headers);
<add> }
<ide>
<del> $uri = static::marshalUriFromServer($server, $headers);
<add> /**
<add> * Build a UriInterface object.
<add> *
<add> * Add in some CakePHP specific logic/properties that help
<add> * perserve backwards compatibility.
<add> *
<add> * @param array $server The server parameters.
<add> * @param array $headers The normalized headers
<add> * @return \Psr\Http\Message\UriInterface a constructed Uri
<add> */
<add> public static function marshalUriFromServer(array $server, array $headers)
<add> {
<add> $uri = parent::marshalUriFromServer($server, $headers);
<ide> list($base, $webroot) = static::getBase($uri, $server);
<ide>
<ide> // Look in PATH_INFO first, as this is the exact value we need prepared
| 1
|
Javascript
|
Javascript
|
prevent race condition on immediate transition
|
3a53228127b3e4c2e7424fd7735e28cf852bf658
|
<ide><path>Libraries/NavigationExperimental/NavigationTransitioner.js
<ide> class NavigationTransitioner extends React.Component<any, Props, State> {
<ide> progress,
<ide> } = nextState;
<ide>
<del> // update scenes.
<del> this.setState(nextState);
<del>
<ide> // get the transition spec.
<ide> const transitionUserSpec = nextProps.configureTransition ?
<ide> nextProps.configureTransition(
<ide> class NavigationTransitioner extends React.Component<any, Props, State> {
<ide> );
<ide> }
<ide>
<del> // play the transition.
<del> nextProps.onTransitionStart && nextProps.onTransitionStart(
<del> this._transitionProps,
<del> this._prevTransitionProps,
<del> );
<del> Animated.parallel(animations).start(this._onTransitionEnd);
<add> // update scenes and play the transition
<add> this.setState(nextState, () => {
<add> nextProps.onTransitionStart && nextProps.onTransitionStart(
<add> this._transitionProps,
<add> this._prevTransitionProps,
<add> );
<add> Animated.parallel(animations).start(this._onTransitionEnd);
<add> });
<ide> }
<ide>
<ide> render(): ReactElement<any> {
| 1
|
Ruby
|
Ruby
|
explain actionamailer authentication types
|
5a898e106a6f92ad2773a6525b0899cf906d2b3f
|
<ide><path>actionmailer/lib/action_mailer/base.rb
<ide> module ActionMailer #:nodoc:
<ide> # * <tt>:password</tt> - If your mail server requires authentication, set the password in this setting.
<ide> # * <tt>:authentication</tt> - If your mail server requires authentication, you need to specify the
<ide> # authentication type here.
<del> # This is a symbol and one of <tt>:plain</tt>, <tt>:login</tt>, <tt>:cram_md5</tt>.
<add> # This is a symbol and one of <tt>:plain</tt> (will send the password in the clear), <tt>:login</tt> (will
<add> # send password BASE64 encoded) or <tt>:cram_md5</tt> (combines a Challenge/Response mechanism to exchange
<add> # information and a cryptographic Message Digest 5 algorithm to hash important information)
<ide> # * <tt>:enable_starttls_auto</tt> - When set to true, detects if STARTTLS is enabled in your SMTP server
<ide> # and starts to use it.
<ide> #
| 1
|
Text
|
Text
|
put a verb in singular by removing a letter
|
599093488df9c0598b12fb8ed00fee4a935657b5
|
<ide><path>curriculum/challenges/english/09-information-security/information-security-with-helmetjs/understand-bcrypt-hashes.md
<ide> For the following challenges, you will be working with a new starter project tha
<ide>
<ide> BCrypt hashes are very secure. A hash is basically a fingerprint of the original data- always unique. This is accomplished by feeding the original data into an algorithm and returning a fixed length result. To further complicate this process and make it more secure, you can also *salt* your hash. Salting your hash involves adding random data to the original data before the hashing process which makes it even harder to crack the hash.
<ide>
<del>BCrypt hashes will always looks like `$2a$13$ZyprE5MRw2Q3WpNOGZWGbeG7ADUre1Q8QO.uUUtcbqloU0yvzavOm` which does have a structure. The first small bit of data `$2a` is defining what kind of hash algorithm was used. The next portion `$13` defines the *cost*. Cost is about how much power it takes to compute the hash. It is on a logarithmic scale of 2^cost and determines how many times the data is put through the hashing algorithm. For example, at a cost of 10 you are able to hash 10 passwords a second on an average computer, however at a cost of 15 it takes 3 seconds per hash... and to take it further, at a cost of 31 it would take multiple days to complete a hash. A cost of 12 is considered very secure at this time. The last portion of your hash `$ZyprE5MRw2Q3WpNOGZWGbeG7ADUre1Q8QO.uUUtcbqloU0yvzavOm`, looks like one large string of numbers, periods, and letters but it is actually two separate pieces of information. The first 22 characters is the salt in plain text, and the rest is the hashed password!
<add>BCrypt hashes will always look like `$2a$13$ZyprE5MRw2Q3WpNOGZWGbeG7ADUre1Q8QO.uUUtcbqloU0yvzavOm` which does have a structure. The first small bit of data `$2a` is defining what kind of hash algorithm was used. The next portion `$13` defines the *cost*. Cost is about how much power it takes to compute the hash. It is on a logarithmic scale of 2^cost and determines how many times the data is put through the hashing algorithm. For example, at a cost of 10 you are able to hash 10 passwords a second on an average computer, however at a cost of 15 it takes 3 seconds per hash... and to take it further, at a cost of 31 it would take multiple days to complete a hash. A cost of 12 is considered very secure at this time. The last portion of your hash `$ZyprE5MRw2Q3WpNOGZWGbeG7ADUre1Q8QO.uUUtcbqloU0yvzavOm`, looks like one large string of numbers, periods, and letters but it is actually two separate pieces of information. The first 22 characters is the salt in plain text, and the rest is the hashed password!
<ide>
<ide> # --instructions--
<ide>
| 1
|
Java
|
Java
|
update copyright year of evaluationtests
|
135506f67238a57bfb2fa8bff6480de611eda1d6
|
<ide><path>spring-expression/src/test/java/org/springframework/expression/spel/EvaluationTests.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.
| 1
|
Java
|
Java
|
fix typo in flowable javadoc
|
c045188ffbbb35bb62ce1d8a00353679321fa641
|
<ide><path>src/main/java/io/reactivex/rxjava3/core/Flowable.java
<ide> * Thread.sleep(1000);
<ide> *
<ide> * // the consumer might have cancelled the flow
<del> * if (emitter.isCancelled() {
<add> * if (emitter.isCancelled()) {
<ide> * return;
<ide> * }
<ide> *
| 1
|
Text
|
Text
|
add info about serializable types
|
b07c72b8be656c7a4a09a6a70ac02aec0688eb1c
|
<ide><path>doc/api/querystring.md
<ide> added: v0.1.25
<ide> The `querystring.stringify()` method produces a URL query string from a
<ide> given `obj` by iterating through the object's "own properties".
<ide>
<add>It serializes the following types of values passed in `obj`:
<add>{string|number|boolean|string[]|number[]|boolean[]}
<add>Any other input values will be coerced to empty strings.
<add>
<ide> For example:
<ide>
<ide> ```js
| 1
|
Text
|
Text
|
fix template typo
|
bd8098e31fcc20e10247866bb9faac31e471e1fc
|
<ide><path>docs/topics/html-and-forms.md
<del># HTML & Forms
<del>
<del>REST framework is suitable for returning both API style responses, and regular HTML pages. Additionally, serializers can used as HTML forms and rendered in templates.
<del>
<del>## Rendering HTML
<del>
<del>In order to return HTML responses you'll need to either `TemplateHTMLRenderer`, or `StaticHTMLRenderer`.
<del>
<del>The `TemplateHTMLRenderer` class expects the response to contain a dictionary of context data, and renders an HTML page based on a template that must be specified either in the view or on the response.
<del>
<del>The `StaticHTMLRender` class expects the response to contain a string of the pre-rendered HTML content.
<del>
<del>Because static HTML pages typically have different behavior from API responses you'll probably need to write any HTML views explicitly, rather than relying on the built-in generic views.
<del>
<del>Here's an example of a view that returns a list of "Profile" instances, rendered in an HTML template:
<del>
<del>**views.py**:
<del>
<del> from my_project.example.models import Profile
<del> from rest_framework.renderers import TemplateHTMLRenderer
<del> from rest_framework.response import Response
<del> from rest_framework.views import APIView
<del>
<del>
<del> class ProfileList(APIView):
<del> renderer_classes = [TemplateHTMLRenderer]
<del> template_name = 'profile_list.html'
<del>
<del> def get(self, request):
<del> queryset = Profile.objects.all()
<del> return Response({'profiles': queryset})
<del>
<del>**profile_list.html**:
<del>
<del> <html><body>
<del> <h1>Profiles</h1>
<del> <ul>
<del> {% for profile in profiles %}
<add># HTML & Forms
<add>
<add>REST framework is suitable for returning both API style responses, and regular HTML pages. Additionally, serializers can used as HTML forms and rendered in templates.
<add>
<add>## Rendering HTML
<add>
<add>In order to return HTML responses you'll need to either `TemplateHTMLRenderer`, or `StaticHTMLRenderer`.
<add>
<add>The `TemplateHTMLRenderer` class expects the response to contain a dictionary of context data, and renders an HTML page based on a template that must be specified either in the view or on the response.
<add>
<add>The `StaticHTMLRender` class expects the response to contain a string of the pre-rendered HTML content.
<add>
<add>Because static HTML pages typically have different behavior from API responses you'll probably need to write any HTML views explicitly, rather than relying on the built-in generic views.
<add>
<add>Here's an example of a view that returns a list of "Profile" instances, rendered in an HTML template:
<add>
<add>**views.py**:
<add>
<add> from my_project.example.models import Profile
<add> from rest_framework.renderers import TemplateHTMLRenderer
<add> from rest_framework.response import Response
<add> from rest_framework.views import APIView
<add>
<add>
<add> class ProfileList(APIView):
<add> renderer_classes = [TemplateHTMLRenderer]
<add> template_name = 'profile_list.html'
<add>
<add> def get(self, request):
<add> queryset = Profile.objects.all()
<add> return Response({'profiles': queryset})
<add>
<add>**profile_list.html**:
<add>
<add> <html><body>
<add> <h1>Profiles</h1>
<add> <ul>
<add> {% for profile in profiles %}
<ide> <li>{{ profile.name }}</li>
<del> {% endfor %}
<del> </ul>
<del> </body></html>
<del>
<del>## Rendering Forms
<del>
<del>Serializers may be rendered as forms by using the `render_form` template tag, and including the serializer instance as context to the template.
<del>
<del>The following view demonstrates an example of using a serializer in a template for viewing and updating a model instance:
<del>
<del>**views.py**:
<del>
<del> from django.shortcuts import get_object_or_404
<del> from my_project.example.models import Profile
<del> from rest_framework.renderers import TemplateHTMLRenderer
<del> from rest_framework.views import APIView
<del>
<del>
<del> class ProfileDetail(APIView):
<del> renderer_classes = [TemplateHTMLRenderer]
<del> template_name = 'profile_detail.html'
<del>
<del> def get(self, request, pk):
<del> profile = get_object_or_404(Profile, pk=pk)
<del> serializer = ProfileSerializer(profile)
<del> return Response({'serializer': serializer, 'profile': profile})
<del>
<del> def post(self, request, pk):
<del> profile = get_object_or_404(Profile, pk=pk)
<del> serializer = ProfileSerializer(profile)
<del> if not serializer.is_valid():
<del> return Response({'serializer': serializer, 'profile': profile})
<ide> return redirect('profile-list')
<del>
<del>**profile_detail.html**:
<del>
<del> {% load rest_framework %}
<del>
<del> <html><body>
<del>
<del> <h1>Profile - {{ profile.name }}</h1>
<del>
<del> <form action="{% url 'profile-detail' pk=profile.pk '%}" method="POST">
<del> {% csrf_token %}
<del> {% render_form serializer %}
<del> <input type="submit" value="Save">
<del> </form>
<del>
<del> </body></html>
<del>
<del>### Using template packs
<del>
<del>The `render_form` tag takes an optional `template_pack` argument, that specifies which template directory should be used for rendering the form and form fields.
<del>
<del>REST framework includes three built-in template packs, all based on Bootstrap 3. The built-in styles are `horizontal`, `vertical`, and `inline`. The default style is `horizontal`. To use any of these template packs you'll want to also include the Bootstrap 3 CSS.
<del>
<del>The following HTML will link to a CDN hosted version of the Bootstrap 3 CSS:
<del>
<del> <head>
<del> …
<del> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<del> </head>
<del>
<del>Third party packages may include alternate template packs, by bundling a template directory containing the necessary form and field templates.
<del>
<del>Let's take a look at how to render each of the three available template packs. For these examples we'll use a single serializer class to present a "Login" form.
<del>
<del> class LoginSerializer(serializers.Serializer):
<del> email = serializers.EmailField(
<del> max_length=100,
<del> style={'placeholder': 'Email'}
<del> )
<del> password = serializers.CharField(
<del> max_length=100,
<del> style={'input_type': 'password', 'placeholder': 'Password'}
<del> )
<del> remember_me = serializers.BooleanField()
<del>--
<del>
<del>#### `rest_framework/vertical`
<del>
<del>Presents form labels above their corresponding control inputs, using the standard Bootstrap layout.
<del>
<del>*This is the default template pack.*
<del>
<del> {% load rest_framework %}
<del>
<del> ...
<del>
<del> <form action="{% url 'login' %}" method="post" novalidate>
<del> {% csrf_token %}
<del> {% render_form serializer template_pack='rest_framework/vertical' %}
<del> <button type="submit" class="btn btn-default">Sign in</button>
<del> </form>
<del>
<del>
<del>
<del>---
<del>
<ide>#### `rest_framework/horizontal`
<del>
<del>Presents labels and controls alongside each other, using a 2/10 column split.
<del>
<del>*This is the form style used in the browsable API and admin renderers.*
<del>
<del> {% load rest_framework %}
<del>
<del> ...
<del>
<del> <form class="form-horizontal" action="{% url 'login' %}" method="post" novalidate>
<del> {% csrf_token %}
<del> {% render_form serializer %}
<del> <div class="form-group">
<del> <div class="col-sm-offset-2 col-sm-10">
<del> <button type="submit" class="btn btn-default">Sign in</button>
<del> </div>
<del> </div>
<del> </form>
<del>
<del>
<del>
<del>---
<del>
<del>#### `rest_framework/inline`
<del>
<del>A compact form style that presents all the controls inline.
<del>
<del> {% load rest_framework %}
<del>
<del> ...
<del>
<del> <form class="form-inline" action="{% url 'login' %}" method="post" novalidate>
<del> {% csrf_token %}
<del> {% render_form serializer template_pack='rest_framework/inline' %}
<del> <button type="submit" class="btn btn-default">Sign in</button>
<del> </form>
<del>
<del>
<del>
<del>## Field styles
<del>
<del>Serializer fields can have their rendering style customized by using the `style` keyword argument. This argument is a dictionary of options that control the template and layout used.
<del>
<del>The most common way to customize the field style is to use the `base_template` style keyword argument to select which template in the template pack should be use.
<del>
<del>For example, to render a `CharField` as an HTML textarea rather than the default HTML input, you would use something like this:
<del>
<del> details = serializers.CharField(
<del> max_length=1000,
<del> style={'base_template': 'textarea.html'}
<del> )
<del>
<del>If you instead want a field to be rendered using a custom template that is *not part of an included template pack*, you can instead use the `template` style option, to fully specify a template name:
<del>
<del> details = serializers.CharField(
<del> max_length=1000,
<del> style={'template': 'my-field-templates/custom-input.html'}
<del> )
<del>
<del>Field templates can also use additional style properties, depending on their type. For example, the `textarea.html` template also accepts a `rows` property that can be used to affect the sizing of the control.
<del>
<del> details = serializers.CharField(
<del> max_length=1000,
<del> style={'base_template': 'textarea.html', 'rows': 10}
<del> )
<del>
<del>The complete list of `base_template` options and their associated style options is listed below.
<del>
<del>base_template | Valid field types | Additional style options
<del>----|----|----
<del>input.html | Any string, numeric or date/time field | input_type, placeholder, hide_label
<del>textarea.html | `CharField` | rows, placeholder, hide_label
<del>select.html | `ChoiceField` or relational field types | hide_label
<del>radio.html | `ChoiceField` or relational field types | inline, hide_label
<del>select_multiple.html | `MultipleChoiceField` or relational fields with `many=True` | hide_label
<del>checkbox_multiple.html | `MultipleChoiceField` or relational fields with `many=True` | inline, hide_label
<del>checkbox.html | `BooleanField` | hide_label
<del>fieldset.html | Nested serializer | hide_label
<del>list_fieldset.html | `ListField` or nested serializer with `many=True` | hide_label
<add> {% endfor %}
<add> </ul>
<add> </body></html>
<add>
<add>## Rendering Forms
<add>
<add>Serializers may be rendered as forms by using the `render_form` template tag, and including the serializer instance as context to the template.
<add>
<add>The following view demonstrates an example of using a serializer in a template for viewing and updating a model instance:
<add>
<add>**views.py**:
<add>
<add> from django.shortcuts import get_object_or_404
<add> from my_project.example.models import Profile
<add> from rest_framework.renderers import TemplateHTMLRenderer
<add> from rest_framework.views import APIView
<add>
<add>
<add> class ProfileDetail(APIView):
<add> renderer_classes = [TemplateHTMLRenderer]
<add> template_name = 'profile_detail.html'
<add>
<add> def get(self, request, pk):
<add> profile = get_object_or_404(Profile, pk=pk)
<add> serializer = ProfileSerializer(profile)
<add> return Response({'serializer': serializer, 'profile': profile})
<add>
<add> def post(self, request, pk):
<add> profile = get_object_or_404(Profile, pk=pk)
<add> serializer = ProfileSerializer(profile)
<add> if not serializer.is_valid():
<add> return Response({'serializer': serializer, 'profile': profile})
<add> return redirect('profile-list')
<add>
<add>**profile_detail.html**:
<add>
<add> {% load rest_framework %}
<add>
<add> <html><body>
<add>
<add> <h1>Profile - {{ profile.name }}</h1>
<add>
<add> <form action="{% url 'profile-detail' pk=profile.pk %}" method="POST">
<add> {% csrf_token %}
<add> {% render_form serializer %}
<add> <input type="submit" value="Save">
<add> </form>
<add>
<add> </body></html>
<add>
<add>### Using template packs
<add>
<add>The `render_form` tag takes an optional `template_pack` argument, that specifies which template directory should be used for rendering the form and form fields.
<add>
<add>REST framework includes three built-in template packs, all based on Bootstrap 3. The built-in styles are `horizontal`, `vertical`, and `inline`. The default style is `horizontal`. To use any of these template packs you'll want to also include the Bootstrap 3 CSS.
<add>
<add>The following HTML will link to a CDN hosted version of the Bootstrap 3 CSS:
<add>
<add> <head>
<add> …
<add> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<add> </head>
<add>
<add>Third party packages may include alternate template packs, by bundling a template directory containing the necessary form and field templates.
<add>
<add>Let's take a look at how to render each of the three available template packs. For these examples we'll use a single serializer class to present a "Login" form.
<add>
<add> class LoginSerializer(serializers.Serializer):
<add> email = serializers.EmailField(
<add> max_length=100,
<add> style={'placeholder': 'Email'}
<add> )
<add> password = serializers.CharField(
<add> max_length=100,
<add> style={'input_type': 'password', 'placeholder': 'Password'}
<add> )
<add> remember_me = serializers.BooleanField()
<add>
<add>---
<add>
<add>#### `rest_framework/vertical`
<add>
<add>Presents form labels above their corresponding control inputs, using the standard Bootstrap layout.
<add>
<add>*This is the default template pack.*
<add>
<add> {% load rest_framework %}
<add>
<add> ...
<add>
<add> <form action="{% url 'login' %}" method="post" novalidate>
<add> {% csrf_token %}
<add> {% render_form serializer template_pack='rest_framework/vertical' %}
<add> <button type="submit" class="btn btn-default">Sign in</button>
<add> </form>
<add>
<add>
<add>
<add>---
<add>
<add>#### `rest_framework/horizontal`
<add>
<add>Presents labels and controls alongside each other, using a 2/10 column split.
<add>
<add>*This is the form style used in the browsable API and admin renderers.*
<add>
<add> {% load rest_framework %}
<add>
<add> ...
<add>
<add> <form class="form-horizontal" action="{% url 'login' %}" method="post" novalidate>
<add> {% csrf_token %}
<add> {% render_form serializer %}
<add> <div class="form-group">
<add> <div class="col-sm-offset-2 col-sm-10">
<add> <button type="submit" class="btn btn-default">Sign in</button>
<add> </div>
<add> </div>
<add> </form>
<add>
<add>
<add>
<add>---
<add>
<add>#### `rest_framework/inline`
<add>
<add>A compact form style that presents all the controls inline.
<add>
<add> {% load rest_framework %}
<add>
<add> ...
<add>
<add> <form class="form-inline" action="{% url 'login' %}" method="post" novalidate>
<add> {% csrf_token %}
<add> {% render_form serializer template_pack='rest_framework/inline' %}
<add> <button type="submit" class="btn btn-default">Sign in</button>
<add> </form>
<add>
<add>
<add>
<add>## Field styles
<add>
<add>Serializer fields can have their rendering style customized by using the `style` keyword argument. This argument is a dictionary of options that control the template and layout used.
<add>
<add>The most common way to customize the field style is to use the `base_template` style keyword argument to select which template in the template pack should be use.
<add>
<add>For example, to render a `CharField` as an HTML textarea rather than the default HTML input, you would use something like this:
<add>
<add> details = serializers.CharField(
<add> max_length=1000,
<add> style={'base_template': 'textarea.html'}
<add> )
<add>
<add>If you instead want a field to be rendered using a custom template that is *not part of an included template pack*, you can instead use the `template` style option, to fully specify a template name:
<add>
<add> details = serializers.CharField(
<add> max_length=1000,
<add> style={'template': 'my-field-templates/custom-input.html'}
<add> )
<add>
<add>Field templates can also use additional style properties, depending on their type. For example, the `textarea.html` template also accepts a `rows` property that can be used to affect the sizing of the control.
<add>
<add> details = serializers.CharField(
<add> max_length=1000,
<add> style={'base_template': 'textarea.html', 'rows': 10}
<add> )
<add>
<add>The complete list of `base_template` options and their associated style options is listed below.
<add>
<add>base_template | Valid field types | Additional style options
<add>----|----|----
<add>input.html | Any string, numeric or date/time field | input_type, placeholder, hide_label
<add>textarea.html | `CharField` | rows, placeholder, hide_label
<add>select.html | `ChoiceField` or relational field types | hide_label
<add>radio.html | `ChoiceField` or relational field types | inline, hide_label
<add>select_multiple.html | `MultipleChoiceField` or relational fields with `many=True` | hide_label
<add>checkbox_multiple.html | `MultipleChoiceField` or relational fields with `many=True` | inline, hide_label
<add>checkbox.html | `BooleanField` | hide_label
<add>fieldset.html | Nested serializer | hide_label
<add>list_fieldset.html | `ListField` or nested serializer with `many=True` | hide_label
| 1
|
PHP
|
PHP
|
fix usage of data and result on some event objects
|
9e06527bee808a8fb15d60c28d27519d346d83c1
|
<ide><path>src/Datasource/RulesAwareTrait.php
<ide> public function checkRules(EntityInterface $entity, $operation = RulesChecker::C
<ide> compact('entity', 'options', 'operation')
<ide> );
<ide> if ($event->isStopped()) {
<del> return $event->result;
<add> return $event->result();
<ide> }
<ide> }
<ide>
<ide> public function checkRules(EntityInterface $entity, $operation = RulesChecker::C
<ide> );
<ide>
<ide> if ($event->isStopped()) {
<del> return $event->result;
<add> return $event->result();
<ide> }
<ide> }
<ide>
<ide><path>src/TestSuite/Constraint/EventFiredWith.php
<ide> public function matches($other)
<ide> return false;
<ide> }
<ide>
<add> /**
<add> * @var Event[] $events
<add> */
<ide> $events = $eventGroup[$other];
<ide>
<ide> if (count($events) > 1) {
<ide> public function matches($other)
<ide>
<ide> $event = $events[0];
<ide>
<del> if (array_key_exists($this->_dataKey, $event->data) === false) {
<add> if (array_key_exists($this->_dataKey, $event->data()) === false) {
<ide> return false;
<ide> }
<ide>
<ide><path>tests/TestCase/Event/EventDispatcherTraitTest.php
<ide>
<ide> namespace Cake\Test\TestCase\Event;
<ide>
<add>use Cake\Event\EventDispatcherTrait;
<ide> use Cake\Event\EventManager;
<ide> use Cake\TestSuite\TestCase;
<ide>
<ide> */
<ide> class EventDispatcherTraitTest extends TestCase
<ide> {
<add> /**
<add> * @var EventDispatcherTrait
<add> */
<add> public $subject;
<ide>
<ide> /**
<ide> * setup
<ide> public function testDispatchEvent()
<ide> $event = $this->subject->dispatchEvent('some.event', ['foo' => 'bar']);
<ide>
<ide> $this->assertInstanceOf('Cake\Event\Event', $event);
<del> $this->assertSame($this->subject, $event->subject);
<del> $this->assertEquals('some.event', $event->name);
<del> $this->assertEquals(['foo' => 'bar'], $event->data);
<add> $this->assertSame($this->subject, $event->subject());
<add> $this->assertEquals('some.event', $event->name());
<add> $this->assertEquals(['foo' => 'bar'], $event->data());
<ide> }
<ide> }
<ide><path>tests/TestCase/Event/EventManagerTest.php
<ide> public function testDispatchGlobalBeforeLocal()
<ide>
<ide> /**
<ide> * test callback
<add> *
<add> * @param Event $event
<ide> */
<del> public function onMyEvent($event)
<add> public function onMyEvent(Event $event)
<ide> {
<del> $event->data['callback'] = 'ok';
<add> $event->setData('callback', 'ok');
<ide> }
<ide>
<ide> /**
<ide> public function onMyEvent($event)
<ide> public function testDispatchLocalHandledByGlobal()
<ide> {
<ide> $callback = [$this, 'onMyEvent'];
<del> EventManager::instance()->attach($callback, 'my_event');
<add> EventManager::instance()->on('my_event', $callback);
<ide> $manager = new EventManager();
<ide> $event = new Event('my_event', $manager);
<ide> $manager->dispatch($event);
<ide> public function testDispatchLocalHandledByGlobal()
<ide> public function testDispatchWithGlobalAndLocalEvents()
<ide> {
<ide> $listener = new CustomTestEventListenerInterface();
<del> EventManager::instance()->attach($listener);
<add> EventManager::instance()->on($listener);
<ide> $listener2 = new EventTestListener();
<ide> $manager = new EventManager();
<del> $manager->attach([$listener2, 'listenerFunction'], 'fake.event');
<add> $manager->on('fake.event', [$listener2, 'listenerFunction']);
<ide>
<ide> $manager->dispatch(new Event('fake.event', $this));
<ide> $this->assertEquals(['listenerFunction'], $listener->callList);
<ide><path>tests/TestCase/ORM/Association/BelongsToManyTest.php
<ide>
<ide> use Cake\Database\Expression\QueryExpression;
<ide> use Cake\Datasource\ConnectionManager;
<add>use Cake\Event\Event;
<ide> use Cake\ORM\Association\BelongsToMany;
<ide> use Cake\ORM\Entity;
<ide> use Cake\ORM\TableRegistry;
| 5
|
Go
|
Go
|
skip some exec tests requiring same-host daemon
|
e6f88f091d59a32f7a1cd9baa18b9d792548f36d
|
<ide><path>integration-cli/docker_cli_exec_test.go
<ide> func TestLinksPingLinkedContainersOnRename(t *testing.T) {
<ide> }
<ide>
<ide> func TestRunExecDir(t *testing.T) {
<add> testRequires(t, SameHostDaemon)
<ide> cmd := exec.Command(dockerBinary, "run", "-d", "busybox", "top")
<ide> out, _, err := runCommandWithOutput(cmd)
<ide> if err != nil {
<ide> func TestRunExecDir(t *testing.T) {
<ide> }
<ide>
<ide> func TestRunMutableNetworkFiles(t *testing.T) {
<add> testRequires(t, SameHostDaemon)
<ide> defer deleteAllContainers()
<ide>
<ide> for _, fn := range []string{"resolv.conf", "hosts"} {
| 1
|
Ruby
|
Ruby
|
fix recursive requirement resolution
|
36c1c8e9b0e5919a5165ffb5eaeddb54db1238b0
|
<ide><path>Library/Homebrew/cmd/uses.rb
<ide> def uses
<ide> Dependency.prune unless includes.include?("build?")
<ide> end
<ide> end
<del> reqs = f.recursive_requirements do |dependent, req|
<add>
<add> dep_formulae = deps.map do |dep|
<add> begin
<add> dep.to_formula
<add> rescue
<add> end
<add> end.compact
<add>
<add> reqs_by_formula = ([f] + dep_formulae).flat_map do |formula|
<add> formula.requirements.map { |req| [formula, req] }
<add> end
<add>
<add> reqs_by_formula.reject! do |dependent, req|
<ide> if req.recommended?
<del> Requirement.prune if ignores.include?("recommended?") || dependent.build.without?(req)
<add> ignores.include?("recommended?") || dependent.build.without?(req)
<ide> elsif req.optional?
<del> Requirement.prune if !includes.include?("optional?") && !dependent.build.with?(req)
<add> !includes.include?("optional?") && !dependent.build.with?(req)
<ide> elsif req.build?
<del> Requirement.prune unless includes.include?("build?")
<add> !includes.include?("build?")
<ide> end
<ide> end
<add>
<add> reqs = reqs_by_formula.map(&:last)
<ide> else
<ide> deps = f.deps.reject do |dep|
<ide> ignores.any? { |ignore| dep.send(ignore) } && !includes.any? { |include| dep.send(include) }
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.