content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Javascript
Javascript
add standard console tests
6ff52b69cc6b3fd05aa332623cbc49c5d3eb7ece
<ide><path>test/parallel/test-console-assign-undefined.js <add>'use strict'; <add> <add>// Should be above require, because code in require read console <add>// what we are trying to avoid <add>// set should be earlier than get <add> <add>global.console = undefined; <add> <add>// Initially, the `console` variable is `undefined`, since console will be <add>// lazily loaded in the getter. <add> <add>require('../common'); <add>const assert = require('assert'); <add> <add>// global.console's getter is called <add>// Since the `console` cache variable is `undefined` and therefore false-y, <add>// the getter still calls NativeModule.require() and returns the object <add>// obtained from it, instead of returning `undefined` as expected. <add> <add>assert.strictEqual(global.console, undefined, 'first read'); <add>assert.strictEqual(global.console, undefined, 'second read'); <add> <add>global.console = 1; <add>assert.strictEqual(global.console, 1, 'set true-like primitive'); <add> <add>global.console = 0; <add>assert.strictEqual(global.console, 0, 'set false-like primitive, again'); <ide><path>test/parallel/test-console-is-a-namespace.js <add>'use strict'; <add> <add>require('../common'); <add> <add>const assert = require('assert'); <add>const { test, assert_equals, assert_true, assert_false } = <add> require('../common/wpt'); <add> <add>assert.doesNotThrow(() => { <add> global.console = global.console; <add>}); <add> <add>const self = global; <add> <add>/* eslint-disable */ <add>/* The following tests are copied from */ <add>/* WPT Refs: <add> https://github.com/w3c/web-platform-tests/blob/40e451c/console/console-is-a-namespace.any.js <add> License: http://www.w3.org/Consortium/Legal/2008/04-testsuite-copyright.html <add>*/ <add> <add>// https://heycam.github.io/webidl/#es-namespaces <add>// https://console.spec.whatwg.org/#console-namespace <add> <add>test(() => { <add> assert_true(self.hasOwnProperty("console")); <add>}, "console exists on the global object"); <add> <add>test(() => { <add> const propDesc = Object.getOwnPropertyDescriptor(self, "console"); <add> assert_equals(propDesc.writable, true, "must be writable"); <add> assert_equals(propDesc.enumerable, false, "must not be enumerable"); <add> assert_equals(propDesc.configurable, true, "must be configurable"); <add> assert_equals(propDesc.value, console, "must have the right value"); <add>}, "console has the right property descriptors"); <add> <add>test(() => { <add> assert_false("Console" in self); <add>}, "Console (uppercase, as if it were an interface) must not exist"); <add> <add> <add>// test(() => { <add>// const prototype1 = Object.getPrototypeOf(console); <add>// const prototype2 = Object.getPrototypeOf(prototype1); <add> <add>// assert_equals(Object.getOwnPropertyNames(prototype1).length, 0, "The [[Prototype]] must have no properties"); <add>// assert_equals(prototype2, Object.prototype, "The [[Prototype]]'s [[Prototype]] must be %ObjectPrototype%"); <add>// }, "The prototype chain must be correct"); <add>/* eslint-enable */
2
Ruby
Ruby
remove unused parameters
47b2ddd34da7dfabcda06d7fca39c1ca03ea87cc
<ide><path>activerecord/lib/active_record/associations/association_scope.rb <ide> def scope(association, connection) <ide> chain_head, chain_tail = get_chain(reflection, association, alias_tracker) <ide> <ide> scope.extending! Array(reflection.options[:extend]) <del> add_constraints(scope, owner, klass, reflection, chain_head, chain_tail) <add> add_constraints(scope, owner, reflection, chain_head, chain_tail) <ide> end <ide> <ide> def join_type <ide> def join(table, constraint) <ide> table.create_join(table, table.create_on(constraint), join_type) <ide> end <ide> <del> def last_chain_scope(scope, table, reflection, owner, association_klass) <add> def last_chain_scope(scope, table, reflection, owner) <ide> join_keys = reflection.join_keys <ide> key = join_keys.key <ide> foreign_key = join_keys.foreign_key <ide> def transform_value(value) <ide> value_transformation.call(value) <ide> end <ide> <del> def next_chain_scope(scope, table, reflection, association_klass, foreign_table, next_reflection) <add> def next_chain_scope(scope, table, reflection, foreign_table, next_reflection) <ide> join_keys = reflection.join_keys <ide> key = join_keys.key <ide> foreign_key = join_keys.foreign_key <ide> def get_chain(reflection, association, tracker) <ide> [runtime_reflection, previous_reflection] <ide> end <ide> <del> def add_constraints(scope, owner, association_klass, refl, chain_head, chain_tail) <add> def add_constraints(scope, owner, refl, chain_head, chain_tail) <ide> owner_reflection = chain_tail <ide> table = owner_reflection.alias_name <del> scope = last_chain_scope(scope, table, owner_reflection, owner, association_klass) <add> scope = last_chain_scope(scope, table, owner_reflection, owner) <ide> <ide> reflection = chain_head <ide> while reflection <ide> def add_constraints(scope, owner, association_klass, refl, chain_head, chain_tai <ide> <ide> unless reflection == chain_tail <ide> foreign_table = next_reflection.alias_name <del> scope = next_chain_scope(scope, table, reflection, association_klass, foreign_table, next_reflection) <add> scope = next_chain_scope(scope, table, reflection, foreign_table, next_reflection) <ide> end <ide> <ide> # Exclude the scope of the association itself, because that
1
Ruby
Ruby
use name `tap_audit_exceptions`
e1f463ff26a13eda48f4fcbaf0049a593d2cb8f0
<ide><path>Library/Homebrew/dev-cmd/audit.rb <ide> def audit <ide> audit_formulae.sort.each do |f| <ide> only = only_cops ? ["style"] : args.only <ide> options = { <del> new_formula: new_formula, <del> strict: strict, <del> online: online, <del> git: git, <del> only: only, <del> except: args.except, <del> spdx_license_data: spdx_license_data, <del> spdx_exception_data: spdx_exception_data, <del> audit_exceptions: f.tap.audit_exceptions, <add> new_formula: new_formula, <add> strict: strict, <add> online: online, <add> git: git, <add> only: only, <add> except: args.except, <add> spdx_license_data: spdx_license_data, <add> spdx_exception_data: spdx_exception_data, <add> tap_audit_exceptions: f.tap.audit_exceptions, <ide> } <ide> options[:style_offenses] = style_offenses.for_path(f.path) if style_offenses <ide> options[:display_cop_names] = args.display_cop_names? <ide> def initialize(formula, options = {}) <ide> @specs = %w[stable head].map { |s| formula.send(s) }.compact <ide> @spdx_license_data = options[:spdx_license_data] <ide> @spdx_exception_data = options[:spdx_exception_data] <del> @audit_exceptions = options[:audit_exceptions] <add> @tap_audit_exceptions = options[:tap_audit_exceptions] <ide> end <ide> <ide> def audit_style <ide> def audit_specs <ide> stable_url_minor_version = stable_url_version.minor.to_i <ide> <ide> formula_suffix = stable.version.patch.to_i <del> throttled_rate = audit_exception_list("THROTTLED_FORMULAE")[formula.name] <add> throttled_rate = tap_audit_exception_list(:throttled_formulae)[formula.name] <ide> if throttled_rate && formula_suffix.modulo(throttled_rate).nonzero? <ide> problem "should only be updated every #{throttled_rate} releases on multiples of #{throttled_rate}" <ide> end <ide> def head_only?(formula) <ide> formula.head && formula.stable.nil? <ide> end <ide> <del> def audit_exception_list(list) <del> if @audit_exceptions.key? list <del> @audit_exceptions[list] <add> def tap_audit_exception_list(list) <add> if @tap_audit_exceptions.key? list <add> @tap_audit_exceptions[list] <ide> else <ide> {} <ide> end
1
Text
Text
add 1.8.1 to changelog
1a14916e45c69dac52773db36ec880ba129394a7
<ide><path>CHANGELOG.md <ide> <ide> * [BREAKING] Require Handlebars 2.0. See [blog post](http://emberjs.com/blog/2014/10/16/handlebars-update.html) for details. <ide> <add>### Ember 1.8.1 (November, 4, 2014) <add> <add>* [BUGFIX] Make sure that `{{view}}` can accept a Ember.View instance. <add>* [BUGFIX] Throw an assertion if `classNameBindings` are specified on a tag-less view. <add>* [BUGFIX] Setting an `attributeBinding` for `class` attribute triggers assertion. <add>* [BUGFIX] Fix `htmlSafe` to allow non-strings in unescaped code. <add>* [BUGFIX] Add support for null prototype object to mandatory setter code. Prevents errors when operating on Ember Data `meta` objects. <add>* [BUGFIX] Fix an issue with select/each that causes the last item rendered to be selected. <add> <ide> ### Ember 1.8.0 (October, 28, 2014) <ide> <ide> * [BUGFIX] Ensure published builds do not use `define` or `require` internally.
1
Python
Python
fix dummy creation for multi-frameworks objects
451df725d6a34b36be5d0c33c18cc98fb6cf9c31
<ide><path>utils/check_dummies.py <ide> _re_backend = re.compile(r"is\_([a-z_]*)_available()") <ide> # Matches from xxx import bla <ide> _re_single_line_import = re.compile(r"\s+from\s+\S*\s+import\s+([^\(\s].*)\n") <del>_re_test_backend = re.compile(r"^\s+if\s+not\s+is\_[a-z_]*\_available\(\)") <add>_re_test_backend = re.compile(r"^\s+if\s+not\s+\(?is\_[a-z_]*\_available\(\)") <ide> <ide> <ide> DUMMY_CONSTANT = """
1
Ruby
Ruby
fix flakey test due to non-deterministic order
5e2d3db4b5846db56728ddae63bb1eb9a14ed6d3
<ide><path>activerecord/test/cases/associations/eager_test.rb <ide> def test_preloading_with_has_one_through_an_sti_with_after_initialize <ide> end <ide> <ide> def test_preloading_has_many_through_with_implicit_source <del> authors = Author.includes(:very_special_comments).to_a <add> authors = Author.includes(:very_special_comments).to_a.sort_by(&:id) <ide> assert_no_queries do <ide> special_comment_authors = authors.map { |author| [author.name, author.very_special_comments.size] } <ide> assert_equal [["David", 1], ["Mary", 0], ["Bob", 0]], special_comment_authors
1
Javascript
Javascript
remove console warnings for innerviewnode/ref
3246f68952c8fe065367ef8d2cdf7da5dfff78e4
<ide><path>Libraries/Components/ScrollView/ScrollView.js <ide> class ScrollView extends React.Component<Props, State> { <ide> }; <ide> <ide> getInnerViewNode(): ?number { <del> console.warn( <del> '`getInnerViewNode()` is deprecated. This will be removed in a future release. ' + <del> 'Use <ScrollView innerViewRef={myRef} /> instead.', <del> ); <ide> return ReactNative.findNodeHandle(this._innerViewRef); <ide> } <ide> <ide> getInnerViewRef(): ?React.ElementRef<typeof View> { <del> console.warn( <del> '`getInnerViewRef()` is deprecated. This will be removed in a future release. ' + <del> 'Use <ScrollView innerViewRef={myRef} /> instead.', <del> ); <ide> return this._innerViewRef; <ide> } <ide>
1
Ruby
Ruby
remove pointless private call
ba2717fb19c0cb74b1bbda979a995a33611fad50
<ide><path>Library/Homebrew/version.rb <ide> def to_s <ide> end <ide> alias_method :to_str, :to_s <ide> <del> def self.parse spec <del> version = _parse(spec) <del> Version.new(version, true) unless version.nil? <del> end <del> <ide> protected <ide> <ide> def to_a <ide> @array ||= @version.scan(/\d+|[a-zA-Z]+/).map { |e| VersionElement.new(e) } <ide> end <ide> <del> private <add> def self.parse spec <add> version = _parse(spec) <add> Version.new(version, true) unless version.nil? <add> end <ide> <ide> def self._parse spec <ide> spec = Pathname.new(spec) unless spec.is_a? Pathname
1
PHP
PHP
apply fixes from styleci
528551536aab0ec08e297f443cbfca1f870aeadb
<ide><path>src/Illuminate/Events/Dispatcher.php <ide> protected function sortListeners($eventName) <ide> $listeners = isset($this->listeners[$eventName]) <ide> ? $this->listeners[$eventName] : []; <ide> <del> <ide> if (class_exists($eventName, false)) { <ide> $listeners = $this->addInterfaceListeners($eventName, $listeners); <ide> }
1
PHP
PHP
add basic option parser integration
186d74849dc3ec3848f002c9fae702b3f36b900e
<ide><path>src/Console/Command.php <ide> use Cake\Datasource\ModelAwareTrait; <ide> use Cake\Log\LogTrait; <ide> use Cake\ORM\Locator\LocatorAwareTrait; <add>use RuntimeException; <ide> <ide> /** <ide> * Base class for console commands. <ide> public function __construct() <ide> { <ide> $locator = $this->getTableLocator() ? : 'Cake\ORM\TableRegistry'; <ide> $this->modelFactory('Table', [$locator, 'get']); <add> } <ide> <del> if (!$this->name) { <del> list(, $class) = namespaceSplit(get_class($this)); <del> $this->name = str_replace('Command', '', $class); <del> } <add> /** <add> * Set the name this command uses in the collection. <add> * <add> * Generally invoked by the CommandCollection when the command is added. <add> * <add> * @param string $name The name the command uses in the collection. <add> * @return $this; <add> */ <add> public function setName($name) <add> { <add> $this->name = $name; <add> <add> return $this; <ide> } <ide> <ide> /** <ide> public function getName() <ide> return $this->name; <ide> } <ide> <add> /** <add> * Get the option parser. <add> * <add> * You can override buildOptionParser() to define your options & arguments. <add> * <add> * @return \Cake\Console\ConsoleOptionParser <add> * @throws \RuntimeException When the parser is invalid <add> */ <add> public function getOptionParser() <add> { <add> $parser = new ConsoleOptionParser($this->name); <add> $parser = $this->buildOptionParser($parser); <add> if (!($parser instanceof ConsoleOptionParser)) { <add> throw new RuntimeException(sprintf( <add> "Invalid option parser returned from buildOptionParser(). Expected %s, got %s", <add> ConsoleOptionParser::class, <add> get_class($parser) <add> )); <add> } <add> <add> return $parser; <add> } <add> <add> /** <add> * Hook method for defining this command's option parser. <add> * <add> * @param \Cake\Console\ConsoleOptionParser $parser The parser to be defined <add> * @return \Cake\Console\ConsoleOptionParser The built parser. <add> */ <add> protected function buildOptionParser(ConsoleOptionParser $parser) <add> { <add> return $parser; <add> } <add> <ide> /** <ide> * Hook method invoked by CakePHP when a command is about to be executed. <ide> * <ide><path>tests/TestCase/Console/CommandTest.php <ide> namespace Cake\Test\TestCase\Console; <ide> <ide> use Cake\Console\Command; <add>use Cake\Console\ConsoleOptionParser; <ide> use Cake\ORM\Locator\TableLocator; <ide> use Cake\ORM\Table; <ide> use Cake\TestSuite\TestCase; <del>use TestApp\Command\ExampleCommand; <ide> <ide> /** <ide> * Test case for Console\Command <ide> public function testConstructorLoadModel() <ide> } <ide> <ide> /** <del> * Test name inflection <add> * Test name <ide> * <ide> * @return void <ide> */ <del> public function testNameInflection() <add> public function testSetName() <ide> { <del> $command = new ExampleCommand(); <del> $this->assertSame('Example', $command->getName()); <add> $command = new Command(); <add> $this->assertSame($command, $command->setName('routes show')); <add> $this->assertSame('routes show', $command->getName()); <add> } <add> <add> /** <add> * Test option parser fetching <add> * <add> * @return void <add> */ <add> public function testGetOptionParser() <add> { <add> $command = new Command(); <add> $command->setName('cake routes show'); <add> $parser = $command->getOptionParser(); <add> $this->assertInstanceOf(ConsoleOptionParser::class, $parser); <add> $this->assertSame('cake routes show', $parser->getCommand()); <add> } <add> <add> /** <add> * Test option parser fetching <add> * <add> * @expectedException RuntimeException <add> * @return void <add> */ <add> public function testGetOptionParserInvalid() <add> { <add> $command = $this->getMockBuilder(Command::class) <add> ->setMethods(['buildOptionParser']) <add> ->getMock(); <add> $command->expects($this->once()) <add> ->method('buildOptionParser') <add> ->will($this->returnValue(null)); <add> $command->getOptionParser(); <ide> } <ide> }
2
PHP
PHP
add fluent stop
5c7b9b232259fc5872307979f0c7e61ae9a0b72f
<ide><path>src/Illuminate/Foundation/Exceptions/Handler.php <ide> public function register() <ide> // <ide> } <ide> <del> /** <del> * Register reportable and renderable callbacks. <del> * <del> * @param callable $reportUsing <del> * @param callable $renderUsing <del> * @return $this <del> */ <del> public function on(callable $reportUsing, callable $renderUsing) <del> { <del> $this->reportCallbacks[] = $reportUsing; <del> $this->renderCallbacks[] = $renderUsing; <del> <del> return $this; <del> } <del> <ide> /** <ide> * Register a reportable callback. <ide> * <ide> * @param callable $reportUsing <del> * @return $this <add> * @return \Illuminate\Foundation\Exceptions\ReportableHandler <ide> */ <ide> public function reportable(callable $reportUsing) <ide> { <del> $this->reportCallbacks[] = $reportUsing; <del> <del> return $this; <add> return tap(new ReportableHandler($reportUsing), function ($callback) { <add> $this->reportCallbacks[] = $callback; <add> }); <ide> } <ide> <ide> /** <ide> public function report(Throwable $e) <ide> } <ide> <ide> foreach ($this->reportCallbacks as $reportCallback) { <del> if (is_a($e, $this->firstClosureParameterType($reportCallback))) { <add> if ($reportCallback->handles($e)) { <ide> if ($reportCallback($e) === false) { <ide> return; <ide> } <ide><path>src/Illuminate/Foundation/Exceptions/ReportableHandler.php <add><?php <add> <add>namespace Illuminate\Foundation\Exceptions; <add> <add>use Illuminate\Support\Traits\ReflectsClosures; <add>use Throwable; <add> <add>class ReportableHandler <add>{ <add> use ReflectsClosures; <add> <add> /** <add> * The underlying callback. <add> * <add> * @var callable <add> */ <add> protected $callback; <add> <add> /** <add> * Indicates if reporting should stop after invoking this handler. <add> * <add> * @var bool <add> */ <add> protected $shouldStop = false; <add> <add> /** <add> * Create a new reportable handler instance. <add> * <add> * @param callable $callback <add> * @return void <add> */ <add> public function __construct(callable $callback) <add> { <add> $this->callback = $callback; <add> } <add> <add> /** <add> * Invoke the handler. <add> * <add> * @param \Throwable $e <add> * @return bool <add> */ <add> public function __invoke(Throwable $e) <add> { <add> call_user_func($this->callback, $e); <add> <add> return ! $this->shouldStop; <add> } <add> <add> /** <add> * Determine if the callback handles the given exception. <add> * <add> * @param \Throwable $e <add> * @return bool <add> */ <add> public function handles(Throwable $e) <add> { <add> return is_a($e, $this->firstClosureParameterType($this->callback)); <add> } <add> <add> /** <add> * Indicate that report handling should stop after invoking this callback. <add> * <add> * @return $this <add> */ <add> public function stop() <add> { <add> $this->shouldStop = true; <add> <add> return $this; <add> } <add>}
2
Javascript
Javascript
hoist regexp literals in requestshortener
998c2bb210303d1edff1d43c1566bbe5f6d5637a
<ide><path>lib/RequestShortener.js <ide> "use strict"; <ide> <ide> const path = require("path"); <add>const NORMALIZE_SLASH_DIRECTION_REGEXP = /\\/g; <add>const PATH_CHARS_REGEXP = /[-[\]{}()*+?.,\\^$|#\s]/g; <add>const SEPERATOR_REGEXP = /[\/\\]$/; <add> <add> <add>const normalizeBackSlashDirection = (request) => { <add> return request.replace(NORMALIZE_SLASH_DIRECTION_REGEXP, "/"); <add>}; <add> <add>const shortenPath = (path) => { <add> return path.replace(PATH_CHARS_REGEXP, "\\$&"); <add>}; <add> <ide> <ide> class RequestShortener { <ide> constructor(directory) { <del> directory = directory.replace(/\\/g, "/"); <add> directory = normalizeBackSlashDirection(directory); <ide> if(/[\/\\]$/.test(directory)) directory = directory.substr(0, directory.length - 1); <ide> <ide> if(directory) { <del> const currentDirectoryRegExpString = directory.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); <add> const currentDirectoryRegExpString = shortenPath(directory); <ide> this.currentDirectoryRegExp = new RegExp("^" + currentDirectoryRegExpString + "|(!)" + currentDirectoryRegExpString, "g"); <ide> } <ide> <ide> const dirname = path.dirname(directory); <del> const endsWithSeperator = /[\/\\]$/.test(dirname); <add> const endsWithSeperator = SEPERATOR_REGEXP.test(dirname); <ide> const parentDirectory = endsWithSeperator ? dirname.substr(0, dirname.length - 1) : dirname; <ide> if(parentDirectory && parentDirectory !== directory) { <del> const parentDirectoryRegExpString = parentDirectory.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); <add> const parentDirectoryRegExpString = shortenPath(parentDirectory); <ide> this.parentDirectoryRegExp = new RegExp("^" + parentDirectoryRegExpString + "|(!)" + parentDirectoryRegExpString, "g"); <ide> } <ide> <ide> if(__dirname.length >= 2) { <del> const buildins = path.join(__dirname, "..").replace(/\\/g, "/"); <add> const buildins = normalizeBackSlashDirection(path.join(__dirname, "..")); <ide> const buildinsAsModule = this.currentDirectoryRegExp && this.currentDirectoryRegExp.test(buildins); <ide> this.buildinsAsModule = buildinsAsModule; <del> const buildinsRegExpString = buildins.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); <add> const buildinsRegExpString = shortenPath(buildins); <ide> this.buildinsRegExp = new RegExp("^" + buildinsRegExpString + "|(!)" + buildinsRegExpString, "g"); <ide> } <ide> <ide> class RequestShortener { <ide> <ide> shorten(request) { <ide> if(!request) return request; <del> request = request.replace(/\\/g, "/"); <add> request = normalizeBackSlashDirection(request); <ide> if(this.buildinsAsModule && this.buildinsRegExp) <ide> request = request.replace(this.buildinsRegExp, "!(webpack)"); <ide> if(this.currentDirectoryRegExp)
1
Mixed
Ruby
treat `image/bmp` as a valid content type
a22bb8fa69bd8f25c8bb882ea66309e4e5d059b3
<ide><path>activestorage/app/models/active_storage/blob.rb <ide> def content_type=(value) <ide> super <ide> end <ide> <del> INVALID_VARIABLE_CONTENT_TYPES_DEPRECATED_IN_RAILS_7 = ["image/jpg", "image/pjpeg", "image/bmp"] <add> INVALID_VARIABLE_CONTENT_TYPES_DEPRECATED_IN_RAILS_7 = ["image/jpg", "image/pjpeg"] <ide> INVALID_VARIABLE_CONTENT_TYPES_TO_SERVE_AS_BINARY_DEPRECATED_IN_RAILS_7 = ["text/javascript"] <ide> <ide> private <ide><path>activestorage/test/engine_test.rb <ide> <ide> class ActiveStorage::EngineTest < ActiveSupport::TestCase <ide> test "all default content types are recognized by mini_mime" do <del> exceptions = ActiveStorage::Blob::INVALID_VARIABLE_CONTENT_TYPES_DEPRECATED_IN_RAILS_7 + ActiveStorage::Blob::INVALID_VARIABLE_CONTENT_TYPES_TO_SERVE_AS_BINARY_DEPRECATED_IN_RAILS_7 <add> exceptions = ActiveStorage::Blob::INVALID_VARIABLE_CONTENT_TYPES_DEPRECATED_IN_RAILS_7 + <add> ActiveStorage::Blob::INVALID_VARIABLE_CONTENT_TYPES_TO_SERVE_AS_BINARY_DEPRECATED_IN_RAILS_7 + <add> ["image/bmp"] # see https://github.com/discourse/mini_mime/pull/45, once mini_mime is updated this can be removed <ide> <ide> ActiveStorage.variable_content_types.each do |content_type| <ide> next if exceptions.include?(content_type) # remove this line in Rails 7.1 <ide> <del> assert_equal content_type, MiniMime.lookup_by_content_type(content_type).content_type <add> assert_equal content_type, MiniMime.lookup_by_content_type(content_type)&.content_type <ide> end <ide> <ide> ActiveStorage.web_image_content_types.each do |content_type| <ide> next if exceptions.include?(content_type) # remove this line in Rails 7.1 <ide> <del> assert_equal content_type, MiniMime.lookup_by_content_type(content_type).content_type <add> assert_equal content_type, MiniMime.lookup_by_content_type(content_type)&.content_type <ide> end <ide> <ide> ActiveStorage.content_types_to_serve_as_binary.each do |content_type| <ide> next if exceptions.include?(content_type) # remove this line in Rails 7.1 <ide> <del> assert_equal content_type, MiniMime.lookup_by_content_type(content_type).content_type <add> assert_equal content_type, MiniMime.lookup_by_content_type(content_type)&.content_type <ide> end <ide> <ide> ActiveStorage.content_types_allowed_inline.each do |content_type| <ide> next if exceptions.include?(content_type) # remove this line in Rails 7.1 <ide> <del> assert_equal content_type, MiniMime.lookup_by_content_type(content_type).content_type <add> assert_equal content_type, MiniMime.lookup_by_content_type(content_type)&.content_type <ide> end <ide> end <add> <add> test "image/bmp is a default content type" do <add> assert_includes ActiveStorage.variable_content_types, "image/bmp" <add> end <ide> end <ide><path>activestorage/test/models/blob_test.rb <ide> class ActiveStorage::BlobTest < ActiveSupport::TestCase <ide> assert_not_deprecated do <ide> create_blob(filename: "funky.jpg", content_type: "image/jpeg") <ide> end <add> <add> assert_not_deprecated do <add> create_file_blob(filename: "colors.bmp", content_type: "image/bmp") <add> end <ide> end <ide> <ide> test "warning if blob is created with invalid mime type can be disabled" do <ide> class ActiveStorage::BlobTest < ActiveSupport::TestCase <ide> create_blob(filename: "funky.jpg", content_type: "image/jpeg") <ide> end <ide> <add> assert_not_deprecated do <add> create_file_blob(filename: "colors.bmp", content_type: "image/bmp") <add> end <add> <ide> ensure <ide> ActiveStorage.silence_invalid_content_types_warning = warning_was <ide> end <ide><path>activestorage/test/models/variant_test.rb <ide> class ActiveStorage::VariantTest < ActiveSupport::TestCase <ide> end <ide> <ide> test "resized variation of BMP blob" do <del> blob = create_file_blob(filename: "colors.bmp", content_type: "image/x-bmp") <add> blob = create_file_blob(filename: "colors.bmp", content_type: "image/bmp") <ide> variant = blob.variant(resize_to_limit: [15, 15]).processed <ide> assert_match(/colors\.png/, variant.url) <ide> <ide><path>guides/source/configuring.md <ide> can transform through ImageMagick. <ide> By default, this is defined as: <ide> <ide> ```ruby <del>config.active_storage.variable_content_types = %w(image/png image/gif image/jpeg image/tiff image/vnd.adobe.photoshop image/vnd.microsoft.icon image/webp image/avif image/heic image/heif) <add>config.active_storage.variable_content_types = %w(image/png image/gif image/jpeg image/tiff image/bmp image/vnd.adobe.photoshop image/vnd.microsoft.icon image/webp image/avif image/heic image/heif) <ide> ``` <ide> <ide> #### `config.active_storage.web_image_content_types`
5
Text
Text
use `asterisk` for unordered list
1fd268ae2b03e3328ba7923a47c6a912b2bc0166
<ide><path>docs/api-guide/fields.md <ide> Defaults to `False` <ide> <ide> ### `source` <ide> <del>The name of the attribute that will be used to populate the field. May be a method that only takes a `self` argument, such as `URLField(source='get_absolute_url')`, or may use dotted notation to traverse attributes, such as `EmailField(source='user.email')`. <add>The name of the attribute that will be used to populate the field. May be a method that only takes a `self` argument, such as `URLField(source='get_absolute_url')`, or may use dotted notation to traverse attributes, such as `EmailField(source='user.email')`. <ide> <ide> When serializing fields with dotted notation, it may be necessary to provide a `default` value if any object is not present or is empty during attribute traversal. Beware of possible n+1 problems when using source attribute if you are accessing a relational orm model. For example: <ide> <ide> Corresponds to `django.db.models.fields.CharField` or `django.db.models.fields.T <ide> <ide> **Signature:** `CharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True)` <ide> <del>- `max_length` - Validates that the input contains no more than this number of characters. <del>- `min_length` - Validates that the input contains no fewer than this number of characters. <del>- `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`. <del>- `trim_whitespace` - If set to `True` then leading and trailing whitespace is trimmed. Defaults to `True`. <add>* `max_length` - Validates that the input contains no more than this number of characters. <add>* `min_length` - Validates that the input contains no fewer than this number of characters. <add>* `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`. <add>* `trim_whitespace` - If set to `True` then leading and trailing whitespace is trimmed. Defaults to `True`. <ide> <ide> The `allow_null` option is also available for string fields, although its usage is discouraged in favor of `allow_blank`. It is valid to set both `allow_blank=True` and `allow_null=True`, but doing so means that there will be two differing types of empty value permissible for string representations, which can lead to data inconsistencies and subtle application bugs. <ide> <ide> A field that ensures the input is a valid UUID string. The `to_internal_value` m <ide> <ide> **Signature:** `UUIDField(format='hex_verbose')` <ide> <del>- `format`: Determines the representation format of the uuid value <del> - `'hex_verbose'` - The canonical hex representation, including hyphens: `"5ce0e9a5-5ffa-654b-cee0-1238041fb31a"` <del> - `'hex'` - The compact hex representation of the UUID, not including hyphens: `"5ce0e9a55ffa654bcee01238041fb31a"` <del> - `'int'` - A 128 bit integer representation of the UUID: `"123456789012312313134124512351145145114"` <del> - `'urn'` - RFC 4122 URN representation of the UUID: `"urn:uuid:5ce0e9a5-5ffa-654b-cee0-1238041fb31a"` <add>* `format`: Determines the representation format of the uuid value <add> * `'hex_verbose'` - The canonical hex representation, including hyphens: `"5ce0e9a5-5ffa-654b-cee0-1238041fb31a"` <add> * `'hex'` - The compact hex representation of the UUID, not including hyphens: `"5ce0e9a55ffa654bcee01238041fb31a"` <add> * `'int'` - A 128 bit integer representation of the UUID: `"123456789012312313134124512351145145114"` <add> * `'urn'` - RFC 4122 URN representation of the UUID: `"urn:uuid:5ce0e9a5-5ffa-654b-cee0-1238041fb31a"` <ide> Changing the `format` parameters only affects representation values. All formats are accepted by `to_internal_value` <ide> <ide> ## FilePathField <ide> Corresponds to `django.forms.fields.FilePathField`. <ide> <ide> **Signature:** `FilePathField(path, match=None, recursive=False, allow_files=True, allow_folders=False, required=None, **kwargs)` <ide> <del>- `path` - The absolute filesystem path to a directory from which this FilePathField should get its choice. <del>- `match` - A regular expression, as a string, that FilePathField will use to filter filenames. <del>- `recursive` - Specifies whether all subdirectories of path should be included. Default is `False`. <del>- `allow_files` - Specifies whether files in the specified location should be included. Default is `True`. Either this or `allow_folders` must be `True`. <del>- `allow_folders` - Specifies whether folders in the specified location should be included. Default is `False`. Either this or `allow_files` must be `True`. <add>* `path` - The absolute filesystem path to a directory from which this FilePathField should get its choice. <add>* `match` - A regular expression, as a string, that FilePathField will use to filter filenames. <add>* `recursive` - Specifies whether all subdirectories of path should be included. Default is `False`. <add>* `allow_files` - Specifies whether files in the specified location should be included. Default is `True`. Either this or `allow_folders` must be `True`. <add>* `allow_folders` - Specifies whether folders in the specified location should be included. Default is `False`. Either this or `allow_files` must be `True`. <ide> <ide> ## IPAddressField <ide> <ide> Corresponds to `django.forms.fields.IPAddressField` and `django.forms.fields.Gen <ide> <ide> **Signature**: `IPAddressField(protocol='both', unpack_ipv4=False, **options)` <ide> <del>- `protocol` Limits valid inputs to the specified protocol. Accepted values are 'both' (default), 'IPv4' or 'IPv6'. Matching is case insensitive. <del>- `unpack_ipv4` Unpacks IPv4 mapped addresses like ::ffff:192.0.2.1. If this option is enabled that address would be unpacked to 192.0.2.1. Default is disabled. Can only be used when protocol is set to 'both'. <add>* `protocol` Limits valid inputs to the specified protocol. Accepted values are 'both' (default), 'IPv4' or 'IPv6'. Matching is case insensitive. <add>* `unpack_ipv4` Unpacks IPv4 mapped addresses like ::ffff:192.0.2.1. If this option is enabled that address would be unpacked to 192.0.2.1. Default is disabled. Can only be used when protocol is set to 'both'. <ide> <ide> --- <ide> <ide> Corresponds to `django.db.models.fields.IntegerField`, `django.db.models.fields. <ide> <ide> **Signature**: `IntegerField(max_value=None, min_value=None)` <ide> <del>- `max_value` Validate that the number provided is no greater than this value. <del>- `min_value` Validate that the number provided is no less than this value. <add>* `max_value` Validate that the number provided is no greater than this value. <add>* `min_value` Validate that the number provided is no less than this value. <ide> <ide> ## FloatField <ide> <ide> Corresponds to `django.db.models.fields.FloatField`. <ide> <ide> **Signature**: `FloatField(max_value=None, min_value=None)` <ide> <del>- `max_value` Validate that the number provided is no greater than this value. <del>- `min_value` Validate that the number provided is no less than this value. <add>* `max_value` Validate that the number provided is no greater than this value. <add>* `min_value` Validate that the number provided is no less than this value. <ide> <ide> ## DecimalField <ide> <ide> Corresponds to `django.db.models.fields.DecimalField`. <ide> <ide> **Signature**: `DecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None)` <ide> <del>- `max_digits` The maximum number of digits allowed in the number. It must be either `None` or an integer greater than or equal to `decimal_places`. <del>- `decimal_places` The number of decimal places to store with the number. <del>- `coerce_to_string` Set to `True` if string values should be returned for the representation, or `False` if `Decimal` objects should be returned. Defaults to the same value as the `COERCE_DECIMAL_TO_STRING` settings key, which will be `True` unless overridden. If `Decimal` objects are returned by the serializer, then the final output format will be determined by the renderer. Note that setting `localize` will force the value to `True`. <del>- `max_value` Validate that the number provided is no greater than this value. <del>- `min_value` Validate that the number provided is no less than this value. <del>- `localize` Set to `True` to enable localization of input and output based on the current locale. This will also force `coerce_to_string` to `True`. Defaults to `False`. Note that data formatting is enabled if you have set `USE_L10N=True` in your settings file. <del>- `rounding` Sets the rounding mode used when quantising to the configured precision. Valid values are [`decimal` module rounding modes][python-decimal-rounding-modes]. Defaults to `None`. <add>* `max_digits` The maximum number of digits allowed in the number. It must be either `None` or an integer greater than or equal to `decimal_places`. <add>* `decimal_places` The number of decimal places to store with the number. <add>* `coerce_to_string` Set to `True` if string values should be returned for the representation, or `False` if `Decimal` objects should be returned. Defaults to the same value as the `COERCE_DECIMAL_TO_STRING` settings key, which will be `True` unless overridden. If `Decimal` objects are returned by the serializer, then the final output format will be determined by the renderer. Note that setting `localize` will force the value to `True`. <add>* `max_value` Validate that the number provided is no greater than this value. <add>* `min_value` Validate that the number provided is no less than this value. <add>* `localize` Set to `True` to enable localization of input and output based on the current locale. This will also force `coerce_to_string` to `True`. Defaults to `False`. Note that data formatting is enabled if you have set `USE_L10N=True` in your settings file. <add>* `rounding` Sets the rounding mode used when quantising to the configured precision. Valid values are [`decimal` module rounding modes][python-decimal-rounding-modes]. Defaults to `None`. <ide> <ide> #### Example usage <ide> <ide> The representation is a string following this format `'[DD] [HH:[MM:]]ss[.uuuuuu <ide> <ide> **Signature:** `DurationField(max_value=None, min_value=None)` <ide> <del>- `max_value` Validate that the duration provided is no greater than this value. <del>- `min_value` Validate that the duration provided is no less than this value. <add>* `max_value` Validate that the duration provided is no greater than this value. <add>* `min_value` Validate that the duration provided is no less than this value. <ide> <ide> --- <ide> <ide> Used by `ModelSerializer` to automatically generate fields if the corresponding <ide> <ide> **Signature:** `ChoiceField(choices)` <ide> <del>- `choices` - A list of valid values, or a list of `(key, display_name)` tuples. <del>- `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`. <del>- `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to `None`. <del>- `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"` <add>* `choices` - A list of valid values, or a list of `(key, display_name)` tuples. <add>* `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`. <add>* `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to `None`. <add>* `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"` <ide> <ide> Both the `allow_blank` and `allow_null` are valid options on `ChoiceField`, although it is highly recommended that you only use one and not both. `allow_blank` should be preferred for textual choices, and `allow_null` should be preferred for numeric or other non-textual choices. <ide> <ide> A field that can accept a set of zero, one or many values, chosen from a limited <ide> <ide> **Signature:** `MultipleChoiceField(choices)` <ide> <del>- `choices` - A list of valid values, or a list of `(key, display_name)` tuples. <del>- `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`. <del>- `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to `None`. <del>- `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"` <add>* `choices` - A list of valid values, or a list of `(key, display_name)` tuples. <add>* `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`. <add>* `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to `None`. <add>* `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"` <ide> <ide> As with `ChoiceField`, both the `allow_blank` and `allow_null` options are valid, although it is highly recommended that you only use one and not both. `allow_blank` should be preferred for textual choices, and `allow_null` should be preferred for numeric or other non-textual choices. <ide> <ide> Corresponds to `django.forms.fields.FileField`. <ide> <ide> **Signature:** `FileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)` <ide> <del> - `max_length` - Designates the maximum length for the file name. <del> - `allow_empty_file` - Designates if empty files are allowed. <del>- `use_url` - If set to `True` then URL string values will be used for the output representation. If set to `False` then filename string values will be used for the output representation. Defaults to the value of the `UPLOADED_FILES_USE_URL` settings key, which is `True` unless set otherwise. <add>* `max_length` - Designates the maximum length for the file name. <add>* `allow_empty_file` - Designates if empty files are allowed. <add>* `use_url` - If set to `True` then URL string values will be used for the output representation. If set to `False` then filename string values will be used for the output representation. Defaults to the value of the `UPLOADED_FILES_USE_URL` settings key, which is `True` unless set otherwise. <ide> <ide> ## ImageField <ide> <ide> Corresponds to `django.forms.fields.ImageField`. <ide> <ide> **Signature:** `ImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)` <ide> <del> - `max_length` - Designates the maximum length for the file name. <del> - `allow_empty_file` - Designates if empty files are allowed. <del>- `use_url` - If set to `True` then URL string values will be used for the output representation. If set to `False` then filename string values will be used for the output representation. Defaults to the value of the `UPLOADED_FILES_USE_URL` settings key, which is `True` unless set otherwise. <add>* `max_length` - Designates the maximum length for the file name. <add>* `allow_empty_file` - Designates if empty files are allowed. <add>* `use_url` - If set to `True` then URL string values will be used for the output representation. If set to `False` then filename string values will be used for the output representation. Defaults to the value of the `UPLOADED_FILES_USE_URL` settings key, which is `True` unless set otherwise. <ide> <ide> Requires either the `Pillow` package or `PIL` package. The `Pillow` package is recommended, as `PIL` is no longer actively maintained. <ide> <ide> A field class that validates a list of objects. <ide> <ide> **Signature**: `ListField(child=<A_FIELD_INSTANCE>, allow_empty=True, min_length=None, max_length=None)` <ide> <del>- `child` - A field instance that should be used for validating the objects in the list. If this argument is not provided then objects in the list will not be validated. <del>- `allow_empty` - Designates if empty lists are allowed. <del>- `min_length` - Validates that the list contains no fewer than this number of elements. <del>- `max_length` - Validates that the list contains no more than this number of elements. <add>* `child` - A field instance that should be used for validating the objects in the list. If this argument is not provided then objects in the list will not be validated. <add>* `allow_empty` - Designates if empty lists are allowed. <add>* `min_length` - Validates that the list contains no fewer than this number of elements. <add>* `max_length` - Validates that the list contains no more than this number of elements. <ide> <ide> For example, to validate a list of integers you might use something like the following: <ide> <ide> A field class that validates a dictionary of objects. The keys in `DictField` ar <ide> <ide> **Signature**: `DictField(child=<A_FIELD_INSTANCE>, allow_empty=True)` <ide> <del>- `child` - A field instance that should be used for validating the values in the dictionary. If this argument is not provided then values in the mapping will not be validated. <del>- `allow_empty` - Designates if empty dictionaries are allowed. <add>* `child` - A field instance that should be used for validating the values in the dictionary. If this argument is not provided then values in the mapping will not be validated. <add>* `allow_empty` - Designates if empty dictionaries are allowed. <ide> <ide> For example, to create a field that validates a mapping of strings to strings, you would write something like this: <ide> <ide> A preconfigured `DictField` that is compatible with Django's postgres `HStoreFie <ide> <ide> **Signature**: `HStoreField(child=<A_FIELD_INSTANCE>, allow_empty=True)` <ide> <del>- `child` - A field instance that is used for validating the values in the dictionary. The default child field accepts both empty strings and null values. <del>- `allow_empty` - Designates if empty dictionaries are allowed. <add>* `child` - A field instance that is used for validating the values in the dictionary. The default child field accepts both empty strings and null values. <add>* `allow_empty` - Designates if empty dictionaries are allowed. <ide> <ide> Note that the child field **must** be an instance of `CharField`, as the hstore extension stores values as strings. <ide> <ide> A field class that validates that the incoming data structure consists of valid <ide> <ide> **Signature**: `JSONField(binary, encoder)` <ide> <del>- `binary` - If set to `True` then the field will output and validate a JSON encoded string, rather than a primitive data structure. Defaults to `False`. <del>- `encoder` - Use this JSON encoder to serialize input object. Defaults to `None`. <add>* `binary` - If set to `True` then the field will output and validate a JSON encoded string, rather than a primitive data structure. Defaults to `False`. <add>* `encoder` - Use this JSON encoder to serialize input object. Defaults to `None`. <ide> <ide> --- <ide> <ide> This is a read-only field. It gets its value by calling a method on the serializ <ide> <ide> **Signature**: `SerializerMethodField(method_name=None)` <ide> <del>- `method_name` - The name of the method on the serializer to be called. If not included this defaults to `get_<field_name>`. <add>* `method_name` - The name of the method on the serializer to be called. If not included this defaults to `get_<field_name>`. <ide> <ide> The serializer method referred to by the `method_name` argument should accept a single argument (in addition to `self`), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object. For example: <ide> <ide><path>docs/api-guide/relations.md <ide> For example, the following serializer would lead to a database hit each time eva <ide> class Meta: <ide> model = Album <ide> fields = ['album_name', 'artist', 'tracks'] <del> <add> <ide> # For each album object, tracks should be fetched from database <ide> qs = Album.objects.all() <ide> print(AlbumSerializer(qs, many=True).data) <ide> This field is always read-only. <ide> <ide> As opposed to previously discussed _references_ to another entity, the referred entity can instead also be embedded or _nested_ <ide> in the representation of the object that refers to it. <del>Such nested relationships can be expressed by using serializers as fields. <add>Such nested relationships can be expressed by using serializers as fields. <ide> <ide> If the field is used to represent a to-many relationship, you should add the `many=True` flag to the serializer field. <ide> <ide> This behavior is intended to prevent a template from being unable to render in a <ide> <ide> There are two keyword arguments you can use to control this behavior: <ide> <del>- `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Set to `None` to disable any limiting. Defaults to `1000`. <del>- `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"` <add>* `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Set to `None` to disable any limiting. Defaults to `1000`. <add>* `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"` <ide> <ide> You can also control these globally using the settings `HTML_SELECT_CUTOFF` and `HTML_SELECT_CUTOFF_TEXT`. <ide>
2
Ruby
Ruby
fix warnings for attribute methods with kwargs
501cb3eb68a9513f7fee58337005cb5cd7230d04
<ide><path>activemodel/lib/active_model/attribute_methods.rb <ide> def method_missing(method, *args, &block) <ide> match ? attribute_missing(match, *args, &block) : super <ide> end <ide> end <add> ruby2_keywords(:method_missing) if respond_to?(:ruby2_keywords, true) <ide> <ide> # +attribute_missing+ is like +method_missing+, but for attributes. When <ide> # +method_missing+ is called we check to see if there is a matching <ide><path>activemodel/test/cases/attribute_methods_test.rb <ide> class ModelWithAttributes2 <ide> <ide> attr_accessor :attributes <ide> <del> attribute_method_suffix "_test" <add> attribute_method_suffix "_test", "_kw" <ide> <ide> private <ide> def attribute(name) <ide> def attribute_test(name, attrs = {}) <ide> attrs[name] = attribute(name) <ide> end <ide> <add> def attribute_kw(name, kw: 1) <add> attribute(name) <add> end <add> <ide> def private_method <ide> "<3 <3" <ide> end <ide> def foo <ide> attrs = {} <ide> <ide> assert_equal "bar", m.foo <add> assert_equal "bar", m.foo_kw(kw: 2) <ide> assert_equal "bar", m.foo_test(attrs) <ide> assert_equal "bar", attrs["foo"] <ide> end <ide> def foo <ide> attrs = {} <ide> <ide> assert_equal "bar", m.foo <add> assert_equal "bar", m.foo_kw(kw: 2) <ide> assert_equal "bar", m.foo_test(attrs) <ide> assert_equal "bar", attrs["foo"] <ide> ensure
2
Python
Python
fix tok2vec begin_training
9987ea9e4ddd920a8035c097b3360a80560352cb
<ide><path>spacy/pipeline/tok2vec.py <ide> def begin_training( <ide> <ide> DOCS: https://spacy.io/api/tok2vec#begin_training <ide> """ <del> docs = [Doc(Vocab(), words=["hello"])] <add> docs = [Doc(self.vocab, words=["hello"])] <ide> self.model.initialize(X=docs) <ide> link_vectors_to_models(self.vocab) <ide>
1
Java
Java
upgrade tests to ehcache 2.10+
22345f7c259f416834eeedf4a06c8a33f66b92de
<ide><path>spring-context-support/src/test/java/org/springframework/cache/ehcache/EhCacheSupportTests.java <ide> /* <del> * Copyright 2002-2013 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public void testCacheManagerFromConfigFile() throws Exception { <ide> assertTrue("Correct number of caches loaded", cm.getCacheNames().length == 1); <ide> Cache myCache1 = cm.getCache("myCache1"); <ide> assertFalse("myCache1 is not eternal", myCache1.getCacheConfiguration().isEternal()); <del> assertTrue("myCache1.maxElements == 300", myCache1.getCacheConfiguration().getMaxElementsInMemory() == 300); <add> assertTrue("myCache1.maxElements == 300", myCache1.getCacheConfiguration().getMaxEntriesLocalHeap() == 300); <ide> } <ide> finally { <ide> cacheManagerFb.destroy(); <ide> private void doTestEhCacheFactoryBean(boolean useCacheManagerFb) throws Exceptio <ide> CacheConfiguration config = cache.getCacheConfiguration(); <ide> assertEquals("myCache1", cache.getName()); <ide> if (useCacheManagerFb){ <del> assertEquals("myCache1.maxElements", 300, config.getMaxElementsInMemory()); <add> assertEquals("myCache1.maxElements", 300, config.getMaxEntriesLocalHeap()); <ide> } <ide> else { <del> assertEquals("myCache1.maxElements", 10000, config.getMaxElementsInMemory()); <add> assertEquals("myCache1.maxElements", 10000, config.getMaxEntriesLocalHeap()); <ide> } <ide> <ide> // Cache region is not defined. Should create one with default properties. <ide> private void doTestEhCacheFactoryBean(boolean useCacheManagerFb) throws Exceptio <ide> cache = (Cache) cacheFb.getObject(); <ide> config = cache.getCacheConfiguration(); <ide> assertEquals("undefinedCache", cache.getName()); <del> assertTrue("default maxElements is correct", config.getMaxElementsInMemory() == 10000); <add> assertTrue("default maxElements is correct", config.getMaxEntriesLocalHeap() == 10000); <ide> assertFalse("default eternal is correct", config.isEternal()); <ide> assertTrue("default timeToLive is correct", config.getTimeToLiveSeconds() == 120); <ide> assertTrue("default timeToIdle is correct", config.getTimeToIdleSeconds() == 120); <ide> private void doTestEhCacheFactoryBean(boolean useCacheManagerFb) throws Exceptio <ide> cacheFb.setCacheManager(cacheManagerFb.getObject()); <ide> } <ide> cacheFb.setBeanName("undefinedCache2"); <del> cacheFb.setMaxElementsInMemory(5); <add> cacheFb.setMaxEntriesLocalHeap(5); <ide> cacheFb.setTimeToLive(8); <ide> cacheFb.setTimeToIdle(7); <ide> cacheFb.setDiskExpiryThreadIntervalSeconds(10); <ide> private void doTestEhCacheFactoryBean(boolean useCacheManagerFb) throws Exceptio <ide> config = cache.getCacheConfiguration(); <ide> <ide> assertEquals("undefinedCache2", cache.getName()); <del> assertTrue("overridden maxElements is correct", config.getMaxElementsInMemory() == 5); <add> assertTrue("overridden maxElements is correct", config.getMaxEntriesLocalHeap() == 5); <ide> assertTrue("default timeToLive is correct", config.getTimeToLiveSeconds() == 8); <ide> assertTrue("default timeToIdle is correct", config.getTimeToIdleSeconds() == 7); <ide> assertTrue("overridden diskExpiryThreadIntervalSeconds is correct", config.getDiskExpiryThreadIntervalSeconds() == 10); <ide> public Object createEntry(Object key) throws Exception { <ide> cacheFb.afterPropertiesSet(); <ide> Ehcache myCache1 = cm.getEhcache("myCache1"); <ide> assertTrue(myCache1 instanceof SelfPopulatingCache); <del> assertEquals("myKey1", myCache1.get("myKey1").getValue()); <add> assertEquals("myKey1", myCache1.get("myKey1").getObjectValue()); <ide> } <ide> finally { <ide> cacheManagerFb.destroy(); <ide> public void updateEntryValue(Object key, Object value) throws Exception { <ide> cacheFb.afterPropertiesSet(); <ide> Ehcache myCache1 = cm.getEhcache("myCache1"); <ide> assertTrue(myCache1 instanceof UpdatingSelfPopulatingCache); <del> assertEquals("myKey1", myCache1.get("myKey1").getValue()); <add> assertEquals("myKey1", myCache1.get("myKey1").getObjectValue()); <ide> } <ide> finally { <ide> cacheManagerFb.destroy();
1
Text
Text
add qoala as officially using airflow
e5f177b375dbffc183f40cc642c2b7a53f8836a5
<ide><path>README.md <ide> Currently **officially** using Airflow: <ide> 1. [QuintoAndar](https://quintoandar.com.br) [[@quintoandar](https://github.com/quintoandar)] <ide> 1. [Quizlet](https://quizlet.com) [[@quizlet](https://github.com/quizlet)] <ide> 1. [Quora](https://www.quora.com/) <add>1. [Qoala](https://www.qoala.id) [[@gnomeria](https://github.com/gnomeria), [@qoala-engineering](https://github.com/qoala-engineering)] <ide> 1. [Rakuten](https://www.rakuten.com) <ide> 1. [Raízen](https://www.raizen.com.br/) [[@rudlac](https://github.com/rudlac) & [@guifneves](https://github.com/guifneves)] <ide> 1. [Rapido](https://rapido.bike/) [[@ChethanUK](https://github.com/ChethanUK)]
1
PHP
PHP
add test for save many with exceptions
382273f456878397bc99c2ef95f02df5ad1d38e5
<ide><path>tests/TestCase/ORM/TableTest.php <ide> public function testSaveManyFailed() <ide> } <ide> } <ide> <add> /** <add> * Test saveMany() with failed save due to an exception <add> * <add> * @return void <add> */ <add> public function testSaveManyFailedWithException() <add> { <add> $table = $this->getTableLocator() <add> ->get('authors'); <add> $entities = [ <add> new Entity(['name' => 'mark']), <add> new Entity(['name' => 'jose']) <add> ]; <add> <add> $table->getEventManager()->on('Model.beforeSave', function (Event $event, Entity $entity) { <add> if ($entity->name === 'jose') { <add> throw new \Exception('Oh noes'); <add> } <add> }); <add> <add> $this->expectException(\Exception::class); <add> <add> try { <add> $table->saveMany($entities); <add> } finally { <add> foreach ($entities as $entity) { <add> $this->assertTrue($entity->isNew()); <add> } <add> } <add> } <add> <ide> /** <ide> * Test simple delete. <ide> *
1
Python
Python
fix tablespace command
d985fd7a189cdbfa2093c1225bdeb7eefaeb6978
<ide><path>django/db/backends/schema.py <ide> def alter_db_tablespace(self, model, old_db_tablespace, new_db_tablespace): <ide> """ <ide> Moves a model's table between tablespaces <ide> """ <del> self.execute(self.sql_rename_table % { <add> self.execute(self.sql_retablespace_table % { <ide> "table": self.quote_name(model._meta.db_table), <ide> "old_tablespace": self.quote_name(old_db_tablespace), <ide> "new_tablespace": self.quote_name(new_db_tablespace),
1
Javascript
Javascript
fix few comment typos in fs/watchers.js
bc55b57e64a374e5b677644c857c3d26247c72ef
<ide><path>lib/internal/fs/watchers.js <ide> StatWatcher.prototype[kFSStatWatcherStart] = function(filename, <ide> this._handle.unref(); <ide> <ide> // uv_fs_poll is a little more powerful than ev_stat but we curb it for <del> // the sake of backwards compatibility <add> // the sake of backwards compatibility. <ide> this[kOldStatus] = -1; <ide> <ide> filename = getValidatedPath(filename, 'filename'); <ide> StatWatcher.prototype[kFSStatWatcherStart] = function(filename, <ide> } <ide> }; <ide> <del>// To maximize backward-compatiblity for the end user, <add>// To maximize backward-compatibility for the end user, <ide> // a no-op stub method has been added instead of <del>// totally removing StatWatcher.prototpye.start. <add>// totally removing StatWatcher.prototype.start. <ide> // This should not be documented. <ide> StatWatcher.prototype.start = () => {}; <ide> <ide> function FSWatcher() { <ide> if (this._handle !== null) { <ide> // We don't use this.close() here to avoid firing the close event. <ide> this._handle.close(); <del> this._handle = null; // Make the handle garbage collectable <add> this._handle = null; // Make the handle garbage collectable. <ide> } <ide> const error = errors.uvException({ <ide> errno: status, <ide> FSWatcher.prototype[kFSWatchStart] = function(filename, <ide> } <ide> }; <ide> <del>// To maximize backward-compatiblity for the end user, <add>// To maximize backward-compatibility for the end user, <ide> // a no-op stub method has been added instead of <del>// totally removing FSWatcher.prototpye.start. <add>// totally removing FSWatcher.prototype.start. <ide> // This should not be documented. <ide> FSWatcher.prototype.start = () => {}; <ide> <ide> FSWatcher.prototype.close = function() { <ide> return; <ide> } <ide> this._handle.close(); <del> this._handle = null; // Make the handle garbage collectable <add> this._handle = null; // Make the handle garbage collectable. <ide> process.nextTick(emitCloseNT, this); <ide> }; <ide>
1
Javascript
Javascript
use assert for unreachable code
04bef7aabd298d668e3f0dfe97801d4c04a8e395
<ide><path>lib/internal/util/inspect.js <ide> function handleMaxCallStackSize(ctx, err, constructorName, indentationLvl) { <ide> 'special' <ide> ); <ide> } <del> throw err; <add> /* c8 ignore next */ <add> assert.fail(err.stack); <ide> } <ide> <ide> function formatNumber(fn, value) {
1
Text
Text
add link to rel project
99d0412b6ebf1af8e5bd4755f2ec8d1947d8cef5
<ide><path>website/docs/usage/layers-architectures.md <ide> steps required: <ide> machine learning model that sets annotations on the [`Doc`](/api/doc) passing <ide> through the pipeline. <ide> <del><!-- TODO: <Project id="tutorials/ner-relations"> <del> <del></Project> --> <add><Project id="tutorials/rel_component"> <add>Run this example use-case by using our project template. It includes all the <add>code to create the ML model and the pipeline component from scratch. <add>It contains two config files to train the model: <add>one to run on CPU with a Tok2Vec layer, and one for the GPU using a transformer. <add>The project applies the relation extraction component to identify biomolecular <add>interactions, but you can easily swap in your own dataset for your experiments. <add></Project> <ide> <ide> #### Step 1: Implementing the Model {#component-rel-model} <ide> <ide> def make_relation_extractor(nlp, name, model): <ide> return RelationExtractor(nlp.vocab, model, name) <ide> ``` <ide> <del><!-- TODO: <Project id="tutorials/ner-relations"> <del> <del></Project> --> <add><Project id="tutorials/rel_component"> <add>Run this example use-case by using our project template. It includes all the <add>code to create the ML model and the pipeline component from scratch. <add>It contains two config files to train the model: <add>one to run on CPU with a Tok2Vec layer, and one for the GPU using a transformer. <add>The project applies the relation extraction component to identify biomolecular <add>interactions, but you can easily swap in your own dataset for your experiments. <add></Project>
1
Javascript
Javascript
add a console log on boot
c2816764f3098139bab06391d9a3f3f813feec92
<ide><path>examples/universal/server.js <ide> function renderFullPage(html, initialState) { <ide> `; <ide> } <ide> <del>app.listen(port); <add>app.listen(port, (error) => { <add> if (error) { <add> console.error(error); <add> } else { <add> console.info('==> 🌎 Listening on port 8080. Open up http://localhost:8080/ in your browser.'); <add> } <add>});
1
Javascript
Javascript
await configuration loading on windows
92db49314fd2af83365ae7191671ad53fd87be3f
<ide><path>src/main-process/atom-application.js <ide> module.exports = class AtomApplication extends EventEmitter { <ide> ); <ide> }); <ide> <del> // TodoElectronIssue: In electron v2 awaiting the watcher causes some delay <del> // in Windows machines, which affects directly the startup time. <del> if (process.platform !== 'win32') { <del> await this.configFilePromise; <del> } <add> await this.configFilePromise; <ide> } <ide> <ide> let optionsForWindowsToOpen = [];
1
Javascript
Javascript
resolve perf regression introduced by v8 7.3
147b9d9792fe5772b554f4be77305805f361a42d
<ide><path>lib/_stream_readable.js <ide> function readableAddChunk(stream, chunk, encoding, addToFront) { <ide> } else if (state.objectMode || chunk && chunk.length > 0) { <ide> if (typeof chunk !== 'string' && <ide> !state.objectMode && <del> Object.getPrototypeOf(chunk) !== Buffer.prototype) { <add> // Do not use Object.getPrototypeOf as it is slower since V8 7.3. <add> !(chunk instanceof Buffer)) { <ide> chunk = Stream._uint8ArrayToBuffer(chunk); <ide> } <ide> <ide> function howMuchToRead(n, state) { <ide> // You can override either this method, or the async _read(n) below. <ide> Readable.prototype.read = function(n) { <ide> debug('read', n); <del> n = parseInt(n, 10); <add> // Same as parseInt(undefined, 10), however V8 7.3 performance regressed <add> // in this scenario, so we are doing it manually. <add> if (n === undefined) { <add> n = NaN; <add> } else if (!Number.isInteger(n)) { <add> n = parseInt(n, 10); <add> } <ide> const state = this._readableState; <ide> const nOrig = n; <ide> <ide><path>lib/_stream_writable.js <ide> Writable.prototype.write = function(chunk, encoding, cb) { <ide> var ret = false; <ide> const isBuf = !state.objectMode && Stream._isUint8Array(chunk); <ide> <del> if (isBuf && Object.getPrototypeOf(chunk) !== Buffer.prototype) { <add> // Do not use Object.getPrototypeOf as it is slower since V8 7.3. <add> if (isBuf && !(chunk instanceof Buffer)) { <ide> chunk = Stream._uint8ArrayToBuffer(chunk); <ide> } <ide>
2
PHP
PHP
add integration test for
fa9b7f8efe8e81a8d5a754c7e5eaf5f32ce31af0
<ide><path>tests/TestCase/ORM/QueryRegressionTest.php <ide> public function testCountWithUnionQuery() { <ide> $this->assertEquals(2, $query->count()); <ide> } <ide> <add>/** <add> * Integration test when selecting no fields on the primary table. <add> * <add> * @return void <add> */ <add> public function testSelectNoFieldsOnPrimaryAlias() { <add> $table = TableRegistry::get('Articles'); <add> $table->belongsTo('Users'); <add> $query = $table->find() <add> ->select(['Users__id' => 'id']); <add> $results = $query->toArray(); <add> $this->assertCount(3, $results); <add> } <add> <ide> }
1
Go
Go
add serialize/deserialize for sequence list
75443aaf729e650f9043bda2fac59b1bc62f85e3
<ide><path>libnetwork/bitseq/sequence.go <ide> package bitseq <ide> <ide> import ( <ide> "fmt" <add> <add> "github.com/docker/libnetwork/netutils" <ide> ) <ide> <ide> // Block Sequence constants <ide> func (s *Sequence) Equal(o *Sequence) bool { <ide> return true <ide> } <ide> <add>// ToByteArray converts the sequence into a byte array <add>// TODO (aboch): manage network/host order stuff <add>func (s *Sequence) ToByteArray() ([]byte, error) { <add> var bb []byte <add> <add> p := s <add> for p != nil { <add> bb = append(bb, netutils.U32ToA(p.Block)...) <add> bb = append(bb, netutils.U32ToA(p.Count)...) <add> p = p.Next <add> } <add> <add> return bb, nil <add>} <add> <add>// FromByteArray construct the sequence from the byte array <add>// TODO (aboch): manage network/host order stuff <add>func (s *Sequence) FromByteArray(data []byte) error { <add> l := len(data) <add> if l%8 != 0 { <add> return fmt.Errorf("cannot deserialize byte sequence of lenght %d", l) <add> } <add> <add> p := s <add> i := 0 <add> for { <add> p.Block = netutils.ATo32(data[i : i+4]) <add> p.Count = netutils.ATo32(data[i+4 : i+8]) <add> i += 8 <add> if i == l { <add> break <add> } <add> p.Next = &Sequence{} <add> p = p.Next <add> } <add> <add> return nil <add>} <add> <ide> // GetFirstAvailable looks for the first unset bit in passed mask <ide> func GetFirstAvailable(head *Sequence) (int, int) { <ide> byteIndex := 0 <ide><path>libnetwork/bitseq/sequence_test.go <ide> func TestPushReservation(t *testing.T) { <ide> } <ide> } <ide> } <add> <add>func TestSerializeDeserialize(t *testing.T) { <add> s := &Sequence{ <add> Block: 0xffffffff, <add> Count: 1, <add> Next: &Sequence{ <add> Block: 0xFF000000, <add> Count: 1, <add> Next: &Sequence{ <add> Block: 0xffffffff, <add> Count: 6, <add> Next: &Sequence{ <add> Block: 0xffffffff, <add> Count: 1, <add> Next: &Sequence{ <add> Block: 0xFF800000, <add> Count: 1, <add> Next: &Sequence{ <add> Block: 0xffffffff, <add> Count: 6, <add> }, <add> }, <add> }, <add> }, <add> }, <add> } <add> <add> data, err := s.ToByteArray() <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> r := &Sequence{} <add> err = r.FromByteArray(data) <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> if !s.Equal(r) { <add> t.Fatalf("Sequences are different: \n%v\n%v", s, r) <add> } <add>} <ide><path>libnetwork/netutils/utils.go <ide> func GenerateIfaceName(prefix string, len int) (string, error) { <ide> } <ide> return "", types.InternalErrorf("could not generate interface name") <ide> } <add> <add>func byteArrayToInt(array []byte, numBytes int) uint64 { <add> if numBytes <= 0 || numBytes > 8 { <add> panic("Invalid argument") <add> } <add> num := 0 <add> for i := 0; i <= len(array)-1; i++ { <add> num += int(array[len(array)-1-i]) << uint(i*8) <add> } <add> return uint64(num) <add>} <add> <add>// ATo64 converts a byte array into a uint32 <add>func ATo64(array []byte) uint64 { <add> return byteArrayToInt(array, 8) <add>} <add> <add>// ATo32 converts a byte array into a uint32 <add>func ATo32(array []byte) uint32 { <add> return uint32(byteArrayToInt(array, 4)) <add>} <add> <add>// ATo16 converts a byte array into a uint16 <add>func ATo16(array []byte) uint16 { <add> return uint16(byteArrayToInt(array, 2)) <add>} <add> <add>func intToByteArray(val uint64, numBytes int) []byte { <add> array := make([]byte, numBytes) <add> for i := numBytes - 1; i >= 0; i-- { <add> array[i] = byte(val & 0xff) <add> val = val >> 8 <add> } <add> return array <add>} <add> <add>// U64ToA converts a uint64 to a byte array <add>func U64ToA(val uint64) []byte { <add> return intToByteArray(uint64(val), 8) <add>} <add> <add>// U32ToA converts a uint64 to a byte array <add>func U32ToA(val uint32) []byte { <add> return intToByteArray(uint64(val), 4) <add>} <add> <add>// U16ToA converts a uint64 to a byte array <add>func U16ToA(val uint16) []byte { <add> return intToByteArray(uint64(val), 2) <add>}
3
PHP
PHP
take care of more int casts
04ef39217f2edb0a4abee6c903146036f3c53a91
<ide><path>lib/Cake/Cache/Engine/ApcEngine.php <ide> public function write($key, $value, $duration) { <ide> */ <ide> public function read($key) { <ide> $time = time(); <del> $cachetime = intval(apc_fetch($key . '_expires')); <add> $cachetime = (int)apc_fetch($key . '_expires'); <ide> if ($cachetime !== 0 && ($cachetime < $time || ($time + $this->settings['duration']) < $cachetime)) { <ide> return false; <ide> } <ide><path>lib/Cake/Cache/Engine/FileEngine.php <ide> public function read($key) { <ide> <ide> $this->_File->rewind(); <ide> $time = time(); <del> $cachetime = intval($this->_File->current()); <add> $cachetime = (int)$this->_File->current(); <ide> <ide> if ($cachetime !== false && ($cachetime < $time || ($time + $this->settings['duration']) < $cachetime)) { <ide> if ($this->settings['lock']) { <ide><path>lib/Cake/Cache/Engine/WincacheEngine.php <ide> public function write($key, $value, $duration) { <ide> */ <ide> public function read($key) { <ide> $time = time(); <del> $cachetime = intval(wincache_ucache_get($key . '_expires')); <add> $cachetime = (int)wincache_ucache_get($key . '_expires'); <ide> if ($cachetime < $time || ($time + $this->settings['duration']) < $cachetime) { <ide> return false; <ide> } <ide><path>lib/Cake/Cache/Engine/XcacheEngine.php <ide> public function write($key, $value, $duration) { <ide> public function read($key) { <ide> if (xcache_isset($key)) { <ide> $time = time(); <del> $cachetime = intval(xcache_get($key . '_expires')); <add> $cachetime = (int)xcache_get($key . '_expires'); <ide> if ($cachetime < $time || ($time + $this->settings['duration']) < $cachetime) { <ide> return false; <ide> } <ide><path>lib/Cake/Console/Command/AclShell.php <ide> protected function _getNodeId($class, $identifier) { <ide> * @return array aro, aco, action <ide> */ <ide> protected function _getParams() { <del> $aro = is_numeric($this->args[0]) ? intval($this->args[0]) : $this->args[0]; <del> $aco = is_numeric($this->args[1]) ? intval($this->args[1]) : $this->args[1]; <add> $aro = is_numeric($this->args[0]) ? (int)$this->args[0] : $this->args[0]; <add> $aco = is_numeric($this->args[1]) ? (int)$this->args[1] : $this->args[1]; <ide> $aroName = $aro; <ide> $acoName = $aco; <ide> <ide><path>lib/Cake/Console/Command/Task/ModelTask.php <ide> public function doMoreAssociations(Model $model, $associations) { <ide> while (strtolower($wannaDoMoreAssoc) === 'y') { <ide> $assocs = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany'); <ide> $this->out(__d('cake_console', 'What is the association type?')); <del> $assocType = intval($this->inOptions($assocs, __d('cake_console', 'Enter a number'))); <add> $assocType = (int)$this->inOptions($assocs, __d('cake_console', 'Enter a number')); <ide> <ide> $this->out(__d('cake_console', "For the following options be very careful to match your setup exactly.\n" . <ide> "Any spelling mistakes will cause errors.")); <ide><path>lib/Cake/Controller/Component/PaginatorComponent.php <ide> public function paginate($object = null, $scope = array(), $whitelist = array()) <ide> } <ide> $count = $object->find('count', array_merge($parameters, $extra)); <ide> } <del> $pageCount = intval(ceil($count / $limit)); <add> $pageCount = (int)ceil($count / $limit); <ide> $requestedPage = $page; <ide> $page = max(min($page, $pageCount), 1); <ide> <ide><path>lib/Cake/Model/Datasource/Database/Sqlite.php <ide> public function index($model) { <ide> $key['name'] = 'PRIMARY'; <ide> } <ide> $index[$key['name']]['column'] = $keyCol[0]['name']; <del> $index[$key['name']]['unique'] = intval($key['unique'] == 1); <add> $index[$key['name']]['unique'] = (int)$key['unique'] === 1; <ide> } else { <ide> if (!is_array($index[$key['name']]['column'])) { <ide> $col[] = $index[$key['name']]['column']; <ide><path>lib/Cake/Model/Datasource/Database/Sqlserver.php <ide> public function renderStatement($type, $data) { <ide> if (version_compare($this->getVersion(), '11', '<') && preg_match('/FETCH\sFIRST\s+([0-9]+)/i', $limit, $offset)) { <ide> preg_match('/OFFSET\s*(\d+)\s*.*?(\d+)\s*ROWS/', $limit, $limitOffset); <ide> <del> $limit = 'TOP ' . intval($limitOffset[2]); <del> $page = intval($limitOffset[1] / $limitOffset[2]); <del> $offset = intval($limitOffset[2] * $page); <add> $limit = 'TOP ' . (int)$limitOffset[2]; <add> $page = (int)($limitOffset[1] / $limitOffset[2]); <add> $offset = (int)($limitOffset[2] * $page); <ide> <ide> $rowCounter = self::ROW_COUNTER; <ide> $sql = "SELECT {$limit} * FROM ( <ide><path>lib/Cake/Model/Model.php <ide> public function updateCounterCache($keys = array(), $created = false) { <ide> <ide> if (isset($keys['old'][$foreignKey]) && $keys['old'][$foreignKey] != $keys[$foreignKey]) { <ide> $conditions[$fkQuoted] = $keys['old'][$foreignKey]; <del> $count = intval($this->find('count', compact('conditions', 'recursive'))); <add> $count = (int)$this->find('count', compact('conditions', 'recursive')); <ide> <ide> $Model->updateAll( <ide> array($field => $count), <ide> public function updateCounterCache($keys = array(), $created = false) { <ide> $conditions = array_merge($conditions, (array)$conditions); <ide> } <ide> <del> $count = intval($this->find('count', compact('conditions', 'recursive'))); <add> $count = (int)$this->find('count', compact('conditions', 'recursive')); <ide> <ide> $Model->updateAll( <ide> array($field => $count), <ide> public function buildQuery($type = 'first', $query = array()) { <ide> $query = $this->{'_find' . ucfirst($type)}('before', $query); <ide> } <ide> <del> if (!is_numeric($query['page']) || intval($query['page']) < 1) { <add> if (!is_numeric($query['page']) || (int)$query['page'] < 1) { <ide> $query['page'] = 1; <ide> } <ide> <ide> protected function _findCount($state, $query, $results = array()) { <ide> return count($results); <ide> } <ide> <del> return intval($results[0][$key]['count']); <add> return (int)$results[0][$key]['count']; <ide> } <ide> } <ide> <ide><path>lib/Cake/Test/Case/Model/ModelWriteTest.php <ide> public function testUpdateExisting() { <ide> 'user' => 'some user', <ide> 'password' => 'some password' <ide> ))); <del> $this->assertTrue(is_int($TestModel->id) || (intval($TestModel->id) === 5)); <add> $this->assertTrue(is_int($TestModel->id) || ((int)$TestModel->id === 5)); <ide> $id = $TestModel->id; <ide> <ide> $TestModel->save(array( <ide><path>lib/Cake/Utility/CakeTime.php <ide> public static function gmt($dateString = null) { <ide> $time = self::fromString($dateString); <ide> } <ide> return gmmktime( <del> intval(date('G', $time)), <del> intval(date('i', $time)), <del> intval(date('s', $time)), <del> intval(date('n', $time)), <del> intval(date('j', $time)), <del> intval(date('Y', $time)) <add> (int)date('G', $time), <add> (int)date('i', $time), <add> (int)date('s', $time), <add> (int)date('n', $time), <add> (int)date('j', $time), <add> (int)date('Y', $time) <ide> ); <ide> } <ide> <ide><path>lib/Cake/View/Helper/FormHelper.php <ide> protected function _generateOptions($name, $options = array()) { <ide> } <ide> break; <ide> case 'year': <del> $current = intval(date('Y')); <add> $current = (int)date('Y'); <ide> <ide> $min = !isset($options['min']) ? $current - 20 : (int)$options['min']; <ide> $max = !isset($options['max']) ? $current + 20 : (int)$options['max']; <ide><path>lib/Cake/View/Helper/JsHelper.php <ide> protected function _createVars() { <ide> */ <ide> public function link($title, $url = null, $options = array()) { <ide> if (!isset($options['id'])) { <del> $options['id'] = 'link-' . intval(mt_rand()); <add> $options['id'] = 'link-' . (int)mt_rand(); <ide> } <ide> list($options, $htmlOptions) = $this->_getHtmlOptions($options); <ide> $out = $this->Html->link($title, $url, $htmlOptions); <ide> public function set($one, $two = null) { <ide> */ <ide> public function submit($caption = null, $options = array()) { <ide> if (!isset($options['id'])) { <del> $options['id'] = 'submit-' . intval(mt_rand()); <add> $options['id'] = 'submit-' . (int)mt_rand(); <ide> } <ide> $formOptions = array('div'); <ide> list($options, $htmlOptions) = $this->_getHtmlOptions($options, $formOptions); <ide><path>lib/Cake/View/Helper/PaginatorHelper.php <ide> public function numbers($options = array()) { <ide> $out = ''; <ide> <ide> if ($modulus && $params['pageCount'] > $modulus) { <del> $half = intval($modulus / 2); <add> $half = (int)($modulus / 2); <ide> $end = $params['page'] + $half; <ide> <ide> if ($end > $params['pageCount']) {
15
Mixed
Ruby
add the fetch method to sessions
84c9f4164bbd5f3d2697949bdd2cdbd15ce6091e
<ide><path>actionpack/CHANGELOG.md <add>* Add `session#fetch` method <add> <add> fetch behaves like [Hash#fetch](http://www.ruby-doc.org/core-1.9.3/Hash.html#method-i-fetch). <add> It returns a value from the hash for the given key. <add> If the key can’t be found, there are several options: <add> <add> * With no other arguments, it will raise an KeyError exception. <add> * If a default value is given, then that will be returned. <add> * If the optional code block is specified, then that will be run and its result returned. <add> <add> *Damien Mathieu* <add> <ide> * Don't let strong parameters mutate the given hash via `fetch` <ide> <ide> Create a new instance if the given parameter is a `Hash` instead of <ide><path>actionpack/lib/action_dispatch/request/session.rb <ide> def delete(key) <ide> @delegate.delete key.to_s <ide> end <ide> <add> def fetch(key, default=nil) <add> if self.key?(key) <add> self[key] <add> elsif default <add> self[key] = default <add> elsif block_given? <add> self[key] = yield(key) <add> else <add> raise KeyError <add> end <add> end <add> <ide> def inspect <ide> if loaded? <ide> super <ide><path>actionpack/test/dispatch/request/session_test.rb <ide> def test_clear <ide> assert_equal([], s.values) <ide> end <ide> <add> def test_fetch <add> session = Session.create(store, {}, {}) <add> session['one'] = '1' <add> <add> assert_equal '1', session.fetch(:one) <add> assert_equal '2', session.fetch(:two, '2') <add> assert_equal 'three', session.fetch(:three) {|el| el.to_s } <add> <add> assert_raise KeyError do <add> session.fetch(:four) <add> end <add> end <add> <ide> private <ide> def store <ide> Class.new {
3
Javascript
Javascript
make stripping of trailing slashes configurable
3878be52f6d95fca4c386d4a5523f3c8fcb04270
<ide><path>src/ngResource/resource.js <ide> function shallowClearAndCopy(src, dst) { <ide> * <ide> * Requires the {@link ngResource `ngResource`} module to be installed. <ide> * <add> * By default, trailing slashes will be stripped from the calculated URLs, <add> * which can pose problems with server backends that do not expect that <add> * behavior. This can be disabled by configuring the `$resourceProvider` like <add> * this: <add> * <add> * ```js <add> app.config(['$resourceProvider', function ($resourceProvider) { <add> // Don't strip trailing slashes from calculated URLs <add> $resourceProvider.defaults.stripTrailingSlashes = false; <add> }]); <add> * ``` <add> * <ide> * @param {string} url A parametrized URL template with parameters prefixed by `:` as in <ide> * `/user/:username`. If you are using a URL with a port number (e.g. <ide> * `http://example.com:8080/api`), it will be respected. <ide> function shallowClearAndCopy(src, dst) { <ide> * `response` and `responseError`. Both `response` and `responseError` interceptors get called <ide> * with `http response` object. See {@link ng.$http $http interceptors}. <ide> * <add> * @param {Object} options Hash with custom settings that should extend the <add> * default `$resourceProvider` behavior. The only supported option is <add> * <add> * Where: <add> * <add> * - **`stripTrailingSlashes`** – {boolean} – If true then the trailing <add> * slashes from any calculated URL will be stripped. (Defaults to true.) <add> * <ide> * @returns {Object} A resource "class" object with methods for the default set of resource actions <ide> * optionally extended with custom `actions`. The default set contains these actions: <ide> * ```js <ide> function shallowClearAndCopy(src, dst) { <ide> * ``` <ide> */ <ide> angular.module('ngResource', ['ng']). <del> factory('$resource', ['$http', '$q', function($http, $q) { <del> <del> var DEFAULT_ACTIONS = { <del> 'get': {method:'GET'}, <del> 'save': {method:'POST'}, <del> 'query': {method:'GET', isArray:true}, <del> 'remove': {method:'DELETE'}, <del> 'delete': {method:'DELETE'} <add> provider('$resource', function () { <add> var provider = this; <add> <add> this.defaults = { <add> // Strip slashes by default <add> stripTrailingSlashes: true, <add> <add> // Default actions configuration <add> actions: { <add> 'get': {method: 'GET'}, <add> 'save': {method: 'POST'}, <add> 'query': {method: 'GET', isArray: true}, <add> 'remove': {method: 'DELETE'}, <add> 'delete': {method: 'DELETE'} <add> } <ide> }; <del> var noop = angular.noop, <add> <add> this.$get = ['$http', '$q', function ($http, $q) { <add> <add> var noop = angular.noop, <ide> forEach = angular.forEach, <ide> extend = angular.extend, <ide> copy = angular.copy, <ide> isFunction = angular.isFunction; <ide> <del> /** <del> * We need our custom method because encodeURIComponent is too aggressive and doesn't follow <del> * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path <del> * segments: <del> * segment = *pchar <del> * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" <del> * pct-encoded = "%" HEXDIG HEXDIG <del> * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" <del> * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" <del> * / "*" / "+" / "," / ";" / "=" <del> */ <del> function encodeUriSegment(val) { <del> return encodeUriQuery(val, true). <del> replace(/%26/gi, '&'). <del> replace(/%3D/gi, '='). <del> replace(/%2B/gi, '+'); <del> } <add> /** <add> * We need our custom method because encodeURIComponent is too aggressive and doesn't follow <add> * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set <add> * (pchar) allowed in path segments: <add> * segment = *pchar <add> * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" <add> * pct-encoded = "%" HEXDIG HEXDIG <add> * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" <add> * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" <add> * / "*" / "+" / "," / ";" / "=" <add> */ <add> function encodeUriSegment(val) { <add> return encodeUriQuery(val, true). <add> replace(/%26/gi, '&'). <add> replace(/%3D/gi, '='). <add> replace(/%2B/gi, '+'); <add> } <ide> <ide> <del> /** <del> * This method is intended for encoding *key* or *value* parts of query component. We need a <del> * custom method because encodeURIComponent is too aggressive and encodes stuff that doesn't <del> * have to be encoded per http://tools.ietf.org/html/rfc3986: <del> * query = *( pchar / "/" / "?" ) <del> * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" <del> * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" <del> * pct-encoded = "%" HEXDIG HEXDIG <del> * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" <del> * / "*" / "+" / "," / ";" / "=" <del> */ <del> function encodeUriQuery(val, pctEncodeSpaces) { <del> return encodeURIComponent(val). <del> replace(/%40/gi, '@'). <del> replace(/%3A/gi, ':'). <del> replace(/%24/g, '$'). <del> replace(/%2C/gi, ','). <del> replace(/%20/g, (pctEncodeSpaces ? '%20' : '+')); <del> } <add> /** <add> * This method is intended for encoding *key* or *value* parts of query component. We need a <add> * custom method because encodeURIComponent is too aggressive and encodes stuff that doesn't <add> * have to be encoded per http://tools.ietf.org/html/rfc3986: <add> * query = *( pchar / "/" / "?" ) <add> * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" <add> * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" <add> * pct-encoded = "%" HEXDIG HEXDIG <add> * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" <add> * / "*" / "+" / "," / ";" / "=" <add> */ <add> function encodeUriQuery(val, pctEncodeSpaces) { <add> return encodeURIComponent(val). <add> replace(/%40/gi, '@'). <add> replace(/%3A/gi, ':'). <add> replace(/%24/g, '$'). <add> replace(/%2C/gi, ','). <add> replace(/%20/g, (pctEncodeSpaces ? '%20' : '+')); <add> } <ide> <del> function Route(template, defaults) { <del> this.template = template; <del> this.defaults = defaults || {}; <del> this.urlParams = {}; <del> } <add> function Route(template, defaults) { <add> this.template = template; <add> this.defaults = extend({}, provider.defaults, defaults); <add> this.urlParams = {}; <add> } <ide> <del> Route.prototype = { <del> setUrlParams: function(config, params, actionUrl) { <del> var self = this, <add> Route.prototype = { <add> setUrlParams: function (config, params, actionUrl) { <add> var self = this, <ide> url = actionUrl || self.template, <ide> val, <ide> encodedVal; <ide> <del> var urlParams = self.urlParams = {}; <del> forEach(url.split(/\W/), function(param){ <del> if (param === 'hasOwnProperty') { <del> throw $resourceMinErr('badname', "hasOwnProperty is not a valid parameter name."); <del> } <del> if (!(new RegExp("^\\d+$").test(param)) && param && <del> (new RegExp("(^|[^\\\\]):" + param + "(\\W|$)").test(url))) { <del> urlParams[param] = true; <del> } <del> }); <del> url = url.replace(/\\:/g, ':'); <del> <del> params = params || {}; <del> forEach(self.urlParams, function(_, urlParam){ <del> val = params.hasOwnProperty(urlParam) ? params[urlParam] : self.defaults[urlParam]; <del> if (angular.isDefined(val) && val !== null) { <del> encodedVal = encodeUriSegment(val); <del> url = url.replace(new RegExp(":" + urlParam + "(\\W|$)", "g"), function(match, p1) { <del> return encodedVal + p1; <del> }); <del> } else { <del> url = url.replace(new RegExp("(\/?):" + urlParam + "(\\W|$)", "g"), function(match, <del> leadingSlashes, tail) { <del> if (tail.charAt(0) == '/') { <del> return tail; <del> } else { <del> return leadingSlashes + tail; <del> } <del> }); <add> var urlParams = self.urlParams = {}; <add> forEach(url.split(/\W/), function (param) { <add> if (param === 'hasOwnProperty') { <add> throw $resourceMinErr('badname', "hasOwnProperty is not a valid parameter name."); <add> } <add> if (!(new RegExp("^\\d+$").test(param)) && param && <add> (new RegExp("(^|[^\\\\]):" + param + "(\\W|$)").test(url))) { <add> urlParams[param] = true; <add> } <add> }); <add> url = url.replace(/\\:/g, ':'); <add> <add> params = params || {}; <add> forEach(self.urlParams, function (_, urlParam) { <add> val = params.hasOwnProperty(urlParam) ? params[urlParam] : self.defaults[urlParam]; <add> if (angular.isDefined(val) && val !== null) { <add> encodedVal = encodeUriSegment(val); <add> url = url.replace(new RegExp(":" + urlParam + "(\\W|$)", "g"), function (match, p1) { <add> return encodedVal + p1; <add> }); <add> } else { <add> url = url.replace(new RegExp("(\/?):" + urlParam + "(\\W|$)", "g"), function (match, <add> leadingSlashes, tail) { <add> if (tail.charAt(0) == '/') { <add> return tail; <add> } else { <add> return leadingSlashes + tail; <add> } <add> }); <add> } <add> }); <add> <add> // strip trailing slashes and set the url (unless this behavior is specifically disabled) <add> if (self.defaults.stripTrailingSlashes) { <add> url = url.replace(/\/+$/, '') || '/'; <ide> } <del> }); <ide> <del> // strip trailing slashes and set the url <del> url = url.replace(/\/+$/, '') || '/'; <del> // then replace collapse `/.` if found in the last URL path segment before the query <del> // E.g. `http://url.com/id./format?q=x` becomes `http://url.com/id.format?q=x` <del> url = url.replace(/\/\.(?=\w+($|\?))/, '.'); <del> // replace escaped `/\.` with `/.` <del> config.url = url.replace(/\/\\\./, '/.'); <add> // then replace collapse `/.` if found in the last URL path segment before the query <add> // E.g. `http://url.com/id./format?q=x` becomes `http://url.com/id.format?q=x` <add> url = url.replace(/\/\.(?=\w+($|\?))/, '.'); <add> // replace escaped `/\.` with `/.` <add> config.url = url.replace(/\/\\\./, '/.'); <ide> <ide> <del> // set params - delegate param encoding to $http <del> forEach(params, function(value, key){ <del> if (!self.urlParams[key]) { <del> config.params = config.params || {}; <del> config.params[key] = value; <del> } <del> }); <del> } <del> }; <add> // set params - delegate param encoding to $http <add> forEach(params, function (value, key) { <add> if (!self.urlParams[key]) { <add> config.params = config.params || {}; <add> config.params[key] = value; <add> } <add> }); <add> } <add> }; <ide> <ide> <del> function resourceFactory(url, paramDefaults, actions) { <del> var route = new Route(url); <add> function resourceFactory(url, paramDefaults, actions, options) { <add> var route = new Route(url, options); <ide> <del> actions = extend({}, DEFAULT_ACTIONS, actions); <add> actions = extend({}, provider.defaults.actions, actions); <ide> <del> function extractParams(data, actionParams){ <del> var ids = {}; <del> actionParams = extend({}, paramDefaults, actionParams); <del> forEach(actionParams, function(value, key){ <del> if (isFunction(value)) { value = value(); } <del> ids[key] = value && value.charAt && value.charAt(0) == '@' ? <del> lookupDottedPath(data, value.substr(1)) : value; <del> }); <del> return ids; <del> } <add> function extractParams(data, actionParams) { <add> var ids = {}; <add> actionParams = extend({}, paramDefaults, actionParams); <add> forEach(actionParams, function (value, key) { <add> if (isFunction(value)) { value = value(); } <add> ids[key] = value && value.charAt && value.charAt(0) == '@' ? <add> lookupDottedPath(data, value.substr(1)) : value; <add> }); <add> return ids; <add> } <ide> <del> function defaultResponseInterceptor(response) { <del> return response.resource; <del> } <add> function defaultResponseInterceptor(response) { <add> return response.resource; <add> } <ide> <del> function Resource(value){ <del> shallowClearAndCopy(value || {}, this); <del> } <add> function Resource(value) { <add> shallowClearAndCopy(value || {}, this); <add> } <ide> <del> forEach(actions, function(action, name) { <del> var hasBody = /^(POST|PUT|PATCH)$/i.test(action.method); <del> <del> Resource[name] = function(a1, a2, a3, a4) { <del> var params = {}, data, success, error; <del> <del> /* jshint -W086 */ /* (purposefully fall through case statements) */ <del> switch(arguments.length) { <del> case 4: <del> error = a4; <del> success = a3; <del> //fallthrough <del> case 3: <del> case 2: <del> if (isFunction(a2)) { <del> if (isFunction(a1)) { <del> success = a1; <del> error = a2; <del> break; <del> } <add> forEach(actions, function (action, name) { <add> var hasBody = /^(POST|PUT|PATCH)$/i.test(action.method); <add> <add> Resource[name] = function (a1, a2, a3, a4) { <add> var params = {}, data, success, error; <ide> <del> success = a2; <del> error = a3; <add> /* jshint -W086 */ /* (purposefully fall through case statements) */ <add> switch (arguments.length) { <add> case 4: <add> error = a4; <add> success = a3; <ide> //fallthrough <del> } else { <del> params = a1; <del> data = a2; <del> success = a3; <del> break; <del> } <del> case 1: <del> if (isFunction(a1)) success = a1; <del> else if (hasBody) data = a1; <del> else params = a1; <del> break; <del> case 0: break; <del> default: <del> throw $resourceMinErr('badargs', <del> "Expected up to 4 arguments [params, data, success, error], got {0} arguments", <del> arguments.length); <del> } <del> /* jshint +W086 */ /* (purposefully fall through case statements) */ <del> <del> var isInstanceCall = this instanceof Resource; <del> var value = isInstanceCall ? data : (action.isArray ? [] : new Resource(data)); <del> var httpConfig = {}; <del> var responseInterceptor = action.interceptor && action.interceptor.response || <del> defaultResponseInterceptor; <del> var responseErrorInterceptor = action.interceptor && action.interceptor.responseError || <del> undefined; <del> <del> forEach(action, function(value, key) { <del> if (key != 'params' && key != 'isArray' && key != 'interceptor') { <del> httpConfig[key] = copy(value); <add> case 3: <add> case 2: <add> if (isFunction(a2)) { <add> if (isFunction(a1)) { <add> success = a1; <add> error = a2; <add> break; <add> } <add> <add> success = a2; <add> error = a3; <add> //fallthrough <add> } else { <add> params = a1; <add> data = a2; <add> success = a3; <add> break; <add> } <add> case 1: <add> if (isFunction(a1)) success = a1; <add> else if (hasBody) data = a1; <add> else params = a1; <add> break; <add> case 0: break; <add> default: <add> throw $resourceMinErr('badargs', <add> "Expected up to 4 arguments [params, data, success, error], got {0} arguments", <add> arguments.length); <ide> } <del> }); <add> /* jshint +W086 */ /* (purposefully fall through case statements) */ <add> <add> var isInstanceCall = this instanceof Resource; <add> var value = isInstanceCall ? data : (action.isArray ? [] : new Resource(data)); <add> var httpConfig = {}; <add> var responseInterceptor = action.interceptor && action.interceptor.response || <add> defaultResponseInterceptor; <add> var responseErrorInterceptor = action.interceptor && action.interceptor.responseError || <add> undefined; <add> <add> forEach(action, function (value, key) { <add> if (key != 'params' && key != 'isArray' && key != 'interceptor') { <add> httpConfig[key] = copy(value); <add> } <add> }); <ide> <del> if (hasBody) httpConfig.data = data; <del> route.setUrlParams(httpConfig, <del> extend({}, extractParams(data, action.params || {}), params), <del> action.url); <add> if (hasBody) httpConfig.data = data; <add> route.setUrlParams(httpConfig, <add> extend({}, extractParams(data, action.params || {}), params), <add> action.url); <ide> <del> var promise = $http(httpConfig).then(function(response) { <del> var data = response.data, <add> var promise = $http(httpConfig).then(function (response) { <add> var data = response.data, <ide> promise = value.$promise; <ide> <del> if (data) { <del> // Need to convert action.isArray to boolean in case it is undefined <del> // jshint -W018 <del> if (angular.isArray(data) !== (!!action.isArray)) { <del> throw $resourceMinErr('badcfg', 'Error in resource configuration. Expected ' + <del> 'response to contain an {0} but got an {1}', <del> action.isArray?'array':'object', angular.isArray(data)?'array':'object'); <add> if (data) { <add> // Need to convert action.isArray to boolean in case it is undefined <add> // jshint -W018 <add> if (angular.isArray(data) !== (!!action.isArray)) { <add> throw $resourceMinErr('badcfg', <add> 'Error in resource configuration. Expected ' + <add> 'response to contain an {0} but got an {1}', <add> action.isArray ? 'array' : 'object', <add> angular.isArray(data) ? 'array' : 'object'); <add> } <add> // jshint +W018 <add> if (action.isArray) { <add> value.length = 0; <add> forEach(data, function (item) { <add> value.push(new Resource(item)); <add> }); <add> } else { <add> shallowClearAndCopy(data, value); <add> value.$promise = promise; <add> } <ide> } <del> // jshint +W018 <del> if (action.isArray) { <del> value.length = 0; <del> forEach(data, function(item) { <del> value.push(new Resource(item)); <del> }); <del> } else { <del> shallowClearAndCopy(data, value); <del> value.$promise = promise; <del> } <del> } <ide> <del> value.$resolved = true; <add> value.$resolved = true; <ide> <del> response.resource = value; <add> response.resource = value; <ide> <del> return response; <del> }, function(response) { <del> value.$resolved = true; <add> return response; <add> }, function (response) { <add> value.$resolved = true; <ide> <del> (error||noop)(response); <add> (error || noop)(response); <ide> <del> return $q.reject(response); <del> }); <add> return $q.reject(response); <add> }); <ide> <del> promise = promise.then( <del> function(response) { <add> promise = promise.then( <add> function (response) { <ide> var value = responseInterceptor(response); <del> (success||noop)(value, response.headers); <add> (success || noop)(value, response.headers); <ide> return value; <ide> }, <ide> responseErrorInterceptor); <ide> <del> if (!isInstanceCall) { <del> // we are creating instance / collection <del> // - set the initial promise <del> // - return the instance / collection <del> value.$promise = promise; <del> value.$resolved = false; <add> if (!isInstanceCall) { <add> // we are creating instance / collection <add> // - set the initial promise <add> // - return the instance / collection <add> value.$promise = promise; <add> value.$resolved = false; <ide> <del> return value; <del> } <add> return value; <add> } <ide> <del> // instance call <del> return promise; <del> }; <add> // instance call <add> return promise; <add> }; <ide> <ide> <del> Resource.prototype['$' + name] = function(params, success, error) { <del> if (isFunction(params)) { <del> error = success; success = params; params = {}; <del> } <del> var result = Resource[name].call(this, params, this, success, error); <del> return result.$promise || result; <del> }; <del> }); <add> Resource.prototype['$' + name] = function (params, success, error) { <add> if (isFunction(params)) { <add> error = success; success = params; params = {}; <add> } <add> var result = Resource[name].call(this, params, this, success, error); <add> return result.$promise || result; <add> }; <add> }); <ide> <del> Resource.bind = function(additionalParamDefaults){ <del> return resourceFactory(url, extend({}, paramDefaults, additionalParamDefaults), actions); <del> }; <add> Resource.bind = function (additionalParamDefaults) { <add> return resourceFactory(url, extend({}, paramDefaults, additionalParamDefaults), actions); <add> }; <ide> <del> return Resource; <del> } <add> return Resource; <add> } <ide> <del> return resourceFactory; <del> }]); <add> return resourceFactory; <add> }]; <add> }); <ide><path>test/ngResource/resourceSpec.js <ide> 'use strict'; <ide> <ide> describe("resource", function() { <del> var $resource, CreditCard, callback, $httpBackend; <add> var $resource, CreditCard, callback, $httpBackend, resourceProvider; <ide> <ide> beforeEach(module('ngResource')); <add> <add> beforeEach(module(function ($resourceProvider) { <add> resourceProvider = $resourceProvider; <add> })); <add> <ide> beforeEach(inject(function($injector) { <ide> $httpBackend = $injector.get('$httpBackend'); <ide> $resource = $injector.get('$resource'); <ide> describe("resource", function() { <ide> R.get({a: 'herp$'}); <ide> }); <ide> <del> <ide> it('should not encode @ in url params', function() { <ide> //encodeURIComponent is too agressive and doesn't follow http://www.ietf.org/rfc/rfc3986.txt <ide> //with regards to the character set (pchar) allowed in path segments <ide> describe("resource", function() { <ide> R.get({a: 'doh@fo o', ':bar': '$baz@1', '!do&h': 'g=a h'}); <ide> }); <ide> <del> <ide> it('should encode array params', function() { <ide> var R = $resource('/Path/:a'); <ide> $httpBackend.expect('GET', '/Path/doh&foo?bar=baz1&bar=baz2').respond('{}'); <ide> describe("resource", function() { <ide> R.get({a: 'null'}); <ide> }); <ide> <add> <add> it('should implicitly strip trailing slashes from URLs by default', function() { <add> var R = $resource('http://localhost:8080/Path/:a/'); <add> <add> $httpBackend.expect('GET', 'http://localhost:8080/Path/foo').respond(); <add> R.get({a: 'foo'}); <add> }); <add> <add> it('should support explicitly stripping trailing slashes from URLs', function() { <add> var R = $resource('http://localhost:8080/Path/:a/', {}, {}, {stripTrailingSlashes: true}); <add> <add> $httpBackend.expect('GET', 'http://localhost:8080/Path/foo').respond(); <add> R.get({a: 'foo'}); <add> }); <add> <add> it('should support explicitly keeping trailing slashes in URLs', function() { <add> var R = $resource('http://localhost:8080/Path/:a/', {}, {}, {stripTrailingSlashes: false}); <add> <add> $httpBackend.expect('GET', 'http://localhost:8080/Path/foo/').respond(); <add> R.get({a: 'foo'}); <add> }); <add> <add> it('should support provider-level configuration to strip trailing slashes in URLs', function() { <add> // Set the new behavior for all new resources created by overriding the <add> // provider configuration <add> resourceProvider.defaults.stripTrailingSlashes = false; <add> <add> var R = $resource('http://localhost:8080/Path/:a/'); <add> <add> $httpBackend.expect('GET', 'http://localhost:8080/Path/foo/').respond(); <add> R.get({a: 'foo'}); <add> }); <add> <add> it('should support overriding provider default trailing-slash stripping configuration', function() { <add> // Set the new behavior for all new resources created by overriding the <add> // provider configuration <add> resourceProvider.defaults.stripTrailingSlashes = false; <add> <add> // Specific instances of $resource can still override the provider's default <add> var R = $resource('http://localhost:8080/Path/:a/', {}, {}, {stripTrailingSlashes: true}); <add> <add> $httpBackend.expect('GET', 'http://localhost:8080/Path/foo').respond(); <add> R.get({a: 'foo'}); <add> }); <add> <add> <ide> it('should allow relative paths in resource url', function () { <ide> var R = $resource(':relativePath'); <ide> $httpBackend.expect('GET', 'data.json').respond('{}');
2
Ruby
Ruby
fix tests in railties
f3482a9fb17ba33e51d9ae096036f5f712078220
<ide><path>railties/test/generators/plugin_new_generator_test.rb <ide> def test_ensure_that_database_option_is_passed_to_app_generator <ide> end <ide> <ide> def test_generation_runs_bundle_install_with_full_and_mountable <del> result = run_generator [destination_root, "--mountable", "--full"] <add> result = run_generator [destination_root, "--mountable", "--full", "--dev"] <ide> assert_file "#{destination_root}/Gemfile.lock" do |contents| <ide> assert_match(/bukkits/, contents) <ide> end
1
Javascript
Javascript
move function creation out of the loop
fb174290c7ed5b2297a5fb53c404cc390478d903
<ide><path>pdf.js <ide> var PartialEvaluator = (function partialEvaluator() { <ide> var patterns = xref.fetchIfRef(resources.get('Pattern')) || new Dict(); <ide> var parser = new Parser(new Lexer(stream), false); <ide> var args = [], argsArray = [], fnArray = [], obj; <add> var getObjBt = function getObjBt() { <add> parser = this.oldParser; <add> return { name: 'BT' }; <add> }; <ide> <ide> while (!isEOF(obj = parser.getObj())) { <ide> if (isCmd(obj)) { <ide> var PartialEvaluator = (function partialEvaluator() { <ide> fn = OP_MAP[cmd.substr(0, cmd.length - 2)]; <ide> // feeding 'BT' on next interation <ide> parser = { <del> getObj: function() { <del> parser = this.oldParser; <del> return { name: 'BT' }; <del> }, <add> getObj: getObjBt, <ide> oldParser: parser <ide> }; <ide> }
1
Java
Java
delete unused imports
7b13311f0303ad7fb564217f2e1c539ced86f1dd
<ide><path>spring-context/src/test/java/org/springframework/beans/factory/support/QualifierAnnotationAutowireContextTests.java <ide> import java.lang.annotation.RetentionPolicy; <ide> import java.lang.annotation.Target; <ide> <del>import org.junit.Ignore; <ide> import org.junit.Test; <ide> <ide> import org.springframework.aop.scope.ScopedProxyUtils; <ide> import org.springframework.beans.factory.config.ConstructorArgumentValues; <ide> import org.springframework.context.annotation.AnnotationConfigUtils; <ide> import org.springframework.context.support.GenericApplicationContext; <del>import org.springframework.core.annotation.AliasFor; <ide> <ide> import static org.junit.Assert.*; <ide> <ide> public class QualifierAnnotationAutowireContextTests { <ide> <ide> private static final String MARK = "mark"; <ide> <del> private static final String SAM = "sam"; <del> <ide> <ide> @Test <ide> public void autowiredFieldWithSingleNonQualifiedCandidate() { <ide><path>spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests.java <ide> import java.util.concurrent.atomic.AtomicInteger; <ide> <ide> import org.apache.commons.logging.LogFactory; <del>import org.junit.Ignore; <ide> import org.junit.Test; <ide> import org.xml.sax.InputSource; <ide> <ide><path>spring-context/src/test/java/org/springframework/cache/config/EnableCachingIntegrationTests.java <add>/* <add> * Copyright 2002-2016 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> <ide> package org.springframework.cache.config; <ide> <ide> import java.util.concurrent.atomic.AtomicLong; <ide> import org.springframework.cache.annotation.Cacheable; <ide> import org.springframework.cache.annotation.CachingConfigurerSupport; <ide> import org.springframework.cache.annotation.EnableCaching; <del>import org.springframework.context.ApplicationContext; <ide> import org.springframework.context.ConfigurableApplicationContext; <ide> import org.springframework.context.annotation.AnnotationConfigApplicationContext; <ide> import org.springframework.context.annotation.Bean; <ide><path>spring-context/src/test/java/org/springframework/context/annotation/ComponentScanAnnotationIntegrationTests.java <ide> import example.scannable_implicitbasepackage.ConfigurableComponent; <ide> import example.scannable_scoped.CustomScopeAnnotationBean; <ide> import example.scannable_scoped.MyScope; <add> <ide> import org.junit.Test; <ide> <ide> import org.springframework.aop.support.AopUtils; <ide> import org.springframework.beans.factory.BeanFactoryAware; <ide> import org.springframework.beans.factory.annotation.CustomAutowireConfigurer; <ide> import org.springframework.beans.factory.config.BeanDefinition; <del>import org.springframework.beans.factory.config.ConfigurableBeanFactory; <ide> import org.springframework.beans.factory.support.BeanDefinitionRegistry; <ide> import org.springframework.beans.factory.support.DefaultListableBeanFactory; <ide> import org.springframework.context.EnvironmentAware; <ide><path>spring-context/src/test/java/org/springframework/validation/beanvalidation/SpringValidatorAdapterTests.java <ide> <ide> package org.springframework.validation.beanvalidation; <ide> <add>import java.lang.annotation.Documented; <add>import java.lang.annotation.Inherited; <add>import java.lang.annotation.Repeatable; <add>import java.lang.annotation.Retention; <add>import java.lang.annotation.Target; <add>import java.util.Locale; <add>import javax.validation.Constraint; <add>import javax.validation.ConstraintValidator; <add>import javax.validation.ConstraintValidatorContext; <add>import javax.validation.Payload; <add>import javax.validation.Validation; <add>import javax.validation.constraints.Size; <add> <ide> import org.junit.Before; <del>import org.junit.BeforeClass; <ide> import org.junit.Test; <add> <ide> import org.springframework.beans.BeanWrapper; <ide> import org.springframework.beans.BeanWrapperImpl; <ide> import org.springframework.context.support.StaticMessageSource; <ide> import org.springframework.util.ObjectUtils; <ide> import org.springframework.validation.BeanPropertyBindingResult; <ide> <del>import javax.validation.*; <del>import javax.validation.constraints.Size; <del>import java.lang.annotation.*; <del>import java.util.Locale; <del> <del>import static java.lang.annotation.ElementType.ANNOTATION_TYPE; <del>import static java.lang.annotation.ElementType.TYPE; <del>import static java.lang.annotation.RetentionPolicy.RUNTIME; <del>import static org.hamcrest.core.Is.is; <del>import static org.junit.Assert.assertThat; <add>import static java.lang.annotation.ElementType.*; <add>import static java.lang.annotation.RetentionPolicy.*; <add>import static org.hamcrest.core.Is.*; <add>import static org.junit.Assert.*; <ide> <ide> /** <ide> * @author Kazuki Shimizu <ide> * @since 4.3 <ide> */ <ide> public class SpringValidatorAdapterTests { <ide> <del> private SpringValidatorAdapter validatorAdapter; <add> private final SpringValidatorAdapter validatorAdapter = new SpringValidatorAdapter( <add> Validation.buildDefaultValidatorFactory().getValidator()); <ide> <del> private StaticMessageSource messageSource; <add> private final StaticMessageSource messageSource = new StaticMessageSource(); <ide> <ide> <ide> @Before <ide> public void setupSpringValidatorAdapter() { <del> validatorAdapter = new SpringValidatorAdapter(Validation.buildDefaultValidatorFactory().getValidator()); <del> <del> messageSource = new StaticMessageSource(); <ide> messageSource.addMessage("Size", Locale.ENGLISH, "Size of {0} is must be between {2} and {1}"); <ide> messageSource.addMessage("Same", Locale.ENGLISH, "{2} must be same value with {1}"); <ide> messageSource.addMessage("password", Locale.ENGLISH, "Password"); <ide> public void setConfirmEmail(String confirmEmail) { <ide> @Target({TYPE, ANNOTATION_TYPE}) <ide> @Retention(RUNTIME) <ide> @Repeatable(SameGroup.class) <del> public @interface Same { <add> @interface Same { <ide> <ide> String message() default "{org.springframework.validation.beanvalidation.Same.message}"; <ide> <ide> public void setConfirmEmail(String confirmEmail) { <ide> @Inherited <ide> @Retention(RUNTIME) <ide> @Target({TYPE, ANNOTATION_TYPE}) <del> public @interface SameGroup { <add> @interface SameGroup { <ide> <ide> Same[] value(); <ide> } <ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/config/MessageBrokerConfigurationTests.java <ide> import org.springframework.messaging.simp.user.MultiServerUserRegistry; <ide> import org.springframework.messaging.simp.user.SimpUserRegistry; <ide> import org.springframework.messaging.simp.user.UserDestinationMessageHandler; <del>import org.springframework.messaging.simp.user.UserDestinationResolver; <ide> import org.springframework.messaging.simp.user.UserRegistryMessageHandler; <ide> import org.springframework.messaging.support.AbstractSubscribableChannel; <ide> import org.springframework.messaging.support.ChannelInterceptor; <ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/user/DefaultUserDestinationResolverTests.java <ide> import org.springframework.messaging.simp.TestPrincipal; <ide> import org.springframework.messaging.support.MessageBuilder; <ide> import org.springframework.util.AntPathMatcher; <del>import org.springframework.util.PathMatcher; <ide> import org.springframework.util.StringUtils; <ide> <ide> /** <ide><path>spring-web/src/main/java/org/springframework/http/converter/ResourceHttpMessageConverter.java <ide> import java.io.FileNotFoundException; <ide> import java.io.IOException; <ide> import java.io.InputStream; <del> <ide> import javax.activation.FileTypeMap; <ide> import javax.activation.MimetypesFileTypeMap; <ide> <ide> import org.springframework.core.io.ByteArrayResource; <ide> import org.springframework.core.io.ClassPathResource; <ide> import org.springframework.core.io.InputStreamResource; <ide> import org.springframework.core.io.Resource; <del>import org.springframework.http.HttpHeaders; <ide> import org.springframework.http.HttpInputMessage; <ide> import org.springframework.http.HttpOutputMessage; <ide> import org.springframework.http.MediaType; <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/RequestMappingInfo.java <ide> /* <del> * Copyright 2002-2015 the original author or authors. <add> * Copyright 2002-2016 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.util.List; <ide> import javax.servlet.http.HttpServletRequest; <ide> <del>import org.springframework.http.HttpHeaders; <ide> import org.springframework.util.PathMatcher; <ide> import org.springframework.util.StringUtils; <ide> import org.springframework.web.accept.ContentNegotiationManager; <ide> import org.springframework.web.bind.annotation.RequestMethod; <del>import org.springframework.web.cors.CorsUtils; <ide> import org.springframework.web.servlet.mvc.condition.ConsumesRequestCondition; <ide> import org.springframework.web.servlet.mvc.condition.HeadersRequestCondition; <ide> import org.springframework.web.servlet.mvc.condition.ParamsRequestCondition; <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/view/script/ScriptTemplateView.java <ide> /* <del> * Copyright 2002-2015 the original author or authors. <add> * Copyright 2002-2016 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.IOException; <ide> import java.io.InputStreamReader; <ide> import java.nio.charset.Charset; <del>import java.util.ArrayList; <ide> import java.util.Arrays; <ide> import java.util.HashMap; <del>import java.util.List; <ide> import java.util.Map; <ide> import javax.script.Invocable; <ide> import javax.script.ScriptEngine; <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/config/MvcNamespaceTests.java <ide> import org.springframework.web.util.UrlPathHelper; <ide> <ide> import static org.hamcrest.CoreMatchers.*; <del>import static org.hamcrest.Matchers.contains; <ide> import static org.hamcrest.Matchers.containsInAnyOrder; <ide> import static org.junit.Assert.*; <ide> <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupportExtensionTests.java <ide> import java.util.Map; <ide> <ide> import com.fasterxml.jackson.databind.ObjectMapper; <add> <ide> import org.junit.Before; <ide> import org.junit.Test; <ide> <ide> import org.springframework.web.method.support.HandlerMethodReturnValueHandler; <ide> import org.springframework.web.servlet.HandlerExceptionResolver; <ide> import org.springframework.web.servlet.HandlerExecutionChain; <del>import org.springframework.web.servlet.HandlerMapping; <ide> import org.springframework.web.servlet.View; <ide> import org.springframework.web.servlet.ViewResolver; <ide> import org.springframework.web.servlet.handler.AbstractHandlerMapping; <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestPartMethodArgumentResolverTests.java <ide> import javax.validation.Valid; <ide> import javax.validation.constraints.NotNull; <ide> <del>import org.hamcrest.Matchers; <ide> import org.junit.Before; <ide> import org.junit.Test; <ide>
13
PHP
PHP
apply fixes from styleci
e09149aaeb5d58b1fabde3a932578479f7ba86fe
<ide><path>tests/Integration/Foundation/Testing/Concerns/InteractsWithAuthenticationTest.php <ide> use Illuminate\Support\Facades\Auth; <ide> use Illuminate\Support\Facades\Route; <ide> use Illuminate\Support\Facades\Schema; <del>use Illuminate\Auth\EloquentUserProvider; <ide> use Illuminate\Foundation\Auth\User as Authenticatable; <ide> <ide> class InteractsWithAuthenticationTest extends TestCase
1
Javascript
Javascript
fix flaky test-http2-server-rst-stream.js
3a977fc8c0d13f796c65e05e31bb548217fbc37b
<ide><path>test/parallel/test-http2-server-rst-stream.js <ide> if (!common.hasCrypto) <ide> common.skip('missing crypto'); <ide> const assert = require('assert'); <ide> const http2 = require('http2'); <add>const Countdown = require('../common/countdown'); <ide> <ide> const { <del> HTTP2_HEADER_METHOD, <del> HTTP2_HEADER_PATH, <del> HTTP2_METHOD_POST, <ide> NGHTTP2_CANCEL, <ide> NGHTTP2_NO_ERROR, <ide> NGHTTP2_PROTOCOL_ERROR, <ide> NGHTTP2_REFUSED_STREAM, <ide> NGHTTP2_INTERNAL_ERROR <ide> } = http2.constants; <ide> <del>const errCheck = common.expectsError({ code: 'ERR_HTTP2_STREAM_ERROR' }, 6); <add>const tests = [ <add> ['rstStream', NGHTTP2_NO_ERROR, false], <add> ['rstWithNoError', NGHTTP2_NO_ERROR, false], <add> ['rstWithProtocolError', NGHTTP2_PROTOCOL_ERROR, true], <add> ['rstWithCancel', NGHTTP2_CANCEL, false], <add> ['rstWithRefuse', NGHTTP2_REFUSED_STREAM, true], <add> ['rstWithInternalError', NGHTTP2_INTERNAL_ERROR, true] <add>]; <add> <add>const server = http2.createServer(); <add>server.on('stream', (stream, headers) => { <add> const method = headers['rstmethod']; <add> stream[method](); <add>}); <add> <add>server.listen(0, common.mustCall(() => { <add> const client = http2.connect(`http://localhost:${server.address().port}`); <add> <add> const countdown = new Countdown(tests.length, common.mustCall(() => { <add> client.destroy(); <add> server.close(); <add> })); <ide> <del>function checkRstCode(rstMethod, expectRstCode) { <del> const server = http2.createServer(); <del> server.on('stream', (stream, headers, flags) => { <del> stream.respond({ <del> 'content-type': 'text/html', <del> ':status': 200 <add> tests.forEach((test) => { <add> const req = client.request({ <add> ':method': 'POST', <add> rstmethod: test[0] <ide> }); <del> stream.write('test'); <del> if (rstMethod === 'rstStream') <del> stream[rstMethod](expectRstCode); <del> else <del> stream[rstMethod](); <del> <del> if (expectRstCode !== NGHTTP2_NO_ERROR && <del> expectRstCode !== NGHTTP2_CANCEL) { <del> stream.on('error', common.mustCall(errCheck)); <del> } else { <del> stream.on('error', common.mustNotCall()); <del> } <del> }); <del> <del> server.listen(0, common.mustCall(() => { <del> const port = server.address().port; <del> const client = http2.connect(`http://localhost:${port}`); <del> <del> const headers = { <del> [HTTP2_HEADER_PATH]: '/', <del> [HTTP2_HEADER_METHOD]: HTTP2_METHOD_POST <del> }; <del> const req = client.request(headers); <del> <del> req.setEncoding('utf8'); <del> req.on('streamClosed', common.mustCall((actualRstCode) => { <del> assert.strictEqual( <del> expectRstCode, actualRstCode, `${rstMethod} is not match rstCode`); <del> server.close(); <del> client.destroy(); <add> req.on('streamClosed', common.mustCall((code) => { <add> assert.strictEqual(code, test[1]); <add> countdown.dec(); <ide> })); <del> req.on('data', common.mustCall()); <ide> req.on('aborted', common.mustCall()); <del> req.on('end', common.mustCall()); <del> <del> if (expectRstCode !== NGHTTP2_NO_ERROR && <del> expectRstCode !== NGHTTP2_CANCEL) { <del> req.on('error', common.mustCall(errCheck)); <del> } else { <add> if (test[2]) <add> req.on('error', common.mustCall()); <add> else <ide> req.on('error', common.mustNotCall()); <del> } <del> <del> })); <del>} <del> <del>checkRstCode('rstStream', NGHTTP2_NO_ERROR); <del>checkRstCode('rstWithNoError', NGHTTP2_NO_ERROR); <del>checkRstCode('rstWithProtocolError', NGHTTP2_PROTOCOL_ERROR); <del>checkRstCode('rstWithCancel', NGHTTP2_CANCEL); <del>checkRstCode('rstWithRefuse', NGHTTP2_REFUSED_STREAM); <del>checkRstCode('rstWithInternalError', NGHTTP2_INTERNAL_ERROR); <add> }); <add>}));
1
Javascript
Javascript
improve the strict equal messages
be26c761146db8357653df345e505a624b2153da
<ide><path>lib/internal/assert.js <ide> let white = ''; <ide> const kReadableOperator = { <ide> deepStrictEqual: 'Expected inputs to be strictly deep-equal:', <ide> strictEqual: 'Expected inputs to be strictly equal:', <add> strictEqualObject: 'Expected "actual" to be reference-equal to "expected":', <ide> deepEqual: 'Expected inputs to be loosely deep-equal:', <ide> equal: 'Expected inputs to be loosely equal:', <ide> notDeepStrictEqual: 'Expected "actual" not to be strictly deep-equal to:', <ide> notStrictEqual: 'Expected "actual" to be strictly unequal to:', <add> // eslint-disable-next-line max-len <add> notStrictEqualObject: 'Expected "actual" not to be reference-equal to "expected":', <ide> notDeepEqual: 'Expected "actual" not to be loosely deep-equal to:', <ide> notEqual: 'Expected "actual" to be loosely unequal to:', <ide> notIdentical: 'Inputs identical but not reference equal:', <ide> function createErrDiff(actual, expected, operator) { <ide> const actualInspected = inspectValue(actual); <ide> const actualLines = actualInspected.split('\n'); <ide> const expectedLines = inspectValue(expected).split('\n'); <del> const msg = kReadableOperator[operator] + <del> `\n${green}+ actual${white} ${red}- expected${white}`; <del> const skippedMsg = ` ${blue}...${white} Lines skipped`; <ide> <ide> let i = 0; <ide> let indicator = ''; <ide> <add> // In case both inputs are objects explicitly mark them as not reference equal <add> // for the `strictEqual` operator. <add> if (operator === 'strictEqual' && <add> typeof actual === 'object' && <add> typeof expected === 'object' && <add> actual !== null && <add> expected !== null) { <add> operator = 'strictEqualObject'; <add> } <add> <ide> // If "actual" and "expected" fit on a single line and they are not strictly <ide> // equal, check further special handling. <ide> if (actualLines.length === 1 && expectedLines.length === 1 && <ide> function createErrDiff(actual, expected, operator) { <ide> return `${kReadableOperator[operator]}\n\n` + <ide> `${actualLines[0]} !== ${expectedLines[0]}\n`; <ide> } <del> } else { <add> } else if (operator !== 'strictEqualObject') { <ide> // If the stderr is a tty and the input length is lower than the current <ide> // columns per line, add a mismatch indicator below the output. If it is <ide> // not a tty, use a default value of 80 characters. <ide> function createErrDiff(actual, expected, operator) { <ide> } <ide> <ide> let printedLines = 0; <add> const msg = kReadableOperator[operator] + <add> `\n${green}+ actual${white} ${red}- expected${white}`; <add> const skippedMsg = ` ${blue}...${white} Lines skipped`; <add> <ide> for (i = 0; i < maxLines; i++) { <ide> // Only extra expected lines exist <ide> const cur = i - lastPos; <ide> class AssertionError extends Error { <ide> operator === 'notStrictEqual') { <ide> // In case the objects are equal but the operator requires unequal, show <ide> // the first object and say A equals B <add> let base = kReadableOperator[operator]; <ide> const res = inspectValue(actual).split('\n'); <del> const base = kReadableOperator[operator]; <add> <add> // In case "actual" is an object, it should not be reference equal. <add> if (operator === 'notStrictEqual' && <add> typeof actual === 'object' && <add> actual !== null) { <add> base = kReadableOperator.notStrictEqualObject; <add> } <ide> <ide> // Only remove lines in case it makes sense to collapse those. <ide> // TODO: Accept env to always show the full error. <ide><path>test/parallel/test-assert.js <ide> assert.throws( <ide> { <ide> code: 'ERR_ASSERTION', <ide> name: 'AssertionError [ERR_ASSERTION]', <del> message: strictEqualMessageStart + <add> message: 'Expected "actual" to be reference-equal to "expected":\n' + <ide> '+ actual - expected\n\n' + <del> '+ [Error: foo]\n- [Error: foobar]\n ^' <add> '+ [Error: foo]\n- [Error: foobar]' <ide> } <ide> ); <ide> <ide> assert.throws( <ide> assert.throws( <ide> () => assert.strictEqual(args, { 0: 'a' }), <ide> { <del> message: `${strictEqualMessageStart}+ actual - expected\n\n` + <add> message: 'Expected "actual" to be reference-equal to "expected":\n' + <add> '+ actual - expected\n\n' + <ide> "+ [Arguments] {\n- {\n '0': 'a'\n }" <ide> } <ide> ); <ide> assert.throws( <ide> } <ide> ); <ide> } <add> <add>// Indicate where the strings diverge. <add>assert.throws( <add> () => assert.strictEqual('test test', 'test foobar'), <add> { <add> code: 'ERR_ASSERTION', <add> name: 'AssertionError [ERR_ASSERTION]', <add> message: strictEqualMessageStart + <add> '+ actual - expected\n\n' + <add> "+ 'test test'\n" + <add> "- 'test foobar'\n" + <add> ' ^' <add> } <add>); <add> <add>// Check for reference equal objects in `notStrictEqual()` <add>assert.throws( <add> () => { <add> const obj = {}; <add> assert.notStrictEqual(obj, obj); <add> }, <add> { <add> code: 'ERR_ASSERTION', <add> name: 'AssertionError [ERR_ASSERTION]', <add> message: 'Expected "actual" not to be reference-equal to "expected": {}' <add> } <add>); <add> <add>assert.throws( <add> () => { <add> const obj = { a: true }; <add> assert.notStrictEqual(obj, obj); <add> }, <add> { <add> code: 'ERR_ASSERTION', <add> name: 'AssertionError [ERR_ASSERTION]', <add> message: 'Expected "actual" not to be reference-equal to "expected":\n\n' + <add> '{\n a: true\n}\n' <add> } <add>);
2
Text
Text
create onboarding guide for fcc moderators
d83f0b539f94e1df6b4f3d20ad12dde395f2386b
<ide><path>docs/moderator-onboarding-guide.md <add># The Official freeCodeCamp Moderator Onboarding Guide <add> <add>This guide will help new moderators get up and running with the processes and procedures followed by experienced moderators on the freeCodeCamp community forum and other official communities that we foster. <add> <add>> [!NOTE] <add>> If you haven't read [The Moderator Handbook](https://contribute.freecodecamp.org/#/moderator-handbook) yet, you should start there first. <add> <add>## The Forum <add> <add>### First Steps <add> <add>The first thing you may notice after being given moderator status on the forum is that your interface will look somewhat different, with new admin tools to explore and access to the Mod-Team subforum. <add> <add>Some of the new tools will appear inside a new menu item that looks like a wrench. Some will appear as new tabs or buttons, or even new enabled options within the forum menus. <add> <add>To get familiar with the new tools and powers, you can combine one or more of the following methods during your first week with this elevated role: <add> <add>> [!TIP] <add>> The first two are the most important. <add> <add>### Become Familiar with the Discourse Admin Tools <add> <add>The freeCodeCamp forum is actually a Discourse forum and follows many of the same guidelines of other forums built on Discourse. To begin to get familiar with Discourse and the moderation role, start by reading Discourse's [new user guide](https://meta.discourse.org/t/discourse-new-user-guide/96331) and Discourse's [new moderator guide](https://meta.discourse.org/t/discourse-moderation-guide/63116). <add> <add>### Shadow a Mod <add> <add>All moderator actions can be followed by reviewing the [action logs](https://forum.freecodecamp.org/admin/logs/staff_action_logs). The actions taken by automated tools like `akistmet` or `system` can mostly be ignored until they result in a post that needs to be reviewed. Posts to be reviewed will show up in the [Review](https://forum.freecodecamp.org/review) area of the forum. <add> <add>For the first week or so you will want to pay attention to what is getting flagged and what is being reviewed, and compare that to the actions being taken upon the flagged posts. You may see the system account flag a post because the user created it too quickly. In many cases, the moderators will unflag the post by clicking on the "Approve Post" button or mark it as "Not Spam" (depending on the flag type). <add> <add>Commonly, spam flags can also be raised by members or moderators. Common duplicitous behaviour would involve opening an account, making a post that seems harmless, then editing that post later on to add a link to an external site for the purpose of advertising it. In this case, usually the member account is fairly new and has only made this one post thus far, which indicates that the account was opened for the sole purpose of spamming the community. The decision should be made to delete the account after the first offence in this case. The same applies for accounts whose first post is deemed to be spam. <add> <add>You may notice moderators performing a procedure called 'split topic'. This may be a case where a moderator has split a post that was made erroneously on an existing topic into a new topic, or a moderator merged duplicate topics that a single user has created for the same question. Watching this procedure will highlight different actions and their causes. <add> <add>Another useful feature that becomes enabled for all moderators is the ability to post a "Canned Reply" which is a pre-written response that was worked out with the mod team in order to quickly respond to some well-known and repetitive scenarios. These include: <add> <add>- Welcoming a new forum member who has posted code without a question -> "Welcome - remind question" <add>- Reminding members not to post code solutions but to provide hints and tips instead -> "Solutions Instead of Help" <add>- Responding to a situation where someone's code works for you but not for them -> "Browser Issues" <add>- Encouraging members to open GitHub issues when a possible bug is found -> "Bug Report" <add> <add>There are more, which you can read through to become familiar with their respective uses. You can also find discussion around the templates in the mod-team subforum, and you are welcome to ask questions if you aren't sure how a template should be used. <add> <add>### Read Mod-Team Subforum Posts <add> <add>The Mod-Team subforum contains a number of posts from past and current moderators discussing the different requirements and/or challenges of moderating the forum. <add> <add>Reading back through these posts can help to uncover some of the underlying goals and processes that concern forum moderators. Some of the threads may also shed some light on handling of spam and inappropriate content on the forum. <add> <add>## Where to Ask for Help <add> <add>To get help dealing with a situation that you are either uncomfortable with or unsure of how to handle, discuss with your fellow moderators on either the [Mod-Team Subforum](https://forum.freecodecamp.org/c/mod-team/4) or the [#mod-chat](https://discord.com/channels/692816967895220344/693157007418720277) on Discord.
1
Text
Text
add bundlejs site
bbbbe20c99ee85ca85bea62c40a7afac91b5e22a
<ide><path>docs/going-to-production.md <ide> To reduce the amount of JavaScript sent to the browser, you can use the followin <ide> - [Package Phobia](https://packagephobia.com/) – Find the cost of adding a new dev dependency to your project. <ide> - [Bundle Phobia](https://bundlephobia.com/) - Analyze how much a dependency can increase bundle sizes. <ide> - [Webpack Bundle Analyzer](https://github.com/vercel/next.js/tree/canary/packages/next-bundle-analyzer) – Visualize size of webpack output files with an interactive, zoomable treemap. <add>- [bundlejs](https://bundlejs.com/) - An online tool to quickly bundle & minify your projects, while viewing the compressed gzip/brotli bundle size, all running locally on your browser. <ide> <ide> Each file inside your `pages/` directory will automatically be code split into its own JavaScript bundle during `next build`. You can also use [Dynamic Imports](/docs/advanced-features/dynamic-import.md) to lazy-load components and libraries. For example, you might want to defer loading your modal code until a user clicks the open button. <ide>
1
Text
Text
remove extraneous word
a36b6c4bd30d378f3b734631e00c0b3bc8b4f1d2
<ide><path>CONTRIBUTING.md <ide> Explain the problem and include additional details to help maintainers reproduce <ide> * **Include screenshots and animated GIFs** which show you following the described steps and clearly demonstrate the problem. If you use the keyboard while following the steps, **record the GIF with the [Keybinding Resolver](https://github.com/atom/keybinding-resolver) shown**. You can use [this tool](http://www.cockos.com/licecap/) to record GIFs on macOS and Windows, and [this tool](https://github.com/colinkeenan/silentcast) or [this tool](https://github.com/GNOME/byzanz) on Linux. <ide> * **If you're reporting that Atom crashed**, include a crash report with a stack trace from the operating system. On macOS, the crash report will be available in `Console.app` under "Diagnostic and usage information" > "User diagnostic reports". Include the crash report in the issue in a [code block](https://help.github.com/articles/markdown-basics/#multiple-lines), a [file attachment](https://help.github.com/articles/file-attachments-on-issues-and-pull-requests/), or put it in a [gist](https://gist.github.com/) and provide link to that gist. <ide> * **If the problem is related to performance**, include a [CPU profile capture and a screenshot](http://flight-manual.atom.io/hacking-atom/sections/debugging/#diagnose-performance-problems-with-the-dev-tools-cpu-profiler) with your report. <del>* **If the Chrome's developer tools pane is shown without you triggering it**, that normally means that an exception was thrown. The Console tab will include an entry for the exception. Expand the exception so that the stack trace is visible, and provide the full exception and stack trace in a [code blocks](https://help.github.com/articles/markdown-basics/#multiple-lines) and as a screenshot. <add>* **If Chrome's developer tools pane is shown without you triggering it**, that normally means that an exception was thrown. The Console tab will include an entry for the exception. Expand the exception so that the stack trace is visible, and provide the full exception and stack trace in a [code blocks](https://help.github.com/articles/markdown-basics/#multiple-lines) and as a screenshot. <ide> * **If the problem wasn't triggered by a specific action**, describe what you were doing before the problem happened and share more information using the guidelines below. <ide> <ide> Provide more context by answering these questions:
1
Ruby
Ruby
remove zsh fpath logic
1f8fd2a9ef72a860e5775bcd64b4600d41e3b52e
<ide><path>Library/Homebrew/caveats.rb <ide> def function_completion_caveats(shell) <ide> #{root_dir}/etc/bash_completion.d <ide> EOS <ide> when :zsh <del> site_functions = root_dir/"share/zsh/site-functions" <del> zsh_caveats = +<<~EOS <add> <<~EOS <ide> zsh #{installed.join(" and ")} have been installed to: <del> #{site_functions} <add> #{root_dir}/share/zsh/site-functions <ide> EOS <del> zsh = which("zsh") || which("zsh", ENV["HOMEBREW_PATH"]) <del> if zsh.present? && Utils.popen_read("'#{zsh}' -ic 'echo $FPATH'").exclude?(site_functions.to_s) <del> zsh_caveats << <<~EOS <del> <del> #{site_functions} is not in your zsh FPATH! <del> Add it by following these steps: <del> #{Formatter.url("https://docs.brew.sh/Shell-Completion#configuring-completions-in-zsh")} <del> EOS <del> end <del> zsh_caveats.freeze <ide> when :fish <ide> fish_caveats = +"fish #{installed.join(" and ")} have been installed to:" <ide> fish_caveats << "\n #{root_dir}/share/fish/vendor_completions.d" if completion_installed
1
Javascript
Javascript
remove dead code
5f386095aa9ba6ee3b193e0d7ddc74d7ff27a5f9
<ide><path>packages/ember-metal/lib/meta.js <ide> if (HAS_NATIVE_WEAKMAP) { <ide> metaStore.set(obj, meta); <ide> }; <ide> <del> peekMeta = function WeakMap_peekMeta(obj) { <del> if (DEBUG) { <del> counters.peekCalls++ <del> } <del> <del> return metaStore.get(obj); <del> }; <del> <ide> peekMeta = function WeakMap_peekParentMeta(obj) { <ide> let pointer = obj; <ide> let meta;
1
Text
Text
fix repeatvector in captioning example
ca758bef0b265f85eac9e3f1a2b6a54ca6007863
<ide><path>README.md <ide> model.add(Dense(128*4*4, 256)) <ide> model.add(Activation('relu')) <ide> model.add(Dropout(0.5)) <ide> <del>model.add(Repeat(max_caption_len)) <add>model.add(RepeatVector(max_caption_len)) <ide> # the GRU below returns sequences of max_caption_len vectors of size 256 (our word embedding size) <ide> model.add(GRU(256, 256, return_sequences=True)) <ide> <ide><path>docs/sources/examples.md <ide> model.add(Dense(128*4*4, 256)) <ide> model.add(Activation('relu')) <ide> model.add(Dropout(0.5)) <ide> <del>model.add(Repeat(max_caption_len)) <add>model.add(RepeatVector(max_caption_len)) <ide> # the GRU below returns sequences of max_caption_len vectors of size 256 (our word embedding size) <ide> model.add(GRU(256, 256, return_sequences=True)) <ide>
2
Text
Text
react devtools 4.23.0 -> 4.24.0
82762bea55d56afda2dcd00a565941be3798e0ac
<ide><path>packages/react-devtools/CHANGELOG.md <ide> --- <ide> <ide> ### 4.24.0 <del>March 2, 2022 <add>March 10, 2022 <ide> <ide> #### Feature <ide> * Show DevTools backend and frontend versions in UI ([bvaughn](https://github.com/bvaughn) in [#23399](https://github.com/facebook/react/pull/23399)) <ide> * Timeline profiler refactored to support reading basic profiling data directly from React ([bvaughn](https://github.com/bvaughn) in [#22529](https://github.com/facebook/react/issues/22529)) <ide> <ide> #### Bugfix <add>* Better handle undefined `Error` stacks in DevTools error boundary ([bvaughn](https://github.com/bvaughn) in [#24065](https://github.com/facebook/react/pull/24065)) <add>* Fixed edge case bug in Profiler commit filtering ([bvaughn](https://github.com/bvaughn) in [#24031](https://github.com/facebook/react/pull/24031)) <ide> * Gracefully handle empty "xstyle" prop values ([lunaruan](https://github.com/lunaruan) in [#23279](https://github.com/facebook/react/pull/23279) and [bvaughn](https://github.com/bvaughn) in [#23190](https://github.com/facebook/react/pull/23190)) <ide> * Add `<TracingMarker>` component boilerplate ([lunaruan](https://github.com/lunaruan) in [#23275](https://github.com/facebook/react/pull/23275)) <ide>
1
Python
Python
add corrections. use region concept from s3 driver
84af616f89b11c6237587083ff962010e3b42518
<ide><path>libcloud/storage/drivers/scaleway.py <ide> <ide> from libcloud.common.types import LibcloudError <ide> from libcloud.common.aws import SignedAWSConnection <del>from libcloud.storage.drivers.s3 import BaseS3Connection <add>from libcloud.storage.drivers.s3 import BaseS3Connection, S3SignatureV4Connection <ide> from libcloud.storage.drivers.s3 import BaseS3StorageDriver <ide> from libcloud.storage.drivers.s3 import API_VERSION <ide> <ide> __all__ = [ <ide> "ScalewayStorageDriver" <ide> ] <ide> <add>SCW_FR_PAR_STANDARD_HOST = "s3.fr-par.scw.cloud" <add>SCW_NL_AMS_HOST = "s3.nl-ams.scw.cloud" <add>SCW_PL_WAR_HOST = "s3.pl-waw.scw.cloud" <ide> <del>class ScalewayConnectionAWS4(SignedAWSConnection, BaseS3Connection): <del> service_name = 's3' <del> version = API_VERSION <del> <del> def __init__(self, user_id, key, secure=True, host=None, port=None, <del> url=None, timeout=None, proxy_url=None, token=None, <del> retry_delay=None, backoff=None, **kwargs): <del> <del> super(ScalewayConnectionAWS4, self).__init__(user_id, key, <del> secure, host, <del> port, url, <del> timeout, <del> proxy_url, token, <del> retry_delay, <del> backoff, <del> 4) # force aws4 <add># Maps SCW region name to connection hostname <add>REGION_TO_HOST_MAP = { <add> "fr-par": SCW_FR_PAR_STANDARD_HOST, <add> "nl-ams": SCW_NL_AMS_HOST, <add> "pl-waw": SCW_PL_WAR_HOST, <add>} <ide> <ide> <ide> class ScalewayStorageDriver(BaseS3StorageDriver): <ide> name = 'Scaleway Storage Driver' <ide> website = 'https://www.scaleway.com/en/object-storage/' <del> connectionCls = ScalewayConnectionAWS4 <del> region_name = "fr-par" <del> <del> def __init__(self, key, secret=None, secure=True, host=None, port=None, url=None): <del> if host is None: <del> raise LibcloudError('host argument is required', driver=self) <del> <del> self.connectionCls.host = host <del> <del> super(ScalewayStorageDriver, self).__init__(key=key, <del> secret=secret, <del> secure=secure, <del> host=host, <del> port=port, <del> url=url) <del> <del> <del>class ScalewayFRParConnection(ScalewayConnectionAWS4): <del> host = "s3.fr-par.scw.cloud" <del> <del> <del>class ScalewayFRParStorageDriver(ScalewayStorageDriver): <del> name = 'Scaleway Storage Driver (fr-par)' <del> connectionCls = ScalewayFRParConnection <add> connectionCls = S3SignatureV4Connection <ide> region_name = "fr-par" <ide> <ide> <del>class ScalewayNLAmsConnection(ScalewayConnectionAWS4): <del> host = "s3.nl-ams.scw.cloud" <add> def __init__( <add> self, <add> key, <add> secret=None, <add> secure=True, <add> host=None, <add> port=None, <add> region=None, <add> url=None, <add> **kwargs, <add> ): <add> # Here for backward compatibility for old and deprecated driver class <add> # per region approach <add> if hasattr(self, "region_name") and not region: <add> region = self.region_name # pylint: disable=no-member <ide> <add> self.region_name = region <ide> <del>class ScalewayNLAmsStorageDriver(ScalewayStorageDriver): <del> name = 'Scaleway Storage Driver (nl-ams)' <del> connectionCls = ScalewayNLAmsConnection <del> region_name = "nl-ams" <add> if region and region not in REGION_TO_HOST_MAP.keys(): <add> raise ValueError("Invalid or unsupported region: %s" % (region)) <ide> <add> self.name = "Amazon S3 (%s)" % (region) <ide> <del>class ScalewayPLWawConnection(ScalewayConnectionAWS4): <del> host = "s3.pl-waw.scw.cloud" <del> <del> <del>class ScalewayPLWawStorageDriver(ScalewayStorageDriver): <del> name = 'Scaleway Storage Driver (pl-waw)' <del> connectionCls = ScalewayPLWawConnection <del> region_name = "pl-waw" <add> if host is None: <add> host = REGION_TO_HOST_MAP[region] <add> <add> super(ScalewayStorageDriver, self).__init__( <add> key=key, <add> secret=secret, <add> secure=secure, <add> host=host, <add> port=port, <add> region=region, <add> url=url, <add> **kwargs, <add> ) <add> <add> @classmethod <add> def list_regions(self): <add> return REGION_TO_HOST_MAP.keys() <ide><path>libcloud/storage/providers.py <ide> "DigitalOceanSpacesStorageDriver", <ide> ), <ide> Provider.MINIO: ("libcloud.storage.drivers.minio", "MinIOStorageDriver"), <del> Provider.SCALEWAY: ("libcloud.storage.drivers.scaleway", "ScalewayStorageDriver"), <del> Provider.SCALEWAY_FR_PAR: ("libcloud.storage.drivers.scaleway", "ScalewayFRParStorageDriver"), <del> Provider.SCALEWAY_NL_AMS: ("libcloud.storage.drivers.scaleway", "ScalewayNLAmsStorageDriver"), <del> Provider.SCALEWAY_PL_WAW: ("libcloud.storage.drivers.scaleway", "ScalewayPLWawStorageDriver") <add> Provider.SCALEWAY: ("libcloud.storage.drivers.scaleway", "ScalewayStorageDriver") <ide> } <ide> <ide>
2
PHP
PHP
add collection serialization
baf62ee5a1b55b62e642c40cee08030faebe1781
<ide><path>src/Illuminate/Queue/SerializesModels.php <ide> public function __wakeup() <ide> */ <ide> protected function getSerializedPropertyValue($value) <ide> { <add> if ($value instanceof QueueableCollection) { <add> return new ModelIdentifier($value->getQueueableClass(), $value->getQueueableIds()); <add> } <add> <ide> if ($value instanceof QueueableEntity) { <ide> return new ModelIdentifier(get_class($value), $value->getQueueableId()); <ide> }
1
Ruby
Ruby
set border on link_to_image to 0 by default
8712652dd9728a1df9c9f095da03318d804ebac2
<ide><path>actionpack/lib/action_view/helpers/url_helper.rb <ide> def link_to(name, options = {}, html_options = {}, *parameters_for_method_refere <ide> # <ide> # ::alt: If no alt text is given, the file name part of the +src+ is used (capitalized and without the extension) <ide> # ::size: Supplied as "XxY", so "30x45" becomes width="30" and height="45" <add> # ::border: Is set to 0 by default <ide> # ::align: Sets the alignment, no special features <ide> # <ide> # The +src+ can be supplied as a... <ide> def link_to_image(src, options = {}, html_options = {}, *parameters_for_method_r <ide> image_options["width"], image_options["height"] = html_options["size"].split("x") <ide> html_options.delete "size" <ide> end <add> <add> if html_options["border"] <add> image_options["border"] = html_options["border"] <add> html_options.delete "border" <add> else <add> image_options["border"] = "0" <add> end <ide> <ide> if html_options["align"] <ide> image_options["align"] = html_options["align"]
1
Javascript
Javascript
remove unneeded variables
c013c8899bceb52a500431cbd28272716d45a98a
<ide><path>packages/sproutcore-handlebars/lib/helpers/debug.js <ide> <ide> require('sproutcore-handlebars/ext'); <ide> <del>var get = SC.get, getPath = SC.getPath; <add>var getPath = SC.getPath; <ide> <ide> /** <ide> `log` allows you to output the value of a value in the current rendering <ide><path>packages/sproutcore-handlebars/lib/helpers/unbound.js <ide> <ide> require('sproutcore-handlebars/ext'); <ide> <del>var get = SC.get, getPath = SC.getPath; <add>var getPath = SC.getPath; <ide> <ide> /** <ide> `unbound` allows you to output a property without binding. *Important:* The
2
Javascript
Javascript
stereoeffect set eye separation
3d0dc519c6a888fe521907cf54c84e4cd821ba29
<ide><path>examples/js/effects/StereoEffect.js <ide> THREE.StereoEffect = function ( renderer ) { <ide> <ide> }; <ide> <add> this.setEyeSep = function ( eyeSep ) { <add> <add> _stereo.eyeSep = eyeSep; <add> <add> }; <add> <ide> this.render = function ( scene, camera ) { <ide> <ide> scene.updateMatrixWorld(); <ide><path>src/cameras/StereoCamera.js <ide> function StereoCamera() { <ide> <ide> this.aspect = 1; <ide> <add> this.eyeSep = 0.064; <add> <ide> this.cameraL = new PerspectiveCamera(); <ide> this.cameraL.layers.enable( 1 ); <ide> this.cameraL.matrixAutoUpdate = false; <ide> Object.assign( StereoCamera.prototype, { <ide> // http://paulbourke.net/stereographics/stereorender/ <ide> <ide> var projectionMatrix = camera.projectionMatrix.clone(); <del> var eyeSep = 0.064 / 2; <add> var eyeSep = this.eyeSep / 2; <ide> var eyeSepOnProjection = eyeSep * near / focus; <ide> var ymax = near * Math.tan( _Math.DEG2RAD * fov * 0.5 ); <ide> var xmin, xmax;
2
Python
Python
add missing license hader
a8aef9680c8458508c478cab0a020bc470b10bf3
<ide><path>test/loadbalancer/test_gogrid.py <add># Licensed to the Apache Software Foundation (ASF) under one or more <add># contributor license agreements. See the NOTICE file distributed with <add># this work for additional information regarding copyright ownership. <add># The ASF licenses this file to You under the Apache License, Version 2.0 <add># (the "License"); you may not use this file except in compliance with <add># the License. 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> <ide> import httplib <ide> import os.path <ide> import sys
1
Java
Java
use collections.addall where feasible
ed64a10c386060697a6904825f2e2a6f14ff297a
<ide><path>spring-core/src/main/java/org/springframework/core/env/AbstractEnvironment.java <ide> public void merge(ConfigurableEnvironment parent) { <ide> String[] parentActiveProfiles = parent.getActiveProfiles(); <ide> if (!ObjectUtils.isEmpty(parentActiveProfiles)) { <ide> synchronized (this.activeProfiles) { <del> for (String profile : parentActiveProfiles) { <del> this.activeProfiles.add(profile); <del> } <add> Collections.addAll(this.activeProfiles, parentActiveProfiles); <ide> } <ide> } <ide> String[] parentDefaultProfiles = parent.getDefaultProfiles(); <ide><path>spring-core/src/main/java/org/springframework/core/env/AbstractPropertyResolver.java <ide> <ide> package org.springframework.core.env; <ide> <add>import java.util.Collections; <ide> import java.util.LinkedHashSet; <ide> import java.util.Set; <ide> <ide> public void setIgnoreUnresolvableNestedPlaceholders(boolean ignoreUnresolvableNe <ide> <ide> @Override <ide> public void setRequiredProperties(String... requiredProperties) { <del> for (String key : requiredProperties) { <del> this.requiredProperties.add(key); <del> } <add> Collections.addAll(this.requiredProperties, requiredProperties); <ide> } <ide> <ide> @Override
2
Javascript
Javascript
remove weird white space not present locally
b2a70fd5baed4aea8500e89a09e785339113cf48
<ide><path>common/app/routes/Challenges/rechallenge/builders.js <ide> export const cssToHtml = cond([ <ide> matchesProperty('ext', 'css'), <ide> flow(padContentWithHTMLCatch, wrapInStyle, setExtToHTML) <ide> ], <del> [ stubTrue, identity ] <add> [ stubTrue, identity ] <ide> ]); <ide> <ide> // FileStream::concactHtml(
1
Python
Python
handle inplace generation of __config__
3f025b5400c0855472a772487de8930bac9b5eef
<ide><path>numpy/setupscons.py <ide> #!/usr/bin/env python <add>from os.path import join as pjoin <ide> <ide> def configuration(parent_package='',top_path=None): <ide> from numpy.distutils.misc_util import Configuration <del> config = Configuration('numpy',parent_package,top_path, setup_name = 'setupscons.py') <add> from numpy.distutils.misc_util import scons_generate_config_py <add> <add> pkgname = 'numpy' <add> config = Configuration(pkgname,parent_package,top_path, setup_name = 'setupscons.py') <ide> config.add_subpackage('distutils') <ide> config.add_subpackage('testing') <ide> config.add_subpackage('f2py') <ide> def configuration(parent_package='',top_path=None): <ide> config.add_subpackage('ma') <ide> config.add_data_dir('doc') <ide> config.add_data_dir('tests') <del> config.scons_make_config_py() # installs __config__.py <add> <add> def add_config(*args, **kw): <add> # Generate __config__, handle inplace issues. <add> if kw['scons_cmd'].inplace: <add> target = pjoin(kw['pkg_name'], '__config__.py') <add> else: <add> target = pjoin(kw['scons_cmd'].build_lib, kw['pkg_name'], '__config__.py') <add> scons_generate_config_py(target) <add> config.add_sconscript(None, post_hook = add_config) <add> <ide> return config <ide> <ide> if __name__ == '__main__':
1
Ruby
Ruby
force wine to use stdenv for now
e1ff17ed75aff0bed4f95a20284531b6bf6d98b5
<ide><path>Library/Homebrew/build.rb <ide> def install f <ide> # TODO replace with Formula DSL <ide> # Python etc. build but then pip can't build stuff. <ide> # Scons resets ENV and then can't find superenv's build-tools. <del> stdenvs = %w{fontforge python python3 ruby ruby-enterprise-edition jruby} <add> stdenvs = %w{fontforge python python3 ruby ruby-enterprise-edition jruby wine} <ide> ARGV.unshift '--env=std' if (stdenvs.include?(f.name) or <ide> f.recursive_deps.detect{|d| d.name == 'scons' }) and <ide> not ARGV.include? '--env=super'
1
Java
Java
add support for autowiring jackson handlers
2fccf3ff4409a641c20947e8fca90308f7236c64
<ide><path>spring-web/src/main/java/org/springframework/http/converter/json/Jackson2ObjectMapperBuilder.java <ide> import com.fasterxml.jackson.databind.DeserializationFeature; <ide> import com.fasterxml.jackson.databind.JsonDeserializer; <ide> import com.fasterxml.jackson.databind.JsonSerializer; <add>import com.fasterxml.jackson.databind.KeyDeserializer; <ide> import com.fasterxml.jackson.databind.MapperFeature; <ide> import com.fasterxml.jackson.databind.Module; <ide> import com.fasterxml.jackson.databind.ObjectMapper; <ide> import com.fasterxml.jackson.databind.PropertyNamingStrategy; <ide> import com.fasterxml.jackson.databind.SerializationFeature; <add>import com.fasterxml.jackson.databind.cfg.HandlerInstantiator; <ide> import com.fasterxml.jackson.databind.module.SimpleModule; <ide> import com.fasterxml.jackson.dataformat.xml.XmlMapper; <add>import javafx.application.Application; <ide> <ide> import org.springframework.beans.BeanUtils; <ide> import org.springframework.beans.FatalBeanException; <add>import org.springframework.context.ApplicationContext; <ide> import org.springframework.util.Assert; <ide> import org.springframework.util.ClassUtils; <ide> <ide> public class Jackson2ObjectMapperBuilder { <ide> <ide> private ClassLoader moduleClassLoader = getClass().getClassLoader(); <ide> <add> private HandlerInstantiator handlerInstantiator; <add> <add> private ApplicationContext applicationContext; <add> <ide> <ide> /** <ide> * If set to {@code true}, an {@link XmlMapper} will be created using its <ide> public Jackson2ObjectMapperBuilder moduleClassLoader(ClassLoader moduleClassLoad <ide> return this; <ide> } <ide> <add> /** <add> * Customize the construction of Jackson handlers ({@link JsonSerializer}, {@link JsonDeserializer}, <add> * {@link KeyDeserializer}, {@code TypeResolverBuilder} and {@code TypeIdResolver}). <add> * @since 4.1.3 <add> * @see Jackson2ObjectMapperBuilder#applicationContext(ApplicationContext) <add> */ <add> public Jackson2ObjectMapperBuilder handlerInstantiator(HandlerInstantiator handlerInstantiator) { <add> this.handlerInstantiator = handlerInstantiator; <add> return this; <add> } <add> <add> /** <add> * Set the Spring {@link ApplicationContext} in order to autowire Jackson handlers ({@link JsonSerializer}, <add> * {@link JsonDeserializer}, {@link KeyDeserializer}, {@code TypeResolverBuilder} and {@code TypeIdResolver}). <add> * @since 4.1.3 <add> * @see SpringHandlerInstantiator <add> */ <add> public Jackson2ObjectMapperBuilder applicationContext(ApplicationContext applicationContext) { <add> this.applicationContext = applicationContext; <add> return this; <add> } <ide> <ide> /** <ide> * Build a new {@link ObjectMapper} instance. <ide> public void configure(ObjectMapper objectMapper) { <ide> for (Class<?> target : this.mixIns.keySet()) { <ide> objectMapper.addMixInAnnotations(target, this.mixIns.get(target)); <ide> } <add> if (this.handlerInstantiator != null) { <add> objectMapper.setHandlerInstantiator(this.handlerInstantiator); <add> } <add> else if (this.applicationContext != null) { <add> objectMapper.setHandlerInstantiator(new SpringHandlerInstantiator(this.applicationContext.getAutowireCapableBeanFactory())); <add> } <ide> } <ide> <ide> // Any change to this method should be also applied to spring-jms and spring-messaging <ide><path>spring-web/src/main/java/org/springframework/http/converter/json/Jackson2ObjectMapperFactoryBean.java <ide> import com.fasterxml.jackson.databind.DeserializationFeature; <ide> import com.fasterxml.jackson.databind.JsonDeserializer; <ide> import com.fasterxml.jackson.databind.JsonSerializer; <add>import com.fasterxml.jackson.databind.KeyDeserializer; <ide> import com.fasterxml.jackson.databind.MapperFeature; <ide> import com.fasterxml.jackson.databind.Module; <ide> import com.fasterxml.jackson.databind.ObjectMapper; <ide> import com.fasterxml.jackson.databind.PropertyNamingStrategy; <ide> import com.fasterxml.jackson.databind.SerializationFeature; <add>import com.fasterxml.jackson.databind.cfg.HandlerInstantiator; <ide> import com.fasterxml.jackson.dataformat.xml.XmlMapper; <ide> <ide> import org.springframework.beans.factory.BeanClassLoaderAware; <ide> import org.springframework.beans.factory.FactoryBean; <ide> import org.springframework.beans.factory.InitializingBean; <add>import org.springframework.context.ApplicationContext; <add>import org.springframework.context.ApplicationContextAware; <ide> <ide> /** <ide> * A {@link FactoryBean} for creating a Jackson 2.x {@link ObjectMapper} (default) or <ide> * @author Brian Clozel <ide> * @author Juergen Hoeller <ide> * @author Tadaya Tsuyukubo <add> * @author Sebastien Deleuze <ide> * @since 3.2 <ide> */ <del>public class Jackson2ObjectMapperFactoryBean implements FactoryBean<ObjectMapper>, BeanClassLoaderAware, InitializingBean { <add>public class Jackson2ObjectMapperFactoryBean implements FactoryBean<ObjectMapper>, BeanClassLoaderAware, <add> ApplicationContextAware, InitializingBean { <ide> <ide> private final Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder(); <ide> <ide> public void setFindModulesViaServiceLoader(boolean findModules) { <ide> this.builder.findModulesViaServiceLoader(findModules); <ide> } <ide> <add> /** <add> * Customize the construction of Jackson handlers ({@link JsonSerializer}, {@link JsonDeserializer}, <add> * {@link KeyDeserializer}, {@code TypeResolverBuilder} and {@code TypeIdResolver}). <add> * @since 4.1.3 <add> * @see Jackson2ObjectMapperFactoryBean#setApplicationContext(ApplicationContext) <add> */ <add> public void setHandlerInstantiator(HandlerInstantiator handlerInstantiator) { <add> this.builder.handlerInstantiator(handlerInstantiator); <add> } <add> <ide> @Override <ide> public void setBeanClassLoader(ClassLoader beanClassLoader) { <ide> this.builder.moduleClassLoader(beanClassLoader); <ide> public void afterPropertiesSet() { <ide> } <ide> } <ide> <add> /** <add> * Set the builder {@link ApplicationContext} in order to autowire Jackson handlers ({@link JsonSerializer}, <add> * {@link JsonDeserializer}, {@link KeyDeserializer}, {@code TypeResolverBuilder} and {@code TypeIdResolver}). <add> * @since 4.1.3 <add> * @see Jackson2ObjectMapperBuilder#applicationContext(ApplicationContext) <add> * @see SpringHandlerInstantiator <add> */ <add> @Override <add> public void setApplicationContext(ApplicationContext applicationContext) { <add> this.builder.applicationContext(applicationContext); <add> } <ide> <ide> /** <ide> * Return the singleton ObjectMapper. <ide><path>spring-web/src/main/java/org/springframework/http/converter/json/SpringHandlerInstantiator.java <add>/* <add> * Copyright 2002-2014 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.http.converter.json; <add> <add>import com.fasterxml.jackson.databind.DeserializationConfig; <add>import com.fasterxml.jackson.databind.JsonDeserializer; <add>import com.fasterxml.jackson.databind.JsonSerializer; <add>import com.fasterxml.jackson.databind.KeyDeserializer; <add>import com.fasterxml.jackson.databind.SerializationConfig; <add>import com.fasterxml.jackson.databind.cfg.HandlerInstantiator; <add>import com.fasterxml.jackson.databind.cfg.MapperConfig; <add>import com.fasterxml.jackson.databind.introspect.Annotated; <add>import com.fasterxml.jackson.databind.jsontype.TypeIdResolver; <add>import com.fasterxml.jackson.databind.jsontype.TypeResolverBuilder; <add> <add>import org.springframework.beans.factory.config.AutowireCapableBeanFactory; <add>import org.springframework.context.ApplicationContext; <add>import org.springframework.util.Assert; <add> <add>/** <add> * Eventually get Jackson handler ({@link JsonSerializer}, {@link JsonDeserializer}, <add> * {@link KeyDeserializer}, {@link TypeResolverBuilder}, {@link TypeIdResolver}) beans by <add> * type from Spring {@link ApplicationContext}. If no bean is found, the default behavior <add> * happen (calling no-argument constructor via reflection). <add> * <add> * @since 4.1.3 <add> * @author Sebastien Deleuze <add> * @see Jackson2ObjectMapperBuilder#handlerInstantiator(HandlerInstantiator) <add> * @see HandlerInstantiator <add> */ <add>public class SpringHandlerInstantiator extends HandlerInstantiator { <add> <add> private final AutowireCapableBeanFactory beanFactory; <add> <add> <add> /** <add> * Create a new SpringHandlerInstantiator for the given BeanFactory. <add> * @param beanFactory the target BeanFactory <add> */ <add> public SpringHandlerInstantiator(AutowireCapableBeanFactory beanFactory) { <add> Assert.notNull(beanFactory, "BeanFactory must not be null"); <add> this.beanFactory = beanFactory; <add> } <add> <add> @Override <add> public JsonSerializer<?> serializerInstance(SerializationConfig config, <add> Annotated annotated, Class<?> keyDeserClass) { <add> return (JsonSerializer<?>) this.beanFactory.createBean(keyDeserClass); <add> } <add> <add> @Override <add> public JsonDeserializer<?> deserializerInstance(DeserializationConfig config, <add> Annotated annotated, Class<?> deserClass) { <add> return (JsonDeserializer<?>) this.beanFactory.createBean(deserClass); <add> } <add> <add> @Override <add> public KeyDeserializer keyDeserializerInstance(DeserializationConfig config, <add> Annotated annotated, Class<?> serClass) { <add> return (KeyDeserializer) this.beanFactory.createBean(serClass); <add> } <add> <add> @Override <add> public TypeResolverBuilder<?> typeResolverBuilderInstance(MapperConfig<?> config, <add> Annotated annotated, Class<?> resolverClass) { <add> return (TypeResolverBuilder<?>) this.beanFactory.createBean(resolverClass); <add> } <add> <add> @Override <add> public TypeIdResolver typeIdResolverInstance(MapperConfig<?> config, <add> Annotated annotated, Class<?> resolverClass) { <add> return (TypeIdResolver) this.beanFactory.createBean(resolverClass); <add> } <add>} <ide><path>spring-web/src/test/java/org/springframework/http/converter/json/SpringHandlerInstantiatorTests.java <add>/* <add> * Copyright 2002-2014 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.http.converter.json; <add> <add>import java.io.IOException; <add>import java.util.Collection; <add>import java.util.HashMap; <add>import java.util.Map; <add> <add>import com.fasterxml.jackson.annotation.JsonTypeInfo; <add>import com.fasterxml.jackson.core.JsonGenerator; <add>import com.fasterxml.jackson.core.JsonParser; <add>import com.fasterxml.jackson.core.JsonProcessingException; <add>import com.fasterxml.jackson.core.ObjectCodec; <add>import com.fasterxml.jackson.databind.DeserializationConfig; <add>import com.fasterxml.jackson.databind.DeserializationContext; <add>import com.fasterxml.jackson.databind.JavaType; <add>import com.fasterxml.jackson.databind.JsonDeserializer; <add>import com.fasterxml.jackson.databind.JsonNode; <add>import com.fasterxml.jackson.databind.JsonSerializer; <add>import com.fasterxml.jackson.databind.KeyDeserializer; <add>import com.fasterxml.jackson.databind.ObjectMapper; <add>import com.fasterxml.jackson.databind.SerializationConfig; <add>import com.fasterxml.jackson.databind.SerializerProvider; <add>import com.fasterxml.jackson.databind.annotation.JsonDeserialize; <add>import com.fasterxml.jackson.databind.annotation.JsonSerialize; <add>import com.fasterxml.jackson.databind.annotation.JsonTypeIdResolver; <add>import com.fasterxml.jackson.databind.annotation.JsonTypeResolver; <add>import com.fasterxml.jackson.databind.jsontype.NamedType; <add>import com.fasterxml.jackson.databind.jsontype.TypeDeserializer; <add>import com.fasterxml.jackson.databind.jsontype.TypeIdResolver; <add>import com.fasterxml.jackson.databind.jsontype.TypeSerializer; <add>import com.fasterxml.jackson.databind.jsontype.impl.StdTypeResolverBuilder; <add>import com.fasterxml.jackson.databind.type.TypeFactory; <add>import static org.junit.Assert.assertEquals; <add>import static org.junit.Assert.assertFalse; <add>import static org.junit.Assert.assertTrue; <add>import org.junit.Before; <add>import org.junit.Test; <add> <add>import org.springframework.beans.factory.annotation.Autowired; <add>import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor; <add>import org.springframework.beans.factory.support.DefaultListableBeanFactory; <add>import org.springframework.beans.factory.support.RootBeanDefinition; <add> <add>/** <add> * Test class for {@link SpringHandlerInstantiatorTests}. <add> * <add> * @author Sebastien Deleuze <add> */ <add>public class SpringHandlerInstantiatorTests { <add> <add> private SpringHandlerInstantiator instantiator; <add> private ObjectMapper objectMapper; <add> <add> @Before <add> public void setup() { <add> DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); <add> AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor(); <add> bpp.setBeanFactory(bf); <add> bf.addBeanPostProcessor(bpp); <add> bf.registerBeanDefinition("capitalizer", new RootBeanDefinition(Capitalizer.class)); <add> instantiator = new SpringHandlerInstantiator(bf); <add> objectMapper = Jackson2ObjectMapperBuilder.json().handlerInstantiator(instantiator).build(); <add> } <add> <add> @Test <add> public void autowiredSerializer() throws JsonProcessingException { <add> User user = new User("bob"); <add> String json = this.objectMapper.writeValueAsString(user); <add> assertEquals("{\"username\":\"BOB\"}", json); <add> <add> } <add> <add> @Test <add> public void autowiredDeserializer() throws IOException { <add> String json = "{\"username\":\"bob\"}"; <add> User user = this.objectMapper.readValue(json, User.class); <add> assertEquals(user.getUsername(), "BOB"); <add> } <add> <add> @Test <add> public void autowiredKeyDeserializer() throws IOException { <add> String json = "{\"credentials\":{\"bob\":\"admin\"}}"; <add> SecurityRegistry registry = this.objectMapper.readValue(json, SecurityRegistry.class); <add> assertTrue(registry.getCredentials().keySet().contains("BOB")); <add> assertFalse(registry.getCredentials().keySet().contains("bob")); <add> } <add> <add> @Test <add> public void applicationContextAwaretypeResolverBuilder() throws JsonProcessingException { <add> this.objectMapper.writeValueAsString(new Group("authors")); <add> assertTrue(CustomTypeResolverBuilder.isAutowiredFiledInitialized); <add> } <add> <add> @Test <add> public void applicationContextAwareTypeIdResolver() throws JsonProcessingException { <add> this.objectMapper.writeValueAsString(new Group("authors")); <add> assertTrue(CustomTypeIdResolver.isAutowiredFiledInitialized); <add> } <add> <add> public static class UserDeserializer extends JsonDeserializer<User> { <add> <add> @Autowired <add> private Capitalizer capitalizer; <add> <add> @Override <add> public User deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { <add> ObjectCodec oc = jsonParser.getCodec(); <add> JsonNode node = oc.readTree(jsonParser); <add> return new User(this.capitalizer.capitalize(node.get("username").asText())); <add> } <add> <add> } <add> <add> public static class UserSerializer extends JsonSerializer<User> { <add> <add> @Autowired <add> private Capitalizer capitalizer; <add> <add> @Override <add> public void serialize(User user, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { <add> jsonGenerator.writeStartObject(); <add> jsonGenerator.writeStringField("username", this.capitalizer.capitalize(user.getUsername())); <add> jsonGenerator.writeEndObject(); <add> } <add> } <add> <add> public static class UpperCaseKeyDeserializer extends KeyDeserializer { <add> <add> @Autowired <add> private Capitalizer capitalizer; <add> <add> @Override <add> public Object deserializeKey(String key, DeserializationContext context) throws IOException, JsonProcessingException { <add> return this.capitalizer.capitalize(key); <add> } <add> } <add> <add> public static class CustomTypeResolverBuilder extends StdTypeResolverBuilder { <add> <add> @Autowired <add> private Capitalizer capitalizer; <add> <add> public static boolean isAutowiredFiledInitialized = false; <add> <add> @Override <add> public TypeSerializer buildTypeSerializer(SerializationConfig config, JavaType baseType, Collection<NamedType> subtypes) { <add> isAutowiredFiledInitialized = (this.capitalizer != null); <add> return super.buildTypeSerializer(config, baseType, subtypes); <add> } <add> <add> @Override <add> public TypeDeserializer buildTypeDeserializer(DeserializationConfig config, JavaType baseType, Collection<NamedType> subtypes) { <add> return super.buildTypeDeserializer(config, baseType, subtypes); <add> } <add> } <add> <add> public static class CustomTypeIdResolver implements TypeIdResolver { <add> <add> @Autowired <add> private Capitalizer capitalizer; <add> <add> public static boolean isAutowiredFiledInitialized = false; <add> <add> public CustomTypeIdResolver() { <add> <add> } <add> <add> @Override <add> public String idFromValueAndType(Object o, Class<?> type) { <add> return type.getClass().getName(); <add> } <add> <add> @Override <add> public JsonTypeInfo.Id getMechanism() { <add> return JsonTypeInfo.Id.CUSTOM; <add> } <add> <add> @Override <add> public JavaType typeFromId(String s) { <add> return TypeFactory.defaultInstance().constructFromCanonical(s); <add> } <add> <add> @Override <add> public String idFromValue(Object value) { <add> isAutowiredFiledInitialized = (this.capitalizer != null); <add> return value.getClass().getName(); <add> } <add> <add> @Override <add> public void init(JavaType type) { <add> <add> } <add> <add> @Override <add> public String idFromBaseType() { <add> return null; <add> } <add> } <add> <add> @JsonDeserialize(using = UserDeserializer.class) <add> @JsonSerialize(using = UserSerializer.class) <add> public static class User { <add> <add> private String username; <add> <add> public User() { <add> } <add> <add> public User(String username) { <add> this.username = username; <add> } <add> <add> public String getUsername() { return this.username; } <add> } <add> <add> public static class SecurityRegistry { <add> <add> @JsonDeserialize(keyUsing = UpperCaseKeyDeserializer.class) <add> private Map<String, String> credentials = new HashMap<>(); <add> <add> public void addCredential(String username, String credential) { <add> this.credentials.put(username, credential); <add> } <add> <add> public Map<String, String> getCredentials() { <add> return credentials; <add> } <add> } <add> <add> @JsonTypeInfo(use = JsonTypeInfo.Id.CUSTOM, property = "type") <add> @JsonTypeResolver(CustomTypeResolverBuilder.class) <add> @JsonTypeIdResolver(CustomTypeIdResolver.class) <add> public static class Group { <add> <add> private String name; <add> <add> public Group(String name) { <add> this.name = name; <add> } <add> <add> public Group() { <add> <add> } <add> <add> public String getType() { <add> return Group.class.getName(); <add> } <add> } <add> <add> public static class Capitalizer { <add> <add> public String capitalize(String text) { <add> return text.toUpperCase(); <add> } <add> } <add>} <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/AnnotationDrivenBeanDefinitionParser.java <ide> import org.springframework.beans.factory.config.RuntimeBeanReference; <ide> import org.springframework.beans.factory.parsing.BeanComponentDefinition; <ide> import org.springframework.beans.factory.parsing.CompositeComponentDefinition; <add>import org.springframework.beans.factory.support.GenericBeanDefinition; <ide> import org.springframework.beans.factory.support.ManagedList; <ide> import org.springframework.beans.factory.support.RootBeanDefinition; <ide> import org.springframework.beans.factory.xml.BeanDefinitionParser; <ide> import org.springframework.http.converter.feed.AtomFeedHttpMessageConverter; <ide> import org.springframework.http.converter.feed.RssChannelHttpMessageConverter; <ide> import org.springframework.http.converter.json.GsonHttpMessageConverter; <add>import org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean; <ide> import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; <ide> import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter; <ide> import org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter; <ide> private ManagedList<?> getMessageConverters(Element element, Object source, Pars <ide> } <ide> <ide> if (jackson2XmlPresent) { <del> messageConverters.add(createConverterDefinition(MappingJackson2XmlHttpMessageConverter.class, source)); <add> RootBeanDefinition jacksonConverterDef = createConverterDefinition(MappingJackson2XmlHttpMessageConverter.class, source); <add> GenericBeanDefinition jacksonFactoryDef = createObjectMapperFactoryDefinition(source); <add> jacksonFactoryDef.getPropertyValues().add("createXmlMapper", true); <add> jacksonConverterDef.getConstructorArgumentValues().addIndexedArgumentValue(0, jacksonFactoryDef); <add> messageConverters.add(jacksonConverterDef); <ide> } <ide> else if (jaxb2Present) { <ide> messageConverters.add(createConverterDefinition(Jaxb2RootElementHttpMessageConverter.class, source)); <ide> } <ide> <ide> if (jackson2Present) { <del> messageConverters.add(createConverterDefinition(MappingJackson2HttpMessageConverter.class, source)); <add> RootBeanDefinition jacksonConverterDef = createConverterDefinition(MappingJackson2HttpMessageConverter.class, source); <add> GenericBeanDefinition jacksonFactoryDef = createObjectMapperFactoryDefinition(source); <add> jacksonConverterDef.getConstructorArgumentValues().addIndexedArgumentValue(0, jacksonFactoryDef); <add> messageConverters.add(jacksonConverterDef); <ide> } <ide> else if (gsonPresent) { <ide> messageConverters.add(createConverterDefinition(GsonHttpMessageConverter.class, source)); <ide> else if (gsonPresent) { <ide> return messageConverters; <ide> } <ide> <add> private GenericBeanDefinition createObjectMapperFactoryDefinition(Object source) { <add> GenericBeanDefinition beanDefinition = new GenericBeanDefinition(); <add> beanDefinition.setBeanClass(Jackson2ObjectMapperFactoryBean.class); <add> beanDefinition.setSource(source); <add> beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); <add> return beanDefinition; <add> } <add> <ide> private RootBeanDefinition createConverterDefinition(Class<?> converterClass, Object source) { <ide> RootBeanDefinition beanDefinition = new RootBeanDefinition(converterClass); <ide> beanDefinition.setSource(source); <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupport.java <ide> import javax.servlet.http.HttpServletRequest; <ide> import javax.xml.transform.Source; <ide> <add>import com.fasterxml.jackson.databind.ObjectMapper; <add> <ide> import org.springframework.beans.BeanUtils; <ide> import org.springframework.beans.factory.BeanFactoryUtils; <ide> import org.springframework.beans.factory.BeanInitializationException; <ide> import org.springframework.http.converter.feed.AtomFeedHttpMessageConverter; <ide> import org.springframework.http.converter.feed.RssChannelHttpMessageConverter; <ide> import org.springframework.http.converter.json.GsonHttpMessageConverter; <add>import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; <ide> import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; <ide> import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter; <ide> import org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter; <ide> protected final void addDefaultHttpMessageConverters(List<HttpMessageConverter<? <ide> } <ide> <ide> if (jackson2XmlPresent) { <del> messageConverters.add(new MappingJackson2XmlHttpMessageConverter()); <add> ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.xml().applicationContext(this.applicationContext).build(); <add> messageConverters.add(new MappingJackson2XmlHttpMessageConverter(objectMapper)); <ide> } <ide> else if (jaxb2Present) { <ide> messageConverters.add(new Jaxb2RootElementHttpMessageConverter()); <ide> } <ide> <ide> if (jackson2Present) { <del> messageConverters.add(new MappingJackson2HttpMessageConverter()); <add> ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().applicationContext(this.applicationContext).build(); <add> messageConverters.add(new MappingJackson2HttpMessageConverter(objectMapper)); <ide> } <ide> else if (gsonPresent) { <ide> messageConverters.add(new GsonHttpMessageConverter()); <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/config/MessageBrokerBeanDefinitionParser.java <ide> import java.util.List; <ide> import java.util.Map; <ide> <del>import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; <add>import org.springframework.beans.factory.support.GenericBeanDefinition; <add>import org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean; <ide> import org.springframework.messaging.support.ImmutableMessageChannelInterceptor; <ide> import org.w3c.dom.Element; <ide> <ide> private RuntimeBeanReference registerMessageConverter(Element element, ParserCon <ide> RootBeanDefinition resolverDef = new RootBeanDefinition(DefaultContentTypeResolver.class); <ide> resolverDef.getPropertyValues().add("defaultMimeType", MimeTypeUtils.APPLICATION_JSON); <ide> jacksonConverterDef.getPropertyValues().add("contentTypeResolver", resolverDef); <del> // Use Jackson builder in order to have JSR-310 and Joda-Time modules registered automatically <del> jacksonConverterDef.getPropertyValues().add("objectMapper", Jackson2ObjectMapperBuilder.json().build()); <add> // Use Jackson factory in order to have JSR-310 and Joda-Time modules registered automatically <add> GenericBeanDefinition jacksonFactoryDef = new GenericBeanDefinition(); <add> jacksonFactoryDef.setBeanClass(Jackson2ObjectMapperFactoryBean.class); <add> jacksonFactoryDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); <add> jacksonFactoryDef.setSource(source); <add> jacksonConverterDef.getPropertyValues().add("objectMapper", jacksonFactoryDef); <ide> converters.add(jacksonConverterDef); <ide> } <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/config/annotation/WebSocketMessageBrokerConfigurationSupport.java <ide> public WebSocketMessageBrokerStats webSocketMessageBrokerStats() { <ide> protected MappingJackson2MessageConverter createJacksonConverter() { <ide> MappingJackson2MessageConverter messageConverter = super.createJacksonConverter(); <ide> // Use Jackson builder in order to have JSR-310 and Joda-Time modules registered automatically <del> messageConverter.setObjectMapper(Jackson2ObjectMapperBuilder.json().build()); <add> messageConverter.setObjectMapper(Jackson2ObjectMapperBuilder.json() <add> .applicationContext(this.getApplicationContext()).build()); <ide> return messageConverter; <ide> } <ide>
8
Javascript
Javascript
add uri code storage
72e0595ca69612f94b9ad999ab5e00d9b7b4eb73
<ide><path>client/commonFramework.js <ide> common.challengeType = common.challengeType || window.challengeType ? <ide> <ide> common.challengeId = common.challengeId || window.challenge_Id; <ide> <add>common.challengeSeed = common.challengeSeed || window.challengeSeed ? <add> window.challengeSeed : <add> []; <add> <add>common.seed = common.challengeSeed.reduce(function(seed, line) { <add> return seed + line + '\n'; <add>}, ''); <add> <add>// store code in the URL <add>common.codeUri = (function(common, encode, decode, location, history) { <add> var codeUri = { <add> encode: function(code) { <add> return encode(code); <add> }, <add> decode: function(code) { <add> try { <add> return decode(code); <add> } catch (ignore) { <add> return null; <add> } <add> }, <add> isInQuery: function(query) { <add> var decoded = codeUri.decode(query); <add> if (!decoded || typeof decoded.split !== 'function') { <add> return false; <add> } <add> return decoded <add> .split('?') <add> .splice(1) <add> .reduce(function(found, param) { <add> var key = param.split('=')[0]; <add> if (key === 'solution') { <add> return true; <add> } <add> return found; <add> }, false); <add> }, <add> isAlive: function() { <add> return codeUri.isInQuery(location.search) || <add> codeUri.isInQuery(location.hash); <add> }, <add> parse: function() { <add> var query; <add> if (location.search && codeUri.isInQuery(location.search)) { <add> query = location.search.replace(/^\?/, ''); <add> if (history && typeof history.replaceState === 'function') { <add> history.replaceState( <add> history.state, <add> null, <add> location.href.split('?')[0] <add> ); <add> location.hash = '#?' + query; <add> } <add> } else { <add> query = location.hash.replace(/^\#\?/, ''); <add> } <add> if (!query) { <add> return null; <add> } <add> <add> return query <add> .split('&') <add> .reduce(function(solution, param) { <add> var key = param.split('=')[0]; <add> var value = param.split('=')[1]; <add> if (key === 'solution') { <add> return codeUri.decode(value); <add> } <add> return solution; <add> }, null); <add> }, <add> querify: function(solution) { <add> location.hash = '?solution=' + codeUri.encode(solution); <add> return solution; <add> } <add> }; <add> <add> common.init.push(function() { <add> codeUri.parse(); <add> }); <add> <add> return codeUri; <add>}(common, encodeURIComponent, decodeURIComponent, location, history)); <add> <ide> // codeStorage <del>common.codeStorageFactory = (function($, localStorage) { <add>common.codeStorageFactory = (function($, localStorage, codeUri) { <ide> <ide> var CodeStorageProps = { <ide> version: 0.01, <ide> common.codeStorageFactory = (function($, localStorage) { <ide> updateStorage: function() { <ide> if (typeof localStorage !== 'undefined') { <ide> var value = this.editor.getValue(); <add> // store in localStorage <ide> localStorage.setItem(this.keyValue, value); <add> // also store code in URL <add> codeUri.querify(value); <ide> } else { <ide> console.log('no web storage'); <ide> } <ide> common.codeStorageFactory = (function($, localStorage) { <ide> } <ide> <ide> return codeStorageFactory; <del>}($, localStorage)); <add>}($, localStorage, common.codeUri)); <ide> <ide> common.codeOutput = (function(CodeMirror, document, challengeType) { <ide> if (!CodeMirror) { <ide> var editor = (function(CodeMirror, emmetCodeMirror, common) { <ide> ); <ide> } <ide> common.init.push(function() { <del> editorValue = codeStorage.isAlive() ? <del> codeStorage.getStoredValue() : <del> allSeeds; <add> var editorValue; <add> if (common.codeUri.isAlive()) { <add> console.log('in query'); <add> editorValue = common.codeUri.parse(); <add> } else { <add> editorValue = codeStorage.isAlive() ? <add> codeStorage.getStoredValue() : <add> common.seed; <add> } <ide> <ide> editor.setValue(replaceSafeTags(editorValue)); <ide> editor.refresh(); <ide> var editor = (function(CodeMirror, emmetCodeMirror, common) { <ide> }(window.CodeMirror, window.emmetCodeMirror, common)); <ide> <ide> <del>var editorValue; <del>var challengeSeed = challengeSeed || []; <ide> var tests = tests || []; <del>var allSeeds = ''; <del> <del>(function() { <del> challengeSeed.forEach(function(elem) { <del> allSeeds += elem + '\n'; <del> }); <del>})(); <ide> <ide> var libraryIncludes = "<script src='//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>" + <ide> "<script src='/js/lib/chai/chai.js'></script>" + <ide> function showCompletion() { <ide> .delay(1000) <ide> .queue(function(next) { <ide> $(this).replaceWith( <del> '<div id="challenge-spinner" class="animated zoomInUp inner-circles-loader">submitting...</div>' <add> '<div id="challenge-spinner" ' + <add> 'class="animated zoomInUp inner-circles-loader">' + <add> 'submitting...</div>' <ide> ); <ide> next(); <ide> }); <ide> function showCompletion() { <ide> } <ide> <ide> var resetEditor = function resetEditor() { <del> editor.setValue(replaceSafeTags(allSeeds)); <add> editor.setValue(replaceSafeTags(common.seed)); <ide> $('#testSuite').empty(); <ide> bonfireExecute(true); <ide> common.codeStorage.updateStorage(); <ide> if (attempts) { <ide> var userTests; <ide> var testSalt = Math.random(); <ide> <del> <ide> var scrapeTests = function(userJavaScript) { <ide> <ide> // insert tests from mongo <ide> var createTestDisplay = function() { <ide> } <ide> for (var i = 0; i < userTests.length; i++) { <ide> var didTestPass = !userTests[i].err; <del> var testText = userTests[i].text.split('message: ').pop().replace(/\'\);/g, ''); <add> var testText = userTests[i].text <add> .split('message: ') <add> .pop() <add> .replace(/\'\);/g, ''); <add> <ide> var testDoc = document.createElement('div'); <ide> <ide> var iconClass = didTestPass ? <ide> var reassembleTest = function(test, data) { <ide> }; <ide> <ide> var runTests = function(err, data) { <add> var editorValue = editor.getValue(); <ide> // userTests = userTests ? null : []; <ide> var allTestsPassed = true; <ide> pushed = false;
1
PHP
PHP
use locatorawaretrait in databasesession
a078e01490dbfab3c4b6101286bac581ca64bf74
<ide><path>src/Network/Session/DatabaseSession.php <ide> namespace Cake\Network\Session; <ide> <ide> use Cake\ORM\Entity; <del>use Cake\ORM\Locator\TableLocator; <add>use Cake\ORM\Locator\LocatorAwareTrait; <ide> use SessionHandlerInterface; <ide> <ide> /** <ide> * DatabaseSession provides methods to be used with Session. <ide> */ <ide> class DatabaseSession implements SessionHandlerInterface <ide> { <add> use LocatorAwareTrait; <ide> <ide> /** <ide> * Reference to the table handling the session data <ide> class DatabaseSession implements SessionHandlerInterface <ide> */ <ide> public function __construct(array $config = []) <ide> { <del> $tableLocator = isset($config['tableLocator']) ? $config['tableLocator'] : TableLocator::getInstance(); <add> if (isset($config['tableLocator'])) { <add> $this->setTableLocator($config['tableLocator']); <add> } <add> $tableLocator = $this->getTableLocator(); <ide> <ide> if (empty($config['model'])) { <ide> $config = $tableLocator->exists('Sessions') ? [] : ['table' => 'sessions'];
1
Ruby
Ruby
push logic outside the fixtureset constructor
30e987936bb2f6122e64d6664e72907881b4ba11
<ide><path>activerecord/lib/active_record/fixtures.rb <ide> def self.create_fixtures(fixtures_directory, fixture_set_names, class_names = {} <ide> <ide> fixture_sets = files_to_read.map do |fs_name| <ide> klass = class_names[fs_name] <add> conn = klass ? klass.connection : connection <ide> fixtures_map[fs_name] = new( # ActiveRecord::FixtureSet.new <del> connection, <add> conn, <ide> fs_name, <ide> klass, <ide> ::File.join(fixtures_directory, fs_name)) <ide> def initialize(connection, name, class_name, path, config = ActiveRecord::Base) <ide> @model_class = class_name.safe_constantize if class_name <ide> end <ide> <del> @connection = ( model_class.respond_to?(:connection) ? <del> model_class.connection : connection ) <add> @connection = connection <ide> <ide> @table_name = ( model_class.respond_to?(:table_name) ? <ide> model_class.table_name :
1
Ruby
Ruby
add test coverage
63790504699ff08088b0f7422eefa6514e3bfc30
<ide><path>activesupport/test/notifications_test.rb <ide> def test_event_is_pushed_even_without_block <ide> <ide> class EventTest < TestCase <ide> def test_events_are_initialized_with_details <del> time = Time.now <add> time = Concurrent.monotonic_time <ide> event = event(:foo, time, time + 0.01, random_id, {}) <ide> <ide> assert_equal :foo, event.name <ide> assert_equal time, event.time <ide> assert_in_delta 10.0, event.duration, 0.00001 <ide> end <ide> <add> def test_event_cpu_time_and_idle_time_when_start_and_finish_is_not_called <add> time = Concurrent.monotonic_time <add> event = event(:foo, time, time + 0.01, random_id, {}) <add> <add> assert_equal 0, event.cpu_time <add> assert_in_delta 10.0, event.idle_time, 0.00001 <add> end <add> <add> <ide> def test_events_consumes_information_given_as_payload <del> event = event(:foo, Time.now, Time.now + 1, random_id, payload: :bar) <add> event = event(:foo, Concurrent.monotonic_time, Concurrent.monotonic_time + 1, random_id, payload: :bar) <ide> assert_equal Hash[payload: :bar], event.payload <ide> end <ide> <ide> def test_event_is_parent_based_on_children <del> time = Time.utc(2009, 01, 01, 0, 0, 1) <add> time = Concurrent.monotonic_time <ide> <del> parent = event(:foo, Time.utc(2009), Time.utc(2009) + 100, random_id, {}) <add> parent = event(:foo, Concurrent.monotonic_time, Concurrent.monotonic_time + 100, random_id, {}) <ide> child = event(:foo, time, time + 10, random_id, {}) <ide> not_child = event(:foo, time, time + 100, random_id, {}) <ide>
1
Python
Python
fix constraints and regularizers
3b2acf76f352bc588a72e0b827d0b9667d43c2b0
<ide><path>keras/constraints.py <ide> def maxnorm_wrap(p): <ide> <ide> def nonneg(p): <ide> p *= T.ge(p,0) <del> return p <ide>\ No newline at end of file <add> return p <add> <add>def identity(g): <add> return g <ide>\ No newline at end of file <ide><path>keras/layers/core.py <ide> import theano.tensor as T <ide> <ide> from .. import activations, initializations <del>from ..regularizers import identity <ide> from ..utils.theano_utils import shared_zeros, floatX <ide> from ..utils.generic_utils import make_tuple <ide> <ide> class Layer(object): <ide> def __init__(self): <ide> self.params = [] <del> self.regularizer = [] <del> self.constraint = [] <ide> <ide> def connect(self, previous_layer): <ide> self.previous_layer = previous_layer <ide> class Dense(Layer): <ide> ''' <ide> Just your regular fully connected NN layer. <ide> ''' <del> def __init__(self, input_dim, output_dim, init='glorot_uniform', activation='linear', weights=None, W_regularizer=identity, b_regularizer=identity, W_constraint=identity, b_constraint=identity): <add> def __init__(self, input_dim, output_dim, init='glorot_uniform', activation='linear', weights=None, <add> W_regularizer=None, b_regularizer=None, W_constraint=None, b_constraint=None): <add> <ide> super(Dense,self).__init__() <ide> self.init = initializations.get(init) <ide> self.activation = activations.get(activation) <ide> def __init__(self, input_dim, output_dim, init='glorot_uniform', activation='lin <ide> <ide> self.params = [self.W, self.b] <ide> <del> self.regularizer = [W_regularizer, b_regularizer] <del> self.constraint = [W_constraint, b_constraint] <add> self.regularizers = [W_regularizer, b_regularizer] <add> self.constraints = [W_constraint, b_constraint] <ide> <ide> if weights is not None: <ide> self.set_weights(weights) <ide> class TimeDistributedDense(Layer): <ide> Tensor output dimensions: (nb_sample, shared_dimension, output_dim) <ide> <ide> ''' <del> def __init__(self, input_dim, output_dim, init='glorot_uniform', activation='linear', weights=None, W_regularizer=identity, b_regularizer=identity, W_constraint=identity, b_constraint=identity): <add> def __init__(self, input_dim, output_dim, init='glorot_uniform', activation='linear', weights=None, <add> W_regularizer=None, b_regularizer=None, W_constraint=None, b_constraint=None): <add> <ide> super(TimeDistributedDense,self).__init__() <ide> self.init = initializations.get(init) <ide> self.activation = activations.get(activation) <ide> def __init__(self, input_dim, output_dim, init='glorot_uniform', activation='lin <ide> <ide> self.params = [self.W, self.b] <ide> <del> self.regularizer = [W_regularizer, b_regularizer] <del> self.constraint = [W_constraint, b_constraint] <add> self.regularizers = [W_regularizer, b_regularizer] <add> self.constraints = [W_constraint, b_constraint] <ide> <ide> if weights is not None: <ide> self.set_weights(weights) <ide><path>keras/models.py <ide> <ide> from . import optimizers <ide> from . import objectives <add>from . import regularizers <add>from . import constraints <ide> import time, copy <ide> from .utils.generic_utils import Progbar <ide> from six.moves import range <ide> class Sequential(object): <ide> def __init__(self): <ide> self.layers = [] <ide> self.params = [] <del> self.regularizer = [] <del> self.constraint = [] <add> self.regularizers = [] <add> self.constraints = [] <ide> <ide> def add(self, layer): <ide> self.layers.append(layer) <ide> if len(self.layers) > 1: <ide> self.layers[-1].connect(self.layers[-2]) <ide> self.params += [p for p in layer.params] <del> self.regularizer += [r for r in layer.regularizer] <del> self.constraint += [c for c in layer.constraint] <add> <add> if hasattr(layer, 'regularizers'): <add> for r in layer.regularizers: <add> if r: <add> self.regularizers.append(r) <add> else: <add> self.regularizers.append(regularizers.identity) <add> elif hasattr(layer, 'regularizer') and layer.regularizer: <add> self.regularizers += [layer.regularizer for _ in range(len(layer.params))] <add> else: <add> self.regularizers += [regularizers.identity for _ in range(len(layer.params))] <add> <add> if hasattr(layer, 'constraints'): <add> for c in layer.constraints: <add> if c: <add> self.constraints.append(c) <add> else: <add> self.constraints.append(constraints.identity) <add> elif hasattr(layer, 'constraint') and layer.constraint: <add> self.constraints += [layer.constraint for _ in range(len(layer.params))] <add> else: <add> self.constraints += [constraints.identity for _ in range(len(layer.params))] <add> <ide> <ide> def compile(self, optimizer, loss, class_mode="categorical"): <ide> self.optimizer = optimizers.get(optimizer) <ide> def compile(self, optimizer, loss, class_mode="categorical"): <ide> raise Exception("Invalid class mode:" + str(class_mode)) <ide> self.class_mode = class_mode <ide> <del> updates = self.optimizer.get_updates(self.params, self.regularizer, self.constraint, self.layers, train_loss) <add> updates = self.optimizer.get_updates(self.params, self.regularizers, self.constraints, train_loss) <ide> <ide> self._train = theano.function([self.X, self.y], train_loss, <ide> updates=updates, allow_input_downcast=True) <ide><path>keras/optimizers.py <ide> class Optimizer(object): <ide> def get_updates(self, params, grads): <ide> raise NotImplementedError <ide> <del> def get_gradients(self, cost, params, layers, regularizers): <del> for layer in layers: <del> if hasattr(layer, 'target') and layer.target > 0: <del> avg_act = T.mean(layer.output(train=True), axis=0) <del> kl_div = layer.beta*kl_divergence(layer.target, avg_act) <del> cost = cost + T.sum(kl_div) <add> def get_gradients(self, cost, params, regularizers): <add> # for layer in layers: <add> # if hasattr(layer, 'target') and layer.target > 0: <add> # avg_act = T.mean(layer.output(train=True), axis=0) <add> # kl_div = layer.beta*kl_divergence(layer.target, avg_act) <add> # cost = cost + T.sum(kl_div) <ide> <ide> grads = T.grad(cost, params) <ide> <ide> def get_gradients(self, cost, params, layers, regularizers): <ide> <ide> new_grads = [] <ide> for p, g, r in zip(params, grads, regularizers): <del> g = r(g,p) <add> g = r(g, p) <ide> new_grads.append(g) <ide> <ide> return new_grads <ide> <del> def update_params(self, params, new_params, updates, constraint): <del> new_params = constraint(new_params) <del> updates.append((params, new_params)) <del> return updates <del> <ide> <ide> class SGD(Optimizer): <ide> <ide> def __init__(self, lr=0.01, momentum=0., decay=0., nesterov=False, *args, **kwar <ide> self.__dict__.update(locals()) <ide> self.iterations = shared_scalar(0) <ide> <del> def get_updates(self, params, regularizers, constraints, layers, cost): <del> grads = self.get_gradients(cost, params, layers, regularizers) <add> def get_updates(self, params, regularizers, constraints, cost): <add> grads = self.get_gradients(cost, params, regularizers) <ide> lr = self.lr * (1.0 / (1.0 + self.decay * self.iterations)) <ide> updates = [(self.iterations, self.iterations+1.)] <ide> <ide> def get_updates(self, params, regularizers, constraints, layers, cost): <ide> else: <ide> new_p = p + v <ide> <del> self.update_params(p, new_p, updates, c) <add> updates.append((p, c(new_p))) # apply constraints <ide> return updates <ide> <ide> <ide> def __init__(self, lr=0.001, rho=0.9, epsilon=1e-6, *args, **kwargs): <ide> self.__dict__.update(kwargs) <ide> self.__dict__.update(locals()) <ide> <del> def get_updates(self, params, regularizers, constraints, layers, cost): <del> grads = self.get_gradients(cost, params, layers, regularizers) <add> def get_updates(self, params, regularizers, constraints, cost): <add> grads = self.get_gradients(cost, params, regularizers) <ide> accumulators = [shared_zeros(p.get_value().shape) for p in params] <ide> updates = [] <ide> <ide> def get_updates(self, params, regularizers, constraints, layers, cost): <ide> updates.append((a, new_a)) <ide> <ide> new_p = p - self.lr * g / T.sqrt(new_a + self.epsilon) <del> self.update_params(p, new_p, updates, c) <add> updates.append((p, c(new_p))) # apply constraints <add> <ide> return updates <ide> <ide> <ide> def __init__(self, lr=0.01, epsilon=1e-6, *args, **kwargs): <ide> self.__dict__.update(kwargs) <ide> self.__dict__.update(locals()) <ide> <del> def get_updates(self, params, regularizers, constraints, layers, cost): <del> grads = self.get_gradients(cost, params, layers, regularizers) <add> def get_updates(self, params, regularizers, constraints, cost): <add> grads = self.get_gradients(cost, params, regularizers) <ide> accumulators = [shared_zeros(p.get_value().shape) for p in params] <ide> updates = [] <ide> <ide> def get_updates(self, params, regularizers, constraints, layers, cost): <ide> updates.append((a, new_a)) <ide> <ide> new_p = p - self.lr * g / T.sqrt(new_a + self.epsilon) <del> self.update_params(p, new_p, updates, c) <add> updates.append((p, c(new_p))) # apply constraints <ide> return updates <ide> <ide> <ide> def __init__(self, lr=1.0, rho=0.95, epsilon=1e-6, *args, **kwargs): <ide> self.__dict__.update(kwargs) <ide> self.__dict__.update(locals()) <ide> <del> def get_updates(self, params, regularizers, constraints, layers, cost): <del> grads = self.get_gradients(cost, params, layers, regularizers) <add> def get_updates(self, params, regularizers, constraints, cost): <add> grads = self.get_gradients(cost, params, regularizers) <ide> accumulators = [shared_zeros(p.get_value().shape) for p in params] <ide> delta_accumulators = [shared_zeros(p.get_value().shape) for p in params] <ide> updates = [] <ide> def get_updates(self, params, regularizers, constraints, layers, cost): <ide> update = g * T.sqrt(d_a + self.epsilon) / T.sqrt(new_a + self.epsilon) <ide> <ide> new_p = p - self.lr * update <del> self.update_params(p, new_p, updates, c) <add> updates.append((p, c(new_p))) # apply constraints <ide> <ide> # update delta_accumulator <ide> new_d_a = self.rho * d_a + (1 - self.rho) * update ** 2 <ide> def __init__(self, lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-8, kappa=1-1e- <ide> self.__dict__.update(locals()) <ide> self.iterations = shared_scalar(0) <ide> <del> def get_updates(self, params, regularizers, constraints, layers, cost): <del> grads = self.get_gradients(cost, params, layers, regularizers) <add> def get_updates(self, params, regularizers, constraints, cost): <add> grads = self.get_gradients(cost, params, regularizers) <ide> updates = [(self.iterations, self.iterations+1.)] <ide> <ide> i = self.iterations <ide> def get_updates(self, params, regularizers, constraints, layers, cost): <ide> <ide> updates.append((m, m_t)) <ide> updates.append((v, v_t)) <del> self.update_params(p, p_t, updates, c) <add> updates.append((p, c(p_t))) # apply constraints <ide> return updates <ide> <ide> # aliases <ide><path>keras/regularizers.py <ide> import theano.tensor as T <ide> import numpy as np <ide> <del>def l1(lam=.01): <add>def l1(l=.01): <ide> def l1wrap(g,p): <del> g += T.sgn(p) * lam <add> g += T.sgn(p) * l <ide> return g <ide> return l1wrap <ide> <del>def l2(lam=.01): <add>def l2(l=.01): <ide> def l2wrap(g,p): <del> g += p * lam <add> g += p * l <ide> return g <ide> return l2wrap <ide> <del>def identity(g,*l): <add>def identity(g, p): <ide> return g <ide>\ No newline at end of file
5
Java
Java
use reactmarker for all perf logging in the bridge
95073f8589d893ad25af07e0d0ac6b7c379af9b3
<ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/ReactMarkerConstants.java <ide> public enum ReactMarkerConstants { <ide> PROCESS_PACKAGES_END, <ide> BUILD_NATIVE_MODULE_REGISTRY_START, <ide> BUILD_NATIVE_MODULE_REGISTRY_END, <del> BUILD_JS_MODULE_CONFIG_START, <del> BUILD_JS_MODULE_CONFIG_END, <ide> CREATE_CATALYST_INSTANCE_START, <ide> CREATE_CATALYST_INSTANCE_END, <ide> RUN_JS_BUNDLE_START, <ide> public enum ReactMarkerConstants { <ide> CREATE_MODULE_END, <ide> PROCESS_CORE_REACT_PACKAGE_START, <ide> PROCESS_CORE_REACT_PACKAGE_END, <del> UI_MANAGER_MODULE_CONSTANTS_CONVERT_START, <del> UI_MANAGER_MODULE_CONSTANTS_CONVERT_END, <ide> CREATE_I18N_MODULE_CONSTANTS_START, <ide> CREATE_I18N_MODULE_CONSTANTS_END, <ide> I18N_MODULE_CONSTANTS_CONVERT_START, <ide> public enum ReactMarkerConstants { <ide> CONVERT_CONSTANTS_START, <ide> CONVERT_CONSTANTS_END, <ide> PRE_REACT_CONTEXT_END, <del> UNPACKER_CHECK_START, <del> UNPACKER_CHECK_END, <del> UNPACKER_BUNDLE_EXTRACTED, <ide> UNPACKING_JS_BUNDLE_LOADER_CHECK_START, <ide> UNPACKING_JS_BUNDLE_LOADER_CHECK_END, <ide> UNPACKING_JS_BUNDLE_LOADER_EXTRACTED, <ide> public enum ReactMarkerConstants { <ide> DOWNLOAD_END, <ide> REACT_CONTEXT_THREAD_START, <ide> REACT_CONTEXT_THREAD_END, <add> GET_REACT_INSTANCE_MANAGER_START, <add> GET_REACT_INSTANCE_MANAGER_END, <add> GET_REACT_INSTANCE_HOLDER_SPEC_START, <add> GET_REACT_INSTANCE_HOLDER_SPEC_END, <add> BUILD_REACT_INSTANCE_MANAGER_START, <add> BUILD_REACT_INSTANCE_MANAGER_END, <add> PROCESS_INFRA_PACKAGE_START, <add> PROCESS_INFRA_PACKAGE_END, <add> PROCESS_PRODUCT_PACKAGE_START, <add> PROCESS_PRODUCT_PACKAGE_END, <add> CREATE_MC_MODULE_START, <add> CREATE_MC_MODULE_END, <add> CREATE_MC_MODULE_GET_METADATA_START, <add> CREATE_MC_MODULE_GET_METADATA_END, <ide> }
1
Javascript
Javascript
add stubs for methods that may not be implemented
69d1e7f5aab8afecd10500c158a9f954cb5e8065
<ide><path>packages/sproutcore-touch/lib/system/gesture.js <ide> SC.Gesture = SC.Object.extend( <ide> <ide> touchEnd: function(evt, view, manager) { <ide> if (get(this, 'gestureIsDiscrete')) { <add> <ide> if (this.state === SC.Gesture.BEGAN && this.gestureShouldEnd()) { <ide> set(this, 'state', SC.Gesture.ENDED); <ide> this.attemptGestureEventDelivery(evt, view, get(this, 'name')+'End'); <add> <ide> } else { <ide> set(this, 'state', SC.Gesture.CANCELLED); <ide> this.attemptGestureEventDelivery(evt, view, get(this, 'name')+'Cancel'); <ide> } <ide> } else { <add> <ide> if (this.state !== SC.Gesture.ENDED) { <ide> this._resetState(); <ide> set(this, 'state', SC.Gesture.ENDED); <ide> SC.Gesture = SC.Object.extend( <ide> } <ide> }, <ide> <del> gestureBecamePossible: function() {}, <del> gestureChanged: function() {}, <del> <ide> gestureShouldBegin: function() { <ide> return true; <ide> }, <ide> <add> gestureBecamePossible: function() { <add> <add> }, <add> <add> gestureChanged: function() { <add> <add> }, <add> <add> <ide> gestureShouldEnd: function() { <ide> return true; <ide> },
1
Text
Text
fix typo in fs
1798674bc99b57f882768ec7bc883c9518350e15
<ide><path>doc/api/fs.md <ide> a string, a {Buffer}, or a {URL} object using the `file:` protocol. <ide> <ide> #### String paths <ide> <del>String from paths are interpreted as UTF-8 character sequences identifying <add>String paths are interpreted as UTF-8 character sequences identifying <ide> the absolute or relative filename. Relative paths will be resolved relative <ide> to the current working directory as determined by calling `process.cwd()`. <ide>
1
Python
Python
change realm checkpoint to new ones
3385ca2582f47239efbc7fc45b044d02ff60f736
<ide><path>src/transformers/models/realm/configuration_realm.py <ide> logger = logging.get_logger(__name__) <ide> <ide> REALM_PRETRAINED_CONFIG_ARCHIVE_MAP = { <del> "qqaatw/realm-cc-news-pretrained-embedder": "https://huggingface.co/qqaatw/realm-cc-news-pretrained-embedder/resolve/main/config.json", <del> "qqaatw/realm-cc-news-pretrained-encoder": "https://huggingface.co/qqaatw/realm-cc-news-pretrained-encoder/resolve/main/config.json", <del> "qqaatw/realm-cc-news-pretrained-scorer": "https://huggingface.co/qqaatw/realm-cc-news-pretrained-scorer/resolve/main/config.json", <del> "qqaatw/realm-cc-news-pretrained-openqa": "https://huggingface.co/qqaatw/realm-cc-news-pretrained-openqa/aresolve/main/config.json", <del> "qqaatw/realm-orqa-nq-openqa": "https://huggingface.co/qqaatw/realm-orqa-nq-openqa/resolve/main/config.json", <del> "qqaatw/realm-orqa-nq-reader": "https://huggingface.co/qqaatw/realm-orqa-nq-reader/resolve/main/config.json", <del> "qqaatw/realm-orqa-wq-openqa": "https://huggingface.co/qqaatw/realm-orqa-wq-openqa/resolve/main/config.json", <del> "qqaatw/realm-orqa-wq-reader": "https://huggingface.co/qqaatw/realm-orqa-wq-reader/resolve/main/config.json", <add> "google/realm-cc-news-pretrained-embedder": "https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/config.json", <add> "google/realm-cc-news-pretrained-encoder": "https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/config.json", <add> "google/realm-cc-news-pretrained-scorer": "https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/config.json", <add> "google/realm-cc-news-pretrained-openqa": "https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/config.json", <add> "google/realm-orqa-nq-openqa": "https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/config.json", <add> "google/realm-orqa-nq-reader": "https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/config.json", <add> "google/realm-orqa-wq-openqa": "https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/config.json", <add> "google/realm-orqa-wq-reader": "https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/config.json", <ide> # See all REALM models at https://huggingface.co/models?filter=realm <ide> } <ide> <ide> class RealmConfig(PretrainedConfig): <ide> <ide> It is used to instantiate an REALM model according to the specified arguments, defining the model architecture. <ide> Instantiating a configuration with the defaults will yield a similar configuration to that of the REALM <del> [realm-cc-news-pretrained](https://huggingface.co/qqaatw/realm-cc-news-pretrained-embedder) architecture. <add> [realm-cc-news-pretrained](https://huggingface.co/google/realm-cc-news-pretrained-embedder) architecture. <ide> <ide> Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the <ide> documentation from [`PretrainedConfig`] for more information. <ide> class RealmConfig(PretrainedConfig): <ide> >>> # Initializing a REALM realm-cc-news-pretrained-* style configuration <ide> >>> configuration = RealmConfig() <ide> <del> >>> # Initializing a model from the qqaatw/realm-cc-news-pretrained-embedder style configuration <add> >>> # Initializing a model from the google/realm-cc-news-pretrained-embedder style configuration <ide> >>> model = RealmEmbedder(configuration) <ide> <ide> >>> # Accessing the model configuration <ide><path>src/transformers/models/realm/modeling_realm.py <ide> <ide> <ide> logger = logging.get_logger(__name__) <del>_EMBEDDER_CHECKPOINT_FOR_DOC = "qqaatw/realm-cc-news-pretrained-embedder" <del>_ENCODER_CHECKPOINT_FOR_DOC = "qqaatw/realm-cc-news-pretrained-encoder" <del>_SCORER_CHECKPOINT_FOR_DOC = "qqaatw/realm-cc-news-pretrained-scorer" <add>_EMBEDDER_CHECKPOINT_FOR_DOC = "google/realm-cc-news-pretrained-embedder" <add>_ENCODER_CHECKPOINT_FOR_DOC = "google/realm-cc-news-pretrained-encoder" <add>_SCORER_CHECKPOINT_FOR_DOC = "google/realm-cc-news-pretrained-scorer" <ide> _CONFIG_FOR_DOC = "RealmConfig" <ide> _TOKENIZER_FOR_DOC = "RealmTokenizer" <ide> <ide> REALM_PRETRAINED_MODEL_ARCHIVE_LIST = [ <del> "qqaatw/realm-cc-news-pretrained-embedder", <del> "qqaatw/realm-cc-news-pretrained-encoder", <del> "qqaatw/realm-cc-news-pretrained-scorer", <del> "qqaatw/realm-cc-news-pretrained-openqa", <del> "qqaatw/realm-orqa-nq-openqa", <del> "qqaatw/realm-orqa-nq-reader", <del> "qqaatw/realm-orqa-wq-openqa", <del> "qqaatw/realm-orqa-wq-reader", <add> "google/realm-cc-news-pretrained-embedder", <add> "google/realm-cc-news-pretrained-encoder", <add> "google/realm-cc-news-pretrained-scorer", <add> "google/realm-cc-news-pretrained-openqa", <add> "google/realm-orqa-nq-openqa", <add> "google/realm-orqa-nq-reader", <add> "google/realm-orqa-wq-openqa", <add> "google/realm-orqa-wq-reader", <ide> # See all REALM models at https://huggingface.co/models?filter=realm <ide> ] <ide> <ide> def forward( <ide> >>> from transformers import RealmTokenizer, RealmEmbedder <ide> >>> import torch <ide> <del> >>> tokenizer = RealmTokenizer.from_pretrained("qqaatw/realm-cc-news-pretrained-embedder") <del> >>> model = RealmEmbedder.from_pretrained("qqaatw/realm-cc-news-pretrained-embedder") <add> >>> tokenizer = RealmTokenizer.from_pretrained("google/realm-cc-news-pretrained-embedder") <add> >>> model = RealmEmbedder.from_pretrained("google/realm-cc-news-pretrained-embedder") <ide> <ide> >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") <ide> >>> outputs = model(**inputs) <ide> def forward( <ide> >>> import torch <ide> >>> from transformers import RealmTokenizer, RealmScorer <ide> <del> >>> tokenizer = RealmTokenizer.from_pretrained("qqaatw/realm-cc-news-pretrained-scorer") <del> >>> model = RealmScorer.from_pretrained("qqaatw/realm-cc-news-pretrained-scorer", num_candidates=2) <add> >>> tokenizer = RealmTokenizer.from_pretrained("google/realm-cc-news-pretrained-scorer") <add> >>> model = RealmScorer.from_pretrained("google/realm-cc-news-pretrained-scorer", num_candidates=2) <ide> <ide> >>> # batch_size = 2, num_candidates = 2 <ide> >>> input_texts = ["How are you?", "What is the item in the picture?"] <ide> def forward( <ide> >>> import torch <ide> >>> from transformers import RealmTokenizer, RealmKnowledgeAugEncoder <ide> <del> >>> tokenizer = RealmTokenizer.from_pretrained("qqaatw/realm-cc-news-pretrained-encoder") <add> >>> tokenizer = RealmTokenizer.from_pretrained("google/realm-cc-news-pretrained-encoder") <ide> >>> model = RealmKnowledgeAugEncoder.from_pretrained( <del> ... "qqaatw/realm-cc-news-pretrained-encoder", num_candidates=2 <add> ... "google/realm-cc-news-pretrained-encoder", num_candidates=2 <ide> ... ) <ide> <ide> >>> # batch_size = 2, num_candidates = 2 <ide> def forward( <ide> >>> import torch <ide> >>> from transformers import RealmForOpenQA, RealmRetriever, RealmTokenizer <ide> <del> >>> retriever = RealmRetriever.from_pretrained("qqaatw/realm-orqa-nq-openqa") <del> >>> tokenizer = RealmTokenizer.from_pretrained("qqaatw/realm-orqa-nq-openqa") <del> >>> model = RealmForOpenQA.from_pretrained("qqaatw/realm-orqa-nq-openqa", retriever=retriever) <add> >>> retriever = RealmRetriever.from_pretrained("google/realm-orqa-nq-openqa") <add> >>> tokenizer = RealmTokenizer.from_pretrained("google/realm-orqa-nq-openqa") <add> >>> model = RealmForOpenQA.from_pretrained("google/realm-orqa-nq-openqa", retriever=retriever) <ide> <ide> >>> question = "Who is the pioneer in modern computer science?" <ide> >>> question_ids = tokenizer([question], return_tensors="pt") <ide><path>src/transformers/models/realm/tokenization_realm.py <ide> <ide> PRETRAINED_VOCAB_FILES_MAP = { <ide> "vocab_file": { <del> "qqaatw/realm-cc-news-pretrained-embedder": "https://huggingface.co/qqaatw/realm-cc-news-pretrained-embedder/resolve/main/vocab.txt", <del> "qqaatw/realm-cc-news-pretrained-encoder": "https://huggingface.co/qqaatw/realm-cc-news-pretrained-encoder/resolve/main/vocab.txt", <del> "qqaatw/realm-cc-news-pretrained-scorer": "https://huggingface.co/qqaatw/realm-cc-news-pretrained-scorer/resolve/main/vocab.txt", <del> "qqaatw/realm-cc-news-pretrained-openqa": "https://huggingface.co/qqaatw/realm-cc-news-pretrained-openqa/aresolve/main/vocab.txt", <del> "qqaatw/realm-orqa-nq-openqa": "https://huggingface.co/qqaatw/realm-orqa-nq-openqa/resolve/main/vocab.txt", <del> "qqaatw/realm-orqa-nq-reader": "https://huggingface.co/qqaatw/realm-orqa-nq-reader/resolve/main/vocab.txt", <del> "qqaatw/realm-orqa-wq-openqa": "https://huggingface.co/qqaatw/realm-orqa-wq-openqa/resolve/main/vocab.txt", <del> "qqaatw/realm-orqa-wq-reader": "https://huggingface.co/qqaatw/realm-orqa-wq-reader/resolve/main/vocab.txt", <add> "google/realm-cc-news-pretrained-embedder": "https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/vocab.txt", <add> "google/realm-cc-news-pretrained-encoder": "https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/vocab.txt", <add> "google/realm-cc-news-pretrained-scorer": "https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/vocab.txt", <add> "google/realm-cc-news-pretrained-openqa": "https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/vocab.txt", <add> "google/realm-orqa-nq-openqa": "https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/vocab.txt", <add> "google/realm-orqa-nq-reader": "https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/vocab.txt", <add> "google/realm-orqa-wq-openqa": "https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/vocab.txt", <add> "google/realm-orqa-wq-reader": "https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/vocab.txt", <ide> } <ide> } <ide> <ide> PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = { <del> "qqaatw/realm-cc-news-pretrained-embedder": 512, <del> "qqaatw/realm-cc-news-pretrained-encoder": 512, <del> "qqaatw/realm-cc-news-pretrained-scorer": 512, <del> "qqaatw/realm-cc-news-pretrained-openqa": 512, <del> "qqaatw/realm-orqa-nq-openqa": 512, <del> "qqaatw/realm-orqa-nq-reader": 512, <del> "qqaatw/realm-orqa-wq-openqa": 512, <del> "qqaatw/realm-orqa-wq-reader": 512, <add> "google/realm-cc-news-pretrained-embedder": 512, <add> "google/realm-cc-news-pretrained-encoder": 512, <add> "google/realm-cc-news-pretrained-scorer": 512, <add> "google/realm-cc-news-pretrained-openqa": 512, <add> "google/realm-orqa-nq-openqa": 512, <add> "google/realm-orqa-nq-reader": 512, <add> "google/realm-orqa-wq-openqa": 512, <add> "google/realm-orqa-wq-reader": 512, <ide> } <ide> <ide> PRETRAINED_INIT_CONFIGURATION = { <del> "qqaatw/realm-cc-news-pretrained-embedder": {"do_lower_case": True}, <del> "qqaatw/realm-cc-news-pretrained-encoder": {"do_lower_case": True}, <del> "qqaatw/realm-cc-news-pretrained-scorer": {"do_lower_case": True}, <del> "qqaatw/realm-cc-news-pretrained-openqa": {"do_lower_case": True}, <del> "qqaatw/realm-orqa-nq-openqa": {"do_lower_case": True}, <del> "qqaatw/realm-orqa-nq-reader": {"do_lower_case": True}, <del> "qqaatw/realm-orqa-wq-openqa": {"do_lower_case": True}, <del> "qqaatw/realm-orqa-wq-reader": {"do_lower_case": True}, <add> "google/realm-cc-news-pretrained-embedder": {"do_lower_case": True}, <add> "google/realm-cc-news-pretrained-encoder": {"do_lower_case": True}, <add> "google/realm-cc-news-pretrained-scorer": {"do_lower_case": True}, <add> "google/realm-cc-news-pretrained-openqa": {"do_lower_case": True}, <add> "google/realm-orqa-nq-openqa": {"do_lower_case": True}, <add> "google/realm-orqa-nq-reader": {"do_lower_case": True}, <add> "google/realm-orqa-wq-openqa": {"do_lower_case": True}, <add> "google/realm-orqa-wq-reader": {"do_lower_case": True}, <ide> } <ide> <ide> <ide> def batch_encode_candidates(self, text, **kwargs): <ide> >>> # batch_size = 2, num_candidates = 2 <ide> >>> text = [["Hello world!", "Nice to meet you!"], ["The cute cat.", "The adorable dog."]] <ide> <del> >>> tokenizer = RealmTokenizer.from_pretrained("qqaatw/realm-cc-news-pretrained-encoder") <add> >>> tokenizer = RealmTokenizer.from_pretrained("google/realm-cc-news-pretrained-encoder") <ide> >>> tokenized_text = tokenizer.batch_encode_candidates(text, max_length=10, return_tensors="pt") <ide> ```""" <ide> <ide><path>src/transformers/models/realm/tokenization_realm_fast.py <ide> <ide> PRETRAINED_VOCAB_FILES_MAP = { <ide> "vocab_file": { <del> "qqaatw/realm-cc-news-pretrained-embedder": "https://huggingface.co/qqaatw/realm-cc-news-pretrained-embedder/resolve/main/vocab.txt", <del> "qqaatw/realm-cc-news-pretrained-encoder": "https://huggingface.co/qqaatw/realm-cc-news-pretrained-encoder/resolve/main/vocab.txt", <del> "qqaatw/realm-cc-news-pretrained-scorer": "https://huggingface.co/qqaatw/realm-cc-news-pretrained-scorer/resolve/main/vocab.txt", <del> "qqaatw/realm-cc-news-pretrained-openqa": "https://huggingface.co/qqaatw/realm-cc-news-pretrained-openqa/aresolve/main/vocab.txt", <del> "qqaatw/realm-orqa-nq-openqa": "https://huggingface.co/qqaatw/realm-orqa-nq-openqa/resolve/main/vocab.txt", <del> "qqaatw/realm-orqa-nq-reader": "https://huggingface.co/qqaatw/realm-orqa-nq-reader/resolve/main/vocab.txt", <del> "qqaatw/realm-orqa-wq-openqa": "https://huggingface.co/qqaatw/realm-orqa-wq-openqa/resolve/main/vocab.txt", <del> "qqaatw/realm-orqa-wq-reader": "https://huggingface.co/qqaatw/realm-orqa-wq-reader/resolve/main/vocab.txt", <add> "google/realm-cc-news-pretrained-embedder": "https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/vocab.txt", <add> "google/realm-cc-news-pretrained-encoder": "https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/vocab.txt", <add> "google/realm-cc-news-pretrained-scorer": "https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/vocab.txt", <add> "google/realm-cc-news-pretrained-openqa": "https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/vocab.txt", <add> "google/realm-orqa-nq-openqa": "https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/vocab.txt", <add> "google/realm-orqa-nq-reader": "https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/vocab.txt", <add> "google/realm-orqa-wq-openqa": "https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/vocab.txt", <add> "google/realm-orqa-wq-reader": "https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/vocab.txt", <ide> }, <ide> "tokenizer_file": { <del> "qqaatw/realm-cc-news-pretrained-embedder": "https://huggingface.co/qqaatw/realm-cc-news-pretrained-embedder/resolve/main/tokenizer.jsont", <del> "qqaatw/realm-cc-news-pretrained-encoder": "https://huggingface.co/qqaatw/realm-cc-news-pretrained-encoder/resolve/main/tokenizer.json", <del> "qqaatw/realm-cc-news-pretrained-scorer": "https://huggingface.co/qqaatw/realm-cc-news-pretrained-scorer/resolve/main/tokenizer.json", <del> "qqaatw/realm-cc-news-pretrained-openqa": "https://huggingface.co/qqaatw/realm-cc-news-pretrained-openqa/aresolve/main/tokenizer.json", <del> "qqaatw/realm-orqa-nq-openqa": "https://huggingface.co/qqaatw/realm-orqa-nq-openqa/resolve/main/tokenizer.json", <del> "qqaatw/realm-orqa-nq-reader": "https://huggingface.co/qqaatw/realm-orqa-nq-reader/resolve/main/tokenizer.json", <del> "qqaatw/realm-orqa-wq-openqa": "https://huggingface.co/qqaatw/realm-orqa-wq-openqa/resolve/main/tokenizer.json", <del> "qqaatw/realm-orqa-wq-reader": "https://huggingface.co/qqaatw/realm-orqa-wq-reader/resolve/main/tokenizer.json", <add> "google/realm-cc-news-pretrained-embedder": "https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/tokenizer.jsont", <add> "google/realm-cc-news-pretrained-encoder": "https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/tokenizer.json", <add> "google/realm-cc-news-pretrained-scorer": "https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/tokenizer.json", <add> "google/realm-cc-news-pretrained-openqa": "https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/tokenizer.json", <add> "google/realm-orqa-nq-openqa": "https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/tokenizer.json", <add> "google/realm-orqa-nq-reader": "https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/tokenizer.json", <add> "google/realm-orqa-wq-openqa": "https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/tokenizer.json", <add> "google/realm-orqa-wq-reader": "https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/tokenizer.json", <ide> }, <ide> } <ide> <ide> PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = { <del> "qqaatw/realm-cc-news-pretrained-embedder": 512, <del> "qqaatw/realm-cc-news-pretrained-encoder": 512, <del> "qqaatw/realm-cc-news-pretrained-scorer": 512, <del> "qqaatw/realm-cc-news-pretrained-openqa": 512, <del> "qqaatw/realm-orqa-nq-openqa": 512, <del> "qqaatw/realm-orqa-nq-reader": 512, <del> "qqaatw/realm-orqa-wq-openqa": 512, <del> "qqaatw/realm-orqa-wq-reader": 512, <add> "google/realm-cc-news-pretrained-embedder": 512, <add> "google/realm-cc-news-pretrained-encoder": 512, <add> "google/realm-cc-news-pretrained-scorer": 512, <add> "google/realm-cc-news-pretrained-openqa": 512, <add> "google/realm-orqa-nq-openqa": 512, <add> "google/realm-orqa-nq-reader": 512, <add> "google/realm-orqa-wq-openqa": 512, <add> "google/realm-orqa-wq-reader": 512, <ide> } <ide> <ide> PRETRAINED_INIT_CONFIGURATION = { <del> "qqaatw/realm-cc-news-pretrained-embedder": {"do_lower_case": True}, <del> "qqaatw/realm-cc-news-pretrained-encoder": {"do_lower_case": True}, <del> "qqaatw/realm-cc-news-pretrained-scorer": {"do_lower_case": True}, <del> "qqaatw/realm-cc-news-pretrained-openqa": {"do_lower_case": True}, <del> "qqaatw/realm-orqa-nq-openqa": {"do_lower_case": True}, <del> "qqaatw/realm-orqa-nq-reader": {"do_lower_case": True}, <del> "qqaatw/realm-orqa-wq-openqa": {"do_lower_case": True}, <del> "qqaatw/realm-orqa-wq-reader": {"do_lower_case": True}, <add> "google/realm-cc-news-pretrained-embedder": {"do_lower_case": True}, <add> "google/realm-cc-news-pretrained-encoder": {"do_lower_case": True}, <add> "google/realm-cc-news-pretrained-scorer": {"do_lower_case": True}, <add> "google/realm-cc-news-pretrained-openqa": {"do_lower_case": True}, <add> "google/realm-orqa-nq-openqa": {"do_lower_case": True}, <add> "google/realm-orqa-nq-reader": {"do_lower_case": True}, <add> "google/realm-orqa-wq-openqa": {"do_lower_case": True}, <add> "google/realm-orqa-wq-reader": {"do_lower_case": True}, <ide> } <ide> <ide> <ide> def batch_encode_candidates(self, text, **kwargs): <ide> >>> # batch_size = 2, num_candidates = 2 <ide> >>> text = [["Hello world!", "Nice to meet you!"], ["The cute cat.", "The adorable dog."]] <ide> <del> >>> tokenizer = RealmTokenizerFast.from_pretrained("qqaatw/realm-cc-news-pretrained-encoder") <add> >>> tokenizer = RealmTokenizerFast.from_pretrained("google/realm-cc-news-pretrained-encoder") <ide> >>> tokenized_text = tokenizer.batch_encode_candidates(text, max_length=10, return_tensors="pt") <ide> ```""" <ide> <ide><path>tests/test_modeling_realm.py <ide> def test_training(self): <ide> input_ids, token_type_ids, input_mask, scorer_encoder_inputs = inputs[0:4] <ide> config.return_dict = True <ide> <del> tokenizer = RealmTokenizer.from_pretrained("qqaatw/realm-orqa-nq-openqa") <add> tokenizer = RealmTokenizer.from_pretrained("google/realm-orqa-nq-openqa") <ide> <ide> # RealmKnowledgeAugEncoder training <ide> model = RealmKnowledgeAugEncoder(config) <ide> def test_training(self): <ide> <ide> @slow <ide> def test_embedder_from_pretrained(self): <del> model = RealmEmbedder.from_pretrained("qqaatw/realm-cc-news-pretrained-embedder") <add> model = RealmEmbedder.from_pretrained("google/realm-cc-news-pretrained-embedder") <ide> self.assertIsNotNone(model) <ide> <ide> @slow <ide> def test_encoder_from_pretrained(self): <del> model = RealmKnowledgeAugEncoder.from_pretrained("qqaatw/realm-cc-news-pretrained-encoder") <add> model = RealmKnowledgeAugEncoder.from_pretrained("google/realm-cc-news-pretrained-encoder") <ide> self.assertIsNotNone(model) <ide> <ide> @slow <ide> def test_open_qa_from_pretrained(self): <del> model = RealmForOpenQA.from_pretrained("qqaatw/realm-orqa-nq-openqa") <add> model = RealmForOpenQA.from_pretrained("google/realm-orqa-nq-openqa") <ide> self.assertIsNotNone(model) <ide> <ide> @slow <ide> def test_reader_from_pretrained(self): <del> model = RealmReader.from_pretrained("qqaatw/realm-orqa-nq-reader") <add> model = RealmReader.from_pretrained("google/realm-orqa-nq-reader") <ide> self.assertIsNotNone(model) <ide> <ide> @slow <ide> def test_scorer_from_pretrained(self): <del> model = RealmScorer.from_pretrained("qqaatw/realm-cc-news-pretrained-scorer") <add> model = RealmScorer.from_pretrained("google/realm-cc-news-pretrained-scorer") <ide> self.assertIsNotNone(model) <ide> <ide> <ide> class RealmModelIntegrationTest(unittest.TestCase): <ide> def test_inference_embedder(self): <ide> retriever_projected_size = 128 <ide> <del> model = RealmEmbedder.from_pretrained("qqaatw/realm-cc-news-pretrained-embedder") <add> model = RealmEmbedder.from_pretrained("google/realm-cc-news-pretrained-embedder") <ide> input_ids = torch.tensor([[0, 1, 2, 3, 4, 5]]) <ide> output = model(input_ids)[0] <ide> <ide> def test_inference_encoder(self): <ide> vocab_size = 30522 <ide> <ide> model = RealmKnowledgeAugEncoder.from_pretrained( <del> "qqaatw/realm-cc-news-pretrained-encoder", num_candidates=num_candidates <add> "google/realm-cc-news-pretrained-encoder", num_candidates=num_candidates <ide> ) <ide> input_ids = torch.tensor([[0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]]) <ide> relevance_score = torch.tensor([[0.3, 0.7]], dtype=torch.float32) <ide> def test_inference_open_qa(self): <ide> <ide> config = RealmConfig() <ide> <del> tokenizer = RealmTokenizer.from_pretrained("qqaatw/realm-orqa-nq-openqa") <del> retriever = RealmRetriever.from_pretrained("qqaatw/realm-orqa-nq-openqa") <add> tokenizer = RealmTokenizer.from_pretrained("google/realm-orqa-nq-openqa") <add> retriever = RealmRetriever.from_pretrained("google/realm-orqa-nq-openqa") <ide> <ide> model = RealmForOpenQA.from_pretrained( <del> "qqaatw/realm-orqa-nq-openqa", <add> "google/realm-orqa-nq-openqa", <ide> retriever=retriever, <ide> config=config, <ide> ) <ide> def test_inference_open_qa(self): <ide> @slow <ide> def test_inference_reader(self): <ide> config = RealmConfig(reader_beam_size=2, max_span_width=3) <del> model = RealmReader.from_pretrained("qqaatw/realm-orqa-nq-reader", config=config) <add> model = RealmReader.from_pretrained("google/realm-orqa-nq-reader", config=config) <ide> <ide> concat_input_ids = torch.arange(10).view((2, 5)) <ide> concat_token_type_ids = torch.tensor([[0, 0, 1, 1, 1], [0, 0, 1, 1, 1]], dtype=torch.int64) <ide> def test_inference_reader(self): <ide> def test_inference_scorer(self): <ide> num_candidates = 2 <ide> <del> model = RealmScorer.from_pretrained("qqaatw/realm-cc-news-pretrained-scorer", num_candidates=num_candidates) <add> model = RealmScorer.from_pretrained("google/realm-cc-news-pretrained-scorer", num_candidates=num_candidates) <ide> <ide> input_ids = torch.tensor([[0, 1, 2, 3, 4, 5]]) <ide> candidate_input_ids = torch.tensor([[0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]]) <ide><path>tests/test_retrieval_realm.py <ide> def test_save_load_pretrained(self): <ide> mock_hf_hub_download.return_value = os.path.join( <ide> os.path.join(self.tmpdirname, "realm_block_records"), _REALM_BLOCK_RECORDS_FILENAME <ide> ) <del> retriever = RealmRetriever.from_pretrained("qqaatw/realm-cc-news-pretrained-openqa") <add> retriever = RealmRetriever.from_pretrained("google/realm-cc-news-pretrained-openqa") <ide> <ide> self.assertEqual(retriever.block_records[0], b"This is the first record")
6
Text
Text
remove wrong reference in changelog
434a82cfecb82453ebccd1f0160b56dd704a6c4c
<ide><path>CHANGELOG-5.5.md <ide> ## v5.5.31 (2018-01-16) <ide> <ide> ### Fixed <del>- Reverted [#22804](https://github.com/laravel/framework/pull/22804) ([d8a8368](https://github.com/laravel/framework/commit/d8a8368e15e73de50b91b903f6b933c7d05b0e28), [f34926c](https://github.com/laravel/framework/commit/f34926c52ba282ff67f4be3e9afc8d0ddc885c3f), [#22817](https://github.com/laravel/framework/pull/22817)) <add>- Reverted [#22804](https://github.com/laravel/framework/pull/22804) ([d8a8368](https://github.com/laravel/framework/commit/d8a8368e15e73de50b91b903f6b933c7d05b0e28), [f34926c](https://github.com/laravel/framework/commit/f34926c52ba282ff67f4be3e9afc8d0ddc885c3f)) <ide> <ide> <ide> ## v5.5.30 (2018-01-16)
1
PHP
PHP
add extra assertion to the unit test
41d562557ae561863f3af4302ea032d5cb990f55
<ide><path>tests/TestCase/Database/DriverTest.php <ide> public function testNewCompiler() <ide> */ <ide> public function testNewTableSchema() <ide> { <del> $actual = $this->driver->newTableSchema('articles'); <add> $tableName = 'articles'; <add> $actual = $this->driver->newTableSchema($tableName); <ide> $this->assertInstanceOf(TableSchema::class, $actual); <add> $this->assertEquals($tableName, $actual->name()); <ide> } <ide> <ide> /**
1
Javascript
Javascript
add benchmark for node_v8_coverage
8c9dc4e9e65af92c9b66bbbe1b001430d9110cd9
<ide><path>benchmark/fixtures/coverage-many-branches.js <add>'use strict'; <add> <add>// Exercise coverage of a class. Note, this logic is silly and exists solely <add>// to generate branch coverage code paths: <add>class CoveredClass { <add> constructor(x, y, opts) { <add> this.x = x; <add> this.y = y; <add> // Exercise coverage of nullish coalescing: <add> this.opts = opts ?? (Math.random() > 0.5 ? {} : undefined); <add> } <add> add() { <add> return this.x + this.y; <add> } <add> addSpecial() { <add> // Exercise coverage of optional chains: <add> if (this.opts?.special && this.opts?.special?.x && this.opts?.special?.y) { <add> return this.opts.special.x + this.opts.special.y; <add> } <add> return add(); <add> } <add> mult() { <add> return this.x * this.y; <add> } <add> multSpecial() { <add> if (this.opts?.special && this.opts?.special?.x && this.opts?.special?.y) { <add> return this.opts.special.x * this.opts.special.y; <add> } <add> return mult(); <add> } <add>} <add> <add>// Excercise coverage of functions: <add>function add(x, y) { <add> const mt = new CoveredClass(x, y); <add> return mt.add(); <add>} <add> <add>function addSpecial(x, y) { <add> let mt; <add> if (Math.random() > 0.5) { <add> mt = new CoveredClass(x, y); <add> } else { <add> mt = new CoveredClass(x, y, { <add> special: { <add> x: Math.random() * x, <add> y: Math.random() * y <add> } <add> }); <add> } <add> return mt.addSpecial(); <add>} <add> <add>function mult(x, y) { <add> const mt = new CoveredClass(x, y); <add> return mt.mult(); <add>} <add> <add>function multSpecial(x, y) { <add> let mt; <add> if (Math.random() > 0.5) { <add> mt = new CoveredClass(x, y); <add> } else { <add> mt = new CoveredClass(x, y, { <add> special: { <add> x: Math.random() * x, <add> y: Math.random() * y <add> } <add> }); <add> } <add> return mt.multSpecial(); <add>} <add> <add>for (let i = 0; i < parseInt(process.env.N); i++) { <add> const operations = ['add', 'addSpecial', 'mult', 'multSpecial']; <add> for (const operation of operations) { <add> // Exercise coverage of switch statements: <add> switch (operation) { <add> case 'add': <add> if (add(Math.random() * 10, Math.random() * 10) > 10) { <add> // Exercise coverage of ternary operations: <add> let r = addSpecial(Math.random() * 10, Math.random() * 10) > 10 ? <add> mult(Math.random() * 10, Math.random() * 10) : <add> add(Math.random() * 10, Math.random() * 10); <add> // Exercise && and || <add> if (r && Math.random() > 0.5 || Math.random() < 0.5) r++; <add> } <add> break; <add> case 'addSpecial': <add> if (addSpecial(Math.random() * 10, Math.random() * 10) > 10 && <add> add(Math.random() * 10, Math.random() * 10) > 10) { <add> let r = mult(Math.random() * 10, Math.random() * 10) > 10 ? <add> add(Math.random() * 10, Math.random() * 10) > 10 : <add> mult(Math.random() * 10, Math.random() * 10); <add> if (r && Math.random() > 0.5 || Math.random() < 0.5) r++; <add> } <add> break; <add> case 'mult': <add> if (mult(Math.random() * 10, Math.random() * 10) > 10) { <add> let r = multSpecial(Math.random() * 10, Math.random() * 10) > 10 ? <add> add(Math.random() * 10, Math.random() * 10) : <add> mult(Math.random() * 10, Math.random() * 10); <add> if (r && Math.random() > 0.5 || Math.random() < 0.5) r++; <add> } <add> break; <add> case 'multSpecial': <add> while (multSpecial(Math.random() * 10, Math.random() * 10) < 10) { <add> mult(Math.random() * 10, Math.random() * 10); <add> } <add> break; <add> default: <add> break; <add> } <add> } <add>} <ide><path>benchmark/process/coverage.js <add>// This benchmark is meant to exercise a grab bag of code paths that would <add>// be expected to run slower under coverage. <add>'use strict'; <add> <add>const common = require('../common.js'); <add>const bench = common.createBenchmark(main, { <add> n: [1e5] <add>}); <add>const path = require('path'); <add>const { rmSync } = require('fs'); <add>const { spawnSync } = require('child_process'); <add>const tmpdir = require('../../test/common/tmpdir'); <add> <add>const coverageDir = path.join(tmpdir.path, `./cov-${Date.now()}`); <add> <add>function main({ n }) { <add> bench.start(); <add> const result = spawnSync(process.execPath, [ <add> require.resolve('../fixtures/coverage-many-branches'), <add> ], { <add> env: { <add> NODE_V8_COVERAGE: coverageDir, <add> N: n, <add> ...process.env <add> } <add> }); <add> bench.end(n); <add> rmSync(coverageDir, { recursive: true, force: true }); <add> if (result.status !== 0) { <add> throw new Error(result.stderr.toString('utf8')); <add> } <add>}
2
Python
Python
add a button to set all tasks to skipped
298435a534237e6b58c8f8c4ab92a4b3f8a416e4
<ide><path>airflow/www/views.py <ide> from airflow.utils.log import secrets_masker <ide> from airflow.utils.log.log_reader import TaskLogReader <ide> from airflow.utils.session import create_session, provide_session <del>from airflow.utils.state import State <add>from airflow.utils.state import State, TaskInstanceState <ide> from airflow.utils.strings import to_boolean <ide> from airflow.utils.timezone import td_format, utcnow <ide> from airflow.version import version <ide> class TaskInstanceModelView(AirflowPrivilegeVerifierModelView): <ide> 'action_set_failed': 'edit', <ide> 'action_set_success': 'edit', <ide> 'action_set_retry': 'edit', <add> 'action_set_skipped': 'edit', <ide> } <ide> base_permissions = [ <ide> permissions.ACTION_CAN_CREATE, <ide> def action_set_retry(self, tis): <ide> self.update_redirect() <ide> return redirect(self.get_redirect()) <ide> <add> @action('set_skipped', "Set state to 'skipped'", '', single=False) <add> @action_has_dag_edit_access <add> def action_set_skipped(self, tis): <add> """Set state to skipped.""" <add> self.set_task_instance_state(tis, TaskInstanceState.SKIPPED) <add> self.update_redirect() <add> return redirect(self.get_redirect()) <add> <ide> <ide> class AutocompleteView(AirflowBaseView): <ide> """View to provide autocomplete results""" <ide><path>tests/www/views/test_views_tasks.py <ide> def test_task_instance_clear_failure(admin_client): <ide> ("set_failed", State.FAILED), <ide> ("set_success", State.SUCCESS), <ide> ("set_retry", State.UP_FOR_RETRY), <add> ("set_skipped", State.SKIPPED), <ide> ], <del> ids=["running", "failed", "success", "retry"], <add> ids=["running", "failed", "success", "retry", "skipped"], <ide> ) <ide> def test_task_instance_set_state(session, admin_client, action, expected_state): <ide> task_id = "runme_0" <ide> def test_task_instance_set_state(session, admin_client, action, expected_state): <ide> "set_failed", <ide> "set_success", <ide> "set_retry", <add> "set_skipped", <ide> ], <ide> ) <ide> def test_task_instance_set_state_failure(admin_client, action): <ide> def test_task_instance_set_state_failure(admin_client, action): <ide> <ide> @pytest.mark.parametrize( <ide> "action", <del> ["clear", "set_success", "set_failed", "set_running"], <del> ids=["clear", "success", "failed", "running"], <add> ["clear", "set_success", "set_failed", "set_running", "set_skipped"], <add> ids=["clear", "success", "failed", "running", "skipped"], <ide> ) <ide> def test_set_task_instance_action_permission_denied(session, client_ti_without_dag_edit, action): <ide> task_id = "runme_0"
2
Text
Text
fix typos and sources in working_groups.md
dfe7a17784626bcad67e085cb40b7f21b6c267ba
<ide><path>WORKING_GROUPS.md <ide> A working group needs 3 initial members. These should be individuals <ide> already undertaking the work described in the charter. <ide> <ide> The list of responsibilities should be specific. Once established these <del>responsibilities are no longer governed by the TC and therefor should <add>responsibilities are no longer governed by the TC and therefore should <ide> not be broad or subjective. The only recourse the TC has over the working <ide> group is to revoke the entire charter and take on the work previously <ide> done by the working group themselves. <ide> For the current list of WG members, see the project <ide> <ide> ### Collaborators <ide> <del>The [iojs/website](https://github.com/iojs/website) GitHub repository is <add>The *[insert WG name]* GitHub repository is <ide> maintained by the WG and additional Collaborators who are added by the <ide> WG on an ongoing basis. <ide> <ide> _Note:_ If you make a significant contribution and are not considered <ide> for commit-access log an issue or contact a WG member directly and it <ide> will be brought up in the next WG meeting. <ide> <del>Modifications of the contents of the iojs/website repository are made on <add>Modifications of the contents of the *[insert WG repo]* repository are made on <ide> a collaborative basis. Anybody with a GitHub account may propose a <ide> modification via pull request and it will be considered by the project <ide> Collaborators. All pull requests must be reviewed and accepted by a
1
Text
Text
add more examples to opp
9da0c53d1605889bacf8bc882ef853ba3f4e56d1
<ide><path>guide/spanish/design-patterns/object-oriented-programming/index.md <ide> En la programación de procedimientos, simplemente creamos variables y las cambi <ide> Otro concepto extremadamente útil es el de la herencia. La idea es que una clase puede heredar atributos y comportamiento de una clase base. Por ejemplo, al crear un juego, tenemos un jugador y un enemigo. Podemos crear una clase base llamada persona y darle atributos como nombre, edad, género, etc. El comportamiento de la persona puede ser caminar y saltar. Un jugador y un enemigo pueden heredar estas "cualidades" de la persona, y pueden tener cualidades adicionales como matar, anotar, comer, etc. <ide> <ide> Esto ayuda a reutilizar el código y hacer que la estructura de código sea mucho más limpia. La ocultación de datos es otra característica interesante. En OO, tenemos la noción de atributos privados y públicos. Los atributos privados se pueden acceder y modificar solo por métodos de esa clase en particular, mientras que los datos públicos se pueden modificar desde cualquier parte del programa (obviamente dentro del alcance). <del> <add> <add> Pongamos un ejemplo de como y para que: <add> <add> Una fabrica de vehículos quiere hace un software para su clasificación. Para ello, un programador decide crear un objeto "vehículo" con las propiedades que los diferencian (atributos) como serían el numero de ruedas, el color, si necesita casco, si tiene motor..... <add> Al mes siguiente, tras el triunfo de esta clasificación descubren que necesitan clasificar los coches que tienen, para ello, el programador crea un objeto coche que hereda las propiedades de vehículo (4 ruedas, sin casco y el color dependerá del coche) <ide> ## ¿Qué sigue? <ide> <del>Elige un lenguaje OO y crea un juego básico basado en terminales para ilustrar estos conceptos. <ide>\ No newline at end of file <add>Elige un lenguaje OO y crea un juego básico basado en terminales para ilustrar estos conceptos.
1
Javascript
Javascript
remove outdated comment
84a0a50b618da480588cf0c9e60e0fcd9785fdc3
<ide><path>packages/ember-metal/lib/meta.js <ide> function getOrCreateOwnMap(key) { <ide> } <ide> <ide> // Implements a member that is a lazily created POJO with inheritable <del>// values. For member `thing` you get methods `getThing`, <del>// `getOrCreateThing`, and `peekThing`. <add>// values. <ide> function inheritedMap(name, Meta) { <ide> let key = memberProperty(name); <ide> let capitalized = capitalize(name);
1
PHP
PHP
apply fixes from styleci
f319ed27348f7bd1796f6e238e577a8269ca84e2
<ide><path>tests/Notifications/NotificationMailMessageTest.php <ide> public function testTemplate() <ide> <ide> $this->assertEquals('notifications::foo', $this->message->markdown); <ide> } <del> <del>} <ide>\ No newline at end of file <add>}
1
Python
Python
use correct model versions for field operations
8d81c6bc821b614f8c6fec337a7bc6c992816c31
<ide><path>django/db/migrations/operations/fields.py <ide> def state_forwards(self, app_label, state): <ide> state.models[app_label, self.model_name.lower()].fields.append((self.name, self.instance)) <ide> <ide> def database_forwards(self, app_label, schema_editor, from_state, to_state): <del> app_cache = to_state.render() <del> model = app_cache.get_model(app_label, self.model_name) <del> schema_editor.add_field(model, model._meta.get_field_by_name(self.name)[0]) <add> from_model = from_state.render().get_model(app_label, self.model_name) <add> to_model = to_state.render().get_model(app_label, self.model_name) <add> schema_editor.add_field(from_model, to_model._meta.get_field_by_name(self.name)[0]) <ide> <ide> def database_backwards(self, app_label, schema_editor, from_state, to_state): <del> app_cache = from_state.render() <del> model = app_cache.get_model(app_label, self.model_name) <del> schema_editor.remove_field(model, model._meta.get_field_by_name(self.name)[0]) <add> from_model = from_state.render().get_model(app_label, self.model_name) <add> schema_editor.remove_field(from_model, from_model._meta.get_field_by_name(self.name)[0]) <ide> <ide> <ide> class RemoveField(Operation): <ide> def state_forwards(self, app_label, state): <ide> state.models[app_label, self.model_name.lower()].fields = new_fields <ide> <ide> def database_forwards(self, app_label, schema_editor, from_state, to_state): <del> app_cache = from_state.render() <del> model = app_cache.get_model(app_label, self.model_name) <del> schema_editor.remove_field(model, model._meta.get_field_by_name(self.name)[0]) <add> from_model = from_state.render().get_model(app_label, self.model_name) <add> schema_editor.remove_field(from_model, from_model._meta.get_field_by_name(self.name)[0]) <ide> <ide> def database_backwards(self, app_label, schema_editor, from_state, to_state): <del> app_cache = to_state.render() <del> model = app_cache.get_model(app_label, self.model_name) <del> schema_editor.add_field(model, model._meta.get_field_by_name(self.name)[0]) <add> from_model = from_state.render().get_model(app_label, self.model_name) <add> to_model = to_state.render().get_model(app_label, self.model_name) <add> schema_editor.add_field(from_model, to_model._meta.get_field_by_name(self.name)[0])
1
PHP
PHP
remove merge method
a07d028d732780249539dc6c33396dafc3bfa173
<ide><path>src/Illuminate/Http/Resources/Json/Resource.php <ide> public function toArray($request) <ide> return $this->resource->toArray(); <ide> } <ide> <del> /** <del> * Merge additional data into the resource array. <del> * <del> * @param array $data <del> * @return $this <del> */ <del> public function merge(array $data) <del> { <del> $this->with = $data; <del> <del> return $this; <del> } <del> <ide> /** <ide> * Get any additional data that should be returned with the resource array. <ide> * <ide><path>tests/Integration/Http/ResourceTest.php <ide> public function test_resources_may_customize_extra_data() <ide> ]); <ide> } <ide> <del> public function test_resources_may_customize_adhoc_extra_data() <del> { <del> Route::get('/', function () { <del> return PostResource::make(new Post([ <del> 'id' => 5, <del> 'title' => 'Test Title', <del> ]))->merge(['foo' => 'bar']); <del> }); <del> <del> $response = $this->withoutExceptionHandling()->get( <del> '/', ['Accept' => 'application/json'] <del> ); <del> <del> $response->assertJson([ <del> 'data' => [ <del> 'id' => 5, <del> 'title' => 'Test Title', <del> ], <del> 'foo' => 'bar', <del> ]); <del> } <del> <ide> public function test_custom_headers_may_be_set_on_responses() <ide> { <ide> Route::get('/', function () {
2
Text
Text
add backticks [ci skip]
4b29d9f1db0dd8fc95829cfefed0687242cfc12b
<ide><path>activerecord/CHANGELOG.md <ide> <ide> *Ryuta Kamizono* <ide> <del>* Query cache was unavailable when entering the ActiveRecord::Base.cache block <add>* Query cache was unavailable when entering the `ActiveRecord::Base.cache` block <ide> without being connected. <ide> <ide> *Tsukasa Oishi* <ide> *bogdanvlviv* <ide> <ide> * Fix destroying existing object does not work well when optimistic locking enabled and <del> `locking column` is null in the database. <add> `locking_column` is null in the database. <ide> <ide> *bogdanvlviv* <ide> <ide><path>railties/CHANGELOG.md <ide> <ide> *Yuji Yaginuma* <ide> <del>* Added a shared section to config/database.yml that will be loaded for all environments. <add>* Added a shared section to `config/database.yml` that will be loaded for all environments. <ide> <ide> *Pierre Schambacher* <ide>
2
Javascript
Javascript
add tests for extracting function name
d268cf5a22e8fe4b631a2ce6a484e8d99991fa24
<ide><path>test/parallel/test-debugger-extract-function-name.js <add>'use strict'; <add>const common = require('../common'); <add> <add>common.skipIfInspectorDisabled(); <add> <add>const fixtures = require('../common/fixtures'); <add>const startCLI = require('../common/debugger'); <add> <add>const assert = require('assert'); <add> <add>const cli = startCLI([fixtures.path('debugger', 'three-lines.js')]); <add> <add>function onFatal(error) { <add> cli.quit(); <add> throw error; <add>} <add> <add>cli.waitForInitialBreak() <add> .then(() => cli.waitForPrompt()) <add> .then(() => cli.command('exec a = function func() {}; a;')) <add> .then(() => assert.match(cli.output, /\[Function: func\]/)) <add> .then(() => cli.command('exec a = function func () {}; a;')) <add> .then(() => assert.match(cli.output, /\[Function\]/)) <add> .then(() => cli.command('exec a = function() {}; a;')) <add> .then(() => assert.match(cli.output, /\[Function: function\]/)) <add> .then(() => cli.command('exec a = () => {}; a;')) <add> .then(() => assert.match(cli.output, /\[Function\]/)) <add> .then(() => cli.command('exec a = function* func() {}; a;')) <add> .then(() => assert.match(cli.output, /\[GeneratorFunction: func\]/)) <add> .then(() => cli.command('exec a = function *func() {}; a;')) <add> .then(() => assert.match(cli.output, /\[GeneratorFunction: \*func\]/)) <add> .then(() => cli.command('exec a = function*func() {}; a;')) <add> .then(() => assert.match(cli.output, /\[GeneratorFunction: function\*func\]/)) <add> .then(() => cli.command('exec a = function * func() {}; a;')) <add> .then(() => assert.match(cli.output, /\[GeneratorFunction\]/)) <add> .then(() => cli.quit()) <add> .then(null, onFatal);
1
PHP
PHP
add null to docs
2093e7e8e440f90499ececbad759b701cb864853
<ide><path>src/Illuminate/Notifications/Messages/SlackAttachment.php <ide> class SlackAttachment <ide> * Set the title of the attachment. <ide> * <ide> * @param string $title <del> * @param string $url <add> * @param string|null $url <ide> * @return $this <ide> */ <ide> public function title($title, $url = null) <ide> public function timestamp($timestamp) <ide> * Set the author. <ide> * <ide> * @param string $name <del> * @param string $link <del> * @param string $icon <add> * @param string|null $link <add> * @param string|null $icon <ide> * @return $this <ide> */ <ide> public function author($name, $link = null, $icon = null)
1
Java
Java
handle [native code] stack frames
0ee8786cd8025302284af6df3f63ea843dfb9737
<ide><path>ReactAndroid/src/main/java/com/facebook/react/devsupport/StackTraceHelper.java <ide> public static StackFrame[] convertJsStackTrace(String stack) { <ide> String[] stackTrace = stack.split("\n"); <ide> StackFrame[] result = new StackFrame[stackTrace.length]; <ide> for (int i = 0; i < stackTrace.length; ++i) { <del> Matcher matcher = STACK_FRAME_PATTERN.matcher(stackTrace[i]); <del> if (!matcher.find()) { <del> throw new IllegalArgumentException( <add> if (stackTrace[i].equals("[native code]")) { <add> result[i] = new StackFrameImpl(null, stackTrace[i], -1, -1); <add> } else { <add> Matcher matcher = STACK_FRAME_PATTERN.matcher(stackTrace[i]); <add> if (!matcher.find()) { <add> throw new IllegalArgumentException( <ide> "Unexpected stack frame format: " + stackTrace[i]); <del> } <add> } <ide> <del> result[i] = new StackFrameImpl( <del> matcher.group(2), <del> matcher.group(1) == null ? "(unknown)" : matcher.group(1), <del> Integer.parseInt(matcher.group(3)), <del> Integer.parseInt(matcher.group(4))); <add> result[i] = new StackFrameImpl( <add> matcher.group(2), <add> matcher.group(1) == null ? "(unknown)" : matcher.group(1), <add> Integer.parseInt(matcher.group(3)), <add> Integer.parseInt(matcher.group(4))); <add> } <ide> } <ide> return result; <ide> }
1
Ruby
Ruby
add a bunch of specs for attribute type casting
61916e408d86d19d1659cd8042de6503aecc6c98
<ide><path>lib/arel/algebra/attributes/attribute.rb <ide> def type_cast(value) <ide> def type_cast_to_numeric(value, method) <ide> return unless value <ide> if value.respond_to?(:to_str) <del> if value.to_str =~ /\A(-?(?:0|[1-9]\d*)(?:\.\d+)?|(?:\.\d+))\z/ <del> $1.send(method) <del> else <del> value <del> end <add> str = value.to_str.strip <add> return if str.empty? <add> return $1.send(method) if str =~ /\A(-?(?:0|[1-9]\d*)(?:\.\d+)?|(?:\.\d+))\z/ <ide> elsif value.respond_to?(method) <del> value.send(method) <del> else <del> raise typecast_error(value) <add> return value.send(method) <ide> end <add> raise typecast_error(value) <ide> end <ide> <ide> def typecast_error(value) <ide><path>lib/arel/algebra/attributes/boolean.rb <ide> module Attributes <ide> class Boolean < Attribute <ide> def type_cast(value) <ide> case value <del> when true, false then value <del> when nil then options[:allow_nil] ? nil : false <del> when 1 then true <del> when 0 then false <del> else <add> when true, false then value <add> # when nil then options[:allow_nil] ? nil : false <add> when nil then false <add> when 1 then true <add> when 0 then false <add> else <ide> case value.to_s.downcase.strip <ide> when 'true' then true <ide> when 'false' then false <ide><path>spec/arel/algebra/integration/basic_spec.rb <ide> require 'spec_helper' <ide> <del>module Arel <del> module Testing <del> class Engine <del> attr_reader :rows <del> <del> def initialize <del> @rows = [] <del> end <del> <del> def supports(operation) <del> false <del> end <del> <del> def read(relation) <del> @rows.dup.map { |r| Row.new(relation, r) } <del> end <del> <del> def create(insert) <del> @rows << insert.record.tuple <del> insert <del> end <del> end <del> end <del>end <del> <del>class Thing < Arel::Relation <del> attr_reader :engine, :attributes <del> <del> def initialize(engine, attributes) <del> @engine, @attributes = engine, [] <del> attributes.each do |name, type| <del> @attributes << type.new(self, name) <del> end <del> end <del> <del> def format(attribute, value) <del> value <del> end <del> <del> def insert(row) <del> insert = super Arel::Row.new(self, row) <del> insert.record <del> end <del>end <del> <ide> def have_rows(expected) <ide> simple_matcher "have rows" do |given, matcher| <ide> found, got, expected = [], [], expected.map { |r| r.tuple } <ide> module Arel <ide> describe "Relation" do <ide> <ide> before :all do <del> @engine = Testing::Engine.new <del> @relation = Thing.new(@engine, <del> :id => Attributes::Integer, <del> :name => Attributes::String, <del> :age => Attributes::Integer) <add> @engine = Testing::Engine.new <add> @relation = Model.build do |r| <add> r.engine @engine <add> <add> r.attribute :id, Attributes::Integer <add> r.attribute :name, Attributes::String <add> r.attribute :age, Attributes::Integer <add> end <ide> end <ide> <ide> describe "..." do <ide><path>spec/attributes/boolean_spec.rb <add>require 'spec_helper' <add> <add>module Arel <add> describe "Attributes::Boolean" do <add> <add> before :all do <add> @relation = Model.build do |r| <add> r.engine Testing::Engine.new <add> r.attribute :awesome, Attributes::Boolean <add> end <add> end <add> <add> def type_cast(val) <add> @relation[:awesome].type_cast(val) <add> end <add> <add> describe "#type_cast" do <add> it "returns same value if passed a boolean" do <add> val = true <add> type_cast(val).should eql(val) <add> end <add> <add> it "returns boolean representation (false) of nil" do <add> type_cast(nil).should eql(false) <add> end <add> <add> it "returns boolean representation of 'true', 'false'" do <add> type_cast('true').should eql(true) <add> type_cast('false').should eql(false) <add> end <add> <add> it "returns boolean representation of :true, :false" do <add> type_cast(:true).should eql(true) <add> type_cast(:false).should eql(false) <add> end <add> <add> it "returns boolean representation of 0, 1" do <add> type_cast(1).should == true <add> type_cast(0).should == false <add> end <add> <add> it "calls #to_s on arbitrary objects" do <add> obj = Object.new <add> obj.extend Module.new { def to_s ; 'true' ; end } <add> type_cast(obj).should == true <add> end <add> <add> [ Object.new, 'string', '00.0', 5 ].each do |value| <add> it "raises exception when attempting type_cast of non-boolean value #{value.inspect}" do <add> lambda do <add> type_cast(value) <add> end.should raise_error(TypecastError, /could not typecast/) <add> end <add> end <add> end <add> end <add>end <ide>\ No newline at end of file <ide><path>spec/attributes/float_spec.rb <add>require 'spec_helper' <add>require 'bigdecimal' <add> <add>module Arel <add> describe "Attributes::Float" do <add> <add> before :all do <add> @relation = Model.build do |r| <add> r.engine Testing::Engine.new <add> r.attribute :percentage, Attributes::Float <add> end <add> end <add> <add> def type_cast(val) <add> @relation[:percentage].type_cast(val) <add> end <add> <add> describe "#type_cast" do <add> it "returns same value if an float" do <add> type_cast(24.01).should eql(24.01) <add> end <add> <add> it "returns nil if passed nil" do <add> type_cast(nil).should be_nil <add> end <add> <add> it "returns nil if passed empty string" do <add> type_cast('').should be_nil <add> end <add> <add> it "returns float representation of a zero string float" do <add> type_cast('0').should eql(0.0) <add> end <add> <add> it "returns float representation of a positive string integer" do <add> type_cast('24').should eql(24.0) <add> end <add> <add> it "returns float representation of a positive string integer with spaces" do <add> type_cast(' 24').should eql(24.0) <add> type_cast('24 ').should eql(24.0) <add> end <add> <add> it "returns float representation of a negative string float" do <add> type_cast('-24.23').should eql(-24.23) <add> end <add> <add> it "returns float representation of a negative string integer with spaces" do <add> type_cast('-24 ').should eql(-24.0) <add> type_cast(' -24').should eql(-24.0) <add> end <add> <add> it "returns integer representation of a zero string float" do <add> type_cast('0.0').should eql(0.0) <add> end <add> <add> it "returns integer representation of a positive string float" do <add> type_cast('24.35').should eql(24.35) <add> end <add> <add> it "returns integer representation of a positive string float with spaces" do <add> type_cast(' 24.35').should eql(24.35) <add> type_cast('24.35 ').should eql(24.35) <add> end <add> <add> it "returns integer representation of a negative string float" do <add> type_cast('-24.35').should eql(-24.35) <add> end <add> <add> it "returns integer representation of a negative string float with spaces" do <add> type_cast(' -24.35 ').should eql(-24.35) <add> end <add> <add> it "returns integer representation of a zero string float, with no leading digits" do <add> type_cast('.0').should eql(0.0) <add> end <add> <add> it "returns integer representation of a zero string float, with no leading digits with spaces" do <add> type_cast(' .0').should eql(0.0) <add> end <add> <add> it "returns integer representation of a positive string float, with no leading digits" do <add> type_cast('.41').should eql(0.41) <add> end <add> <add> it "returns integer representation of a zero float" do <add> type_cast(0.0).should eql(0.0) <add> end <add> <add> it "returns integer representation of a positive float" do <add> type_cast(24.35).should eql(24.35) <add> end <add> <add> it "returns integer representation of a negative float" do <add> type_cast(-24.35).should eql(-24.35) <add> end <add> <add> it "returns integer representation of a zero decimal" do <add> type_cast(BigDecimal('0.0')).should eql(0.0) <add> end <add> <add> it "returns integer representation of a positive decimal" do <add> type_cast(BigDecimal('24.35')).should eql(24.35) <add> end <add> <add> it "returns integer representation of a negative decimal" do <add> type_cast(BigDecimal('-24.35')).should eql(-24.35) <add> end <add> <add> [ Object.new, true, '00.0', '0.', 'string' ].each do |value| <add> it "raises exception when attempting type_cast of non-numeric value #{value.inspect}" do <add> lambda do <add> type_cast(value) <add> end.should raise_error(TypecastError, /could not typecast/) <add> end <add> end <add> end <add> end <add>end <ide>\ No newline at end of file <ide><path>spec/attributes/integer_spec.rb <add>require 'spec_helper' <add>require 'bigdecimal' <add> <add>module Arel <add> describe "Attributes::Integer" do <add> <add> before :all do <add> @relation = Model.build do |r| <add> r.engine Testing::Engine.new <add> r.attribute :age, Attributes::Integer <add> end <add> end <add> <add> def type_cast(val) <add> @relation[:age].type_cast(val) <add> end <add> <add> describe "#type_cast" do <add> it "returns same value if an integer" do <add> type_cast(24).should eql(24) <add> end <add> <add> it "returns nil if passed nil" do <add> type_cast(nil).should be_nil <add> end <add> <add> it "returns nil if passed empty string" do <add> type_cast('').should be_nil <add> end <add> <add> it "returns integer representation of a zero string integer" do <add> type_cast('0').should eql(0) <add> end <add> <add> it "returns integer representation of a positive string integer" do <add> type_cast('24').should eql(24) <add> end <add> <add> it "returns integer representation of a positive string integer with spaces" do <add> type_cast(' 24').should eql(24) <add> type_cast('24 ').should eql(24) <add> end <add> <add> it "returns integer representation of a negative string integer" do <add> type_cast('-24').should eql(-24) <add> end <add> <add> it "returns integer representation of a negative string integer with spaces" do <add> type_cast('-24 ').should eql(-24) <add> type_cast(' -24').should eql(-24) <add> end <add> <add> it "returns integer representation of a zero string float" do <add> type_cast('0.0').should eql(0) <add> end <add> <add> it "returns integer representation of a positive string float" do <add> type_cast('24.35').should eql(24) <add> end <add> <add> it "returns integer representation of a positive string float with spaces" do <add> type_cast(' 24.35').should eql(24) <add> type_cast('24.35 ').should eql(24) <add> end <add> <add> it "returns integer representation of a negative string float" do <add> type_cast('-24.35').should eql(-24) <add> end <add> <add> it "returns integer representation of a negative string float with spaces" do <add> type_cast(' -24.35 ').should eql(-24) <add> end <add> <add> it "returns integer representation of a zero string float, with no leading digits" do <add> type_cast('.0').should eql(0) <add> end <add> <add> it "returns integer representation of a zero string float, with no leading digits with spaces" do <add> type_cast(' .0').should eql(0) <add> end <add> <add> it "returns integer representation of a positive string float, with no leading digits" do <add> type_cast('.41').should eql(0) <add> end <add> <add> it "returns integer representation of a zero float" do <add> type_cast(0.0).should eql(0) <add> end <add> <add> it "returns integer representation of a positive float" do <add> type_cast(24.35).should eql(24) <add> end <add> <add> it "returns integer representation of a negative float" do <add> type_cast(-24.35).should eql(-24) <add> end <add> <add> it "returns integer representation of a zero decimal" do <add> type_cast(BigDecimal('0.0')).should eql(0) <add> end <add> <add> it "returns integer representation of a positive decimal" do <add> type_cast(BigDecimal('24.35')).should eql(24) <add> end <add> <add> it "returns integer representation of a negative decimal" do <add> type_cast(BigDecimal('-24.35')).should eql(-24) <add> end <add> <add> [ Object.new, true, '00.0', '0.', 'string' ].each do |value| <add> it "raises exception when attempting type_cast of non-numeric value #{value.inspect}" do <add> lambda do <add> type_cast(value) <add> end.should raise_error(TypecastError, /could not typecast/) <add> end <add> end <add> end <add> end <add>end <ide>\ No newline at end of file <ide><path>spec/attributes/string_spec.rb <add>require 'spec_helper' <add>require 'bigdecimal' <add> <add>module Arel <add> describe "Attributes::String" do <add> <add> before :all do <add> @relation = Model.build do |r| <add> r.engine Testing::Engine.new <add> r.attribute :name, Attributes::String <add> end <add> end <add> <add> def type_cast(val) <add> @relation[:name].type_cast(val) <add> end <add> <add> describe "#type_cast" do <add> it "returns same value if passed a String" do <add> val = "hell" <add> type_cast(val).should eql(val) <add> end <add> <add> it "returns nil if passed nil" do <add> type_cast(nil).should be_nil <add> end <add> <add> it "returns String representation of Symbol" do <add> type_cast(:hello).should == "hello" <add> end <add> <add> it "returns string representation of Integer" do <add> type_cast(1).should == '1' <add> end <add> <add> it "calls #to_s on arbitrary objects" do <add> obj = Object.new <add> obj.extend Module.new { def to_s ; 'hello' ; end } <add> type_cast(obj).should == 'hello' <add> end <add> end <add> end <add>end <ide>\ No newline at end of file <ide><path>spec/attributes/time_spec.rb <add>require 'spec_helper' <add>require 'bigdecimal' <add> <add>module Arel <add> describe "Attributes::Time" do <add> <add> before :all do <add> @relation = Model.build do |r| <add> r.engine Testing::Engine.new <add> r.attribute :created_at, Attributes::Time <add> end <add> end <add> <add> def type_cast(val) <add> @relation[:created_at].type_cast(val) <add> end <add> <add> describe "#type_cast" do <add> it "works" <add> end <add> end <add>end <ide>\ No newline at end of file <ide><path>spec/support/model.rb <add>module Arel <add> module Testing <add> class Engine <add> attr_reader :rows <add> <add> def initialize <add> @rows = [] <add> end <add> <add> def supports(operation) <add> false <add> end <add> <add> def read(relation) <add> @rows.dup.map { |r| Row.new(relation, r) } <add> end <add> <add> def create(insert) <add> @rows << insert.record.tuple <add> insert <add> end <add> end <add> end <add> <add> class Model < Relation <add> attr_reader :engine, :attributes <add> <add> def self.build <add> relation = new <add> yield relation <add> relation <add> end <add> <add> def initialize <add> @attributes = [] <add> end <add> <add> def engine(engine = nil) <add> @engine = engine if engine <add> @engine <add> end <add> <add> def attribute(name, type) <add> @attributes << type.new(self, name) <add> end <add> <add> def format(attribute, value) <add> value <add> end <add> <add> def insert(row) <add> insert = super Arel::Row.new(self, row) <add> insert.record <add> end <add> end <add>end <ide>\ No newline at end of file
9
Java
Java
fix precondition assertions
e5878ab15b46079e29043426d38ac7f1543ca377
<ide><path>spring-tx/src/main/java/org/springframework/transaction/reactive/TransactionalOperatorImpl.java <ide> /* <del> * Copyright 2002-2019 the original author or authors. <add> * Copyright 2002-2022 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> final class TransactionalOperatorImpl implements TransactionalOperator { <ide> */ <ide> TransactionalOperatorImpl(ReactiveTransactionManager transactionManager, TransactionDefinition transactionDefinition) { <ide> Assert.notNull(transactionManager, "ReactiveTransactionManager must not be null"); <del> Assert.notNull(transactionManager, "TransactionDefinition must not be null"); <add> Assert.notNull(transactionDefinition, "TransactionDefinition must not be null"); <ide> this.transactionManager = transactionManager; <ide> this.transactionDefinition = transactionDefinition; <ide> } <ide><path>spring-web/src/main/java/org/springframework/http/ContentDisposition.java <ide> else if (!escaped && ch == '"') { <ide> * @see <a href="https://tools.ietf.org/html/rfc5987">RFC 5987</a> <ide> */ <ide> private static String decodeFilename(String filename, Charset charset) { <del> Assert.notNull(filename, "'input' String should not be null"); <del> Assert.notNull(charset, "'charset' should not be null"); <add> Assert.notNull(filename, "'filename' must not be null"); <add> Assert.notNull(charset, "'charset' must not be null"); <add> <ide> byte[] value = filename.getBytes(charset); <ide> ByteArrayOutputStream baos = new ByteArrayOutputStream(); <ide> int index = 0; <ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/UndertowServerHttpResponse.java <ide> class UndertowServerHttpResponse extends AbstractListenerServerHttpResponse impl <ide> HttpServerExchange exchange, DataBufferFactory bufferFactory, UndertowServerHttpRequest request) { <ide> <ide> super(bufferFactory, createHeaders(exchange)); <del> Assert.notNull(exchange, "HttpServerExchange must not be null"); <ide> this.exchange = exchange; <ide> this.request = request; <ide> } <ide> <ide> private static HttpHeaders createHeaders(HttpServerExchange exchange) { <add> Assert.notNull(exchange, "HttpServerExchange must not be null"); <ide> UndertowHeadersAdapter headersMap = new UndertowHeadersAdapter(exchange.getResponseHeaders()); <ide> return new HttpHeaders(headersMap); <ide> } <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/handler/RequestMatchResult.java <ide> /* <del> * Copyright 2002-2020 the original author or authors. <add> * Copyright 2002-2022 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public class RequestMatchResult { <ide> */ <ide> public RequestMatchResult(PathPattern pathPattern, PathContainer lookupPath) { <ide> Assert.notNull(pathPattern, "PathPattern is required"); <del> Assert.notNull(pathPattern, "PathContainer is required"); <add> Assert.notNull(lookupPath, "PathContainer is required"); <ide> <ide> this.pattern = null; <ide> this.lookupPath = null;
4
Javascript
Javascript
add tests for ignored context modules
926d94a54f1935928d9c50a9202c3b291482c9a1
<ide><path>test/configCases/ignore/only-resource-context/src/ignored-module.js <add>module.exports = "ignored"; <ide><path>test/configCases/ignore/only-resource-context/src/normal-module.js <add>module.exports = "normal"; <ide><path>test/configCases/ignore/only-resource-context/test.js <add>/* globals it */ <add>"use strict"; <add> <add>it("should ignore ignored resources", function() { <add> const folderBContext = function(mod) { <add> require("./src/" + mod); <add> }; <add> <add> (function() { <add> folderBContext("ignored-module"); <add> }).should.throw(); <add>}); <add>it("should not ignore resources that do not match", function() { <add> const folderBContext = function(mod) { <add> require("./src/" + mod); <add> }; <add> <add> (function() { <add> folderBContext("normal-module"); <add> }).should.not.throw(); <add>}); <ide><path>test/configCases/ignore/only-resource-context/webpack.config.js <add>"use strict"; <add> <add>const IgnorePlugin = require("../../../../lib/IgnorePlugin"); <add> <add>module.exports = { <add> entry: "./test.js", <add> plugins: [ <add> new IgnorePlugin(/ignored-module/) <add> ], <add>}; <ide><path>test/configCases/ignore/resource-and-context-contextmodule/folder-a/ignored-module.js <add>module.exports = "ignored"; <ide><path>test/configCases/ignore/resource-and-context-contextmodule/folder-a/normal-module.js <add>module.exports = require("./normal-module"); <ide><path>test/configCases/ignore/resource-and-context-contextmodule/folder-b/ignored-module.js <add>module.exports = "ignored"; <ide><path>test/configCases/ignore/resource-and-context-contextmodule/folder-b/normal-module.js <add>module.exports = require("./ignored-module"); <ide><path>test/configCases/ignore/resource-and-context-contextmodule/folder-b/only-context-match-require.js <add>module.exports = "should be fine"; <ide><path>test/configCases/ignore/resource-and-context-contextmodule/folder-b/only-context-match.js <add>module.exports = require("./only-context-match-require"); <ide><path>test/configCases/ignore/resource-and-context-contextmodule/test.js <add>/* globals it */ <add>"use strict"; <add> <add>it("should ignore context modules that match resource regex and context", function() { <add> const folderBContext = function(mod) { <add> require("./folder-b/" + mod); <add> }; <add> <add> (function() { <add> folderBContext("normal-module"); <add> }).should.throw(); <add>}); <add> <add>it("should not ignore context modules that dont match the resource", function() { <add> const folderBContext = function(mod) { <add> require("./folder-b/" + mod); <add> }; <add> <add> (function() { <add> folderBContext("only-context-match"); <add> }).should.not.throw(); <add>}); <add> <add>it("should not ignore context modules that dont match the context", function() { <add> const folderBContext = function(mod) { <add> require("./folder-a/" + mod); <add> }; <add> <add> (function() { <add> folderBContext("normal-module"); <add> }).should.not.throw(); <add> (function() { <add> folderBContext("ignored-module"); <add> }).should.not.throw(); <add>}); <ide><path>test/configCases/ignore/resource-and-context-contextmodule/webpack.config.js <add>"use strict"; <add> <add>const IgnorePlugin = require("../../../../lib/IgnorePlugin"); <add> <add>module.exports = { <add> entry: "./test.js", <add> plugins: [ <add> new IgnorePlugin(/ignored-module/, /folder-b/) <add> ], <add>};
12
Python
Python
remove value error
b01ddc9577b87f057e163d49563ee3f74f4810cf
<ide><path>src/transformers/modeling_tf_utils.py <ide> def booleans_processing(config, **kwargs): <ide> <ide> def input_processing(func, config, input_ids, **kwargs): <ide> """ <del> Process the input of each TensorFlow model including the booleans. <add> Process the input of each TensorFlow model including the booleans. In case of a list of symbolic inputs, each input <add> has to be named accordingly to the parameters name, i.e. `input_ids = tf.keras.Input(shape=(128,), dtype='int32', <add> name="input_ids")` otherwise the order of the tensors will not be guaranteed during the training. <ide> <ide> Args: <ide> func (:obj:`callable`): <ide> def input_processing(func, config, input_ids, **kwargs): <ide> if tensor_name in parameter_names: <ide> output[tensor_name] = input <ide> else: <del> raise ValueError( <del> f"The tensor named {input.name} does not belong to the authorized list of names {parameter_names}." <del> ) <add> output[parameter_names[i]] = input <ide> elif isinstance(input, allowed_types) or input is None: <ide> output[parameter_names[i]] = input <ide> else:
1
Text
Text
fix typos in changelog
57f29f24e46c845ebbd6d309a3ca5af39ee0f3ec
<ide><path>CHANGELOG.md <ide> be found. <ide> <ide> ### Builder <ide> <del>- Fix a bug where Docker would not used the correct uid/gid when processing the `WORKDIR` command ([#21033](https://github.com/docker/docker/pull/21033)) <add>- Fix a bug where Docker would not use the correct uid/gid when processing the `WORKDIR` command ([#21033](https://github.com/docker/docker/pull/21033)) <ide> - Fix a bug where copy operations with userns would not use the proper uid/gid ([#20782](https://github.com/docker/docker/pull/20782), [#21162](https://github.com/docker/docker/pull/21162)) <ide> <ide> ### Client <ide> be found. <ide> + Docker learned how to use a SOCKS proxy ([#20366](https://github.com/docker/docker/pull/20366), [#18373](https://github.com/docker/docker/pull/18373)) <ide> + Docker now supports external credential stores ([#20107](https://github.com/docker/docker/pull/20107)) <ide> * `docker ps` now supports displaying the list of volumes mounted inside a container ([#20017](https://github.com/docker/docker/pull/20017)) <del>* `docker info` now also report Docker's root directory location ([#19986](https://github.com/docker/docker/pull/19986)) <add>* `docker info` now also reports Docker's root directory location ([#19986](https://github.com/docker/docker/pull/19986)) <ide> - Docker now prohibits login in with an empty username (spaces are trimmed) ([#19806](https://github.com/docker/docker/pull/19806)) <ide> * Docker events attributes are now sorted by key ([#19761](https://github.com/docker/docker/pull/19761)) <del>* `docker ps` no longer show exported port for stopped containers ([#19483](https://github.com/docker/docker/pull/19483)) <add>* `docker ps` no longer shows exported port for stopped containers ([#19483](https://github.com/docker/docker/pull/19483)) <ide> - Docker now cleans after itself if a save/export command fails ([#17849](https://github.com/docker/docker/pull/17849)) <ide> * Docker load learned how to display a progress bar ([#17329](https://github.com/docker/docker/pull/17329), [#120078](https://github.com/docker/docker/pull/20078)) <ide> <ide> ### Distribution <ide> <del>- Fix a panic that occurred when pulling an images with 0 layers ([#21222](https://github.com/docker/docker/pull/21222)) <add>- Fix a panic that occurred when pulling an image with 0 layers ([#21222](https://github.com/docker/docker/pull/21222)) <ide> - Fix a panic that could occur on error while pushing to a registry with a misconfigured token service ([#21212](https://github.com/docker/docker/pull/21212)) <ide> + All first-level delegation roles are now signed when doing a trusted push ([#21046](https://github.com/docker/docker/pull/21046)) <ide> + OAuth support for registries was added ([#20970](https://github.com/docker/docker/pull/20970)) <ide> be found. <ide> * The `dockremap` is now created as a system user ([#21266](https://github.com/docker/docker/pull/21266)) <ide> - Fix a few response body leaks ([#21258](https://github.com/docker/docker/pull/21258)) <ide> - Docker, when run as a service with systemd, will now properly manage its processes cgroups ([#20633](https://github.com/docker/docker/pull/20633)) <del>* Docker info now reports the value of cgroup KernelMemory or emits a warning if it is not supported ([#20863](https://github.com/docker/docker/pull/20863)) <del>* Docker info now also reports the cgroup driver in use ([#20388](https://github.com/docker/docker/pull/20388)) <add>* `docker info` now reports the value of cgroup KernelMemory or emits a warning if it is not supported ([#20863](https://github.com/docker/docker/pull/20863)) <add>* `docker info` now also reports the cgroup driver in use ([#20388](https://github.com/docker/docker/pull/20388)) <ide> * Docker completion is now available on PowerShell ([#19894](https://github.com/docker/docker/pull/19894)) <ide> * `dockerinit` is no more ([#19490](https://github.com/docker/docker/pull/19490),[#19851](https://github.com/docker/docker/pull/19851)) <ide> + Support for building Docker on arm64 was added ([#19013](https://github.com/docker/docker/pull/19013)) <ide> be found. <ide> - Fix panic if a node is forcibly removed from the cluster ([#21671](https://github.com/docker/docker/pull/21671)) <ide> - Fix "error creating vxlan interface" when starting a container in a Swarm cluster ([#21671](https://github.com/docker/docker/pull/21671)) <ide> * `docker network inspect` will now report all endpoints whether they have an active container or not ([#21160](https://github.com/docker/docker/pull/21160)) <del>+ Experimental support for the MacVlan and IPVlan network drivers have been added ([#21122](https://github.com/docker/docker/pull/21122)) <add>+ Experimental support for the MacVlan and IPVlan network drivers has been added ([#21122](https://github.com/docker/docker/pull/21122)) <ide> * Output of `docker network ls` is now sorted by network name ([#20383](https://github.com/docker/docker/pull/20383)) <ide> - Fix a bug where Docker would allow a network to be created with the reserved `default` name ([#19431](https://github.com/docker/docker/pull/19431)) <ide> * `docker network inspect` returns whether a network is internal or not ([#19357](https://github.com/docker/docker/pull/19357)) <ide> be found. <ide> - Fix a race with event timers stopping early ([#21692](https://github.com/docker/docker/pull/21692)) <ide> - Fix race conditions in the layer store, potentially corrupting the map and crashing the process ([#21677](https://github.com/docker/docker/pull/21677)) <ide> - Un-deprecate auto-creation of host directories for mounts. This feature was marked deprecated in ([#21666](https://github.com/docker/docker/pull/21666)) <del> Docker 1.9, but was decided to be too much of an backward-incompatible change, so it was decided to keep the feature. <add> Docker 1.9, but was decided to be too much of a backward-incompatible change, so it was decided to keep the feature. <ide> + It is now possible for containers to share the NET and IPC namespaces when `userns` is enabled ([#21383](https://github.com/docker/docker/pull/21383)) <ide> + `docker inspect <image-id>` will now expose the rootfs layers ([#21370](https://github.com/docker/docker/pull/21370)) <ide> + Docker Windows gained a minimal `top` implementation ([#21354](https://github.com/docker/docker/pull/21354)) <ide> be found. <ide> ### Volumes <ide> <ide> * Output of `docker volume ls` is now sorted by volume name ([#20389](https://github.com/docker/docker/pull/20389)) <del>* Local volumes can now accepts options similar to the unix `mount` tool ([#20262](https://github.com/docker/docker/pull/20262)) <add>* Local volumes can now accept options similar to the unix `mount` tool ([#20262](https://github.com/docker/docker/pull/20262)) <ide> - Fix an issue where one letter directory name could not be used as source for volumes ([#21106](https://github.com/docker/docker/pull/21106)) <del>+ `docker run -v` now accepts a new flag `nocopy`. This tell the runtime not to copy the container path content into the volume (which is the default behavior) ([#21223](https://github.com/docker/docker/pull/21223)) <add>+ `docker run -v` now accepts a new flag `nocopy`. This tells the runtime not to copy the container path content into the volume (which is the default behavior) ([#21223](https://github.com/docker/docker/pull/21223)) <ide> <ide> ## 1.10.3 (2016-03-10) <ide>
1
Javascript
Javascript
change the repeat buffer.from('blerg'); statments
04cf20261f241530d00bf2e4f8153d55102429d2
<ide><path>test/parallel/test-stream-writable-constructor-set-methods.js <ide> w.on('error', common.expectsError({ <ide> message: 'The _write() method is not implemented' <ide> })); <ide> <del>w.end(Buffer.from('blerg')); <add>const bufferBlerg = Buffer.from('blerg'); <add> <add>w.end(bufferBlerg); <ide> <ide> const _write = common.mustCall((chunk, _, next) => { <ide> next(); <ide> const w2 = new Writable({ write: _write, writev: _writev }); <ide> strictEqual(w2._write, _write); <ide> strictEqual(w2._writev, _writev); <ide> <del>w2.write(Buffer.from('blerg')); <add>w2.write(bufferBlerg); <ide> <ide> w2.cork(); <del>w2.write(Buffer.from('blerg')); <del>w2.write(Buffer.from('blerg')); <add>w2.write(bufferBlerg); <add>w2.write(bufferBlerg); <ide> <ide> w2.end();
1
Text
Text
correct version number formats in changelog
b6312af19f10c72039901fcf930883ad6808161e
<ide><path>CHANGELOG.md <del><a name="1.2.0-rc2"></a> <del># 1.2.0-rc2 barehand-atomsplitting (2013-09-04) <add><a name="1.2.0-rc.2"></a> <add># 1.2.0-rc.2 barehand-atomsplitting (2013-09-04) <ide> <ide> ## Features <ide> <ide> Contains only these fixes cherry-picked from [v1.2.0rc1](#1.2.0rc1). <ide> <ide> <ide> <a name="1.2.0rc1"></a> <del># 1.2.0-rc1 spooky-giraffe (2013-08-13) <add># 1.2.0rc1 spooky-giraffe (2013-08-13) <ide> <ide> [Full Commit Log](https://github.com/angular/angular.js/compare/v1.1.5...master) <ide>
1
Ruby
Ruby
move requirement subclasses to a separate file
a1af5a6cc321d083d718f86d8821217634bff2c6
<ide><path>Library/Homebrew/dependencies.rb <ide> def hash <ide> end <ide> end <ide> <del> <del># A dependency on a language-specific module. <del>class LanguageModuleDependency < Requirement <del> def initialize language, module_name, import_name=nil <del> @language = language <del> @module_name = module_name <del> @import_name = import_name || module_name <del> end <del> <del> def fatal?; true; end <del> <del> def satisfied? <del> quiet_system(*the_test) <del> end <del> <del> def message; <<-EOS.undent <del> Unsatisfied dependency: #{@module_name} <del> Homebrew does not provide #{@language.to_s.capitalize} dependencies; install with: <del> #{command_line} #{@module_name} <del> EOS <del> end <del> <del> def the_test <del> case @language <del> when :chicken then %W{/usr/bin/env csi -e (use #{@import_name})} <del> when :jruby then %W{/usr/bin/env jruby -rubygems -e require\ '#{@import_name}'} <del> when :lua then %W{/usr/bin/env luarocks show #{@import_name}} <del> when :node then %W{/usr/bin/env node -e require('#{@import_name}');} <del> when :perl then %W{/usr/bin/env perl -e use\ #{@import_name}} <del> when :python then %W{/usr/bin/env python -c import\ #{@import_name}} <del> when :ruby then %W{/usr/bin/env ruby -rubygems -e require\ '#{@import_name}'} <del> when :rbx then %W{/usr/bin/env rbx -rubygems -e require\ '#{@import_name}'} <del> end <del> end <del> <del> def command_line <del> case @language <del> when :chicken then "chicken-install" <del> when :jruby then "jruby -S gem install" <del> when :lua then "luarocks install" <del> when :node then "npm install" <del> when :perl then "cpan -i" <del> when :python then "pip install" <del> when :rbx then "rbx gem install" <del> when :ruby then "gem install" <del> end <del> end <del>end <del> <del> <del># This requirement is used to require an X11 implementation, <del># optionally with a minimum version number. <del>class X11Dependency < Requirement <del> include Comparable <del> attr_reader :min_version <del> <del> def initialize min_version=nil <del> @min_version = min_version <del> end <del> <del> def fatal?; true; end <del> <del> def satisfied? <del> MacOS::XQuartz.installed? and (@min_version.nil? or @min_version <= MacOS::XQuartz.version) <del> end <del> <del> def message; <<-EOS.undent <del> Unsatisfied dependency: XQuartz #{@min_version} <del> Homebrew does not package XQuartz. Installers may be found at: <del> https://xquartz.macosforge.org <del> EOS <del> end <del> <del> def modify_build_environment <del> ENV.x11 <del> end <del> <del> def <=> other <del> unless other.is_a? X11Dependency <del> raise TypeError, "expected X11Dependency" <del> end <del> <del> if other.min_version.nil? <del> 1 <del> elsif @min_version.nil? <del> -1 <del> else <del> @min_version <=> other.min_version <del> end <del> end <del> <del>end <del> <del> <del># There are multiple implementations of MPI-2 available. <del># http://www.mpi-forum.org/ <del># This requirement is used to find an appropriate one. <del>class MPIDependency < Requirement <del> <del> attr_reader :lang_list <del> <del> def initialize *lang_list <del> @lang_list = lang_list <del> @non_functional = [] <del> @unknown_langs = [] <del> end <del> <del> def fatal?; true; end <del> <del> def mpi_wrapper_works? compiler <del> compiler = which compiler <del> return false if compiler.nil? or not compiler.executable? <del> <del> # Some wrappers are non-functional and will return a non-zero exit code <del> # when invoked for version info. <del> # <del> # NOTE: A better test may be to do a small test compilation a la autotools. <del> quiet_system compiler, '--version' <del> end <del> <del> def satisfied? <del> @lang_list.each do |lang| <del> case lang <del> when :cc, :cxx, :f90, :f77 <del> compiler = 'mpi' + lang.to_s <del> @non_functional << compiler unless mpi_wrapper_works? compiler <del> else <del> @unknown_langs << lang.to_s <del> end <del> end <del> <del> @unknown_langs.empty? and @non_functional.empty? <del> end <del> <del> def modify_build_environment <del> # Set environment variables to help configure scripts find MPI compilers. <del> # Variable names taken from: <del> # http://www.gnu.org/software/autoconf-archive/ax_mpi.html <del> lang_list.each do |lang| <del> compiler = 'mpi' + lang.to_s <del> mpi_path = which compiler <del> <del> # Fortran 90 environment var has a different name <del> compiler = 'MPIFC' if lang == :f90 <del> ENV[compiler.upcase] = mpi_path <del> end <del> end <del> <del> def message <del> if not @unknown_langs.empty? <del> <<-EOS.undent <del> There is no MPI compiler wrapper for: <del> #{@unknown_langs.join ', '} <del> <del> The following values are valid arguments to `MPIDependency.new`: <del> :cc, :cxx, :f90, :f77 <del> EOS <del> else <del> <<-EOS.undent <del> Homebrew could not locate working copies of the following MPI compiler <del> wrappers: <del> #{@non_functional.join ', '} <del> <del> If you have a MPI installation, please ensure the bin folder is on your <del> PATH and that all the wrappers are functional. Otherwise, a MPI <del> installation can be obtained from homebrew by *picking one* of the <del> following formulae: <del> open-mpi, mpich2 <del> EOS <del> end <del> end <del> <del>end <del> <del># This requirement added by the `conflicts_with` DSL method. <del>class ConflictRequirement < Requirement <del> attr_reader :formula <del> <del> def initialize formula, message <del> @formula = formula <del> @message = message <del> end <del> <del> def message; @message; end <del> <del> def satisfied? <del> keg = Formula.factory(@formula).prefix <del> not keg.exist? && Keg.new(keg).linked? <del> end <del> <del> # The user can chose to force installation even in the face of conflicts. <del> def fatal? <del> not ARGV.force? <del> end <del>end <del> <del>class XCodeDependency < Requirement <del> def fatal?; true; end <del> <del> def satisfied? <del> MacOS::Xcode.installed? <del> end <del> <del> def message; <<-EOS.undent <del> A full installation of XCode.app is required to compile this software. <del> Installing just the Command Line Tools is not sufficent. <del> EOS <del> end <del>end <add>require 'requirements' <ide><path>Library/Homebrew/requirements.rb <add># A dependency on a language-specific module. <add>class LanguageModuleDependency < Requirement <add> def initialize language, module_name, import_name=nil <add> @language = language <add> @module_name = module_name <add> @import_name = import_name || module_name <add> end <add> <add> def fatal?; true; end <add> <add> def satisfied? <add> quiet_system(*the_test) <add> end <add> <add> def message; <<-EOS.undent <add> Unsatisfied dependency: #{@module_name} <add> Homebrew does not provide #{@language.to_s.capitalize} dependencies; install with: <add> #{command_line} #{@module_name} <add> EOS <add> end <add> <add> def the_test <add> case @language <add> when :chicken then %W{/usr/bin/env csi -e (use #{@import_name})} <add> when :jruby then %W{/usr/bin/env jruby -rubygems -e require\ '#{@import_name}'} <add> when :lua then %W{/usr/bin/env luarocks show #{@import_name}} <add> when :node then %W{/usr/bin/env node -e require('#{@import_name}');} <add> when :perl then %W{/usr/bin/env perl -e use\ #{@import_name}} <add> when :python then %W{/usr/bin/env python -c import\ #{@import_name}} <add> when :ruby then %W{/usr/bin/env ruby -rubygems -e require\ '#{@import_name}'} <add> when :rbx then %W{/usr/bin/env rbx -rubygems -e require\ '#{@import_name}'} <add> end <add> end <add> <add> def command_line <add> case @language <add> when :chicken then "chicken-install" <add> when :jruby then "jruby -S gem install" <add> when :lua then "luarocks install" <add> when :node then "npm install" <add> when :perl then "cpan -i" <add> when :python then "pip install" <add> when :rbx then "rbx gem install" <add> when :ruby then "gem install" <add> end <add> end <add>end <add> <add> <add># This requirement is used to require an X11 implementation, <add># optionally with a minimum version number. <add>class X11Dependency < Requirement <add> include Comparable <add> attr_reader :min_version <add> <add> def initialize min_version=nil <add> @min_version = min_version <add> end <add> <add> def fatal?; true; end <add> <add> def satisfied? <add> MacOS::XQuartz.installed? and (@min_version.nil? or @min_version <= MacOS::XQuartz.version) <add> end <add> <add> def message; <<-EOS.undent <add> Unsatisfied dependency: XQuartz #{@min_version} <add> Homebrew does not package XQuartz. Installers may be found at: <add> https://xquartz.macosforge.org <add> EOS <add> end <add> <add> def modify_build_environment <add> ENV.x11 <add> end <add> <add> def <=> other <add> unless other.is_a? X11Dependency <add> raise TypeError, "expected X11Dependency" <add> end <add> <add> if other.min_version.nil? <add> 1 <add> elsif @min_version.nil? <add> -1 <add> else <add> @min_version <=> other.min_version <add> end <add> end <add> <add>end <add> <add> <add># There are multiple implementations of MPI-2 available. <add># http://www.mpi-forum.org/ <add># This requirement is used to find an appropriate one. <add>class MPIDependency < Requirement <add> <add> attr_reader :lang_list <add> <add> def initialize *lang_list <add> @lang_list = lang_list <add> @non_functional = [] <add> @unknown_langs = [] <add> end <add> <add> def fatal?; true; end <add> <add> def mpi_wrapper_works? compiler <add> compiler = which compiler <add> return false if compiler.nil? or not compiler.executable? <add> <add> # Some wrappers are non-functional and will return a non-zero exit code <add> # when invoked for version info. <add> # <add> # NOTE: A better test may be to do a small test compilation a la autotools. <add> quiet_system compiler, '--version' <add> end <add> <add> def satisfied? <add> @lang_list.each do |lang| <add> case lang <add> when :cc, :cxx, :f90, :f77 <add> compiler = 'mpi' + lang.to_s <add> @non_functional << compiler unless mpi_wrapper_works? compiler <add> else <add> @unknown_langs << lang.to_s <add> end <add> end <add> <add> @unknown_langs.empty? and @non_functional.empty? <add> end <add> <add> def modify_build_environment <add> # Set environment variables to help configure scripts find MPI compilers. <add> # Variable names taken from: <add> # http://www.gnu.org/software/autoconf-archive/ax_mpi.html <add> lang_list.each do |lang| <add> compiler = 'mpi' + lang.to_s <add> mpi_path = which compiler <add> <add> # Fortran 90 environment var has a different name <add> compiler = 'MPIFC' if lang == :f90 <add> ENV[compiler.upcase] = mpi_path <add> end <add> end <add> <add> def message <add> if not @unknown_langs.empty? <add> <<-EOS.undent <add> There is no MPI compiler wrapper for: <add> #{@unknown_langs.join ', '} <add> <add> The following values are valid arguments to `MPIDependency.new`: <add> :cc, :cxx, :f90, :f77 <add> EOS <add> else <add> <<-EOS.undent <add> Homebrew could not locate working copies of the following MPI compiler <add> wrappers: <add> #{@non_functional.join ', '} <add> <add> If you have a MPI installation, please ensure the bin folder is on your <add> PATH and that all the wrappers are functional. Otherwise, a MPI <add> installation can be obtained from homebrew by *picking one* of the <add> following formulae: <add> open-mpi, mpich2 <add> EOS <add> end <add> end <add> <add>end <add> <add># This requirement added by the `conflicts_with` DSL method. <add>class ConflictRequirement < Requirement <add> attr_reader :formula <add> <add> def initialize formula, message <add> @formula = formula <add> @message = message <add> end <add> <add> def message; @message; end <add> <add> def satisfied? <add> keg = Formula.factory(@formula).prefix <add> not keg.exist? && Keg.new(keg).linked? <add> end <add> <add> # The user can chose to force installation even in the face of conflicts. <add> def fatal? <add> not ARGV.force? <add> end <add>end <add> <add>class XCodeDependency < Requirement <add> def fatal?; true; end <add> <add> def satisfied? <add> MacOS::Xcode.installed? <add> end <add> <add> def message; <<-EOS.undent <add> A full installation of XCode.app is required to compile this software. <add> Installing just the Command Line Tools is not sufficent. <add> EOS <add> end <add>end
2
Ruby
Ruby
install invisible files and dirs
21ca138edf584daebf1795a52d6edd6ec34ce605
<ide><path>Library/Homebrew/resource.rb <ide> def unpack(target = nil) <ide> yield ResourceStageContext.new(self, staging) <ide> elsif target <ide> target = Pathname.new(target) unless target.is_a? Pathname <del> target.install Dir["*"] <add> target.install Pathname.pwd.children <ide> end <ide> end <ide> end
1
Javascript
Javascript
handle smartos bug in test-tls-session-cache
fb4c022fbe0dd3182cfc6d19fe8710402d9697ca
<ide><path>test/parallel/test-tls-session-cache.js <ide> 'use strict'; <del>var common = require('../common'); <add>const common = require('../common'); <ide> <ide> if (!common.opensslCli) { <ide> common.skip('node compiled without OpenSSL CLI.'); <ide> doTest({ tickets: false }, function() { <ide> }); <ide> <ide> function doTest(testOptions, callback) { <del> var assert = require('assert'); <del> var tls = require('tls'); <del> var fs = require('fs'); <del> var join = require('path').join; <del> var spawn = require('child_process').spawn; <add> const assert = require('assert'); <add> const tls = require('tls'); <add> const fs = require('fs'); <add> const join = require('path').join; <add> const spawn = require('child_process').spawn; <ide> <del> var keyFile = join(common.fixturesDir, 'agent.key'); <del> var certFile = join(common.fixturesDir, 'agent.crt'); <del> var key = fs.readFileSync(keyFile); <del> var cert = fs.readFileSync(certFile); <del> var options = { <add> const keyFile = join(common.fixturesDir, 'agent.key'); <add> const certFile = join(common.fixturesDir, 'agent.crt'); <add> const key = fs.readFileSync(keyFile); <add> const cert = fs.readFileSync(certFile); <add> const options = { <ide> key: key, <ide> cert: cert, <ide> ca: [cert], <ide> function doTest(testOptions, callback) { <ide> var resumeCount = 0; <ide> var session; <ide> <del> var server = tls.createServer(options, function(cleartext) { <add> const server = tls.createServer(options, function(cleartext) { <ide> cleartext.on('error', function(er) { <ide> // We're ok with getting ECONNRESET in this test, but it's <ide> // timing-dependent, and thus unreliable. Any other errors <ide> function doTest(testOptions, callback) { <ide> }); <ide> <ide> server.listen(0, function() { <del> var args = [ <add> const args = [ <ide> 's_client', <ide> '-tls1', <ide> '-connect', `localhost:${this.address().port}`, <ide> function doTest(testOptions, callback) { <ide> if (common.isWindows) <ide> args.push('-no_rand_screen'); <ide> <del> var client = spawn(common.opensslCli, args, { <del> stdio: [ 0, 1, 'pipe' ] <del> }); <del> var err = ''; <del> client.stderr.setEncoding('utf8'); <del> client.stderr.on('data', function(chunk) { <del> err += chunk; <del> }); <del> client.on('exit', function(code) { <del> console.error('done'); <del> assert.equal(code, 0); <del> server.close(function() { <del> setTimeout(callback, 100); <add> function spawnClient() { <add> const client = spawn(common.opensslCli, args, { <add> stdio: [ 0, 1, 'pipe' ] <ide> }); <del> }); <add> var err = ''; <add> client.stderr.setEncoding('utf8'); <add> client.stderr.on('data', function(chunk) { <add> err += chunk; <add> }); <add> <add> client.on('exit', common.mustCall(function(code, signal) { <add> if (code !== 0) { <add> // If SmartOS and connection refused, then retry. See <add> // https://github.com/nodejs/node/issues/2663. <add> if (common.isSunOS && err.includes('Connection refused')) { <add> requestCount = 0; <add> spawnClient(); <add> return; <add> } <add> common.fail(`code: ${code}, signal: ${signal}, output: ${err}`); <add> } <add> assert.equal(code, 0); <add> server.close(common.mustCall(function() { <add> setTimeout(callback, 100); <add> })); <add> })); <add> } <add> <add> spawnClient(); <ide> }); <ide> <ide> process.on('exit', function() {
1
Javascript
Javascript
fix tests, filter nullish test cases
ac0b340fb2b3617ec626666971743235ce1ce458
<ide><path>test/cases/parsing/nullish-coalescing/test.filter.js <add>var supportsNullishCoalescing = require("../../../helpers/supportsNullishCoalescing"); <add> <add>module.exports = function (config) { <add> return supportsNullishCoalescing(); <add>};
1
PHP
PHP
generate keys of the correct length
97a1ae2f68f692b7f6c3d0dc3bd285d4bef119e0
<ide><path>src/Illuminate/Foundation/Console/KeyGenerateCommand.php <ide> <ide> namespace Illuminate\Foundation\Console; <ide> <del>use Illuminate\Support\Str; <ide> use Illuminate\Console\Command; <ide> use Symfony\Component\Console\Input\InputOption; <ide> <ide> class KeyGenerateCommand extends Command <ide> */ <ide> public function fire() <ide> { <del> $key = $this->getRandomKey(); <add> $key = $this->getRandomKey($this->laravel['config']['app.cipher']); <ide> <ide> if ($this->option('show')) { <ide> return $this->line('<comment>'.$key.'</comment>'); <ide> public function fire() <ide> /** <ide> * Generate a random key for the application. <ide> * <add> * @param string $cipher <ide> * @return string <ide> */ <del> protected function getRandomKey() <add> protected function getRandomKey($cipher) <ide> { <del> return Str::random(32); <add> if ($cipher === 'AES-128-CBC') { <add> return str_random(16); <add> } <add> <add> return str_random(32); <ide> } <ide> <ide> /**
1
Javascript
Javascript
add more owner context to monitoring
620c1bc2ffa0026bc1ac3a238bd1158cb16a06e7
<ide><path>src/core/ReactComponent.js <ide> function validateExplicitKey(component) { <ide> <ide> var message = 'Each child in an array should have a unique "key" prop. ' + <ide> 'Check the render method of ' + currentName + '.'; <add> <add> var childOwnerName = null; <ide> if (!component.isOwnedBy(ReactCurrentOwner.current)) { <ide> // Name of the component that originally created this child. <del> var childOwnerName = <add> childOwnerName = <ide> component._owner && <ide> component._owner.constructor.displayName; <ide> <ide> function validateExplicitKey(component) { <ide> } <ide> <ide> message += ' See http://fb.me/react-warning-keys for more information.'; <del> monitorCodeUse('react_key_warning'); <add> monitorCodeUse('react_key_warning', { <add> component: currentName, <add> componentOwner: childOwnerName <add> }); <ide> console.warn(message); <ide> } <ide>
1
Javascript
Javascript
fix broken build system for lite and min tasks
522b9cf35f30d0dc83e03f2425c5cbdccfbdc812
<ide><path>build/build/lite.js <del>load("../jquerybuild/js/writeFile.js"); <add>load("../jquery/build/js/writeFile.js"); <ide> <ide> var blockMatch = /\s*\/\*\*\s*((.|\n|\r\n)*?)\s*\*\/\n*/g; <ide> var f = readFile(arguments[0]).replace( blockMatch, "\n" ).replace( /\n\n+/g, "\n\n" ); <ide><path>build/build/min.js <del>load("../jquerybuild/js/jsmin.js", "../jquerybuild/js/writeFile.js"); <add>load("../jquery/build/js/jsmin.js", "../jquery/build/js/writeFile.js"); <ide> <ide> var f = jsmin('', readFile(arguments[0]), 3); <ide>
2
Java
Java
replace word "request" with "response"
db424d0bc5b5a8b6d77062039f260edea02bfb66
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/client/ClientResponse.java <ide> public interface ClientResponse { <ide> /** <ide> * Return a builder to mutate this response, for example to change <ide> * the status, headers, cookies, and replace or transform the body. <del> * @return a builder to mutate the request with <add> * @return a builder to mutate the response with <ide> * @since 5.3 <ide> */ <ide> default Builder mutate() {
1
Ruby
Ruby
use pathname.glob when we want pathname objects
a023f10310bfd11379202de87c28a7594fdfd363
<ide><path>Library/Homebrew/extend/pathname.rb <ide> def write_env_script target, env <ide> # Writes a wrapper env script and moves all files to the dst <ide> def env_script_all_files dst, env <ide> dst.mkpath <del> Dir["#{self}/*"].each do |file| <del> file = Pathname.new(file) <add> Pathname.glob("#{self}/*") do |file| <ide> dst.install_p file <ide> new_file = dst+file.basename <ide> file.write_env_script(new_file, env) <ide><path>Library/Homebrew/formula_installer.rb <ide> def pour <ide> downloader.stage <ide> end <ide> <del> Dir["#{f.bottle_prefix}/{etc,var}/**/*"].each do |file| <del> path = Pathname.new(file) <add> Pathname.glob("#{f.bottle_prefix}/{etc,var}/**/*") do |path| <ide> path.extend(InstallRenamed) <ide> path.cp_path_sub(f.bottle_prefix, HOMEBREW_PREFIX) <ide> end
2
Python
Python
fix reporting if no dev data with train
4f9657b42b79af4c640b67e1d2740b9d901d5aba
<ide><path>spacy/cli/train.py <ide> from __future__ import unicode_literals, division, print_function <ide> <ide> import json <add>from collections import defaultdict <ide> <ide> from ..util import ensure_path <ide> from ..scorer import Scorer <ide> def train_model(Language, train_data, dev_data, output_path, tagger_cfg, parser_ <ide> for itn, epoch in enumerate(trainer.epochs(n_iter, augment_data=None)): <ide> for doc, gold in epoch: <ide> trainer.update(doc, gold) <del> dev_scores = trainer.evaluate(dev_data).scores if dev_data else {} <add> dev_scores = trainer.evaluate(dev_data).scores if dev_data else defaultdict(float) <ide> print_progress(itn, trainer.nlp.parser.model.nr_weight, <ide> trainer.nlp.parser.model.nr_active_feat, <ide> **dev_scores)
1
PHP
PHP
use proper instance of relation
2f263dce2948559dafb9944eab146d0721e9d7a5
<ide><path>src/Illuminate/Database/Eloquent/Model.php <ide> use Illuminate\Database\Eloquent\Relations\HasMany; <ide> use Illuminate\Support\Contracts\JsonableInterface; <ide> use Illuminate\Support\Contracts\ArrayableInterface; <add>use Illuminate\Database\Eloquent\Relations\Relation; <ide> use Illuminate\Database\Eloquent\Relations\MorphOne; <ide> use Illuminate\Database\Eloquent\Relations\MorphMany; <ide> use Illuminate\Database\Eloquent\Relations\BelongsTo;
1
Javascript
Javascript
use base plugin for web and node
c2f1c4f123ad6c4e2e83707396714b5448925276
<ide><path>lib/BaseWasmMainTemplatePlugin.js <add>/* <add> MIT License http://www.opensource.org/licenses/mit-license.php <add> Author Tobias Koppers @sokra <add>*/ <add>"use strict"; <add> <add>const Template = require("./Template"); <add>const WebAssemblyImportDependency = require("./dependencies/WebAssemblyImportDependency"); <add> <add>// Get all wasm modules <add>function getAllWasmModules(chunk) { <add> const wasmModules = chunk.getAllAsyncChunks(); <add> const array = []; <add> for (const chunk of wasmModules) { <add> for (const m of chunk.modulesIterable) { <add> if (m.type.startsWith("webassembly")) { <add> array.push(m); <add> } <add> } <add> } <add> <add> return array; <add>} <add> <add>function generateImportObject(module) { <add> const depsByRequest = new Map(); <add> for (const dep of module.dependencies) { <add> if (dep instanceof WebAssemblyImportDependency) { <add> // Ignore global they will be handled later <add> if (dep.description.type === "GlobalType") { <add> continue; <add> } <add> <add> const request = dep.request; <add> let array = depsByRequest.get(request); <add> if (!array) { <add> depsByRequest.set(request, (array = [])); <add> } <add> const exportName = dep.name; <add> const usedName = dep.module && dep.module.isUsed(exportName); <add> array.push({ <add> exportName, <add> usedName, <add> module: dep.module, <add> description: dep.description <add> }); <add> } <add> } <add> const importsCode = []; <add> for (const pair of depsByRequest) { <add> const properties = []; <add> for (const data of pair[1]) { <add> let params = ""; <add> let result = "void 0"; <add> <add> if (data.description.type === "FuncImportDescr") { <add> params = data.description.params.map( <add> (param, k) => "p" + k + param.valtype <add> ); <add> <add> result = `__webpack_require__(${JSON.stringify( <add> data.module.id <add> )})[${JSON.stringify(data.usedName)}](${params})`; <add> } <add> <add> properties.push( <add> `\n\t\t${JSON.stringify(data.exportName)}: function(${params}) { <add> return ${result}; <add> }` <add> ); <add> } <add> importsCode.push( <add> `\n\t${JSON.stringify(pair[0])}: {${properties.join(",")}\n\t}` <add> ); <add> } <add> <add> return JSON.stringify(module.id) + ": {" + importsCode.join(",") + "\n},"; <add>} <add> <add>class BaseWasmMainTemplatePlugin { <add> applyWeb(mainTemplate) { <add> const generateLoadBinaryCode = path => <add> `fetch(${mainTemplate.requireFn}.p + ${path})`; <add> <add> this.apply(mainTemplate, generateLoadBinaryCode); <add> } <add> <add> applyNode(mainTemplate) { <add> const generateLoadBinaryCode = path => ` <add> new Promise(function (resolve, reject) { <add> try { <add> fs.readFile(${path}, function(err, buffer){ <add> if (err) reject(err); else resolve(buffer); <add> }); <add> } catch (err) { <add> reject(err); <add> } <add> }); <add> `; <add> <add> this.apply(mainTemplate, generateLoadBinaryCode); <add> } <add> <add> apply(mainTemplate, generateLoadBinaryCode) { <add> mainTemplate.hooks.localVars.tap( <add> "BaseWasmMainTemplatePlugin", <add> (source, chunk) => { <add> if (!chunk.hasModuleInGraph(m => m.type.startsWith("webassembly"))) <add> return source; <add> return Template.asString([ <add> source, <add> "", <add> "// object to store loaded and loading wasm modules", <add> "var installedWasmModules = {};" <add> ]); <add> } <add> ); <add> mainTemplate.hooks.requireEnsure.tap( <add> "BaseWasmMainTemplatePlugin", <add> (source, chunk, hash) => { <add> const webassemblyModuleFilename = <add> mainTemplate.outputOptions.webassemblyModuleFilename; <add> <add> const wasmModules = getAllWasmModules(chunk); <add> const importObjects = wasmModules.map(generateImportObject); <add> <add> const chunkModuleMaps = chunk.getChunkModuleMaps(m => <add> m.type.startsWith("webassembly") <add> ); <add> if (Object.keys(chunkModuleMaps.id).length === 0) return source; <add> const wasmModuleSrcPath = mainTemplate.getAssetPath( <add> JSON.stringify(webassemblyModuleFilename), <add> { <add> hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, <add> hashWithLength: length => <add> `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`, <add> module: { <add> id: '" + wasmModuleId + "', <add> hash: `" + ${JSON.stringify( <add> chunkModuleMaps.hash <add> )}[wasmModuleId] + "`, <add> hashWithLength(length) { <add> const shortChunkHashMap = Object.create(null); <add> for (const wasmModuleId of Object.keys(chunkModuleMaps.hash)) { <add> if (typeof chunkModuleMaps.hash[wasmModuleId] === "string") <add> shortChunkHashMap[wasmModuleId] = chunkModuleMaps.hash[ <add> wasmModuleId <add> ].substr(0, length); <add> } <add> return `" + ${JSON.stringify( <add> shortChunkHashMap <add> )}[wasmModuleId] + "`; <add> } <add> } <add> } <add> ); <add> return Template.asString([ <add> source, <add> "", <add> "// Fetch + compile chunk loading for webassembly", <add> "", <add> "var importObjects = {", <add> Template.indent([importObjects]), <add> "}", <add> "", <add> `var wasmModules = ${JSON.stringify( <add> chunkModuleMaps.id <add> )}[chunkId] || [];`, <add> "", <add> "wasmModules.forEach(function(wasmModuleId) {", <add> Template.indent([ <add> "var installedWasmModuleData = installedWasmModules[wasmModuleId];", <add> "", <add> '// a Promise means "currently loading" or "already loaded".', <add> Template.indent([ <add> `var importObject = importObjects[wasmModuleId]`, <add> `var req = ${generateLoadBinaryCode(wasmModuleSrcPath)}`, <add> "if(typeof WebAssembly.instantiateStreaming !== 'function') {", <add> Template.indent([ <add> "promises.push(WebAssembly.instantiateStreaming(req, importObject)", <add> ".then(function(res) {", <add> Template.indent([ <add> `${ <add> mainTemplate.requireFn <add> }.w[wasmModuleId] = installedWasmModules[wasmModuleId] = res.instance;` <add> ]), <add> "}))" <add> ]), <add> "} else {", <add> Template.indent([ <add> "var promise = req.then(x => x.arrayBuffer()).then(function(bytes) {", <add> Template.indent([ <add> "return WebAssembly.instantiate(bytes, importObject);" <add> ]), <add> "}).then(function(res) {", <add> Template.indent([ <add> `${ <add> mainTemplate.requireFn <add> }.w[wasmModuleId] = installedWasmModules[wasmModuleId] = res.instance;`, <add> "return res.instance" <add> ]), <add> "})", <add> "promises.push(promise);" <add> ]), <add> "}" <add> ]) <add> ]), <add> "});" <add> ]); <add> } <add> ); <add> mainTemplate.hooks.requireExtensions.tap( <add> "BaseWasmMainTemplatePlugin", <add> (source, chunk) => { <add> if (!chunk.hasModuleInGraph(m => m.type.startsWith("webassembly"))) <add> return source; <add> return Template.asString([ <add> source, <add> "", <add> "// object with all WebAssembly.instance", <add> `${mainTemplate.requireFn}.w = {};` <add> ]); <add> } <add> ); <add> mainTemplate.hooks.hash.tap("BaseWasmMainTemplatePlugin", hash => { <add> hash.update("BaseWasmMainTemplatePlugin"); <add> hash.update("1"); <add> hash.update(`${mainTemplate.outputOptions.webassemblyModuleFilename}`); <add> }); <add> } <add>} <add> <add>module.exports = BaseWasmMainTemplatePlugin; <ide><path>lib/node/ReadFileCompileWasmTemplatePlugin.js <ide> */ <ide> "use strict"; <ide> <del>const FetchCompileWasmMainTemplatePlugin = require("../web/FetchCompileWasmMainTemplatePlugin"); <add>const BaseWasmMainTemplatePlugin = require("../BaseWasmMainTemplatePlugin"); <ide> const WasmModuleTemplatePlugin = require("../wasm/WasmModuleTemplatePlugin"); <ide> <ide> class ReadFileCompileWasmTemplatePlugin { <ide> apply(compiler) { <ide> compiler.hooks.thisCompilation.tap( <ide> "ReadFileCompileWasmTemplatePlugin", <ide> compilation => { <del> new FetchCompileWasmMainTemplatePlugin().apply( <del> compilation.mainTemplate <del> ); <add> new BaseWasmMainTemplatePlugin().applyNode(compilation.mainTemplate); <ide> new WasmModuleTemplatePlugin().apply( <ide> compilation.moduleTemplates.javascript <ide> ); <ide><path>lib/web/FetchCompileWasmMainTemplatePlugin.js <ide> */ <ide> "use strict"; <ide> <del>const Template = require("../Template"); <del>const WebAssemblyImportDependency = require("../dependencies/WebAssemblyImportDependency"); <add>const BaseWasmMainTemplatePlugin = require("../BaseWasmMainTemplatePlugin"); <ide> <ide> class FetchCompileWasmMainTemplatePlugin { <ide> apply(mainTemplate) { <del> mainTemplate.hooks.localVars.tap( <del> "FetchCompileWasmMainTemplatePlugin", <del> (source, chunk) => { <del> if (!chunk.hasModuleInGraph(m => m.type.startsWith("webassembly"))) <del> return source; <del> return Template.asString([ <del> source, <del> "", <del> "// object to store loaded and loading wasm modules", <del> "var installedWasmModules = {};" <del> ]); <del> } <del> ); <del> mainTemplate.hooks.requireEnsure.tap( <del> "FetchCompileWasmMainTemplatePlugin", <del> (source, chunk, hash) => { <del> const webassemblyModuleFilename = <del> mainTemplate.outputOptions.webassemblyModuleFilename; <del> <del> // Get all wasm modules <del> function getAllWasmModules() { <del> const wasmModules = chunk.getAllAsyncChunks(); <del> const array = []; <del> for (const chunk of wasmModules) { <del> for (const m of chunk.modulesIterable) { <del> if (m.type.startsWith("webassembly")) { <del> array.push(m); <del> } <del> } <del> } <del> <del> return array; <del> } <del> <del> function generateImportObject(module) { <del> const depsByRequest = new Map(); <del> for (const dep of module.dependencies) { <del> if (dep instanceof WebAssemblyImportDependency) { <del> // Ignore global they will be handled later <del> if (dep.description.type === "GlobalType") { <del> continue; <del> } <del> <del> const request = dep.request; <del> let array = depsByRequest.get(request); <del> if (!array) { <del> depsByRequest.set(request, (array = [])); <del> } <del> const exportName = dep.name; <del> const usedName = dep.module && dep.module.isUsed(exportName); <del> array.push({ <del> exportName, <del> usedName, <del> module: dep.module, <del> description: dep.description <del> }); <del> } <del> } <del> const importsCode = []; <del> for (const pair of depsByRequest) { <del> const properties = []; <del> for (const data of pair[1]) { <del> let params = ""; <del> let result = "void 0"; <del> <del> if (data.description.type === "FuncImportDescr") { <del> params = data.description.params.map( <del> (param, k) => "p" + k + param.valtype <del> ); <del> <del> result = `__webpack_require__(${JSON.stringify( <del> data.module.id <del> )})[${JSON.stringify(data.usedName)}](${params})`; <del> } <del> <del> properties.push( <del> `\n\t\t${JSON.stringify(data.exportName)}: function(${params}) { <del> return ${result}; <del> }` <del> ); <del> } <del> importsCode.push( <del> `\n\t${JSON.stringify(pair[0])}: {${properties.join(",")}\n\t}` <del> ); <del> } <del> <del> return ( <del> JSON.stringify(module.id) + ": {" + importsCode.join(",") + "\n}," <del> ); <del> } <del> <del> const wasmModules = getAllWasmModules(); <del> const importObjects = wasmModules.map(generateImportObject); <del> <del> const chunkModuleMaps = chunk.getChunkModuleMaps(m => <del> m.type.startsWith("webassembly") <del> ); <del> if (Object.keys(chunkModuleMaps.id).length === 0) return source; <del> const wasmModuleSrcPath = mainTemplate.getAssetPath( <del> JSON.stringify(webassemblyModuleFilename), <del> { <del> hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, <del> hashWithLength: length => <del> `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`, <del> module: { <del> id: '" + wasmModuleId + "', <del> hash: `" + ${JSON.stringify( <del> chunkModuleMaps.hash <del> )}[wasmModuleId] + "`, <del> hashWithLength(length) { <del> const shortChunkHashMap = Object.create(null); <del> for (const wasmModuleId of Object.keys(chunkModuleMaps.hash)) { <del> if (typeof chunkModuleMaps.hash[wasmModuleId] === "string") <del> shortChunkHashMap[wasmModuleId] = chunkModuleMaps.hash[ <del> wasmModuleId <del> ].substr(0, length); <del> } <del> return `" + ${JSON.stringify( <del> shortChunkHashMap <del> )}[wasmModuleId] + "`; <del> } <del> } <del> } <del> ); <del> return Template.asString([ <del> source, <del> "", <del> "// Fetch + compile chunk loading for webassembly", <del> "", <del> "var importObjects = {", <del> Template.indent([importObjects]), <del> "}", <del> "", <del> `var wasmModules = ${JSON.stringify( <del> chunkModuleMaps.id <del> )}[chunkId] || [];`, <del> "", <del> "wasmModules.forEach(function(wasmModuleId) {", <del> Template.indent([ <del> "var installedWasmModuleData = installedWasmModules[wasmModuleId];", <del> "", <del> '// a Promise means "currently loading" or "already loaded".', <del> Template.indent([ <del> `var importObject = importObjects[wasmModuleId]`, <del> `var req = fetch(${mainTemplate.requireFn}.p + ${ <del> wasmModuleSrcPath <del> })`, <del> "if(WebAssembly.instantiateStreaming) {", <del> Template.indent([ <del> "promises.push(WebAssembly.instantiateStreaming(req, importObject)", <del> `.then(function(res) { ${ <del> mainTemplate.requireFn <del> }.w[wasmModuleId] = installedWasmModules[wasmModuleId] = res.instance;`, <del> "}))" <del> ]), <del> "} else {", <del> Template.indent([ <del> // FIXME(sven): ensrue this still works / change it <del> "promises.push(response.arrayBuffer().then(function(bytes) { installedWasmModules[wasmModuleId] = WebAssembly.compile(bytes); }));" <del> ]), <del> "}" <del> ]) <del> ]), <del> "});" <del> ]); <del> } <del> ); <del> mainTemplate.hooks.requireExtensions.tap( <del> "FetchCompileWasmMainTemplatePlugin", <del> (source, chunk) => { <del> if (!chunk.hasModuleInGraph(m => m.type.startsWith("webassembly"))) <del> return source; <del> return Template.asString([ <del> source, <del> "", <del> "// object with all WebAssembly.instance", <del> `${mainTemplate.requireFn}.w = {};` <del> ]); <del> } <del> ); <del> mainTemplate.hooks.hash.tap("FetchCompileWasmMainTemplatePlugin", hash => { <del> hash.update("FetchCompileWasmMainTemplatePlugin"); <del> hash.update("1"); <del> hash.update(`${mainTemplate.outputOptions.webassemblyModuleFilename}`); <del> }); <add> new BaseWasmMainTemplatePlugin().applyWeb(mainTemplate); <ide> } <ide> } <add> <ide> module.exports = FetchCompileWasmMainTemplatePlugin;
3
Ruby
Ruby
simplify load and require tests
cfc467f73e801717325b4addef4fa05798462d5c
<ide><path>activesupport/test/dependencies_test.rb <ide> def test_require_returns_true_when_file_not_yet_required <ide> original_features = $".dup <ide> $:.push(path) <ide> <del> with_loading('autoloading_fixtures/load_path') do <add> with_loading do <ide> assert_equal true, require('loaded_constant') <ide> end <ide> ensure <ide> def test_require_returns_true_when_file_not_yet_required_even_when_no_new_consta <ide> original_features = $".dup <ide> $:.push(path) <ide> <del> with_loading('autoloading_fixtures/load_path') do <add> with_loading do <ide> Object.module_eval "module LoadedConstant; end" <ide> assert_equal true, require('loaded_constant') <ide> end <ide> def test_require_returns_false_when_file_already_required <ide> original_features = $".dup <ide> $:.push(path) <ide> <del> with_loading('autoloading_fixtures/load_path') do <add> with_loading do <ide> require 'loaded_constant' <ide> assert_equal false, require('loaded_constant') <ide> end <ide> def test_load_returns_true_when_file_found <ide> original_features = $".dup <ide> $:.push(path) <ide> <del> with_loading('autoloading_fixtures/load_path') do <add> with_loading do <ide> assert_equal true, load('loaded_constant.rb') <ide> assert_equal true, load('loaded_constant.rb') <ide> end
1
Python
Python
fix a bug in assert_string_equal
eadc135a5f2ab577748188770af66feafe87859d
<ide><path>numpy/testing/tests/test_utils.py <ide> assert_array_almost_equal, build_err_msg, raises, assert_raises, <ide> assert_warns, assert_no_warnings, assert_allclose, assert_approx_equal, <ide> assert_array_almost_equal_nulp, assert_array_max_ulp, <del> clear_and_catch_warnings, run_module_suite <add> clear_and_catch_warnings, run_module_suite, <add> assert_string_equal <ide> ) <ide> import unittest <ide> <ide> def test_nan(self): <ide> lambda: assert_array_max_ulp(nan, nzero, <ide> maxulp=maxulp)) <ide> <add>class TestStringEqual(unittest.TestCase): <add> def test_simple(self): <add> assert_string_equal("hello", "hello") <add> assert_string_equal("hello\nmultiline", "hello\nmultiline") <add> <add> try: <add> assert_string_equal("foo\nbar", "hello\nbar") <add> except AssertionError as exc: <add> assert_equal(str(exc), "Differences in strings:\n- foo\n+ hello") <add> else: <add> raise AssertionError("exception not raised") <add> <add> self.assertRaises(AssertionError, <add> lambda: assert_string_equal("foo", "hello")) <add> <add> <ide> def assert_warn_len_equal(mod, n_in_context): <ide> mod_warns = mod.__warningregistry__ <ide> # Python 3.4 appears to clear any pre-existing warnings of the same type, <ide><path>numpy/testing/utils.py <ide> def assert_string_equal(actual, desired): <ide> if not d2.startswith('+ '): <ide> raise AssertionError(repr(d2)) <ide> l.append(d2) <del> d3 = diff.pop(0) <del> if d3.startswith('? '): <del> l.append(d3) <del> else: <del> diff.insert(0, d3) <add> if diff: <add> d3 = diff.pop(0) <add> if d3.startswith('? '): <add> l.append(d3) <add> else: <add> diff.insert(0, d3) <ide> if re.match(r'\A'+d2[2:]+r'\Z', d1[2:]): <ide> continue <ide> diff_list.extend(l)
2
Javascript
Javascript
fix paths for ember-source addon
65f35c8a6e37785988c753f4328e9c27d5c6974b
<ide><path>lib/index.js <ide> module.exports = { <ide> files: ['jquery.js'], <ide> }); <ide> <add> let emberSourceDistPath = path.join(__dirname, '..', 'dist'); <ide> var emberFiles = [ <ide> 'ember-runtime.js', <ide> 'ember-template-compiler.js', <ide> module.exports = { <ide> return flat.concat(jsAndMap); <ide> }, []) <ide> .filter(function(file) { <del> var fullPath = path.join(__dirname, '..', 'dist', file); <add> var fullPath = path.join(emberSourceDistPath, file); <ide> <ide> return fs.existsSync(fullPath); <ide> }); <ide> <del> var ember = new Funnel(__dirname + '../dist', { <add> var ember = new Funnel(emberSourceDistPath, { <ide> destDir: 'ember', <ide> files: emberFiles, <ide> });
1