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
PHP
PHP
add missing space
41e76aed563c83a633c1187b1768e2181c213a28
<ide><path>src/Illuminate/Support/SerializableClosure.php <ide> public function getVariables() <ide> */ <ide> protected function determineCodeAndVariables() <ide> { <del> if (!$this->code) <add> if ( ! $this->code) <ide> { <ide> list($this->code, $this->variables) = unserialize($this->serialize()); <ide> }
1
PHP
PHP
remove duplicated test code
f677bfea7da6c97ff8970cf6ec4d5d5dadb43cce
<ide><path>lib/Cake/Test/Case/Utility/SetTest.php <ide> public function testEnum() { <ide> /** <ide> * testFilter method <ide> * <add> * @see Hash test cases, as Set::filter() is just a proxy. <ide> * @return void <ide> */ <ide> public function testFilter() { <ide> $result = Set::filter(array('0', false, true, 0, array('one thing', 'I can tell you', 'is you got to be', false))); <ide> $expected = array('0', 2 => true, 3 => 0, 4 => array('one thing', 'I can tell you', 'is you got to be')); <ide> $this->assertSame($expected, $result); <del> <del> $result = Set::filter(array(1, array(false))); <del> $expected = array(1); <del> $this->assertEquals($expected, $result); <del> <del> $result = Set::filter(array(1, array(false, false))); <del> $expected = array(1); <del> $this->assertEquals($expected, $result); <del> <del> $result = Set::filter(array(1, array('empty', false))); <del> $expected = array(1, array('empty')); <del> $this->assertEquals($expected, $result); <del> <del> $result = Set::filter(array(1, array('2', false, array(3, null)))); <del> $expected = array(1, array('2', 2 => array(3))); <del> $this->assertEquals($expected, $result); <del> <del> $this->assertSame(array(), Set::filter(array())); <ide> } <ide> <ide> /** <ide> * testNumericArrayCheck method <ide> * <add> * @see Hash test cases, as Set::numeric() is just a proxy. <ide> * @return void <ide> */ <ide> public function testNumericArrayCheck() { <ide> $data = array('one'); <ide> $this->assertTrue(Set::numeric(array_keys($data))); <del> <del> $data = array(1 => 'one'); <del> $this->assertFalse(Set::numeric($data)); <del> <del> $data = array('one'); <del> $this->assertFalse(Set::numeric($data)); <del> <del> $data = array('one' => 'two'); <del> $this->assertFalse(Set::numeric($data)); <del> <del> $data = array('one' => 1); <del> $this->assertTrue(Set::numeric($data)); <del> <del> $data = array(0); <del> $this->assertTrue(Set::numeric($data)); <del> <del> $data = array('one', 'two', 'three', 'four', 'five'); <del> $this->assertTrue(Set::numeric(array_keys($data))); <del> <del> $data = array(1 => 'one', 2 => 'two', 3 => 'three', 4 => 'four', 5 => 'five'); <del> $this->assertTrue(Set::numeric(array_keys($data))); <del> <del> $data = array('1' => 'one', 2 => 'two', 3 => 'three', 4 => 'four', 5 => 'five'); <del> $this->assertTrue(Set::numeric(array_keys($data))); <del> <del> $data = array('one', 2 => 'two', 3 => 'three', 4 => 'four', 'a' => 'five'); <del> $this->assertFalse(Set::numeric(array_keys($data))); <ide> } <ide> <ide> /** <ide> public function testClassicExtract() { <ide> /** <ide> * testInsert method <ide> * <add> * @see Hash tests, as Set::insert() is just a proxy. <ide> * @return void <ide> */ <ide> public function testInsert() { <ide> public function testInsert() { <ide> <ide> $result = Set::insert($a, 'files', array('name' => 'files')); <ide> $expected = array( <del> 'pages' => array('name' => 'page'), <del> 'files' => array('name' => 'files') <del> ); <del> $this->assertEquals($expected, $result); <del> <del> $a = array( <del> 'pages' => array('name' => 'page') <del> ); <del> $result = Set::insert($a, 'pages.name', array()); <del> $expected = array( <del> 'pages' => array('name' => array()), <del> ); <del> $this->assertEquals($expected, $result); <del> <del> $a = array( <del> 'pages' => array( <del> 0 => array('name' => 'main'), <del> 1 => array('name' => 'about') <del> ) <del> ); <del> <del> $result = Set::insert($a, 'pages.1.vars', array('title' => 'page title')); <del> $expected = array( <del> 'pages' => array( <del> 0 => array('name' => 'main'), <del> 1 => array('name' => 'about', 'vars' => array('title' => 'page title')) <del> ) <del> ); <del> $this->assertEquals($expected, $result); <del> } <del> <del>/** <del> * Test that insert() can insert data over a string value. <del> * <del> * @return void <del> */ <del> public function testInsertOverwriteStringValue() { <del> $data = array( <del> 'Some' => array( <del> 'string' => 'value' <del> ) <del> ); <del> $result = Set::insert($data, 'Some.string.value', array('values')); <del> $expected = array( <del> 'Some' => array( <del> 'string' => array( <del> 'value' => array( 'values') <del> ) <del> ) <add> 'pages' => array('name' => 'page'), <add> 'files' => array('name' => 'files') <ide> ); <ide> $this->assertEquals($expected, $result); <ide> } <ide> public function testInsertOverwriteStringValue() { <ide> */ <ide> public function testRemove() { <ide> $a = array( <del> 'pages' => array('name' => 'page'), <del> 'files' => array('name' => 'files') <add> 'pages' => array('name' => 'page'), <add> 'files' => array('name' => 'files') <ide> ); <ide> <ide> $result = Set::remove($a, 'files'); <ide> $expected = array( <ide> 'pages' => array('name' => 'page') <ide> ); <ide> $this->assertEquals($expected, $result); <del> <del> $a = array( <del> 'pages' => array( <del> 0 => array('name' => 'main'), <del> 1 => array('name' => 'about', 'vars' => array('title' => 'page title')) <del> ) <del> ); <del> <del> $result = Set::remove($a, 'pages.1.vars'); <del> $expected = array( <del> 'pages' => array( <del> 0 => array('name' => 'main'), <del> 1 => array('name' => 'about') <del> ) <del> ); <del> $this->assertEquals($expected, $result); <del> <del> $result = Set::remove($a, 'pages.2.vars'); <del> $expected = $a; <del> $this->assertEquals($expected, $result); <ide> } <ide> <ide> /** <ide> public function testFlatten() { <ide> $data[9] = 'Shemp'; <ide> $result = Set::flatten($data); <ide> $this->assertEquals($data, $result); <del> <del> $data = array( <del> array( <del> 'Post' => array('id' => '1', 'author_id' => '1', 'title' => 'First Post'), <del> 'Author' => array('id' => '1', 'user' => 'nate', 'password' => 'foo'), <del> ), <del> array( <del> 'Post' => array('id' => '2', 'author_id' => '3', 'title' => 'Second Post', 'body' => 'Second Post Body'), <del> 'Author' => array('id' => '3', 'user' => 'larry', 'password' => null), <del> ) <del> ); <del> <del> $result = Set::flatten($data); <del> $expected = array( <del> '0.Post.id' => '1', '0.Post.author_id' => '1', '0.Post.title' => 'First Post', '0.Author.id' => '1', <del> '0.Author.user' => 'nate', '0.Author.password' => 'foo', '1.Post.id' => '2', '1.Post.author_id' => '3', <del> '1.Post.title' => 'Second Post', '1.Post.body' => 'Second Post Body', '1.Author.id' => '3', <del> '1.Author.user' => 'larry', '1.Author.password' => null <del> ); <del> $this->assertEquals($expected, $result); <ide> } <ide> <ide> /** <ide> public function testExpand() { <ide> $flat = Set::flatten($data); <ide> $result = Set::expand($flat); <ide> $this->assertEqual($data, $result); <del> <del> $data = array( <del> '0.Post.id' => '1', '0.Post.author_id' => '1', '0.Post.title' => 'First Post', '0.Author.id' => '1', <del> '0.Author.user' => 'nate', '0.Author.password' => 'foo', '1.Post.id' => '2', '1.Post.author_id' => '3', <del> '1.Post.title' => 'Second Post', '1.Post.body' => 'Second Post Body', '1.Author.id' => '3', <del> '1.Author.user' => 'larry', '1.Author.password' => null <del> ); <del> $result = Set::expand($data); <del> $expected = array( <del> array( <del> 'Post' => array('id' => '1', 'author_id' => '1', 'title' => 'First Post'), <del> 'Author' => array('id' => '1', 'user' => 'nate', 'password' => 'foo'), <del> ), <del> array( <del> 'Post' => array('id' => '2', 'author_id' => '3', 'title' => 'Second Post', 'body' => 'Second Post Body'), <del> 'Author' => array('id' => '3', 'user' => 'larry', 'password' => null), <del> ) <del> ); <del> $this->assertEqual($result, $expected); <del> <del> $data = array( <del> '0/Post/id' => 1, <del> '0/Post/name' => 'test post' <del> ); <del> $result = Set::expand($data, '/'); <del> $expected = array( <del> array( <del> 'Post' => array( <del> 'id' => 1, <del> 'name' => 'test post' <del> ) <del> ) <del> ); <del> $this->assertEqual($result, $expected); <ide> } <ide> <ide> /**
1
Ruby
Ruby
fix rubocop warnings
9b5c45a7df6a9a170389d6045bf06803fe4bc78b
<ide><path>Library/Homebrew/dev-cmd/bottle.rb <ide> require "erb" <ide> require "extend/pathname" <ide> <del>BOTTLE_ERB = <<-EOS <add>BOTTLE_ERB = <<-EOS.freeze <ide> bottle do <ide> <% if !root_url.start_with?(BottleSpecification::DEFAULT_DOMAIN) %> <ide> root_url "<%= root_url %>" <ide> def print_filename(string, filename) <ide> end <ide> end <ide> <del> if ARGV.verbose? && !text_matches.empty? <del> print_filename string, file <del> text_matches.first(MAXIMUM_STRING_MATCHES).each do |match, offset| <del> puts " #{Tty.gray}-->#{Tty.reset} match '#{match}' at offset #{Tty.em}0x#{offset}#{Tty.reset}" <del> end <add> next unless ARGV.verbose? && !text_matches.empty? <add> print_filename string, file <add> text_matches.first(MAXIMUM_STRING_MATCHES).each do |match, offset| <add> puts " #{Tty.gray}-->#{Tty.reset} match '#{match}' at offset #{Tty.em}0x#{offset}#{Tty.reset}" <add> end <ide> <del> if text_matches.size > MAXIMUM_STRING_MATCHES <del> puts "Only the first #{MAXIMUM_STRING_MATCHES} matches were output" <del> end <add> if text_matches.size > MAXIMUM_STRING_MATCHES <add> puts "Only the first #{MAXIMUM_STRING_MATCHES} matches were output" <ide> end <ide> end <ide> <ide> def print_filename(string, filename) <ide> def keg_contain_absolute_symlink_starting_with?(string, keg) <ide> absolute_symlinks_start_with_string = [] <ide> keg.find do |pn| <del> if pn.symlink? && (link = pn.readlink).absolute? <del> if link.to_s.start_with?(string) <del> absolute_symlinks_start_with_string << pn <del> end <add> next unless pn.symlink? && (link = pn.readlink).absolute? <add> if link.to_s.start_with?(string) <add> absolute_symlinks_start_with_string << pn <ide> end <ide> end <ide> <ide> def bottle_formula(f) <ide> return <ide> end <ide> <del> unless Utils::Bottles::built_as? f <add> unless Utils::Bottles.built_as? f <ide> return ofail "Formula not installed with '--build-bottle': #{f.full_name}" <ide> end <ide> <ide> def bottle_formula(f) <ide> bottle.sha256 sha256 => Utils::Bottles.tag <ide> <ide> old_spec = f.bottle_specification <add> p root_url <add> p old_spec.root_url(root_url) <add> p bottle.root_url(root_url) <ide> if ARGV.include?("--keep-old") && !old_spec.checksums.empty? <ide> mismatches = [:root_url, :prefix, :cellar, :rebuild].select do |key| <ide> old_spec.send(key) != bottle.send(key) <ide> def bottle_formula(f) <ide> "filename" => filename.to_s, <ide> "sha256" => sha256, <ide> }, <del> } <add> }, <ide> }, <ide> "bintray" => { <ide> "package" => Utils::Bottles::Bintray.package(f.name), <ide> def merge <ide> output = bottle_output bottle <ide> <ide> if write <del> path = Pathname.new("#{HOMEBREW_REPOSITORY/bottle_hash["formula"]["path"]}") <add> path = Pathname.new((HOMEBREW_REPOSITORY/bottle_hash["formula"]["path"]).to_s) <ide> update_or_add = nil <ide> <ide> Utils::Inreplace.inreplace(path) do |s| <ide> def merge <ide> old_value = old_value_original.to_s.delete ":'\"" <ide> tag = tag.to_s.delete ":" <ide> <del> if !tag.empty? <add> unless tag.empty? <ide> if !bottle_hash["bottle"]["tags"][tag].to_s.empty? <ide> mismatches << "#{key} => #{tag}" <ide> else <ide> def merge <ide> value_original = bottle_hash["bottle"][key] <ide> value = value_original.to_s <ide> next if key == "cellar" && old_value == "any" && value == "any_skip_relocation" <del> if old_value.empty? || value != old_value <del> old_value = old_value_original.inspect <del> value = value_original.inspect <del> mismatches << "#{key}: old: #{old_value}, new: #{value}" <del> end <add> next unless old_value.empty? || value != old_value <add> old_value = old_value_original.inspect <add> value = value_original.inspect <add> mismatches << "#{key}: old: #{old_value}, new: #{value}" <ide> end <ide> <ide> unless mismatches.empty? <ide> def merge <ide> rebuild\ \d+ # rebuild with a number <ide> )\n+ # multiple empty lines <ide> )+ <del> /mx, '\0' + output + "\n") <add> /mx, '\0' + output + "\n" <add> ) <ide> end <ide> odie "Bottle block addition failed!" unless string <ide> end
1
Python
Python
fix issue #265
a556e998b7303fe57d98f7c898f8c9252860bfa1
<ide><path>glances/glances.py <ide> def displayHelp(self, core): <ide> <ide> # display the limits table <ide> limits_table_x = self.help_x <del> limits_table_y = self.help_y + 2 <add> limits_table_y = self.help_y + 1 <ide> self.term_window.addnstr(limits_table_y, limits_table_x + 18, <ide> format(_("OK"), '^8'), 8, <ide> self.default_color) <ide> def displayHelp(self, core): <ide> <ide> width = 8 <ide> limits_table_x = self.help_x + 2 <del> limits_table_y = self.help_y + 3 <add> limits_table_y = self.help_y + 2 <ide> for label in stat_labels: <ide> self.term_window.addnstr(limits_table_y, limits_table_x, <ide> format(label, '<14'), 14) <ide> def displayHelp(self, core): <ide> limits.getProcessCritical(stat='MEM')]] <ide> <ide> limits_table_x = self.help_x + 15 <del> limits_table_y = self.help_y + 3 <add> limits_table_y = self.help_y + 2 <ide> for value in limit_values: <ide> self.term_window.addnstr( <ide> limits_table_y, limits_table_x,
1
Javascript
Javascript
move options to assetmodulesplugin
a04f7bcafd83f6f3b17a673717361fed7db3422f
<ide><path>lib/asset/AssetGenerator.js <ide> const RuntimeGlobals = require("../RuntimeGlobals"); <ide> /** @typedef {import("../NormalModule")} NormalModule */ <ide> /** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ <ide> <del>/** <del> * @type {Map<string|Buffer, string|null>} <del> */ <del>const dataUrlFnCache = new Map(); <del> <ide> /** <ide> * @param {NormalModule} module the module <ide> * @param {AssetModulesPluginOptions} options the options to encode <ide> const shouldEmitAsset = (module, options) => { <ide> return originalSource.size() > options.dataUrl.maxSize; <ide> }; <ide> <del>/** <del> * @param {AssetModulesPluginOptions} options the options to the encoder <del> * @returns {AssetModulesPluginOptions} normalized options <del> */ <del>const prepareOptions = (options = {}) => { <del> const dataUrl = options.dataUrl || {}; <del> <del> if (options.dataUrl === false) { <del> return { <del> dataUrl: false <del> }; <del> } <del> <del> if (typeof dataUrl === "function") { <del> return { <del> dataUrl: (source, resourcePath) => { <del> if (dataUrlFnCache.has(source)) { <del> return dataUrlFnCache.get(source); <del> } <del> <del> const encoded = dataUrl.call(null, source, resourcePath); <del> dataUrlFnCache.set(source, encoded); <del> <del> return encoded; <del> } <del> }; <del> } <del> <del> return { <del> dataUrl: { <del> encoding: "base64", <del> maxSize: 8192, <del> ...dataUrl <del> } <del> }; <del>}; <del> <ide> const JS_TYPES = new Set(["javascript"]); <ide> const JS_AND_ASSET_TYPES = new Set(["javascript", "asset"]); <ide> <ide> class AssetGenerator extends Generator { <ide> constructor(compilation, options) { <ide> super(); <ide> this.compilation = compilation; <del> this.options = prepareOptions(options); <add> this.options = options; <ide> } <ide> <ide> /** <ide><path>lib/asset/AssetModulesPlugin.js <ide> const AssetGenerator = require("./AssetGenerator"); <ide> const AssetParser = require("./AssetParser"); <ide> <ide> /** @typedef {import("webpack-sources").Source} Source */ <add>/** @typedef {import("../../declarations/plugins/AssetModulesPlugin").AssetModulesPluginOptions} AssetModulesPluginOptions */ <ide> /** @typedef {import("../Chunk")} Chunk */ <ide> /** @typedef {import("../Compiler")} Compiler */ <ide> /** @typedef {import("../Module")} Module */ <ide> <ide> const type = "asset"; <ide> const plugin = "AssetModulesPlugin"; <ide> <add>/** <add> * @type {Map<string|Buffer, string|null>} <add> */ <add>const dataUrlFnCache = new Map(); <add> <add>/** <add> * @param {AssetModulesPluginOptions} options the options to the encoder <add> * @returns {AssetModulesPluginOptions} normalized options <add> */ <add>const prepareOptions = (options = {}) => { <add> const dataUrl = options.dataUrl || {}; <add> <add> if (options.dataUrl === false) { <add> return { <add> dataUrl: false <add> }; <add> } <add> <add> if (typeof dataUrl === "function") { <add> return { <add> dataUrl: (source, resourcePath) => { <add> if (dataUrlFnCache.has(source)) { <add> return dataUrlFnCache.get(source); <add> } <add> <add> const encoded = dataUrl.call(null, source, resourcePath); <add> dataUrlFnCache.set(source, encoded); <add> <add> return encoded; <add> } <add> }; <add> } <add> <add> return { <add> dataUrl: { <add> encoding: "base64", <add> maxSize: 8192, <add> ...dataUrl <add> } <add> }; <add>}; <add> <ide> class AssetModulesPlugin { <ide> /** <ide> * @param {Compiler} compiler webpack compiler <ide> class AssetModulesPlugin { <ide> name: "Asset Modules Plugin" <ide> }); <ide> <del> return new AssetGenerator(compilation, generatorOptions); <add> return new AssetGenerator( <add> compilation, <add> prepareOptions(generatorOptions) <add> ); <ide> }); <ide> <ide> compilation.hooks.renderManifest.tap(plugin, (result, options) => {
2
PHP
PHP
apply fixes from styleci
8b289e9dd00ae34394f76e3615ecd8a30d7be8dd
<ide><path>src/Illuminate/Database/Migrations/Migrator.php <ide> protected function getMigrationsForRollback(array $options) <ide> if (($steps = $options['step'] ?? 0) > 0) { <ide> return $this->repository->getMigrations($steps); <ide> } <del> <add> <ide> return $this->repository->getLast(); <ide> } <ide>
1
Text
Text
add the text line 27
c58af731f3c9e5cb53f0f54f8cc69446985f296a
<ide><path>guide/english/vim/vim-plug/index.md <ide> Some useful plugins to get you started are : <ide> - <a href='https://github.com/sheerun/vim-polyglot' target='_blank' rel='nofollow'>vim-polygot</a> - A solid language pack for Vim. <ide> - <a href='https://github.com/jiangmiao/auto-pairs' target='_blank' rel='nofollow'>Auto Pairs</a> - Insert or delete brackets, parens, quotes in pair. <ide> - <a href='https://github.com/tpope/vim-fugitive' target='_blank' rel='nofollow'>fugitive.vim</a> - A git wrapper for Vim. <add>- <a href='https://github.com/Townk/vim-autoclose' target='_blank' rel='nofollow'>vim-autoclose</a> - vim automatically completes parentheses <ide> <ide> You may add more plugins to your Vim installation. <ide>
1
Javascript
Javascript
change how non-objects are handled
1f0e77c9de3294c89c99da90ae32f793ed30a573
<ide><path>lib/compareLocations.js <ide> * @returns {-1|0|1} sorting comparator value <ide> */ <ide> module.exports = (a, b) => { <del> if (typeof a !== "object" || a === null) { <del> return undefined; <del> } <del> if (typeof b !== "object" || b === null) { <add> let isObjectA = typeof a === "object" && a !== null; <add> let isObjectB = typeof b === "object" && b !== null; <add> if (!isObjectA || !isObjectB) { <add> if (isObjectA) return 1; <add> if (isObjectB) return -1; <ide> return 0; <ide> } <ide> if ("start" in a && "start" in b) { <ide><path>test/compareLocations.unittest.js <ide> describe("compareLocations", () => { <ide> }); <ide> <ide> describe("unknown location type comparison", () => { <del> it("returns 0 when the first parameter is an object and the second parameter is not", () => { <del> expect(compareLocations(createLocation(), 123)).toBe(0); <del> expect(compareLocations(createLocation(), "alpha")).toBe(0); <add> it("returns 1 when the first parameter is an object and the second parameter is not", () => { <add> expect(compareLocations(createLocation(), 123)).toBe(1); <add> expect(compareLocations(createLocation(), "alpha")).toBe(1); <ide> }); <ide> <del> it("returns undefined when the first parameter is a number and the second parameter is an object", () => { <del> expect(compareLocations(123, createLocation())).toBe(undefined); <add> it("returns -1 when the first parameter is not an object and the second parameter is", () => { <add> expect(compareLocations(123, createLocation())).toBe(-1); <add> expect(compareLocations("alpha", createLocation())).toBe(-1); <ide> }); <ide> <del> it("returns undefined when the first parameter is a string and the second parameter is a number", () => { <del> expect(compareLocations("alpha", 123)).toBe(undefined); <del> }); <del> <del> it("returns undefined when the first parameter is a number and the second parameter is a string", () => { <del> expect(compareLocations(123, "alpha")).toBe(undefined); <del> }); <del> <del> it("returns undefined when both the first parameter and the second parameter is a number", () => { <del> expect(compareLocations(123, 456)).toBe(undefined); <add> it("returns 0 when both the first parameter and the second parameter is an object", () => { <add> expect(compareLocations(123, 456)).toBe(0); <ide> }); <ide> }); <ide> });
2
Javascript
Javascript
add title field to challenges
fa566e47624f195dc61b44d5311c30971cc0f163
<ide><path>index.js <ide> var fs = require('fs'), <ide> nonprofits = require('./nonprofits.json'), <ide> jobs = require('./jobs.json'); <ide> <add>var challangesRegex = /^(bonfire:|waypoint:|zipline:|basejump:|hikes:)/i; <add> <ide> function getFilesFor(dir) { <ide> return fs.readdirSync(path.join(__dirname, '/' + dir)); <ide> } <ide> Challenge.destroyAll(function(err, info) { <ide> console.log('Deleted ', info); <ide> } <ide> challenges.forEach(function(file) { <add> var challenges = require('./challenges/' + file).challenges <add> .map(function(challenge) { <add> // NOTE(berks): add title for displaying in views <add> challenge.title = challenge.name.replace(challangesRegex, '').trim(); <add> return challenge; <add> }); <add> <ide> Challenge.create( <del> require('./challenges/' + file).challenges, <add> challenges, <ide> function(err) { <ide> if (err) { <ide> console.log(err);
1
Python
Python
fix typo in decorator test
1fdde76d68407b0bad17fa98f2aee4919b46c2cc
<ide><path>tests/decorators/test_python.py <ide> def do_run(): <ide> assert ret.operator.owner == 'airflow' <ide> <ide> @task_decorator <del> def test_apply_default_raise(unknow): <del> return unknow <add> def test_apply_default_raise(unknown): <add> return unknown <ide> <ide> with pytest.raises(TypeError): <ide> with self.dag:
1
Javascript
Javascript
add missing decorate docs
cae9ad4ba9c31dfa9e1aa2acc945dfc8242d1c72
<ide><path>src/Injector.js <ide> function inferInjectionArgs(fn) { <ide> */ <ide> <ide> <add>/** <add> * @ngdoc method <add> * @name angular.module.AUTO.$provide#decorator <add> * @methodOf angular.module.AUTO.$provide <add> * @description <add> * <add> * Decoration of service, allows the decorator to intercept the service instance creation. The <add> * returned instance may be the original instance, or a new instance which delegates to the <add> * original instance. <add> * <add> * @param {string} name The name of the service to decorate. <add> * @param {function()} decorator This function will be invoked when the service needs to be <add> * instanciated. The function is called using the {@link angular.module.AUTO.$injector#invoke <add> * injector.invoke} method and is therefore fully injectable. Local injection arguments: <add> * <add> * * `$delegate` - The original service instance, which can be monkey patched, configured, <add> * decorated or delegated to. <add> */ <add> <add> <ide> function createInjector(modulesToLoad) { <ide> var providerSuffix = 'Provider', <ide> path = [],
1
Ruby
Ruby
ask the request object for the session
9f23ee0fdcdc1337e4b489e51053ee1e6037215b
<ide><path>actionpack/lib/action_dispatch/middleware/flash.rb <ide> def call(env) <ide> req = ActionDispatch::Request.new env <ide> @app.call(env) <ide> ensure <del> session = Request::Session.find(req) || {} <add> session = req.session || {} <ide> flash_hash = req.flash_hash <ide> <ide> if flash_hash && (flash_hash.present? || session.key?('flash'))
1
Ruby
Ruby
add replica? check to databaseconfig
8737dffce73a37dff073dfe0af8931efd08632c5
<ide><path>activerecord/lib/active_record/database_configurations/database_config.rb <ide> def initialize(env_name, spec_name) <ide> @spec_name = spec_name <ide> end <ide> <add> def replica? <add> raise NotImplementedError <add> end <add> <ide> def url_config? <ide> false <ide> end <ide><path>activerecord/lib/active_record/database_configurations/hash_config.rb <ide> def initialize(env_name, spec_name, config) <ide> super(env_name, spec_name) <ide> @config = config <ide> end <add> <add> def replica? <add> config["replica"] <add> end <ide> end <ide> end <ide> end <ide><path>activerecord/lib/active_record/database_configurations/url_config.rb <ide> def url_config? # :nodoc: <ide> true <ide> end <ide> <add> def replica? <add> config["replica"] <add> end <add> <ide> private <ide> def build_config(original_config, url) <ide> if /^jdbc:/.match?(url)
3
Text
Text
improve active record changelog [ci skip]
eed9f15ba87d4d4c9be48119e55e8ff17102c4a7
<ide><path>activerecord/CHANGELOG.md <del>* Raise error when non-existent enum used in query <del> <del> This change will raise an error when a non-existent enum is passed to a query. Previously <del> with MySQL this would return an unrelated record. Fixes #38687. <add>* Raise error when non-existent enum used in query. <add> <add> This change will raise an error when a non-existent enum is passed to a query. <add> Previously with MySQL this would return an unrelated record. Fixes #38687. <add> <ide> ```ruby <ide> class User < ActiveRecord::Base <ide> enum status: { active: 0, non_active: 1 } <ide> end <add> <ide> User.where(status: :non_existing_status) <ide> => ArgumentError ('non_existing_status' is not a valid status) <ide> ``` <del> *Atul Kanswal * <ide> <del>* Dump the schema or structure of a database when calling db:migrate:name <add> *Atul Kanswal* <add> <add>* Dump the schema or structure of a database when calling `db:migrate:name`. <ide> <ide> In previous versions of Rails, `rails db:migrate` would dump the schema of the database. In Rails 6, that holds true (`rails db:migrate` dumps all databases' schemas), but `rails db:migrate:name` does not share that behavior. <ide> <ide> Going forward, calls to `rails db:migrate:name` will dump the schema (or structure) of the database being migrated. <ide> <ide> *Kyle Thompson* <ide> <del>* Reset the `ActiveRecord::Base` connection after `rails db:migrate:name` <add>* Reset the `ActiveRecord::Base` connection after `rails db:migrate:name`. <ide> <ide> When `rails db:migrate` has finished, it ensures the `ActiveRecord::Base` connection is reset to its original configuration. Going forward, `rails db:migrate:name` will have the same behavior. <ide>
1
Text
Text
replace function with arrow function
53d87b370b14ae6ff7a6daca360bef8680e07d88
<ide><path>doc/api/util.md <ide> but may return a value of any type that will be formatted accordingly by <ide> const util = require('util'); <ide> <ide> const obj = { foo: 'this will not show up in the inspect() output' }; <del>obj[util.inspect.custom] = function(depth) { <add>obj[util.inspect.custom] = (depth) => { <ide> return { bar: 'baz' }; <ide> }; <ide> <ide> function doSomething(foo, callback) { <ide> // ... <ide> } <ide> <del>doSomething[util.promisify.custom] = function(foo) { <add>doSomething[util.promisify.custom] = (foo) => { <ide> return getPromiseSomehow(); <ide> }; <ide> <ide> standard format of taking an error-first callback as the last argument. <ide> For example, with a function that takes in `(foo, onSuccessCallback, onErrorCallback)`: <ide> <ide> ```js <del>doSomething[util.promisify.custom] = function(foo) { <del> return new Promise(function(resolve, reject) { <add>doSomething[util.promisify.custom] = (foo) => { <add> return new Promise((resolve, reject) => { <ide> doSomething(foo, resolve, reject); <ide> }); <ide> };
1
Ruby
Ruby
add methods for manipulating the opt record
d792b6465524dbcefa7876e2fb63c8e7b6074aa8
<ide><path>Library/Homebrew/keg.rb <ide> def remove_linked_keg_record <ide> linked_keg_record.parent.rmdir_if_possible <ide> end <ide> <add> def optlinked? <add> opt_record.symlink? && path == opt_record.resolved_path <add> end <add> <add> def remove_opt_record <add> opt_record.unlink <add> opt_record.parent.rmdir_if_possible <add> end <add> <ide> def uninstall <ide> path.rmtree <ide> path.parent.rmdir_if_possible <del> <del> if opt_record.symlink? && path == opt_record.resolved_path <del> opt_record.unlink <del> opt_record.parent.rmdir_if_possible <del> end <add> remove_opt_record if optlinked? <ide> end <ide> <ide> def unlink
1
Go
Go
add fallback to resolvesystemaddr() in linux
c0b24c600e30656144522f85b053f015525022da
<ide><path>daemon/cluster/listen_addr.go <ide> func resolveInterfaceAddr(specifiedInterface string) (net.IP, error) { <ide> return interfaceAddr6, nil <ide> } <ide> <add>func (c *Cluster) resolveSystemAddrViaSubnetCheck() (net.IP, error) { <add> // Use the system's only IP address, or fail if there are <add> // multiple addresses to choose from. Skip interfaces which <add> // are managed by docker via subnet check. <add> interfaces, err := net.Interfaces() <add> if err != nil { <add> return nil, err <add> } <add> <add> var systemAddr net.IP <add> var systemInterface string <add> <add> // List Docker-managed subnets <add> v4Subnets := c.config.NetworkSubnetsProvider.V4Subnets() <add> v6Subnets := c.config.NetworkSubnetsProvider.V6Subnets() <add> <add>ifaceLoop: <add> for _, intf := range interfaces { <add> // Skip inactive interfaces and loopback interfaces <add> if (intf.Flags&net.FlagUp == 0) || (intf.Flags&net.FlagLoopback) != 0 { <add> continue <add> } <add> <add> addrs, err := intf.Addrs() <add> if err != nil { <add> continue <add> } <add> <add> var interfaceAddr4, interfaceAddr6 net.IP <add> <add> for _, addr := range addrs { <add> ipAddr, ok := addr.(*net.IPNet) <add> <add> // Skip loopback and link-local addresses <add> if !ok || !ipAddr.IP.IsGlobalUnicast() { <add> continue <add> } <add> <add> if ipAddr.IP.To4() != nil { <add> // IPv4 <add> <add> // Ignore addresses in subnets that are managed by Docker. <add> for _, subnet := range v4Subnets { <add> if subnet.Contains(ipAddr.IP) { <add> continue ifaceLoop <add> } <add> } <add> <add> if interfaceAddr4 != nil { <add> return nil, errMultipleIPs(intf.Name, intf.Name, interfaceAddr4, ipAddr.IP) <add> } <add> <add> interfaceAddr4 = ipAddr.IP <add> } else { <add> // IPv6 <add> <add> // Ignore addresses in subnets that are managed by Docker. <add> for _, subnet := range v6Subnets { <add> if subnet.Contains(ipAddr.IP) { <add> continue ifaceLoop <add> } <add> } <add> <add> if interfaceAddr6 != nil { <add> return nil, errMultipleIPs(intf.Name, intf.Name, interfaceAddr6, ipAddr.IP) <add> } <add> <add> interfaceAddr6 = ipAddr.IP <add> } <add> } <add> <add> // In the case that this interface has exactly one IPv4 address <add> // and exactly one IPv6 address, favor IPv4 over IPv6. <add> if interfaceAddr4 != nil { <add> if systemAddr != nil { <add> return nil, errMultipleIPs(systemInterface, intf.Name, systemAddr, interfaceAddr4) <add> } <add> systemAddr = interfaceAddr4 <add> systemInterface = intf.Name <add> } else if interfaceAddr6 != nil { <add> if systemAddr != nil { <add> return nil, errMultipleIPs(systemInterface, intf.Name, systemAddr, interfaceAddr6) <add> } <add> systemAddr = interfaceAddr6 <add> systemInterface = intf.Name <add> } <add> } <add> <add> if systemAddr == nil { <add> return nil, errNoIP <add> } <add> <add> return systemAddr, nil <add>} <add> <ide> func listSystemIPs() []net.IP { <ide> interfaces, err := net.Interfaces() <ide> if err != nil { <ide><path>daemon/cluster/listen_addr_linux.go <ide> func (c *Cluster) resolveSystemAddr() (net.IP, error) { <ide> return nil, err <ide> } <ide> <del> var systemAddr net.IP <del> var systemInterface string <add> var ( <add> systemAddr net.IP <add> systemInterface string <add> deviceFound bool <add> ) <ide> <ide> for _, intf := range interfaces { <ide> // Skip non device or inactive interfaces <ide> func (c *Cluster) resolveSystemAddr() (net.IP, error) { <ide> continue <ide> } <ide> <add> // At least one non-loopback device is found and it is administratively up <add> deviceFound = true <add> <ide> if ipAddr.To4() != nil { <ide> if interfaceAddr4 != nil { <ide> return nil, errMultipleIPs(intf.Attrs().Name, intf.Attrs().Name, interfaceAddr4, ipAddr) <ide> func (c *Cluster) resolveSystemAddr() (net.IP, error) { <ide> } <ide> <ide> if systemAddr == nil { <add> if !deviceFound { <add> // If no non-loopback device type interface is found, <add> // fall back to the regular auto-detection mechanism. <add> // This is to cover the case where docker is running <add> // inside a container (eths are in fact veths). <add> return c.resolveSystemAddrViaSubnetCheck() <add> } <ide> return nil, errNoIP <ide> } <ide> <ide><path>daemon/cluster/listen_addr_others.go <ide> package cluster <ide> import "net" <ide> <ide> func (c *Cluster) resolveSystemAddr() (net.IP, error) { <del> // Use the system's only IP address, or fail if there are <del> // multiple addresses to choose from. <del> interfaces, err := net.Interfaces() <del> if err != nil { <del> return nil, err <del> } <del> <del> var systemAddr net.IP <del> var systemInterface string <del> <del> // List Docker-managed subnets <del> v4Subnets := c.config.NetworkSubnetsProvider.V4Subnets() <del> v6Subnets := c.config.NetworkSubnetsProvider.V6Subnets() <del> <del>ifaceLoop: <del> for _, intf := range interfaces { <del> // Skip inactive interfaces and loopback interfaces <del> if (intf.Flags&net.FlagUp == 0) || (intf.Flags&net.FlagLoopback) != 0 { <del> continue <del> } <del> <del> addrs, err := intf.Addrs() <del> if err != nil { <del> continue <del> } <del> <del> var interfaceAddr4, interfaceAddr6 net.IP <del> <del> for _, addr := range addrs { <del> ipAddr, ok := addr.(*net.IPNet) <del> <del> // Skip loopback and link-local addresses <del> if !ok || !ipAddr.IP.IsGlobalUnicast() { <del> continue <del> } <del> <del> if ipAddr.IP.To4() != nil { <del> // IPv4 <del> <del> // Ignore addresses in subnets that are managed by Docker. <del> for _, subnet := range v4Subnets { <del> if subnet.Contains(ipAddr.IP) { <del> continue ifaceLoop <del> } <del> } <del> <del> if interfaceAddr4 != nil { <del> return nil, errMultipleIPs(intf.Name, intf.Name, interfaceAddr4, ipAddr.IP) <del> } <del> <del> interfaceAddr4 = ipAddr.IP <del> } else { <del> // IPv6 <del> <del> // Ignore addresses in subnets that are managed by Docker. <del> for _, subnet := range v6Subnets { <del> if subnet.Contains(ipAddr.IP) { <del> continue ifaceLoop <del> } <del> } <del> <del> if interfaceAddr6 != nil { <del> return nil, errMultipleIPs(intf.Name, intf.Name, interfaceAddr6, ipAddr.IP) <del> } <del> <del> interfaceAddr6 = ipAddr.IP <del> } <del> } <del> <del> // In the case that this interface has exactly one IPv4 address <del> // and exactly one IPv6 address, favor IPv4 over IPv6. <del> if interfaceAddr4 != nil { <del> if systemAddr != nil { <del> return nil, errMultipleIPs(systemInterface, intf.Name, systemAddr, interfaceAddr4) <del> } <del> systemAddr = interfaceAddr4 <del> systemInterface = intf.Name <del> } else if interfaceAddr6 != nil { <del> if systemAddr != nil { <del> return nil, errMultipleIPs(systemInterface, intf.Name, systemAddr, interfaceAddr6) <del> } <del> systemAddr = interfaceAddr6 <del> systemInterface = intf.Name <del> } <del> } <del> <del> if systemAddr == nil { <del> return nil, errNoIP <del> } <del> <del> return systemAddr, nil <add> return c.resolveSystemAddrViaSubnetCheck() <ide> }
3
PHP
PHP
add the actions and only options to resources()
5b40e2da456f6777340f663d8daef6abb0b325b2
<ide><path>src/Routing/RouteBuilder.php <ide> class RouteBuilder { <ide> * <ide> * @var array <ide> */ <del> protected static $_resourceMap = array( <del> array('action' => 'index', 'method' => 'GET', 'id' => false), <del> array('action' => 'view', 'method' => 'GET', 'id' => true), <del> array('action' => 'add', 'method' => 'POST', 'id' => false), <del> array('action' => 'edit', 'method' => 'PUT', 'id' => true), <del> array('action' => 'delete', 'method' => 'DELETE', 'id' => true), <del> array('action' => 'edit', 'method' => 'POST', 'id' => true) <del> ); <add> protected static $_resourceMap = [ <add> 'index' => ['action' => 'index', 'method' => 'GET', 'id' => false], <add> 'create' => ['action' => 'add', 'method' => 'POST', 'id' => false], <add> 'view' => ['action' => 'view', 'method' => 'GET', 'id' => true], <add> 'update' => ['action' => 'edit', 'method' => ['PUT', 'PATCH'], 'id' => true], <add> 'delete' => ['action' => 'delete', 'method' => 'DELETE', 'id' => true], <add> ]; <ide> <ide> /** <ide> * The extensions that should be set into the routes connected. <ide> public function params() { <ide> * <ide> * - 'id' - The regular expression fragment to use when matching IDs. By default, matches <ide> * integer values and UUIDs. <add> * - 'only' - Only connect the specific list of actions. <add> * - 'actions' - Override the method names used for connecting actions. <ide> * <ide> * @param string|array $name A controller name or array of controller names (i.e. "Posts" or "ListItems") <ide> * @param array $options Options to use when generating REST routes <ide> public function resources($name, $options = [], $callback = null) { <ide> } <ide> $options += array( <ide> 'connectOptions' => [], <del> 'id' => static::ID . '|' . static::UUID <add> 'id' => static::ID . '|' . static::UUID, <add> 'only' => ['index', 'update', 'create', 'view', 'delete'], <add> 'actions' => [], <ide> ); <add> $options['only'] = (array)$options['only']; <add> <ide> $connectOptions = $options['connectOptions']; <del> unset($options['connectOptions']); <ide> <ide> $urlName = Inflector::underscore($name); <ide> <ide> public function resources($name, $options = [], $callback = null) { <ide> $ext = $options['_ext']; <ide> } <ide> <del> foreach (static::$_resourceMap as $params) { <add> foreach (static::$_resourceMap as $method => $params) { <add> if (!in_array($method, $options['only'], true)) { <add> continue; <add> } <add> <add> $action = $params['action']; <add> if (isset($options['actions'][$method])) { <add> $action = $options['actions'][$method]; <add> } <add> <ide> $id = $params['id'] ? ':id' : ''; <ide> $url = '/' . implode('/', array_filter(array($urlName, $id))); <ide> $params = array( <ide> 'controller' => $name, <del> 'action' => $params['action'], <add> 'action' => $action, <ide> '[method]' => $params['method'], <ide> '_ext' => $ext <ide> ); <ide><path>tests/TestCase/Routing/RouteBuilderTest.php <ide> public function testResources() { <ide> $routes->resources('Articles', ['_ext' => 'json']); <ide> <ide> $all = $this->collection->routes(); <del> $this->assertCount(6, $all); <add> $this->assertCount(5, $all); <ide> <ide> $this->assertEquals('/api/articles', $all[0]->template); <ide> $this->assertEquals('json', $all[0]->defaults['_ext']); <ide> $this->assertEquals('Articles', $all[0]->defaults['controller']); <ide> } <ide> <add>/** <add> * Test the only option of RouteBuilder. <add> * <add> * @return void <add> */ <add> public function testResourcesOnlyString() { <add> $routes = new RouteBuilder($this->collection, '/'); <add> $routes->resources('Articles', ['only' => 'index']); <add> <add> $result = $this->collection->routes(); <add> $this->assertCount(1, $result); <add> $this->assertEquals('/articles', $result[0]->template); <add> } <add> <add>/** <add> * Test the only option of RouteBuilder. <add> * <add> * @return void <add> */ <add> public function testResourcesOnlyArray() { <add> $routes = new RouteBuilder($this->collection, '/'); <add> $routes->resources('Articles', ['only' => ['index', 'delete']]); <add> <add> $result = $this->collection->routes(); <add> $this->assertCount(2, $result); <add> $this->assertEquals('/articles', $result[0]->template); <add> $this->assertEquals('index', $result[0]->defaults['action']); <add> $this->assertEquals('GET', $result[0]->defaults['[method]']); <add> <add> $this->assertEquals('/articles/:id', $result[1]->template); <add> $this->assertEquals('delete', $result[1]->defaults['action']); <add> $this->assertEquals('DELETE', $result[1]->defaults['[method]']); <add> } <add> <add>/** <add> * Test the actions option of RouteBuilder. <add> * <add> * @return void <add> */ <add> public function testResourcesActions() { <add> $routes = new RouteBuilder($this->collection, '/'); <add> $routes->resources('Articles', [ <add> 'only' => ['index', 'delete'], <add> 'actions' => ['index' => 'showList'] <add> ]); <add> <add> $result = $this->collection->routes(); <add> $this->assertCount(2, $result); <add> $this->assertEquals('/articles', $result[0]->template); <add> $this->assertEquals('showList', $result[0]->defaults['action']); <add> <add> $this->assertEquals('/articles/:id', $result[1]->template); <add> $this->assertEquals('delete', $result[1]->defaults['action']); <add> } <add> <ide> /** <ide> * Test nesting resources <ide> *
2
Python
Python
use modern exception syntax
705bf928e1256a06019c75ee945370fbe89cdde7
<ide><path>numpy/_import_tools.py <ide> def _init_info_modules(self, packages=None): <ide> try: <ide> exec 'import %s.info as info' % (package_name) <ide> info_modules[package_name] = info <del> except ImportError, msg: <add> except ImportError as msg: <ide> self.warn('No scipy-style subpackage %r found in %s. '\ <ide> 'Ignoring: %s'\ <ide> % (package_name,':'.join(self.parent_path), msg)) <ide> def _init_info_modules(self, packages=None): <ide> open(info_file,filedescriptor[1]), <ide> info_file, <ide> filedescriptor) <del> except Exception,msg: <add> except Exception as msg: <ide> self.error(msg) <ide> info_module = None <ide> <ide> def _execcmd(self,cmdstr): <ide> frame = self.parent_frame <ide> try: <ide> exec (cmdstr, frame.f_globals,frame.f_locals) <del> except Exception,msg: <add> except Exception as msg: <ide> self.error('%s -> failed: %s' % (cmdstr,msg)) <ide> return True <ide> else: <ide><path>numpy/build_utils/waf.py <ide> def do_binary_search(conf, type_name, kw): <ide> <ide> try: <ide> conf.run_c_code(**kw) <del> except conf.errors.ConfigurationError, e: <add> except conf.errors.ConfigurationError as e: <ide> conf.end_msg("failed !") <ide> if waflib.Logs.verbose > 1: <ide> raise <ide><path>numpy/core/tests/test_half.py <ide> def assert_raises_fpe(strmatch, callable, *args, **kwargs): <ide> try: <ide> callable(*args, **kwargs) <del> except FloatingPointError, exc: <add> except FloatingPointError as exc: <ide> assert_(str(exc).find(strmatch) >= 0, <ide> "Did not raise floating point %s error" % strmatch) <ide> else: <ide><path>numpy/core/tests/test_machar.py <ide> def test_underlow(self): <ide> try: <ide> try: <ide> self._run_machar_highprec() <del> except FloatingPointError, e: <add> except FloatingPointError as e: <ide> self.fail("Caught %s exception, should not have been raised." % e) <ide> finally: <ide> seterr(**serrstate) <ide><path>numpy/core/tests/test_nditer.py <ide> def test_iter_broadcasting_errors(): <ide> [], <ide> [['readonly'], ['readonly'], ['writeonly','no_broadcast']]) <ide> assert_(False, 'Should have raised a broadcast error') <del> except ValueError, e: <add> except ValueError as e: <ide> msg = str(e) <ide> # The message should contain the shape of the 3rd operand <ide> assert_(msg.find('(2,3)') >= 0, <ide> def test_iter_broadcasting_errors(): <ide> op_axes=[[0,1], [0,np.newaxis]], <ide> itershape=(4,3)) <ide> assert_(False, 'Should have raised a broadcast error') <del> except ValueError, e: <add> except ValueError as e: <ide> msg = str(e) <ide> # The message should contain "shape->remappedshape" for each operand <ide> assert_(msg.find('(2,3)->(2,3)') >= 0, <ide> def test_iter_broadcasting_errors(): <ide> [], <ide> [['writeonly','no_broadcast'], ['readonly']]) <ide> assert_(False, 'Should have raised a broadcast error') <del> except ValueError, e: <add> except ValueError as e: <ide> msg = str(e) <ide> # The message should contain the shape of the bad operand <ide> assert_(msg.find('(2,1,1)') >= 0, <ide><path>numpy/core/tests/test_numeric.py <ide> def assert_raises_fpe(self, fpeerr, flop, x, y): <ide> flop(x, y) <ide> assert_(False, <ide> "Type %s did not raise fpe error '%s'." % (ftype, fpeerr)) <del> except FloatingPointError, exc: <add> except FloatingPointError as exc: <ide> assert_(str(exc).find(fpeerr) >= 0, <ide> "Type %s raised wrong fpe error '%s'." % (ftype, exc)) <ide> <ide><path>numpy/core/tests/test_print.py <ide> def test_scalar_format(): <ide> try: <ide> assert_equal(fmat.format(val), fmat.format(valtype(val)), <ide> "failed with val %s, type %s" % (val, valtype)) <del> except ValueError, e: <add> except ValueError as e: <ide> assert_(False, <ide> "format raised exception (fmt='%s', val=%s, type=%s, exc='%s')" % <ide> (fmat, repr(val), repr(valtype), str(e))) <ide><path>numpy/core/tests/test_regression.py <ide> def test_zeros(self): <ide> good = 'Maximum allowed dimension exceeded' <ide> try: <ide> np.empty(sz) <del> except ValueError, e: <add> except ValueError as e: <ide> if not str(e) == good: <ide> self.fail("Got msg '%s', expected '%s'" % (e, good)) <del> except Exception, e: <add> except Exception as e: <ide> self.fail("Got exception of type %s instead of ValueError" % type(e)) <ide> <ide> def test_huge_arange(self): <ide> def test_huge_arange(self): <ide> try: <ide> a = np.arange(sz) <ide> self.assertTrue(np.size == sz) <del> except ValueError, e: <add> except ValueError as e: <ide> if not str(e) == good: <ide> self.fail("Got msg '%s', expected '%s'" % (e, good)) <del> except Exception, e: <add> except Exception as e: <ide> self.fail("Got exception of type %s instead of ValueError" % type(e)) <ide> <ide> def test_fromiter_bytes(self): <ide> def test_ticket_1539(self): <ide> c = a.astype(y) <ide> try: <ide> np.dot(b, c) <del> except TypeError, e: <add> except TypeError as e: <ide> failures.append((x, y)) <ide> if failures: <ide> raise AssertionError("Failures: %r" % failures) <ide><path>numpy/ctypeslib.py <ide> def load_library(libname, loader_path): <ide> try: <ide> libpath = os.path.join(libdir, ln) <ide> return ctypes.cdll[libpath] <del> except OSError, e: <add> except OSError as e: <ide> exc = e <ide> raise exc <ide> <ide><path>numpy/distutils/interactive.py <ide> def interactive_sys_argv(argv): <ide> import atexit <ide> atexit.register(readline.write_history_file, histfile) <ide> except AttributeError: pass <del> except Exception, msg: <add> except Exception as msg: <ide> print msg <ide> <ide> task_dict = {'i':show_information, <ide> def interactive_sys_argv(argv): <ide> print '-'*68 <ide> try: <ide> task_func(argv,readline) <del> except Exception,msg: <add> except Exception as msg: <ide> print 'Failed running task %s: %s' % (task,msg) <ide> break <ide> print '-'*68 <ide><path>numpy/distutils/system_info.py <ide> def calc_info(self): <ide> ## (self.modulename.upper()+'_VERSION_HEX', <ide> ## hex(vstr2hex(module.__version__))), <ide> ## ) <del>## except Exception,msg: <add>## except Exception as msg: <ide> ## print msg <ide> dict_append(info, define_macros=macros) <ide> include_dirs = self.get_include_dirs() <ide><path>numpy/f2py/capi_maps.py <ide> else: <ide> errmess("\tIgnoring map {'%s':{'%s':'%s'}}: '%s' must be in %s\n"%(k,k1,d[k][k1],d[k][k1],c2py_map.keys())) <ide> outmess('Succesfully applied user defined changes from .f2py_f2cmap\n') <del> except Exception, msg: <add> except Exception as msg: <ide> errmess('Failed to apply user defined changes from .f2py_f2cmap: %s. Skipping.\n' % (msg)) <ide> cformat_map={'double':'%g', <ide> 'float':'%g', <ide><path>numpy/f2py/crackfortran.py <ide> def analyzeline(m,case,line): <ide> replace(',','+1j*(') <ide> try: <ide> v = eval(initexpr,{},params) <del> except (SyntaxError,NameError,TypeError),msg: <add> except (SyntaxError,NameError,TypeError) as msg: <ide> errmess('analyzeline: Failed to evaluate %r. Ignoring: %s\n'\ <ide> % (initexpr, msg)) <ide> continue <ide> def get_parameters(vars, global_params={}): <ide> l = markoutercomma(v[1:-1]).split('@,@') <ide> try: <ide> params[n] = eval(v,g_params,params) <del> except Exception,msg: <add> except Exception as msg: <ide> params[n] = v <ide> #print params <ide> outmess('get_parameters: got "%s" on %s\n' % (msg,`v`)) <ide> def _eval_scalar(value,params): <ide> value = str(eval(value,{},params)) <ide> except (NameError, SyntaxError): <ide> return value <del> except Exception,msg: <add> except Exception as msg: <ide> errmess('"%s" in evaluating %r '\ <ide> '(available names: %s)\n' \ <ide> % (msg,value,params.keys())) <ide> def crack2fortran(block): <ide> try: <ide> open(l).close() <ide> files.append(l) <del> except IOError,detail: <add> except IOError as detail: <ide> errmess('IOError: %s\n'%str(detail)) <ide> else: <ide> funcs.append(l) <ide><path>numpy/f2py/diagnose.py <ide> def run(): <ide> try: <ide> print 'Found new numpy version %r in %s' % \ <ide> (numpy.__version__, numpy.__file__) <del> except Exception,msg: <add> except Exception as msg: <ide> print 'error:', msg <ide> print '------' <ide> <ide> if has_f2py2e: <ide> try: <ide> print 'Found f2py2e version %r in %s' % \ <ide> (f2py2e.__version__.version,f2py2e.__file__) <del> except Exception,msg: <add> except Exception as msg: <ide> print 'error:',msg <ide> print '------' <ide> <ide> def run(): <ide> numpy_distutils.numpy_distutils_version.numpy_distutils_version, <ide> numpy_distutils.__file__) <ide> print '------' <del> except Exception,msg: <add> except Exception as msg: <ide> print 'error:',msg <ide> print '------' <ide> try: <ide> def run(): <ide> for compiler_class in build_flib.all_compilers: <ide> compiler_class(verbose=1).is_available() <ide> print '------' <del> except Exception,msg: <add> except Exception as msg: <ide> print 'error:',msg <ide> print '------' <del> except Exception,msg: <add> except Exception as msg: <ide> print 'error:',msg,'(ignore it, build_flib is obsolute for numpy.distutils 0.2.2 and up)' <ide> print '------' <ide> try: <ide> def run(): <ide> print 'Checking availability of supported Fortran compilers:' <ide> fcompiler.show_fcompilers() <ide> print '------' <del> except Exception,msg: <add> except Exception as msg: <ide> print 'error:',msg <ide> print '------' <del> except Exception,msg: <add> except Exception as msg: <ide> print 'error:',msg <ide> print '------' <ide> try: <ide> def run(): <ide> from numpy_distutils.command.cpuinfo import cpuinfo <ide> print 'ok' <ide> print '------' <del> except Exception,msg: <add> except Exception as msg: <ide> print 'error:',msg,'(ignore it)' <ide> print 'Importing numpy_distutils.cpuinfo ...', <ide> from numpy_distutils.cpuinfo import cpuinfo <ide> def run(): <ide> if name[0]=='_' and name[1]!='_' and getattr(cpu,name[1:])(): <ide> print name[1:], <ide> print '------' <del> except Exception,msg: <add> except Exception as msg: <ide> print 'error:',msg <ide> print '------' <ide> os.chdir(_path) <ide><path>numpy/f2py/f2py2e.py <ide> def scaninputline(inputline): <ide> try: <ide> open(l).close() <ide> files.append(l) <del> except IOError,detail: <add> except IOError as detail: <ide> errmess('IOError: %s. Skipping file "%s".\n'%(str(detail),l)) <ide> elif f==-1: skipfuncs.append(l) <ide> elif f==0: onlyfuncs.append(l) <ide><path>numpy/f2py/tests/test_array_from_pyobj.py <ide> def test_inout_2seq(self): <ide> <ide> try: <ide> a = self.array([2],intent.in_.inout,self.num2seq) <del> except TypeError,msg: <add> except TypeError as msg: <ide> if not str(msg).startswith('failed to initialize intent(inout|inplace|cache) array'): <ide> raise <ide> else: <ide> def test_f_inout_23seq(self): <ide> shape = (len(self.num23seq),len(self.num23seq[0])) <ide> try: <ide> a = self.array(shape,intent.in_.inout,obj) <del> except ValueError,msg: <add> except ValueError as msg: <ide> if not str(msg).startswith('failed to initialize intent(inout) array'): <ide> raise <ide> else: <ide> def test_in_cache_from_2casttype(self): <ide> <ide> try: <ide> a = self.array(shape,intent.in_.cache,obj[::-1]) <del> except ValueError,msg: <add> except ValueError as msg: <ide> if not str(msg).startswith('failed to initialize intent(cache) array'): <ide> raise <ide> else: <ide> def test_in_cache_from_2casttype_failure(self): <ide> shape = (len(self.num2seq),) <ide> try: <ide> a = self.array(shape,intent.in_.cache,obj) <del> except ValueError,msg: <add> except ValueError as msg: <ide> if not str(msg).startswith('failed to initialize intent(cache) array'): <ide> raise <ide> else: <ide> def test_cache_hidden(self): <ide> shape = (-1,3) <ide> try: <ide> a = self.array(shape,intent.cache.hide,None) <del> except ValueError,msg: <add> except ValueError as msg: <ide> if not str(msg).startswith('failed to create intent(cache|hide)|optional array'): <ide> raise <ide> else: <ide> def test_hidden(self): <ide> shape = (-1,3) <ide> try: <ide> a = self.array(shape,intent.hide,None) <del> except ValueError,msg: <add> except ValueError as msg: <ide> if not str(msg).startswith('failed to create intent(cache|hide)|optional array'): <ide> raise <ide> else: <ide><path>numpy/f2py/tests/util.py <ide> def wrapper(*a, **kw): <ide> if key not in memo: <ide> try: <ide> memo[key] = func(*a, **kw) <del> except Exception, e: <add> except Exception as e: <ide> memo[key] = e <ide> raise <ide> ret = memo[key] <ide><path>numpy/lib/format.py <ide> def read_array_header_1_0(fp): <ide> # "descr" : dtype.descr <ide> try: <ide> d = safe_eval(header) <del> except SyntaxError, e: <add> except SyntaxError as e: <ide> msg = "Cannot parse header: %r\nException: %r" <ide> raise ValueError(msg % (header, e)) <ide> if not isinstance(d, dict): <ide> def read_array_header_1_0(fp): <ide> raise ValueError(msg % (d['fortran_order'],)) <ide> try: <ide> dtype = numpy.dtype(d['descr']) <del> except TypeError, e: <add> except TypeError as e: <ide> msg = "descr is not a valid dtype descriptor: %r" <ide> raise ValueError(msg % (d['descr'],)) <ide> <ide><path>numpy/lib/tests/test__datasource.py <ide> def test_InvalidHTTP(self): <ide> self.assertRaises(IOError, self.ds.open, url) <ide> try: <ide> self.ds.open(url) <del> except IOError, e: <add> except IOError as e: <ide> # Regression test for bug fixed in r4342. <ide> assert_(e.errno is None) <ide> <ide><path>numpy/lib/tests/test_io.py <ide> def writer(error_list): <ide> arr = np.random.randn(500, 500) <ide> try: <ide> np.savez(tmp, arr=arr) <del> except OSError, err: <add> except OSError as err: <ide> error_list.append(err) <ide> finally: <ide> os.remove(tmp) <ide> def test_closing_fid(self): <ide> for i in range(1, 1025): <ide> try: <ide> np.load(tmp)["data"] <del> except Exception, e: <add> except Exception as e: <ide> raise AssertionError("Failed to load data from a file: %s" % e) <ide> finally: <ide> os.remove(tmp) <ide><path>numpy/lib/utils.py <ide> def safe_eval(source): <ide> walker = SafeEval() <ide> try: <ide> ast = compiler.parse(source, mode="eval") <del> except SyntaxError, err: <add> except SyntaxError as err: <ide> raise <ide> try: <ide> return walker.visit(ast) <del> except SyntaxError, err: <add> except SyntaxError as err: <ide> raise <ide> <ide> #----------------------------------------------------------------------------- <ide><path>numpy/linalg/tests/test_linalg.py <ide> def test_empty(self): <ide> try: <ide> self.do(a, b) <ide> raise AssertionError("%s should fail with empty matrices", self.__name__[5:]) <del> except linalg.LinAlgError, e: <add> except linalg.LinAlgError as e: <ide> pass <ide> <ide> def test_nonarray(self): <ide><path>numpy/ma/core.py <ide> def get_object_signature(obj): <ide> """ <ide> try: <ide> sig = formatargspec(*getargspec(obj)) <del> except TypeError, errmsg: <add> except TypeError as errmsg: <ide> sig = '' <ide> # msg = "Unable to retrieve the signature of %s '%s'\n"\ <ide> # "(Initial error message: %s)" <ide><path>numpy/testing/numpytest.py <ide> def importall(package): <ide> name = package_name+'.'+subpackage_name <ide> try: <ide> exec 'import %s as m' % (name) <del> except Exception, msg: <add> except Exception as msg: <ide> print 'Failed importing %s: %s' %(name, msg) <ide> continue <ide> importall(m) <ide><path>numpy/testing/utils.py <ide> def chk_same_position(x_id, y_id, hasval='nan'): <ide> names=('x', 'y')) <ide> if not cond : <ide> raise AssertionError(msg) <del> except ValueError, e: <add> except ValueError as e: <ide> import traceback <ide> efmt = traceback.format_exc() <ide> header = 'error during assertion:\n\n%s\n\n%s' % (efmt, header) <ide><path>numpy/tests/test_ctypeslib.py <ide> def test_basic(self): <ide> try: <ide> cdll = load_library('multiarray', <ide> np.core.multiarray.__file__) <del> except ImportError, e: <add> except ImportError as e: <ide> msg = "ctypes is not available on this python: skipping the test" \ <ide> " (import error was: %s)" % str(e) <ide> print msg <ide> def test_basic2(self): <ide> np.core.multiarray.__file__) <ide> except ImportError: <ide> print "No distutils available, skipping test." <del> except ImportError, e: <add> except ImportError as e: <ide> msg = "ctypes is not available on this python: skipping the test" \ <ide> " (import error was: %s)" % str(e) <ide> print msg
26
Mixed
Ruby
make enum feature work with dirty methods
a57a2bcf4a2c29519d553277e4439790ca443cc7
<ide><path>activerecord/CHANGELOG.md <add>* Make enum fields work as expected with the `ActiveModel::Dirty` API. <add> <add> Before this change, using the dirty API would have surprising results: <add> <add> conversation = Conversation.new <add> conversation.status = :active <add> conversation.status = :archived <add> conversation.status_was # => 0 <add> <add> After this change, the same code would result in: <add> <add> conversation = Conversation.new <add> conversation.status = :active <add> conversation.status = :archived <add> conversation.status_was # => "active" <add> <add> *Rafael Mendonça França* <add> <ide> * Ensure `second` through `fifth` methods act like the `first` finder. <ide> <ide> The famous ordinal Array instance methods defined in ActiveSupport <ide><path>activerecord/lib/active_record/enum.rb <ide> module ActiveRecord <ide> # <ide> # Conversation.where("status <> ?", Conversation.statuses[:archived]) <ide> module Enum <add> DEFINED_ENUMS = [] # :nodoc: <add> <add> def enum_attribute?(attr_name) # :nodoc: <add> DEFINED_ENUMS.include?(attr_name.to_sym) <add> end <add> <ide> def enum(definitions) <ide> klass = self <ide> definitions.each do |name, values| <ide> # statuses = { } <ide> enum_values = ActiveSupport::HashWithIndifferentAccess.new <ide> name = name.to_sym <ide> <add> DEFINED_ENUMS.unshift name <add> <ide> # def self.statuses statuses end <ide> klass.singleton_class.send(:define_method, name.to_s.pluralize) { enum_values } <ide> <ide> def enum(definitions) <ide> private <ide> def _enum_methods_module <ide> @_enum_methods_module ||= begin <del> mod = Module.new <add> mod = Module.new do <add> def save_changed_attribute(attr_name, value) <add> if self.class.enum_attribute?(attr_name) <add> old = clone_attribute_value(:read_attribute, attr_name) <add> changed_attributes[attr_name] = self.class.public_send(attr_name.pluralize).key old <add> else <add> super <add> end <add> end <add> end <ide> include mod <ide> mod <ide> end <ide><path>activerecord/test/cases/enum_test.rb <ide> class EnumTest < ActiveRecord::TestCase <ide> assert @book.written? <ide> end <ide> <add> test "enum changed attributes" do <add> old_status = @book.status <add> @book.status = :published <add> assert_equal old_status, @book.changed_attributes[:status] <add> end <add> <add> test "enum changes" do <add> old_status = @book.status <add> @book.status = :published <add> assert_equal [old_status, 'published'], @book.changes[:status] <add> end <add> <add> test "enum attribute was" do <add> old_status = @book.status <add> @book.status = :published <add> assert_equal old_status, @book.attribute_was(:status) <add> end <add> <add> test "enum attribute changed" do <add> @book.status = :published <add> assert @book.attribute_changed?(:status) <add> end <add> <add> test "enum attribute changed to" do <add> @book.status = :published <add> assert @book.attribute_changed?(:status, to: 'published') <add> end <add> <add> test "enum attribute changed from" do <add> old_status = @book.status <add> @book.status = :published <add> assert @book.attribute_changed?(:status, from: old_status) <add> end <add> <add> test "enum attribute changed from old status to new status" do <add> old_status = @book.status <add> @book.status = :published <add> assert @book.attribute_changed?(:status, from: old_status, to: 'published') <add> end <add> <ide> test "assign non existing value raises an error" do <ide> e = assert_raises(ArgumentError) do <ide> @book.status = :unknown
3
Python
Python
switch tf to oss keras (1/n)
045f34b232830e50a7990a5ba3814d8de5b9cde3
<ide><path>research/object_detection/models/keras_models/resnet_v1.py <ide> from __future__ import division <ide> from __future__ import print_function <ide> <add>from keras.applications import resnet <add> <ide> import tensorflow.compat.v1 as tf <ide> <del>from tensorflow.python.keras.applications import resnet <ide> from object_detection.core import freezable_batch_norm <ide> from object_detection.models.keras_models import model_utils <ide>
1
PHP
PHP
clarify cookie comment
97cb0035f4935e60ccd86f881156d4a1ddd23ad9
<ide><path>laravel/cookie.php <ide> protected static function set($cookie) <ide> setcookie($name, $value, $time, $path, $domain, $secure); <ide> } <ide> } <del> <add> <ide> <ide> /** <ide> * Get the value of a cookie. <ide> public static function get($name, $default = null) <ide> if ( ! is_null($value) and isset($value[40]) and $value[40] == '~') <ide> { <ide> // The hash signature and the cookie value are separated by a tilde <del> // character for convenience. To separate the hash and the contents <add> // character for convenience. To separate the hash and the payload <ide> // we can simply expode on that character. <ide> list($hash, $value) = explode('~', $value, 2); <ide>
1
Ruby
Ruby
fix a warning about grouped expressions
881ca628b0df2db19f70830f178b0d55efc299ca
<ide><path>activesupport/test/core_ext/range_ext_test.rb <ide> def test_should_not_include_overlapping_last <ide> end <ide> <ide> def test_should_include_identical_exclusive_with_floats <del> assert (1.0...10.0).include?(1.0...10.0) <add> assert((1.0...10.0).include?(1.0...10.0)) <ide> end <ide> <ide> def test_blockless_step
1
PHP
PHP
fix return types in cachemanager
3c5fd2873f7225d884e1c88fb5877ae69ce8b644
<ide><path>src/Illuminate/Cache/CacheManager.php <ide> protected function callCustomCreator(array $config) <ide> * Create an instance of the APC cache driver. <ide> * <ide> * @param array $config <del> * @return \Illuminate\Cache\ApcStore <add> * @return \Illuminate\Cache\Repository <ide> */ <ide> protected function createApcDriver(array $config) <ide> { <ide> protected function createApcDriver(array $config) <ide> /** <ide> * Create an instance of the array cache driver. <ide> * <del> * @return \Illuminate\Cache\ArrayStore <add> * @return \Illuminate\Cache\Repository <ide> */ <ide> protected function createArrayDriver() <ide> { <ide> protected function createArrayDriver() <ide> * Create an instance of the file cache driver. <ide> * <ide> * @param array $config <del> * @return \Illuminate\Cache\FileStore <add> * @return \Illuminate\Cache\Repository <ide> */ <ide> protected function createFileDriver(array $config) <ide> { <ide> protected function createFileDriver(array $config) <ide> * Create an instance of the Memcached cache driver. <ide> * <ide> * @param array $config <del> * @return \Illuminate\Cache\MemcachedStore <add> * @return \Illuminate\Cache\Repository <ide> */ <ide> protected function createMemcachedDriver(array $config) <ide> { <ide> protected function createMemcachedDriver(array $config) <ide> /** <ide> * Create an instance of the Null cache driver. <ide> * <del> * @return \Illuminate\Cache\NullStore <add> * @return \Illuminate\Cache\Repository <ide> */ <ide> protected function createNullDriver() <ide> { <ide> protected function createNullDriver() <ide> * Create an instance of the Redis cache driver. <ide> * <ide> * @param array $config <del> * @return \Illuminate\Cache\RedisStore <add> * @return \Illuminate\Cache\Repository <ide> */ <ide> protected function createRedisDriver(array $config) <ide> { <ide> protected function createRedisDriver(array $config) <ide> * Create an instance of the database cache driver. <ide> * <ide> * @param array $config <del> * @return \Illuminate\Cache\DatabaseStore <add> * @return \Illuminate\Cache\Repository <ide> */ <ide> protected function createDatabaseDriver(array $config) <ide> { <ide> public function forgetDriver($name = null) <ide> /** <ide> * Register a custom driver creator Closure. <ide> * <del> * @param string $driver <add> * @param string $driver <ide> * @param \Closure $callback <ide> * @return $this <ide> */ <ide> public function extend($driver, Closure $callback) <ide> * Dynamically call the default driver instance. <ide> * <ide> * @param string $method <del> * @param array $parameters <add> * @param array $parameters <ide> * @return mixed <ide> */ <ide> public function __call($method, $parameters)
1
Ruby
Ruby
add missing comma
3a746723c351a582c2711b67c412e3905527776e
<ide><path>Library/Homebrew/os/mac/version.rb <ide> class Version < ::Version <ide> extend T::Sig <ide> <ide> SYMBOLS = { <del> monterey: "12" <add> monterey: "12", <ide> big_sur: "11", <ide> catalina: "10.15", <ide> mojave: "10.14",
1
Python
Python
introduce masking to simpledeeprnn
981d23a66e3921ff5a3819b9d512f47b6b4f79f0
<ide><path>keras/layers/recurrent.py <ide> class SimpleDeepRNN(Layer): <ide> def __init__(self, input_dim, output_dim, depth=3, <ide> init='glorot_uniform', inner_init='orthogonal', <ide> activation='sigmoid', inner_activation='hard_sigmoid', <del> weights=None, truncate_gradient=-1, return_sequences=False): <add> weights=None, truncate_gradient=-1, return_sequences=False, mask_val=default_mask_val): <ide> super(SimpleDeepRNN,self).__init__() <ide> self.init = initializations.get(init) <ide> self.inner_init = initializations.get(inner_init) <ide> def __init__(self, input_dim, output_dim, depth=3, <ide> self.depth = depth <ide> self.return_sequences = return_sequences <ide> self.input = T.tensor3() <add> self.mask_val = shared_scalar(mask_val) <ide> <ide> self.W = self.init((self.input_dim, self.output_dim)) <ide> self.Us = [self.inner_init((self.output_dim, self.output_dim)) for _ in range(self.depth)] <ide> def __init__(self, input_dim, output_dim, depth=3, <ide> if weights is not None: <ide> self.set_weights(weights) <ide> <del> def _step(self, *args): <del> o = args[0] <del> for i in range(1, self.depth+1): <del> o += self.inner_activation(T.dot(args[i], args[i+self.depth])) <del> return self.activation(o) <add> def _step(self, x_t, mask_t, *args): <add> o = x_t <add> for i in range(self.depth): <add> mask_tmi = args[i] <add> h_tmi = args[i + self.depth] <add> U_tmi = args[i + 2*self.depth] <add> o += mask_tmi*self.inner_activation(T.dot(h_tmi, U_tmi)) <add> result = mask_t*self.activation(o) + (1 - mask_t)*self.mask_val <add> return result <ide> <ide> def get_output(self, train): <ide> X = self.get_input(train) <ide> X = X.dimshuffle((1,0,2)) <ide> <add> mask = get_mask(X, self.mask_val, steps_back=self.depth) <add> <ide> x = T.dot(X, self.W) + self.b <ide> <add> if self.depth == 1: <add> initial = T.unbroadcast(alloc_zeros_matrix(X.shape[1], self.output_dim), 1) <add> else: <add> initial = T.unbroadcast(T.unbroadcast(alloc_zeros_matrix(self.depth, X.shape[1], self.output_dim), 0), 2) <add> <ide> outputs, updates = theano.scan( <ide> self._step, <del> sequences=x, <add> sequences=[x, dict( <add> input = mask, <add> taps = [(-i) for i in range(self.depth+1)] <add> )], <ide> outputs_info=[dict( <del> initial=T.alloc(np.cast[theano.config.floatX](0.), self.depth, X.shape[1], self.output_dim), <add> initial = initial, <ide> taps = [(-i-1) for i in range(self.depth)] <ide> )], <ide> non_sequences=self.Us, <ide><path>test/test_masked_recurrent.py <ide> from keras.models import Sequential <ide> from keras.layers.core import Dense, Activation, Merge <ide> from keras.layers.embeddings import Embedding <del>from keras.layers.recurrent import SimpleRNN <add>from keras.layers.recurrent import SimpleRNN, SimpleDeepRNN <ide> from keras.layers.core import default_mask_val <ide> import theano <ide> <ide> theano.config.exception_verbosity='high' <ide> <ide> # (nb_samples, timesteps, dimensions) <del>X = np.random.random_integers(1, 4, size=(400000,3)) <add>X = np.random.random_integers(1, 4, size=(400000,4)) <ide> <ide> model = Sequential() <ide> model.add(Embedding(5, 2, zero_is_mask=True)) <add>#model.add(SimpleRNN(2,3, activation='relu', return_sequences=True)) <add>#model.add(SimpleRNN(3,3, activation='relu')) <ide> model.add(SimpleRNN(2,3, activation='relu', return_sequences=True)) <del>model.add(SimpleRNN(3,3, activation='relu')) <add># This next one is basically just a SimpleRNN, but I'm testing that the masking is <add>model.add(SimpleDeepRNN(3,3, depth=2, activation='relu')) <ide> model.add(Dense(3,4, activation='softmax')) <ide> model.compile(loss='categorical_crossentropy', <ide> optimizer='rmsprop', theano_mode=theano.compile.mode.FAST_RUN) <ide> Xmask0 = X.copy() <ide> Xmask0[:,0] = 0 <ide> <del>Xmask1 = X.copy() <del>Xmask1[:,1] = 0 <add>Xmask12 = X.copy() <add>Xmask12[:,1] = 0 <add>Xmask12[:,2] = 0 <ide> <ide> X0_onehot = np.zeros((X.shape[0], 4)) <ide> X1_onehot = np.zeros((X.shape[0], 4)) <ide> <ide> model.set_weights(W) <ide> <del># Finally, make sure the mask is actually blocking input, mask out timestep 1, and see if <add># Finally, make sure the mask is actually blocking input, mask out timesteps 1 and 2, and see if <ide> # it can learn timestep 0 (should fail) <del>model.fit(Xmask1, X0_onehot, nb_epoch=1, batch_size=batch_size) <add>model.fit(Xmask12, X0_onehot, nb_epoch=1, batch_size=batch_size) <ide> <ide> W0 = model.layers[0].W.get_value()[0,:] <ide> if (W0 != default_mask_val).any(): <ide> raise Exception("After masked training, the W0 of the Embedding's mask value changed to: ", <ide> W0) <ide> <del>score = model.evaluate(Xmask1, X0_onehot, batch_size=batch_size) <add>score = model.evaluate(Xmask12, X0_onehot, batch_size=batch_size) <ide> if score < uniform_score*0.9: <ide> raise Exception('Somehow learned to copy timestep 0 despite masking 1, score %f' % score) <ide>
2
Javascript
Javascript
remove hidden use of common.port in parallel tests
abd5d95711ee03265f3521712ef8a6794b5a6ecc
<ide><path>test/common/index.js <ide> function _mustCallInner(fn, criteria = 1, field) { <ide> exports.hasMultiLocalhost = function hasMultiLocalhost() { <ide> const { TCP, constants: TCPConstants } = process.binding('tcp_wrap'); <ide> const t = new TCP(TCPConstants.SOCKET); <del> const ret = t.bind('127.0.0.2', exports.PORT); <add> const ret = t.bind('127.0.0.2', 0); <ide> t.close(); <ide> return ret === 0; <ide> };
1
Python
Python
fix yaml serialization support
8824f1b469cf48d5d8fa96be5368a4cd82d783ca
<ide><path>keras/layers/containers.py <ide> def get_config(self): <ide> return {"name":self.__class__.__name__, <ide> "layers":[layer.get_config() for layer in self.layers]} <ide> <del> def to_yaml(self, store_params=True): <del> seq_config = {} <del> seq_config['name'] = self.__class__.__name__ <del> layers = [] <del> for layer in self.layers: <del> layer_conf = layer.to_yaml(store_params) <del> layers.append(layer_conf) <del> seq_config['layers'] = layers <del> return seq_config <ide> <ide> class Graph(Layer): <ide> ''' <ide> def add_output(self, name, input=None, inputs=[], merge_mode='concat'): <ide> def get_config(self): <ide> return {"name":self.__class__.__name__, <ide> "input_config":self.input_config, <del> "output_config":self.output_config, <ide> "node_config":self.node_config, <del> "nodes":[self.nodes[c["name"]].get_config() for c in self.node_config]} <del> <del> def to_yaml(self, store_params=True): <del> graph_config = {} <del> graph_config['name'] = self.__class__.__name__ <del> <del> inputs = [] <del> for input_conf in self.input_config: <del> inputs.append(input_conf) <del> graph_config['inputs'] = inputs <del> <del> outputs = [] <del> for output_conf in self.output_config: <del> outputs.append(output_conf) <del> graph_config['outputs'] = outputs <del> <del> nodes = [] <del> for node_conf in self.node_config: <del> name = node_conf.get('name') <del> layer = self.nodes[name] <del> layer_conf = layer.to_yaml(store_params) <del> node_conf['layer'] = layer_conf <del> nodes.append(node_conf) <del> graph_config['nodes'] = nodes <del> <del> return graph_config <add> "output_config":self.output_config, <add> "input_order":self.input_order, <add> "output_order":self.output_order, <add> "nodes":dict([(c["name"], self.nodes[c["name"]].get_config()) for c in self.node_config])} <ide><path>keras/layers/core.py <ide> def get_params(self): <ide> <ide> return self.params, regularizers, consts <ide> <del> def to_yaml(self, store_params=True): <del> layer_conf = self.get_config() <del> if store_params: <del> layer_conf['parameters'] = [{'shape':list(param.get_value().shape), 'data':param.get_value().tolist()} for param in self.params] <del> return layer_conf <ide> <ide> class MaskedLayer(Layer): <ide> ''' <ide> def get_config(self): <ide> return {"name":self.__class__.__name__, <ide> "layers":[l.get_config() for l in self.layers], <ide> "mode":self.mode} <del> <del> def to_yaml(self, store_params=True): <del> merge_conf = {} <del> merge_conf['name'] = self.__class__.__name__ <del> merge_conf['mode'] = self.mode <del> layers = [] <del> for layer in self.layers: <del> layer_conf = layer.to_yaml(store_params) <del> layers.append(layer_conf) <del> merge_conf['layers'] = layers <del> return merge_conf <add> <ide> <ide> class Dropout(MaskedLayer): <ide> ''' <ide><path>keras/models.py <ide> from . import callbacks as cbks <ide> <ide> import time, copy, pprint <del>from .utils.layer_utils import container_from_yaml <add>from .utils.layer_utils import container_from_config <ide> from .utils.generic_utils import Progbar, printv <ide> from .layers import containers <ide> from six.moves import range <ide> def model_from_yaml(yaml_string): <ide> which is either created by hand or from to_yaml method of Sequential or Graph <ide> ''' <ide> model_params = yaml.load(yaml_string) <add> print(model_params) <add> <ide> model_name = model_params.get('name') <ide> if not model_name in {'Graph', 'Sequential'}: <ide> raise Exception('Unrecognized model:', model_name) <ide> <ide> # Create a container then set class to appropriate model <del> print(model_params) <del> model = container_from_yaml(model_params) <add> model = container_from_config(model_params) <ide> model.__class__ = get(model_name) <ide> <ide> if 'optimizer' in model_params: # if it has an optimizer, the model is assumed to be compiled <ide> def _test_loop(self, f, ins, batch_size=128, verbose=0): <ide> outs[i] /= nb_sample <ide> return outs <ide> <add> def get_config(self, verbose=0): <add> config = super(Model, self).get_config() <add> if verbose: <add> pp = pprint.PrettyPrinter(indent=4) <add> pp.pprint(config) <add> return config <add> <ide> class Sequential(Model, containers.Sequential): <ide> ''' <ide> Inherits from Model the following methods: <ide> def evaluate(self, X, y, batch_size=128, show_accuracy=False, verbose=1, sample_ <ide> return outs[0] <ide> <ide> <del> def get_config(self, verbose=0): <del> layers = [] <del> for i, l in enumerate(self.layers): <del> config = l.get_config() <del> layers.append(config) <del> if verbose: <del> printv(layers) <del> return layers <del> <del> <ide> def save_weights(self, filepath, overwrite=False): <ide> # Save weights from all layers to HDF5 <ide> import h5py <ide> def load_weights(self, filepath): <ide> f.close() <ide> <ide> <del> def to_yaml(self, store_params=True): <add> def to_yaml(self): <ide> ''' <ide> Stores a model to yaml string, optionally with all learnable parameters <ide> If the model is compiled, it will also serialize the necessary components <ide> ''' <del> model_params = super(Sequential, self).to_yaml(store_params) <add> model_params = self.get_config() <ide> if hasattr(self, 'optimizer'): <ide> model_params['class_mode'] = self.class_mode <ide> model_params['theano_mode'] = self.theano_mode <ide> model_params['loss'] = self.unweighted_loss.__name__ <ide> model_params['optimizer'] = self.optimizer.get_config() <add> <ide> return yaml.dump(model_params) <ide> <ide> <ide> def load_weights(self, filepath): <ide> self.set_weights(weights) <ide> f.close() <ide> <del> def get_config(self, verbose=1): <del> config = super(Graph, self).get_config() <del> if verbose: <del> pp = pprint.PrettyPrinter(indent=4) <del> pp.pprint(config) <del> return config <del> <del> def to_yaml(self, store_params=True): <add> def to_yaml(self): <ide> ''' <ide> Stores a model to yaml string, optionally with all learnable parameters <ide> If the model is compiled, it will also serialize the necessary components <ide> ''' <del> model_params = super(Graph, self).to_yaml(store_params) <add> model_params = self.get_config() <ide> if hasattr(self, 'optimizer'): <ide> model_params['theano_mode'] = self.theano_mode <ide> model_params['loss'] = self.loss <ide><path>keras/utils/layer_utils.py <ide> from .. import constraints <ide> <ide> <del>def container_from_yaml(layer_dict): <add>def container_from_config(layer_dict): <ide> name = layer_dict.get('name') <ide> hasParams = False <ide> <ide> if name == 'Merge': <ide> mode = layer_dict.get('mode') <ide> layers = layer_dict.get('layers') <ide> layer_list = [] <del> <ide> for layer in layers: <del> init_layer = container_from_yaml(layer) <add> init_layer = container_from_config(layer) <ide> layer_list.append(init_layer) <ide> merge_layer = Merge(layer_list, mode) <ide> return merge_layer <ide> <ide> elif name == 'Sequential': <ide> layers = layer_dict.get('layers') <ide> layer_list = [] <del> <ide> for layer in layers: <del> init_layer = container_from_yaml(layer) <add> init_layer = container_from_config(layer) <ide> layer_list.append(init_layer) <ide> seq_layer = containers.Sequential(layer_list) <ide> return seq_layer <ide> <ide> elif name == 'Graph': <ide> graph_layer = containers.Graph() <del> inputs = layer_dict.get('inputs') <add> inputs = layer_dict.get('input_config') <ide> <ide> for input in inputs: <ide> graph_layer.add_input(**input) <del> nodes = layer_dict.get('nodes') <ide> <add> nodes = layer_dict.get('node_config') <ide> for node in nodes: <del> layer_conf = node.get('layer') <del> layer = container_from_yaml(layer_conf) <add> layer = container_from_config(layer_dict['nodes'].get(node['name'])) <ide> node['layer'] = layer <ide> graph_layer.add_node(**node) <del> outputs = layer_dict.get('outputs') <ide> <add> outputs = layer_dict.get('output_config') <ide> for output in outputs: <ide> graph_layer.add_output(**output) <ide> return graph_layer <ide> def container_from_yaml(layer_dict): <ide> base_layer = get_layer(name, layer_dict) <ide> if hasParams: <ide> shaped_params = [] <del> <ide> for param in params: <ide> data = np.asarray(param.get('data')) <ide> shape = tuple(param.get('shape')) <ide><path>tests/manual/check_yaml.py <ide> model.add(Dense(128, 1, W_regularizer='identity', b_constraint='maxnorm')) <ide> model.add(Activation('sigmoid')) <ide> <del>#model.compile(loss='binary_crossentropy', optimizer='adam', class_mode="binary") <del> <ide> model.get_config(verbose=1) <ide> <del>###################### <del># save model to yaml # <del>###################### <del>#yaml_string = model.to_yaml() <del> <del>#recovered_model = model_from_yaml(yaml_string) <del>#recovered_model.get_config(verbose=1) <del> <ide> ##################################### <ide> # save model w/o parameters to yaml # <ide> ##################################### <ide> <del>yaml_no_params = model.to_yaml(store_params=False) <add>yaml_no_params = model.to_yaml() <ide> <ide> no_param_model = model_from_yaml(yaml_no_params) <ide> no_param_model.get_config(verbose=1) <ide> seq = Sequential() <ide> seq.add(Merge([model, model], mode='sum')) <ide> seq.get_config(verbose=1) <del>merge_yaml = seq.to_yaml(store_params=False) <add>merge_yaml = seq.to_yaml() <ide> merge_model = model_from_yaml(merge_yaml) <ide> <ide> large_model = Sequential() <ide> large_model.add(Merge([seq,model], mode='concat')) <ide> large_model.get_config(verbose=1) <del>large_model.to_yaml(store_params=False) <add>large_model.to_yaml() <ide> <ide> #################### <ide> # save graph model # <ide> history = graph.fit({'input1':X_train, 'output1':y_train}, nb_epoch=10) <ide> original_pred = graph.predict({'input1':X_test}) <ide> <del>graph_yaml = graph.to_yaml(store_params=True) <add>graph_yaml = graph.to_yaml() <add>graph.save_weights('temp.h5', overwrite=True) <add> <ide> reloaded_graph = model_from_yaml(graph_yaml) <add>reloaded_graph.load_weights('temp.h5') <ide> reloaded_graph.get_config(verbose=1) <ide> <ide> reloaded_graph.compile('rmsprop', {'output1':'mse'}) <ide> new_pred = reloaded_graph.predict({'input1':X_test}) <ide> <del>print(new_pred['output1'][3][1] == original_pred['output1'][3][1]) <add>assert(new_pred['output1'][3][1] == original_pred['output1'][3][1])
5
Python
Python
fix another bug, see last commit
b9086fdf39941343fde65551b8667e635e05f14f
<ide><path>numpy/distutils/system_info.py <ide> def __init__ (self, <ide> def parse_config_files(self): <ide> self.cp.read(self.files) <ide> if not self.cp.has_section(self.section): <del> self.cp.add_section(self.section) <add> if self.section is not None: <add> self.cp.add_section(self.section) <ide> <ide> def calc_libraries_info(self): <ide> libs = self.get_libraries()
1
Javascript
Javascript
remove unnecessary use of inner state
f9c16b87eff60858efa0b6977fa1d253be538589
<ide><path>lib/internal/child_process.js <ide> function flushStdio(subprocess) { <ide> // TODO(addaleax): This doesn't necessarily account for all the ways in <ide> // which data can be read from a stream, e.g. being consumed on the <ide> // native layer directly as a StreamBase. <del> if (!stream || !stream.readable || <del> stream._readableState.readableListening || <del> stream[kIsUsedAsStdio]) { <add> if (!stream || !stream.readable || stream[kIsUsedAsStdio]) { <ide> continue; <ide> } <ide> stream.resume();
1
Python
Python
remove lock in fit_generator
acc5c45feba49de09ee6f46dfb5fad64f4eeb28f
<ide><path>keras/engine/training.py <ide> def generator_queue(generator, max_q_size=10, <ide> if pickle_safe: <ide> q = multiprocessing.Queue(maxsize=max_q_size) <ide> _stop = multiprocessing.Event() <del> lock = multiprocessing.Lock() <ide> else: <ide> q = queue.Queue() <ide> _stop = threading.Event() <del> lock = threading.Lock() <ide> <ide> try: <ide> def data_generator_task(): <ide> while not _stop.is_set(): <ide> try: <ide> if pickle_safe or q.qsize() < max_q_size: <del> lock.acquire() <ide> generator_output = next(generator) <del> lock.release() <ide> q.put(generator_output) <ide> else: <ide> time.sleep(wait_time)
1
Javascript
Javascript
fix reference in code comment
7cff6e80bfd2f61ed67ff07af87af3ab63860273
<ide><path>lib/async_hooks.js <ide> const errors = require('internal/errors'); <ide> * hooks for each type. <ide> * <ide> * async_id_fields is a Float64Array wrapping the double array of <del> * Environment::AsyncHooks::uid_fields_[]. Each index contains the ids for the <del> * various asynchronous states of the application. These are: <add> * Environment::AsyncHooks::async_id_fields_[]. Each index contains the ids for <add> * the various asynchronous states of the application. These are: <ide> * kExecutionAsyncId: The async_id assigned to the resource responsible for the <ide> * current execution stack. <ide> * kTriggerAsyncId: The trigger_async_id of the resource responsible for
1
Text
Text
add evan lucas to release team
b46c627ee9bbc9ce43ba53c1cc1e489d5bc9e64e
<ide><path>README.md <ide> Releases of Node.js and io.js will be signed with one of the following GPG keys: <ide> * **James M Snell** &lt;jasnell@keybase.io&gt; `71DCFD284A79C3B38668286BC97EC7A07EDE3FC1` <ide> * **Rod Vagg** &lt;rod@vagg.org&gt; `DD8F2338BAE7501E3DD5AC78C273792F7D83545D` <ide> * **Myles Borins** &lt;thealphanerd@keybase.io&gt; `792807C150954BF0299B289A38CE40DEEE898E15` <add>* **Evan Lucas** &lt;evanlucas@me.com&gt; `B9AE9905FFD7803F25714661B63B535A4C206CA9` <ide> <ide> The full set of trusted release keys can be imported by running: <ide> <ide> gpg --keyserver pool.sks-keyservers.net --recv-keys FD3A5288F042B6850C66B31F09FE <ide> gpg --keyserver pool.sks-keyservers.net --recv-keys 71DCFD284A79C3B38668286BC97EC7A07EDE3FC1 <ide> gpg --keyserver pool.sks-keyservers.net --recv-keys DD8F2338BAE7501E3DD5AC78C273792F7D83545D <ide> gpg --keyserver pool.sks-keyservers.net --recv-keys 792807C150954BF0299B289A38CE40DEEE898E15 <add>gpg --keyserver pool.sks-keyservers.net --recv-keys B9AE9905FFD7803F25714661B63B535A4C206CA9 <ide> ``` <ide> <ide> See the section above on [Verifying Binaries](#verifying-binaries) for
1
PHP
PHP
update app/config to include all options
660e0fc1c4bbec573671eacc1c7098cc338af1ab
<ide><path>App/Config/error.php <ide> * - `errorLevel` - int - The level of errors you are interested in capturing. <ide> * - `trace` - boolean - Whether or not backtraces should be included in <ide> * logged errors/exceptions. <add> * - `log` - boolean - Whether or not you want exceptions logged. <ide> * - `exceptionRenderer` - string - The class responsible for rendering <ide> * uncaught exceptions. If you choose a custom class you should place <ide> * the file for that class in app/Lib/Error. This class needs to implement a render method.
1
PHP
PHP
add the method addreplyto
5546bd331a18a285a3319f29ec86c1410a199e37
<ide><path>src/Mailer/Mailer.php <ide> * @method array getSender() Gets "sender" address. {@see \Cake\Mailer\Message::getSender()} <ide> * @method $this setReplyTo($email, $name = null) Sets "Reply-To" address. {@see \Cake\Mailer\Message::setReplyTo()} <ide> * @method array getReplyTo() Gets "Reply-To" address. {@see \Cake\Mailer\Message::getReplyTo()} <add> * @method $this addReplyTo($email, $name = null) Add "Reply-To" address. {@see \Cake\Mailer\Message::addReplyTo()} <ide> * @method $this setReadReceipt($email, $name = null) Sets Read Receipt (Disposition-Notification-To header). <ide> * {@see \Cake\Mailer\Message::setReadReceipt()} <ide> * @method array getReadReceipt() Gets Read Receipt (Disposition-Notification-To header). <ide><path>src/Mailer/Message.php <ide> public function getReplyTo(): array <ide> return $this->replyTo; <ide> } <ide> <add> /** <add> * Add "Reply-To" address. <add> * <add> * @param string|array $email Null to get, String with email, <add> * Array with email as key, name as value or email as value (without name) <add> * @param string|null $name Name <add> * @return $this <add> */ <add> public function addReplyTo($email, ?string $name = null) <add> { <add> return $this->addEmail('replyTo', $email, $name); <add> } <add> <ide> /** <ide> * Sets Read Receipt (Disposition-Notification-To header). <ide> * <ide><path>tests/TestCase/Mailer/EmailTest.php <ide> public function testAddresses() <ide> $this->Email->addTo('to2@cakephp.org', 'To2 CakePHP'); <ide> $this->Email->addCc('cc2@cakephp.org', 'Cc2 CakePHP'); <ide> $this->Email->addBcc('bcc2@cakephp.org', 'Bcc2 CakePHP'); <add> $this->Email->addReplyTo('replyto2@cakephp.org', 'ReplyTo2 CakePHP'); <ide> <ide> $this->assertSame($this->Email->getFrom(), ['cake@cakephp.org' => 'CakePHP']); <del> $this->assertSame($this->Email->getReplyTo(), ['replyto@cakephp.org' => 'ReplyTo CakePHP']); <add> $this->assertSame($this->Email->getReplyTo(), ['replyto@cakephp.org' => 'ReplyTo CakePHP', 'replyto2@cakephp.org' => 'ReplyTo2 CakePHP']); <ide> $this->assertSame($this->Email->getReadReceipt(), ['readreceipt@cakephp.org' => 'ReadReceipt CakePHP']); <ide> $this->assertSame($this->Email->getReturnPath(), ['returnpath@cakephp.org' => 'ReturnPath CakePHP']); <ide> $this->assertSame($this->Email->getTo(), ['to@cakephp.org' => 'To, CakePHP', 'to2@cakephp.org' => 'To2 CakePHP']); <ide> public function testAddresses() <ide> <ide> $headers = $this->Email->getHeaders(array_fill_keys(['from', 'replyTo', 'readReceipt', 'returnPath', 'to', 'cc', 'bcc'], true)); <ide> $this->assertSame($headers['From'], 'CakePHP <cake@cakephp.org>'); <del> $this->assertSame($headers['Reply-To'], 'ReplyTo CakePHP <replyto@cakephp.org>'); <add> $this->assertSame($headers['Reply-To'], 'ReplyTo CakePHP <replyto@cakephp.org>, ReplyTo2 CakePHP <replyto2@cakephp.org>'); <ide> $this->assertSame($headers['Disposition-Notification-To'], 'ReadReceipt CakePHP <readreceipt@cakephp.org>'); <ide> $this->assertSame($headers['Return-Path'], 'ReturnPath CakePHP <returnpath@cakephp.org>'); <ide> $this->assertSame($headers['To'], '"To, CakePHP" <to@cakephp.org>, To2 CakePHP <to2@cakephp.org>'); <ide><path>tests/TestCase/Mailer/MessageTest.php <ide> public function testAddresses() <ide> $this->message->addTo('to2@cakephp.org', 'To2 CakePHP'); <ide> $this->message->addCc('cc2@cakephp.org', 'Cc2 CakePHP'); <ide> $this->message->addBcc('bcc2@cakephp.org', 'Bcc2 CakePHP'); <add> $this->message->addReplyTo('replyto2@cakephp.org', 'ReplyTo2 CakePHP'); <ide> <ide> $this->assertSame($this->message->getFrom(), ['cake@cakephp.org' => 'CakePHP']); <del> $this->assertSame($this->message->getReplyTo(), ['replyto@cakephp.org' => 'ReplyTo CakePHP']); <add> $this->assertSame($this->message->getReplyTo(), ['replyto@cakephp.org' => 'ReplyTo CakePHP', 'replyto2@cakephp.org' => 'ReplyTo2 CakePHP']); <ide> $this->assertSame($this->message->getReadReceipt(), ['readreceipt@cakephp.org' => 'ReadReceipt CakePHP']); <ide> $this->assertSame($this->message->getReturnPath(), ['returnpath@cakephp.org' => 'ReturnPath CakePHP']); <ide> $this->assertSame($this->message->getTo(), ['to@cakephp.org' => 'To, CakePHP', 'to2@cakephp.org' => 'To2 CakePHP']); <ide> public function testAddresses() <ide> <ide> $headers = $this->message->getHeaders(array_fill_keys(['from', 'replyTo', 'readReceipt', 'returnPath', 'to', 'cc', 'bcc'], true)); <ide> $this->assertSame($headers['From'], 'CakePHP <cake@cakephp.org>'); <del> $this->assertSame($headers['Reply-To'], 'ReplyTo CakePHP <replyto@cakephp.org>'); <add> $this->assertSame($headers['Reply-To'], 'ReplyTo CakePHP <replyto@cakephp.org>, ReplyTo2 CakePHP <replyto2@cakephp.org>'); <ide> $this->assertSame($headers['Disposition-Notification-To'], 'ReadReceipt CakePHP <readreceipt@cakephp.org>'); <ide> $this->assertSame($headers['Return-Path'], 'ReturnPath CakePHP <returnpath@cakephp.org>'); <ide> $this->assertSame($headers['To'], '"To, CakePHP" <to@cakephp.org>, To2 CakePHP <to2@cakephp.org>');
4
Java
Java
fix url decoding issue in reactive @requestparam
613e65f043e36324577eed14e08da3d83b2fa520
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/AbstractServerHttpRequest.java <ide> <ide> package org.springframework.http.server.reactive; <ide> <add>import java.io.UnsupportedEncodingException; <ide> import java.net.URI; <add>import java.net.URLDecoder; <add>import java.nio.charset.StandardCharsets; <ide> import java.util.regex.Matcher; <ide> import java.util.regex.Pattern; <ide> <ide> public MultiValueMap<String, String> getQueryParams() { <ide> return this.queryParams; <ide> } <ide> <add> /** <add> * A method for decoding name and value string in a name-value pair. <add> * <p>Note that the plus sign "+" is converted into a space character " ".</p> <add> * @param encodedString the string to be decoded <add> * @return the decoded string <add> * @see java.net.URLDecoder#decode(String, String) <add> */ <add> private static String decodeQueryParam(final String encodedString) { <add> try { <add> return URLDecoder.decode(encodedString, StandardCharsets.UTF_8.name()); <add> } catch (UnsupportedEncodingException e) { <add> // StandardCharsets are guaranteed to be available on every implementation of the Java platform, so this should never happen. <add> throw new IllegalStateException(e); <add> } <add> } <add> <ide> /** <ide> * A method for parsing of the query into name-value pairs. The return <ide> * value is turned into an immutable map and cached. <ide> protected MultiValueMap<String, String> initQueryParams() { <ide> String eq = matcher.group(2); <ide> String value = matcher.group(3); <ide> value = (value != null ? value : (StringUtils.hasLength(eq) ? "" : null)); <del> queryParams.add(name, value); <add> queryParams.add(decodeQueryParam(name), <add> value != null ? decodeQueryParam(value) : null); <ide> } <ide> } <ide> return queryParams; <ide><path>spring-web/src/test/java/org/springframework/http/server/reactive/ServerHttpRequestTests.java <ide> public void queryParamsWithMulitpleValues() throws Exception { <ide> assertEquals(Arrays.asList("1", "2"), params.get("a")); <ide> } <ide> <add> @Test <add> public void queryParamsWithUrlEncodedValue() throws Exception { <add> MultiValueMap<String, String> params = createHttpRequest("/path?a=%20%2B+%C3%A0").getQueryParams(); <add> assertEquals(1, params.size()); <add> assertEquals(Collections.singletonList(" + \u00e0"), params.get("a")); <add> } <add> <ide> @Test <ide> public void queryParamsWithEmptyValue() throws Exception { <ide> MultiValueMap<String, String> params = createHttpRequest("/path?a=").getQueryParams();
2
Javascript
Javascript
add alert docs
73b2c529caea0697456cff1d9071ec3733ea4897
<ide><path>website/server/extractDocs.js <ide> var components = [ <ide> <ide> var apis = [ <ide> '../Libraries/ActionSheetIOS/ActionSheetIOS.js', <add> '../Libraries/Utilities/Alert.js', <ide> '../Libraries/Utilities/AlertIOS.js', <ide> '../Libraries/Animated/src/AnimatedImplementation.js', <ide> '../Libraries/AppRegistry/AppRegistry.js',
1
PHP
PHP
decomplicate the messages->format method
be3266d255529069c767b176c5c9c7e15af9f3a9
<ide><path>system/messages.php <ide> public function all($format = ':message') <ide> */ <ide> private function format($messages, $format) <ide> { <del> array_walk($messages, function(&$message, $key) use ($format) { $message = str_replace(':message', $message, $format); }); <add> foreach ($messages as $key => &$message) <add> { <add> $message = str_replace(':message', $message, $format); <add> } <ide> <ide> return $messages; <ide> }
1
Java
Java
expose resource lookup function
bfb2effddb7d2cb9b50c1088b3971028633ad8f2
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/server/RouterFunctions.java <ide> public static <T extends ServerResponse> RouterFunction<T> nest( <ide> * For instance <ide> * <pre class="code"> <ide> * Resource location = new FileSystemResource("public-resources/"); <del> * RoutingFunction&lt;ServerResponse&gt; resources = RouterFunctions.resources("/resources/**", location); <add> * RouterFunction&lt;ServerResponse&gt; resources = RouterFunctions.resources("/resources/**", location); <ide> * </pre> <ide> * @param pattern the pattern to match <ide> * @param location the location directory relative to which resources should be resolved <ide> * @return a router function that routes to resources <add> * @see #resourceLookupFunction(String, Resource) <ide> */ <ide> public static RouterFunction<ServerResponse> resources(String pattern, Resource location) { <del> return resources(new PathResourceLookupFunction(pattern, location)); <add> return resources(resourceLookupFunction(pattern, location)); <add> } <add> <add> /** <add> * Returns the resource lookup function used by {@link #resources(String, Resource)}. <add> * The returned function can be {@linkplain Function#andThen(Function) composed} on, for <add> * instance to return a default resource when the lookup function does not match: <add> * <pre class="code"> <add> * Mono&lt;Resource&gt; defaultResource = Mono.just(new ClassPathResource("index.html")); <add> * Function&lt;ServerRequest, Mono&lt;Resource&gt;&gt; lookupFunction = <add> * RouterFunctions.resourceLookupFunction("/resources/**", new FileSystemResource("public-resources/")) <add> * .andThen(resourceMono -&gt; resourceMono.switchIfEmpty(defaultResource)); <add> * <add> * RouterFunction&lt;ServerResponse&gt; resources = RouterFunctions.resources(lookupFunction); <add> * </pre> <add> * @param pattern the pattern to match <add> * @param location the location directory relative to which resources should be resolved <add> * @return the default resource lookup function for the given parameters. <add> */ <add> public static Function<ServerRequest, Mono<Resource>> resourceLookupFunction(String pattern, Resource location) { <add> return new PathResourceLookupFunction(pattern, location); <ide> } <ide> <ide> /** <ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/function/server/PathResourceLookupFunctionTests.java <ide> /* <del> * Copyright 2002-2016 the original author or authors. <add> * Copyright 2002-2018 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import java.io.File; <ide> import java.io.IOException; <ide> import java.net.URI; <add>import java.util.function.Function; <ide> <ide> import org.junit.Test; <ide> import reactor.core.publisher.Mono; <ide> public void notFound() throws Exception { <ide> .verify(); <ide> } <ide> <add> @Test <add> public void composeResourceLookupFunction() throws Exception { <add> <add> Function<ServerRequest, Mono<Resource>> lookupFunction = <add> new PathResourceLookupFunction("/resources/**", <add> new ClassPathResource("org/springframework/web/reactive/function/server/")); <add> <add> ClassPathResource defaultResource = new ClassPathResource("response.txt", getClass()); <add> <add> Function<ServerRequest, Mono<Resource>> customLookupFunction = <add> lookupFunction.andThen(resourceMono -> resourceMono <add> .switchIfEmpty(Mono.just(defaultResource))); <add> <add> MockServerRequest request = MockServerRequest.builder() <add> .uri(new URI("http://localhost/resources/foo")) <add> .build(); <add> <add> Mono<Resource> result = customLookupFunction.apply(request); <add> StepVerifier.create(result) <add> .expectNextMatches(resource -> { <add> try { <add> return defaultResource.getFile().equals(resource.getFile()); <add> } <add> catch (IOException ex) { <add> return false; <add> } <add> }) <add> .expectComplete() <add> .verify(); <add> <add> } <add> <add> <ide> } <ide>\ No newline at end of file
2
Python
Python
add argument for cnn maxout pieces
f5144f04be1e5b6d7bb937611f1303ec39054f99
<ide><path>spacy/_ml.py <ide> def drop_layer_fwd(X, drop=0.): <ide> return model <ide> <ide> <del>def Tok2Vec(width, embed_size, pretrained_dims=0): <del> if pretrained_dims is None: <del> pretrained_dims = 0 <add>def Tok2Vec(width, embed_size, pretrained_dims=0, **kwargs): <add> assert pretrained_dims is not None <add> cnn_maxout_pieces = kwargs.get('cnn_maxout_pieces', 3) <ide> cols = [ID, NORM, PREFIX, SUFFIX, SHAPE, ORTH] <ide> with Model.define_operators({'>>': chain, '|': concatenate, '**': clone, '+': add}): <ide> norm = HashEmbed(width, embed_size, column=cols.index(NORM), name='embed_norm') <ide> def Tok2Vec(width, embed_size, pretrained_dims=0): <ide> >> LN(Maxout(width, width*4, pieces=3)), column=5) <ide> ) <ide> ) <del> convolution = Residual(ExtractWindow(nW=1) >> LN(Maxout(width, width*3, pieces=3))) <add> convolution = Residual( <add> ExtractWindow(nW=1) <add> >> LN(Maxout(width, width*3, pieces=cnn_maxout_pieces)) <add> ) <ide> <ide> if pretrained_dims >= 1: <ide> embed = concatenate_lists(trained_vectors, SpacyVectors)
1
Text
Text
add mapreduce description to core hadoop
71559e7aa827826777e64bacb29d997125af9f57
<ide><path>guide/english/data-science-tools/hadoop/index.md <ide> At the time of its release, Hadoop was capable of processing data on a larger sc <ide> <ide> Data is stored in the Hadoop Distributed File System (HDFS). Using map reduce, Hadoop processes data in parallel chunks (processing several parts at the same time) rather than in a single queue. This reduces the time needed to process large data sets. <ide> <del>HDFS works by storing large files divided into chunks, and replicating them across many servers. Having multiple copies of files creates redundancy, which protects against data loss. <add>HDFS works by storing large files divided into chunks (also known as blocks) , and replicating them across many servers. Having multiple copies of files creates redundancy, which protects against data loss. <add> <add>MapReduce is a parallel processing framework which utilizes three operations in essence: <add>- Map : Each datanode processes the data locally and spits it out to a temporary location. <add>- Shuffle : The datanode shuffles(redistributes) the data based on an output key , thus ensuring that each datanode has data related to a single key. <add>- Reduce : Now the only task left for each data is to group data per key . This task is independent across datanodes and is processesed parallely. <ide> <ide> ### Hadoop Ecosystem <ide>
1
PHP
PHP
fix cache events not being fired when using tags
7b6600ba4fc97fd1eb6549913961cd0020d02e56
<ide><path>src/Illuminate/Cache/RedisTaggedCache.php <ide> class RedisTaggedCache extends TaggedCache <ide> */ <ide> public function forever($key, $value) <ide> { <del> $this->pushForeverKeys($namespace = $this->tags->getNamespace(), $key); <add> $this->pushForeverKeys($this->tags->getNamespace(), $key); <ide> <del> $this->store->forever(sha1($namespace).':'.$key, $value); <add> parent::forever($key, $value); <ide> } <ide> <ide> /** <ide><path>src/Illuminate/Cache/Repository.php <ide> use DateTime; <ide> use ArrayAccess; <ide> use Carbon\Carbon; <add>use BadMethodCallException; <ide> use Illuminate\Contracts\Cache\Store; <ide> use Illuminate\Support\Traits\Macroable; <ide> use Illuminate\Contracts\Events\Dispatcher; <ide> public function forget($key) <ide> return $success; <ide> } <ide> <add> /** <add> * Begin executing a new tags operation if the store supports it. <add> * <add> * @param string $name <add> * @return \Illuminate\Cache\TaggedCache <add> * <add> * @deprecated since version 5.1. Use tags instead. <add> */ <add> public function section($name) <add> { <add> return $this->tags($name); <add> } <add> <add> /** <add> * Begin executing a new tags operation if the store supports it. <add> * <add> * @param array|mixed $names <add> * @return \Illuminate\Cache\TaggedCache <add> * <add> * @throws \BadMethodCallException <add> */ <add> public function tags($names) <add> { <add> if (method_exists($this->store, 'tags')) { <add> $taggedCache = $this->store->tags($names); <add> <add> if (! is_null($this->events)) { <add> $taggedCache->setEventDispatcher($this->events); <add> } <add> $taggedCache->setDefaultCacheTime($this->default); <add> <add> return $taggedCache; <add> } <add> <add> throw BadMethodCallException('The current cache store does not support tagging.'); <add> } <add> <ide> /** <ide> * Get the default cache time. <ide> * <ide><path>src/Illuminate/Cache/TagSet.php <ide> public function tagKey($name) <ide> { <ide> return 'tag:'.$name.':key'; <ide> } <add> <add> /** <add> * Get all of the names in the set. <add> * <add> * @return array <add> */ <add> public function getNames() <add> { <add> return $this->names; <add> } <ide> } <ide><path>src/Illuminate/Cache/TaggedCache.php <ide> <ide> namespace Illuminate\Cache; <ide> <del>use Closure; <del>use DateTime; <del>use Carbon\Carbon; <ide> use Illuminate\Contracts\Cache\Store; <ide> <del>class TaggedCache implements Store <add>class TaggedCache extends Repository <ide> { <del> /** <del> * The cache store implementation. <del> * <del> * @var \Illuminate\Contracts\Cache\Store <del> */ <del> protected $store; <del> <ide> /** <ide> * The tag set instance. <ide> * <ide> class TaggedCache implements Store <ide> */ <ide> public function __construct(Store $store, TagSet $tags) <ide> { <add> parent::__construct($store); <add> <ide> $this->tags = $tags; <del> $this->store = $store; <ide> } <ide> <ide> /** <del> * Determine if an item exists in the cache. <del> * <del> * @param string $key <del> * @return bool <add> * {@inheritdoc} <ide> */ <del> public function has($key) <add> protected function fireCacheEvent($event, $payload) <ide> { <del> return ! is_null($this->get($key)); <add> if (preg_match('/^'.sha1($this->tags->getNamespace()).':(.*)$/', $payload[0], $matches) === 1) { <add> $payload[0] = $matches[1]; <add> } <add> $payload[] = $this->tags->getNames(); <add> <add> parent::fireCacheEvent($event, $payload); <ide> } <ide> <ide> /** <del> * Retrieve an item from the cache by key. <del> * <del> * @param string $key <del> * @param mixed $default <del> * @return mixed <add> * {@inheritdoc} <ide> */ <ide> public function get($key, $default = null) <ide> { <del> $value = $this->store->get($this->taggedItemKey($key)); <del> <del> return ! is_null($value) ? $value : value($default); <add> return parent::get($this->taggedItemKey($key), $default); <ide> } <ide> <ide> /** <del> * Store an item in the cache for a given number of minutes. <del> * <del> * @param string $key <del> * @param mixed $value <del> * @param \DateTime|int $minutes <del> * @return void <add> * {@inheritdoc} <ide> */ <ide> public function put($key, $value, $minutes) <ide> { <del> $minutes = $this->getMinutes($minutes); <del> <del> if (! is_null($minutes)) { <del> $this->store->put($this->taggedItemKey($key), $value, $minutes); <del> } <add> parent::put($this->taggedItemKey($key), $value, $minutes); <ide> } <ide> <ide> /** <del> * Store an item in the cache if the key does not exist. <del> * <del> * @param string $key <del> * @param mixed $value <del> * @param \DateTime|int $minutes <del> * @return bool <add> * {@inheritdoc} <ide> */ <ide> public function add($key, $value, $minutes) <ide> { <del> if (is_null($this->get($key))) { <del> $this->put($key, $value, $minutes); <del> <del> return true; <add> if (method_exists($this->store, 'add')) { <add> $key = $this->taggedItemKey($key); <ide> } <ide> <del> return false; <add> return parent::add($key, $value, $minutes); <ide> } <ide> <ide> /** <ide> public function decrement($key, $value = 1) <ide> } <ide> <ide> /** <del> * Store an item in the cache indefinitely. <del> * <del> * @param string $key <del> * @param mixed $value <del> * @return void <add> * {@inheritdoc} <ide> */ <ide> public function forever($key, $value) <ide> { <del> $this->store->forever($this->taggedItemKey($key), $value); <add> parent::forever($this->taggedItemKey($key), $value); <ide> } <ide> <ide> /** <del> * Remove an item from the cache. <del> * <del> * @param string $key <del> * @return bool <add> * {@inheritdoc} <ide> */ <ide> public function forget($key) <ide> { <del> return $this->store->forget($this->taggedItemKey($key)); <add> return parent::forget($this->taggedItemKey($key)); <ide> } <ide> <ide> /** <ide> public function flush() <ide> $this->tags->reset(); <ide> } <ide> <del> /** <del> * Get an item from the cache, or store the default value. <del> * <del> * @param string $key <del> * @param \DateTime|int $minutes <del> * @param \Closure $callback <del> * @return mixed <del> */ <del> public function remember($key, $minutes, Closure $callback) <del> { <del> // If the item exists in the cache we will just return this immediately <del> // otherwise we will execute the given Closure and cache the result <del> // of that execution for the given number of minutes in storage. <del> if (! is_null($value = $this->get($key))) { <del> return $value; <del> } <del> <del> $this->put($key, $value = $callback(), $minutes); <del> <del> return $value; <del> } <del> <del> /** <del> * Get an item from the cache, or store the default value forever. <del> * <del> * @param string $key <del> * @param \Closure $callback <del> * @return mixed <del> */ <del> public function sear($key, Closure $callback) <del> { <del> return $this->rememberForever($key, $callback); <del> } <del> <del> /** <del> * Get an item from the cache, or store the default value forever. <del> * <del> * @param string $key <del> * @param \Closure $callback <del> * @return mixed <del> */ <del> public function rememberForever($key, Closure $callback) <del> { <del> // If the item exists in the cache we will just return this immediately <del> // otherwise we will execute the given Closure and cache the result <del> // of that execution for an indefinite amount of time. It's easy. <del> if (! is_null($value = $this->get($key))) { <del> return $value; <del> } <del> <del> $this->forever($key, $value = $callback()); <del> <del> return $value; <del> } <del> <ide> /** <ide> * Get a fully qualified key for a tagged item. <ide> * <ide> public function taggedItemKey($key) <ide> { <ide> return sha1($this->tags->getNamespace()).':'.$key; <ide> } <del> <del> /** <del> * Get the cache key prefix. <del> * <del> * @return string <del> */ <del> public function getPrefix() <del> { <del> return $this->store->getPrefix(); <del> } <del> <del> /** <del> * Calculate the number of minutes with the given duration. <del> * <del> * @param \DateTime|int $duration <del> * @return int|null <del> */ <del> protected function getMinutes($duration) <del> { <del> if ($duration instanceof DateTime) { <del> $fromNow = Carbon::now()->diffInMinutes(Carbon::instance($duration), false); <del> <del> return $fromNow > 0 ? $fromNow : null; <del> } <del> <del> return is_string($duration) ? (int) $duration : $duration; <del> } <ide> } <ide><path>tests/Cache/CacheEventsTest.php <add><?php <add> <add>use Mockery as m; <add> <add>class CacheEventTest extends PHPUnit_Framework_TestCase <add>{ <add> public function tearDown() <add> { <add> m::close(); <add> } <add> <add> public function testHasTriggersEvents() <add> { <add> $dispatcher = $this->getDispatcher(); <add> $repository = $this->getRepository($dispatcher); <add> <add> $dispatcher->shouldReceive('fire')->once()->with('cache.missed', ['foo']); <add> $this->assertFalse($repository->has('foo')); <add> <add> $dispatcher->shouldReceive('fire')->once()->with('cache.hit', ['baz', 'qux']); <add> $this->assertTrue($repository->has('baz')); <add> <add> $dispatcher->shouldReceive('fire')->once()->with('cache.missed', ['foo', ['taylor']]); <add> $dispatcher->shouldReceive('fire')->never(); <add> $this->assertFalse($repository->tags('taylor')->has('foo')); <add> <add> $dispatcher->shouldReceive('fire')->once()->with('cache.hit', ['baz', 'qux', ['taylor']]); <add> $this->assertTrue($repository->tags('taylor')->has('baz')); <add> } <add> <add> public function testGetTriggersEvents() <add> { <add> $dispatcher = $this->getDispatcher(); <add> $repository = $this->getRepository($dispatcher); <add> <add> $dispatcher->shouldReceive('fire')->once()->with('cache.missed', ['foo']); <add> $this->assertNull($repository->get('foo')); <add> <add> $dispatcher->shouldReceive('fire')->once()->with('cache.hit', ['baz', 'qux']); <add> $this->assertEquals('qux', $repository->get('baz')); <add> <add> $dispatcher->shouldReceive('fire')->once()->with('cache.missed', ['foo', ['taylor']]); <add> $this->assertNull($repository->tags('taylor')->get('foo')); <add> <add> $dispatcher->shouldReceive('fire')->once()->with('cache.hit', ['baz', 'qux', ['taylor']]); <add> $this->assertEquals('qux', $repository->tags('taylor')->get('baz')); <add> } <add> <add> public function testPullTriggersEvents() <add> { <add> $dispatcher = $this->getDispatcher(); <add> $repository = $this->getRepository($dispatcher); <add> <add> $dispatcher->shouldReceive('fire')->once()->with('cache.hit', ['baz', 'qux']); <add> $dispatcher->shouldReceive('fire')->once()->with('cache.delete', ['baz']); <add> $this->assertEquals('qux', $repository->pull('baz')); <add> <add> $dispatcher->shouldReceive('fire')->once()->with('cache.hit', ['baz', 'qux', ['taylor']]); <add> $dispatcher->shouldReceive('fire')->once()->with('cache.delete', ['baz', ['taylor']]); <add> $this->assertEquals('qux', $repository->tags('taylor')->pull('baz')); <add> } <add> <add> public function testPutTriggersEvents() <add> { <add> $dispatcher = $this->getDispatcher(); <add> $repository = $this->getRepository($dispatcher); <add> <add> $dispatcher->shouldReceive('fire')->once()->with('cache.write', ['foo', 'bar', 99]); <add> $repository->put('foo', 'bar', 99); <add> <add> $dispatcher->shouldReceive('fire')->once()->with('cache.write', ['foo', 'bar', 99, ['taylor']]); <add> $repository->tags('taylor')->put('foo', 'bar', 99); <add> } <add> <add> public function testAddTriggersEvents() <add> { <add> $dispatcher = $this->getDispatcher(); <add> $repository = $this->getRepository($dispatcher); <add> <add> $dispatcher->shouldReceive('fire')->once()->with('cache.missed', ['foo']); <add> $dispatcher->shouldReceive('fire')->once()->with('cache.write', ['foo', 'bar', 99]); <add> $this->assertTrue($repository->add('foo', 'bar', 99)); <add> <add> $dispatcher->shouldReceive('fire')->once()->with('cache.missed', ['foo', ['taylor']]); <add> $dispatcher->shouldReceive('fire')->once()->with('cache.write', ['foo', 'bar', 99, ['taylor']]); <add> $this->assertTrue($repository->tags('taylor')->add('foo', 'bar', 99)); <add> } <add> <add> public function testForeverTriggersEvents() <add> { <add> $dispatcher = $this->getDispatcher(); <add> $repository = $this->getRepository($dispatcher); <add> <add> $dispatcher->shouldReceive('fire')->once()->with('cache.write', ['foo', 'bar', 0]); <add> $repository->forever('foo', 'bar'); <add> <add> $dispatcher->shouldReceive('fire')->once()->with('cache.write', ['foo', 'bar', 0, ['taylor']]); <add> $repository->tags('taylor')->forever('foo', 'bar'); <add> } <add> <add> public function testRememberTriggersEvents() <add> { <add> $dispatcher = $this->getDispatcher(); <add> $repository = $this->getRepository($dispatcher); <add> <add> $dispatcher->shouldReceive('fire')->once()->with('cache.missed', ['foo']); <add> $dispatcher->shouldReceive('fire')->once()->with('cache.write', ['foo', 'bar', 99]); <add> $this->assertEquals('bar', $repository->remember('foo', 99, function () { <add> return 'bar'; <add> })); <add> <add> $dispatcher->shouldReceive('fire')->once()->with('cache.missed', ['foo', ['taylor']]); <add> $dispatcher->shouldReceive('fire')->once()->with('cache.write', ['foo', 'bar', 99, ['taylor']]); <add> $this->assertEquals('bar', $repository->tags('taylor')->remember('foo', 99, function () { <add> return 'bar'; <add> })); <add> } <add> <add> public function testRememberForeverTriggersEvents() <add> { <add> $dispatcher = $this->getDispatcher(); <add> $repository = $this->getRepository($dispatcher); <add> <add> $dispatcher->shouldReceive('fire')->once()->with('cache.missed', ['foo']); <add> $dispatcher->shouldReceive('fire')->once()->with('cache.write', ['foo', 'bar', 0]); <add> $this->assertEquals('bar', $repository->rememberForever('foo', function () { <add> return 'bar'; <add> })); <add> <add> $dispatcher->shouldReceive('fire')->once()->with('cache.missed', ['foo', ['taylor']]); <add> $dispatcher->shouldReceive('fire')->once()->with('cache.write', ['foo', 'bar', 0, ['taylor']]); <add> $this->assertEquals('bar', $repository->tags('taylor')->rememberForever('foo', function () { <add> return 'bar'; <add> })); <add> } <add> <add> public function testForgetTriggersEvents() <add> { <add> $dispatcher = $this->getDispatcher(); <add> $repository = $this->getRepository($dispatcher); <add> <add> $dispatcher->shouldReceive('fire')->once()->with('cache.delete', ['baz']); <add> $this->assertTrue($repository->forget('baz')); <add> <add> // $dispatcher->shouldReceive('fire')->once()->with('cache.delete', ['baz', ['taylor']]); <add> // $this->assertTrue($repository->tags('taylor')->forget('baz')); <add> } <add> <add> protected function getDispatcher() <add> { <add> return m::mock('Illuminate\Events\Dispatcher'); <add> } <add> <add> protected function getRepository($dispatcher) <add> { <add> $repository = new \Illuminate\Cache\Repository(new \Illuminate\Cache\ArrayStore()); <add> $repository->put('baz', 'qux', 99); <add> $repository->tags('taylor')->put('baz', 'qux', 99); <add> $repository->setEventDispatcher($dispatcher); <add> <add> return $repository; <add> } <add>} <ide><path>tests/Cache/CacheTaggedCacheTest.php <ide> public function testRedisCacheTagsPushForeverKeysCorrectly() <ide> $store = m::mock('Illuminate\Contracts\Cache\Store'); <ide> $tagSet = m::mock('Illuminate\Cache\TagSet', [$store, ['foo', 'bar']]); <ide> $tagSet->shouldReceive('getNamespace')->andReturn('foo|bar'); <add> $tagSet->shouldReceive('getNames')->andReturn(['foo', 'bar']); <ide> $redis = new Illuminate\Cache\RedisTaggedCache($store, $tagSet); <ide> $store->shouldReceive('getPrefix')->andReturn('prefix:'); <ide> $store->shouldReceive('connection')->andReturn($conn = m::mock('StdClass'));
6
Text
Text
document the fact you can add_index on new columns
1badf20497828cf20f86455fb958832cc5104c08
<ide><path>guides/source/migrations.md <ide> class AddPartNumberToProducts < ActiveRecord::Migration <ide> end <ide> ``` <ide> <del>Similarly, <add>If you'd like to add an index on the new column, you can do that as well: <add> <add>```bash <add>$ rails generate migration AddPartNumberToProducts part_number:string:index <add>``` <add> <add>will generate <add> <add>```ruby <add>class AddPartNumberToProducts < ActiveRecord::Migration <add> def change <add> add_column :products, :part_number, :string <add> add_index :products, :part_number <add> end <add>end <add>``` <add> <add> <add>Similarly, you can generate a migration to remove a column from the command line: <ide> <ide> ```bash <ide> $ rails generate migration RemovePartNumberFromProducts part_number:string
1
Python
Python
add initialize method for entity_ruler
251b3eb4e5c688e076f4e761a43ffbab9ea793b9
<ide><path>spacy/errors.py <ide> class Errors: <ide> "issue tracker: http://github.com/explosion/spaCy/issues") <ide> <ide> # TODO: fix numbering after merging develop into master <add> E900 = ("Patterns for component '{name}' not initialized. This can be fixed " <add> "by calling 'add_patterns' or 'initialize'.") <ide> E092 = ("The sentence-per-line IOB/IOB2 file is not formatted correctly. " <ide> "Try checking whitespace and delimiters. See " <ide> "https://nightly.spacy.io/api/cli#convert") <ide><path>spacy/pipeline/entityruler.py <del>from typing import Optional, Union, List, Dict, Tuple, Iterable, Any <add>from typing import Optional, Union, List, Dict, Tuple, Iterable, Any, Callable <ide> from collections import defaultdict <ide> from pathlib import Path <ide> import srsly <add>from spacy.training import Example <ide> <ide> from ..language import Language <ide> from ..errors import Errors <ide> def __call__(self, doc: Doc) -> Doc: <ide> <ide> DOCS: https://nightly.spacy.io/api/entityruler#call <ide> """ <add> self._require_patterns() <ide> matches = list(self.matcher(doc)) + list(self.phrase_matcher(doc)) <ide> matches = set( <ide> [(m_id, start, end) for m_id, start, end in matches if start != end] <ide> def labels(self) -> Tuple[str, ...]: <ide> all_labels.add(l) <ide> return tuple(all_labels) <ide> <add> def initialize( <add> self, <add> get_examples: Callable[[], Iterable[Example]], <add> *, <add> nlp: Optional[Language] = None, <add> patterns_path: Optional[Path] = None <add> ): <add> """Initialize the pipe for training. <add> <add> get_examples (Callable[[], Iterable[Example]]): Function that <add> returns a representative sample of gold-standard Example objects. <add> nlp (Language): The current nlp object the component is part of. <add> patterns_path: Path to serialized patterns. <add> <add> DOCS (TODO): https://nightly.spacy.io/api/entityruler#initialize <add> """ <add> if patterns_path: <add> patterns = srsly.read_jsonl(patterns_path) <add> self.add_patterns(patterns) <add> <add> <ide> @property <ide> def ent_ids(self) -> Tuple[str, ...]: <ide> """All entity ids present in the match patterns `id` properties <ide> def clear(self) -> None: <ide> self.phrase_patterns = defaultdict(list) <ide> self._ent_ids = defaultdict(dict) <ide> <add> def _require_patterns(self) -> None: <add> """Raise an error if the component has no patterns.""" <add> if not self.patterns or list(self.patterns) == [""]: <add> raise ValueError(Errors.E900.format(name=self.name)) <add> <ide> def _split_label(self, label: str) -> Tuple[str, str]: <ide> """Split Entity label into ent_label and ent_id if it contains self.ent_id_sep <ide> <ide><path>spacy/training/initialize.py <ide> def init_nlp(config: Config, *, use_gpu: int = -1) -> "Language": <ide> nlp.resume_training(sgd=optimizer) <ide> with nlp.select_pipes(disable=[*frozen_components, *resume_components]): <ide> nlp.initialize(lambda: train_corpus(nlp), sgd=optimizer) <del> logger.info("Initialized pipeline components") <add> logger.info(f"Initialized pipeline components: {nlp.pipe_names}") <ide> return nlp <ide> <ide>
3
PHP
PHP
change stackframe default in deprecationwarning()
7332e0a410024ccbba5904aec4da44514bb0b3ef
<ide><path>src/Core/functions.php <ide> function triggerWarning($message) <ide> * Helper method for outputting deprecation warnings <ide> * <ide> * @param string $message The message to output as a deprecation warning. <del> * @param int $stackFrame The stack frame to include in the error. Defaults to 2 <add> * @param int $stackFrame The stack frame to include in the error. Defaults to 1 <ide> * as that should point to application/plugin code. <ide> * @return void <ide> */ <del> function deprecationWarning($message, $stackFrame = 2) <add> function deprecationWarning($message, $stackFrame = 1) <ide> { <ide> if (!(error_reporting() & E_USER_DEPRECATED)) { <ide> return; <ide><path>tests/TestCase/Core/FunctionsTest.php <ide> public function testEnv() <ide> * Test error messages coming out when debug is on, manually setting the stack frame <ide> * <ide> * @expectedException PHPUnit\Framework\Error\Deprecated <del> * @expectedExceptionMessageRegExp /This is going away - (.*?)[\/\\]TestCase.php, line\: \d+/ <add> * @expectedExceptionMessageRegExp /This is going away - (.*?)[\/\\]FunctionsTest.php, line\: \d+/ <ide> */ <ide> public function testDeprecationWarningEnabled() <ide> { <ide> $this->withErrorReporting(E_ALL, function () { <del> deprecationWarning('This is going away', 1); <add> deprecationWarning('This is going away', 2); <ide> }); <ide> } <ide> <ide> /** <ide> * Test error messages coming out when debug is on, not setting the stack frame manually <ide> * <ide> * @expectedException PHPUnit\Framework\Error\Deprecated <del> * @expectedExceptionMessageRegExp /This is going away - (.*?)[\/\\]FunctionsTest.php, line\: \d+/ <add> * @expectedExceptionMessageRegExp /This is going away - (.*?)[\/\\]TestCase.php, line\: \d+/ <ide> */ <ide> public function testDeprecationWarningEnabledDefaultFrame() <ide> {
2
PHP
PHP
add more test cases
408b3ffe09a562542f374ed7129a345248ed75d2
<ide><path>tests/TestCase/Validation/ValidatorTest.php <ide> public function testAllowEmpty() <ide> * <ide> * @return void <ide> */ <del> public function testAllowEmptyDateTime() <add> public function testAllowEmptyWithDateTimeFields() <ide> { <ide> $validator = new Validator(); <ide> $validator->allowEmpty('created') <ide> public function testAllowEmptyDateTime() <ide> * <ide> * @return void <ide> */ <del> public function testAllowEmptyFileFields() <add> public function testAllowEmptyWithFileFields() <ide> { <ide> $validator = new Validator(); <ide> $validator->allowEmpty('picture') <ide> public function testAllowEmptyAsArrayFailure() <ide> $validator->allowEmpty(['title' => 'derp', 'created' => false]); <ide> } <ide> <add> /** <add> * Tests the allowEmptyString method <add> * <add> * @return void <add> */ <add> public function testAllowEmptyString() <add> { <add> $validator = new Validator(); <add> $validator->allowEmptyString('title') <add> ->scalar('title'); <add> <add> $this->assertTrue($validator->isEmptyAllowed('title', true)); <add> $this->assertTrue($validator->isEmptyAllowed('title', false)); <add> <add> $data = [ <add> 'title' => '', <add> ]; <add> $this->assertEmpty($validator->errors($data)); <add> <add> $data = [ <add> 'title' => null, <add> ]; <add> $this->assertEmpty($validator->errors($data)); <add> <add> $data = [ <add> 'title' => [], <add> ]; <add> $this->assertNotEmpty($validator->errors($data)); <add> <add> $validator = new Validator(); <add> $validator->allowEmptyString('title', 'update', 'message'); <add> $this->assertFalse($validator->isEmptyAllowed('title', true)); <add> $this->assertTrue($validator->isEmptyAllowed('title', false)); <add> <add> $data = [ <add> 'title' => null, <add> ]; <add> $expected = [ <add> 'title' => ['_empty' => 'message'], <add> ]; <add> $this->assertSame($expected, $validator->errors($data, true)); <add> $this->assertEmpty($validator->errors($data, false)); <add> } <add> <add> /** <add> * Tests the allowEmptyArray method <add> * <add> * @return void <add> */ <add> public function testAllowEmptyArray() <add> { <add> $validator = new Validator(); <add> $validator->allowEmptyArray('items') <add> ->hasAtMost('items', 3); <add> <add> $this->assertTrue($validator->field('items')->isEmptyAllowed()); <add> <add> $data = [ <add> 'items' => '', <add> ]; <add> $result = $validator->errors($data); <add> $this->assertEmpty($result); <add> <add> $data = [ <add> 'items' => null, <add> ]; <add> $result = $validator->errors($data); <add> $this->assertEmpty($result); <add> <add> $data = [ <add> 'items' => [], <add> ]; <add> $result = $validator->errors($data); <add> $this->assertEmpty($result); <add> <add> $data = [ <add> 'items' => [1, 2, 3, 4, 5], <add> ]; <add> $result = $validator->errors($data); <add> $this->assertNotEmpty($result); <add> <add> $validator = new Validator(); <add> $validator->allowEmptyArray('items', 'update', 'message'); <add> $this->assertFalse($validator->isEmptyAllowed('items', true)); <add> $this->assertTrue($validator->isEmptyAllowed('items', false)); <add> <add> $data = [ <add> 'items' => null, <add> ]; <add> $expected = [ <add> 'items' => ['_empty' => 'message'], <add> ]; <add> $this->assertSame($expected, $validator->errors($data, true)); <add> $this->assertEmpty($validator->errors($data, false)); <add> } <add> <add> /** <add> * Tests the allowEmptyFile method <add> * <add> * @return void <add> */ <add> public function testAllowEmptyFile() <add> { <add> $validator = new Validator(); <add> $validator->allowEmptyFile('photo') <add> ->uploadedFile('photo', []); <add> <add> $this->assertTrue($validator->field('photo')->isEmptyAllowed()); <add> <add> $data = [ <add> 'photo' => [ <add> 'name' => '', <add> 'type' => '', <add> 'tmp_name' => '', <add> 'error' => UPLOAD_ERR_NO_FILE, <add> ] <add> ]; <add> $result = $validator->errors($data); <add> $this->assertEmpty($result); <add> <add> $data = [ <add> 'photo' => null, <add> ]; <add> $result = $validator->errors($data); <add> $this->assertEmpty($result); <add> <add> $data = [ <add> 'photo' => [ <add> 'name' => '', <add> 'type' => '', <add> 'tmp_name' => '', <add> 'error' => UPLOAD_ERR_FORM_SIZE, <add> ] <add> ]; <add> $result = $validator->errors($data); <add> $this->assertNotEmpty($result); <add> <add> $data = [ <add> 'photo' => '', <add> ]; <add> $result = $validator->errors($data); <add> $this->assertNotEmpty($result); <add> <add> $data = [ <add> 'photo' => [], <add> ]; <add> $result = $validator->errors($data); <add> $this->assertNotEmpty($result); <add> <add> $validator = new Validator(); <add> $validator->allowEmptyArray('photo', 'update', 'message'); <add> $this->assertFalse($validator->isEmptyAllowed('photo', true)); <add> $this->assertTrue($validator->isEmptyAllowed('photo', false)); <add> <add> $data = [ <add> 'photo' => null, <add> ]; <add> $expected = [ <add> 'photo' => ['_empty' => 'message'], <add> ]; <add> $this->assertSame($expected, $validator->errors($data, true)); <add> $this->assertEmpty($validator->errors($data, false)); <add> } <add> <add> /** <add> * Tests the allowEmptyDate method <add> * <add> * @return void <add> */ <add> public function testAllowEmptyDate() <add> { <add> $validator = new Validator(); <add> $validator->allowEmptyDate('date') <add> ->date('date'); <add> <add> $this->assertTrue($validator->field('date')->isEmptyAllowed()); <add> <add> $data = [ <add> 'date' => [ <add> 'year' => '', <add> 'month' => '', <add> 'day' => '' <add> ], <add> ]; <add> $result = $validator->errors($data); <add> $this->assertEmpty($result); <add> <add> $data = [ <add> 'date' => '', <add> ]; <add> $result = $validator->errors($data); <add> $this->assertEmpty($result); <add> <add> $data = [ <add> 'date' => null, <add> ]; <add> $result = $validator->errors($data); <add> $this->assertEmpty($result); <add> <add> $data = [ <add> 'date' => [], <add> ]; <add> $result = $validator->errors($data); <add> $this->assertNotEmpty($result); <add> <add> $validator = new Validator(); <add> $validator->allowEmptyArray('date', 'update', 'message'); <add> $this->assertFalse($validator->isEmptyAllowed('date', true)); <add> $this->assertTrue($validator->isEmptyAllowed('date', false)); <add> <add> $data = [ <add> 'date' => null, <add> ]; <add> $expected = [ <add> 'date' => ['_empty' => 'message'], <add> ]; <add> $this->assertSame($expected, $validator->errors($data, true)); <add> $this->assertEmpty($validator->errors($data, false)); <add> } <add> <add> /** <add> * Tests the allowEmptyDate method <add> * <add> * @return void <add> */ <add> public function testAllowEmptyTime() <add> { <add> $validator = new Validator(); <add> $validator->allowEmptyTime('time') <add> ->time('time'); <add> <add> $this->assertTrue($validator->field('time')->isEmptyAllowed()); <add> <add> $data = [ <add> 'time' => [ <add> 'hour' => '', <add> 'minute' => '', <add> 'second' => '', <add> ], <add> ]; <add> $result = $validator->errors($data); <add> $this->assertEmpty($result); <add> <add> $data = [ <add> 'time' => '', <add> ]; <add> $result = $validator->errors($data); <add> $this->assertEmpty($result); <add> <add> $data = [ <add> 'time' => null, <add> ]; <add> $result = $validator->errors($data); <add> $this->assertEmpty($result); <add> <add> $data = [ <add> 'time' => [], <add> ]; <add> $result = $validator->errors($data); <add> $this->assertNotEmpty($result); <add> <add> $validator = new Validator(); <add> $validator->allowEmptyArray('time', 'update', 'message'); <add> $this->assertFalse($validator->isEmptyAllowed('time', true)); <add> $this->assertTrue($validator->isEmptyAllowed('time', false)); <add> <add> $data = [ <add> 'time' => null, <add> ]; <add> $expected = [ <add> 'time' => ['_empty' => 'message'], <add> ]; <add> $this->assertSame($expected, $validator->errors($data, true)); <add> $this->assertEmpty($validator->errors($data, false)); <add> } <add> <add> /** <add> * Tests the allowEmptyDate method <add> * <add> * @return void <add> */ <add> public function testAllowEmptyDateTime() <add> { <add> $validator = new Validator(); <add> $validator->allowEmptyDate('published') <add> ->time('published'); <add> <add> $this->assertTrue($validator->field('published')->isEmptyAllowed()); <add> <add> $data = [ <add> 'published' => [ <add> 'year' => '', <add> 'month' => '', <add> 'day' => '', <add> 'hour' => '', <add> 'minute' => '', <add> 'second' => '', <add> ], <add> ]; <add> $result = $validator->errors($data); <add> $this->assertEmpty($result); <add> <add> $data = [ <add> 'published' => '', <add> ]; <add> $result = $validator->errors($data); <add> $this->assertEmpty($result); <add> <add> $data = [ <add> 'published' => null, <add> ]; <add> $result = $validator->errors($data); <add> $this->assertEmpty($result); <add> <add> $data = [ <add> 'published' => [], <add> ]; <add> $result = $validator->errors($data); <add> $this->assertNotEmpty($result); <add> <add> $validator = new Validator(); <add> $validator->allowEmptyArray('published', 'update', 'message'); <add> $this->assertFalse($validator->isEmptyAllowed('published', true)); <add> $this->assertTrue($validator->isEmptyAllowed('published', false)); <add> <add> $data = [ <add> 'published' => null, <add> ]; <add> $expected = [ <add> 'published' => ['_empty' => 'message'], <add> ]; <add> $this->assertSame($expected, $validator->errors($data, true)); <add> $this->assertEmpty($validator->errors($data, false)); <add> } <add> <ide> /** <ide> * Test the notEmpty() method. <ide> *
1
Mixed
Ruby
add `time` option to `#touch`
219d71fb9049da677c9426c6d81bf9e74fae1977
<ide><path>activerecord/CHANGELOG.md <add>* `:time` option added for `#touch` <add> Fixes #18905. <add> <add> *Hyonjee Joo* <add> <ide> * Deprecated passing of `start` value to `find_in_batches` and `find_each` <ide> in favour of `begin_at` value. <ide> <ide><path>activerecord/lib/active_record/persistence.rb <ide> def reload(options = nil) <ide> self <ide> end <ide> <del> # Saves the record with the updated_at/on attributes set to the current time. <add> # Saves the record with the updated_at/on attributes set to the current time <add> # or the time specified. <ide> # Please note that no validation is performed and only the +after_touch+, <ide> # +after_commit+ and +after_rollback+ callbacks are executed. <ide> # <add> # This method can be passed attribute names and an optional time argument. <ide> # If attribute names are passed, they are updated along with updated_at/on <del> # attributes. <add> # attributes. If no time argument is passed, the current time is used as default. <ide> # <del> # product.touch # updates updated_at/on <add> # product.touch # updates updated_at/on with current time <add> # product.touch(time: Time.new(2015, 2, 16, 0, 0, 0)) # updates updated_at/on with specified time <ide> # product.touch(:designed_at) # updates the designed_at attribute and updated_at/on <ide> # product.touch(:started_at, :ended_at) # updates started_at, ended_at and updated_at/on attributes <ide> # <ide> def reload(options = nil) <ide> # ball = Ball.new <ide> # ball.touch(:updated_at) # => raises ActiveRecordError <ide> # <del> def touch(*names) <add> def touch(*names, time: current_time_from_proper_timezone) <ide> raise ActiveRecordError, "cannot touch on a new record object" unless persisted? <ide> <ide> attributes = timestamp_attributes_for_update_in_model <ide> attributes.concat(names) <ide> <ide> unless attributes.empty? <del> current_time = current_time_from_proper_timezone <ide> changes = {} <ide> <ide> attributes.each do |column| <ide> column = column.to_s <del> changes[column] = write_attribute(column, current_time) <add> changes[column] = write_attribute(column, time) <ide> end <ide> <ide> changes[self.class.locking_column] = increment_lock if locking_enabled? <ide><path>activerecord/test/cases/timestamp_test.rb <ide> def test_saving_when_instance_record_timestamps_is_false_doesnt_update_its_times <ide> assert_equal @previously_updated_at, @developer.updated_at <ide> end <ide> <add> def test_touching_updates_timestamp_with_given_time <add> previously_updated_at = @developer.updated_at <add> new_time = Time.utc(2015, 2, 16, 0, 0, 0) <add> @developer.touch(time: new_time) <add> <add> assert_not_equal previously_updated_at, @developer.updated_at <add> assert_equal new_time, @developer.updated_at <add> end <add> <ide> def test_touching_an_attribute_updates_timestamp <ide> previously_created_at = @developer.created_at <ide> @developer.touch(:created_at) <ide> def test_touching_an_attribute_updates_it <ide> assert_in_delta Time.now, task.ending, 1 <ide> end <ide> <add> def test_touching_an_attribute_updates_timestamp_with_given_time <add> previously_updated_at = @developer.updated_at <add> previously_created_at = @developer.created_at <add> new_time = Time.utc(2015, 2, 16, 4, 54, 0) <add> @developer.touch(:created_at, time: new_time) <add> <add> assert_not_equal previously_created_at, @developer.created_at <add> assert_not_equal previously_updated_at, @developer.updated_at <add> assert_equal new_time, @developer.created_at <add> assert_equal new_time, @developer.updated_at <add> end <add> <ide> def test_touching_many_attributes_updates_them <ide> task = Task.first <ide> previous_starting = task.starting
3
Javascript
Javascript
fix resetting styles in nodepool
a171380544109ccacb35c26e0ad7c8210e20e923
<ide><path>src/text-editor-component.js <ide> class NodePool { <ide> constructor () { <ide> this.elementsByType = {} <ide> this.textNodes = [] <del> this.stylesByNode = new WeakMap() <ide> } <ide> <ide> getElement (type, className, style) { <ide> class NodePool { <ide> <ide> if (element) { <ide> element.className = className <del> var existingStyle = this.stylesByNode.get(element) <del> if (existingStyle) { <del> for (var key in existingStyle) { <del> if (!style || !style[key]) element.style[key] = '' <del> } <del> } <add> element.styleMap.forEach((value, key) => { <add> if (!style || style[key] == null) element.style[key] = '' <add> }) <ide> if (style) Object.assign(element.style, style) <del> this.stylesByNode.set(element, style) <ide> <ide> while (element.firstChild) element.firstChild.remove() <ide> return element <ide> } else { <ide> var newElement = document.createElement(type) <ide> if (className) newElement.className = className <ide> if (style) Object.assign(newElement.style, style) <del> this.stylesByNode.set(newElement, style) <ide> return newElement <ide> } <ide> }
1
Ruby
Ruby
adjust compilerselectionerror message
29d204c697ff2a554a4767657884d72a85ff9ff5
<ide><path>Library/Homebrew/exceptions.rb <ide> def dump <ide> # raised by CompilerSelector if the formula fails with all of <ide> # the compilers available on the user's system <ide> class CompilerSelectionError < StandardError <del> def message <del> if MacOS.version > :tiger then <<-EOS.undent <del> This formula cannot be built with any available compilers. <del> To install this formula, you may need to: <del> brew tap homebrew/dupes <del> brew install apple-gcc42 <del> EOS <del> # tigerbrew has a separate apple-gcc42 for Xcode 2.5 <del> else <<-EOS.undent <del> This formula cannot be built with any available compilers. <del> To install this formula, you need to: <del> brew install apple-gcc42 <del> EOS <del> end <add> def message; <<-EOS.undent <add> This formula cannot be built with any available compilers. <add> To install this formula, you may need to: <add> brew install apple-gcc42 <add> EOS <ide> end <ide> end <ide>
1
PHP
PHP
fix failing tests for sql date functions
e26251b187765ebc2a21a5e4726ae5ffcd6a490e
<ide><path>src/Database/Dialect/PostgresDialectTrait.php <ide> protected function _transformFunctionExpression(FunctionExpression $expression) <ide> ->type(' + INTERVAL') <ide> ->iterateParts(function ($p, $key) { <ide> if ($key === 1) { <del> $interval = sprintf("'%s'", key($p)); <del> $p = [$interval => 'literal']; <add> $p = sprintf("'%s'", $p); <ide> } <ide> return $p; <ide> }); <ide><path>src/Database/Dialect/SqliteDialectTrait.php <ide> protected function _transformFunctionExpression(FunctionExpression $expression) <ide> ->type(' ,') <ide> ->iterateParts(function ($p, $key) { <ide> if ($key === 0) { <del> $value = rtrim(key($p), 's'); <add> $value = rtrim($p, 's'); <ide> if (isset($this->_dateParts[$value])) { <ide> $p = '%' . $this->_dateParts[$value]; <ide> } <ide> protected function _transformFunctionExpression(FunctionExpression $expression) <ide> ->type(',') <ide> ->iterateParts(function ($p, $key) { <ide> if ($key === 1) { <del> $p = key($p); <add> $p = ['value' => $p, 'type' => null]; <ide> } <ide> return $p; <ide> }); <ide><path>src/Database/Dialect/SqlserverDialectTrait.php <ide> protected function _transformFunctionExpression(FunctionExpression $expression) <ide> $params = []; <ide> $visitor = function ($p, $key) use (&$params) { <ide> if ($key === 0) { <del> $params[2] = $value; <add> $params[2] = $p; <ide> } else { <del> $valueUnit = explode(' ', key($p)); <add> $valueUnit = explode(' ', $p); <ide> $params[0] = $valueUnit[1]; <ide> $params[1] = $valueUnit[0]; <ide> } <ide><path>tests/TestCase/Database/QueryTest.php <ide> function ($q) { <ide> 'ye' => $query->func()->extract('year', 'created'), <ide> 'wd' => $query->func()->weekday('created'), <ide> 'dow' => $query->func()->dayOfWeek('created'), <del> 'addDays' => $query->func()->dateAdd('created', +2, 'days'), <del> 'minusYears' => $query->func()->dateAdd('created', -2, 'years') <add> 'addDays' => $query->func()->dateAdd('created', +2, 'day'), <add> 'substractYears' => $query->func()->dateAdd('created', -2, 'year') <ide> ]) <ide> ->from('users') <ide> ->where(['username' => 'mariano']) <ide> ->execute() <ide> ->fetchAll('assoc'); <add> $result[0]['m'] = ltrim($result[0]['m'], '0'); <add> $result[0]['me'] = ltrim($result[0]['me'], '0'); <add> $result[0]['addDays'] = substr($result[0]['addDays'], 0, 19); <add> $result[0]['substractYears'] = substr($result[0]['substractYears'], 0, 19); <ide> $expected = [ <ide> 'd' => '17', <del> 'm' => '03', <add> 'm' => '3', <ide> 'y' => '2007', <ide> 'de' => '17', <del> 'me' => '03', <add> 'me' => '3', <ide> 'ye' => '2007', <ide> 'wd' => '6', // Saturday <ide> 'dow' => '6', <ide> 'addDays' => '2007-03-19 01:16:23', <del> 'minusYears' => '2005-03-17 01:16:23' <add> 'substractYears' => '2005-03-17 01:16:23' <ide> ]; <ide> $this->assertEquals($expected, $result[0]); <ide> }
4
Java
Java
fix one more issue in stomp broker relay int test
56d26443e22d0704c655fa2535fe48501b8cebff
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandlerIntegrationTests.java <ide> public void messageDeliveryExceptionIfSystemSessionForwardFails() throws Excepti <ide> logger.debug("Starting test messageDeliveryExceptionIfSystemSessionForwardFails()"); <ide> <ide> stopActiveMqBrokerAndAwait(); <add> this.eventPublisher.expectBrokerAvailabilityEvent(false); <add> <ide> StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.SEND); <ide> this.relay.handleMessage(MessageBuilder.createMessage("test".getBytes(), headers.getMessageHeaders())); <ide> } <ide> public void brokerBecomingUnvailableTriggersErrorFrame() throws Exception { <ide> <ide> MessageExchange error = MessageExchangeBuilder.error(sess1).build(); <ide> stopActiveMqBrokerAndAwait(); <add> this.eventPublisher.expectBrokerAvailabilityEvent(false); <ide> this.responseHandler.expectMessages(error); <ide> } <ide>
1
Javascript
Javascript
fix crash because for invalid type
f2ed7ca3e398e74e902e364449888743fa13899e
<ide><path>lib/RuntimeTemplate.js <ide> class RuntimeTemplate { <ide> }) { <ide> if (runtimeCondition === undefined) return "true"; <ide> if (typeof runtimeCondition === "boolean") return `${runtimeCondition}`; <add> /** @type {Set<string>} */ <ide> const positiveRuntimeIds = new Set(); <ide> forEachRuntime(runtimeCondition, runtime => <del> positiveRuntimeIds.add(chunkGraph.getRuntimeId(runtime)) <add> positiveRuntimeIds.add(`${chunkGraph.getRuntimeId(runtime)}`) <ide> ); <add> /** @type {Set<string>} */ <ide> const negativeRuntimeIds = new Set(); <ide> forEachRuntime(subtractRuntime(runtime, runtimeCondition), runtime => <del> negativeRuntimeIds.add(chunkGraph.getRuntimeId(runtime)) <add> negativeRuntimeIds.add(`${chunkGraph.getRuntimeId(runtime)}`) <ide> ); <ide> runtimeRequirements.add(RuntimeGlobals.runtimeId); <ide> return compileBooleanMatcher.fromLists( <ide><path>test/configCases/graph/issue-11770/test.config.js <ide> module.exports = { <ide> findBundle: function (i, options) { <del> return ["shared.js", "a.js", "b.js", "c.js"]; <add> return ["shared.js", "a.js", "b.js", "c1.js", "c2.js"]; <ide> } <ide> }; <ide><path>test/configCases/graph/issue-11770/webpack.config.js <ide> module.exports = { <ide> entry: { <ide> a: "./a", <ide> b: "./b", <del> c: "./c" <add> c1: "./c", <add> c2: "./c" <ide> }, <ide> target: "web", <ide> output: {
3
Text
Text
add note about removing asm archs
4f1f14e5cdf028870c577aa32b3f87a82c2bb0cf
<ide><path>deps/openssl/README.md <ide> little) <ide> These are listed in [config/Makefile](config/Makefile). <ide> Please refer [config/opensslconf_asm.h](config/opensslconf_asm.h) for details. <ide> <add>To remove or add an architecture the templates need to be updated for which <add>there are two: <add>* include_asm.h.tmpl <add>* include_no-asm.h.tmpl <add> <add>Remove the architecture in question from these files and then run: <add>```console <add>$ make generate-headers <add>``` <add>Also remove the architecture from the list of supported ASM architectures in <add>[README.md](../README.md#supported-architectures-for-use-of-asm) <add> <ide> ### Upgrading OpenSSL <ide> <ide> Please refer to [maintaining-openssl](../../doc/contributing/maintaining-openssl.md).
1
Text
Text
add a space on readme
ad84d23a02550663a10502cdec148e126935f795
<ide><path>packages/next/README.md <ide> import { withRouter } from 'next/router' <ide> const ActiveLink = ({ children, router, href }) => { <ide> const style = { <ide> marginRight: 10, <del> color: router.pathname === href? 'red' : 'black' <add> color: router.pathname === href ? 'red' : 'black' <ide> } <ide> <ide> const handleClick = (e) => {
1
Python
Python
update tagger serialization
a7309a217d5a0d9c94bc9dff85c2e7d8262b345a
<ide><path>spacy/tests/serialize/test_serialize_tagger.py <ide> def taggers(en_vocab): <ide> tagger1 = Tagger(en_vocab) <ide> tagger2 = Tagger(en_vocab) <del> tagger1.model = tagger1.Model(None, None) <del> tagger2.model = tagger2.Model(None, None) <add> tagger1.model = tagger1.Model(8, 8) <add> tagger2.model = tagger2.Model(8, 8) <ide> return (tagger1, tagger2) <ide> <ide>
1
Javascript
Javascript
make crypto.timingsafeequal test less flaky
c678ecbca0c9d18d6578fa2a65c9a4ab2a569744
<ide><path>test/fixtures/crypto-timing-safe-equal-benchmark-func.js <add>'use strict'; <add> <add>const assert = require('assert'); <add>module.exports = (compareFunc, firstBufFill, secondBufFill, bufSize) => { <add> const firstBuffer = Buffer.alloc(bufSize, firstBufFill); <add> const secondBuffer = Buffer.alloc(bufSize, secondBufFill); <add> <add> const startTime = process.hrtime(); <add> const result = compareFunc(firstBuffer, secondBuffer); <add> const endTime = process.hrtime(startTime); <add> <add> // Ensure that the result of the function call gets used, so it doesn't <add> // get discarded due to engine optimizations. <add> assert.strictEqual(result, firstBufFill === secondBufFill); <add> <add> return endTime[0] * 1e9 + endTime[1]; <add>}; <ide><path>test/sequential/test-crypto-timing-safe-equal-benchmarks.js <add>'use strict'; <add>const common = require('../common'); <add>const assert = require('assert'); <add> <add>if (!common.hasCrypto) { <add> common.skip('missing crypto'); <add> return; <add>} <add> <add>if (!common.enoughTestMem) { <add> common.skip('memory-intensive test'); <add> return; <add>} <add> <add>const crypto = require('crypto'); <add> <add>const BENCHMARK_FUNC_PATH = <add> `${common.fixturesDir}/crypto-timing-safe-equal-benchmark-func`; <add>function runOneBenchmark(...args) { <add> const benchmarkFunc = require(BENCHMARK_FUNC_PATH); <add> const result = benchmarkFunc(...args); <add> <add> // Don't let the comparison function get cached. This avoid a timing <add> // inconsistency due to V8 optimization where the function would take <add> // less time when called with a specific set of parameters. <add> delete require.cache[require.resolve(BENCHMARK_FUNC_PATH)]; <add> return result; <add>} <add> <add>function getTValue(compareFunc) { <add> const numTrials = 10000; <add> const bufSize = 10000; <add> // Perform benchmarks to verify that timingSafeEqual is actually timing-safe. <add> <add> const rawEqualBenches = Array(numTrials); <add> const rawUnequalBenches = Array(numTrials); <add> <add> for (let i = 0; i < numTrials; i++) { <add> if (Math.random() < 0.5) { <add> // First benchmark: comparing two equal buffers <add> rawEqualBenches[i] = runOneBenchmark(compareFunc, 'A', 'A', bufSize); <add> // Second benchmark: comparing two unequal buffers <add> rawUnequalBenches[i] = runOneBenchmark(compareFunc, 'B', 'C', bufSize); <add> } else { <add> // Flip the order of the benchmarks half of the time. <add> rawUnequalBenches[i] = runOneBenchmark(compareFunc, 'B', 'C', bufSize); <add> rawEqualBenches[i] = runOneBenchmark(compareFunc, 'A', 'A', bufSize); <add> } <add> } <add> <add> const equalBenches = filterOutliers(rawEqualBenches); <add> const unequalBenches = filterOutliers(rawUnequalBenches); <add> <add> // Use a two-sample t-test to determine whether the timing difference between <add> // the benchmarks is statistically significant. <add> // https://wikipedia.org/wiki/Student%27s_t-test#Independent_two-sample_t-test <add> <add> const equalMean = mean(equalBenches); <add> const unequalMean = mean(unequalBenches); <add> <add> const equalLen = equalBenches.length; <add> const unequalLen = unequalBenches.length; <add> <add> const combinedStd = combinedStandardDeviation(equalBenches, unequalBenches); <add> const standardErr = combinedStd * Math.sqrt(1 / equalLen + 1 / unequalLen); <add> <add> return (equalMean - unequalMean) / standardErr; <add>} <add> <add>// Returns the mean of an array <add>function mean(array) { <add> return array.reduce((sum, val) => sum + val, 0) / array.length; <add>} <add> <add>// Returns the sample standard deviation of an array <add>function standardDeviation(array) { <add> const arrMean = mean(array); <add> const total = array.reduce((sum, val) => sum + Math.pow(val - arrMean, 2), 0); <add> return Math.sqrt(total / (array.length - 1)); <add>} <add> <add>// Returns the common standard deviation of two arrays <add>function combinedStandardDeviation(array1, array2) { <add> const sum1 = Math.pow(standardDeviation(array1), 2) * (array1.length - 1); <add> const sum2 = Math.pow(standardDeviation(array2), 2) * (array2.length - 1); <add> return Math.sqrt((sum1 + sum2) / (array1.length + array2.length - 2)); <add>} <add> <add>// Filter large outliers from an array. A 'large outlier' is a value that is at <add>// least 50 times larger than the mean. This prevents the tests from failing <add>// due to the standard deviation increase when a function unexpectedly takes <add>// a very long time to execute. <add>function filterOutliers(array) { <add> const arrMean = mean(array); <add> return array.filter((value) => value / arrMean < 50); <add>} <add> <add>// t_(0.99995, ∞) <add>// i.e. If a given comparison function is indeed timing-safe, the t-test result <add>// has a 99.99% chance to be below this threshold. Unfortunately, this means <add>// that this test will be a bit flakey and will fail 0.01% of the time even if <add>// crypto.timingSafeEqual is working properly. <add>// t-table ref: http://www.sjsu.edu/faculty/gerstman/StatPrimer/t-table.pdf <add>// Note that in reality there are roughly `2 * numTrials - 2` degrees of <add>// freedom, not ∞. However, assuming `numTrials` is large, this doesn't <add>// significantly affect the threshold. <add>const T_THRESHOLD = 3.892; <add> <add>const t = getTValue(crypto.timingSafeEqual); <add>assert( <add> Math.abs(t) < T_THRESHOLD, <add> `timingSafeEqual should not leak information from its execution time (t=${t})` <add>); <add> <add>// As a sanity check to make sure the statistical tests are working, run the <add>// same benchmarks again, this time with an unsafe comparison function. In this <add>// case the t-value should be above the threshold. <add>const unsafeCompare = (bufA, bufB) => bufA.equals(bufB); <add>const t2 = getTValue(unsafeCompare); <add>assert( <add> Math.abs(t2) > T_THRESHOLD, <add> `Buffer#equals should leak information from its execution time (t=${t2})` <add>); <ide><path>test/sequential/test-crypto-timing-safe-equal.js <ide> assert.throws(function() { <ide> assert.throws(function() { <ide> crypto.timingSafeEqual(Buffer.from([1, 2]), 'not a buffer'); <ide> }, 'should throw if the second argument is not a buffer'); <del> <del>function getTValue(compareFunc) { <del> const numTrials = 10000; <del> const testBufferSize = 10000; <del> // Perform benchmarks to verify that timingSafeEqual is actually timing-safe. <del> <del> const rawEqualBenches = Array(numTrials); <del> const rawUnequalBenches = Array(numTrials); <del> <del> for (let i = 0; i < numTrials; i++) { <del> <del> // The `runEqualBenchmark` and `runUnequalBenchmark` functions are <del> // intentionally redefined on every iteration of this loop, to avoid <del> // timing inconsistency. <del> function runEqualBenchmark(compareFunc, bufferA, bufferB) { <del> const startTime = process.hrtime(); <del> const result = compareFunc(bufferA, bufferB); <del> const endTime = process.hrtime(startTime); <del> <del> // Ensure that the result of the function call gets used, so it doesn't <del> // get discarded due to engine optimizations. <del> assert.strictEqual(result, true); <del> return endTime[0] * 1e9 + endTime[1]; <del> } <del> <del> // This is almost the same as the runEqualBenchmark function, but it's <del> // duplicated to avoid timing issues with V8 optimization/inlining. <del> function runUnequalBenchmark(compareFunc, bufferA, bufferB) { <del> const startTime = process.hrtime(); <del> const result = compareFunc(bufferA, bufferB); <del> const endTime = process.hrtime(startTime); <del> <del> assert.strictEqual(result, false); <del> return endTime[0] * 1e9 + endTime[1]; <del> } <del> <del> if (i % 2) { <del> const bufferA1 = Buffer.alloc(testBufferSize, 'A'); <del> const bufferB = Buffer.alloc(testBufferSize, 'B'); <del> const bufferA2 = Buffer.alloc(testBufferSize, 'A'); <del> const bufferC = Buffer.alloc(testBufferSize, 'C'); <del> <del> // First benchmark: comparing two equal buffers <del> rawEqualBenches[i] = runEqualBenchmark(compareFunc, bufferA1, bufferA2); <del> <del> // Second benchmark: comparing two unequal buffers <del> rawUnequalBenches[i] = runUnequalBenchmark(compareFunc, bufferB, bufferC); <del> } else { <del> // Swap the order of the benchmarks every second iteration, to avoid any <del> // patterns caused by memory usage. <del> const bufferB = Buffer.alloc(testBufferSize, 'B'); <del> const bufferA1 = Buffer.alloc(testBufferSize, 'A'); <del> const bufferC = Buffer.alloc(testBufferSize, 'C'); <del> const bufferA2 = Buffer.alloc(testBufferSize, 'A'); <del> rawUnequalBenches[i] = runUnequalBenchmark(compareFunc, bufferB, bufferC); <del> rawEqualBenches[i] = runEqualBenchmark(compareFunc, bufferA1, bufferA2); <del> } <del> } <del> <del> const equalBenches = filterOutliers(rawEqualBenches); <del> const unequalBenches = filterOutliers(rawUnequalBenches); <del> <del> // Use a two-sample t-test to determine whether the timing difference between <del> // the benchmarks is statistically significant. <del> // https://wikipedia.org/wiki/Student%27s_t-test#Independent_two-sample_t-test <del> <del> const equalMean = mean(equalBenches); <del> const unequalMean = mean(unequalBenches); <del> <del> const equalLen = equalBenches.length; <del> const unequalLen = unequalBenches.length; <del> <del> const combinedStd = combinedStandardDeviation(equalBenches, unequalBenches); <del> const standardErr = combinedStd * Math.sqrt(1 / equalLen + 1 / unequalLen); <del> <del> return (equalMean - unequalMean) / standardErr; <del>} <del> <del>// Returns the mean of an array <del>function mean(array) { <del> return array.reduce((sum, val) => sum + val, 0) / array.length; <del>} <del> <del>// Returns the sample standard deviation of an array <del>function standardDeviation(array) { <del> const arrMean = mean(array); <del> const total = array.reduce((sum, val) => sum + Math.pow(val - arrMean, 2), 0); <del> return Math.sqrt(total / (array.length - 1)); <del>} <del> <del>// Returns the common standard deviation of two arrays <del>function combinedStandardDeviation(array1, array2) { <del> const sum1 = Math.pow(standardDeviation(array1), 2) * (array1.length - 1); <del> const sum2 = Math.pow(standardDeviation(array2), 2) * (array2.length - 1); <del> return Math.sqrt((sum1 + sum2) / (array1.length + array2.length - 2)); <del>} <del> <del>// Filter large outliers from an array. A 'large outlier' is a value that is at <del>// least 50 times larger than the mean. This prevents the tests from failing <del>// due to the standard deviation increase when a function unexpectedly takes <del>// a very long time to execute. <del>function filterOutliers(array) { <del> const arrMean = mean(array); <del> return array.filter((value) => value / arrMean < 50); <del>} <del> <del>// t_(0.99995, ∞) <del>// i.e. If a given comparison function is indeed timing-safe, the t-test result <del>// has a 99.99% chance to be below this threshold. Unfortunately, this means <del>// that this test will be a bit flakey and will fail 0.01% of the time even if <del>// crypto.timingSafeEqual is working properly. <del>// t-table ref: http://www.sjsu.edu/faculty/gerstman/StatPrimer/t-table.pdf <del>// Note that in reality there are roughly `2 * numTrials - 2` degrees of <del>// freedom, not ∞. However, assuming `numTrials` is large, this doesn't <del>// significantly affect the threshold. <del>const T_THRESHOLD = 3.892; <del> <del>const t = getTValue(crypto.timingSafeEqual); <del>assert( <del> Math.abs(t) < T_THRESHOLD, <del> `timingSafeEqual should not leak information from its execution time (t=${t})` <del>); <del> <del>// As a sanity check to make sure the statistical tests are working, run the <del>// same benchmarks again, this time with an unsafe comparison function. In this <del>// case the t-value should be above the threshold. <del>const unsafeCompare = (bufA, bufB) => bufA.equals(bufB); <del>const t2 = getTValue(unsafeCompare); <del>assert( <del> Math.abs(t2) > T_THRESHOLD, <del> `Buffer#equals should leak information from its execution time (t=${t2})` <del>);
3
PHP
PHP
fix method order
5317cb529989e73793a64bbfc3ae9b6ed55ed3fd
<ide><path>src/Illuminate/Database/Query/Grammars/PostgresGrammar.php <ide> protected function compileLock(Builder $query, $value) <ide> return $value ? 'for update' : 'for share'; <ide> } <ide> <add> /** <add> * Compile a "where date" clause. <add> * <add> * @param \Illuminate\Database\Query\Builder $query <add> * @param array $where <add> * @return string <add> */ <add> protected function whereDate(Builder $query, $where) <add> { <add> $value = $this->parameter($where['value']); <add> <add> return $this->wrap($where['column']).' '.$where['operator'].' '.$value.'::date'; <add> } <add> <add> /** <add> * Compile a "where day" clause. <add> * <add> * @param \Illuminate\Database\Query\Builder $query <add> * @param array $where <add> * @return string <add> */ <add> protected function whereDay(Builder $query, $where) <add> { <add> return $this->dateBasedWhere('day', $query, $where); <add> } <add> <add> /** <add> * Compile a "where month" clause. <add> * <add> * @param \Illuminate\Database\Query\Builder $query <add> * @param array $where <add> * @return string <add> */ <add> protected function whereMonth(Builder $query, $where) <add> { <add> return $this->dateBasedWhere('month', $query, $where); <add> } <add> <add> /** <add> * Compile a "where year" clause. <add> * <add> * @param \Illuminate\Database\Query\Builder $query <add> * @param array $where <add> * @return string <add> */ <add> protected function whereYear(Builder $query, $where) <add> { <add> return $this->dateBasedWhere('year', $query, $where); <add> } <add> <add> /** <add> * Compile a date based where clause. <add> * <add> * @param string $type <add> * @param \Illuminate\Database\Query\Builder $query <add> * @param array $where <add> * @return string <add> */ <add> protected function dateBasedWhere($type, Builder $query, $where) <add> { <add> $value = $this->parameter($where['value']); <add> <add> return 'extract('.$type.' from '.$this->wrap($where['column']).') '.$where['operator'].' '.$value; <add> } <add> <ide> /** <ide> * Compile an update statement into SQL. <ide> * <ide> public function compileTruncate(Builder $query) <ide> { <ide> return ['truncate '.$this->wrapTable($query->from).' restart identity' => []]; <ide> } <del> <del> /** <del> * Compile a "where date" clause. <del> * <del> * @param \Illuminate\Database\Query\Builder $query <del> * @param array $where <del> * @return string <del> */ <del> protected function whereDate(Builder $query, $where) <del> { <del> $value = $this->parameter($where['value']); <del> <del> return $this->wrap($where['column']).' '.$where['operator'].' '.$value.'::date'; <del> } <del> <del> /** <del> * Compile a "where day" clause. <del> * <del> * @param \Illuminate\Database\Query\Builder $query <del> * @param array $where <del> * @return string <del> */ <del> protected function whereDay(Builder $query, $where) <del> { <del> return $this->dateBasedWhere('day', $query, $where); <del> } <del> <del> /** <del> * Compile a "where month" clause. <del> * <del> * @param \Illuminate\Database\Query\Builder $query <del> * @param array $where <del> * @return string <del> */ <del> protected function whereMonth(Builder $query, $where) <del> { <del> return $this->dateBasedWhere('month', $query, $where); <del> } <del> <del> /** <del> * Compile a "where year" clause. <del> * <del> * @param \Illuminate\Database\Query\Builder $query <del> * @param array $where <del> * @return string <del> */ <del> protected function whereYear(Builder $query, $where) <del> { <del> return $this->dateBasedWhere('year', $query, $where); <del> } <del> <del> /** <del> * Compile a date based where clause. <del> * <del> * @param string $type <del> * @param \Illuminate\Database\Query\Builder $query <del> * @param array $where <del> * @return string <del> */ <del> protected function dateBasedWhere($type, Builder $query, $where) <del> { <del> $value = $this->parameter($where['value']); <del> <del> return 'extract('.$type.' from '.$this->wrap($where['column']).') '.$where['operator'].' '.$value; <del> } <ide> }
1
Python
Python
fix output shape of the position embedding layer
c93ac621f011ed490a9f19488f115ba2641a5fc7
<ide><path>official/nlp/modeling/layers/position_embedding.py <ide> def call(self, inputs): <ide> seq_length = input_shape[1] <ide> width = input_shape[2] <ide> <del> position_embeddings = tf.expand_dims( <del> tf.slice(self._position_embeddings, [0, 0], [seq_length, width]), <del> axis=0) <add> position_embeddings = tf.slice(self._position_embeddings, <add> [0, 0], <add> [seq_length, width]) <ide> else: <del> position_embeddings = tf.expand_dims(self._position_embeddings, axis=0) <add> position_embeddings = self._position_embeddings <ide> <del> return position_embeddings <add> return tf.broadcast_to(position_embeddings, input_shape)
1
Go
Go
make `errorresponse` implement `error`
6ddd43b589e91fbe0b015745a9fdf78a043361fc
<ide><path>api/types/error_response_ext.go <add>package types <add> <add>// Error returns the error message <add>func (e ErrorResponse) Error() string { <add> return e.Message <add>}
1
Javascript
Javascript
track thenable state in work loop
7572e4931f820ad7c8aa59452ab7a40eb68843fc
<ide><path>packages/react-reconciler/src/ReactFiberHooks.new.js <ide> import { <ide> requestEventTime, <ide> markSkippedUpdateLanes, <ide> isInvalidExecutionContextForEventFunction, <add> getSuspendedThenableState, <ide> } from './ReactFiberWorkLoop.new'; <ide> <ide> import getComponentNameFromFiber from 'react-reconciler/src/getComponentNameFromFiber'; <ide> import { <ide> import {getTreeId} from './ReactFiberTreeContext.new'; <ide> import {now} from './Scheduler'; <ide> import { <add> prepareThenableState, <ide> trackUsedThenable, <ide> getPreviouslyUsedThenableAtIndex, <ide> } from './ReactFiberThenable.new'; <ide> export function renderWithHooks<Props, SecondArg>( <ide> : HooksDispatcherOnUpdate; <ide> } <ide> <add> // If this is a replay, restore the thenable state from the previous attempt. <add> const prevThenableState = getSuspendedThenableState(); <add> prepareThenableState(prevThenableState); <ide> let children = Component(props, secondArg); <ide> <ide> // Check if there was a render phase update <ide> export function renderWithHooks<Props, SecondArg>( <ide> ? HooksDispatcherOnRerenderInDEV <ide> : HooksDispatcherOnRerender; <ide> <add> prepareThenableState(prevThenableState); <ide> children = Component(props, secondArg); <ide> } while (didScheduleRenderPhaseUpdateDuringThisPass); <ide> } <ide><path>packages/react-reconciler/src/ReactFiberHooks.old.js <ide> import { <ide> requestEventTime, <ide> markSkippedUpdateLanes, <ide> isInvalidExecutionContextForEventFunction, <add> getSuspendedThenableState, <ide> } from './ReactFiberWorkLoop.old'; <ide> <ide> import getComponentNameFromFiber from 'react-reconciler/src/getComponentNameFromFiber'; <ide> import { <ide> import {getTreeId} from './ReactFiberTreeContext.old'; <ide> import {now} from './Scheduler'; <ide> import { <add> prepareThenableState, <ide> trackUsedThenable, <ide> getPreviouslyUsedThenableAtIndex, <ide> } from './ReactFiberThenable.old'; <ide> export function renderWithHooks<Props, SecondArg>( <ide> : HooksDispatcherOnUpdate; <ide> } <ide> <add> // If this is a replay, restore the thenable state from the previous attempt. <add> const prevThenableState = getSuspendedThenableState(); <add> prepareThenableState(prevThenableState); <ide> let children = Component(props, secondArg); <ide> <ide> // Check if there was a render phase update <ide> export function renderWithHooks<Props, SecondArg>( <ide> ? HooksDispatcherOnRerenderInDEV <ide> : HooksDispatcherOnRerender; <ide> <add> prepareThenableState(prevThenableState); <ide> children = Component(props, secondArg); <ide> } while (didScheduleRenderPhaseUpdateDuringThisPass); <ide> } <ide><path>packages/react-reconciler/src/ReactFiberThenable.new.js <ide> import type { <ide> import ReactSharedInternals from 'shared/ReactSharedInternals'; <ide> const {ReactCurrentActQueue} = ReactSharedInternals; <ide> <del>let suspendedThenable: Thenable<any> | null = null; <del>let usedThenables: Array<Thenable<any> | void> | null = null; <add>// TODO: Sparse arrays are bad for performance. <add>export opaque type ThenableState = Array<Thenable<any> | void>; <ide> <del>export function isTrackingSuspendedThenable(): boolean { <del> return suspendedThenable !== null; <add>let thenableState: ThenableState | null = null; <add> <add>export function createThenableState(): ThenableState { <add> // The ThenableState is created the first time a component suspends. If it <add> // suspends again, we'll reuse the same state. <add> return []; <add>} <add> <add>export function prepareThenableState(prevThenableState: ThenableState | null) { <add> // This function is called before every function that might suspend <add> // with `use`. Right now, that's only Hooks, but in the future we'll use the <add> // same mechanism for unwrapping promises during reconciliation. <add> thenableState = prevThenableState; <add>} <add> <add>export function getThenableStateAfterSuspending(): ThenableState | null { <add> // Called by the work loop so it can stash the thenable state. It will use <add> // the state to replay the component when the promise resolves. <add> if ( <add> thenableState !== null && <add> // If we only `use`-ed resolved promises, then there is no suspended state <add> // TODO: The only reason we do this is to distinguish between throwing a <add> // promise (old Suspense pattern) versus `use`-ing one. A better solution is <add> // for `use` to throw a special, opaque value instead of a promise. <add> !isThenableStateResolved(thenableState) <add> ) { <add> const state = thenableState; <add> thenableState = null; <add> return state; <add> } <add> return null; <ide> } <ide> <del>export function suspendedThenableDidResolve(): boolean { <del> if (suspendedThenable !== null) { <del> const status = suspendedThenable.status; <add>export function isThenableStateResolved(thenables: ThenableState): boolean { <add> const lastThenable = thenables[thenables.length - 1]; <add> if (lastThenable !== undefined) { <add> const status = lastThenable.status; <ide> return status === 'fulfilled' || status === 'rejected'; <ide> } <del> return false; <add> return true; <ide> } <ide> <ide> export function trackUsedThenable<T>(thenable: Thenable<T>, index: number) { <ide> if (__DEV__ && ReactCurrentActQueue.current !== null) { <ide> ReactCurrentActQueue.didUsePromise = true; <ide> } <ide> <del> if (usedThenables === null) { <del> usedThenables = [thenable]; <add> if (thenableState === null) { <add> thenableState = [thenable]; <ide> } else { <del> usedThenables[index] = thenable; <add> thenableState[index] = thenable; <ide> } <ide> <del> suspendedThenable = thenable; <del> <ide> // We use an expando to track the status and result of a thenable so that we <ide> // can synchronously unwrap the value. Think of this as an extension of the <ide> // Promise API, or a custom interface that is a superset of Thenable. <ide> export function trackUsedThenable<T>(thenable: Thenable<T>, index: number) { <ide> // this thenable, because if we keep trying it will likely infinite loop <ide> // without ever resolving. <ide> // TODO: Log a warning? <del> suspendedThenable = null; <ide> break; <ide> default: { <ide> if (typeof thenable.status === 'string') { <ide> export function trackUsedThenable<T>(thenable: Thenable<T>, index: number) { <ide> } <ide> } <ide> <del>export function resetWakeableStateAfterEachAttempt() { <del> suspendedThenable = null; <del>} <del> <del>export function resetThenableStateOnCompletion() { <del> usedThenables = null; <del>} <del> <ide> export function getPreviouslyUsedThenableAtIndex<T>( <ide> index: number, <ide> ): Thenable<T> | null { <del> if (usedThenables !== null) { <del> const thenable = usedThenables[index]; <add> if (thenableState !== null) { <add> const thenable = thenableState[index]; <ide> if (thenable !== undefined) { <ide> return thenable; <ide> } <ide><path>packages/react-reconciler/src/ReactFiberThenable.old.js <ide> import type { <ide> import ReactSharedInternals from 'shared/ReactSharedInternals'; <ide> const {ReactCurrentActQueue} = ReactSharedInternals; <ide> <del>let suspendedThenable: Thenable<any> | null = null; <del>let usedThenables: Array<Thenable<any> | void> | null = null; <add>// TODO: Sparse arrays are bad for performance. <add>export opaque type ThenableState = Array<Thenable<any> | void>; <ide> <del>export function isTrackingSuspendedThenable(): boolean { <del> return suspendedThenable !== null; <add>let thenableState: ThenableState | null = null; <add> <add>export function createThenableState(): ThenableState { <add> // The ThenableState is created the first time a component suspends. If it <add> // suspends again, we'll reuse the same state. <add> return []; <add>} <add> <add>export function prepareThenableState(prevThenableState: ThenableState | null) { <add> // This function is called before every function that might suspend <add> // with `use`. Right now, that's only Hooks, but in the future we'll use the <add> // same mechanism for unwrapping promises during reconciliation. <add> thenableState = prevThenableState; <add>} <add> <add>export function getThenableStateAfterSuspending(): ThenableState | null { <add> // Called by the work loop so it can stash the thenable state. It will use <add> // the state to replay the component when the promise resolves. <add> if ( <add> thenableState !== null && <add> // If we only `use`-ed resolved promises, then there is no suspended state <add> // TODO: The only reason we do this is to distinguish between throwing a <add> // promise (old Suspense pattern) versus `use`-ing one. A better solution is <add> // for `use` to throw a special, opaque value instead of a promise. <add> !isThenableStateResolved(thenableState) <add> ) { <add> const state = thenableState; <add> thenableState = null; <add> return state; <add> } <add> return null; <ide> } <ide> <del>export function suspendedThenableDidResolve(): boolean { <del> if (suspendedThenable !== null) { <del> const status = suspendedThenable.status; <add>export function isThenableStateResolved(thenables: ThenableState): boolean { <add> const lastThenable = thenables[thenables.length - 1]; <add> if (lastThenable !== undefined) { <add> const status = lastThenable.status; <ide> return status === 'fulfilled' || status === 'rejected'; <ide> } <del> return false; <add> return true; <ide> } <ide> <ide> export function trackUsedThenable<T>(thenable: Thenable<T>, index: number) { <ide> if (__DEV__ && ReactCurrentActQueue.current !== null) { <ide> ReactCurrentActQueue.didUsePromise = true; <ide> } <ide> <del> if (usedThenables === null) { <del> usedThenables = [thenable]; <add> if (thenableState === null) { <add> thenableState = [thenable]; <ide> } else { <del> usedThenables[index] = thenable; <add> thenableState[index] = thenable; <ide> } <ide> <del> suspendedThenable = thenable; <del> <ide> // We use an expando to track the status and result of a thenable so that we <ide> // can synchronously unwrap the value. Think of this as an extension of the <ide> // Promise API, or a custom interface that is a superset of Thenable. <ide> export function trackUsedThenable<T>(thenable: Thenable<T>, index: number) { <ide> // this thenable, because if we keep trying it will likely infinite loop <ide> // without ever resolving. <ide> // TODO: Log a warning? <del> suspendedThenable = null; <ide> break; <ide> default: { <ide> if (typeof thenable.status === 'string') { <ide> export function trackUsedThenable<T>(thenable: Thenable<T>, index: number) { <ide> } <ide> } <ide> <del>export function resetWakeableStateAfterEachAttempt() { <del> suspendedThenable = null; <del>} <del> <del>export function resetThenableStateOnCompletion() { <del> usedThenables = null; <del>} <del> <ide> export function getPreviouslyUsedThenableAtIndex<T>( <ide> index: number, <ide> ): Thenable<T> | null { <del> if (usedThenables !== null) { <del> const thenable = usedThenables[index]; <add> if (thenableState !== null) { <add> const thenable = thenableState[index]; <ide> if (thenable !== undefined) { <ide> return thenable; <ide> } <ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.new.js <ide> import type { <ide> TransitionAbort, <ide> } from './ReactFiberTracingMarkerComponent.new'; <ide> import type {OffscreenInstance} from './ReactFiberOffscreenComponent'; <add>import type {ThenableState} from './ReactFiberThenable.new'; <ide> <ide> import { <ide> warnAboutDeprecatedLifecycles, <ide> import { <ide> } from './ReactFiberAct.new'; <ide> import {processTransitionCallbacks} from './ReactFiberTracingMarkerComponent.new'; <ide> import { <del> resetWakeableStateAfterEachAttempt, <del> resetThenableStateOnCompletion, <del> suspendedThenableDidResolve, <del> isTrackingSuspendedThenable, <add> getThenableStateAfterSuspending, <add> isThenableStateResolved, <ide> } from './ReactFiberThenable.new'; <ide> import {schedulePostPaintCallback} from './ReactPostPaintCallback'; <ide> <ide> let workInProgressRootRenderLanes: Lanes = NoLanes; <ide> // immediately instead of unwinding the stack. <ide> let workInProgressIsSuspended: boolean = false; <ide> let workInProgressThrownValue: mixed = null; <add>let workInProgressSuspendedThenableState: ThenableState | null = null; <ide> <ide> // Whether a ping listener was attached during this render. This is slightly <ide> // different that whether something suspended, because we don't add multiple <ide> function prepareFreshStack(root: FiberRoot, lanes: Lanes): Fiber { <ide> ); <ide> interruptedWork = interruptedWork.return; <ide> } <del> resetWakeableStateAfterEachAttempt(); <del> resetThenableStateOnCompletion(); <ide> } <ide> workInProgressRoot = root; <ide> const rootWorkInProgress = createWorkInProgress(root.current, null); <ide> workInProgress = rootWorkInProgress; <ide> workInProgressRootRenderLanes = renderLanes = lanes; <ide> workInProgressIsSuspended = false; <ide> workInProgressThrownValue = null; <add> workInProgressSuspendedThenableState = null; <ide> workInProgressRootDidAttachPingListener = false; <ide> workInProgressRootExitStatus = RootInProgress; <ide> workInProgressRootFatalError = null; <ide> function handleThrow(root, thrownValue): void { <ide> // as suspending the execution of the work loop. <ide> workInProgressIsSuspended = true; <ide> workInProgressThrownValue = thrownValue; <add> workInProgressSuspendedThenableState = getThenableStateAfterSuspending(); <ide> <ide> const erroredWork = workInProgress; <ide> if (erroredWork === null) { <ide> function renderRootConcurrent(root: FiberRoot, lanes: Lanes) { <ide> break; <ide> } catch (thrownValue) { <ide> handleThrow(root, thrownValue); <del> if (isTrackingSuspendedThenable()) { <add> if (workInProgressSuspendedThenableState !== null) { <ide> // If this fiber just suspended, it's possible the data is already <ide> // cached. Yield to the main thread to give it a chance to ping. If <ide> // it does, we can retry immediately without unwinding the stack. <ide> function resumeSuspendedUnitOfWork( <ide> // instead of unwinding the stack. It's a separate function to keep the <ide> // additional logic out of the work loop's hot path. <ide> <del> const wasPinged = suspendedThenableDidResolve(); <del> resetWakeableStateAfterEachAttempt(); <add> const wasPinged = <add> workInProgressSuspendedThenableState !== null && <add> isThenableStateResolved(workInProgressSuspendedThenableState); <ide> <ide> if (!wasPinged) { <ide> // The thenable wasn't pinged. Return to the normal work loop. This will <ide> // unwind the stack, and potentially result in showing a fallback. <del> resetThenableStateOnCompletion(); <add> workInProgressSuspendedThenableState = null; <ide> <ide> const returnFiber = unitOfWork.return; <ide> if (returnFiber === null || workInProgressRoot === null) { <ide> function resumeSuspendedUnitOfWork( <ide> // The begin phase finished successfully without suspending. Reset the state <ide> // used to track the fiber while it was suspended. Then return to the normal <ide> // work loop. <del> resetThenableStateOnCompletion(); <add> workInProgressSuspendedThenableState = null; <ide> <ide> resetCurrentDebugFiberInDEV(); <ide> unitOfWork.memoizedProps = unitOfWork.pendingProps; <ide> function resumeSuspendedUnitOfWork( <ide> ReactCurrentOwner.current = null; <ide> } <ide> <add>export function getSuspendedThenableState(): ThenableState | null { <add> return workInProgressSuspendedThenableState; <add>} <add> <ide> function completeUnitOfWork(unitOfWork: Fiber): void { <ide> // Attempt to complete the current unit of work, then move to the next <ide> // sibling. If there are no more siblings, return to the parent fiber. <ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.old.js <ide> import type { <ide> TransitionAbort, <ide> } from './ReactFiberTracingMarkerComponent.old'; <ide> import type {OffscreenInstance} from './ReactFiberOffscreenComponent'; <add>import type {ThenableState} from './ReactFiberThenable.old'; <ide> <ide> import { <ide> warnAboutDeprecatedLifecycles, <ide> import { <ide> } from './ReactFiberAct.old'; <ide> import {processTransitionCallbacks} from './ReactFiberTracingMarkerComponent.old'; <ide> import { <del> resetWakeableStateAfterEachAttempt, <del> resetThenableStateOnCompletion, <del> suspendedThenableDidResolve, <del> isTrackingSuspendedThenable, <add> getThenableStateAfterSuspending, <add> isThenableStateResolved, <ide> } from './ReactFiberThenable.old'; <ide> import {schedulePostPaintCallback} from './ReactPostPaintCallback'; <ide> <ide> let workInProgressRootRenderLanes: Lanes = NoLanes; <ide> // immediately instead of unwinding the stack. <ide> let workInProgressIsSuspended: boolean = false; <ide> let workInProgressThrownValue: mixed = null; <add>let workInProgressSuspendedThenableState: ThenableState | null = null; <ide> <ide> // Whether a ping listener was attached during this render. This is slightly <ide> // different that whether something suspended, because we don't add multiple <ide> function prepareFreshStack(root: FiberRoot, lanes: Lanes): Fiber { <ide> ); <ide> interruptedWork = interruptedWork.return; <ide> } <del> resetWakeableStateAfterEachAttempt(); <del> resetThenableStateOnCompletion(); <ide> } <ide> workInProgressRoot = root; <ide> const rootWorkInProgress = createWorkInProgress(root.current, null); <ide> workInProgress = rootWorkInProgress; <ide> workInProgressRootRenderLanes = renderLanes = lanes; <ide> workInProgressIsSuspended = false; <ide> workInProgressThrownValue = null; <add> workInProgressSuspendedThenableState = null; <ide> workInProgressRootDidAttachPingListener = false; <ide> workInProgressRootExitStatus = RootInProgress; <ide> workInProgressRootFatalError = null; <ide> function handleThrow(root, thrownValue): void { <ide> // as suspending the execution of the work loop. <ide> workInProgressIsSuspended = true; <ide> workInProgressThrownValue = thrownValue; <add> workInProgressSuspendedThenableState = getThenableStateAfterSuspending(); <ide> <ide> const erroredWork = workInProgress; <ide> if (erroredWork === null) { <ide> function renderRootConcurrent(root: FiberRoot, lanes: Lanes) { <ide> break; <ide> } catch (thrownValue) { <ide> handleThrow(root, thrownValue); <del> if (isTrackingSuspendedThenable()) { <add> if (workInProgressSuspendedThenableState !== null) { <ide> // If this fiber just suspended, it's possible the data is already <ide> // cached. Yield to the main thread to give it a chance to ping. If <ide> // it does, we can retry immediately without unwinding the stack. <ide> function resumeSuspendedUnitOfWork( <ide> // instead of unwinding the stack. It's a separate function to keep the <ide> // additional logic out of the work loop's hot path. <ide> <del> const wasPinged = suspendedThenableDidResolve(); <del> resetWakeableStateAfterEachAttempt(); <add> const wasPinged = <add> workInProgressSuspendedThenableState !== null && <add> isThenableStateResolved(workInProgressSuspendedThenableState); <ide> <ide> if (!wasPinged) { <ide> // The thenable wasn't pinged. Return to the normal work loop. This will <ide> // unwind the stack, and potentially result in showing a fallback. <del> resetThenableStateOnCompletion(); <add> workInProgressSuspendedThenableState = null; <ide> <ide> const returnFiber = unitOfWork.return; <ide> if (returnFiber === null || workInProgressRoot === null) { <ide> function resumeSuspendedUnitOfWork( <ide> // The begin phase finished successfully without suspending. Reset the state <ide> // used to track the fiber while it was suspended. Then return to the normal <ide> // work loop. <del> resetThenableStateOnCompletion(); <add> workInProgressSuspendedThenableState = null; <ide> <ide> resetCurrentDebugFiberInDEV(); <ide> unitOfWork.memoizedProps = unitOfWork.pendingProps; <ide> function resumeSuspendedUnitOfWork( <ide> ReactCurrentOwner.current = null; <ide> } <ide> <add>export function getSuspendedThenableState(): ThenableState | null { <add> return workInProgressSuspendedThenableState; <add>} <add> <ide> function completeUnitOfWork(unitOfWork: Fiber): void { <ide> // Attempt to complete the current unit of work, then move to the next <ide> // sibling. If there are no more siblings, return to the parent fiber. <ide><path>packages/react-reconciler/src/__tests__/ReactThenable-test.js <ide> let use; <ide> let Suspense; <ide> let startTransition; <ide> <del>describe('ReactWakeable', () => { <add>describe('ReactThenable', () => { <ide> beforeEach(() => { <ide> jest.resetModules(); <ide> <ide> describe('ReactWakeable', () => { <ide> expect(Scheduler).toHaveYielded(['Oops!', 'Oops!']); <ide> }); <ide> <add> // @gate enableUseHook <add> test('use(promise) in multiple components', async () => { <add> // This tests that the state for tracking promises is reset per component. <add> const promiseA = Promise.resolve('A'); <add> const promiseB = Promise.resolve('B'); <add> const promiseC = Promise.resolve('C'); <add> const promiseD = Promise.resolve('D'); <add> <add> function Child({prefix}) { <add> return <Text text={prefix + use(promiseC) + use(promiseD)} />; <add> } <add> <add> function Parent() { <add> return <Child prefix={use(promiseA) + use(promiseB)} />; <add> } <add> <add> function App() { <add> return ( <add> <Suspense fallback={<Text text="Loading..." />}> <add> <Parent /> <add> </Suspense> <add> ); <add> } <add> <add> const root = ReactNoop.createRoot(); <add> await act(async () => { <add> startTransition(() => { <add> root.render(<App />); <add> }); <add> }); <add> expect(Scheduler).toHaveYielded(['ABCD']); <add> expect(root).toMatchRenderedOutput('ABCD'); <add> }); <add> <add> // @gate enableUseHook <add> test('use(promise) in multiple sibling components', async () => { <add> // This tests that the state for tracking promises is reset per component. <add> <add> const promiseA = {then: () => {}, status: 'pending', value: null}; <add> const promiseB = {then: () => {}, status: 'pending', value: null}; <add> const promiseC = {then: () => {}, status: 'fulfilled', value: 'C'}; <add> const promiseD = {then: () => {}, status: 'fulfilled', value: 'D'}; <add> <add> function Sibling1({prefix}) { <add> return <Text text={use(promiseA) + use(promiseB)} />; <add> } <add> <add> function Sibling2() { <add> return <Text text={use(promiseC) + use(promiseD)} />; <add> } <add> <add> function App() { <add> return ( <add> <Suspense fallback={<Text text="Loading..." />}> <add> <Sibling1 /> <add> <Sibling2 /> <add> </Suspense> <add> ); <add> } <add> <add> const root = ReactNoop.createRoot(); <add> await act(async () => { <add> startTransition(() => { <add> root.render(<App />); <add> }); <add> }); <add> expect(Scheduler).toHaveYielded(['CD', 'Loading...']); <add> expect(root).toMatchRenderedOutput('Loading...'); <add> }); <add> <ide> // @gate enableUseHook <ide> test('erroring in the same component as an uncached promise does not result in an infinite loop', async () => { <ide> class ErrorBoundary extends React.Component {
7
Ruby
Ruby
hoist assignment to simplify a conditional
85feea33c003748740f3a3dc1e410549afa50e95
<ide><path>Library/Homebrew/formula.rb <ide> def test_defined? <ide> # Throws if there's an error <ide> def system cmd, *args <ide> removed_ENV_variables = {} <add> rd, wr = IO.pipe <ide> <ide> # remove "boring" arguments so that the important ones are more likely to <ide> # be shown considering that we trim long ohai lines to the terminal width <ide> def system cmd, *args <ide> logfn = "#{logd}/%02d.%s" % [@exec_count, File.basename(cmd).split(' ').first] <ide> mkdir_p(logd) <ide> <del> rd, wr = IO.pipe <ide> fork do <ide> ENV['HOMEBREW_CC_LOG_PATH'] = logfn <ide> rd.close <ide> def system cmd, *args <ide> end <ide> end <ide> ensure <del> rd.close if rd and not rd.closed? <add> rd.close unless rd.closed? <ide> ENV.update(removed_ENV_variables) <ide> end <ide>
1
Text
Text
add lxe as collaborator
96597bc5927c57737c3bea943dd163d69ac76a96
<ide><path>README.md <ide> information about the governance of the io.js project, see <ide> * **Vladimir Kurchatkin** ([@vkurchatkin](https://github.com/vkurchatkin)) &lt;vladimir.kurchatkin@gmail.com&gt; <ide> * **Nikolai Vavilov** ([@seishun](https://github.com/seishun)) &lt;vvnicholas@gmail.com&gt; <ide> * **Nicu Micleușanu** ([@micnic](https://github.com/micnic)) &lt;micnic90@gmail.com&gt; <add>* **Aleksey Smolenchuk** ([@lxe](https://github.com/lxe)) &lt;lxe@lxe.co&gt; <ide> <ide> Collaborators follow the [COLLABORATOR_GUIDE.md](./COLLABORATOR_GUIDE.md) in <ide> maintaining the io.js project.
1
Javascript
Javascript
fix real world to be case insensitive
e64573ecf9d470b41b476916e7375137863bb70d
<ide><path>examples/real-world/containers/RepoPage.js <ide> RepoPage.propTypes = { <ide> } <ide> <ide> function mapStateToProps(state, ownProps) { <del> const { login, name } = ownProps.params <add> // We need to lower case the login/name due to the way GitHub's API behaves. <add> // Have a look at ../middleware/api.js for more details. <add> const login = ownProps.params.login.toLowerCase() <add> const name = ownProps.params.name.toLowerCase() <add> <ide> const { <ide> pagination: { stargazersByRepo }, <ide> entities: { users, repos } <ide><path>examples/real-world/containers/UserPage.js <ide> UserPage.propTypes = { <ide> } <ide> <ide> function mapStateToProps(state, ownProps) { <del> const { login } = ownProps.params <add> // We need to lower case the login due to the way GitHub's API behaves. <add> // Have a look at ../middleware/api.js for more details. <add> const login = ownProps.params.login.toLowerCase() <add> <ide> const { <ide> pagination: { starredByUser }, <ide> entities: { users, repos } <ide><path>examples/real-world/middleware/api.js <ide> function callApi(endpoint, schema) { <ide> <ide> // Read more about Normalizr: https://github.com/gaearon/normalizr <ide> <add>// GitHub's API may return results with uppercase letters while the query <add>// doesn't contain any. For example, "someuser" could result in "SomeUser" <add>// leading to a frozen UI as it wouldn't find "someuser" in the entities. <add>// That's why we're forcing lower cases down there. <add> <ide> const userSchema = new Schema('users', { <del> idAttribute: 'login' <add> idAttribute: user => user.login.toLowerCase() <ide> }) <ide> <ide> const repoSchema = new Schema('repos', { <del> idAttribute: 'fullName' <add> idAttribute: repo => repo.fullName.toLowerCase() <ide> }) <ide> <ide> repoSchema.define({
3
Text
Text
remove internal link in orbit readme
9d9456d221edd5f1e886d06b2599f6460e8de3e4
<ide><path>orbit/README.md <ide> the inner training loop. It integrates with `tf.distribute` seamlessly and <ide> supports running on different device types (CPU, GPU, and TPU). The core code is <ide> intended to be easy to read and fork. <ide> <del>See our [g3doc](g3doc) at go/orbit-trainer for additional documentation. <del> <ide> [custom_training]: https://www.tensorflow.org/tutorials/distribute/custom_training
1
Ruby
Ruby
remove duplicate line
537a07b42d1e419cab678d68710ca12ce00a8f0c
<ide><path>Library/Homebrew/utils.rb <ide> require "utils/repology" <ide> require "utils/svn" <ide> require "utils/tty" <del>require "utils/repology" <ide> require "tap_constants" <ide> require "time" <ide>
1
PHP
PHP
reduce 5-level if cases to 2 levels
5e0e85073337620fbd5e9c3ca7d9aefda491e709
<ide><path>lib/Cake/Model/CakeSchema.php <ide> public function read($options = array()) { <ide> continue; <ide> } <ide> <del> $db = $Object->getDataSource(); <del> if (is_object($Object) && $Object->useTable !== false) { <del> $fulltable = $table = $db->fullTableName($Object, false, false); <del> if ($prefix && strpos($table, $prefix) !== 0) { <add> $fulltable = $table = $db->fullTableName($Object, false, false); <add> if ($prefix && strpos($table, $prefix) !== 0) { <add> continue; <add> } <add> if (!is_object($Object) || $Object->useTable === false) { <add> continue; <add> } <add> if (!in_array($fulltable, $currentTables)) { <add> continue; <add> } <add> <add> $table = $this->_noPrefixTable($prefix, $table); <add> <add> $key = array_search($fulltable, $currentTables); <add> if (empty($tables[$table])) { <add> $tables[$table] = $this->_columns($Object); <add> $tables[$table]['indexes'] = $db->index($Object); <add> $tables[$table]['tableParameters'] = $db->readTableParameters($fulltable); <add> unset($currentTables[$key]); <add> } <add> if (empty($Object->hasAndBelongsToMany)) { <add> continue; <add> } <add> foreach ($Object->hasAndBelongsToMany as $Assoc => $assocData) { <add> if (isset($assocData['with'])) { <add> $class = $assocData['with']; <add> } <add> if (!is_object($Object->$class)) { <ide> continue; <ide> } <del> $table = $this->_noPrefixTable($prefix, $table); <del> <del> if (in_array($fulltable, $currentTables)) { <del> $key = array_search($fulltable, $currentTables); <del> if (empty($tables[$table])) { <del> $tables[$table] = $this->_columns($Object); <del> $tables[$table]['indexes'] = $db->index($Object); <del> $tables[$table]['tableParameters'] = $db->readTableParameters($fulltable); <del> unset($currentTables[$key]); <del> } <del> if (!empty($Object->hasAndBelongsToMany)) { <del> foreach ($Object->hasAndBelongsToMany as $Assoc => $assocData) { <del> if (isset($assocData['with'])) { <del> $class = $assocData['with']; <del> } <del> if (is_object($Object->$class)) { <del> $withTable = $db->fullTableName($Object->$class, false, false); <del> if ($prefix && strpos($withTable, $prefix) !== 0) { <del> continue; <del> } <del> if (in_array($withTable, $currentTables)) { <del> $key = array_search($withTable, $currentTables); <del> $noPrefixWith = $this->_noPrefixTable($prefix, $withTable); <del> <del> $tables[$noPrefixWith] = $this->_columns($Object->$class); <del> $tables[$noPrefixWith]['indexes'] = $db->index($Object->$class); <del> $tables[$noPrefixWith]['tableParameters'] = $db->readTableParameters($withTable); <del> unset($currentTables[$key]); <del> } <del> } <del> } <del> } <add> $withTable = $db->fullTableName($Object->$class, false, false); <add> if ($prefix && strpos($withTable, $prefix) !== 0) { <add> continue; <add> } <add> if (in_array($withTable, $currentTables)) { <add> $key = array_search($withTable, $currentTables); <add> $noPrefixWith = $this->_noPrefixTable($prefix, $withTable); <add> <add> $tables[$noPrefixWith] = $this->_columns($Object->$class); <add> $tables[$noPrefixWith]['indexes'] = $db->index($Object->$class); <add> $tables[$noPrefixWith]['tableParameters'] = $db->readTableParameters($withTable); <add> unset($currentTables[$key]); <ide> } <ide> } <ide> }
1
PHP
PHP
fix notice in cakesession
864f5e06f69afe93918ba8d0fe3403a8fc11f549
<ide><path>lib/Cake/Model/Datasource/CakeSession.php <ide> protected static function _validAgentAndTime() { <ide> $config = self::read('Config'); <ide> $validAgent = ( <ide> Configure::read('Session.checkAgent') === false || <del> self::$_userAgent == $config['userAgent'] <add> isset($config['userAgent']) && self::$_userAgent === $config['userAgent'] <ide> ); <ide> return ($validAgent && self::$time <= $config['time']); <ide> }
1
Javascript
Javascript
fix potential deopt while reading arguments
96f80d27be74cead08e8a21d8ccadd162e05c111
<ide><path>packages/container/lib/container.js <ide> function areInjectionsDynamic(injections) { <ide> return !!injections._dynamic; <ide> } <ide> <del>function buildInjections(container) { <add>function buildInjections(/* container, ...injections */) { <ide> var hash = {}; <ide> <ide> if (arguments.length > 1) { <del> var injectionArgs = Array.prototype.slice.call(arguments, 1); <add> var container = arguments[0]; <ide> var injections = []; <ide> var injection; <ide> <del> for (var i = 0, l = injectionArgs.length; i < l; i++) { <del> if (injectionArgs[i]) { <del> injections = injections.concat(injectionArgs[i]); <add> for (var i = 1, l = arguments.length; i < l; i++) { <add> if (arguments[i]) { <add> injections = injections.concat(arguments[i]); <ide> } <ide> } <ide>
1
Javascript
Javascript
put createroot export under a feature flag
1e35f2b282a20b41000e6b048fa5a16e147d930b
<ide><path>packages/react-cs-renderer/src/ReactNativeCSFeatureFlags.js <ide> var ReactNativeCSFeatureFlags: FeatureFlags = { <ide> enableAsyncSubtreeAPI: true, <ide> enableAsyncSchedulingByDefaultInReactDOM: false, <ide> enableReactFragment: false, <add> enableCreateRoot: false, <ide> // React Native CS uses persistent reconciler. <ide> enableMutatingReconciler: false, <ide> enableNoopReconciler: false, <ide><path>packages/react-dom/src/__tests__/ReactDOMRoot-test.js <ide> <ide> 'use strict'; <ide> <add>require('shared/ReactFeatureFlags').enableCreateRoot = true; <ide> var React = require('react'); <ide> var ReactDOM = require('react-dom'); <ide> var ReactDOMServer = require('react-dom/server'); <ide><path>packages/react-dom/src/client/ReactDOM.js <ide> ReactRoot.prototype.unmount = function(callback) { <ide> DOMRenderer.updateContainer(null, root, null, callback); <ide> }; <ide> <del>var ReactDOM = { <del> createRoot(container: DOMContainer, options?: RootOptions): ReactRootNode { <del> const hydrate = options != null && options.hydrate === true; <del> return new ReactRoot(container, hydrate); <del> }, <del> <add>var ReactDOM: Object = { <ide> createPortal, <ide> <ide> findDOMNode( <ide> var ReactDOM = { <ide> }, <ide> }; <ide> <add>if (ReactFeatureFlags.enableCreateRoot) { <add> ReactDOM.createRoot = function createRoot( <add> container: DOMContainer, <add> options?: RootOptions, <add> ): ReactRootNode { <add> const hydrate = options != null && options.hydrate === true; <add> return new ReactRoot(container, hydrate); <add> }; <add>} <add> <ide> const foundDevTools = injectInternals({ <ide> findFiberByHostInstance: ReactDOMComponentTree.getClosestInstanceFromNode, <ide> findHostInstanceByFiber: DOMRenderer.findHostInstance, <ide><path>packages/shared/ReactFeatureFlags.js <ide> export type FeatureFlags = {| <ide> enableNoopReconciler: boolean, <ide> enablePersistentReconciler: boolean, <ide> enableReactFragment: boolean, <add> enableCreateRoot: boolean, <ide> |}; <ide> <ide> var ReactFeatureFlags: FeatureFlags = { <ide> var ReactFeatureFlags: FeatureFlags = { <ide> enablePersistentReconciler: false, <ide> // Exports React.Fragment <ide> enableReactFragment: false, <add> // Exports ReactDOM.createRoot <add> enableCreateRoot: false, <ide> }; <ide> <ide> if (__DEV__) {
4
Text
Text
wrap long lines in http.request
4d55d1611db3241c8bfb177189373e4e2c928788
<ide><path>doc/api/http.md <ide> added: v0.3.6 <ide> <ide> * `options` {Object} <ide> * `protocol` {String} Protocol to use. Defaults to `'http:'`. <del> * `host` {String} A domain name or IP address of the server to issue the request to. <del> Defaults to `'localhost'`. <del> * `hostname` {String} Alias for `host`. To support [`url.parse()`][] `hostname` is <del> preferred over `host`. <del> * `family` {Number} IP address family to use when resolving `host` and `hostname`. <del> Valid values are `4` or `6`. When unspecified, both IP v4 and v6 will be <del> used. <add> * `host` {String} A domain name or IP address of the server to issue the <add> request to. Defaults to `'localhost'`. <add> * `hostname` {String} Alias for `host`. To support [`url.parse()`][], <add> `hostname` is preferred over `host`. <add> * `family` {Number} IP address family to use when resolving `host` and <add> `hostname`. Valid values are `4` or `6`. When unspecified, both IP v4 and <add> v6 will be used. <ide> * `port` {Number} Port of remote server. Defaults to 80. <ide> * `localAddress` {String} Local interface to bind for network connections. <del> * `socketPath` {String} Unix Domain Socket (use one of host:port or socketPath). <del> * `method` {String} A string specifying the HTTP request method. Defaults to `'GET'`. <del> * `path` {String} Request path. Defaults to `'/'`. Should include query string if any. <del> E.G. `'/index.html?page=12'`. An exception is thrown when the request path <del> contains illegal characters. Currently, only spaces are rejected but that <del> may change in the future. <add> * `socketPath` {String} Unix Domain Socket (use one of host:port or <add> socketPath). <add> * `method` {String} A string specifying the HTTP request method. Defaults to <add> `'GET'`. <add> * `path` {String} Request path. Defaults to `'/'`. Should include query <add> string if any. E.G. `'/index.html?page=12'`. An exception is thrown when <add> the request path contains illegal characters. Currently, only spaces are <add> rejected but that may change in the future. <ide> * `headers` {Object} An object containing request headers. <ide> * `auth` {String} Basic authentication i.e. `'user:password'` to compute an <ide> Authorization header. <del> * `agent` {http.Agent|Boolean} Controls [`Agent`][] behavior. When an Agent is used request will <del> default to `Connection: keep-alive`. Possible values: <add> * `agent` {http.Agent|Boolean} Controls [`Agent`][] behavior. When an Agent <add> is used request will default to `Connection: keep-alive`. Possible values: <ide> * `undefined` (default): use [`http.globalAgent`][] for this host and port. <ide> * `Agent` object: explicitly use the passed in `Agent`. <ide> * `false`: opts out of connection pooling with an Agent, defaults request to <ide> `Connection: close`. <del> * `createConnection` {Function} A function that produces a socket/stream to use for the <del> request when the `agent` option is not used. This can be used to avoid <del> creating a custom Agent class just to override the default `createConnection` <del> function. See [`agent.createConnection()`][] for more details. <add> * `createConnection` {Function} A function that produces a socket/stream to <add> use for the request when the `agent` option is not used. This can be used to <add> avoid creating a custom Agent class just to override the default <add> `createConnection` function. See [`agent.createConnection()`][] for more <add> details. <ide> * `timeout` {Integer}: A number specifying the socket timeout in milliseconds. <ide> This will set the timeout before the socket is connected. <ide> * `callback` {Function}
1
Ruby
Ruby
remove extra white spaces on actionmailer docs
5d0d4d8ad33be90e34721090991c86c8a22f2d05
<ide><path>actionmailer/lib/action_mailer/base.rb <ide> module ActionMailer #:nodoc: <ide> # <ide> # = Observing and Intercepting Mails <ide> # <del> # Action Mailer provides hooks into the Mail observer and interceptor methods. These allow you to <add> # Action Mailer provides hooks into the Mail observer and interceptor methods. These allow you to <ide> # register objects that are called during the mail delivery life cycle. <ide> # <ide> # An observer object must implement the <tt>:delivered_email(message)</tt> method which will be <ide> # called once for every email sent after the email has been sent. <ide> # <ide> # An interceptor object must implement the <tt>:delivering_email(message)</tt> method which will be <ide> # called before the email is sent, allowing you to make modifications to the email before it hits <del> # the delivery agents. Your object should make any needed modifications directly to the passed <add> # the delivery agents. Your object should make any needed modifications directly to the passed <ide> # in Mail::Message instance. <ide> # <ide> # = Default Hash <ide> module ActionMailer #:nodoc: <ide> # <ide> # * <tt>delivery_method</tt> - Defines a delivery method. Possible values are <tt>:smtp</tt> (default), <ide> # <tt>:sendmail</tt>, <tt>:test</tt>, and <tt>:file</tt>. Or you may provide a custom delivery method <del> # object eg. MyOwnDeliveryMethodClass.new. See the Mail gem documentation on the interface you need to <add> # object eg. MyOwnDeliveryMethodClass.new. See the Mail gem documentation on the interface you need to <ide> # implement for a custom delivery agent. <ide> # <ide> # * <tt>perform_deliveries</tt> - Determines whether emails are actually sent from Action Mailer when you <del> # call <tt>.deliver</tt> on an mail message or on an Action Mailer method. This is on by default but can <add> # call <tt>.deliver</tt> on an mail message or on an Action Mailer method. This is on by default but can <ide> # be turned off to aid in functional testing. <ide> # <ide> # * <tt>deliveries</tt> - Keeps an array of all the emails sent out through the Action Mailer with <ide> module ActionMailer #:nodoc: <ide> # to set the default +:mime_version+. <ide> # <ide> # * <tt>default_implicit_parts_order</tt> - This is now deprecated, use the +default+ method above <del> # to set the default +:parts_order+. Parts Order is used when a message is built implicitly <add> # to set the default +:parts_order+. Parts Order is used when a message is built implicitly <ide> # (i.e. multiple parts are assembled from templates which specify the content type in their <ide> # filenames) this variable controls how the parts are ordered. <ide> class Base < AbstractController::Base <ide> def attachments <ide> # method. <ide> # <ide> # When a <tt>:return_path</tt> is specified as header, that value will be used as the 'envelope from' <del> # address for the Mail message. Setting this is useful when you want delivery notifications <del> # sent to a different address than the one in <tt>:from</tt>. Mail will actually use the <add> # address for the Mail message. Setting this is useful when you want delivery notifications <add> # sent to a different address than the one in <tt>:from</tt>. Mail will actually use the <ide> # <tt>:return_path</tt> in preference to the <tt>:sender</tt> in preference to the <tt>:from</tt> <ide> # field for the 'envelope from' value. <ide> #
1
Ruby
Ruby
remove massassignmentsecurity from activemodel
f8c9a4d3e88181cee644f91e1342bfe896ca64c6
<ide><path>activemodel/lib/active_model.rb <ide> module ActiveModel <ide> autoload :EachValidator, 'active_model/validator' <ide> autoload :ForbiddenAttributesProtection <ide> autoload :Lint <del> autoload :MassAssignmentSecurity <ide> autoload :Model <ide> autoload :Name, 'active_model/naming' <ide> autoload :Naming <ide><path>activemodel/lib/active_model/forbidden_attributes_protection.rb <ide> class ForbiddenAttributes < StandardError <ide> end <ide> <ide> module ForbiddenAttributesProtection <del> def sanitize_for_mass_assignment(new_attributes, options = {}) <del> if !new_attributes.respond_to?(:permitted?) || (new_attributes.respond_to?(:permitted?) && new_attributes.permitted?) <del> super <del> else <add> def sanitize_for_mass_assignment(attributes, options = {}) <add> if attributes.respond_to?(:permitted?) && !attributes.permitted? <ide> raise ActiveModel::ForbiddenAttributes <add> else <add> attributes <ide> end <ide> end <ide> end <ide><path>activemodel/lib/active_model/mass_assignment_security.rb <del>require 'active_support/core_ext/string/inflections' <del>require 'active_model/mass_assignment_security/permission_set' <del>require 'active_model/mass_assignment_security/sanitizer' <del> <del>module ActiveModel <del> # == Active Model Mass-Assignment Security <del> # <del> # Mass assignment security provides an interface for protecting attributes <del> # from end-user assignment. For more complex permissions, mass assignment <del> # security may be handled outside the model by extending a non-ActiveRecord <del> # class, such as a controller, with this behavior. <del> # <del> # For example, a logged in user may need to assign additional attributes <del> # depending on their role: <del> # <del> # class AccountsController < ApplicationController <del> # include ActiveModel::MassAssignmentSecurity <del> # <del> # attr_accessible :first_name, :last_name <del> # attr_accessible :first_name, :last_name, :plan_id, as: :admin <del> # <del> # def update <del> # ... <del> # @account.update_attributes(account_params) <del> # ... <del> # end <del> # <del> # protected <del> # <del> # def account_params <del> # role = admin ? :admin : :default <del> # sanitize_for_mass_assignment(params[:account], role) <del> # end <del> # <del> # end <del> # <del> # === Configuration options <del> # <del> # * <tt>mass_assignment_sanitizer</tt> - Defines sanitize method. Possible <del> # values are: <del> # * <tt>:logger</tt> (default) - writes filtered attributes to logger <del> # * <tt>:strict</tt> - raise <tt>ActiveModel::MassAssignmentSecurity::Error</tt> <del> # on any protected attribute update. <del> # <del> # You can specify your own sanitizer object eg. <tt>MySanitizer.new</tt>. <del> # See <tt>ActiveModel::MassAssignmentSecurity::LoggerSanitizer</tt> for <del> # example implementation. <del> module MassAssignmentSecurity <del> extend ActiveSupport::Concern <del> <del> included do <del> class_attribute :_accessible_attributes, instance_writer: false <del> class_attribute :_protected_attributes, instance_writer: false <del> class_attribute :_active_authorizer, instance_writer: false <del> <del> class_attribute :_mass_assignment_sanitizer, instance_writer: false <del> self.mass_assignment_sanitizer = :logger <del> end <del> <del> module ClassMethods <del> # Attributes named in this macro are protected from mass-assignment <del> # whenever attributes are sanitized before assignment. A role for the <del> # attributes is optional, if no role is provided then <tt>:default</tt> <del> # is used. A role can be defined by using the <tt>:as</tt> option with a <del> # symbol or an array of symbols as the value. <del> # <del> # Mass-assignment to these attributes will simply be ignored, to assign <del> # to them you can use direct writer methods. This is meant to protect <del> # sensitive attributes from being overwritten by malicious users <del> # tampering with URLs or forms. <del> # <del> # class Customer <del> # include ActiveModel::MassAssignmentSecurity <del> # <del> # attr_accessor :name, :email, :logins_count <del> # <del> # attr_protected :logins_count <del> # # Suppose that admin can not change email for customer <del> # attr_protected :logins_count, :email, as: :admin <del> # <del> # def assign_attributes(values, options = {}) <del> # sanitize_for_mass_assignment(values, options[:as]).each do |k, v| <del> # send("#{k}=", v) <del> # end <del> # end <del> # end <del> # <del> # When using the <tt>:default</tt> role: <del> # <del> # customer = Customer.new <del> # customer.assign_attributes({ name: 'David', email: 'a@b.com', logins_count: 5 }, as: :default) <del> # customer.name # => "David" <del> # customer.email # => "a@b.com" <del> # customer.logins_count # => nil <del> # <del> # And using the <tt>:admin</tt> role: <del> # <del> # customer = Customer.new <del> # customer.assign_attributes({ name: 'David', email: 'a@b.com', logins_count: 5}, as: :admin) <del> # customer.name # => "David" <del> # customer.email # => nil <del> # customer.logins_count # => nil <del> # <del> # customer.email = 'c@d.com' <del> # customer.email # => "c@d.com" <del> # <del> # To start from an all-closed default and enable attributes as needed, <del> # have a look at +attr_accessible+. <del> # <del> # Note that using <tt>Hash#except</tt> or <tt>Hash#slice</tt> in place of <del> # +attr_protected+ to sanitize attributes provides basically the same <del> # functionality, but it makes a bit tricky to deal with nested attributes. <del> def attr_protected(*args) <del> options = args.extract_options! <del> role = options[:as] || :default <del> <del> self._protected_attributes = protected_attributes_configs.dup <del> <del> Array(role).each do |name| <del> self._protected_attributes[name] = self.protected_attributes(name) + args <del> end <del> <del> self._active_authorizer = self._protected_attributes <del> end <del> <del> # Specifies a white list of model attributes that can be set via <del> # mass-assignment. <del> # <del> # Like +attr_protected+, a role for the attributes is optional, <del> # if no role is provided then <tt>:default</tt> is used. A role can be <del> # defined by using the <tt>:as</tt> option with a symbol or an array of <del> # symbols as the value. <del> # <del> # This is the opposite of the +attr_protected+ macro: Mass-assignment <del> # will only set attributes in this list, to assign to the rest of <del> # attributes you can use direct writer methods. This is meant to protect <del> # sensitive attributes from being overwritten by malicious users <del> # tampering with URLs or forms. If you'd rather start from an all-open <del> # default and restrict attributes as needed, have a look at <del> # +attr_protected+. <del> # <del> # class Customer <del> # include ActiveModel::MassAssignmentSecurity <del> # <del> # attr_accessor :name, :credit_rating <del> # <del> # # Both admin and default user can change name of a customer <del> # attr_accessible :name, as: [:admin, :default] <del> # # Only admin can change credit rating of a customer <del> # attr_accessible :credit_rating, as: :admin <del> # <del> # def assign_attributes(values, options = {}) <del> # sanitize_for_mass_assignment(values, options[:as]).each do |k, v| <del> # send("#{k}=", v) <del> # end <del> # end <del> # end <del> # <del> # When using the <tt>:default</tt> role: <del> # <del> # customer = Customer.new <del> # customer.assign_attributes({ name: 'David', credit_rating: 'Excellent', last_login: 1.day.ago }, as: :default) <del> # customer.name # => "David" <del> # customer.credit_rating # => nil <del> # <del> # customer.credit_rating = 'Average' <del> # customer.credit_rating # => "Average" <del> # <del> # And using the <tt>:admin</tt> role: <del> # <del> # customer = Customer.new <del> # customer.assign_attributes({ name: 'David', credit_rating: 'Excellent', last_login: 1.day.ago }, as: :admin) <del> # customer.name # => "David" <del> # customer.credit_rating # => "Excellent" <del> # <del> # Note that using <tt>Hash#except</tt> or <tt>Hash#slice</tt> in place of <del> # +attr_accessible+ to sanitize attributes provides basically the same <del> # functionality, but it makes a bit tricky to deal with nested attributes. <del> def attr_accessible(*args) <del> options = args.extract_options! <del> role = options[:as] || :default <del> <del> self._accessible_attributes = accessible_attributes_configs.dup <del> <del> Array(role).each do |name| <del> self._accessible_attributes[name] = self.accessible_attributes(name) + args <del> end <del> <del> self._active_authorizer = self._accessible_attributes <del> end <del> <del> # Returns an instance of <tt>ActiveModel::MassAssignmentSecurity::BlackList</tt> <del> # with the attributes protected by #attr_protected method. If no +role+ <del> # is provided, then <tt>:default</tt> is used. <del> # <del> # class Customer <del> # include ActiveModel::MassAssignmentSecurity <del> # <del> # attr_accessor :name, :email, :logins_count <del> # <del> # attr_protected :logins_count <del> # attr_protected :logins_count, :email, as: :admin <del> # end <del> # <del> # Customer.protected_attributes <del> # # => #<ActiveModel::MassAssignmentSecurity::BlackList: {"logins_count"}> <del> # <del> # Customer.protected_attributes(:default) <del> # # => #<ActiveModel::MassAssignmentSecurity::BlackList: {"logins_count"}> <del> # <del> # Customer.protected_attributes(:admin) <del> # # => #<ActiveModel::MassAssignmentSecurity::BlackList: {"logins_count", "email"}> <del> def protected_attributes(role = :default) <del> protected_attributes_configs[role] <del> end <del> <del> # Returns an instance of <tt>ActiveModel::MassAssignmentSecurity::WhiteList</tt> <del> # with the attributes protected by #attr_accessible method. If no +role+ <del> # is provided, then <tt>:default</tt> is used. <del> # <del> # class Customer <del> # include ActiveModel::MassAssignmentSecurity <del> # <del> # attr_accessor :name, :credit_rating <del> # <del> # attr_accessible :name, as: [:admin, :default] <del> # attr_accessible :credit_rating, as: :admin <del> # end <del> # <del> # Customer.accessible_attributes <del> # # => #<ActiveModel::MassAssignmentSecurity::WhiteList: {"name"}> <del> # <del> # Customer.accessible_attributes(:default) <del> # # => #<ActiveModel::MassAssignmentSecurity::WhiteList: {"name"}> <del> # <del> # Customer.accessible_attributes(:admin) <del> # # => #<ActiveModel::MassAssignmentSecurity::WhiteList: {"name", "credit_rating"}> <del> def accessible_attributes(role = :default) <del> accessible_attributes_configs[role] <del> end <del> <del> # Returns a hash with the protected attributes (by #attr_accessible or <del> # #attr_protected) per role. <del> # <del> # class Customer <del> # include ActiveModel::MassAssignmentSecurity <del> # <del> # attr_accessor :name, :credit_rating <del> # <del> # attr_accessible :name, as: [:admin, :default] <del> # attr_accessible :credit_rating, as: :admin <del> # end <del> # <del> # Customer.active_authorizers <del> # # => { <del> # # :admin=> #<ActiveModel::MassAssignmentSecurity::WhiteList: {"name", "credit_rating"}>, <del> # # :default=>#<ActiveModel::MassAssignmentSecurity::WhiteList: {"name"}> <del> # #  } <del> def active_authorizers <del> self._active_authorizer ||= protected_attributes_configs <del> end <del> alias active_authorizer active_authorizers <del> <del> # Returns an empty array by default. You can still override this to define <del> # the default attributes protected by #attr_protected method. <del> # <del> # class Customer <del> # include ActiveModel::MassAssignmentSecurity <del> # <del> # def self.attributes_protected_by_default <del> # [:name] <del> # end <del> # end <del> # <del> # Customer.protected_attributes <del> # # => #<ActiveModel::MassAssignmentSecurity::BlackList: {:name}> <del> def attributes_protected_by_default <del> [] <del> end <del> <del> # Defines sanitize method. <del> # <del> # class Customer <del> # include ActiveModel::MassAssignmentSecurity <del> # <del> # attr_accessor :name <del> # <del> # attr_protected :name <del> # <del> # def assign_attributes(values) <del> # sanitize_for_mass_assignment(values).each do |k, v| <del> # send("#{k}=", v) <del> # end <del> # end <del> # end <del> # <del> # # See ActiveModel::MassAssignmentSecurity::StrictSanitizer for more information. <del> # Customer.mass_assignment_sanitizer = :strict <del> # <del> # customer = Customer.new <del> # customer.assign_attributes(name: 'David') <del> # # => ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes for Customer: name <del> # <del> # Also, you can specify your own sanitizer object. <del> # <del> # class CustomSanitizer < ActiveModel::MassAssignmentSecurity::Sanitizer <del> # def process_removed_attributes(klass, attrs) <del> # raise StandardError <del> # end <del> # end <del> # <del> # Customer.mass_assignment_sanitizer = CustomSanitizer.new <del> # <del> # customer = Customer.new <del> # customer.assign_attributes(name: 'David') <del> # # => StandardError: StandardError <del> def mass_assignment_sanitizer=(value) <del> self._mass_assignment_sanitizer = if value.is_a?(Symbol) <del> const_get(:"#{value.to_s.camelize}Sanitizer").new(self) <del> else <del> value <del> end <del> end <del> <del> private <del> <del> def protected_attributes_configs <del> self._protected_attributes ||= begin <del> Hash.new { |h,k| h[k] = BlackList.new(attributes_protected_by_default) } <del> end <del> end <del> <del> def accessible_attributes_configs <del> self._accessible_attributes ||= begin <del> Hash.new { |h,k| h[k] = WhiteList.new } <del> end <del> end <del> end <del> <del> protected <del> <del> def sanitize_for_mass_assignment(attributes, role = nil) #:nodoc: <del> _mass_assignment_sanitizer.sanitize(self.class, attributes, mass_assignment_authorizer(role)) <del> end <del> <del> def mass_assignment_authorizer(role) #:nodoc: <del> self.class.active_authorizer[role || :default] <del> end <del> end <del>end <ide><path>activemodel/lib/active_model/mass_assignment_security/permission_set.rb <del>require 'set' <del> <del>module ActiveModel <del> module MassAssignmentSecurity <del> class PermissionSet < Set #:nodoc: <del> <del> def +(values) <del> super(values.compact.map(&:to_s)) <del> end <del> <del> def include?(key) <del> super(remove_multiparameter_id(key)) <del> end <del> <del> def deny?(key) <del> raise NotImplementedError, "#deny?(key) supposed to be overwritten" <del> end <del> <del> protected <del> <del> def remove_multiparameter_id(key) <del> key.to_s.gsub(/\(.+/, '') <del> end <del> end <del> <del> class WhiteList < PermissionSet #:nodoc: <del> <del> def deny?(key) <del> !include?(key) <del> end <del> end <del> <del> class BlackList < PermissionSet #:nodoc: <del> <del> def deny?(key) <del> include?(key) <del> end <del> end <del> end <del>end <ide><path>activemodel/lib/active_model/mass_assignment_security/sanitizer.rb <del>module ActiveModel <del> module MassAssignmentSecurity <del> class Sanitizer #:nodoc: <del> # Returns all attributes not denied by the authorizer. <del> def sanitize(klass, attributes, authorizer) <del> rejected = [] <del> sanitized_attributes = attributes.reject do |key, value| <del> rejected << key if authorizer.deny?(key) <del> end <del> process_removed_attributes(klass, rejected) unless rejected.empty? <del> sanitized_attributes <del> end <del> <del> protected <del> <del> def process_removed_attributes(klass, attrs) <del> raise NotImplementedError, "#process_removed_attributes(attrs) suppose to be overwritten" <del> end <del> end <del> <del> class LoggerSanitizer < Sanitizer #:nodoc: <del> def initialize(target) <del> @target = target <del> super() <del> end <del> <del> def logger <del> @target.logger <del> end <del> <del> def logger? <del> @target.respond_to?(:logger) && @target.logger <del> end <del> <del> def backtrace <del> if defined? Rails <del> Rails.backtrace_cleaner.clean(caller) <del> else <del> caller <del> end <del> end <del> <del> def process_removed_attributes(klass, attrs) <del> if logger? <del> logger.warn do <del> "WARNING: Can't mass-assign protected attributes for #{klass.name}: #{attrs.join(', ')}\n" + <del> backtrace.map { |trace| "\t#{trace}" }.join("\n") <del> end <del> end <del> end <del> end <del> <del> class StrictSanitizer < Sanitizer #:nodoc: <del> def initialize(target = nil) <del> super() <del> end <del> <del> def process_removed_attributes(klass, attrs) <del> return if (attrs - insensitive_attributes).empty? <del> raise ActiveModel::MassAssignmentSecurity::Error.new(klass, attrs) <del> end <del> <del> def insensitive_attributes <del> ['id'] <del> end <del> end <del> <del> class Error < StandardError #:nodoc: <del> def initialize(klass, attrs) <del> super("Can't mass-assign protected attributes for #{klass.name}: #{attrs.join(', ')}") <del> end <del> end <del> end <del>end <ide><path>activemodel/test/cases/forbidden_attributes_protection_test.rb <ide> require 'cases/helper' <del>require 'models/mass_assignment_specific' <add>require 'models/account' <ide> <ide> class ActiveModelMassUpdateProtectionTest < ActiveSupport::TestCase <ide> test "forbidden attributes cannot be used for mass updating" do <ide> class << params <ide> define_method(:permitted?) { false } <ide> end <ide> assert_raises(ActiveModel::ForbiddenAttributes) do <del> SpecialPerson.new.sanitize_for_mass_assignment(params) <add> Account.new.sanitize_for_mass_assignment(params) <ide> end <ide> end <ide> <ide> class << params <ide> end <ide> assert_nothing_raised do <ide> assert_equal({ "a" => "b" }, <del> SpecialPerson.new.sanitize_for_mass_assignment(params)) <add> Account.new.sanitize_for_mass_assignment(params)) <ide> end <ide> end <ide> <ide> test "regular attributes should still be allowed" do <ide> assert_nothing_raised do <ide> assert_equal({ a: "b" }, <del> SpecialPerson.new.sanitize_for_mass_assignment(a: "b")) <add> Account.new.sanitize_for_mass_assignment(a: "b")) <ide> end <ide> end <ide> end <ide><path>activemodel/test/cases/mass_assignment_security/black_list_test.rb <del>require "cases/helper" <del> <del>class BlackListTest < ActiveModel::TestCase <del> <del> def setup <del> @black_list = ActiveModel::MassAssignmentSecurity::BlackList.new <del> @included_key = 'admin' <del> @black_list += [ @included_key ] <del> end <del> <del> test "deny? is true for included items" do <del> assert_equal true, @black_list.deny?(@included_key) <del> end <del> <del> test "deny? is false for non-included items" do <del> assert_equal false, @black_list.deny?('first_name') <del> end <del> <del> <del>end <ide><path>activemodel/test/cases/mass_assignment_security/permission_set_test.rb <del>require "cases/helper" <del> <del>class PermissionSetTest < ActiveModel::TestCase <del> <del> def setup <del> @permission_list = ActiveModel::MassAssignmentSecurity::PermissionSet.new <del> end <del> <del> test "+ stringifies added collection values" do <del> symbol_collection = [ :admin ] <del> new_list = @permission_list += symbol_collection <del> <del> assert new_list.include?('admin'), "did not add collection to #{@permission_list.inspect}}" <del> end <del> <del> test "+ compacts added collection values" do <del> added_collection = [ nil ] <del> new_list = @permission_list + added_collection <del> assert_equal new_list, @permission_list, "did not add collection to #{@permission_list.inspect}}" <del> end <del> <del> test "include? normalizes multi-parameter keys" do <del> multi_param_key = 'admin(1)' <del> new_list = @permission_list += [ 'admin' ] <del> <del> assert new_list.include?(multi_param_key), "#{multi_param_key} not found in #{@permission_list.inspect}" <del> end <del> <del> test "include? normal keys" do <del> normal_key = 'admin' <del> new_list = @permission_list += [ normal_key ] <del> <del> assert new_list.include?(normal_key), "#{normal_key} not found in #{@permission_list.inspect}" <del> end <del> <del>end <ide><path>activemodel/test/cases/mass_assignment_security/sanitizer_test.rb <del>require "cases/helper" <del>require 'active_support/logger' <del> <del>class SanitizerTest < ActiveModel::TestCase <del> attr_accessor :logger <del> <del> class Authorizer < ActiveModel::MassAssignmentSecurity::PermissionSet <del> def deny?(key) <del> ['admin', 'id'].include?(key) <del> end <del> end <del> <del> def setup <del> @logger_sanitizer = ActiveModel::MassAssignmentSecurity::LoggerSanitizer.new(self) <del> @strict_sanitizer = ActiveModel::MassAssignmentSecurity::StrictSanitizer.new(self) <del> @authorizer = Authorizer.new <del> end <del> <del> test "sanitize attributes" do <del> original_attributes = { 'first_name' => 'allowed', 'admin' => 'denied' } <del> attributes = @logger_sanitizer.sanitize(self.class, original_attributes, @authorizer) <del> <del> assert attributes.key?('first_name'), "Allowed key shouldn't be rejected" <del> assert !attributes.key?('admin'), "Denied key should be rejected" <del> end <del> <del> test "debug mass assignment removal with LoggerSanitizer" do <del> original_attributes = { 'first_name' => 'allowed', 'admin' => 'denied' } <del> log = StringIO.new <del> self.logger = ActiveSupport::Logger.new(log) <del> @logger_sanitizer.sanitize(self.class, original_attributes, @authorizer) <del> assert_match(/admin/, log.string, "Should log removed attributes: #{log.string}") <del> end <del> <del> test "debug mass assignment removal with StrictSanitizer" do <del> original_attributes = { 'first_name' => 'allowed', 'admin' => 'denied' } <del> assert_raise ActiveModel::MassAssignmentSecurity::Error do <del> @strict_sanitizer.sanitize(self.class, original_attributes, @authorizer) <del> end <del> end <del> <del> test "mass assignment insensitive attributes" do <del> original_attributes = {'id' => 1, 'first_name' => 'allowed'} <del> <del> assert_nothing_raised do <del> @strict_sanitizer.sanitize(self.class, original_attributes, @authorizer) <del> end <del> end <del> <del>end <ide><path>activemodel/test/cases/mass_assignment_security/white_list_test.rb <del>require "cases/helper" <del> <del>class WhiteListTest < ActiveModel::TestCase <del> <del> def setup <del> @white_list = ActiveModel::MassAssignmentSecurity::WhiteList.new <del> @included_key = 'first_name' <del> @white_list += [ @included_key ] <del> end <del> <del> test "deny? is false for included items" do <del> assert_equal false, @white_list.deny?(@included_key) <del> end <del> <del> test "deny? is true for non-included items" do <del> assert_equal true, @white_list.deny?('admin') <del> end <del> <del>end <ide><path>activemodel/test/cases/mass_assignment_security_test.rb <del>require "cases/helper" <del>require 'models/mass_assignment_specific' <del> <del> <del>class CustomSanitizer < ActiveModel::MassAssignmentSecurity::Sanitizer <del> <del> def process_removed_attributes(klass, attrs) <del> raise StandardError <del> end <del> <del>end <del> <del>class MassAssignmentSecurityTest < ActiveModel::TestCase <del> def test_attribute_protection <del> user = User.new <del> expected = { "name" => "John Smith", "email" => "john@smith.com" } <del> sanitized = user.sanitize_for_mass_assignment(expected.merge("admin" => true)) <del> assert_equal expected, sanitized <del> end <del> <del> def test_attribute_protection_when_role_is_nil <del> user = User.new <del> expected = { "name" => "John Smith", "email" => "john@smith.com" } <del> sanitized = user.sanitize_for_mass_assignment(expected.merge("admin" => true), nil) <del> assert_equal expected, sanitized <del> end <del> <del> def test_only_moderator_role_attribute_accessible <del> user = SpecialUser.new <del> expected = { "name" => "John Smith", "email" => "john@smith.com" } <del> sanitized = user.sanitize_for_mass_assignment(expected.merge("admin" => true), :moderator) <del> assert_equal expected, sanitized <del> <del> sanitized = user.sanitize_for_mass_assignment({ "name" => "John Smith", "email" => "john@smith.com", "admin" => true }) <del> assert_equal({}, sanitized) <del> end <del> <del> def test_attributes_accessible <del> user = Person.new <del> expected = { "name" => "John Smith", "email" => "john@smith.com" } <del> sanitized = user.sanitize_for_mass_assignment(expected.merge("admin" => true)) <del> assert_equal expected, sanitized <del> end <del> <del> def test_attributes_accessible_with_admin_role <del> user = Person.new <del> expected = { "name" => "John Smith", "email" => "john@smith.com", "admin" => true } <del> sanitized = user.sanitize_for_mass_assignment(expected.merge("super_powers" => true), :admin) <del> assert_equal expected, sanitized <del> end <del> <del> def test_attributes_accessible_with_roles_given_as_array <del> user = Account.new <del> expected = { "name" => "John Smith", "email" => "john@smith.com" } <del> sanitized = user.sanitize_for_mass_assignment(expected.merge("admin" => true)) <del> assert_equal expected, sanitized <del> end <del> <del> def test_attributes_accessible_with_admin_role_when_roles_given_as_array <del> user = Account.new <del> expected = { "name" => "John Smith", "email" => "john@smith.com", "admin" => true } <del> sanitized = user.sanitize_for_mass_assignment(expected.merge("super_powers" => true), :admin) <del> assert_equal expected, sanitized <del> end <del> <del> def test_attributes_protected_by_default <del> firm = Firm.new <del> expected = { } <del> sanitized = firm.sanitize_for_mass_assignment({ "type" => "Client" }) <del> assert_equal expected, sanitized <del> end <del> <del> def test_mass_assignment_protection_inheritance <del> assert_blank LoosePerson.accessible_attributes <del> assert_equal Set.new(['credit_rating', 'administrator']), LoosePerson.protected_attributes <del> <del> assert_blank LoosePerson.accessible_attributes <del> assert_equal Set.new(['credit_rating']), LoosePerson.protected_attributes(:admin) <del> <del> assert_blank LooseDescendant.accessible_attributes <del> assert_equal Set.new(['credit_rating', 'administrator', 'phone_number']), LooseDescendant.protected_attributes <del> <del> assert_blank LooseDescendantSecond.accessible_attributes <del> assert_equal Set.new(['credit_rating', 'administrator', 'phone_number', 'name']), LooseDescendantSecond.protected_attributes, <del> 'Running attr_protected twice in one class should merge the protections' <del> <del> assert_blank TightPerson.protected_attributes - TightPerson.attributes_protected_by_default <del> assert_equal Set.new(['name', 'address']), TightPerson.accessible_attributes <del> <del> assert_blank TightPerson.protected_attributes(:admin) - TightPerson.attributes_protected_by_default <del> assert_equal Set.new(['name', 'address', 'admin']), TightPerson.accessible_attributes(:admin) <del> <del> assert_blank TightDescendant.protected_attributes - TightDescendant.attributes_protected_by_default <del> assert_equal Set.new(['name', 'address', 'phone_number']), TightDescendant.accessible_attributes <del> <del> assert_blank TightDescendant.protected_attributes(:admin) - TightDescendant.attributes_protected_by_default <del> assert_equal Set.new(['name', 'address', 'admin', 'super_powers']), TightDescendant.accessible_attributes(:admin) <del> end <del> <del> def test_mass_assignment_multiparameter_protector <del> task = Task.new <del> attributes = { "starting(1i)" => "2004", "starting(2i)" => "6", "starting(3i)" => "24" } <del> sanitized = task.sanitize_for_mass_assignment(attributes) <del> assert_equal sanitized, { } <del> end <del> <del> def test_custom_sanitizer <del> old_sanitizer = User._mass_assignment_sanitizer <del> <del> user = User.new <del> User.mass_assignment_sanitizer = CustomSanitizer.new <del> assert_raise StandardError do <del> user.sanitize_for_mass_assignment("admin" => true) <del> end <del> ensure <del> User.mass_assignment_sanitizer = old_sanitizer <del> end <del>end <ide>\ No newline at end of file <ide><path>activemodel/test/cases/secure_password_test.rb <ide> class SecurePasswordTest < ActiveModel::TestCase <ide> assert @user.authenticate("secret") <ide> end <ide> <del> test "visitor#password_digest should be protected against mass assignment" do <del> assert Visitor.active_authorizers[:default].kind_of?(ActiveModel::MassAssignmentSecurity::BlackList) <del> assert Visitor.active_authorizers[:default].include?(:password_digest) <del> end <del> <del> test "Administrator's mass_assignment_authorizer should be WhiteList" do <del> active_authorizer = Administrator.active_authorizers[:default] <del> assert active_authorizer.kind_of?(ActiveModel::MassAssignmentSecurity::WhiteList) <del> assert !active_authorizer.include?(:password_digest) <del> assert active_authorizer.include?(:name) <del> end <del> <ide> test "User should not be created with blank digest" do <ide> assert_raise RuntimeError do <ide> @user.run_callbacks :create <ide><path>activemodel/test/models/account.rb <add>class Account <add> include ActiveModel::ForbiddenAttributesProtection <add> <add> public :sanitize_for_mass_assignment <add>end <ide><path>activemodel/test/models/administrator.rb <ide> class Administrator <ide> extend ActiveModel::Callbacks <ide> include ActiveModel::Validations <ide> include ActiveModel::SecurePassword <del> include ActiveModel::MassAssignmentSecurity <del> <add> <ide> define_model_callbacks :create <ide> <ide> attr_accessor :name, :password_digest <del> attr_accessible :name <ide> <ide> has_secure_password <ide> end <ide><path>activemodel/test/models/mass_assignment_specific.rb <del>class User <del> include ActiveModel::MassAssignmentSecurity <del> attr_protected :admin <del> <del> public :sanitize_for_mass_assignment <del>end <del> <del>class SpecialUser <del> include ActiveModel::MassAssignmentSecurity <del> attr_accessible :name, :email, :as => :moderator <del> <del> public :sanitize_for_mass_assignment <del>end <del> <del>class Person <del> include ActiveModel::MassAssignmentSecurity <del> attr_accessible :name, :email <del> attr_accessible :name, :email, :admin, :as => :admin <del> <del> public :sanitize_for_mass_assignment <del>end <del> <del>class SpecialPerson <del> include ActiveModel::MassAssignmentSecurity <del> include ActiveModel::ForbiddenAttributesProtection <del> <del> public :sanitize_for_mass_assignment <del>end <del> <del>class Account <del> include ActiveModel::MassAssignmentSecurity <del> attr_accessible :name, :email, :as => [:default, :admin] <del> attr_accessible :admin, :as => :admin <del> <del> public :sanitize_for_mass_assignment <del>end <del> <del>class Firm <del> include ActiveModel::MassAssignmentSecurity <del> <del> public :sanitize_for_mass_assignment <del> <del> def self.attributes_protected_by_default <del> ["type"] <del> end <del>end <del> <del>class Task <del> include ActiveModel::MassAssignmentSecurity <del> attr_protected :starting <del> <del> public :sanitize_for_mass_assignment <del>end <del> <del>class LoosePerson <del> include ActiveModel::MassAssignmentSecurity <del> attr_protected :credit_rating, :administrator <del> attr_protected :credit_rating, :as => :admin <del>end <del> <del>class LooseDescendant < LoosePerson <del> attr_protected :phone_number <del>end <del> <del>class LooseDescendantSecond< LoosePerson <del> attr_protected :phone_number <del> attr_protected :name <del>end <del> <del>class TightPerson <del> include ActiveModel::MassAssignmentSecurity <del> attr_accessible :name, :address <del> attr_accessible :name, :address, :admin, :as => :admin <del> <del> def self.attributes_protected_by_default <del> ["mobile_number"] <del> end <del>end <del> <del>class TightDescendant < TightPerson <del> attr_accessible :phone_number <del> attr_accessible :super_powers, :as => :admin <del>end <ide><path>activemodel/test/models/visitor.rb <ide> class Visitor <ide> extend ActiveModel::Callbacks <ide> include ActiveModel::Validations <ide> include ActiveModel::SecurePassword <del> include ActiveModel::MassAssignmentSecurity <del> <add> <ide> define_model_callbacks :create <ide> <ide> has_secure_password(validations: false)
16
Text
Text
correct a small typo in style guide for articles.
583676707ab5167dfb8ecc34ca898f2872cb27a9
<ide><path>docs/style-guide-for-guide-articles.md <ide> Proper nouns should use correct capitalization when possible. Below is a list of <ide> - JavaScript (capital letters in "J" and "S" and no abbreviations) <ide> - Node.js <ide> <del>Front-end development (adjective form with a dash) is when you working on the front end (noun form with no dash). The same goes with the back end, full stack, and many other compound terms. <add>Front-end development (adjective form with a dash) is when you are working on the front end (noun form with no dash). The same goes with the back end, full stack, and many other compound terms. <ide> <ide> ## Third-Party Tools <ide>
1
Go
Go
use waitgroup instead of iterating errors chan
e6c9343457c501c1da718c25bb9601f87d82cd7d
<ide><path>daemon/attach.go <ide> import ( <ide> "encoding/json" <ide> "io" <ide> "os" <add> "sync" <ide> "time" <ide> <ide> log "github.com/Sirupsen/logrus" <ide> func (daemon *Daemon) attach(streamConfig *StreamConfig, openStdin, stdinOnce, t <ide> var ( <ide> cStdout, cStderr io.ReadCloser <ide> cStdin io.WriteCloser <del> nJobs int <add> wg sync.WaitGroup <add> errors = make(chan error, 3) <ide> ) <ide> <ide> if stdin != nil && openStdin { <ide> cStdin = streamConfig.StdinPipe() <del> nJobs++ <add> wg.Add(1) <ide> } <ide> <ide> if stdout != nil { <ide> cStdout = streamConfig.StdoutPipe() <del> nJobs++ <add> wg.Add(1) <ide> } <ide> <ide> if stderr != nil { <ide> cStderr = streamConfig.StderrPipe() <del> nJobs++ <add> wg.Add(1) <ide> } <ide> <del> errors := make(chan error, nJobs) <del> <ide> // Connect stdin of container to the http conn. <del> if stdin != nil && openStdin { <del> // Get the stdin pipe. <del> cStdin = streamConfig.StdinPipe() <del> go func() { <del> log.Debugf("attach: stdin: begin") <del> defer func() { <del> if stdinOnce && !tty { <del> defer cStdin.Close() <del> } else { <del> // No matter what, when stdin is closed (io.Copy unblock), close stdout and stderr <del> if cStdout != nil { <del> cStdout.Close() <del> } <del> if cStderr != nil { <del> cStderr.Close() <del> } <del> } <del> log.Debugf("attach: stdin: end") <del> }() <del> var err error <del> if tty { <del> _, err = utils.CopyEscapable(cStdin, stdin) <add> go func() { <add> if stdin == nil || !openStdin { <add> return <add> } <add> log.Debugf("attach: stdin: begin") <add> defer func() { <add> if stdinOnce && !tty { <add> cStdin.Close() <ide> } else { <del> _, err = io.Copy(cStdin, stdin) <del> <del> } <del> if err == io.ErrClosedPipe { <del> err = nil <del> } <del> if err != nil { <del> log.Errorf("attach: stdin: %s", err) <add> // No matter what, when stdin is closed (io.Copy unblock), close stdout and stderr <add> if cStdout != nil { <add> cStdout.Close() <add> } <add> if cStderr != nil { <add> cStderr.Close() <add> } <ide> } <del> errors <- err <add> wg.Done() <add> log.Debugf("attach: stdin: end") <ide> }() <del> } <add> <add> var err error <add> if tty { <add> _, err = utils.CopyEscapable(cStdin, stdin) <add> } else { <add> _, err = io.Copy(cStdin, stdin) <add> <add> } <add> if err == io.ErrClosedPipe { <add> err = nil <add> } <add> if err != nil { <add> log.Errorf("attach: stdin: %s", err) <add> errors <- err <add> return <add> } <add> }() <ide> <ide> attachStream := func(name string, stream io.Writer, streamPipe io.ReadCloser) { <ide> if stream == nil { <ide> func (daemon *Daemon) attach(streamConfig *StreamConfig, openStdin, stdinOnce, t <ide> cStdin.Close() <ide> } <ide> streamPipe.Close() <add> wg.Done() <add> log.Debugf("attach: %s: end", name) <ide> }() <ide> <ide> log.Debugf("attach: %s: begin", name) <del> defer log.Debugf("attach: %s: end", name) <ide> _, err := io.Copy(stream, streamPipe) <ide> if err == io.ErrClosedPipe { <ide> err = nil <ide> } <ide> if err != nil { <ide> log.Errorf("attach: %s: %v", name, err) <add> errors <- err <ide> } <del> errors <- err <ide> } <ide> <ide> go attachStream("stdout", stdout, cStdout) <ide> go attachStream("stderr", stderr, cStderr) <ide> <ide> return promise.Go(func() error { <del> for i := 0; i < nJobs; i++ { <del> log.Debugf("attach: waiting for job %d/%d", i+1, nJobs) <del> err := <-errors <add> wg.Wait() <add> close(errors) <add> for err := range errors { <ide> if err != nil { <del> log.Errorf("attach: job %d returned error %s, aborting all jobs", i+1, err) <ide> return err <ide> } <del> log.Debugf("attach: job %d completed successfully", i+1) <ide> } <del> log.Debugf("attach: all jobs completed successfully") <ide> return nil <ide> }) <ide> }
1
Text
Text
add syntax highlighting
092f8473cef58ab67d6287194ebadebdd3a46498
<ide><path>src/Illuminate/Database/README.md <ide> The Illuminate Database component is a full database toolkit for PHP, providing <ide> <ide> First, create a new "Capsule" manager instance. Capsule aims to make configuring the library for usage outside of the Laravel framework as easy as possible. <ide> <del>``` <add>```PHP <ide> use Illuminate\Database\Capsule\Manager as Capsule; <ide> <ide> $capsule = new Capsule; <ide> Once the Capsule instance has been registered. You may use it like so: <ide> <ide> **Using The Query Builder** <ide> <del>``` <add>```PHP <ide> $users = Capsule::table('users')->where('votes', '>', 100)->get(); <ide> ``` <ide> Other core methods may be accessed directly from the Capsule in the same manner as from the DB facade: <del>``` <add>```PHP <ide> $results = Capsule::select('select * from users where id = ?', array(1)); <ide> ``` <ide> <ide> **Using The Schema Builder** <ide> <del>``` <add>```PHP <ide> Capsule::schema()->create('users', function($table) <ide> { <ide> $table->increments('id'); <ide> Capsule::schema()->create('users', function($table) <ide> <ide> **Using The Eloquent ORM** <ide> <del>``` <add>```PHP <ide> class User extends Illuminate\Database\Eloquent\Model {} <ide> <ide> $users = User::where('votes', '>', 1)->get();
1
Go
Go
add unit test for lxc conf merge and native opts
10fdbc0467d1be6c7c731d3f35590d87ee42f96f
<ide><path>runtime/container.go <ide> func populateCommand(c *Container) { <ide> } <ide> } <ide> <del> // merge in the lxc conf options into the generic config map <del> if lxcConf := c.hostConfig.LxcConf; lxcConf != nil { <del> lxc := driverConfig["lxc"] <del> for _, pair := range lxcConf { <del> lxc = append(lxc, fmt.Sprintf("%s = %s", pair.Key, pair.Value)) <del> } <del> driverConfig["lxc"] = lxc <del> } <add> // TODO: this can be removed after lxc-conf is fully deprecated <add> mergeLxcConfIntoOptions(c.hostConfig, driverConfig) <ide> <ide> resources := &execdriver.Resources{ <ide> Memory: c.Config.Memory, <ide><path>runtime/execdriver/lxc/lxc_template.go <ide> lxc.cgroup.cpu.shares = {{.Resources.CpuShares}} <ide> <ide> {{if .Config.lxc}} <ide> {{range $value := .Config.lxc}} <del>{{$value}} <add>lxc.{{$value}} <ide> {{end}} <ide> {{end}} <ide> ` <ide><path>runtime/execdriver/native/configuration/parse.go <ide> var actions = map[string]Action{ <ide> "fs.readonly": readonlyFs, // make the rootfs of the container read only <ide> } <ide> <del>// GetSupportedActions returns a list of all the avaliable actions supported by the driver <del>// TODO: this should return a description also <del>func GetSupportedActions() []string { <del> var ( <del> i int <del> out = make([]string, len(actions)) <del> ) <del> for k := range actions { <del> out[i] = k <del> i++ <del> } <del> return out <del>} <del> <ide> func cpusetCpus(container *libcontainer.Container, context interface{}, value string) error { <ide> if container.Cgroups == nil { <ide> return fmt.Errorf("cannot set cgroups when they are disabled") <ide><path>runtime/execdriver/native/configuration/parse_test.go <add>package configuration <add> <add>import ( <add> "github.com/dotcloud/docker/runtime/execdriver/native/template" <add> "testing" <add>) <add> <add>func TestSetReadonlyRootFs(t *testing.T) { <add> var ( <add> container = template.New() <add> opts = []string{ <add> "fs.readonly=true", <add> } <add> ) <add> <add> if container.ReadonlyFs { <add> t.Fatal("container should not have a readonly rootfs by default") <add> } <add> if err := ParseConfiguration(container, nil, opts); err != nil { <add> t.Fatal(err) <add> } <add> <add> if !container.ReadonlyFs { <add> t.Fatal("container should have a readonly rootfs") <add> } <add>} <add> <add>func TestConfigurationsDoNotConflict(t *testing.T) { <add> var ( <add> container1 = template.New() <add> container2 = template.New() <add> opts = []string{ <add> "cap.add=NET_ADMIN", <add> } <add> ) <add> <add> if err := ParseConfiguration(container1, nil, opts); err != nil { <add> t.Fatal(err) <add> } <add> <add> if !container1.CapabilitiesMask.Get("NET_ADMIN").Enabled { <add> t.Fatal("container one should have NET_ADMIN enabled") <add> } <add> if container2.CapabilitiesMask.Get("NET_ADMIN").Enabled { <add> t.Fatal("container two should not have NET_ADMIN enabled") <add> } <add>} <add> <add>func TestCpusetCpus(t *testing.T) { <add> var ( <add> container = template.New() <add> opts = []string{ <add> "cgroups.cpuset.cpus=1,2", <add> } <add> ) <add> if err := ParseConfiguration(container, nil, opts); err != nil { <add> t.Fatal(err) <add> } <add> <add> if expected := "1,2"; container.Cgroups.CpusetCpus != expected { <add> t.Fatalf("expected %s got %s for cpuset.cpus", expected, container.Cgroups.CpusetCpus) <add> } <add>} <add> <add>func TestAppArmorProfile(t *testing.T) { <add> var ( <add> container = template.New() <add> opts = []string{ <add> "apparmor_profile=koye-the-protector", <add> } <add> ) <add> if err := ParseConfiguration(container, nil, opts); err != nil { <add> t.Fatal(err) <add> } <add> if expected := "koye-the-protector"; container.Context["apparmor_profile"] != expected { <add> t.Fatalf("expected profile %s got %s", expected, container.Context["apparmor_profile"]) <add> } <add>} <add> <add>func TestCpuShares(t *testing.T) { <add> var ( <add> container = template.New() <add> opts = []string{ <add> "cgroups.cpu_shares=1048", <add> } <add> ) <add> if err := ParseConfiguration(container, nil, opts); err != nil { <add> t.Fatal(err) <add> } <add> <add> if expected := int64(1048); container.Cgroups.CpuShares != expected { <add> t.Fatalf("expected cpu shares %d got %d", expected, container.Cgroups.CpuShares) <add> } <add>} <add> <add>func TestCgroupMemory(t *testing.T) { <add> var ( <add> container = template.New() <add> opts = []string{ <add> "cgroups.memory=500m", <add> } <add> ) <add> if err := ParseConfiguration(container, nil, opts); err != nil { <add> t.Fatal(err) <add> } <add> <add> if expected := int64(500 * 1024 * 1024); container.Cgroups.Memory != expected { <add> t.Fatalf("expected memory %d got %d", expected, container.Cgroups.Memory) <add> } <add>} <add> <add>func TestAddCap(t *testing.T) { <add> var ( <add> container = template.New() <add> opts = []string{ <add> "cap.add=MKNOD", <add> "cap.add=SYS_ADMIN", <add> } <add> ) <add> if err := ParseConfiguration(container, nil, opts); err != nil { <add> t.Fatal(err) <add> } <add> <add> if !container.CapabilitiesMask.Get("MKNOD").Enabled { <add> t.Fatal("container should have MKNOD enabled") <add> } <add> if !container.CapabilitiesMask.Get("SYS_ADMIN").Enabled { <add> t.Fatal("container should have SYS_ADMIN enabled") <add> } <add>} <add> <add>func TestDropCap(t *testing.T) { <add> var ( <add> container = template.New() <add> opts = []string{ <add> "cap.drop=MKNOD", <add> } <add> ) <add> // enabled all caps like in privileged mode <add> for _, c := range container.CapabilitiesMask { <add> c.Enabled = true <add> } <add> if err := ParseConfiguration(container, nil, opts); err != nil { <add> t.Fatal(err) <add> } <add> <add> if container.CapabilitiesMask.Get("MKNOD").Enabled { <add> t.Fatal("container should not have MKNOD enabled") <add> } <add>} <add> <add>func TestDropNamespace(t *testing.T) { <add> var ( <add> container = template.New() <add> opts = []string{ <add> "ns.drop=NEWNET", <add> } <add> ) <add> if err := ParseConfiguration(container, nil, opts); err != nil { <add> t.Fatal(err) <add> } <add> <add> if container.Namespaces.Get("NEWNET").Enabled { <add> t.Fatal("container should not have NEWNET enabled") <add> } <add>} <ide><path>runtime/execdriver/native/create.go <ide> import ( <ide> "github.com/dotcloud/docker/pkg/libcontainer" <ide> "github.com/dotcloud/docker/runtime/execdriver" <ide> "github.com/dotcloud/docker/runtime/execdriver/native/configuration" <add> "github.com/dotcloud/docker/runtime/execdriver/native/template" <ide> "os" <ide> ) <ide> <ide> // createContainer populates and configures the container type with the <ide> // data provided by the execdriver.Command <ide> func (d *driver) createContainer(c *execdriver.Command) (*libcontainer.Container, error) { <del> container := getDefaultTemplate() <add> container := template.New() <ide> <ide> container.Hostname = getEnv("HOSTNAME", c.Env) <ide> container.Tty = c.Tty <ide> container.User = c.User <ide> container.WorkingDir = c.WorkingDir <ide> container.Env = c.Env <add> container.Cgroups.Name = c.ID <add> // check to see if we are running in ramdisk to disable pivot root <add> container.NoPivotRoot = os.Getenv("DOCKER_RAMDISK") != "" <ide> <del> loopbackNetwork := libcontainer.Network{ <del> Mtu: c.Network.Mtu, <del> Address: fmt.Sprintf("%s/%d", "127.0.0.1", 0), <del> Gateway: "localhost", <del> Type: "loopback", <del> Context: libcontainer.Context{}, <add> if err := d.createNetwork(container, c); err != nil { <add> return nil, err <ide> } <add> if c.Privileged { <add> if err := d.setPrivileged(container); err != nil { <add> return nil, err <add> } <add> } <add> if err := d.setupCgroups(container, c); err != nil { <add> return nil, err <add> } <add> if err := d.setupMounts(container, c); err != nil { <add> return nil, err <add> } <add> if err := configuration.ParseConfiguration(container, d.activeContainers, c.Config["native"]); err != nil { <add> return nil, err <add> } <add> return container, nil <add>} <ide> <add>func (d *driver) createNetwork(container *libcontainer.Container, c *execdriver.Command) error { <ide> container.Networks = []*libcontainer.Network{ <del> &loopbackNetwork, <add> { <add> Mtu: c.Network.Mtu, <add> Address: fmt.Sprintf("%s/%d", "127.0.0.1", 0), <add> Gateway: "localhost", <add> Type: "loopback", <add> Context: libcontainer.Context{}, <add> }, <ide> } <ide> <ide> if c.Network.Interface != nil { <ide> func (d *driver) createContainer(c *execdriver.Command) (*libcontainer.Container <ide> } <ide> container.Networks = append(container.Networks, &vethNetwork) <ide> } <add> return nil <add>} <ide> <del> container.Cgroups.Name = c.ID <del> if c.Privileged { <del> container.CapabilitiesMask = nil <del> container.Cgroups.DeviceAccess = true <del> container.Context["apparmor_profile"] = "unconfined" <add>func (d *driver) setPrivileged(container *libcontainer.Container) error { <add> for _, c := range container.CapabilitiesMask { <add> c.Enabled = true <ide> } <add> container.Cgroups.DeviceAccess = true <add> container.Context["apparmor_profile"] = "unconfined" <add> return nil <add>} <add> <add>func (d *driver) setupCgroups(container *libcontainer.Container, c *execdriver.Command) error { <ide> if c.Resources != nil { <ide> container.Cgroups.CpuShares = c.Resources.CpuShares <ide> container.Cgroups.Memory = c.Resources.Memory <ide> container.Cgroups.MemorySwap = c.Resources.MemorySwap <ide> } <del> // check to see if we are running in ramdisk to disable pivot root <del> container.NoPivotRoot = os.Getenv("DOCKER_RAMDISK") != "" <add> return nil <add>} <ide> <add>func (d *driver) setupMounts(container *libcontainer.Container, c *execdriver.Command) error { <ide> for _, m := range c.Mounts { <ide> container.Mounts = append(container.Mounts, libcontainer.Mount{m.Source, m.Destination, m.Writable, m.Private}) <ide> } <del> <del> if err := configuration.ParseConfiguration(container, d.activeContainers, c.Config["native"]); err != nil { <del> return nil, err <del> } <del> return container, nil <add> return nil <ide> } <add><path>runtime/execdriver/native/template/default_template.go <del><path>runtime/execdriver/native/default_template.go <del>package native <add>package template <ide> <ide> import ( <ide> "github.com/dotcloud/docker/pkg/cgroups" <ide> "github.com/dotcloud/docker/pkg/libcontainer" <ide> ) <ide> <del>// getDefaultTemplate returns the docker default for <del>// the libcontainer configuration file <del>func getDefaultTemplate() *libcontainer.Container { <add>// New returns the docker default configuration for libcontainer <add>func New() *libcontainer.Container { <ide> return &libcontainer.Container{ <ide> CapabilitiesMask: libcontainer.Capabilities{ <ide> libcontainer.GetCapability("SETPCAP"), <ide><path>runtime/utils.go <ide> package runtime <ide> <ide> import ( <add> "fmt" <ide> "github.com/dotcloud/docker/nat" <ide> "github.com/dotcloud/docker/pkg/namesgenerator" <ide> "github.com/dotcloud/docker/runconfig" <add> "strings" <ide> ) <ide> <ide> func migratePortMappings(config *runconfig.Config, hostConfig *runconfig.HostConfig) error { <ide> func migratePortMappings(config *runconfig.Config, hostConfig *runconfig.HostCon <ide> return nil <ide> } <ide> <add>func mergeLxcConfIntoOptions(hostConfig *runconfig.HostConfig, driverConfig map[string][]string) { <add> if hostConfig == nil { <add> return <add> } <add> <add> // merge in the lxc conf options into the generic config map <add> if lxcConf := hostConfig.LxcConf; lxcConf != nil { <add> lxc := driverConfig["lxc"] <add> for _, pair := range lxcConf { <add> // because lxc conf gets the driver name lxc.XXXX we need to trim it off <add> // and let the lxc driver add it back later if needed <add> parts := strings.SplitN(pair.Key, ".", 2) <add> lxc = append(lxc, fmt.Sprintf("%s=%s", parts[1], pair.Value)) <add> } <add> driverConfig["lxc"] = lxc <add> } <add>} <add> <ide> type checker struct { <ide> runtime *Runtime <ide> } <ide><path>runtime/utils_test.go <add>package runtime <add> <add>import ( <add> "github.com/dotcloud/docker/runconfig" <add> "testing" <add>) <add> <add>func TestMergeLxcConfig(t *testing.T) { <add> var ( <add> hostConfig = &runconfig.HostConfig{ <add> LxcConf: []runconfig.KeyValuePair{ <add> {Key: "lxc.cgroups.cpuset", Value: "1,2"}, <add> }, <add> } <add> driverConfig = make(map[string][]string) <add> ) <add> <add> mergeLxcConfIntoOptions(hostConfig, driverConfig) <add> if l := len(driverConfig["lxc"]); l > 1 { <add> t.Fatalf("expected lxc options len of 1 got %d", l) <add> } <add> <add> cpuset := driverConfig["lxc"][0] <add> if expected := "cgroups.cpuset=1,2"; cpuset != expected { <add> t.Fatalf("expected %s got %s", expected, cpuset) <add> } <add>}
8
Ruby
Ruby
add example to collectionassociation#destroy_all
fcc13f46f5f8db2a7010c00bd209d442461e948d
<ide><path>activerecord/lib/active_record/associations/collection_association.rb <ide> module Associations <ide> # <ide> # CollectionAssociation is an abstract class that provides common stuff to <ide> # ease the implementation of association proxies that represent <del> # collections. See the class hierarchy in AssociationProxy <add> # collections. See the class hierarchy in AssociationProxy. <ide> # <ide> # CollectionAssociation: <ide> # HasAndBelongsToManyAssociation => has_and_belongs_to_many <ide> # HasManyAssociation => has_many <ide> # HasManyThroughAssociation + ThroughAssociation => has_many :through <ide> # <ide> # CollectionAssociation class provides common methods to the collections <del> # defined by +has_and_belongs_to_many+, +has_many+ and +has_many+ with <add> # defined by +has_and_belongs_to_many+, +has_many+ or +has_many+ with <ide> # +:through+ association option. <ide> # <ide> # You need to be careful with assumptions regarding the target: The proxy <ide> def delete_all_on_destroy <ide> <ide> # Destroy all the records from this association. <ide> # <add> # class Person < ActiveRecord::Base <add> # has_many :pets <add> # end <add> # <add> # person.pets.size # => 3 <add> # <add> # person.pets.destroy_all <add> # <add> # person.pets.size # => 0 <add> # person.pets # => [] <add> # <ide> # See destroy for more info. <ide> def destroy_all <ide> destroy(load_target).tap do <ide> def destroy_all <ide> end <ide> end <ide> <del> # Calculate sum using SQL, not Enumerable <add> # Calculate sum using SQL, not Enumerable. <ide> def sum(*args) <ide> if block_given? <ide> scoped.sum(*args) { |*block_args| yield(*block_args) }
1
Mixed
Javascript
change windowshide default to true
420d8afe3db22ad703e74892f58f9e32d34ff699
<ide><path>doc/api/child_process.md <ide> exec('"my script.cmd" a b', (err, stdout, stderr) => { <ide> <!-- YAML <ide> added: v0.1.90 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/21316 <add> description: The `windowsHide` option now defaults to `true`. <ide> - version: v8.8.0 <ide> pr-url: https://github.com/nodejs/node/pull/15380 <ide> description: The `windowsHide` option is supported now. <ide> changes: <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> * `windowsHide` {boolean} Hide the subprocess console window that would <del> normally be created on Windows systems. **Default:** `false`. <add> normally be created on Windows systems. **Default:** `true`. <ide> * `callback` {Function} called with the output when process terminates. <ide> * `error` {Error} <ide> * `stdout` {string|Buffer} <ide> lsExample(); <ide> <!-- YAML <ide> added: v0.1.91 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/21316 <add> description: The `windowsHide` option now defaults to `true`. <ide> - version: v8.8.0 <ide> pr-url: https://github.com/nodejs/node/pull/15380 <ide> description: The `windowsHide` option is supported now. <ide> changes: <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> * `windowsHide` {boolean} Hide the subprocess console window that would <del> normally be created on Windows systems. **Default:** `false`. <add> normally be created on Windows systems. **Default:** `true`. <ide> * `windowsVerbatimArguments` {boolean} No quoting or escaping of arguments is <ide> done on Windows. Ignored on Unix. **Default:** `false`. <ide> * `shell` {boolean|string} If `true`, runs `command` inside of a shell. Uses <ide> The `shell` option available in [`child_process.spawn()`][] is not supported by <ide> <!-- YAML <ide> added: v0.1.90 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/21316 <add> description: The `windowsHide` option now defaults to `true`. <ide> - version: v8.8.0 <ide> pr-url: https://github.com/nodejs/node/pull/15380 <ide> description: The `windowsHide` option is supported now. <ide> changes: <ide> done on Windows. Ignored on Unix. This is set to `true` automatically <ide> when `shell` is specified. **Default:** `false`. <ide> * `windowsHide` {boolean} Hide the subprocess console window that would <del> normally be created on Windows systems. **Default:** `false`. <add> normally be created on Windows systems. **Default:** `true`. <ide> * Returns: {ChildProcess} <ide> <ide> The `child_process.spawn()` method spawns a new process using the given <ide> configuration at startup. <ide> <!-- YAML <ide> added: v0.11.12 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/21316 <add> description: The `windowsHide` option now defaults to `true`. <ide> - version: v8.8.0 <ide> pr-url: https://github.com/nodejs/node/pull/15380 <ide> description: The `windowsHide` option is supported now. <ide> changes: <ide> * `encoding` {string} The encoding used for all stdio inputs and outputs. <ide> **Default:** `'buffer'`. <ide> * `windowsHide` {boolean} Hide the subprocess console window that would <del> normally be created on Windows systems. **Default:** `false`. <add> normally be created on Windows systems. **Default:** `true`. <ide> * `shell` {boolean|string} If `true`, runs `command` inside of a shell. Uses <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> arbitrary command execution.** <ide> <!-- YAML <ide> added: v0.11.12 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/21316 <add> description: The `windowsHide` option now defaults to `true`. <ide> - version: v8.8.0 <ide> pr-url: https://github.com/nodejs/node/pull/15380 <ide> description: The `windowsHide` option is supported now. <ide> changes: <ide> * `encoding` {string} The encoding used for all stdio inputs and outputs. <ide> **Default:** `'buffer'`. <ide> * `windowsHide` {boolean} Hide the subprocess console window that would <del> normally be created on Windows systems. **Default:** `false`. <add> normally be created on Windows systems. **Default:** `true`. <ide> * Returns: {Buffer|string} The stdout from the command. <ide> <ide> The `child_process.execSync()` method is generally identical to <ide> metacharacters may be used to trigger arbitrary command execution.** <ide> <!-- YAML <ide> added: v0.11.12 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/21316 <add> description: The `windowsHide` option now defaults to `true`. <ide> - version: v8.8.0 <ide> pr-url: https://github.com/nodejs/node/pull/15380 <ide> description: The `windowsHide` option is supported now. <ide> changes: <ide> done on Windows. Ignored on Unix. This is set to `true` automatically <ide> when `shell` is specified. **Default:** `false`. <ide> * `windowsHide` {boolean} Hide the subprocess console window that would <del> normally be created on Windows systems. **Default:** `false`. <add> normally be created on Windows systems. **Default:** `true`. <ide> * Returns: {Object} <ide> * `pid` {number} Pid of the child process. <ide> * `output` {Array} Array of results from stdio output. <ide><path>doc/api/cluster.md <ide> values are `'rr'` and `'none'`. <ide> <!-- YAML <ide> added: v0.7.1 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/21316 <add> description: The `windowsHide` option now defaults to `true`. <ide> - version: v9.5.0 <ide> pr-url: https://github.com/nodejs/node/pull/18399 <ide> description: The `cwd` option is supported now. <ide> changes: <ide> number. By default each worker gets its own port, incremented from the <ide> master's `process.debugPort`. <ide> * `windowsHide` {boolean} Hide the forked processes console window that would <del> normally be created on Windows systems. **Default:** `false`. <add> normally be created on Windows systems. **Default:** `true`. <ide> <ide> After calling `.setupMaster()` (or `.fork()`) this settings object will contain <ide> the settings, including the default values. <ide><path>lib/child_process.js <ide> exports.execFile = function execFile(file /* , args, options, callback */) { <ide> gid: options.gid, <ide> uid: options.uid, <ide> shell: options.shell, <del> windowsHide: !!options.windowsHide, <add> windowsHide: options.windowsHide !== false, <ide> windowsVerbatimArguments: !!options.windowsVerbatimArguments <ide> }); <ide> <ide> var spawn = exports.spawn = function spawn(/* file, args, options */) { <ide> file: opts.file, <ide> args: opts.args, <ide> cwd: options.cwd, <del> windowsHide: !!options.windowsHide, <add> windowsHide: options.windowsHide !== false, <ide> windowsVerbatimArguments: !!options.windowsVerbatimArguments, <ide> detached: !!options.detached, <ide> envPairs: opts.envPairs, <ide> function spawnSync(/* file, args, options */) { <ide> <ide> options.stdio = _validateStdio(options.stdio || 'pipe', true).stdio; <ide> <add> options.windowsHide = options.windowsHide !== false; <add> <ide> if (options.input) { <ide> var stdin = options.stdio[0] = util._extend({}, options.stdio[0]); <ide> stdin.input = options.input; <ide><path>test/parallel/test-child-process-spawnsync-shell.js <ide> assert.strictEqual(env.stdout.toString().trim(), 'buzz'); <ide> assert.strictEqual(opts.options.shell, shell); <ide> assert.strictEqual(opts.options.file, opts.file); <ide> assert.deepStrictEqual(opts.options.args, opts.args); <del> assert.strictEqual(opts.options.windowsHide, undefined); <add> assert.strictEqual(opts.options.windowsHide, true); <ide> assert.strictEqual(opts.options.windowsVerbatimArguments, <ide> windowsVerbatim); <ide> });
4
Python
Python
restore tok2vec function
fa7c1990b6bb094c82271586739a4ce036f3ae61
<ide><path>spacy/_ml.py <del>from thinc.api import layerize, chain, clone <add>from thinc.api import layerize, chain, clone, concatenate <ide> from thinc.neural import Model, Maxout, Softmax <ide> from thinc.neural._classes.hash_embed import HashEmbed <del>from .attrs import TAG, DEP <add> <add>from thinc.neural._classes.convolution import ExtractWindow <add>from thinc.neural._classes.static_vectors import StaticVectors <add> <add>from .attrs import ID, PREFIX, SUFFIX, SHAPE, TAG, DEP <ide> <ide> <ide> def get_col(idx): <ide> def backward(d_y, sgd=None): <ide> model._layers.append(layer) <ide> return model <ide> <del>#from thinc.api import layerize, chain, clone, concatenate, add <del># from thinc.neural._classes.convolution import ExtractWindow <del># from thinc.neural._classes.static_vectors import StaticVectors <del> <del>#def build_tok2vec(lang, width, depth, embed_size, cols): <del># with Model.define_operators({'>>': chain, '|': concatenate, '**': clone}): <del># static = get_col(cols.index(ID)) >> StaticVectors(lang, width) <del># prefix = get_col(cols.index(PREFIX)) >> HashEmbed(width, embed_size) <del># suffix = get_col(cols.index(SUFFIX)) >> HashEmbed(width, embed_size) <del># shape = get_col(cols.index(SHAPE)) >> HashEmbed(width, embed_size) <del># tok2vec = ( <del># (static | prefix | suffix | shape) <del># >> Maxout(width, width*4) <del># >> (ExtractWindow(nW=1) >> Maxout(width, width*3)) ** depth <del># ) <del># return tok2vec <add>def build_tok2vec(lang, width, depth, embed_size, cols): <add> with Model.define_operators({'>>': chain, '|': concatenate, '**': clone}): <add> static = get_col(cols.index(ID)) >> StaticVectors(lang, width) <add> prefix = get_col(cols.index(PREFIX)) >> HashEmbed(width, embed_size) <add> suffix = get_col(cols.index(SUFFIX)) >> HashEmbed(width, embed_size) <add> shape = get_col(cols.index(SHAPE)) >> HashEmbed(width, embed_size) <add> tok2vec = ( <add> (static | prefix | suffix | shape) <add> >> Maxout(width, width*4) <add> >> (ExtractWindow(nW=1) >> Maxout(width, width*3)) ** depth <add> ) <add> return tok2vec
1
Ruby
Ruby
fix info/options for new options dsl
e196c845bf3099a1aaf7264fe87fa4e40ea8e2e6
<ide><path>Library/Homebrew/cmd/info.rb <ide> def info_formula f <ide> history = github_info(f) <ide> puts history if history <ide> <del> unless f.options.empty? <add> unless f.build.empty? <ide> require 'cmd/options' <ide> ohai "Options" <ide> Homebrew.dump_options_for_formula f <ide><path>Library/Homebrew/cmd/options.rb <ide> def options <ide> end <ide> <ide> def dump_options_for_formula f <del> f.options.each do |k,v| <add> f.build.each do |k,v| <ide> puts k <ide> puts "\t"+v <ide> end
2
Ruby
Ruby
remove unnecessary call to #tap
d97ba0d31bd10cd793649dbeb9e972edf3934fa7
<ide><path>actionpack/test/dispatch/routing_test.rb <ide> def test_enforce_with_string <ide> class TestCallableConstraintValidation < ActionDispatch::IntegrationTest <ide> def test_constraint_with_object_not_callable <ide> assert_raises(ArgumentError) do <del> ActionDispatch::Routing::RouteSet.new.tap do |app| <del> app.draw do <del> ok = lambda { |env| [200, { 'Content-Type' => 'text/plain' }, []] } <del> get '/test', to: ok, constraints: Object.new <del> end <add> ActionDispatch::Routing::RouteSet.new.draw do <add> ok = lambda { |env| [200, { 'Content-Type' => 'text/plain' }, []] } <add> get '/test', to: ok, constraints: Object.new <ide> end <ide> end <ide> end
1
Text
Text
fix code snippet
1aec8aeefc2ad6ccb39ef6c43d03ed86e0adb6ef
<ide><path>docs/templates/constraints.md <ide> These layers expose 2 keyword arguments: <ide> <ide> <ide> ```python <del>from keras.constraints import maxnorm <add>from keras.constraints import max_norm <ide> model.add(Dense(64, kernel_constraint=max_norm(2.))) <ide> ``` <ide>
1
Text
Text
fix doc styles
986be03a4c349dcac7a5fa4c85d81a25af50f02f
<ide><path>CONTRIBUTING.md <ide> By making a contribution to this project, I certify that: <ide> [Building guide]: ./BUILDING.md <ide> [CI (Continuous Integration) test run]: #ci-testing <ide> [Code of Conduct]: https://github.com/nodejs/TSC/blob/master/CODE_OF_CONDUCT.md <del>[guide for writing tests in Node.js]: ./doc/guides/writing-tests.md <ide> [https://ci.nodejs.org/]: https://ci.nodejs.org/ <ide> [IRC in the #node-dev channel]: https://webchat.freenode.net?channels=node-dev&uio=d4 <ide> [Node.js help repository]: https://github.com/nodejs/help/issues <del>[notes about the waiting time]: #waiting-until-the-pull-request-gets-landed <ide> [Onboarding guide]: ./doc/onboarding.md <del>[on GitHub]: https://github.com/nodejs/node <ide> [Technical Steering Committee (TSC) repository]: https://github.com/nodejs/TSC/issues <ide><path>doc/api/assert.md <ide> assert(Object.is(str1 / 1, str2 / 1)); <ide> For more information, see <ide> [MDN's guide on equality comparisons and sameness][mdn-equality-guide]. <ide> <del>[`Error`]: errors.html#errors_class_error <ide> [`Error.captureStackTrace`]: errors.html#errors_error_capturestacktrace_targetobject_constructoropt <ide> [`Map`]: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map <ide> [`Object.is()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is <ide><path>doc/api/async_hooks.md <ide> new Promise((resolve) => resolve(true)).then((a) => {}); <ide> <ide> calls the following callbacks: <ide> <del>``` <add>```text <ide> init for PROMISE with id 5, trigger id: 1 <ide> promise resolve 5 # corresponds to resolve(true) <ide> init for PROMISE with id 6, trigger id: 5 # the Promise returned by then() <ide><path>doc/api/child_process.md <ide> unavailable. <ide> [`Error`]: errors.html#errors_class_error <ide> [`EventEmitter`]: events.html#events_class_eventemitter <ide> [`JSON.stringify` spec]: https://tc39.github.io/ecma262/#sec-json.stringify <del>[`JSON.stringify()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify <ide> [`subprocess.connected`]: #child_process_subprocess_connected <ide> [`subprocess.disconnect()`]: #child_process_subprocess_disconnect <ide> [`subprocess.kill()`]: #child_process_subprocess_kill_signal <ide><path>doc/api/dns.md <ide> uses. For instance, _they do not use the configuration from `/etc/hosts`_. <ide> [Implementation considerations section]: #dns_implementation_considerations <ide> [rfc5952]: https://tools.ietf.org/html/rfc5952#section-6 <ide> [supported `getaddrinfo` flags]: #dns_supported_getaddrinfo_flags <del>[the official libuv documentation]: http://docs.libuv.org/en/latest/threadpool.html <ide><path>doc/api/esm.md <ide> export function resolve(specifier, parentModuleURL/*, defaultResolve */) { <ide> <ide> With this loader, running: <ide> <del>``` <add>```console <ide> NODE_OPTIONS='--experimental-modules --loader ./custom-loader.mjs' node x.js <ide> ``` <ide> <ide><path>doc/api/http.md <ide> const req = http.request(options, (res) => { <ide> ``` <ide> <ide> [`'checkContinue'`]: #http_event_checkcontinue <del>[`'listening'`]: net.html#net_event_listening <ide> [`'request'`]: #http_event_request <ide> [`'response'`]: #http_event_response <ide> [`Agent`]: #http_class_http_agent <ide> const req = http.request(options, (res) => { <ide> [`http.request()`]: #http_http_request_options_callback <ide> [`message.headers`]: #http_message_headers <ide> [`net.Server.close()`]: net.html#net_server_close_callback <del>[`net.Server.listen()`]: net.html#net_server_listen_handle_backlog_callback <del>[`net.Server.listen(path)`]: net.html#net_server_listen_path_backlog_callback <del>[`net.Server.listen(port)`]: net.html#net_server_listen_port_host_backlog_callback <ide> [`net.Server`]: net.html#net_class_net_server <ide> [`net.Socket`]: net.html#net_class_net_socket <ide> [`net.createConnection()`]: net.html#net_net_createconnection_options_connectlistener <ide> const req = http.request(options, (res) => { <ide> [Readable Stream]: stream.html#stream_class_stream_readable <ide> [Writable Stream]: stream.html#stream_class_stream_writable <ide> [socket.unref()]: net.html#net_socket_unref <del>[unspecified IPv4 address]: https://en.wikipedia.org/wiki/0.0.0.0 <del>[unspecified IPv6 address]: https://en.wikipedia.org/wiki/IPv6_address#Unspecified_address <ide><path>doc/api/https.md <ide> const req = https.request(options, (res) => { <ide> [`http.Server`]: http.html#http_class_http_server <ide> [`http.close()`]: http.html#http_server_close_callback <ide> [`http.get()`]: http.html#http_http_get_options_callback <del>[`http.listen()`]: http.html#http_server_listen_port_hostname_backlog_callback <ide> [`http.request()`]: http.html#http_http_request_options_callback <ide> [`https.Agent`]: #https_class_https_agent <ide> [`https.request()`]: #https_https_request_options_callback <ide><path>doc/api/os.md <ide> information. <ide> <ide> [`process.arch`]: process.html#process_process_arch <ide> [`process.platform`]: process.html#process_process_platform <del>[OS Constants]: #os_os_constants <ide> [uname(3)]: https://linux.die.net/man/3/uname <ide><path>doc/api/process.md <ide> cases: <ide> [`Error`]: errors.html#errors_class_error <ide> [`EventEmitter`]: events.html#events_class_eventemitter <ide> [`JSON.stringify` spec]: https://tc39.github.io/ecma262/#sec-json.stringify <del>[`JSON.stringify()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify <ide> [`console.error()`]: console.html#console_console_error_data_args <ide> [`console.log()`]: console.html#console_console_log_data_args <ide> [`end()`]: stream.html#stream_writable_end_chunk_encoding_callback <ide><path>doc/api/stream.md <ide> contain multi-byte characters. <ide> [http-incoming-message]: http.html#http_class_http_incomingmessage <ide> [zlib]: zlib.html <ide> [hwm-gotcha]: #stream_highwatermark_discrepency_after_calling_readable_setencoding <del>[Readable]: #stream_class_stream_readable <ide> [stream-_flush]: #stream_transform_flush_callback <ide> [stream-_read]: #stream_readable_read_size_1 <ide> [stream-_transform]: #stream_transform_transform_chunk_encoding_callback <ide><path>doc/guides/writing-and-running-benchmarks.md <ide> Supported options keys are: <ide> [t-test]: https://en.wikipedia.org/wiki/Student%27s_t-test#Equal_or_unequal_sample_sizes.2C_unequal_variances <ide> [git-for-windows]: http://git-scm.com/download/win <ide> [nghttp2.org]: http://nghttp2.org <del>[benchmark-ci]: https://github.com/nodejs/benchmarking/blob/master/docs/core_benchmarks.md <ide>\ No newline at end of file <add>[benchmark-ci]: https://github.com/nodejs/benchmarking/blob/master/docs/core_benchmarks.md
12
Text
Text
fix broken links in russian challenges
82b340d42980075f24b80dc7078ff6faf94d003f
<ide><path>curriculum/challenges/russian/02-javascript-algorithms-and-data-structures/basic-javascript/assignment-with-a-returned-value.russian.md <ide> localeTitle: Назначение с возвращенной стоимость <ide> --- <ide> <ide> ## Description <del><section id="description"> Если вы вспомните из нашего обсуждения « <a href="javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator" target="_blank">Сохранение значений с помощью оператора назначения»</a> , все, что находится справа от знака равенства, будет разрешено до присвоения значения. Это означает, что мы можем взять возвращаемое значение функции и присвоить ее переменной. Предположим, что мы предварительно определили <code>sum</code> функций, которая объединяет два числа, а затем: <code>ourSum = sum(5, 12);</code> вызовет функцию <code>sum</code> , которая возвращает значение <code>17</code> и присваивает ее переменной <code>ourSum</code> . </section> <add><section id="description"> Если вы вспомните из нашего обсуждения « <a href="learn/javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator" target="_blank">Сохранение значений с помощью оператора назначения»</a> , все, что находится справа от знака равенства, будет разрешено до присвоения значения. Это означает, что мы можем взять возвращаемое значение функции и присвоить ее переменной. Предположим, что мы предварительно определили <code>sum</code> функций, которая объединяет два числа, а затем: <code>ourSum = sum(5, 12);</code> вызовет функцию <code>sum</code> , которая возвращает значение <code>17</code> и присваивает ее переменной <code>ourSum</code> . </section> <ide> <ide> ## Instructions <ide> <section id="instructions"> Вызовите функцию <code>processArg</code> с аргументом <code>7</code> и назначьте его возвращаемое значение <code>processed</code> переменной. </section> <ide><path>curriculum/challenges/russian/02-javascript-algorithms-and-data-structures/basic-javascript/generate-random-fractions-with-javascript.russian.md <ide> localeTitle: Генерировать случайные дроби с помо <ide> --- <ide> <ide> ## Description <del><section id="description"> Случайные числа полезны для создания случайного поведения. JavaScript имеет функцию <code>Math.random()</code> которая генерирует случайное десятичное число между <code>0</code> (включительно) и не совсем до <code>1</code> (исключая). Таким образом, <code>Math.random()</code> может возвращать <code>0</code> но никогда не возвращать <code>1</code> <strong>Примечание</strong> <br> Подобно <a href="storing-values-with-the-assignment-operator" target="_blank">сохранению значений с помощью Equal Operator</a> , все вызовы функций будут разрешены до выполнения <code>return</code> , поэтому мы можем <code>return</code> значение функции <code>Math.random()</code> . </section> <add><section id="description"> Случайные числа полезны для создания случайного поведения. JavaScript имеет функцию <code>Math.random()</code> которая генерирует случайное десятичное число между <code>0</code> (включительно) и не совсем до <code>1</code> (исключая). Таким образом, <code>Math.random()</code> может возвращать <code>0</code> но никогда не возвращать <code>1</code> <strong>Примечание</strong> <br> Подобно <a href="learn/javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator" target="_blank">сохранению значений с помощью Equal Operator</a> , все вызовы функций будут разрешены до выполнения <code>return</code> , поэтому мы можем <code>return</code> значение функции <code>Math.random()</code> . </section> <ide> <ide> ## Instructions <ide> <section id="instructions"> Измените <code>randomFraction</code> чтобы вернуть случайное число вместо возврата <code>0</code> . </section> <ide><path>curriculum/challenges/russian/02-javascript-algorithms-and-data-structures/basic-javascript/record-collection.russian.md <ide> localeTitle: Коллекция записей <ide> --- <ide> <ide> ## Description <del><section id="description"> Вам предоставляется объект JSON, представляющий часть вашей коллекции музыкальных альбомов. Каждый альбом имеет несколько свойств и уникальный идентификационный номер в качестве ключа. Не все альбомы имеют полную информацию. Напишите функцию, которая принимает <code>id</code> альбома (например, <code>2548</code> ), свойство <code>prop</code> (например, <code>&quot;artist&quot;</code> или <code>&quot;tracks&quot;</code> ) и <code>value</code> (например, <code>&quot;Addicted to Love&quot;</code> ) для изменения данных в этой коллекции. Если <code>prop</code> не является <code>&quot;tracks&quot;</code> а <code>value</code> не пусто ( <code>&quot;&quot;</code> ), обновите или установите <code>value</code> для свойства этого альбома записи. Ваша функция всегда должна возвращать весь объект коллекции. Существует несколько правил обработки неполных данных: если <code>prop</code> является <code>&quot;tracks&quot;</code> но альбом не имеет свойства <code>&quot;tracks&quot;</code> , создайте пустой массив перед добавлением нового значения в соответствующее свойство альбома. Если <code>prop</code> - это <code>&quot;tracks&quot;</code> а <code>value</code> не пусто ( <code>&quot;&quot;</code> ), нажмите <code>value</code> в конец существующего массива <code>tracks</code> . Если <code>value</code> пусто ( <code>&quot;&quot;</code> ), удалите данное свойство <code>prop</code> из альбома. <strong>Советы</strong> <br> Используйте <code>bracket notation</code> при <a href="javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-variables" target="_blank">доступе к свойствам объекта с переменными</a> . Push - метод массива, который вы можете прочитать в <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push" target="_blank">Mozilla Developer Network</a> . Вы можете обратиться к <a href="javascript-algorithms-and-data-structures/basic-javascript/manipulating-complex-objects" target="_blank">Манипулированию сложными объектами,</a> представляющими Обозначение <a href="javascript-algorithms-and-data-structures/basic-javascript/manipulating-complex-objects" target="_blank">объектов</a> JavaScript (JSON) для обновления. </section> <add><section id="description"> Вам предоставляется объект JSON, представляющий часть вашей коллекции музыкальных альбомов. Каждый альбом имеет несколько свойств и уникальный идентификационный номер в качестве ключа. Не все альбомы имеют полную информацию. Напишите функцию, которая принимает <code>id</code> альбома (например, <code>2548</code> ), свойство <code>prop</code> (например, <code>&quot;artist&quot;</code> или <code>&quot;tracks&quot;</code> ) и <code>value</code> (например, <code>&quot;Addicted to Love&quot;</code> ) для изменения данных в этой коллекции. Если <code>prop</code> не является <code>&quot;tracks&quot;</code> а <code>value</code> не пусто ( <code>&quot;&quot;</code> ), обновите или установите <code>value</code> для свойства этого альбома записи. Ваша функция всегда должна возвращать весь объект коллекции. Существует несколько правил обработки неполных данных: если <code>prop</code> является <code>&quot;tracks&quot;</code> но альбом не имеет свойства <code>&quot;tracks&quot;</code> , создайте пустой массив перед добавлением нового значения в соответствующее свойство альбома. Если <code>prop</code> - это <code>&quot;tracks&quot;</code> а <code>value</code> не пусто ( <code>&quot;&quot;</code> ), нажмите <code>value</code> в конец существующего массива <code>tracks</code> . Если <code>value</code> пусто ( <code>&quot;&quot;</code> ), удалите данное свойство <code>prop</code> из альбома. <strong>Советы</strong> <br> Используйте <code>bracket notation</code> при <a href="learn/javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-variables" target="_blank">доступе к свойствам объекта с переменными</a> . Push - метод массива, который вы можете прочитать в <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push" target="_blank">Mozilla Developer Network</a> . Вы можете обратиться к <a href="learn/javascript-algorithms-and-data-structures/basic-javascript/manipulating-complex-objects" target="_blank">Манипулированию сложными объектами,</a> представляющими Обозначение <a href="javascript-algorithms-and-data-structures/basic-javascript/manipulating-complex-objects" target="_blank">объектов</a> JavaScript (JSON) для обновления. </section> <ide> <ide> ## Instructions <ide> <section id="instructions"> <ide><path>curriculum/challenges/russian/02-javascript-algorithms-and-data-structures/basic-javascript/returning-boolean-values-from-functions.russian.md <ide> localeTitle: Возврат булевых значений из функций <ide> --- <ide> <ide> ## Description <del><section id="description"> Вы можете вспомнить из <a href="waypoint-comparison-with-the-equality-operator" target="_blank">сравнения с Оператором равенства,</a> что все операторы сравнения возвращают логическое <code>true</code> или <code>false</code> значение. Иногда люди используют оператор if / else для сравнения, например: <blockquote> функция isEqual (a, b) { <br> if (a === b) { <br> return true; <br> } else { <br> return false; <br> } <br> } </blockquote> Но есть лучший способ сделать это. Поскольку <code>===</code> возвращает <code>true</code> или <code>false</code> , мы можем вернуть результат сравнения: <blockquote> функция isEqual (a, b) { <br> return a === b; <br> } </blockquote></section> <add><section id="description"> Вы можете вспомнить из <a href="learn/javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-equality-operator" target="_blank">сравнения с Оператором равенства,</a> что все операторы сравнения возвращают логическое <code>true</code> или <code>false</code> значение. Иногда люди используют оператор if / else для сравнения, например: <blockquote> функция isEqual (a, b) { <br> if (a === b) { <br> return true; <br> } else { <br> return false; <br> } <br> } </blockquote> Но есть лучший способ сделать это. Поскольку <code>===</code> возвращает <code>true</code> или <code>false</code> , мы можем вернуть результат сравнения: <blockquote> функция isEqual (a, b) { <br> return a === b; <br> } </blockquote></section> <ide> <ide> ## Instructions <ide> <section id="instructions"> Исправить функцию <code>isLess</code> чтобы удалить инструкции <code>if/else</code> . </section> <ide><path>curriculum/challenges/russian/03-front-end-libraries/react/introducing-inline-styles.russian.md <ide> localeTitle: Представление встроенных стилей <ide> --- <ide> <ide> ## Description <del><section id="description"> Существуют и другие сложные концепции, которые добавляют мощные возможности для вашего кода React. Но вам может быть интересно узнать о более простой проблеме того, как стилизовать те элементы JSX, которые вы создаете в React. Вероятно, вы знаете, что это будет не то же самое, что работать с HTML из-за <a target="_blank" href="front-end-libraries/react/define-an-html-class-in-jsx">того, как вы применяете классы к элементам JSX</a> . Если вы импортируете стили из таблицы стилей, это совсем не так. Вы применяете класс к своему элементу JSX, используя атрибут <code>className</code> , и применяете стили к классу в таблице стилей. Другой вариант - применить <strong><em>встроенные</em></strong> стили, которые очень распространены в разработке ReactJS. Вы применяете встроенные стили к элементам JSX, подобным тому, как это делается в HTML, но с несколькими отличиями JSX. Ниже приведен пример встроенного стиля в HTML: <code>&lt;div style=&quot;color: yellow; font-size: 16px&quot;&gt;Mellow Yellow&lt;/div&gt;</code> Элементы JSX используют атрибут <code>style</code> , но из-за того, что JSX переполнен, вы можете &#39;t установить значение в <code>string</code> . Вместо этого вы устанавливаете его равным <code>object</code> JavaScript. Вот пример: <code>&lt;div style={{color: &quot;yellow&quot;, fontSize: 16}}&gt;Mellow Yellow&lt;/div&gt;</code> Обратите внимание, как мы camelCase свойство fontSize? Это связано с тем, что React не будет принимать ключи кебаба в объекте стиля. React применит правильное имя свойства для нас в HTML. </section> <add><section id="description"> Существуют и другие сложные концепции, которые добавляют мощные возможности для вашего кода React. Но вам может быть интересно узнать о более простой проблеме того, как стилизовать те элементы JSX, которые вы создаете в React. Вероятно, вы знаете, что это будет не то же самое, что работать с HTML из-за <a target="_blank" href="learn/front-end-libraries/react/define-an-html-class-in-jsx">того, как вы применяете классы к элементам JSX</a> . Если вы импортируете стили из таблицы стилей, это совсем не так. Вы применяете класс к своему элементу JSX, используя атрибут <code>className</code> , и применяете стили к классу в таблице стилей. Другой вариант - применить <strong><em>встроенные</em></strong> стили, которые очень распространены в разработке ReactJS. Вы применяете встроенные стили к элементам JSX, подобным тому, как это делается в HTML, но с несколькими отличиями JSX. Ниже приведен пример встроенного стиля в HTML: <code>&lt;div style=&quot;color: yellow; font-size: 16px&quot;&gt;Mellow Yellow&lt;/div&gt;</code> Элементы JSX используют атрибут <code>style</code> , но из-за того, что JSX переполнен, вы можете &#39;t установить значение в <code>string</code> . Вместо этого вы устанавливаете его равным <code>object</code> JavaScript. Вот пример: <code>&lt;div style={{color: &quot;yellow&quot;, fontSize: 16}}&gt;Mellow Yellow&lt;/div&gt;</code> Обратите внимание, как мы camelCase свойство fontSize? Это связано с тем, что React не будет принимать ключи кебаба в объекте стиля. React применит правильное имя свойства для нас в HTML. </section> <ide> <ide> ## Instructions <ide> <section id="instructions"> Добавьте атрибут <code>style</code> в <code>div</code> в редакторе кода, чтобы придать тексту цвет красного и размер шрифта 72px. Обратите внимание, что вы можете указать размер шрифта как число, опустив единицы «px» или записать его как «72px». </section>
5
Ruby
Ruby
fix #not to stop wrapping in a grouping node
dbc86c0f2c2fc3c8bacf35c67fb8e0967b0a8980
<ide><path>lib/arel/nodes/node.rb <ide> class Node <ide> # Factory method to create a Nodes::Not node that has the recipient of <ide> # the caller as a child. <ide> def not <del> Nodes::Not.new Nodes::Grouping.new self <add> Nodes::Not.new self <ide> end <ide> <ide> ### <ide><path>test/nodes/test_not.rb <ide> module Nodes <ide> describe '#not' do <ide> it 'makes a NOT node' do <ide> attr = Table.new(:users)[:id] <del> left = attr.eq(10) <del> right = attr.eq(11) <del> node = left.or right <del> node.expr.left.must_equal left <del> node.expr.right.must_equal right <del> <del> node.or(right).not <add> expr = attr.eq(10) <add> node = expr.not <add> node.must_be_kind_of Not <add> node.expr.must_equal expr <ide> end <ide> end <ide> end
2
PHP
PHP
run provider boot method through container call
8056d41b148dfca2d2f73a5c325e8fc91ecff3c5
<ide><path>src/Illuminate/Foundation/Application.php <ide> use Illuminate\Container\Container; <ide> use Illuminate\Filesystem\Filesystem; <ide> use Illuminate\Support\Facades\Facade; <add>use Illuminate\Support\ServiceProvider; <ide> use Illuminate\Events\EventServiceProvider; <ide> use Illuminate\Routing\RoutingServiceProvider; <ide> use Illuminate\Exception\ExceptionServiceProvider; <ide> public function register($provider, $options = array(), $force = false) <ide> // If the application has already booted, we will call this boot method on <ide> // the provider class so it has an opportunity to do its boot logic and <ide> // will be ready for any usage by the developer's application logics. <del> if ($this->booted) $provider->boot(); <add> if ($this->booted) <add> { <add> $this->bootProvider($provider); <add> } <ide> <ide> return $provider; <ide> } <ide> public function registerDeferredProvider($provider, $service = null) <ide> { <ide> $this->booting(function() use ($instance) <ide> { <del> $instance->boot(); <add> $this->bootProvider($instance); <ide> }); <ide> } <ide> } <ide> public function boot() <ide> { <ide> if ($this->booted) return; <ide> <del> array_walk($this->serviceProviders, function($p) { $p->boot(); }); <add> array_walk($this->serviceProviders, function($p) { $this->bootProvider($p); }); <ide> <ide> $this->bootApplication(); <ide> } <ide> public function booted($callback) <ide> if ($this->isBooted()) $this->fireAppCallbacks(array($callback)); <ide> } <ide> <add> /** <add> * Boot the given service provider. <add> * <add> * @param \Illuminate\Support\ServiceProvider $provider <add> * @return void <add> */ <add> protected function bootProvider(ServiceProvider $provider) <add> { <add> return $this->call([$provider, 'boot']); <add> } <add> <ide> /** <ide> * Run the application and send the response. <ide> *
1
Javascript
Javascript
remove an unused internal module `assertport`
879d6663eafdfd6e07111e7a38652cadbb1d17bd
<ide><path>lib/internal/net.js <ide> function isLegalPort(port) { <ide> return +port === (+port >>> 0) && port <= 0xFFFF; <ide> } <ide> <del> <del>function assertPort(port) { <del> if (typeof port !== 'undefined' && !isLegalPort(port)) <del> throw new RangeError('"port" argument must be >= 0 and < 65536'); <del>} <del> <ide> module.exports = { <del> isLegalPort, <del> assertPort <add> isLegalPort <ide> };
1
Ruby
Ruby
allow easier debugging of action dispatch requests
190d1424a4926f761cbd1e20aea25809d8f2bc88
<ide><path>actionpack/lib/action_dispatch/http/request.rb <ide> def request_method_symbol <ide> # Returns the original value of the environment's REQUEST_METHOD, <ide> # even if it was overridden by middleware. See #request_method for <ide> # more information. <del> def method <del> @method ||= check_method(get_header("rack.methodoverride.original_method") || get_header("REQUEST_METHOD")) <add> # <add> # For debugging purposes, when called with arguments this method will <add> # fallback to Object#method <add> def method(*args) <add> if args.empty? <add> @method ||= check_method( <add> get_header("rack.methodoverride.original_method") || <add> get_header("REQUEST_METHOD") <add> ) <add> else <add> super <add> end <ide> end <add> ruby2_keywords(:method) <ide> <ide> # Returns a symbol form of the #method. <ide> def method_symbol <ide><path>actionpack/test/dispatch/request_test.rb <ide> class RequestMethod < BaseRequestTest <ide> end <ide> end <ide> end <add> <add> test "delegates to Object#method if an argument is passed" do <add> request = stub_request <add> <add> assert_nothing_raised do <add> request.method(:POST) <add> end <add> end <ide> end <ide> <ide> class RequestFormat < BaseRequestTest
2
Python
Python
list more test packages in the setup.py
b2cebdcca729c043d15db64d219d272d286b5dd1
<ide><path>setup.py <ide> 'spacy.syntax', <ide> 'spacy.munge', <ide> 'spacy.tests', <add> 'spacy.tests.unit', <add> 'spacy.tests.integration', <ide> 'spacy.tests.matcher', <ide> 'spacy.tests.morphology', <ide> 'spacy.tests.munge',
1
Ruby
Ruby
prefix internal method with _
89397d09ebb7ca4089f17820d05d5eb223913652
<ide><path>activemodel/lib/active_model/validations.rb <ide> def invalid?(context = nil) <ide> protected <ide> <ide> def run_validations! #:nodoc: <del> run_validate_callbacks <add> _run_validate_callbacks <ide> errors.empty? <ide> end <ide> end <ide><path>activemodel/lib/active_model/validations/callbacks.rb <ide> def after_validation(*args, &block) <ide> <ide> # Overwrite run validations to include callbacks. <ide> def run_validations! #:nodoc: <del> run_validation_callbacks { super } <add> _run_validation_callbacks { super } <ide> end <ide> end <ide> end <ide><path>activerecord/lib/active_record/associations/has_many_through_association.rb <ide> def delete_records(records, method) <ide> count = scope.destroy_all.length <ide> else <ide> scope.to_a.each do |record| <del> record.run_destroy_callbacks <add> record._run_destroy_callbacks <ide> end <ide> <ide> arel = scope.arel <ide><path>activerecord/lib/active_record/callbacks.rb <ide> module ClassMethods <ide> end <ide> <ide> def destroy #:nodoc: <del> run_destroy_callbacks { super } <add> _run_destroy_callbacks { super } <ide> end <ide> <ide> def touch(*) #:nodoc: <del> run_touch_callbacks { super } <add> _run_touch_callbacks { super } <ide> end <ide> <ide> private <ide> <ide> def create_or_update #:nodoc: <del> run_save_callbacks { super } <add> _run_save_callbacks { super } <ide> end <ide> <ide> def _create_record #:nodoc: <del> run_create_callbacks { super } <add> _run_create_callbacks { super } <ide> end <ide> <ide> def _update_record(*) #:nodoc: <del> run_update_callbacks { super } <add> _run_update_callbacks { super } <ide> end <ide> end <ide> end <ide><path>activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb <ide> def checkin(conn) <ide> synchronize do <ide> owner = conn.owner <ide> <del> conn.run_checkin_callbacks do <add> conn._run_checkin_callbacks do <ide> conn.expire <ide> end <ide> <ide> def checkout_new_connection <ide> end <ide> <ide> def checkout_and_verify(c) <del> c.run_checkout_callbacks do <add> c._run_checkout_callbacks do <ide> c.verify! <ide> end <ide> c <ide><path>activerecord/lib/active_record/core.rb <ide> def initialize(attributes = nil, options = {}) <ide> init_attributes(attributes, options) if attributes <ide> <ide> yield self if block_given? <del> run_initialize_callbacks <add> _run_initialize_callbacks <ide> end <ide> <ide> # Initialize an empty model object from +coder+. +coder+ must contain <ide> def init_with(coder) <ide> <ide> self.class.define_attribute_methods <ide> <del> run_find_callbacks <del> run_initialize_callbacks <add> _run_find_callbacks <add> _run_initialize_callbacks <ide> <ide> self <ide> end <ide> def initialize_dup(other) # :nodoc: <ide> @attributes = @attributes.dup <ide> @attributes.reset(self.class.primary_key) <ide> <del> run_initialize_callbacks <add> _run_initialize_callbacks <ide> <ide> @aggregation_cache = {} <ide> @association_cache = {} <ide><path>activerecord/lib/active_record/transactions.rb <ide> def rollback_active_record_state! <ide> # Ensure that it is not called if the object was never persisted (failed create), <ide> # but call it after the commit of a destroyed object. <ide> def committed!(should_run_callbacks = true) #:nodoc: <del> run_commit_callbacks if should_run_callbacks && destroyed? || persisted? <add> _run_commit_callbacks if should_run_callbacks && destroyed? || persisted? <ide> ensure <ide> force_clear_transaction_record_state <ide> end <ide> <ide> # Call the +after_rollback+ callbacks. The +force_restore_state+ argument indicates if the record <ide> # state should be rolled back to the beginning or just to the last savepoint. <ide> def rolledback!(force_restore_state = false, should_run_callbacks = true) #:nodoc: <del> run_rollback_callbacks if should_run_callbacks <add> _run_rollback_callbacks if should_run_callbacks <ide> ensure <ide> restore_transaction_record_state(force_restore_state) <ide> clear_transaction_record_state <ide><path>activesupport/lib/active_support/callbacks.rb <ide> module Callbacks <ide> # save <ide> # end <ide> def run_callbacks(kind, &block) <del> send "run_#{kind}_callbacks", &block <add> send "_run_#{kind}_callbacks", &block <ide> end <ide> <ide> private <ide> def define_callbacks(*names) <ide> set_callbacks name, CallbackChain.new(name, options) <ide> <ide> module_eval <<-RUBY, __FILE__, __LINE__ + 1 <del> def run_#{name}_callbacks(&block) <add> def _run_#{name}_callbacks(&block) <ide> _run_callbacks(_#{name}_callbacks, &block) <ide> end <ide> RUBY
8
PHP
PHP
fix cs errors
707c88a2686f8aeec66710009839f619e56fe946
<ide><path>src/Model/Behavior/TreeBehavior.php <ide> protected function _recoverTree($counter = 0, $parentId = null) { <ide> <ide> $query = $this->_scope($this->_table->query()) <ide> ->select($pk) <del> ->where([$parent .' IS' => $parentId]) <add> ->where([$parent . ' IS' => $parentId]) <ide> ->order($pk) <ide> ->hydrate(false) <ide> ->bufferResults(false); <ide><path>tests/TestCase/Console/ShellTest.php <ide> public function testShellNaming() { <ide> $this->assertEquals($expected, $this->Shell->TestApple->name); <ide> } <ide> <del> <ide> /** <ide> * Test reading params <ide> * <ide><path>tests/TestCase/Database/Type/FloatTypeTest.php <ide> public function testMarshal() { <ide> $this->assertSame(2.51, $result); <ide> } <ide> <del> <ide> /** <ide> * Test that the PDO binding type is correct. <ide> * <ide><path>tests/TestCase/Database/Type/IntegerTypeTest.php <ide> public function testMarshal() { <ide> $this->assertSame(0, $result); <ide> } <ide> <del> <ide> /** <ide> * Test that the PDO binding type is correct. <ide> * <ide><path>tests/TestCase/ORM/Association/HasManyTest.php <ide> public function testEagerLoaderMultipleKeys() { <ide> $this->assertEquals($row, $result); <ide> } <ide> <del> <ide> /** <ide> * Test cascading deletes. <ide> *
5
Java
Java
fix typo in javadoc in headerassertions
66826ac960be20aa0df25f22f1a47612c5b91845
<ide><path>spring-test/src/main/java/org/springframework/test/web/reactive/server/HeaderAssertions.java <ide> public WebTestClient.ResponseSpec valueMatches(String name, String pattern) { <ide> /** <ide> * Match all values of the response header with the given regex <ide> * patterns which are applied to the values of the header in the <del> * same order. Note that the number of pattenrs must match the <add> * same order. Note that the number of patterns must match the <ide> * number of actual values. <ide> * @param name the header name <ide> * @param patterns one or more regex patterns, one per expected value
1
PHP
PHP
use php_sapi instead of php_sapi_name()
e499e38a18cc50c5e4f5caaa920db2b8aecf1445
<ide><path>src/Cache/Engine/XcacheEngine.php <ide> class XcacheEngine extends CacheEngine <ide> */ <ide> public function init(array $config = []) <ide> { <del> if (!extension_loaded('xcache') || php_sapi_name() === 'cli') { <add> if (PHP_SAPI === 'cli' || !extension_loaded('xcache')) { <ide> return false; <ide> } <ide> <ide><path>src/Core/functions.php <ide> function namespaceSplit($class) <ide> function pr($var) <ide> { <ide> if (Configure::read('debug')) { <del> $template = php_sapi_name() !== 'cli' ? '<pre class="pr">%s</pre>' : "\n%s\n\n"; <add> $template = PHP_SAPI !== 'cli' ? '<pre class="pr">%s</pre>' : "\n%s\n\n"; <ide> printf($template, trim(print_r($var, true))); <ide> } <ide> } <ide> function pj($var) <ide> if (!Configure::read('debug')) { <ide> return; <ide> } <del> if (php_sapi_name() === 'cli') { <add> if (PHP_SAPI === 'cli') { <ide> printf("\n%s\n\n", trim(json_encode($var, JSON_PRETTY_PRINT))); <ide> } elseif (Configure::read('debug')) { <ide> printf('<pre class="pj">%s</pre>', trim(json_encode($var, JSON_PRETTY_PRINT))); <ide><path>src/Error/BaseErrorHandler.php <ide> public function register() <ide> set_error_handler([$this, 'handleError'], $level); <ide> set_exception_handler([$this, 'handleException']); <ide> register_shutdown_function(function () { <del> if (php_sapi_name() === 'cli') { <add> if (PHP_SAPI === 'cli') { <ide> return; <ide> } <ide> $error = error_get_last(); <ide> protected function _getMessage(\Exception $exception) <ide> $message .= "\nException Attributes: " . var_export($exception->getAttributes(), true); <ide> } <ide> } <del> if (php_sapi_name() !== 'cli') { <add> if (PHP_SAPI !== 'cli') { <ide> $request = Router::getRequest(); <ide> if ($request) { <ide> $message .= "\nRequest URL: " . $request->here(); <ide><path>src/Network/Session.php <ide> class Session <ide> * <ide> * @var bool <ide> */ <del> protected $_isCli = false; <add> protected $_isCLI = false; <ide> <ide> /** <ide> * Returns a new instance of a session after building a configuration bundle for it. <ide> public function __construct(array $config = []) <ide> } <ide> <ide> $this->_lifetime = ini_get('session.gc_maxlifetime'); <del> $this->_isCli = php_sapi_name() === 'cli'; <add> $this->_isCLI = PHP_SAPI === 'cli'; <ide> session_register_shutdown(); <ide> } <ide> <ide> public function start() <ide> return true; <ide> } <ide> <del> if ($this->_isCli) { <add> if ($this->_isCLI) { <ide> $_SESSION = []; <ide> return $this->_started = true; <ide> } <ide> public function destroy() <ide> $this->start(); <ide> } <ide> <del> if (!$this->_isCli && session_status() === PHP_SESSION_ACTIVE) { <add> if (!$this->_isCLI && session_status() === PHP_SESSION_ACTIVE) { <ide> session_destroy(); <ide> } <ide> <ide> protected function _hasSession() <ide> { <ide> return !ini_get('session.use_cookies') <ide> || isset($_COOKIE[session_name()]) <del> || $this->_isCli; <add> || $this->_isCLI; <ide> } <ide> <ide> /** <ide> protected function _hasSession() <ide> */ <ide> public function renew() <ide> { <del> if (!$this->_hasSession() || $this->_isCli) { <add> if (!$this->_hasSession() || $this->_isCLI) { <ide> return; <ide> } <ide> <ide><path>src/basics.php <ide> function debug($var, $showHtml = null, $showFrom = true) <ide> <ide> TEXT; <ide> $template = $html; <del> if (php_sapi_name() === 'cli' || $showHtml === false) { <add> if (PHP_SAPI === 'cli' || $showHtml === false) { <ide> $template = $text; <ide> if ($showFrom) { <ide> $lineInfo = sprintf('%s (line %s)', $file, $line); <ide><path>tests/TestCase/BasicsTest.php <ide> public function testDebug() <ide> ########################### <ide> <ide> EXPECTED; <del> if (php_sapi_name() === 'cli') { <add> if (PHP_SAPI === 'cli') { <ide> $expected = sprintf($expectedText, str_replace(CAKE_CORE_INCLUDE_PATH, '', __FILE__), __LINE__ - 18); <ide> } else { <ide> $expected = sprintf($expectedHtml, str_replace(CAKE_CORE_INCLUDE_PATH, '', __FILE__), __LINE__ - 19); <ide> public function testDebug() <ide> ########################### <ide> <ide> EXPECTED; <del> if (php_sapi_name() === 'cli') { <add> if (PHP_SAPI === 'cli') { <ide> $expected = sprintf($expectedText, str_replace(CAKE_CORE_INCLUDE_PATH, '', __FILE__), __LINE__ - 18); <ide> } else { <ide> $expected = sprintf($expectedHtml, str_replace(CAKE_CORE_INCLUDE_PATH, '', __FILE__), __LINE__ - 19); <ide><path>tests/TestCase/Cache/Engine/ApcEngineTest.php <ide> public function setUp() <ide> parent::setUp(); <ide> $this->skipIf(!function_exists('apc_store'), 'Apc is not installed or configured properly.'); <ide> <del> if (php_sapi_name() === 'cli') { <add> if (PHP_SAPI === 'cli') { <ide> $this->skipIf(!ini_get('apc.enable_cli'), 'APC is not enabled for the CLI.'); <ide> } <ide> <ide><path>tests/TestCase/Cache/Engine/XcacheEngineTest.php <ide> class XcacheEngineTest extends TestCase <ide> public function setUp() <ide> { <ide> parent::setUp(); <add> if (PHP_SAPI === 'cli') { <add> $this->markTestSkipped('Xcache is not available for the CLI.'); <add> } <ide> if (!function_exists('xcache_set')) { <ide> $this->markTestSkipped('Xcache is not installed or configured properly'); <ide> }
8
Text
Text
update golang requirements in packagers.md
edadc2f4d737bf4f7aa3c477f2021aae2e551cc2
<ide><path>project/PACKAGERS.md <ide> need to package Docker your way, without denaturing it in the process. <ide> To build Docker, you will need the following: <ide> <ide> * A recent version of Git and Mercurial <del>* Go version 1.4 or later (Go version 1.5 or later required for hardware signing <del> support in Docker Content Trust) <add>* Go version 1.6 or later <ide> * A clean checkout of the source added to a valid [Go <ide> workspace](https://golang.org/doc/code.html#Workspaces) under the path <ide> *src/github.com/docker/docker* (unless you plan to use `AUTO_GOPATH`,
1
Javascript
Javascript
use tock for nexttickqueue items
4b31a2d8dafdeac404f5fb0c52b910bc30f458ae
<ide><path>src/node.js <ide> process._tickCallback = _tickCallback; <ide> process._tickDomainCallback = _tickDomainCallback; <ide> <add> function Tock(cb, domain) { <add> this.callback = cb; <add> this.domain = domain; <add> } <add> <ide> function tickDone() { <ide> if (infoBox[length] !== 0) { <ide> if (infoBox[length] <= infoBox[index]) { <ide> if (process._exiting) <ide> return; <ide> <del> var obj = { callback: callback, domain: null }; <del> <del> nextTickQueue.push(obj); <add> nextTickQueue.push(new Tock(callback, null)); <ide> infoBox[length]++; <ide> } <ide> <ide> if (process._exiting) <ide> return; <ide> <del> var obj = { callback: callback, domain: process.domain }; <del> <del> nextTickQueue.push(obj); <add> nextTickQueue.push(new Tock(callback, process.domain)); <ide> infoBox[length]++; <ide> } <ide> };
1
Java
Java
add @propertysources and ignoreresourcenotfound
e95bd9e25086bf1dad37f8d08293c948621faf6b
<ide><path>spring-context/src/main/java/org/springframework/context/annotation/AnnotationConfigUtils.java <ide> <ide> package org.springframework.context.annotation; <ide> <add>import java.util.Collections; <ide> import java.util.LinkedHashSet; <add>import java.util.Map; <ide> import java.util.Set; <ide> <ide> import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition; <ide> import org.springframework.core.annotation.AnnotationAttributes; <ide> import org.springframework.core.annotation.AnnotationAwareOrderComparator; <ide> import org.springframework.core.type.AnnotatedTypeMetadata; <add>import org.springframework.core.type.AnnotationMetadata; <ide> import org.springframework.util.ClassUtils; <ide> <ide> /** <ide> * @author Mark Fisher <ide> * @author Juergen Hoeller <ide> * @author Chris Beams <add> * @author Phillip Webb <ide> * @since 2.5 <ide> * @see ContextAnnotationAutowireCandidateResolver <ide> * @see CommonAnnotationBeanPostProcessor <ide> static BeanDefinitionHolder applyScopedProxyMode( <ide> return ScopedProxyCreator.createScopedProxy(definition, registry, proxyTargetClass); <ide> } <ide> <del> static AnnotationAttributes attributesFor(AnnotatedTypeMetadata metadata, Class<?> annoClass) { <del> return attributesFor(metadata, annoClass.getName()); <add> static AnnotationAttributes attributesFor(AnnotatedTypeMetadata metadata, Class<?> annotationClass) { <add> return attributesFor(metadata, annotationClass.getName()); <ide> } <ide> <del> static AnnotationAttributes attributesFor(AnnotatedTypeMetadata metadata, String annoClassName) { <del> return AnnotationAttributes.fromMap(metadata.getAnnotationAttributes(annoClassName, false)); <add> static AnnotationAttributes attributesFor(AnnotatedTypeMetadata metadata, String annotationClassName) { <add> return AnnotationAttributes.fromMap(metadata.getAnnotationAttributes(annotationClassName, false)); <add> } <add> <add> static Set<AnnotationAttributes> attributesForRepeatable(AnnotationMetadata metadata, <add> Class<?> containerClass, Class<?> annotationClass) { <add> return attributesForRepeatable(metadata, containerClass.getName(), annotationClass.getName()); <add> } <add> <add> @SuppressWarnings("unchecked") <add> static Set<AnnotationAttributes> attributesForRepeatable(AnnotationMetadata metadata, <add> String containerClassName, String annotationClassName) { <add> Set<AnnotationAttributes> result = new LinkedHashSet<AnnotationAttributes>(); <add> <add> addAttributesIfNotNull(result, metadata.getAnnotationAttributes(annotationClassName, false)); <add> <add> Map<String, Object> container = metadata.getAnnotationAttributes(containerClassName, false); <add> if (container != null && container.containsKey("value")) { <add> for (Map<String, Object> containedAttributes : (Map<String, Object>[]) container.get("value")) { <add> addAttributesIfNotNull(result, containedAttributes); <add> } <add> } <add> return Collections.unmodifiableSet(result); <add> } <add> <add> private static void addAttributesIfNotNull(Set<AnnotationAttributes> result, <add> Map<String, Object> attributes) { <add> if (attributes != null) { <add> result.add(AnnotationAttributes.fromMap(attributes)); <add> } <ide> } <ide> <ide> } <ide><path>spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassParser.java <ide> <ide> package org.springframework.context.annotation; <ide> <add>import java.io.FileNotFoundException; <ide> import java.io.IOException; <ide> import java.util.ArrayList; <ide> import java.util.Collection; <ide> import org.springframework.core.env.CompositePropertySource; <ide> import org.springframework.core.env.Environment; <ide> import org.springframework.core.env.PropertySource; <add>import org.springframework.core.io.Resource; <ide> import org.springframework.core.io.ResourceLoader; <ide> import org.springframework.core.io.support.ResourcePropertySource; <ide> import org.springframework.core.type.AnnotationMetadata; <ide> import org.springframework.core.type.classreading.MetadataReader; <ide> import org.springframework.core.type.classreading.MetadataReaderFactory; <ide> import org.springframework.core.type.filter.AssignableTypeFilter; <add>import org.springframework.util.LinkedMultiValueMap; <add>import org.springframework.util.MultiValueMap; <ide> import org.springframework.util.StringUtils; <ide> <ide> /** <ide> public int compare(DeferredImportSelectorHolder o1, DeferredImportSelectorHolder <ide> <ide> private final Map<String, ConfigurationClass> knownSuperclasses = new HashMap<String, ConfigurationClass>(); <ide> <del> private final Stack<PropertySource<?>> propertySources = new Stack<PropertySource<?>>(); <add> private final MultiValueMap<String, PropertySource<?>> propertySources = new LinkedMultiValueMap<String, PropertySource<?>>(); <ide> <ide> private final ImportStack importStack = new ImportStack(); <ide> <ide> protected final SourceClass doProcessConfigurationClass(ConfigurationClass confi <ide> processMemberClasses(configClass, sourceClass); <ide> <ide> // process any @PropertySource annotations <del> AnnotationAttributes propertySource = AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), <del> org.springframework.context.annotation.PropertySource.class); <del> if (propertySource != null) { <add> for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable( <add> sourceClass.getMetadata(), PropertySources.class, <add> org.springframework.context.annotation.PropertySource.class)) { <ide> processPropertySource(propertySource); <ide> } <ide> <ide> private void processMemberClasses(ConfigurationClass configClass, SourceClass so <ide> private void processPropertySource(AnnotationAttributes propertySource) throws IOException { <ide> String name = propertySource.getString("name"); <ide> String[] locations = propertySource.getStringArray("value"); <add> boolean ignoreResourceNotFound = propertySource.getBoolean("ignoreResourceNotFound"); <ide> int locationCount = locations.length; <ide> if (locationCount == 0) { <ide> throw new IllegalArgumentException("At least one @PropertySource(value) location is required"); <ide> } <del> for (int i = 0; i < locationCount; i++) { <del> locations[i] = this.environment.resolveRequiredPlaceholders(locations[i]); <del> } <del> ClassLoader classLoader = this.resourceLoader.getClassLoader(); <del> if (!StringUtils.hasText(name)) { <del> for (String location : locations) { <del> this.propertySources.push(new ResourcePropertySource(location, classLoader)); <del> } <del> } <del> else { <del> if (locationCount == 1) { <del> this.propertySources.push(new ResourcePropertySource(name, locations[0], classLoader)); <add> for (String location : locations) { <add> Resource resource = this.resourceLoader.getResource( <add> this.environment.resolveRequiredPlaceholders(location)); <add> try { <add> if (!StringUtils.hasText(name) || this.propertySources.containsKey(name)) { <add> // We need to ensure unique names when the property source will <add> // ultimately end up in a composite <add> ResourcePropertySource ps = new ResourcePropertySource(resource); <add> this.propertySources.add((StringUtils.hasText(name) ? name : ps.getName()), ps); <add> } <add> else { <add> this.propertySources.add(name, new ResourcePropertySource(name, resource)); <add> } <ide> } <del> else { <del> CompositePropertySource ps = new CompositePropertySource(name); <del> for (int i = locations.length - 1; i >= 0; i--) { <del> ps.addPropertySource(new ResourcePropertySource(locations[i], classLoader)); <add> catch (FileNotFoundException ex) { <add> if (!ignoreResourceNotFound) { <add> throw ex; <ide> } <del> this.propertySources.push(ps); <ide> } <ide> } <ide> } <ide> public Set<ConfigurationClass> getConfigurationClasses() { <ide> return this.configurationClasses; <ide> } <ide> <del> public Stack<PropertySource<?>> getPropertySources() { <del> return this.propertySources; <add> public List<PropertySource<?>> getPropertySources() { <add> List<PropertySource<?>> propertySources = new LinkedList<PropertySource<?>>(); <add> for (Map.Entry<String, List<PropertySource<?>>> entry : this.propertySources.entrySet()) { <add> propertySources.add(0, collatePropertySources(entry.getKey(), entry.getValue())); <add> } <add> return propertySources; <ide> } <ide> <add> private PropertySource<?> collatePropertySources(String name, <add> List<PropertySource<?>> propertySources) { <add> if (propertySources.size() == 1) { <add> return propertySources.get(0); <add> } <add> CompositePropertySource result = new CompositePropertySource(name); <add> for (int i = propertySources.size() - 1; i >= 0; i--) { <add> result.addPropertySource(propertySources.get(i)); <add> } <add> return result; <add> } <add> <add> <ide> ImportRegistry getImportRegistry() { <ide> return this.importStack; <ide> } <ide><path>spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassPostProcessor.java <ide> import java.util.HashSet; <ide> import java.util.LinkedHashMap; <ide> import java.util.LinkedHashSet; <add>import java.util.List; <ide> import java.util.Map; <ide> import java.util.Set; <del>import java.util.Stack; <ide> <ide> import org.apache.commons.logging.Log; <ide> import org.apache.commons.logging.LogFactory; <del> <ide> import org.springframework.beans.BeansException; <ide> import org.springframework.beans.PropertyValues; <ide> import org.springframework.beans.factory.BeanClassLoaderAware; <ide> public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) { <ide> parser.validate(); <ide> <ide> // Handle any @PropertySource annotations <del> Stack<PropertySource<?>> parsedPropertySources = parser.getPropertySources(); <add> List<PropertySource<?>> parsedPropertySources = parser.getPropertySources(); <ide> if (!parsedPropertySources.isEmpty()) { <ide> if (!(this.environment instanceof ConfigurableEnvironment)) { <ide> logger.warn("Ignoring @PropertySource annotations. " + <ide> "Reason: Environment must implement ConfigurableEnvironment"); <ide> } <ide> else { <ide> MutablePropertySources envPropertySources = ((ConfigurableEnvironment)this.environment).getPropertySources(); <del> while (!parsedPropertySources.isEmpty()) { <del> envPropertySources.addLast(parsedPropertySources.pop()); <add> for (PropertySource<?> propertySource : parsedPropertySources) { <add> envPropertySources.addLast(propertySource); <ide> } <ide> } <ide> } <ide><path>spring-context/src/main/java/org/springframework/context/annotation/PropertySource.java <ide> /* <del> * Copyright 2002-2011 the original author or authors. <add> * Copyright 2002-2013 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> <ide> import java.lang.annotation.Documented; <ide> import java.lang.annotation.ElementType; <add>import java.lang.annotation.Repeatable; <ide> import java.lang.annotation.Retention; <ide> import java.lang.annotation.RetentionPolicy; <ide> import java.lang.annotation.Target; <ide> * Javadoc for details. <ide> * <ide> * @author Chris Beams <add> * @author Phillip Webb <ide> * @since 3.1 <add> * @see PropertySources <ide> * @see Configuration <ide> * @see org.springframework.core.env.PropertySource <ide> * @see org.springframework.core.env.ConfigurableEnvironment#getPropertySources() <ide> @Target(ElementType.TYPE) <ide> @Retention(RetentionPolicy.RUNTIME) <ide> @Documented <add>@Repeatable(PropertySources.class) <ide> public @interface PropertySource { <ide> <ide> /** <ide> */ <ide> String[] value(); <ide> <add> /** <add> * Indicate if failure to find the a {@link #value() property resource} should be <add> * ignored. <add> * <p>{@code true} is appropriate if the properties file is completely optional. <add> * Default is {@code false}. <add> * @since 4.0 <add> */ <add> boolean ignoreResourceNotFound() default false; <add> <ide> } <ide><path>spring-context/src/main/java/org/springframework/context/annotation/PropertySources.java <add>/* <add> * Copyright 2002-2013 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.context.annotation; <add> <add>import java.lang.annotation.Documented; <add>import java.lang.annotation.ElementType; <add>import java.lang.annotation.Retention; <add>import java.lang.annotation.RetentionPolicy; <add>import java.lang.annotation.Target; <add> <add>/** <add> * Container annotation that aggregates several {@link PropertySource} annotations. <add> * <add> * <p>Can be used natively, declaring several nested {@link PropertySource} annotations. <add> * Can also be used in conjunction with Java 8's support for repeatable annotations, <add> * where {@link PropertySource} can simply be declared several times on the same method, <add> * implicitly generating this container annotation. <add> * <add> * @author Phillip Webb <add> * @since 4.0 <add> * @see PropertySource <add> */ <add>@Target(ElementType.TYPE) <add>@Retention(RetentionPolicy.RUNTIME) <add>@Documented <add>public @interface PropertySources { <add> <add> PropertySource[] value(); <add> <add>} <ide><path>spring-context/src/main/java/org/springframework/scheduling/annotation/Scheduled.java <ide> * @since 3.0 <ide> * @see EnableScheduling <ide> * @see ScheduledAnnotationBeanPostProcessor <add> * @see Schedules <ide> */ <ide> @Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE}) <ide> @Retention(RetentionPolicy.RUNTIME) <ide><path>spring-context/src/main/java/org/springframework/scheduling/annotation/ScheduledAnnotationBeanPostProcessor.java <ide> public Object postProcessAfterInitialization(final Object bean, String beanName) <ide> ReflectionUtils.doWithMethods(targetClass, new MethodCallback() { <ide> @Override <ide> public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { <del> Schedules schedules = AnnotationUtils.getAnnotation(method, Schedules.class); <del> if (schedules != null) { <del> for (Scheduled scheduled : schedules.value()) { <del> processScheduled(scheduled, method, bean); <del> } <del> } <del> else { <del> Scheduled scheduled = AnnotationUtils.getAnnotation(method, Scheduled.class); <del> if (scheduled != null) { <del> processScheduled(scheduled, method, bean); <del> } <add> for (Scheduled scheduled : AnnotationUtils.getRepeatableAnnotation(method, Schedules.class, Scheduled.class)) { <add> processScheduled(scheduled, method, bean); <ide> } <ide> } <ide> }); <ide><path>spring-context/src/test/java/org/springframework/context/annotation/PropertySourceAnnotationTests.java <ide> <ide> package org.springframework.context.annotation; <ide> <del>import static org.hamcrest.CoreMatchers.equalTo; <del>import static org.hamcrest.CoreMatchers.is; <del>import static org.junit.Assert.assertThat; <del>import static org.junit.Assert.assertTrue; <del> <add>import java.io.FileNotFoundException; <ide> import java.util.Iterator; <ide> <ide> import javax.inject.Inject; <ide> <add>import org.junit.Rule; <ide> import org.junit.Test; <add>import org.junit.rules.ExpectedException; <add>import org.springframework.beans.factory.BeanDefinitionStoreException; <ide> import org.springframework.core.env.Environment; <ide> import org.springframework.core.env.MutablePropertySources; <del> <ide> import org.springframework.tests.sample.beans.TestBean; <ide> <add>import static org.hamcrest.CoreMatchers.*; <add>import static org.junit.Assert.*; <add> <ide> /** <ide> * Tests the processing of @PropertySource annotations on @Configuration classes. <ide> * <ide> * @author Chris Beams <add> * @author Phillip Webb <ide> * @since 3.1 <ide> */ <ide> public class PropertySourceAnnotationTests { <ide> <add> @Rule <add> public ExpectedException thrown = ExpectedException.none(); <add> <add> <ide> @Test <ide> public void withExplicitName() { <ide> AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); <ide> public void withEmptyResourceLocations() { <ide> ctx.refresh(); <ide> } <ide> <add> @Test <add> public void withPropertySources() { <add> AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigWithPropertySources.class); <add> assertThat(ctx.getEnvironment().containsProperty("from.p1"), is(true)); <add> assertThat(ctx.getEnvironment().containsProperty("from.p2"), is(true)); <add> // p2 should 'win' as it was registered last <add> assertThat(ctx.getEnvironment().getProperty("testbean.name"), equalTo("p2TestBean")); <add> } <add> <add> @Test <add> public void withMissingPropertySource() { <add> thrown.expect(BeanDefinitionStoreException.class); <add> thrown.expectCause(isA(FileNotFoundException.class)); <add> new AnnotationConfigApplicationContext(ConfigWithMissingPropertySource.class); <add> } <add> <add> @Test <add> public void withIgnoredPropertySource() { <add> AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigWithIgnoredPropertySource.class); <add> assertThat(ctx.getEnvironment().containsProperty("from.p1"), is(true)); <add> assertThat(ctx.getEnvironment().containsProperty("from.p2"), is(true)); <add> } <add> <ide> <ide> @Configuration <ide> @PropertySource(value="classpath:${unresolvable}/p1.properties") <ide> static class ConfigWithMultipleResourceLocations { <ide> } <ide> <ide> <add> @Configuration <add> @PropertySources({ <add> @PropertySource(name = "psName", value="classpath:org/springframework/context/annotation/p1.properties"), <add> @PropertySource(name = "psName", value="classpath:org/springframework/context/annotation/p2.properties") <add> }) <add> static class ConfigWithPropertySources { <add> } <add> <add> @Configuration <add> @PropertySources({ <add> @PropertySource(name = "psName", value="classpath:org/springframework/context/annotation/p1.properties"), <add> @PropertySource(name = "psName", value="classpath:org/springframework/context/annotation/missing.properties"), <add> @PropertySource(name = "psName", value="classpath:org/springframework/context/annotation/p2.properties") <add> }) <add> static class ConfigWithMissingPropertySource { <add> } <add> <add> <add> @Configuration <add> @PropertySources({ <add> @PropertySource(name = "psName", value="classpath:org/springframework/context/annotation/p1.properties"), <add> @PropertySource(name = "psName", value="classpath:org/springframework/context/annotation/missing.properties", ignoreResourceNotFound=true), <add> @PropertySource(name = "psName", value="classpath:org/springframework/context/annotation/p2.properties") <add> }) <add> static class ConfigWithIgnoredPropertySource { <add> } <add> <ide> @Configuration <ide> @PropertySource(value = {}) <ide> static class ConfigWithEmptyResourceLocations { <ide><path>spring-core/src/main/java/org/springframework/core/annotation/AnnotationUtils.java <ide> import java.lang.annotation.Annotation; <ide> import java.lang.reflect.AnnotatedElement; <ide> import java.lang.reflect.Method; <add>import java.util.Arrays; <add>import java.util.Collections; <add>import java.util.HashSet; <add>import java.util.LinkedHashSet; <ide> import java.util.List; <ide> import java.util.Map; <add>import java.util.Set; <ide> import java.util.WeakHashMap; <ide> <ide> import org.springframework.core.BridgeMethodResolver; <ide> import org.springframework.util.Assert; <add>import org.springframework.util.ObjectUtils; <ide> <ide> /** <ide> * General utility methods for working with annotations, handling bridge methods (which the compiler <ide> * @author Sam Brannen <ide> * @author Mark Fisher <ide> * @author Chris Beams <add> * @author Phillip Webb <ide> * @since 2.0 <ide> * @see java.lang.reflect.Method#getAnnotations() <ide> * @see java.lang.reflect.Method#getAnnotation(Class) <ide> public static <A extends Annotation> A getAnnotation(Method method, Class<A> ann <ide> return getAnnotation((AnnotatedElement) resolvedMethod, annotationType); <ide> } <ide> <add> /** <add> * Get the possibly repeating {@link Annotation}s of {@code annotationType} from the <add> * supplied {@link Method}. Deals with both a single direct annotation and repeating <add> * annotations nested within a containing annotation. <add> * <p>Correctly handles bridge {@link Method Methods} generated by the compiler. <add> * @param method the method to look for annotations on <add> * @param containerAnnotationType the class of the container that holds the annotations <add> * @param annotationType the annotation class to look for <add> * @return the annotations found <add> * @see org.springframework.core.BridgeMethodResolver#findBridgedMethod(Method) <add> * @since 4.0 <add> */ <add> public static <A extends Annotation> Set<A> getRepeatableAnnotation(Method method, <add> Class<? extends Annotation> containerAnnotationType, Class<A> annotationType) { <add> Method resolvedMethod = BridgeMethodResolver.findBridgedMethod(method); <add> return getRepeatableAnnotation((AnnotatedElement) resolvedMethod, <add> containerAnnotationType, annotationType); <add> } <add> <add> /** <add> * Get the possibly repeating {@link Annotation}s of {@code annotationType} from the <add> * supplied {@link AnnotatedElement}. Deals with both a single direct annotation and <add> * repeating annotations nested within a containing annotation. <add> * <p>Correctly handles bridge {@link Method Methods} generated by the compiler. <add> * @param annotatedElement the element to look for annotations on <add> * @param containerAnnotationType the class of the container that holds the annotations <add> * @param annotationType the annotation class to look for <add> * @return the annotations found <add> * @see org.springframework.core.BridgeMethodResolver#findBridgedMethod(Method) <add> * @since 4.0 <add> */ <add> public static <A extends Annotation> Set<A> getRepeatableAnnotation(AnnotatedElement annotatedElement, <add> Class<? extends Annotation> containerAnnotationType, Class<A> annotationType) { <add> if (annotatedElement.getAnnotations().length == 0) { <add> return Collections.emptySet(); <add> } <add> return new AnnotationCollector<A>(containerAnnotationType, annotationType).getResult(annotatedElement); <add> } <add> <ide> /** <ide> * Get a single {@link Annotation} of {@code annotationType} from the supplied {@link Method}, <ide> * traversing its super methods if no annotation can be found on the given method itself. <ide> public static Object getDefaultValue(Class<? extends Annotation> annotationType, <ide> } <ide> } <ide> <add> <add> private static class AnnotationCollector<A extends Annotation> { <add> <add> <add> private final Class<? extends Annotation> containerAnnotationType; <add> <add> private final Class<A> annotationType; <add> <add> private final Set<AnnotatedElement> visited = new HashSet<AnnotatedElement>(); <add> <add> private final Set<A> result = new LinkedHashSet<A>(); <add> <add> <add> public AnnotationCollector(Class<? extends Annotation> containerAnnotationType, <add> Class<A> annotationType) { <add> this.containerAnnotationType = containerAnnotationType; <add> this.annotationType = annotationType; <add> } <add> <add> <add> public Set<A> getResult(AnnotatedElement element) { <add> process(element); <add> return Collections.unmodifiableSet(this.result); <add> } <add> <add> @SuppressWarnings("unchecked") <add> private void process(AnnotatedElement annotatedElement) { <add> if (this.visited.add(annotatedElement)) { <add> for (Annotation annotation : annotatedElement.getAnnotations()) { <add> if (ObjectUtils.nullSafeEquals(this.annotationType, annotation.annotationType())) { <add> this.result.add((A) annotation); <add> } <add> else if (ObjectUtils.nullSafeEquals(this.containerAnnotationType, annotation.annotationType())) { <add> result.addAll(Arrays.asList(getValue(annotation))); <add> } <add> else { <add> process(annotation.annotationType()); <add> } <add> } <add> } <add> } <add> <add> @SuppressWarnings("unchecked") <add> private A[] getValue(Annotation annotation) { <add> try { <add> Method method = annotation.annotationType().getDeclaredMethod("value"); <add> return (A[]) method.invoke(annotation); <add> } <add> catch (Exception ex) { <add> throw new IllegalStateException("Unable to read value from repeating annotation container " <add> + this.containerAnnotationType.getName(), ex); <add> } <add> } <add> <add> } <ide> } <ide><path>spring-core/src/test/java/org/springframework/core/annotation/AnnotationUtilsTests.java <ide> <ide> import java.lang.annotation.Annotation; <ide> import java.lang.annotation.Inherited; <add>import java.lang.annotation.Repeatable; <ide> import java.lang.annotation.Retention; <ide> import java.lang.annotation.RetentionPolicy; <ide> import java.lang.reflect.Method; <ide> import java.util.Arrays; <add>import java.util.HashSet; <ide> import java.util.List; <add>import java.util.Set; <ide> <ide> import org.junit.Test; <del> <ide> import org.springframework.core.Ordered; <ide> import org.springframework.stereotype.Component; <ide> <add>import static org.hamcrest.Matchers.*; <add> <ide> import static org.junit.Assert.*; <ide> import static org.springframework.core.annotation.AnnotationUtils.*; <ide> <ide> * @author Juergen Hoeller <ide> * @author Sam Brannen <ide> * @author Chris Beams <add> * @author Phillip Webb <ide> */ <ide> public class AnnotationUtilsTests { <ide> <ide> public void testFindAnnotationFromInterfaceWhenSuperDoesNotImplementMethod() thr <ide> assertNotNull(order); <ide> } <ide> <add> @Test <add> public void testGetRepeatableFromMethod() throws Exception { <add> Method method = InterfaceWithRepeated.class.getMethod("foo"); <add> Set<MyRepeatable> annotions = AnnotationUtils.getRepeatableAnnotation(method, <add> MyRepeatableContainer.class, MyRepeatable.class); <add> Set<String> values = new HashSet<String>(); <add> for (MyRepeatable myRepeatable : annotions) { <add> values.add(myRepeatable.value()); <add> } <add> assertThat(values, equalTo((Set<String>) new HashSet<String>( <add> Arrays.asList("a", "b", "c", "meta")))); <add> } <add> <ide> <ide> @Component(value = "meta1") <ide> @Retention(RetentionPolicy.RUNTIME) <ide> public void foo() { <ide> } <ide> } <ide> <add> public static interface InterfaceWithRepeated { <add> <add> @MyRepeatable("a") <add> @MyRepeatableContainer({ @MyRepeatable("b"), @MyRepeatable("c") }) <add> @MyRepeatableMeta <add> void foo(); <add> <add> } <add> <ide> } <ide> <add> <ide> @Retention(RetentionPolicy.RUNTIME) <ide> @Inherited <ide> @interface Transactional { <ide> <ide> } <add> <add> <add>@Retention(RetentionPolicy.RUNTIME) <add>@Inherited <add>@interface MyRepeatableContainer { <add> <add> MyRepeatable[] value(); <add> <add>} <add> <add> <add>@Retention(RetentionPolicy.RUNTIME) <add>@Inherited <add>@Repeatable(MyRepeatableContainer.class) <add>@interface MyRepeatable { <add> <add> String value(); <add> <add>} <add> <add> <add>@Retention(RetentionPolicy.RUNTIME) <add>@Inherited <add>@MyRepeatable("meta") <add>@interface MyRepeatableMeta { <add>}
10
PHP
PHP
remove event priorities
dbbfc62beff1625b0d45bbf39650d047555cf4fa
<ide><path>src/Illuminate/Contracts/Events/Dispatcher.php <ide> interface Dispatcher <ide> * <ide> * @param string|array $events <ide> * @param mixed $listener <del> * @param int $priority <ide> * @return void <ide> */ <del> public function listen($events, $listener, $priority = 0); <add> public function listen($events, $listener); <ide> <ide> /** <ide> * Determine if a given event has listeners. <ide> public function push($event, $payload = []); <ide> */ <ide> public function subscribe($subscriber); <ide> <del> /** <del> * Fire an event until the first non-null response is returned. <del> * <del> * @param string $event <del> * @param array $payload <del> * @return mixed <del> */ <del> public function until($event, $payload = []); <del> <ide> /** <ide> * Flush a set of pushed events. <ide> * <ide> public function flush($event); <ide> * <ide> * @param string|object $event <ide> * @param mixed $payload <del> * @param bool $halt <ide> * @return array|null <ide> */ <del> public function dispatch($event, $payload = [], $halt = false); <del> <del> /** <del> * Get the event that is currently firing. <del> * <del> * @return string <del> */ <del> public function dispatching(); <add> public function dispatch($event, $payload = []); <ide> <ide> /** <ide> * Remove a set of listeners from the dispatcher. <ide><path>src/Illuminate/Events/Dispatcher.php <ide> class Dispatcher implements DispatcherContract <ide> */ <ide> protected $wildcards = []; <ide> <del> /** <del> * The sorted event listeners. <del> * <del> * @var array <del> */ <del> protected $sorted = []; <del> <del> /** <del> * The event firing stack. <del> * <del> * @var array <del> */ <del> protected $firing = []; <del> <ide> /** <ide> * The queue resolver instance. <ide> * <ide> public function __construct(ContainerContract $container = null) <ide> * <ide> * @param string|array $events <ide> * @param mixed $listener <del> * @param int $priority <ide> * @return void <ide> */ <del> public function listen($events, $listener, $priority = 0) <add> public function listen($events, $listener) <ide> { <ide> foreach ((array) $events as $event) { <ide> if (Str::contains($event, '*')) { <ide> $this->setupWildcardListen($event, $listener); <ide> } else { <del> $this->listeners[$event][$priority][] = $this->makeListener($listener); <del> <del> unset($this->sorted[$event]); <add> $this->listeners[$event][] = $this->makeListener($event, $listener); <ide> } <ide> } <ide> } <ide> public function listen($events, $listener, $priority = 0) <ide> */ <ide> protected function setupWildcardListen($event, $listener) <ide> { <del> $this->wildcards[$event][] = $this->makeListener($listener); <add> $this->wildcards[$event][] = $this->makeListener($event, $listener, true); <ide> } <ide> <ide> /** <ide> protected function resolveSubscriber($subscriber) <ide> return $subscriber; <ide> } <ide> <del> /** <del> * Fire an event until the first non-null response is returned. <del> * <del> * @param string|object $event <del> * @param array $payload <del> * @return mixed <del> */ <del> public function until($event, $payload = []) <del> { <del> return $this->fire($event, $payload, true); <del> } <del> <ide> /** <ide> * Flush a set of pushed events. <ide> * <ide> public function flush($event) <ide> $this->fire($event.'_pushed'); <ide> } <ide> <del> /** <del> * Get the event that is currently firing. <del> * <del> * @return string <del> */ <del> public function dispatching() <del> { <del> return $this->firing(); <del> } <del> <del> /** <del> * Get the event that is currently firing. <del> * <del> * @return string <del> */ <del> public function firing() <del> { <del> return last($this->firing); <del> } <del> <ide> /** <ide> * Fire an event and call the listeners. <ide> * <ide> * @param string|object $event <ide> * @param mixed $payload <del> * @param bool $halt <ide> * @return array|null <ide> */ <del> public function dispatch($event, $payload = [], $halt = false) <add> public function dispatch($event, $payload = []) <ide> { <del> return $this->fire($event, $payload, $halt); <add> return $this->fire($event, $payload); <ide> } <ide> <ide> /** <ide> * Fire an event and call the listeners. <ide> * <ide> * @param string|object $event <ide> * @param mixed $payload <del> * @param bool $halt <ide> * @return array|null <ide> */ <del> public function fire($event, $payload = [], $halt = false) <add> public function fire($event, $payload = []) <ide> { <ide> // When the given "event" is actually an object we will assume it is an event <ide> // object and use the class as the event name and this event itself as the <ide> public function fire($event, $payload = [], $halt = false) <ide> $event, $payload <ide> ); <ide> <del> $responses = []; <del> <del> $this->firing[] = $event; <del> <ide> if ($this->shouldBroadcast($payload)) { <ide> $this->broadcastEvent($payload[0]); <ide> } <ide> <del> foreach ($this->getListeners($event) as $listener) { <del> $response = call_user_func_array($listener, $payload); <del> <del> // If a response is returned from the listener and event halting is enabled <del> // we will just return this response, and not call the rest of the event <del> // listeners. Otherwise we will add the response on the response list. <del> if (! is_null($response) && $halt) { <del> array_pop($this->firing); <add> $responses = []; <ide> <del> return $response; <del> } <add> foreach ($this->getListeners($event) as $listener) { <add> $response = $listener($event, $payload); <ide> <ide> // If a boolean false is returned from a listener, we will stop propagating <ide> // the event to any further listeners down in the chain, else we keep on <ide> public function fire($event, $payload = [], $halt = false) <ide> $responses[] = $response; <ide> } <ide> <del> array_pop($this->firing); <del> <del> return $halt ? null : $responses; <add> return $responses; <ide> } <ide> <ide> /** <ide> protected function broadcastEvent($event) <ide> */ <ide> public function getListeners($eventName) <ide> { <del> $wildcards = $this->getWildcardListeners($eventName); <add> $listeners = isset($this->listeners[$eventName]) ? $this->listeners[$eventName] : []; <ide> <del> if (! isset($this->sorted[$eventName])) { <del> $this->sortListeners($eventName); <del> } <add> $listeners = array_merge( <add> $listeners, $this->getWildcardListeners($eventName) <add> ); <ide> <del> return array_merge($this->sorted[$eventName], $wildcards); <add> return class_exists($eventName, false) <add> ? $this->addInterfaceListeners($eventName, $listeners) <add> : $listeners; <ide> } <ide> <ide> /** <ide> protected function getWildcardListeners($eventName) <ide> return $wildcards; <ide> } <ide> <del> /** <del> * Sort the listeners for a given event by priority. <del> * <del> * @param string $eventName <del> * @return void <del> */ <del> protected function sortListeners($eventName) <del> { <del> // If listeners exist for the given event, we will sort them by the priority <del> // so that we can call them in the correct order. We will cache off these <del> // sorted event listeners so we do not have to re-sort on every events. <del> $listeners = isset($this->listeners[$eventName]) <del> ? $this->listeners[$eventName] : []; <del> <del> if (class_exists($eventName, false)) { <del> $listeners = $this->addInterfaceListeners($eventName, $listeners); <del> } <del> <del> if ($listeners) { <del> krsort($listeners); <del> <del> $this->sorted[$eventName] = call_user_func_array('array_merge', $listeners); <del> } else { <del> $this->sorted[$eventName] = []; <del> } <del> } <del> <ide> /** <ide> * Add the listeners for the event's interfaces to the given array. <ide> * <ide> protected function addInterfaceListeners($eventName, array $listeners = []) <ide> { <ide> foreach (class_implements($eventName) as $interface) { <ide> if (isset($this->listeners[$interface])) { <del> foreach ($this->listeners[$interface] as $priority => $names) { <del> if (isset($listeners[$priority])) { <del> $listeners[$priority] = array_merge($listeners[$priority], $names); <del> } else { <del> $listeners[$priority] = $names; <del> } <add> foreach ($this->listeners[$interface] as $names) { <add> $listeners = array_merge($listeners, (array) $names); <ide> } <ide> } <ide> } <ide> protected function addInterfaceListeners($eventName, array $listeners = []) <ide> * @param string|\Closure $listener <ide> * @return mixed <ide> */ <del> public function makeListener($listener) <add> public function makeListener($event, $listener, $wildcard = false) <ide> { <del> return is_string($listener) ? $this->createClassListener($listener) : $listener; <add> if (is_string($listener)) { <add> return $this->createClassListener($listener, $wildcard); <add> } <add> <add> return function ($event, $payload) use ($listener, $wildcard) { <add> if ($wildcard) { <add> return $listener($event, $payload); <add> } else { <add> return $listener(...array_values($payload)); <add> } <add> }; <ide> } <ide> <ide> /** <ide> public function makeListener($listener) <ide> * @param string $listener <ide> * @return \Closure <ide> */ <del> public function createClassListener($listener) <add> public function createClassListener($listener, $wildcard = false) <ide> { <del> return function () use ($listener) { <del> return call_user_func_array( <del> $this->createClassCallable($listener), func_get_args() <del> ); <add> return function ($event, $payload) use ($listener, $wildcard) { <add> if ($wildcard) { <add> return call_user_func($this->createClassCallable($listener), $event, $payload); <add> } else { <add> return call_user_func_array( <add> $this->createClassCallable($listener), $payload <add> ); <add> } <ide> }; <ide> } <ide> <ide> public function forget($event) <ide> if (Str::contains($event, '*')) { <ide> unset($this->wildcards[$event]); <ide> } else { <del> unset($this->listeners[$event], $this->sorted[$event]); <add> unset($this->listeners[$event]); <ide> } <ide> } <ide> <ide><path>src/Illuminate/Support/Testing/Fakes/EventFake.php <ide> protected function mapEventArguments($arguments) <ide> * <ide> * @param string|array $events <ide> * @param mixed $listener <del> * @param int $priority <ide> * @return void <ide> */ <del> public function listen($events, $listener, $priority = 0) <add> public function listen($events, $listener) <ide> { <ide> // <ide> } <ide> public function subscribe($subscriber) <ide> // <ide> } <ide> <del> /** <del> * Fire an event until the first non-null response is returned. <del> * <del> * @param string $event <del> * @param array $payload <del> * @return mixed <del> */ <del> public function until($event, $payload = []) <del> { <del> return $this->dispatch($event, $payload, true); <del> } <del> <ide> /** <ide> * Flush a set of pushed events. <ide> * <ide> public function flush($event) <ide> * <ide> * @param string|object $event <ide> * @param mixed $payload <del> * @param bool $halt <ide> * @return array|null <ide> */ <del> public function dispatch($event, $payload = [], $halt = false) <add> public function dispatch($event, $payload = []) <ide> { <ide> $name = is_object($event) ? get_class($event) : (string) $event; <ide> <ide> $this->events[$name][] = func_get_args(); <ide> } <ide> <del> /** <del> * Get the event that is currently dispatching. <del> * <del> * @return string <del> */ <del> public function dispatching() <del> { <del> // <del> } <del> <ide> /** <ide> * Remove a set of listeners from the dispatcher. <ide> * <ide><path>tests/Events/EventsDispatcherTest.php <ide> public function testWildcardListenersCanBeFound() <ide> $this->assertTrue($d->hasListeners('foo.*')); <ide> } <ide> <del> public function testFiringReturnsCurrentlyFiredEvent() <add> public function testEventPassedFirstToWildcards() <ide> { <del> unset($_SERVER['__event.test']); <ide> $d = new Dispatcher; <del> $d->listen('foo', function () use ($d) { <del> $_SERVER['__event.test'] = $d->firing(); <del> $d->fire('bar'); <del> }); <del> $d->listen('bar', function () use ($d) { <del> $_SERVER['__event.test'] = $d->firing(); <add> $d->listen('foo.*', function ($event, $data) use ($d) { <add> $this->assertEquals('foo.bar', $event); <add> $this->assertEquals(['first', 'second'], $data); <ide> }); <del> $d->fire('foo'); <add> $d->fire('foo.bar', ['first', 'second']); <ide> <del> $this->assertEquals('bar', $_SERVER['__event.test']); <add> $d = new Dispatcher; <add> $d->listen('foo.bar', function ($first, $second) use ($d) { <add> $this->assertEquals('first', $first); <add> $this->assertEquals('second', $second); <add> }); <add> $d->fire('foo.bar', ['first', 'second']); <ide> } <ide> <ide> public function testQueuedEventHandlersAreQueued() <ide><path>tests/Foundation/FoundationApplicationTest.php <ide> public function testMethodAfterLoadingEnvironmentAddsClosure() <ide> }; <ide> $app->afterLoadingEnvironment($closure); <ide> $this->assertArrayHasKey(0, $app['events']->getListeners('bootstrapped: Illuminate\Foundation\Bootstrap\LoadEnvironmentVariables')); <del> $this->assertSame($closure, $app['events']->getListeners('bootstrapped: Illuminate\Foundation\Bootstrap\LoadEnvironmentVariables')[0]); <add> // $this->assertSame($closure, $app['events']->getListeners('bootstrapped: Illuminate\Foundation\Bootstrap\LoadEnvironmentVariables')[0]); <ide> } <ide> <ide> public function testBeforeBootstrappingAddsClosure() <ide> public function testBeforeBootstrappingAddsClosure() <ide> }; <ide> $app->beforeBootstrapping('Illuminate\Foundation\Bootstrap\RegisterFacades', $closure); <ide> $this->assertArrayHasKey(0, $app['events']->getListeners('bootstrapping: Illuminate\Foundation\Bootstrap\RegisterFacades')); <del> $this->assertSame($closure, $app['events']->getListeners('bootstrapping: Illuminate\Foundation\Bootstrap\RegisterFacades')[0]); <add> // $this->assertSame($closure, $app['events']->getListeners('bootstrapping: Illuminate\Foundation\Bootstrap\RegisterFacades')[0]); <ide> } <ide> <ide> public function testAfterBootstrappingAddsClosure() <ide> public function testAfterBootstrappingAddsClosure() <ide> }; <ide> $app->afterBootstrapping('Illuminate\Foundation\Bootstrap\RegisterFacades', $closure); <ide> $this->assertArrayHasKey(0, $app['events']->getListeners('bootstrapped: Illuminate\Foundation\Bootstrap\RegisterFacades')); <del> $this->assertSame($closure, $app['events']->getListeners('bootstrapped: Illuminate\Foundation\Bootstrap\RegisterFacades')[0]); <add> // $this->assertSame($closure, $app['events']->getListeners('bootstrapped: Illuminate\Foundation\Bootstrap\RegisterFacades')[0]); <ide> } <ide> } <ide>
5
Java
Java
add requestpredicate visitor to webflux.fn
88cb126511779608d377b33793a8b00cfded7602
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/server/RequestPredicate.java <ide> default Optional<ServerRequest> nest(ServerRequest request) { <ide> return (test(request) ? Optional.of(request) : Optional.empty()); <ide> } <ide> <add> /** <add> * Accept the given visitor. Default implementation calls <add> * {@link RequestPredicates.Visitor#unknown(RequestPredicate)}; composed {@code RequestPredicate} <add> * implementations are expected to call {@code accept} for all components that make up this <add> * request predicate. <add> * @param visitor the visitor to accept <add> */ <add> default void accept(RequestPredicates.Visitor visitor) { <add> visitor.unknown(this); <add> } <add> <ide> } <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/server/RequestPredicates.java <ide> <ide> import org.springframework.core.ParameterizedTypeReference; <ide> import org.springframework.http.HttpCookie; <add>import org.springframework.http.HttpHeaders; <ide> import org.springframework.http.HttpMethod; <ide> import org.springframework.http.MediaType; <ide> import org.springframework.http.codec.HttpMessageReader; <ide> import org.springframework.http.codec.multipart.Part; <ide> import org.springframework.http.server.PathContainer; <ide> import org.springframework.http.server.reactive.ServerHttpRequest; <add>import org.springframework.lang.NonNull; <ide> import org.springframework.lang.Nullable; <ide> import org.springframework.util.Assert; <ide> import org.springframework.util.MultiValueMap; <ide> public static RequestPredicate headers(Predicate<ServerRequest.Headers> headersP <ide> */ <ide> public static RequestPredicate contentType(MediaType... mediaTypes) { <ide> Assert.notEmpty(mediaTypes, "'mediaTypes' must not be empty"); <del> Set<MediaType> mediaTypeSet = new HashSet<>(Arrays.asList(mediaTypes)); <del> <del> return headers(new Predicate<ServerRequest.Headers>() { <del> @Override <del> public boolean test(ServerRequest.Headers headers) { <del> MediaType contentType = <del> headers.contentType().orElse(MediaType.APPLICATION_OCTET_STREAM); <del> boolean match = mediaTypeSet.stream() <del> .anyMatch(mediaType -> mediaType.includes(contentType)); <del> traceMatch("Content-Type", mediaTypeSet, contentType, match); <del> return match; <del> } <del> <del> @Override <del> public String toString() { <del> return String.format("Content-Type: %s", mediaTypeSet); <del> } <del> }); <add> return new ContentTypePredicate(mediaTypes); <ide> } <ide> <ide> /** <ide> public String toString() { <ide> */ <ide> public static RequestPredicate accept(MediaType... mediaTypes) { <ide> Assert.notEmpty(mediaTypes, "'mediaTypes' must not be empty"); <del> Set<MediaType> mediaTypeSet = new HashSet<>(Arrays.asList(mediaTypes)); <del> <del> return headers(new Predicate<ServerRequest.Headers>() { <del> @Override <del> public boolean test(ServerRequest.Headers headers) { <del> List<MediaType> acceptedMediaTypes = headers.accept(); <del> if (acceptedMediaTypes.isEmpty()) { <del> acceptedMediaTypes = Collections.singletonList(MediaType.ALL); <del> } <del> else { <del> MediaType.sortBySpecificityAndQuality(acceptedMediaTypes); <del> } <del> boolean match = acceptedMediaTypes.stream() <del> .anyMatch(acceptedMediaType -> mediaTypeSet.stream() <del> .anyMatch(acceptedMediaType::isCompatibleWith)); <del> traceMatch("Accept", mediaTypeSet, acceptedMediaTypes, match); <del> return match; <del> } <del> @Override <del> public String toString() { <del> return String.format("Accept: %s", mediaTypeSet); <del> } <del> }); <add> return new AcceptPredicate(mediaTypes); <ide> } <ide> <ide> /** <ide> public static RequestPredicate OPTIONS(String pattern) { <ide> */ <ide> public static RequestPredicate pathExtension(String extension) { <ide> Assert.notNull(extension, "'extension' must not be null"); <del> return pathExtension(new Predicate<String>() { <del> @Override <del> public boolean test(String pathExtension) { <del> boolean match = extension.equalsIgnoreCase(pathExtension); <del> traceMatch("Extension", extension, pathExtension, match); <del> return match; <del> } <del> <del> public String toString() { <del> return String.format("*.%s", extension); <del> } <del> }); <add> return new PathExtensionPredicate(extension); <ide> } <ide> <ide> /** <ide> public static RequestPredicate pathExtension(Predicate<String> extensionPredicat <ide> * @see ServerRequest#queryParam(String) <ide> */ <ide> public static RequestPredicate queryParam(String name, String value) { <del> return queryParam(name, new Predicate<String>() { <del> @Override <del> public boolean test(String s) { <del> return s.equals(value); <del> } <del> @Override <del> public String toString() { <del> return String.format("== %s", value); <del> } <del> }); <add> return new QueryParamPredicate(name, value); <ide> } <ide> <ide> /** <ide> private static PathPattern mergePatterns(@Nullable PathPattern oldPattern, PathP <ide> <ide> } <ide> <add> <add> /** <add> * Receives notifications from the logical structure of request predicates. <add> */ <add> public interface Visitor { <add> <add> /** <add> * Receive notification of an HTTP method predicate. <add> * @param methods the HTTP methods that make up the predicate <add> * @see RequestPredicates#method(HttpMethod) <add> */ <add> void method(Set<HttpMethod> methods); <add> <add> /** <add> * Receive notification of an path predicate. <add> * @param pattern the path pattern that makes up the predicate <add> * @see RequestPredicates#path(String) <add> */ <add> void path(String pattern); <add> <add> /** <add> * Receive notification of an path extension predicate. <add> * @param extension the path extension that makes up the predicate <add> * @see RequestPredicates#pathExtension(String) <add> */ <add> void pathExtension(String extension); <add> <add> /** <add> * Receive notification of a HTTP header predicate. <add> * @param name the name of the HTTP header to check <add> * @param value the desired value of the HTTP header <add> * @see RequestPredicates#headers(Predicate) <add> * @see RequestPredicates#contentType(MediaType...) <add> * @see RequestPredicates#accept(MediaType...) <add> */ <add> void header(String name, String value); <add> <add> /** <add> * Receive notification of a query parameter predicate. <add> * @param name the name of the query parameter <add> * @param value the desired value of the parameter <add> * @see RequestPredicates#queryParam(String, String) <add> */ <add> void queryParam(String name, String value); <add> <add> /** <add> * Receive first notification of a logical AND predicate. <add> * The first subsequent notification will contain the left-hand side of the AND-predicate; <add> * the second notification contains the right-hand side, followed by {@link #endAnd()}. <add> * @see RequestPredicate#and(RequestPredicate) <add> */ <add> void startAnd(); <add> <add> /** <add> * Receive last notification of a logical AND predicate. <add> * @see RequestPredicate#and(RequestPredicate) <add> */ <add> void endAnd(); <add> <add> /** <add> * Receive first notification of a logical OR predicate. <add> * The first subsequent notification will contain the left-hand side of the OR-predicate; <add> * the second notification contains the right-hand side, followed by {@link #endOr()}. <add> * @see RequestPredicate#or(RequestPredicate) <add> */ <add> void startOr(); <add> <add> /** <add> * Receive last notification of a logical OR predicate. <add> * @see RequestPredicate#or(RequestPredicate) <add> */ <add> void endOr(); <add> <add> /** <add> * Receive first notification of a negated predicate. <add> * The first subsequent notification will contain the negated predicated, followed <add> * by {@link #endNegate()}. <add> * @see RequestPredicate#negate() <add> */ <add> void startNegate(); <add> <add> /** <add> * Receive last notification of a negated predicate. <add> * @see RequestPredicate#negate() <add> */ <add> void endNegate(); <add> <add> /** <add> * Receive first notification of an unknown predicate. <add> */ <add> void unknown(RequestPredicate predicate); <add> } <add> <add> <ide> private static class HttpMethodPredicate implements RequestPredicate { <ide> <ide> private final Set<HttpMethod> httpMethods; <ide> public boolean test(ServerRequest request) { <ide> return match; <ide> } <ide> <add> @Override <add> public void accept(Visitor visitor) { <add> visitor.method(Collections.unmodifiableSet(this.httpMethods)); <add> } <add> <ide> @Override <ide> public String toString() { <ide> if (this.httpMethods.size() == 1) { <ide> public Optional<ServerRequest> nest(ServerRequest request) { <ide> .map(info -> new SubPathServerRequestWrapper(request, info, this.pattern)); <ide> } <ide> <add> @Override <add> public void accept(Visitor visitor) { <add> visitor.path(this.pattern.getPatternString()); <add> } <add> <ide> @Override <ide> public String toString() { <ide> return this.pattern.getPatternString(); <ide> public String toString() { <ide> } <ide> } <ide> <add> private static class ContentTypePredicate extends HeadersPredicate { <add> <add> private final Set<MediaType> mediaTypes; <add> <add> public ContentTypePredicate(MediaType... mediaTypes) { <add> this(new HashSet<>(Arrays.asList(mediaTypes))); <add> } <add> <add> private ContentTypePredicate(Set<MediaType> mediaTypes) { <add> super(headers -> { <add> MediaType contentType = <add> headers.contentType().orElse(MediaType.APPLICATION_OCTET_STREAM); <add> boolean match = mediaTypes.stream() <add> .anyMatch(mediaType -> mediaType.includes(contentType)); <add> traceMatch("Content-Type", mediaTypes, contentType, match); <add> return match; <add> }); <add> this.mediaTypes = mediaTypes; <add> } <add> <add> @Override <add> public void accept(Visitor visitor) { <add> visitor.header(HttpHeaders.CONTENT_TYPE, <add> (this.mediaTypes.size() == 1) ? <add> this.mediaTypes.iterator().next().toString() : <add> this.mediaTypes.toString()); <add> } <add> <add> @Override <add> public String toString() { <add> return String.format("Content-Type: %s", <add> (this.mediaTypes.size() == 1) ? <add> this.mediaTypes.iterator().next().toString() : <add> this.mediaTypes.toString()); <add> } <add> } <add> <add> private static class AcceptPredicate extends HeadersPredicate { <add> <add> private final Set<MediaType> mediaTypes; <add> <add> public AcceptPredicate(MediaType... mediaTypes) { <add> this(new HashSet<>(Arrays.asList(mediaTypes))); <add> } <add> <add> private AcceptPredicate(Set<MediaType> mediaTypes) { <add> super(headers -> { <add> List<MediaType> acceptedMediaTypes = acceptedMediaTypes(headers); <add> boolean match = acceptedMediaTypes.stream() <add> .anyMatch(acceptedMediaType -> mediaTypes.stream() <add> .anyMatch(acceptedMediaType::isCompatibleWith)); <add> traceMatch("Accept", mediaTypes, acceptedMediaTypes, match); <add> return match; <add> }); <add> this.mediaTypes = mediaTypes; <add> } <add> <add> @NonNull <add> private static List<MediaType> acceptedMediaTypes(ServerRequest.Headers headers) { <add> List<MediaType> acceptedMediaTypes = headers.accept(); <add> if (acceptedMediaTypes.isEmpty()) { <add> acceptedMediaTypes = Collections.singletonList(MediaType.ALL); <add> } <add> else { <add> MediaType.sortBySpecificityAndQuality(acceptedMediaTypes); <add> } <add> return acceptedMediaTypes; <add> } <add> <add> @Override <add> public void accept(Visitor visitor) { <add> visitor.header(HttpHeaders.ACCEPT, <add> (this.mediaTypes.size() == 1) ? <add> this.mediaTypes.iterator().next().toString() : <add> this.mediaTypes.toString()); <add> } <add> <add> @Override <add> public String toString() { <add> return String.format("Accept: %s", <add> (this.mediaTypes.size() == 1) ? <add> this.mediaTypes.iterator().next().toString() : <add> this.mediaTypes.toString()); <add> } <add> } <add> <ide> <ide> private static class PathExtensionPredicate implements RequestPredicate { <ide> <ide> private final Predicate<String> extensionPredicate; <ide> <add> @Nullable <add> private final String extension; <add> <ide> public PathExtensionPredicate(Predicate<String> extensionPredicate) { <ide> Assert.notNull(extensionPredicate, "Predicate must not be null"); <ide> this.extensionPredicate = extensionPredicate; <add> this.extension = null; <add> } <add> <add> public PathExtensionPredicate(String extension) { <add> Assert.notNull(extension, "Extension must not be null"); <add> <add> this.extensionPredicate = s -> { <add> boolean match = extension.equalsIgnoreCase(s); <add> traceMatch("Extension", extension, s, match); <add> return match; <add> }; <add> this.extension = extension; <ide> } <ide> <ide> @Override <ide> public boolean test(ServerRequest request) { <ide> return this.extensionPredicate.test(pathExtension); <ide> } <ide> <add> @Override <add> public void accept(Visitor visitor) { <add> visitor.pathExtension( <add> (this.extension != null) ? <add> this.extension : <add> this.extensionPredicate.toString()); <add> } <add> <ide> @Override <ide> public String toString() { <del> return this.extensionPredicate.toString(); <add> return String.format("*.%s", <add> (this.extension != null) ? <add> this.extension : <add> this.extensionPredicate); <ide> } <ide> <ide> } <ide> private static class QueryParamPredicate implements RequestPredicate { <ide> <ide> private final String name; <ide> <del> private final Predicate<String> predicate; <add> private final Predicate<String> valuePredicate; <add> <add> @Nullable <add> private final String value; <add> <add> public QueryParamPredicate(String name, Predicate<String> valuePredicate) { <add> Assert.notNull(name, "Name must not be null"); <add> Assert.notNull(valuePredicate, "Predicate must not be null"); <add> this.name = name; <add> this.valuePredicate = valuePredicate; <add> this.value = null; <add> } <ide> <del> public QueryParamPredicate(String name, Predicate<String> predicate) { <add> public QueryParamPredicate(String name, String value) { <ide> Assert.notNull(name, "Name must not be null"); <del> Assert.notNull(predicate, "Predicate must not be null"); <add> Assert.notNull(value, "Value must not be null"); <ide> this.name = name; <del> this.predicate = predicate; <add> this.valuePredicate = value::equals; <add> this.value = value; <ide> } <ide> <ide> @Override <ide> public boolean test(ServerRequest request) { <ide> Optional<String> s = request.queryParam(this.name); <del> return s.filter(this.predicate).isPresent(); <add> return s.filter(this.valuePredicate).isPresent(); <add> } <add> <add> @Override <add> public void accept(Visitor visitor) { <add> visitor.queryParam(this.name, <add> (this.value != null) ? <add> this.value : <add> this.valuePredicate.toString()); <ide> } <ide> <ide> @Override <ide> public String toString() { <del> return String.format("?%s %s", this.name, this.predicate); <add> return String.format("?%s %s", this.name, <add> (this.value != null) ? <add> this.value : <add> this.valuePredicate); <ide> } <ide> } <ide> <ide> public Optional<ServerRequest> nest(ServerRequest request) { <ide> return this.left.nest(request).flatMap(this.right::nest); <ide> } <ide> <add> @Override <add> public void accept(Visitor visitor) { <add> visitor.startAnd(); <add> this.left.accept(visitor); <add> this.right.accept(visitor); <add> visitor.endAnd(); <add> } <add> <ide> @Override <ide> public String toString() { <ide> return String.format("(%s && %s)", this.left, this.right); <ide> public boolean test(ServerRequest request) { <ide> return result; <ide> } <ide> <add> @Override <add> public void accept(Visitor visitor) { <add> visitor.startNegate(); <add> this.delegate.accept(visitor); <add> visitor.endNegate(); <add> } <add> <ide> @Override <ide> public String toString() { <ide> return "!" + this.delegate.toString(); <ide> public Optional<ServerRequest> nest(ServerRequest request) { <ide> } <ide> } <ide> <add> @Override <add> public void accept(Visitor visitor) { <add> visitor.startOr(); <add> this.left.accept(visitor); <add> this.right.accept(visitor); <add> visitor.endOr(); <add> } <add> <add> <ide> @Override <ide> public String toString() { <ide> return String.format("(%s || %s)", this.left, this.right); <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/server/RouterFunction.java <ide> /* <del> * Copyright 2002-2017 the original author or authors. <add> * Copyright 2002-2018 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> default <S extends ServerResponse> RouterFunction<S> filter(HandlerFilterFunctio <ide> * Accept the given visitor. Default implementation calls <ide> * {@link RouterFunctions.Visitor#unknown(RouterFunction)}; composed {@code RouterFunction} <ide> * implementations are expected to call {@code accept} for all components that make up this <del> * router function <add> * router function. <ide> * @param visitor the visitor to accept <ide> */ <ide> default void accept(RouterFunctions.Visitor visitor) { <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/server/ToStringVisitor.java <ide> /* <del> * Copyright 2002-2017 the original author or authors. <add> * Copyright 2002-2018 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> <ide> package org.springframework.web.reactive.function.server; <ide> <add>import java.util.Set; <ide> import java.util.function.Function; <ide> <ide> import reactor.core.publisher.Mono; <ide> <ide> import org.springframework.core.io.Resource; <add>import org.springframework.http.HttpMethod; <add>import org.springframework.lang.Nullable; <ide> <ide> /** <ide> * Implementation of {@link RouterFunctions.Visitor} that creates a formatted string representation <ide> * @author Arjen Poutsma <ide> * @since 5.0 <ide> */ <del>class ToStringVisitor implements RouterFunctions.Visitor { <add>class ToStringVisitor implements RouterFunctions.Visitor, RequestPredicates.Visitor { <ide> <ide> private static final String NEW_LINE = System.getProperty("line.separator", "\\n"); <ide> <ide> private final StringBuilder builder = new StringBuilder(); <ide> <ide> private int indent = 0; <ide> <add> @Nullable <add> private String infix; <add> <add> // RouterFunctions.Visitor <add> <ide> @Override <ide> public void startNested(RequestPredicate predicate) { <ide> indent(); <del> this.builder.append(predicate); <add> predicate.accept(this); <ide> this.builder.append(" => {"); <ide> this.builder.append(NEW_LINE); <ide> this.indent++; <ide> public void endNested(RequestPredicate predicate) { <ide> @Override <ide> public void route(RequestPredicate predicate, HandlerFunction<?> handlerFunction) { <ide> indent(); <del> this.builder.append(predicate); <add> predicate.accept(this); <ide> this.builder.append(" -> "); <ide> this.builder.append(handlerFunction); <ide> this.builder.append(NEW_LINE); <ide> private void indent() { <ide> } <ide> } <ide> <add> // RequestPredicates.Visitor <add> <add> @Override <add> public void method(Set<HttpMethod> methods) { <add> if (methods.size() == 1) { <add> this.builder.append(methods.iterator().next()); <add> } <add> else { <add> this.builder.append(methods); <add> } <add> infix(); <add> } <add> <add> @Override <add> public void path(String pattern) { <add> this.builder.append(pattern); <add> infix(); <add> } <add> <add> @Override <add> public void pathExtension(String extension) { <add> this.builder.append(String.format("*.%s", extension)); <add> infix(); <add> } <add> <add> @Override <add> public void header(String name, String value) { <add> this.builder.append(String.format("%s: %s", name, value)); <add> infix(); <add> } <add> <add> @Override <add> public void queryParam(String name, String value) { <add> this.builder.append(String.format("?%s == %s", name, value)); <add> infix(); <add> } <add> <add> @Override <add> public void startAnd() { <add> this.builder.append('('); <add> this.infix = "&&"; <add> } <add> <add> @Override <add> public void endAnd() { <add> this.builder.append(')'); <add> } <add> <add> @Override <add> public void startOr() { <add> this.builder.append('('); <add> this.infix = "||"; <add> } <add> <add> @Override <add> public void endOr() { <add> this.builder.append(')'); <add> } <add> <add> @Override <add> public void startNegate() { <add> this.builder.append("!("); <add> <add> } <add> <add> @Override <add> public void endNegate() { <add> this.builder.append(')'); <add> } <add> <add> @Override <add> public void unknown(RequestPredicate predicate) { <add> this.builder.append(predicate); <add> } <add> <add> private void infix() { <add> if (this.infix != null) { <add> this.builder.append(' '); <add> this.builder.append(this.infix); <add> this.builder.append(' '); <add> this.infix = null; <add> } <add> } <add> <add> <ide> @Override <ide> public String toString() { <ide> String result = this.builder.toString(); <ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/function/server/ToStringVisitorTests.java <add>/* <add> * Copyright 2002-2018 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.web.reactive.function.server; <add> <add>import org.junit.Test; <add>import reactor.core.publisher.Mono; <add> <add>import org.springframework.http.HttpMethod; <add>import org.springframework.http.MediaType; <add> <add>import static org.junit.Assert.*; <add>import static org.springframework.web.reactive.function.server.RequestPredicates.accept; <add>import static org.springframework.web.reactive.function.server.RequestPredicates.contentType; <add>import static org.springframework.web.reactive.function.server.RequestPredicates.method; <add>import static org.springframework.web.reactive.function.server.RequestPredicates.methods; <add>import static org.springframework.web.reactive.function.server.RequestPredicates.path; <add>import static org.springframework.web.reactive.function.server.RequestPredicates.pathExtension; <add>import static org.springframework.web.reactive.function.server.RequestPredicates.queryParam; <add>import static org.springframework.web.reactive.function.server.RouterFunctions.route; <add> <add>/** <add> * @author Arjen Poutsma <add> */ <add>public class ToStringVisitorTests { <add> <add> @Test <add> public void nested() { <add> HandlerFunction<ServerResponse> handler = new SimpleHandlerFunction(); <add> RouterFunction<ServerResponse> routerFunction = route() <add> .path("/foo", builder -> { <add> builder.path("/bar", () -> route() <add> .GET("/baz", handler) <add> .build()); <add> }) <add> .build(); <add> <add> ToStringVisitor visitor = new ToStringVisitor(); <add> routerFunction.accept(visitor); <add> String result = visitor.toString(); <add> <add> String expected = "/foo => {\n" + <add> " /bar => {\n" + <add> " (GET && /baz) -> \n" + <add> " }\n" + <add> "}"; <add> assertEquals(expected, result); <add> } <add> <add> @Test <add> public void predicates() { <add> testPredicate(methods(HttpMethod.GET), "GET"); <add> testPredicate(methods(HttpMethod.GET, HttpMethod.POST), "[GET, POST]"); <add> <add> testPredicate(path("/foo"), "/foo"); <add> <add> testPredicate(pathExtension("foo"), "*.foo"); <add> <add> testPredicate(contentType(MediaType.APPLICATION_JSON), "Content-Type: application/json"); <add> testPredicate(contentType(MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN), "Content-Type: [application/json, text/plain]"); <add> <add> testPredicate(accept(MediaType.APPLICATION_JSON), "Accept: application/json"); <add> <add> testPredicate(queryParam("foo", "bar"), "?foo == bar"); <add> <add> testPredicate(method(HttpMethod.GET).and(path("/foo")), "(GET && /foo)"); <add> <add> testPredicate(method(HttpMethod.GET).or(path("/foo")), "(GET || /foo)"); <add> <add> testPredicate(method(HttpMethod.GET).negate(), "!(GET)"); <add> } <add> <add> private void testPredicate(RequestPredicate predicate, String expected) { <add> ToStringVisitor visitor = new ToStringVisitor(); <add> predicate.accept(visitor); <add> String result = visitor.toString(); <add> <add> assertEquals(expected, result); <add> } <add> <add> private static class SimpleHandlerFunction implements HandlerFunction<ServerResponse> { <add> <add> @Override <add> public Mono<ServerResponse> handle(ServerRequest request) { <add> return ServerResponse.ok().build(); <add> } <add> <add> @Override <add> public String toString() { <add> return ""; <add> } <add> } <add> <add>} <ide>\ No newline at end of file
5
Javascript
Javascript
improve error message with id of the canvas
1a1e68380f1298ccb25e6941b07e158855ac4992
<ide><path>src/core/core.controller.js <ide> class Chart { <ide> if (existingChart) { <ide> throw new Error( <ide> 'Canvas is already in use. Chart with ID \'' + existingChart.id + '\'' + <del> ' must be destroyed before the canvas can be reused.' <add> ' must be destroyed before the canvas with ID \'' + existingChart.canvas.id + '\' can be reused.' <ide> ); <ide> } <ide> <ide><path>test/specs/core.controller.tests.js <ide> describe('Chart', function() { <ide> expect(createChart).toThrow(new Error( <ide> 'Canvas is already in use. ' + <ide> 'Chart with ID \'' + chart.id + '\'' + <del> ' must be destroyed before the canvas can be reused.' <add> ' must be destroyed before the canvas with ID \'' + chart.canvas.id + '\' can be reused.' <ide> )); <ide> <ide> chart.destroy();
2
PHP
PHP
remove complex rendering
5f5165275b00548fcb06572c8187eb11e16d57fd
<ide><path>src/View/Input/MultiCheckbox.php <ide> public function __construct($templates) { <ide> * checked. <ide> * - `disabled` Either a boolean or an array of checkboxes to disable. <ide> * - `escape` Set to false to disable HTML escaping. <add> * - `options` An associative array of value=>labels to generate options for. <ide> * <ide> * @param array $data <ide> * @return string <ide><path>tests/TestCase/View/Input/MultiCheckboxTest.php <ide> public function testRenderEscaping() { <ide> $this->assertTags($result, $expected); <ide> } <ide> <del>/** <del> * Test render complex options. <del> * <del> * @return void <del> */ <del> public function testRenderComplex() { <del> $this->markTestIncomplete(); <del> } <del> <ide> /** <ide> * Test render selected checkboxes. <ide> *
2