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 nobridge prefix to venice metro logs
8a677face45735c80e76c78b3f1633e02491c28f
<ide><path>Libraries/Utilities/HMRClient.js <ide> const HMRClient: HMRClientNativeInterface = { <ide> JSON.stringify({ <ide> type: 'log', <ide> level, <add> mode: global.RN$Bridgeless ? 'NOBRIDGE' : 'BRIDGE', <ide> data: data.map(item => <ide> typeof item === 'string' <ide> ? item
1
Text
Text
fix some links
4d1e0862ced8134b1b4e57480bbd46ca14e61d0f
<ide><path>doc/api/dns.md <ide> added: v0.1.27 <ide> - `rrtype` {string} Resource record type. Default: `'A'`. <ide> - `callback` {Function} <ide> - `err` {Error} <del> - `records` {string[] | Object[] | string[][] | Object} <add> - `records` {string[] | Object[] | Object} <ide> <ide> Uses the DNS protocol to resolve a hostname (e.g. `'nodejs.org'`) into an array <ide> of the resource records. The `callback` function has arguments <ide> added: v0.1.27 <ide> - `hostname` {string} <ide> - `callback` {Function} <ide> - `err` {Error} <del> - `addresses` {string[][]} <add> - `addresses` {string[]} <ide> <ide> Uses the DNS protocol to resolve text queries (`TXT` records) for the <ide> `hostname`. The `addresses` argument passed to the `callback` function is <ide> treated separately. <ide> - `hostname` {string} <ide> - `callback` {Function} <ide> - `err` {Error} <del> - `ret` {Object[][]} <add> - `ret` {Object[]} <ide> <ide> Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query). <ide> The `ret` argument passed to the `callback` function will be an array containing <ide><path>doc/api/n-api.md <ide> support it: <ide> [`napi_queue_async_work`]: #n_api_napi_queue_async_work <ide> [`napi_reference_ref`]: #n_api_napi_reference_ref <ide> [`napi_reference_unref`]: #n_api_napi_reference_unref <add>[`napi_throw`]: #n_api_napi_throw <ide> [`napi_throw_error`]: #n_api_napi_throw_error <ide> [`napi_throw_range_error`]: #n_api_napi_throw_range_error <ide> [`napi_throw_type_error`]: #n_api_napi_throw_type_error <ide><path>doc/api/v8.md <ide> by subclasses. <ide> * `flag` {boolean} <ide> <ide> Indicate whether to treat `TypedArray` and `DataView` objects as <del>host objects, i.e. pass them to [`serializer._writeHostObject`][]. <add>host objects, i.e. pass them to [`serializer._writeHostObject()`][]. <ide> <ide> The default is not to treat those objects as host objects. <ide> <ide><path>doc/guides/writing-tests.md <ide> The test checks functionality in the `http` module. <ide> Most tests use the `assert` module to confirm expectations of the test. <ide> <ide> The require statements are sorted in <del>[ASCII](http://man7.org/linux/man-pages/man7/ascii.7.html) order (digits, upper <add>[ASCII][] order (digits, upper <ide> case, `_`, lower case). <ide> <ide> ### **Lines 10-21** <ide> assert.throws( <ide> For performance considerations, we only use a selected subset of ES.Next <ide> features in JavaScript code in the `lib` directory. However, when writing <ide> tests, for the ease of backporting, it is encouraged to use those ES.Next <del>features that can be used directly without a flag in [all maintained branches] <del>(https://github.com/nodejs/lts). [node.green](http://node.green/) lists <del>available features in each release. <add>features that can be used directly without a flag in <add>[all maintained branches][]. [node.green][] lists available features <add>in each release. <ide> <ide> For example: <ide> <ide> functions worked correctly with the `beforeExit` event, then it might be named <ide> ### Web Platform Tests <ide> <ide> Some of the tests for the WHATWG URL implementation (named <del>`test-whatwg-url-*.js`) are imported from the <del>[Web Platform Tests Project](https://github.com/w3c/web-platform-tests/tree/master/url). <add>`test-whatwg-url-*.js`) are imported from the [Web Platform Tests Project][]. <ide> These imported tests will be wrapped like this: <ide> <ide> ```js <ide> $ make cctest <ide> ``` <ide> <ide> ### Node test fixture <del>There is a [test fixture] named `node_test_fixture.h` which can be included by <add>There is a [test fixture][] named `node_test_fixture.h` which can be included by <ide> unit tests. The fixture takes care of setting up the Node.js environment <ide> and tearing it down after the tests have finished. <ide> <ide> It also contains a helper to create arguments to be passed into Node.js. It <ide> will depend on what is being tested if this is required or not. <ide> <add>[ASCII]: http://man7.org/linux/man-pages/man7/ascii.7.html <ide> [Google Test]: https://github.com/google/googletest <del>[Test fixture]: https://github.com/google/googletest/blob/master/googletest/docs/Primer.md#test-fixtures-using-the-same-data-configuration-for-multiple-tests <add>[Web Platform Tests Project]: https://github.com/w3c/web-platform-tests/tree/master/url <ide> [`common` module]: https://github.com/nodejs/node/blob/master/test/common/README.md <add>[all maintained branches]: https://github.com/nodejs/lts <add>[node.green]: http://node.green/ <add>[test fixture]: https://github.com/google/googletest/blob/master/googletest/docs/Primer.md#test-fixtures-using-the-same-data-configuration-for-multiple-tests
4
Python
Python
fix issue with tf clip
590a5a5382dc47af188b0c7f34bed3b4ef6d394e
<ide><path>keras/backend/tensorflow_backend.py <ide> <ide> import numpy as np <ide> import os <del>import copy <ide> import warnings <ide> from .common import floatx, _EPSILON, image_dim_ordering, reset_uids <ide> py_all = all <ide> def clip(x, min_value, max_value): <ide> """ <ide> if max_value is not None and max_value < min_value: <ide> max_value = min_value <add> if max_value is None: <add> max_value = np.inf <ide> min_value = _to_tensor(min_value, x.dtype.base_dtype) <ide> max_value = _to_tensor(max_value, x.dtype.base_dtype) <ide> return tf.clip_by_value(x, min_value, max_value)
1
PHP
PHP
expand doc blocks more
ad2f11ee6392c9b3fba534900ae968ee991ba725
<ide><path>src/Controller/Component/CookieComponent.php <ide> public function __construct(ComponentRegistry $collection, array $config = array <ide> /** <ide> * Set the configuration for a specific top level key. <ide> * <add> * ### Examples: <add> * <add> * Set a single config option for a key: <add> * <add> * {{{ <add> * $this->Cookie->configKey('User', 'expires', '+3 months'); <add> * }}} <add> * <add> * Set multiple options: <add> * <add> * {{{ <add> * $this->Cookie->configKey('User', [ <add> * 'expires', '+3 months', <add> * 'httpOnly' => true, <add> * ]); <add> * }}} <add> * <ide> * @param string $keyname The top level keyname to configure. <ide> * @param null|string|array $option Either the option name to set, or an array of options to set, <ide> * or null to read config options for a given key. <ide> public function implementedEvents() { <ide> } <ide> <ide> /** <del> * Write a value to the $_COOKIE[$key]; <del> * <del> * By default all values are encrypted. <del> * You must pass $encrypt false to store values in clear test <add> * Write a value to the response cookies. <ide> * <ide> * You must use this method before any output is sent to the browser. <ide> * Failure to do so will result in header already sent errors. <ide> public function write($key, $value = null) { <ide> /** <ide> * Read the value of key path from request cookies. <ide> * <add> * This method will also allow you to read cookies that have been written in this <add> * request, but not yet sent to the client. <add> * <ide> * @param string $key Key of the value to be obtained. If none specified, obtain map key => values <ide> * @return string or null, value for specified key <ide> * @link http://book.cakephp.org/2.0/en/core-libraries/components/cookie.html#CookieComponent::read <ide> public function check($key = null) { <ide> * You must use this method before any output is sent to the browser. <ide> * Failure to do so will result in header already sent errors. <ide> * <del> * This method will delete both the top level and 2nd level cookies set. <del> * For example assuming that $name = App, deleting `User` will delete <del> * both `App[User]` and any other cookie values like `App[User][email]` <add> * Deleting a top level key will delete all keys nested within that key. <add> * For example deleting the `User` key, will also delete `User.email`. <ide> * <ide> * @param string $key Key of the value to be deleted <ide> * @return void
1
Ruby
Ruby
remove redundant parenthesis
e6f0a5372eaebdf2d71c060ed5ecaa2e9a95777c
<ide><path>actionview/test/template/atom_feed_helper_test.rb <ide> class ScrollsController < ActionController::Base <ide> FEEDS["defaults"] = <<-EOT <ide> atom_feed(:schema_date => '2008') do |feed| <ide> feed.title("My great blog!") <del> feed.updated((@scrolls.first.created_at)) <add> feed.updated(@scrolls.first.created_at) <ide> <ide> @scrolls.each do |scroll| <ide> feed.entry(scroll) do |entry| <ide> class ScrollsController < ActionController::Base <ide> FEEDS["entry_options"] = <<-EOT <ide> atom_feed do |feed| <ide> feed.title("My great blog!") <del> feed.updated((@scrolls.first.created_at)) <add> feed.updated(@scrolls.first.created_at) <ide> <ide> @scrolls.each do |scroll| <ide> feed.entry(scroll, :url => "/otherstuff/" + scroll.to_param.to_s, :updated => Time.utc(2007, 1, scroll.id)) do |entry| <ide> class ScrollsController < ActionController::Base <ide> FEEDS["entry_type_options"] = <<-EOT <ide> atom_feed(:schema_date => '2008') do |feed| <ide> feed.title("My great blog!") <del> feed.updated((@scrolls.first.created_at)) <add> feed.updated(@scrolls.first.created_at) <ide> <ide> @scrolls.each do |scroll| <ide> feed.entry(scroll, :type => 'text/xml') do |entry| <ide> class ScrollsController < ActionController::Base <ide> FEEDS["entry_url_false_option"] = <<-EOT <ide> atom_feed do |feed| <ide> feed.title("My great blog!") <del> feed.updated((@scrolls.first.created_at)) <add> feed.updated(@scrolls.first.created_at) <ide> <ide> @scrolls.each do |scroll| <ide> feed.entry(scroll, :url => false) do |entry| <ide> class ScrollsController < ActionController::Base <ide> FEEDS["xml_block"] = <<-EOT <ide> atom_feed do |feed| <ide> feed.title("My great blog!") <del> feed.updated((@scrolls.first.created_at)) <add> feed.updated(@scrolls.first.created_at) <ide> <ide> feed.author do |author| <ide> author.name("DHH") <ide> class ScrollsController < ActionController::Base <ide> atom_feed({'xmlns:app' => 'http://www.w3.org/2007/app', <ide> 'xmlns:openSearch' => 'http://a9.com/-/spec/opensearch/1.1/'}) do |feed| <ide> feed.title("My great blog!") <del> feed.updated((@scrolls.first.created_at)) <add> feed.updated(@scrolls.first.created_at) <ide> <ide> @scrolls.each do |scroll| <ide> feed.entry(scroll) do |entry| <ide> class ScrollsController < ActionController::Base <ide> FEEDS["feed_with_overridden_ids"] = <<-EOT <ide> atom_feed({:id => 'tag:test.rubyonrails.org,2008:test/'}) do |feed| <ide> feed.title("My great blog!") <del> feed.updated((@scrolls.first.created_at)) <add> feed.updated(@scrolls.first.created_at) <ide> <ide> @scrolls.each do |scroll| <ide> feed.entry(scroll, :id => "tag:test.rubyonrails.org,2008:"+scroll.id.to_s) do |entry| <ide> class ScrollsController < ActionController::Base <ide> atom_feed(:schema_date => '2008', <ide> :instruct => {'xml-stylesheet' => { :href=> 't.css', :type => 'text/css' }}) do |feed| <ide> feed.title("My great blog!") <del> feed.updated((@scrolls.first.created_at)) <add> feed.updated(@scrolls.first.created_at) <ide> <ide> @scrolls.each do |scroll| <ide> feed.entry(scroll) do |entry| <ide> class ScrollsController < ActionController::Base <ide> atom_feed(:schema_date => '2008', <ide> :instruct => {'target1' => [{ :a => '1', :b => '2' }, { :c => '3', :d => '4' }]}) do |feed| <ide> feed.title("My great blog!") <del> feed.updated((@scrolls.first.created_at)) <add> feed.updated(@scrolls.first.created_at) <ide> <ide> @scrolls.each do |scroll| <ide> feed.entry(scroll) do |entry| <ide> class ScrollsController < ActionController::Base <ide> FEEDS["feed_with_xhtml_content"] = <<-'EOT' <ide> atom_feed do |feed| <ide> feed.title("My great blog!") <del> feed.updated((@scrolls.first.created_at)) <add> feed.updated(@scrolls.first.created_at) <ide> <ide> @scrolls.each do |scroll| <ide> feed.entry(scroll) do |entry| <ide> class ScrollsController < ActionController::Base <ide> new_xml = Builder::XmlMarkup.new(:target=>'') <ide> atom_feed(:xml => new_xml) do |feed| <ide> feed.title("My great blog!") <del> feed.updated((@scrolls.first.created_at)) <add> feed.updated(@scrolls.first.created_at) <ide> <ide> @scrolls.each do |scroll| <ide> feed.entry(scroll) do |entry|
1
Ruby
Ruby
improve test case to test enum correctly
d510295b31dd6311f88e2eb2c76b12b1b0ab960a
<ide><path>activerecord/test/cases/associations/has_one_associations_test.rb <ide> class SpecialBook < ActiveRecord::Base <ide> self.table_name = "books" <ide> belongs_to :author, class_name: "SpecialAuthor" <ide> has_one :subscription, class_name: "SpecialSupscription", foreign_key: "subscriber_id" <add> <add> enum status: [:proposed, :written, :published] <ide> end <ide> <ide> class SpecialAuthor < ActiveRecord::Base <ide> def test_association_enum_works_properly <ide> book = SpecialBook.create!(status: "published") <ide> author.book = book <ide> <add> assert_equal "published", book.status <ide> assert_not_equal 0, SpecialAuthor.joins(:book).where(books: { status: "published" }).count <ide> end <ide>
1
PHP
PHP
update collection.php
01fa44a345c8df3624a633a2cc2738083f275241
<ide><path>src/Illuminate/Collections/Collection.php <ide> public function except($keys) <ide> /** <ide> * Run a filter over each of the items. <ide> * <del> * @param (callable(TValue): bool)|null $callback <add> * @param (callable(TValue, TKey): bool)|null $callback <ide> * @return static <ide> */ <ide> public function filter(callable $callback = null)
1
Ruby
Ruby
improve error message on cask doctor
f9a67019d62c26d60081479934eb1f71a3d8a905
<ide><path>Library/Homebrew/cask/cmd/doctor.rb <ide> def check_staging_location <ide> <ide> if path.exist? && !path.writable? <ide> add_error "The staging path #{user_tilde(path.to_s)} is not writable by the current user." <add> add_error "To fix, run \'sudo chown -R ${USER}:staff #{user_tilde(path.to_s)}'" <ide> end <ide> <ide> puts user_tilde(path.to_s)
1
Text
Text
update v2 docs [ci skip]
10742d3219385d52f02e887944cc506599d9d6de
<ide><path>website/docs/usage/spacy-101.md <ide> of a model, see the usage guides on <ide> <ide> </Infobox> <ide> <del><Infobox title="📖 Entity Linking"> <del> <del>To learn more about entity linking in spaCy, and how to **train and update** the <del>entity linker predictions, see the usage guides on <del>[entity linking](/usage/linguistic-features#entity-linking) and <del>[training the entity linker](/usage/training#entity-linker). <del> <del></Infobox> <del> <ide> ### Word vectors and similarity {#vectors-similarity model="vectors"} <ide> <ide> import Vectors101 from 'usage/101/\_vectors-similarity.md' <ide><path>website/docs/usage/v2-2.md <ide> menu: <ide> spaCy v2.2 features improved statistical models, new pretrained models for <ide> Norwegian and Lithuanian, better Dutch NER, as well as a new mechanism for <ide> storing language data that makes the installation about **15&times; smaller** on <del>disk. We've also added a new API for **entity linking**, a new class to <del>efficiently **serialize annotations**, an improved and 10&times; faster phrase <del>matching engine, built-in scoring and **CLI training for text classification** <del>and a new command to analyze and **debug training data**. For the full <add>disk. We've also added a new class to efficiently **serialize annotations**, an <add>improved and **10&times; faster** phrase matching engine, built-in scoring and <add>**CLI training for text classification**, a new command to analyze and **debug <add>training data**, data augmentation during training and more. For the full <ide> changelog, see the <ide> [release notes on GitHub](https://github.com/explosion/spaCy/releases/tag/v2.2.0). <ide> <ide> overall. We've also added new core models for [Norwegian](/models/nb) (MIT) and <ide> <ide> </Infobox> <ide> <del>### Entity linking API {#entity-linking} <del> <del>> #### Example <del>> <del>> ```python <del>> nlp = spacy.load("my_custom_wikidata_model") <del>> doc = nlp("Ada Lovelace was born in London") <del>> print([(e.text, e.label_, e.kb_id_) for e in doc.ents]) <del>> # [('Ada Lovelace', 'PERSON', 'Q7259'), ('London', 'GPE', 'Q84')] <del>> ``` <del> <del>Entity linking lets you ground named entities into the "real world". We're <del>excited to now provide a built-in API for training entity linking models and <del>resolving textual entities to unique identifiers from a knowledge base. The <del>annotated KB identifier is accessible as either a hash value or as a string from <del>a `Span` or `Token` object. For more details on entity linking in spaCy, check <del>out <del>[Sofie's talk](https://www.youtube.com/watch?v=PW3RJM8tDGo&list=PLBmcuObd5An4UC6jvK_-eSl6jCvP1gwXc&index=6) <del>at spaCy IRL 2019. <del> <del><Infobox> <del> <del>**API:** [`EntityLinker`](/api/entitylinker), <del>[`KnowledgeBase`](/api/knowledgebase) **Code: ** <del>[`bin/wiki_entity_linking`](https://github.com/explosion/spaCy/tree/master/bin/wiki_entity_linking) <del>**Usage: ** [Entity linking](/usage/linguistic-features#entity-linking), <del>[Training an entity linking model](/usage/training#entity-linker) <del> <del></Infobox> <del> <ide> ### Serializable lookup table and dictionary API {#lookups} <ide> <ide> > #### Example
2
Javascript
Javascript
change variable name
f7114d0c1c16ac10c6a9df9c1d369ead828bebbb
<ide><path>src/ng/q.js <ide> function qFactory(nextTick, exceptionHandler) { <ide> } <ide> <ide> function processQueue(state) { <del> var fn, promise, pending; <add> var fn, deferred, pending; <ide> <ide> pending = state.pending; <ide> state.processScheduled = false; <ide> state.pending = undefined; <ide> for (var i = 0, ii = pending.length; i < ii; ++i) { <del> promise = pending[i][0]; <add> deferred = pending[i][0]; <ide> fn = pending[i][state.status]; <ide> try { <ide> if (isFunction(fn)) { <del> promise.resolve(fn(state.value)); <add> deferred.resolve(fn(state.value)); <ide> } else if (state.status === 1) { <del> promise.resolve(state.value); <add> deferred.resolve(state.value); <ide> } else { <del> promise.reject(state.value); <add> deferred.reject(state.value); <ide> } <ide> } catch (e) { <del> promise.reject(e); <add> deferred.reject(e); <ide> exceptionHandler(e); <ide> } <ide> }
1
Javascript
Javascript
add suffix _timeout consistently in scheduler
2325375f4faaa77db6671e914da5220a879a1da8
<ide><path>packages/scheduler/src/Scheduler.js <ide> var maxSigned31BitInt = 1073741823; <ide> // Times out immediately <ide> var IMMEDIATE_PRIORITY_TIMEOUT = -1; <ide> // Eventually times out <del>var USER_BLOCKING_PRIORITY = 250; <add>var USER_BLOCKING_PRIORITY_TIMEOUT = 250; <ide> var NORMAL_PRIORITY_TIMEOUT = 5000; <ide> var LOW_PRIORITY_TIMEOUT = 10000; <ide> // Never times out <del>var IDLE_PRIORITY = maxSigned31BitInt; <add>var IDLE_PRIORITY_TIMEOUT = maxSigned31BitInt; <ide> <ide> // Tasks are stored on a min heap <ide> var taskQueue = []; <ide> function timeoutForPriorityLevel(priorityLevel) { <ide> case ImmediatePriority: <ide> return IMMEDIATE_PRIORITY_TIMEOUT; <ide> case UserBlockingPriority: <del> return USER_BLOCKING_PRIORITY; <add> return USER_BLOCKING_PRIORITY_TIMEOUT; <ide> case IdlePriority: <del> return IDLE_PRIORITY; <add> return IDLE_PRIORITY_TIMEOUT; <ide> case LowPriority: <ide> return LOW_PRIORITY_TIMEOUT; <ide> case NormalPriority:
1
Javascript
Javascript
improve http test reliability
fcd82e760106ed7bd7aea634b65fe9faac7c8e7c
<ide><path>test/parallel/test-http-client-immediate-error.js <ide> <ide> const common = require('../common'); <ide> const assert = require('assert'); <add>const net = require('net'); <ide> const http = require('http'); <del>const req = http.get({ host: '127.0.0.1', port: 1 }); <del>req.on('error', common.mustCall((err) => { <del> assert.strictEqual(err.code, 'ECONNREFUSED'); <add>const uv = process.binding('uv'); <add>const { async_id_symbol } = process.binding('async_wrap'); <add>const { newUid } = require('async_hooks'); <add> <add>const agent = new http.Agent(); <add>agent.createConnection = common.mustCall((cfg) => { <add> const sock = new net.Socket(); <add> <add> // Fake the handle so we can enforce returning an immediate error <add> sock._handle = { <add> connect: common.mustCall((req, addr, port) => { <add> return uv.UV_ENETUNREACH; <add> }), <add> readStart() {}, <add> close() {} <add> }; <add> <add> // Simulate just enough socket handle initialization <add> sock[async_id_symbol] = newUid(); <add> <add> sock.connect(cfg); <add> return sock; <add>}); <add> <add>http.get({ <add> host: '127.0.0.1', <add> port: 1, <add> agent <add>}).on('error', common.mustCall((err) => { <add> assert.strictEqual(err.code, 'ENETUNREACH'); <ide> }));
1
Ruby
Ruby
use the single line editor in console test
c8b88dd4df3b3abded80177b8cbdd428af7d5230
<ide><path>railties/test/application/console_test.rb <ide> def spawn_console(options, wait_for_prompt: true) <ide> end <ide> <ide> def test_sandbox <del> spawn_console("--sandbox") <add> options = "--sandbox" <add> options += " -- --singleline --nocolorize" if RUBY_VERSION >= "2.7" <add> spawn_console(options) <ide> <ide> write_prompt "Post.count", "=> 0" <ide> write_prompt "Post.create" <ide> write_prompt "Post.count", "=> 1" <ide> @primary.puts "quit" <ide> <del> spawn_console("--sandbox") <add> spawn_console(options) <ide> <ide> write_prompt "Post.count", "=> 0" <ide> write_prompt "Post.transaction { Post.create; raise }" <ide> def test_sandbox_when_sandbox_is_disabled <ide> end <ide> <ide> def test_environment_option_and_irb_option <del> spawn_console("-e test -- --verbose") <add> options = "-e test -- --verbose" <add> options += " --singleline --nocolorize" if RUBY_VERSION >= "2.7" <add> spawn_console(options) <ide> <ide> write_prompt "a = 1", "a = 1" <ide> write_prompt "puts Rails.env", "puts Rails.env\r\ntest" <ide><path>railties/test/engine/commands_test.rb <ide> def test_console_command_work_inside_engine <ide> skip "PTY unavailable" unless available_pty? <ide> <ide> primary, replica = PTY.open <del> spawn_command("console", replica) <add> cmd = "console" <add> cmd += " --singleline" if RUBY_VERSION >= "2.7" <add> spawn_command(cmd, replica) <ide> assert_output(">", primary) <ide> ensure <ide> primary.puts "quit"
2
Javascript
Javascript
add delay support to animated.spring
9c2ce53b89bc3b8198c6e6157e8c8629712652cb
<ide><path>Libraries/Animated/src/AnimatedImplementation.js <ide> type SpringAnimationConfig = AnimationConfig & { <ide> speed?: number, <ide> tension?: number, <ide> friction?: number, <add> delay?: number, <ide> }; <ide> <ide> type SpringAnimationConfigSingle = AnimationConfig & { <ide> type SpringAnimationConfigSingle = AnimationConfig & { <ide> speed?: number, <ide> tension?: number, <ide> friction?: number, <add> delay?: number, <ide> }; <ide> <ide> function withDefault<T>(value: ?T, defaultValue: T): T { <ide> class SpringAnimation extends Animation { <ide> _toValue: any; <ide> _tension: number; <ide> _friction: number; <add> _delay: number; <add> _timeout: any; <ide> _lastTime: number; <ide> _onUpdate: (value: number) => void; <ide> _animationFrame: any; <ide> class SpringAnimation extends Animation { <ide> this._initialVelocity = config.velocity; <ide> this._lastVelocity = withDefault(config.velocity, 0); <ide> this._toValue = config.toValue; <add> this._delay = withDefault(config.delay, 0); <ide> this._useNativeDriver = shouldUseNativeDriver(config); <ide> this.__isInteraction = config.isInteraction !== undefined ? config.isInteraction : true; <ide> this.__iterations = config.iterations !== undefined ? config.iterations : 1; <ide> class SpringAnimation extends Animation { <ide> this._initialVelocity !== null) { <ide> this._lastVelocity = this._initialVelocity; <ide> } <del> if (this._useNativeDriver) { <del> this.__startNativeAnimation(animatedValue); <add> <add> var start = () => { <add> if (this._useNativeDriver) { <add> this.__startNativeAnimation(animatedValue); <add> } else { <add> this.onUpdate(); <add> } <add> }; <add> <add> // If this._delay is more than 0, we start after the timeout. <add> if (this._delay) { <add> this._timeout = setTimeout(start, this._delay); <ide> } else { <del> this.onUpdate(); <add> start(); <ide> } <ide> } <ide> <ide> class SpringAnimation extends Animation { <ide> stop(): void { <ide> super.stop(); <ide> this.__active = false; <add> clearTimeout(this._timeout); <ide> global.cancelAnimationFrame(this._animationFrame); <ide> this.__debouncedOnEnd({finished: false}); <ide> }
1
Javascript
Javascript
add benchmark for string concatenations
3b1e837c270b4b540705b7c447db850e48cc2bf3
<ide><path>benchmark/es/string-concatenations.js <add>'use strict'; <add> <add>const common = require('../common.js'); <add> <add>const configs = { <add> n: [1e3], <add> mode: [ <add> 'multi-concat', <add> 'multi-join', <add> 'multi-template', <add> 'to-string-string', <add> 'to-string-concat', <add> 'to-string-template', <add> ], <add>}; <add> <add>const bench = common.createBenchmark(main, configs); <add> <add> <add>function main(conf) { <add> const n = +conf.n; <add> const mode = conf.mode; <add> <add> const str = 'abc'; <add> const num = 123; <add> <add> let string; <add> <add> switch (mode) { <add> case 'multi-concat': <add> bench.start(); <add> for (let i = 0; i < n; i++) <add> string = '...' + str + ', ' + num + ', ' + str + ', ' + num + '.'; <add> bench.end(n); <add> break; <add> case 'multi-join': <add> bench.start(); <add> for (let i = 0; i < n; i++) <add> string = ['...', str, ', ', num, ', ', str, ', ', num, '.'].join(''); <add> bench.end(n); <add> break; <add> case 'multi-template': <add> bench.start(); <add> for (let i = 0; i < n; i++) <add> string = `...${str}, ${num}, ${str}, ${num}.`; <add> bench.end(n); <add> break; <add> case 'to-string-string': <add> bench.start(); <add> for (let i = 0; i < n; i++) <add> string = String(num); <add> bench.end(n); <add> break; <add> case 'to-string-concat': <add> bench.start(); <add> for (let i = 0; i < n; i++) <add> string = '' + num; <add> bench.end(n); <add> break; <add> case 'to-string-template': <add> bench.start(); <add> for (let i = 0; i < n; i++) <add> string = `${num}`; <add> bench.end(n); <add> break; <add> } <add> <add> return string; <add>}
1
Text
Text
add a blurb about serve-static
4aaf985555bd84b6923e239cdf5ac3fbb8000efa
<ide><path>docs/recipes/ServerRendering.md <ide> In the following recipe, we are going to look at how to set up server-side rende <ide> <ide> ### Install Packages <ide> <del>For this example, we'll be using [Express](http://expressjs.com/) as a simple web server. <add>For this example, we'll be using [Express](http://expressjs.com/) as a simple web server. We'll include the [serve-static](https://www.npmjs.com/package/serve-static) middleware to handle static files, which we'll see in just a bit. <ide> <ide> We also need to install the React bindings for Redux, since they are not included in Redux by default. <ide> <del> npm install --save react-redux express serve-static <add> npm install --save express serve-static react-redux <ide> <ide> <ide> ## The Server Side
1
Javascript
Javascript
make queuemicrotask faster
2c49e8b537a5fba07568c2363ba6a594caa74c17
<ide><path>benchmark/process/queue-microtask-breadth.js <add>'use strict'; <add> <add>const common = require('../common.js'); <add>const bench = common.createBenchmark(main, { <add> n: [4e5] <add>}); <add> <add>function main({ n }) { <add> var j = 0; <add> <add> function cb() { <add> j++; <add> if (j === n) <add> bench.end(n); <add> } <add> <add> bench.start(); <add> for (var i = 0; i < n; i++) { <add> queueMicrotask(cb); <add> } <add>} <ide><path>benchmark/process/queue-microtask-depth.js <add>'use strict'; <add>const common = require('../common.js'); <add>const bench = common.createBenchmark(main, { <add> n: [12e5] <add>}); <add> <add>function main({ n }) { <add> let counter = n; <add> bench.start(); <add> queueMicrotask(onNextTick); <add> function onNextTick() { <add> if (--counter) <add> queueMicrotask(onNextTick); <add> else <add> bench.end(n); <add> } <add>} <ide><path>lib/internal/process/task_queues.js <ide> const { <ide> } = require('internal/errors').codes; <ide> const FixedQueue = require('internal/fixed_queue'); <ide> <add>const FunctionBind = Function.call.bind(Function.prototype.bind); <add> <ide> // *Must* match Environment::TickInfo::Fields in src/env.h. <ide> const kHasTickScheduled = 0; <ide> <ide> function createMicrotaskResource() { <ide> }); <ide> } <ide> <add>function runMicrotask() { <add> this.runInAsyncScope(() => { <add> const callback = this.callback; <add> try { <add> callback(); <add> } catch (error) { <add> // TODO(devsnek) remove this if <add> // https://bugs.chromium.org/p/v8/issues/detail?id=8326 <add> // is resolved such that V8 triggers the fatal exception <add> // handler for microtasks <add> triggerFatalException(error); <add> } finally { <add> this.emitDestroy(); <add> } <add> }); <add>} <add> <ide> function queueMicrotask(callback) { <ide> if (typeof callback !== 'function') { <ide> throw new ERR_INVALID_ARG_TYPE('callback', 'function', callback); <ide> } <ide> <ide> const asyncResource = createMicrotaskResource(); <add> asyncResource.callback = callback; <ide> <del> enqueueMicrotask(() => { <del> asyncResource.runInAsyncScope(() => { <del> try { <del> callback(); <del> } catch (error) { <del> // TODO(devsnek) remove this if <del> // https://bugs.chromium.org/p/v8/issues/detail?id=8326 <del> // is resolved such that V8 triggers the fatal exception <del> // handler for microtasks <del> triggerFatalException(error); <del> } finally { <del> asyncResource.emitDestroy(); <del> } <del> }); <del> }); <add> enqueueMicrotask(FunctionBind(runMicrotask, asyncResource)); <ide> } <ide> <ide> module.exports = {
3
Text
Text
fix typo for how pki works
bf9c6d3115dd388cf379ec1a80d29104521a7b42
<ide><path>docs/swarm/how-swarm-mode-works/pki.md <ide> in a swarm use mutual Transport Layer Security (TLS) to authenticate, authorize, <ide> and encrypt the communications between themselves and other nodes in the swarm. <ide> <ide> When you create a swarm by running `docker swarm init`, the Docker Engine <del>designates istself as a manager node. By default, the manager node generates <add>designates itself as a manager node. By default, the manager node generates <ide> itself a new root Certificate Authority (CA) along with a key pair to secure <ide> communications with other nodes that join the swarm. If you prefer, you can pass <ide> the `--external-ca` flag to specify a root CA external to the swarm. Refer to
1
Ruby
Ruby
use literal "python"
7ccec0cdf0d521471d185b6a48bb3678cb536aaf
<ide><path>Library/Homebrew/language/python.rb <ide> def create <ide> <ide> Pathname.glob(@venv_root/"lib/python*/orig-prefix.txt").each do |prefix_file| <ide> prefix_path = prefix_file.read <del> prefix_path.sub! %r{^#{HOMEBREW_CELLAR}/#{python}/[^/]+}, Formula["python"].opt_prefix <add> prefix_path.sub! %r{^#{HOMEBREW_CELLAR}/python/[^/]+}, Formula["python"].opt_prefix <ide> prefix_file.atomic_write prefix_path <ide> end <ide> end
1
Go
Go
parse input timestamps with standard rfc3339
999f464feb5b78e8ecc97625e70f3b1796d0a758
<ide><path>integration-cli/docker_cli_events_test.go <ide> import ( <ide> "github.com/go-check/check" <ide> ) <ide> <add>func (s *DockerSuite) TestEventsTimestampFormats(c *check.C) { <add> image := "busybox" <add> <add> // Start stopwatch, generate an event <add> time.Sleep(time.Second) // so that we don't grab events from previous test occured in the same second <add> start := daemonTime(c) <add> time.Sleep(time.Second) // remote API precision is only a second, wait a while before creating an event <add> dockerCmd(c, "tag", image, "timestamptest:1") <add> dockerCmd(c, "rmi", "timestamptest:1") <add> time.Sleep(time.Second) // so that until > since <add> end := daemonTime(c) <add> <add> // List of available time formats to --since <add> unixTs := func(t time.Time) string { return fmt.Sprintf("%v", t.Unix()) } <add> rfc3339 := func(t time.Time) string { return t.Format(time.RFC3339) } <add> <add> // --since=$start must contain only the 'untag' event <add> for _, f := range []func(time.Time) string{unixTs, rfc3339} { <add> since, until := f(start), f(end) <add> cmd := exec.Command(dockerBinary, "events", "--since="+since, "--until="+until) <add> out, _, err := runCommandWithOutput(cmd) <add> if err != nil { <add> c.Fatalf("docker events cmd failed: %v\nout=%s", err, out) <add> } <add> events := strings.Split(strings.TrimSpace(out), "\n") <add> if len(events) != 1 { <add> c.Fatalf("unexpected events, was expecting only 1 (since=%s, until=%s) out=%s", since, until, out) <add> } <add> if !strings.Contains(out, "untag") { <add> c.Fatalf("expected 'untag' event not found (since=%s, until=%s) out=%s", since, until, out) <add> } <add> } <add> <add>} <add> <ide> func (s *DockerSuite) TestEventsUntag(c *check.C) { <ide> image := "busybox" <ide> dockerCmd(c, "tag", image, "utest:tag1") <ide><path>pkg/timeutils/utils.go <ide> package timeutils <ide> <ide> import ( <ide> "strconv" <add> "strings" <ide> "time" <ide> ) <ide> <ide> // GetTimestamp tries to parse given string as RFC3339 time <del>// or Unix timestamp, if successful returns a Unix timestamp <del>// as string otherwise returns value back. <add>// or Unix timestamp (with seconds precision), if successful <add>//returns a Unix timestamp as string otherwise returns value back. <ide> func GetTimestamp(value string) string { <del> format := RFC3339NanoFixed <add> var format string <add> if strings.Contains(value, ".") { <add> format = time.RFC3339Nano <add> } else { <add> format = time.RFC3339 <add> } <add> <ide> loc := time.FixedZone(time.Now().Zone()) <ide> if len(value) < len(format) { <ide> format = format[:len(value)] <ide><path>pkg/timeutils/utils_test.go <add>package timeutils <add> <add>import ( <add> "testing" <add>) <add> <add>func TestGetTimestamp(t *testing.T) { <add> cases := []struct{ in, expected string }{ <add> {"0", "-62167305600"}, // 0 gets parsed year 0 <add> <add> // Partial RFC3339 strings get parsed with second precision <add> {"2006-01-02T15:04:05.999999999+07:00", "1136189045"}, <add> {"2006-01-02T15:04:05.999999999Z", "1136214245"}, <add> {"2006-01-02T15:04:05.999999999", "1136214245"}, <add> {"2006-01-02T15:04:05", "1136214245"}, <add> {"2006-01-02T15:04", "1136214240"}, <add> {"2006-01-02T15", "1136214000"}, <add> {"2006-01-02T", "1136160000"}, <add> {"2006-01-02", "1136160000"}, <add> {"2006", "1136073600"}, <add> {"2015-05-13T20:39:09Z", "1431549549"}, <add> <add> // unix timestamps returned as is <add> {"1136073600", "1136073600"}, <add> <add> // String fallback <add> {"invalid", "invalid"}, <add> } <add> <add> for _, c := range cases { <add> o := GetTimestamp(c.in) <add> if o != c.expected { <add> t.Fatalf("wrong value for '%s'. expected:'%s' got:'%s'", c.in, c.expected, o) <add> } <add> } <add>}
3
Text
Text
update sample formula
59fab56afdf6129c37ff30eb842bf7bff41348e0
<ide><path>docs/Formula-Cookbook.md <ide> class Foo < Formula <ide> # depends_on "cmake" => :build <ide> <ide> def install <del> system "./configure", "--prefix=#{prefix}", "--disable-debug", "--disable-dependency-tracking" <add> # ENV.deparallelize <add> system "./configure", "--disable-debug", <add> "--disable-dependency-tracking", <add> "--disable-silent-rules", <add> "--prefix=#{prefix}" <ide> # system "cmake", ".", *std_cmake_args <ide> system "make", "install" <ide> end <add> <add> test do <add> system "false" <add> end <ide> end <ide> ``` <ide> <ide> Check the top of the e.g. `./configure` output. Some configure scripts do not re <ide> <ide> ### Add a test to the formula <ide> <del>Please add a [`test do`](http://www.rubydoc.info/github/Homebrew/brew/master/Formula#test-class_method) block to the formula. This will be run by `brew test foo` and the [Brew Test Bot](Brew-Test-Bot.md). <add>Add a valid test to the [`test do`](http://www.rubydoc.info/github/Homebrew/brew/master/Formula&num;test-class_method) block of the formula. This will be run by `brew test foo` and the [Brew Test Bot](Brew-Test-Bot.md). <ide> <ide> The <ide> [`test do`](http://www.rubydoc.info/github/Homebrew/brew/master/Formula#test-class_method)
1
Javascript
Javascript
add simple test for d3.interpolatetransform
537e9e234aa57612e67ac10f3fa092f740cda3de
<ide><path>test/interpolate/interpolate-transform-test.js <add>var vows = require("vows"), <add> load = require("../load"), <add> assert = require("../assert"); <add> <add>var suite = vows.describe("d3.interpolateTransform"); <add> <add>suite.addBatch({ <add> "interpolateTransform": { <add> topic: load("interpolate/transform").document(), <add> "interpolation of a decomposed transform": { <add> topic: function(d3) { <add> // Use a custom d3.transform to parse a decomposed transform, since <add> // JSDOM doesn't support consolidating SVG transform strings. <add> d3.transform = function(s) { <add> var m = s.split(/,/g).map(Number); <add> return { <add> translate: [m[0], m[1]], <add> rotate: m[2], <add> skew: m[3], <add> scale: [m[4], m[5]] <add> }; <add> }; <add> return d3; <add> }, <add> "identity": function(d3) { <add> assert.equal(d3.interpolateTransform([0, 0, 0, 0, 1, 1] + "", [0, 0, 0, 0, 1, 1] + "")(.4), ""); <add> }, <add> "translate": { <add> "x": function(d3) { <add> assert.equal(d3.interpolateTransform([0, 0, 0, 0, 1, 1] + "", [10, 0, 0, 0, 1, 1] + "")(.4), "translate(4,0)"); <add> }, <add> "y": function(d3) { <add> assert.equal(d3.interpolateTransform([0, 0, 0, 0, 1, 1] + "", [0, 10, 0, 0, 1, 1] + "")(.4), "translate(0,4)"); <add> }, <add> "x and y": function(d3) { <add> assert.equal(d3.interpolateTransform([0, 0, 0, 0, 1, 1] + "", [1, 10, 0, 0, 1, 1] + "")(.4), "translate(0.4,4)"); <add> } <add> }, <add> "rotate": { <add> "simple": function(d3) { <add> assert.equal(d3.interpolateTransform([0, 0, -10, 0, 1, 1] + "", [0, 0, 30, 0, 1, 1] + "")(.4), "rotate(6)"); <add> }, <add> "with constant translate": function(d3) { <add> assert.equal(d3.interpolateTransform([5, 6, -10, 0, 1, 1] + "", [5, 6, 30, 0, 1, 1] + "")(.4), "translate(5,6)rotate(6)"); <add> } <add> }, <add> "skew": function(d3) { <add> assert.equal(d3.interpolateTransform([0, 0, 0, 0, 1, 1] + "", [0, 0, 0, 40, 1, 1] + "")(.4), "skewX(16)"); <add> }, <add> "scale": function(d3) { <add> assert.equal(d3.interpolateTransform([0, 0, 0, 0, 1, 1] + "", [0, 0, 0, 0, 10, 1] + "")(.5), "scale(5.5,1)"); <add> }, <add> "translate and rotate": function(d3) { <add> assert.equal(d3.interpolateTransform([0, 0, 0, 0, 1, 1] + "", [100, 0, 90, 0, 1, 1] + "")(.5), "translate(50,0)rotate(45)"); <add> } <add> } <add> } <add>}); <add> <add>suite.export(module);
1
Javascript
Javascript
use hasownproperty in for in loops
1a10838a61ed2d85a114b8638fe55f4b4c56dc26
<ide><path>lib/HotModuleReplacementPlugin.js <ide> var hotInitCode = Template.getFunctionContent(function() { <ide> return; <ide> hotRequestedFilesMap[chunkId] = false; <ide> for(var moduleId in moreModules) { <del> hotUpdate[moduleId] = moreModules[moduleId]; <add> if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) { <add> hotUpdate[moduleId] = moreModules[moduleId]; <add> } <ide> } <ide> if(--hotWaitingFiles === 0 && hotChunksLoading === 0) { <ide> hotUpdateDownloaded(); <ide> var hotInitCode = Template.getFunctionContent(function() { <ide> } else { <ide> var outdatedModules = []; <ide> for(var id in hotUpdate) { <del> outdatedModules.push(+id); <add> if(Object.prototype.hasOwnProperty.call(hotUpdate, id)) { <add> outdatedModules.push(+id); <add> } <ide> } <ide> callback(null, outdatedModules); <ide> } <ide> var hotInitCode = Template.getFunctionContent(function() { <ide> var outdatedModules = []; <ide> var appliedUpdate = {}; <ide> for(var id in hotUpdate) { <del> var moduleId = +id; <del> var result = getAffectedStuff(moduleId); <del> if(!result) { <del> if(options.ignoreUnaccepted) <del> continue; <del> hotSetStatus("abort"); <del> return callback(new Error("Aborted because " + moduleId + " is not accepted")); <del> } <del> if(result instanceof Error) { <del> hotSetStatus("abort"); <del> return callback(result); <del> } <del> appliedUpdate[moduleId] = hotUpdate[moduleId]; <del> addAllToSet(outdatedModules, result[0]); <del> for(var moduleId in result[1]) { <del> if(Object.prototype.hasOwnProperty.call(result[1], moduleId)) { <del> if(!outdatedDependencies[moduleId]) <del> outdatedDependencies[moduleId] = []; <del> addAllToSet(outdatedDependencies[moduleId], result[1][moduleId]); <add> if(Object.prototype.hasOwnProperty.call(hotUpdate, id)) { <add> var moduleId = +id; <add> var result = getAffectedStuff(moduleId); <add> if(!result) { <add> if(options.ignoreUnaccepted) <add> continue; <add> hotSetStatus("abort"); <add> return callback(new Error("Aborted because " + moduleId + " is not accepted")); <add> } <add> if(result instanceof Error) { <add> hotSetStatus("abort"); <add> return callback(result); <add> } <add> appliedUpdate[moduleId] = hotUpdate[moduleId]; <add> addAllToSet(outdatedModules, result[0]); <add> for(var moduleId in result[1]) { <add> if(Object.prototype.hasOwnProperty.call(result[1], moduleId)) { <add> if(!outdatedDependencies[moduleId]) <add> outdatedDependencies[moduleId] = []; <add> addAllToSet(outdatedDependencies[moduleId], result[1][moduleId]); <add> } <ide> } <ide> } <ide> }
1
Python
Python
use resolver404 instead of base exception
0ac52e0808288892717c017e57c57aa8ad81e6d3
<ide><path>rest_framework/relations.py <ide> from rest_framework.fields import Field <ide> from rest_framework.reverse import reverse <ide> from django.core.exceptions import ObjectDoesNotExist, ImproperlyConfigured <del>from django.core.urlresolvers import resolve, get_script_prefix, NoReverseMatch <add>from django.core.urlresolvers import resolve, get_script_prefix, NoReverseMatch, Resolver404 <ide> from django.db.models.query import QuerySet <ide> from django.utils.translation import ugettext_lazy as _ <ide> <ide> def to_internal_value(self, data): <ide> <ide> try: <ide> match = self.resolve(data) <del> except Exception: <add> except Resolver404: <ide> self.fail('no_match') <ide> <ide> if match.view_name != self.view_name:
1
Text
Text
fix a writing mistake
464def3ecf79247834bd1d5053c3a76aeee03084
<ide><path>guides/source/active_record_validations.md <ide> If you validate the presence of an object associated via a `has_one` or <ide> Since `false.blank?` is true, if you want to validate the presence of a boolean <ide> field you should use `validates :field_name, inclusion: { in: [true, false] }`. <ide> <del>The default error message is _"can't be empty"_. <add>The default error message is _"can't be blank"_. <ide> <ide> ### `absence` <ide>
1
Javascript
Javascript
use const where applicable in maintemplate
9c9f2b89c942afce94b751b1979a1986a9bc4c00
<ide><path>lib/MainTemplate.js <ide> module.exports = class MainTemplate extends Template { <ide> constructor(outputOptions) { <ide> super(outputOptions); <ide> this.plugin("startup", (source, chunk, hash) => { <del> let buf = []; <add> const buf = []; <ide> if(chunk.entryModule) { <ide> buf.push("// Load entry module and return exports"); <ide> buf.push("return " + this.renderRequireFunctionForModule(hash, chunk, JSON.stringify(chunk.entryModule.id)) + <ide> module.exports = class MainTemplate extends Template { <ide> return this.asString(buf); <ide> }); <ide> this.plugin("render", (bootstrapSource, chunk, hash, moduleTemplate, dependencyTemplates) => { <del> let source = new ConcatSource(); <add> const source = new ConcatSource(); <ide> source.add("/******/ (function(modules) { // webpackBootstrap\n"); <ide> source.add(new PrefixSource("/******/", bootstrapSource)); <ide> source.add("/******/ })\n"); <ide> source.add("/************************************************************************/\n"); <ide> source.add("/******/ ("); <del> let modules = this.renderChunkModules(chunk, moduleTemplate, dependencyTemplates, "/******/ "); <add> const modules = this.renderChunkModules(chunk, moduleTemplate, dependencyTemplates, "/******/ "); <ide> source.add(this.applyPluginsWaterfall("modules", modules, chunk, hash, moduleTemplate, dependencyTemplates)); <ide> source.add(")"); <ide> return source; <ide> module.exports = class MainTemplate extends Template { <ide> ]); <ide> }); <ide> this.plugin("require-extensions", (source, chunk, hash) => { <del> let buf = []; <add> const buf = []; <ide> if(chunk.chunks.length > 0) { <ide> buf.push("// This file contains only the entry chunk."); <ide> buf.push("// The chunk loading function for additional chunks"); <ide> module.exports = class MainTemplate extends Template { <ide> buf.push("// Object.prototype.hasOwnProperty.call"); <ide> buf.push(this.requireFn + ".o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };"); <ide> <del> let publicPath = this.getPublicPath({ <add> const publicPath = this.getPublicPath({ <ide> hash: hash <ide> }); <ide> buf.push(""); <ide> module.exports = class MainTemplate extends Template { <ide> } <ide> <ide> render(hash, chunk, moduleTemplate, dependencyTemplates) { <del> let buf = []; <add> const buf = []; <ide> buf.push(this.applyPluginsWaterfall("bootstrap", "", chunk, hash, moduleTemplate, dependencyTemplates)); <ide> buf.push(this.applyPluginsWaterfall("local-vars", "", chunk, hash)); <ide> buf.push(""); <ide> module.exports = class MainTemplate extends Template { <ide> } <ide> <ide> entryPointInChildren(chunk) { <del> let checkChildren = (chunk, alreadyCheckedChunks) => { <add> const checkChildren = (chunk, alreadyCheckedChunks) => { <ide> return chunk.chunks.some((child) => { <ide> if(alreadyCheckedChunks.indexOf(child) >= 0) return; <ide> alreadyCheckedChunks.push(child); <ide> module.exports = class MainTemplate extends Template { <ide> } <ide> <ide> useChunkHash(chunk) { <del> let paths = this.applyPluginsWaterfall("global-hash-paths", []); <add> const paths = this.applyPluginsWaterfall("global-hash-paths", []); <ide> return !this.applyPluginsBailResult("global-hash", chunk, paths); <ide> } <ide> };
1
Javascript
Javascript
remove unnecessary parameter to jquery#constructor
98cee73244d55910a1ac82bcf6cae04a7f650484
<ide><path>src/core.js <ide> jQuery.fn = jQuery.prototype = { <ide> }, <ide> <ide> end: function() { <del> return this.prevObject || this.constructor( null ); <add> return this.prevObject || this.constructor(); <ide> }, <ide> <ide> // For internal use only.
1
Text
Text
update coverage badge for switched location
36b9ee7e9eabd0fe7ad5cf5c5db821570a024c24
<ide><path>README.md <ide> # Chart.js <ide> <del>[![Build Status](https://travis-ci.org/chartjs/Chart.js.svg?branch=master)](https://travis-ci.org/chartjs/Chart.js) [![Code Climate](https://codeclimate.com/github/nnnick/Chart.js/badges/gpa.svg)](https://codeclimate.com/github/nnnick/Chart.js)[![Coverage Status](https://coveralls.io/repos/nnnick/Chart.js/badge.svg?branch=master)](https://coveralls.io/r/nnnick/Chart.js?branch=master) <add>[![Build Status](https://travis-ci.org/chartjs/Chart.js.svg?branch=master)](https://travis-ci.org/chartjs/Chart.js) [![Code Climate](https://codeclimate.com/github/nnnick/Chart.js/badges/gpa.svg)](https://codeclimate.com/github/nnnick/Chart.js)[![Coverage Status](https://coveralls.io/repos/github/chartjs/Chart.js/badge.svg?branch=master)](https://coveralls.io/github/chartjs/Chart.js?branch=master) <ide> <ide> [![Chart.js on Slack](https://img.shields.io/badge/slack-Chart.js-blue.svg)](https://chartjs-slack-automation.herokuapp.com/) <ide>
1
Javascript
Javascript
remove extra spacing in http options
083c421b5ca08576897b5da396085a462010780e
<ide><path>benchmark/http/client-request-body.js <ide> var bench = common.createBenchmark(main, { <ide> dur: [5], <ide> type: ['asc', 'utf', 'buf'], <ide> bytes: [32, 256, 1024], <del> method: ['write', 'end '] // two spaces added to line up each row <add> method: ['write', 'end'] <ide> }); <ide> <ide> function main(conf) { <ide><path>benchmark/http/end-vs-write-end.js <ide> var bench = common.createBenchmark(main, { <ide> type: ['asc', 'utf', 'buf'], <ide> kb: [64, 128, 256, 1024], <ide> c: [100], <del> method: ['write', 'end '] // two spaces added to line up each row <add> method: ['write', 'end'] <ide> }); <ide> <ide> function main(conf) {
2
Javascript
Javascript
update some todos
2ecf8f35f013e4bc6c5f814c50aebcf5237029a9
<ide><path>src/geo/centroid.js <ide> d3.geo.centroid = function(object) { <ide> d3_geo_centroidDimension = d3_geo_centroidW = d3_geo_centroidX = d3_geo_centroidY = d3_geo_centroidZ = 0; <ide> d3.geo.stream(object, d3_geo_centroid); <del> // TODO mixed geometries <ide> var m; <ide> if (d3_geo_centroidW && <ide> Math.abs(m = Math.sqrt(d3_geo_centroidX * d3_geo_centroidX + d3_geo_centroidY * d3_geo_centroidY + d3_geo_centroidZ * d3_geo_centroidZ)) > ε) { <ide><path>src/geo/path-centroid.js <ide> // TODO Unify this code with d3.geom.polygon centroid? <ide> // TODO Enforce positive area for exterior, negative area for interior? <del>// TODO ignore lower dimensions. <ide> <ide> var d3_geo_pathCentroid = { <ide> point: d3_geo_pathCentroidPoint, <ide><path>src/geo/path.js <del>// TODO fallback for projections that don't implement stream? (or fix albersUsa?) <add>// TODO fallback for projections that don't implement stream? <ide> // TODO cache pathBuffer / pathContext across invocations? <ide> // TODO better encapsulation for d3_geo_pathArea; move to area.js <ide> // TODO better encapsulation for d3_geo_pathCentroid; move to centroid.js
3
Text
Text
fix judgement spelling [ci skip]
d81f2953f4c4399b0bf7188944025675f066dc78
<ide><path>guides/source/contributing_to_ruby_on_rails.md <ide> can expect it to be marked "invalid" as soon as it's reviewed. <ide> Sometimes, the line between 'bug' and 'feature' is a hard one to draw. <ide> Generally, a feature is anything that adds new behavior, while a bug is <ide> anything that causes incorrect behavior. Sometimes, <del>the core team will have to make a judgement call. That said, the distinction <add>the core team will have to make a judgment call. That said, the distinction <ide> generally just affects which release your patch will get in to; we love feature <ide> submissions! They just won't get backported to maintenance branches. <ide>
1
Python
Python
correct the correction
c0b93a1c7a961e30b30d02d641c9d22120ef5d73
<ide><path>src/transformers/benchmark/benchmark_utils.py <ide> def start_memory_tracing( <ide> gpus_to_trace: Optional[List[int]] = None, <ide> ) -> MemoryTrace: <ide> """ Setup line-by-line tracing to record rss mem (RAM) at each line of a module or sub-module. <del> See `../../../examples/benchmarking/` for usage examples. <add> See `./benchmark.py` for usage examples. <ide> Current memory consumption is returned using psutil and in particular is the RSS memory <ide> "Resident Set Size” (the non-swapped physical memory the process is using). <ide> See https://psutil.readthedocs.io/en/latest/#psutil.Process.memory_info
1
Go
Go
provide the hostconfig during "run"
1df87b95066198c30312147393c18e0be0564fd0
<ide><path>api/client/commands.go <ide> func (cli *DockerCli) createContainer(config *runconfig.Config, hostConfig *runc <ide> containerValues.Set("name", name) <ide> } <ide> <del> var data interface{} <del> if hostConfig != nil { <del> data = runconfig.MergeConfigs(config, hostConfig) <del> } else { <del> data = config <del> } <add> mergedConfig := runconfig.MergeConfigs(config, hostConfig) <ide> <ide> var containerIDFile *cidFile <ide> if cidfile != "" { <ide> func (cli *DockerCli) createContainer(config *runconfig.Config, hostConfig *runc <ide> } <ide> <ide> //create the container <del> stream, statusCode, err := cli.call("POST", "/containers/create?"+containerValues.Encode(), data, false) <add> stream, statusCode, err := cli.call("POST", "/containers/create?"+containerValues.Encode(), mergedConfig, false) <ide> //if image not found try to pull it <ide> if statusCode == 404 { <ide> fmt.Fprintf(cli.err, "Unable to find image '%s' locally\n", config.Image) <ide> func (cli *DockerCli) createContainer(config *runconfig.Config, hostConfig *runc <ide> return nil, err <ide> } <ide> // Retry <del> if stream, _, err = cli.call("POST", "/containers/create?"+containerValues.Encode(), data, false); err != nil { <add> if stream, _, err = cli.call("POST", "/containers/create?"+containerValues.Encode(), mergedConfig, false); err != nil { <ide> return nil, err <ide> } <ide> } else if err != nil { <ide> func (cli *DockerCli) CmdRun(args ...string) error { <ide> sigProxy = false <ide> } <ide> <del> runResult, err := cli.createContainer(config, nil, hostConfig.ContainerIDFile, *flName) <add> runResult, err := cli.createContainer(config, hostConfig, hostConfig.ContainerIDFile, *flName) <ide> if err != nil { <ide> return err <ide> } <ide><path>builder/internals.go <ide> func (b *Builder) runContextCommand(args []string, allowRemote bool, allowDecomp <ide> return nil <ide> } <ide> <del> container, _, err := b.Daemon.Create(b.Config, "") <add> container, _, err := b.Daemon.Create(b.Config, nil, "") <ide> if err != nil { <ide> return err <ide> } <ide> func (b *Builder) create() (*daemon.Container, error) { <ide> config := *b.Config <ide> <ide> // Create the container <del> c, warnings, err := b.Daemon.Create(b.Config, "") <add> c, warnings, err := b.Daemon.Create(b.Config, nil, "") <ide> if err != nil { <ide> return nil, err <ide> } <ide><path>daemon/create.go <ide> func (daemon *Daemon) ContainerCreate(job *engine.Job) engine.Status { <ide> job.Errorf("Your kernel does not support swap limit capabilities. Limitation discarded.\n") <ide> config.MemorySwap = -1 <ide> } <del> container, buildWarnings, err := daemon.Create(config, name) <add> <add> var hostConfig *runconfig.HostConfig <add> if job.EnvExists("HostConfig") { <add> hostConfig = runconfig.ContainerHostConfigFromJob(job) <add> } else { <add> // Older versions of the API don't provide a HostConfig. <add> hostConfig = nil <add> } <add> <add> container, buildWarnings, err := daemon.Create(config, hostConfig, name) <ide> if err != nil { <ide> if daemon.Graph().IsNotExist(err) { <ide> _, tag := parsers.ParseRepositoryTag(config.Image) <ide> func (daemon *Daemon) ContainerCreate(job *engine.Job) engine.Status { <ide> job.Errorf("%s\n", warning) <ide> } <ide> <del> if job.EnvExists("HostConfig") { <del> hostConfig := runconfig.ContainerHostConfigFromJob(job) <del> if err := daemon.setHostConfig(container, hostConfig); err != nil { <del> return job.Error(err) <del> } <del> } <del> <ide> return engine.StatusOK <ide> } <ide> <ide> // Create creates a new container from the given configuration with a given name. <del>func (daemon *Daemon) Create(config *runconfig.Config, name string) (*Container, []string, error) { <add>func (daemon *Daemon) Create(config *runconfig.Config, hostConfig *runconfig.HostConfig, name string) (*Container, []string, error) { <ide> var ( <ide> container *Container <ide> warnings []string <ide> func (daemon *Daemon) Create(config *runconfig.Config, name string) (*Container, <ide> if err := daemon.createRootfs(container, img); err != nil { <ide> return nil, nil, err <ide> } <add> if hostConfig != nil { <add> if err := daemon.setHostConfig(container, hostConfig); err != nil { <add> return nil, nil, err <add> } <add> } <ide> if err := container.ToDisk(); err != nil { <ide> return nil, nil, err <ide> } <ide><path>daemon/start.go <ide> func (daemon *Daemon) ContainerStart(job *engine.Job) engine.Status { <ide> } <ide> <ide> // If no environment was set, then no hostconfig was passed. <add> // This is kept for backward compatibility - hostconfig should be passed when <add> // creating a container, not during start. <ide> if len(job.Environ()) > 0 { <ide> hostConfig := runconfig.ContainerHostConfigFromJob(job) <ide> if err := daemon.setHostConfig(container, hostConfig); err != nil { <ide><path>integration/container_test.go <ide> func TestRestartStdin(t *testing.T) { <ide> <ide> OpenStdin: true, <ide> }, <add> &runconfig.HostConfig{}, <ide> "", <ide> ) <ide> if err != nil { <ide> func TestStdin(t *testing.T) { <ide> <ide> OpenStdin: true, <ide> }, <add> &runconfig.HostConfig{}, <ide> "", <ide> ) <ide> if err != nil { <ide> func TestTty(t *testing.T) { <ide> <ide> OpenStdin: true, <ide> }, <add> &runconfig.HostConfig{}, <ide> "", <ide> ) <ide> if err != nil { <ide> func BenchmarkRunSequential(b *testing.B) { <ide> Image: GetTestImage(daemon).ID, <ide> Cmd: []string{"echo", "-n", "foo"}, <ide> }, <add> &runconfig.HostConfig{}, <ide> "", <ide> ) <ide> if err != nil { <ide> func BenchmarkRunParallel(b *testing.B) { <ide> Image: GetTestImage(daemon).ID, <ide> Cmd: []string{"echo", "-n", "foo"}, <ide> }, <add> &runconfig.HostConfig{}, <ide> "", <ide> ) <ide> if err != nil { <ide><path>integration/runtime_test.go <ide> func TestDaemonCreate(t *testing.T) { <ide> Image: GetTestImage(daemon).ID, <ide> Cmd: []string{"ls", "-al"}, <ide> }, <add> &runconfig.HostConfig{}, <ide> "", <ide> ) <ide> if err != nil { <ide> func TestDaemonCreate(t *testing.T) { <ide> Image: GetTestImage(daemon).ID, <ide> Cmd: []string{"ls", "-al"}, <ide> }, <add> &runconfig.HostConfig{}, <ide> "conflictname", <ide> ) <del> if _, _, err := daemon.Create(&runconfig.Config{Image: GetTestImage(daemon).ID, Cmd: []string{"ls", "-al"}}, testContainer.Name); err == nil || !strings.Contains(err.Error(), utils.TruncateID(testContainer.ID)) { <add> if _, _, err := daemon.Create(&runconfig.Config{Image: GetTestImage(daemon).ID, Cmd: []string{"ls", "-al"}}, &runconfig.HostConfig{}, testContainer.Name); err == nil || !strings.Contains(err.Error(), utils.TruncateID(testContainer.ID)) { <ide> t.Fatalf("Name conflict error doesn't include the correct short id. Message was: %s", err.Error()) <ide> } <ide> <ide> // Make sure create with bad parameters returns an error <del> if _, _, err = daemon.Create(&runconfig.Config{Image: GetTestImage(daemon).ID}, ""); err == nil { <add> if _, _, err = daemon.Create(&runconfig.Config{Image: GetTestImage(daemon).ID}, &runconfig.HostConfig{}, ""); err == nil { <ide> t.Fatal("Builder.Create should throw an error when Cmd is missing") <ide> } <ide> <ide> func TestDaemonCreate(t *testing.T) { <ide> Image: GetTestImage(daemon).ID, <ide> Cmd: []string{}, <ide> }, <add> &runconfig.HostConfig{}, <ide> "", <ide> ); err == nil { <ide> t.Fatal("Builder.Create should throw an error when Cmd is empty") <ide> func TestDaemonCreate(t *testing.T) { <ide> Cmd: []string{"/bin/ls"}, <ide> PortSpecs: []string{"80"}, <ide> } <del> container, _, err = daemon.Create(config, "") <add> container, _, err = daemon.Create(config, &runconfig.HostConfig{}, "") <ide> <ide> _, err = daemon.Commit(container, "testrepo", "testtag", "", "", true, config) <ide> if err != nil { <ide> func TestDaemonCreate(t *testing.T) { <ide> Cmd: []string{"ls", "-al"}, <ide> PortSpecs: []string{"80:8000"}, <ide> }, <add> &runconfig.HostConfig{}, <ide> "", <ide> ) <ide> if err != nil { <ide> func TestDestroy(t *testing.T) { <ide> container, _, err := daemon.Create(&runconfig.Config{ <ide> Image: GetTestImage(daemon).ID, <ide> Cmd: []string{"ls", "-al"}, <del> }, "") <add> }, <add> &runconfig.HostConfig{}, <add> "") <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide> func TestDestroyWithInitLayer(t *testing.T) { <ide> container, _, err := daemon.Create(&runconfig.Config{ <ide> Image: GetTestImage(daemon).ID, <ide> Cmd: []string{"ls", "-al"}, <del> }, "") <add> }, <add> &runconfig.HostConfig{}, <add> "") <ide> <ide> if err != nil { <ide> t.Fatal(err) <ide><path>integration/utils_test.go <ide> func mkContainer(r *daemon.Daemon, args []string, t *testing.T) (*daemon.Contain <ide> if config.Image == "_" { <ide> config.Image = GetTestImage(r).ID <ide> } <del> c, _, err := r.Create(config, "") <add> c, _, err := r.Create(config, nil, "") <ide> if err != nil { <ide> return nil, nil, err <ide> }
7
Text
Text
move code of conduct to admin repo
645cd19b584f8c6d1c9d75a40724cc2dd498fc74
<ide><path>CODE_OF_CONDUCT.md <ide> # Code of Conduct <ide> <ide> The Node.js Code of Conduct document has moved to <del>https://github.com/nodejs/TSC/blob/master/CODE_OF_CONDUCT.md. Please update <add>https://github.com/nodejs/admin/blob/master/CODE_OF_CONDUCT.md. Please update <ide> links to this document accordingly. <add> <add>The Node.js Moderation policy can be found at <add>https://github.com/nodejs/admin/blob/master/Moderation-Policy.md <ide><path>CONTRIBUTING.md <ide> By making a contribution to this project, I certify that: <ide> [benchmark results]: ./doc/guides/writing-and-running-benchmarks.md <ide> [Building guide]: ./BUILDING.md <ide> [CI (Continuous Integration) test run]: #ci-testing <del>[Code of Conduct]: https://github.com/nodejs/TSC/blob/master/CODE_OF_CONDUCT.md <add>[Code of Conduct]: https://github.com/nodejs/admin/blob/master/CODE_OF_CONDUCT.md <ide> [https://ci.nodejs.org/]: https://ci.nodejs.org/ <ide> [IRC in the #node-dev channel]: https://webchat.freenode.net?channels=node-dev&uio=d4 <ide> [Node.js help repository]: https://github.com/nodejs/help/issues <ide><path>README.md <ide> Previous releases may also have been signed with one of the following GPG keys: <ide> * [Working Groups][] <ide> <ide> [npm]: https://www.npmjs.com <del>[Code of Conduct]: https://github.com/nodejs/TSC/blob/master/CODE_OF_CONDUCT.md <add>[Code of Conduct]: https://github.com/nodejs/admin/blob/master/CODE_OF_CONDUCT.md <ide> [Contributing to the project]: CONTRIBUTING.md <ide> [Node.js Help]: https://github.com/nodejs/help <ide> [Node.js Website]: https://nodejs.org/en/ <ide><path>doc/onboarding.md <ide> onboarding session. <ide> accommodation, transportation, visa fees etc. if needed. Check out the <ide> [summit](https://github.com/nodejs/summit) repository for details. <ide> <del>[Code of Conduct]: https://github.com/nodejs/TSC/blob/master/CODE_OF_CONDUCT.md <add>[Code of Conduct]: https://github.com/nodejs/admin/blob/master/CODE_OF_CONDUCT.md <ide> [`core-validate-commit`]: https://github.com/evanlucas/core-validate-commit <ide> [`node-core-utils`]: https://github.com/nodejs/node-core-utils
4
Ruby
Ruby
remove file#to_path alias
a7ba8e1fb325a20dc5115eeef278ce946d0450c7
<ide><path>actionpack/lib/action_controller/metal/data_streaming.rb <del>require 'active_support/core_ext/file/path' <ide> require 'action_controller/metal/exceptions' <ide> <ide> module ActionController #:nodoc: <ide> def send_data(data, options = {}) #:doc: <ide> private <ide> def send_file_headers!(options) <ide> type_provided = options.has_key?(:type) <del> <add> <ide> options.update(DEFAULT_SEND_FILE_OPTIONS.merge(options)) <ide> [:type, :disposition].each do |arg| <ide> raise ArgumentError, ":#{arg} option required" if options[arg].nil? <ide><path>actionpack/lib/action_controller/metal/streaming.rb <del>require 'active_support/core_ext/file/path' <ide> require 'rack/chunked' <ide> <ide> module ActionController #:nodoc: <ide> module ActionController #:nodoc: <ide> # ==== Passenger <ide> # <ide> # To be described. <del> # <add> # <ide> module Streaming <ide> extend ActiveSupport::Concern <ide> <ide><path>activesupport/lib/active_support/core_ext/file.rb <ide> require 'active_support/core_ext/file/atomic' <del>require 'active_support/core_ext/file/path' <ide><path>activesupport/lib/active_support/core_ext/file/path.rb <del>class File <del> unless File.allocate.respond_to?(:to_path) <del> alias to_path path <del> end <del>end <ide>\ No newline at end of file <ide><path>activesupport/lib/active_support/ruby/shim.rb <ide> require 'active_support/core_ext/string/encoding' <ide> require 'active_support/core_ext/rexml' <ide> require 'active_support/core_ext/time/conversions' <del>require 'active_support/core_ext/file/path' <ide><path>activesupport/test/core_ext/file_test.rb <ide> def test_atomic_write_preserves_default_file_permissions <ide> File.unlink(file_name) rescue nil <ide> end <ide> <del> def test_responds_to_to_path <del> assert_equal __FILE__, File.open(__FILE__, "r").to_path <del> end <del> <ide> private <ide> def file_name <ide> "atomic.file"
6
Text
Text
remove strong syntax around code inline code
83e3d939537d1ab3e4e84577bbaa8a94b9edc8bb
<ide><path>curriculum/challenges/english/01-responsive-web-design/basic-html-and-html5/link-to-external-pages-with-anchor-elements.md <ide> You can use `a` (*anchor*) elements to link to content outside of your web page. <ide> <ide> `<a href="https://freecodecamp.org">this links to freecodecamp.org</a>` <ide> <del>Then your browser will display the text **"this links to freecodecamp.org"** as a link you can click. And that link will take you to the web address **`https://www.freecodecamp.org`**. <add>Then your browser will display the text `this links to freecodecamp.org` as a link you can click. And that link will take you to the web address `https://www.freecodecamp.org`. <ide> <ide> # --instructions-- <ide>
1
Python
Python
fix a bug
fbe2af255824ad463da6936ab86738429008aee9
<ide><path>numpy/f2py/crackfortran.py <ide> def crack2fortrangen(block,tab='\n'): <ide> global skipfuncs, onlyfuncs <ide> setmesstext(block) <ide> ret='' <del> if type(block) is type([]): <add> if isinstance(block, list): <ide> for g in block: <del> if g['block'] in ['function','subroutine']: <add> if g and g['block'] in ['function','subroutine']: <ide> if g['name'] in skipfuncs: <ide> continue <ide> if onlyfuncs and g['name'] not in onlyfuncs:
1
Python
Python
add binary to file reading
dd983ea6b9e716abd5e35886e4d4672f1e420b72
<ide><path>inception/inception/data/build_image_data.py <ide> def _process_image(filename, coder): <ide> width: integer, image width in pixels. <ide> """ <ide> # Read the image file. <del> with tf.gfile.FastGFile(filename, 'r') as f: <add> with tf.gfile.FastGFile(filename, 'rb') as f: <ide> image_data = f.read() <ide> <ide> # Convert any PNG to JPEG's for consistency.
1
PHP
PHP
add a chunk method to collection
6cd389a68d7fffa94fd3439ee49065562fe74ef9
<ide><path>src/Illuminate/Support/Collection.php <ide> public function slice($offset, $length = null, $preserveKeys = false) <ide> return new static(array_slice($this->items, $offset, $length, $preserveKeys)); <ide> } <ide> <add> /** <add> * Chunk the underlying collection array. <add> * <add> * @param int $size <add> * @param bool $preserveKeys <add> * @return \Illuminate\Support\Collection <add> */ <add> public function chunk($size, $preserveKeys = false) <add> { <add> $chunks = new static; <add> <add> foreach (array_chunk($this->items, $size, $preserveKeys) as $chunk) <add> { <add> $chunks->push(new static($chunk)); <add> } <add> <add> return $chunks; <add> } <add> <ide> /** <ide> * Sort through each item with a callback. <ide> * <ide><path>tests/Support/SupportCollectionTest.php <ide> public function testReverse() <ide> } <ide> <ide> <add> public function testChunk () <add> { <add> $data = new Collection(array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)); <add> $data = $data->chunk(3); <add> <add> $this->assertInstanceOf('Illuminate\Support\Collection', $data); <add> $this->assertInstanceOf('Illuminate\Support\Collection', $data[0]); <add> $this->assertEquals(4, $data->count()); <add> $this->assertEquals(array(1, 2, 3), $data[0]->toArray()); <add> $this->assertEquals(array(10), $data[3]->toArray()); <add> } <add> <add> <ide> public function testListsWithArrayAndObjectValues() <ide> { <ide> $data = new Collection(array((object) array('name' => 'taylor', 'email' => 'foo'), array('name' => 'dayle', 'email' => 'bar')));
2
Python
Python
expand tasks in mapped group at parse time
a16aa730686c99916f5bc5550ed52259499b2468
<ide><path>airflow/decorators/base.py <ide> ListOfDictsExpandInput, <ide> OperatorExpandArgument, <ide> OperatorExpandKwargsArgument, <add> is_mappable, <ide> ) <del>from airflow.models.mappedoperator import ( <del> MappedOperator, <del> ValidationSource, <del> ensure_xcomarg_return_value, <del> get_mappable_types, <del>) <add>from airflow.models.mappedoperator import MappedOperator, ValidationSource, ensure_xcomarg_return_value <ide> from airflow.models.pool import Pool <ide> from airflow.models.xcom_arg import XComArg <ide> from airflow.typing_compat import ParamSpec, Protocol <ide> def _validate_arg_names(self, func: ValidationSource, kwargs: dict[str, Any]) -> <ide> kwargs_left = kwargs.copy() <ide> for arg_name in self._mappable_function_argument_names: <ide> value = kwargs_left.pop(arg_name, NOTSET) <del> if func != "expand" or value is NOTSET or isinstance(value, get_mappable_types()): <add> if func != "expand" or value is NOTSET or is_mappable(value): <ide> continue <ide> tname = type(value).__name__ <ide> raise ValueError(f"expand() got an unexpected type {tname!r} for keyword argument {arg_name!r}") <ide><path>airflow/decorators/task_group.py <ide> from typing import TYPE_CHECKING, Any, Callable, ClassVar, Generic, Mapping, Sequence, TypeVar, overload <ide> <ide> import attr <del>from sqlalchemy.orm import Session <ide> <ide> from airflow.decorators.base import ExpandableFactory <ide> from airflow.models.expandinput import ( <ide> DictOfListsExpandInput, <del> ExpandInput, <ide> ListOfDictsExpandInput, <add> MappedArgument, <ide> OperatorExpandArgument, <ide> OperatorExpandKwargsArgument, <ide> ) <ide> from airflow.models.taskmixin import DAGNode <ide> from airflow.models.xcom_arg import XComArg <ide> from airflow.typing_compat import ParamSpec <del>from airflow.utils.context import Context <ide> from airflow.utils.helpers import prevent_duplicates <del>from airflow.utils.mixins import ResolveMixin <del>from airflow.utils.session import NEW_SESSION, provide_session <ide> from airflow.utils.task_group import MappedTaskGroup, TaskGroup <ide> <ide> if TYPE_CHECKING: <ide> task_group_sig = inspect.signature(TaskGroup.__init__) <ide> <ide> <del>@attr.define(kw_only=True) <del>class _MappedArgument(ResolveMixin): <del> _input: ExpandInput <del> _key: str <del> <del> @provide_session <del> def resolve(self, context: Context, *, session: Session = NEW_SESSION) -> Any: <del> data, _ = self._input.resolve(context, session=session) <del> return data[self._key] <del> <del> <ide> @attr.define() <ide> class _TaskGroupFactory(ExpandableFactory, Generic[FParams, FReturn]): <ide> function: Callable[FParams, FReturn] = attr.ib(validator=attr.validators.is_callable()) <ide> def expand(self, **kwargs: OperatorExpandArgument) -> DAGNode: <ide> return self._create_task_group( <ide> functools.partial(MappedTaskGroup, expand_input=expand_input), <ide> **self.partial_kwargs, <del> **{k: _MappedArgument(input=expand_input, key=k) for k in kwargs}, <add> **{k: MappedArgument(input=expand_input, key=k) for k in kwargs}, <ide> ) <ide> <ide> def expand_kwargs(self, kwargs: OperatorExpandKwargsArgument) -> DAGNode: <ide> def expand_kwargs(self, kwargs: OperatorExpandKwargsArgument) -> DAGNode: <ide> return self._create_task_group( <ide> functools.partial(MappedTaskGroup, expand_input=expand_input), <ide> **self.partial_kwargs, <del> **{k: _MappedArgument(input=expand_input, key=k) for k in map_kwargs}, <add> **{k: MappedArgument(input=expand_input, key=k) for k in map_kwargs}, <ide> ) <ide> <ide> <ide><path>airflow/models/abstractoperator.py <ide> from __future__ import annotations <ide> <ide> import datetime <add>import functools <ide> import inspect <add>import operator <ide> from typing import TYPE_CHECKING, Any, Callable, ClassVar, Collection, Iterable, Iterator, Sequence <ide> <del>from airflow.compat.functools import cached_property <add>from airflow.compat.functools import cache, cached_property <ide> from airflow.configuration import conf <ide> from airflow.exceptions import AirflowException <ide> from airflow.models.taskmixin import DAGNode <ide> from airflow.utils.log.logging_mixin import LoggingMixin <ide> from airflow.utils.mixins import ResolveMixin <ide> from airflow.utils.session import NEW_SESSION, provide_session <add>from airflow.utils.task_group import MappedTaskGroup <ide> from airflow.utils.trigger_rule import TriggerRule <ide> from airflow.utils.weight_rule import WeightRule <ide> <ide> ) <ide> <ide> <add>class NotMapped(Exception): <add> """Raise if a task is neither mapped nor has any parent mapped groups.""" <add> <add> <ide> class AbstractOperator(LoggingMixin, DAGNode): <ide> """Common implementation for operators, including unmapped and mapped. <ide> <ide> def iter_mapped_dependants(self) -> Iterator[MappedOperator]: <ide> if any(p.node_id == self.node_id for p in downstream.iter_mapped_dependencies()) <ide> ) <ide> <add> def iter_mapped_task_groups(self) -> Iterator[MappedTaskGroup]: <add> """Return mapped task groups this task belongs to.""" <add> parent = self.task_group <add> while parent is not None: <add> if isinstance(parent, MappedTaskGroup): <add> yield parent <add> parent = parent.task_group <add> <ide> def unmap(self, resolve: None | dict[str, Any] | tuple[Context, Session]) -> BaseOperator: <ide> """Get the "normal" operator from current abstract operator. <ide> <ide> def get_extra_links(self, ti: TaskInstance, link_name: str) -> str | None: <ide> return link.get_link(self.unmap(None), ti.dag_run.logical_date) # type: ignore[misc] <ide> return link.get_link(self.unmap(None), ti_key=ti.key) <ide> <add> @cache <add> def get_parse_time_mapped_ti_count(self) -> int: <add> """Number of mapped task instances that can be created on DAG run creation. <add> <add> This only considers literal mapped arguments, and would return *None* <add> when any non-literal values are used for mapping. <add> <add> :raise NotFullyPopulated: If non-literal mapped arguments are encountered. <add> :raise NotMapped: If the operator is neither mapped, nor has any parent <add> mapped task groups. <add> :return: Total number of mapped TIs this task should have. <add> """ <add> mapped_task_groups = list(self.iter_mapped_task_groups()) <add> if not mapped_task_groups: <add> raise NotMapped <add> counts = (g.get_parse_time_mapped_ti_count() for g in mapped_task_groups) <add> return functools.reduce(operator.mul, counts) <add> <add> def get_mapped_ti_count(self, run_id: str, *, session: Session) -> int: <add> """Number of mapped TaskInstances that can be created at run time. <add> <add> This considers both literal and non-literal mapped arguments, and the <add> result is therefore available when all depended tasks have finished. The <add> return value should be identical to ``parse_time_mapped_ti_count`` if <add> all mapped arguments are literal. <add> <add> :raise NotFullyPopulated: If upstream tasks are not all complete yet. <add> :raise NotMapped: If the operator is neither mapped, nor has any parent <add> mapped task groups. <add> :return: Total number of mapped TIs this task should have. <add> """ <add> mapped_task_groups = list(self.iter_mapped_task_groups()) <add> if not mapped_task_groups: <add> raise NotMapped <add> counts = (g.get_mapped_ti_count(run_id, session=session) for g in mapped_task_groups) <add> return functools.reduce(operator.mul, counts) <add> <ide> def render_template_fields( <ide> self, <ide> context: Context, <ide><path>airflow/models/dagrun.py <ide> import warnings <ide> from collections import defaultdict <ide> from datetime import datetime <del>from typing import ( <del> TYPE_CHECKING, <del> Any, <del> Callable, <del> Iterable, <del> Iterator, <del> NamedTuple, <del> Sequence, <del> TypeVar, <del> cast, <del> overload, <del>) <add>from typing import TYPE_CHECKING, Any, Callable, Iterable, Iterator, NamedTuple, Sequence, TypeVar, overload <ide> <ide> from sqlalchemy import ( <ide> Boolean, <ide> from airflow.callbacks.callback_requests import DagCallbackRequest <ide> from airflow.configuration import conf as airflow_conf <ide> from airflow.exceptions import AirflowException, RemovedInAirflow3Warning, TaskNotFound <add>from airflow.models.abstractoperator import NotMapped <ide> from airflow.models.base import Base, StringID <add>from airflow.models.expandinput import NotFullyPopulated <ide> from airflow.models.mappedoperator import MappedOperator <ide> from airflow.models.taskinstance import TaskInstance as TI <ide> from airflow.models.tasklog import LogTemplate <ide> def _check_for_removed_or_restored_tasks( <ide> for ti in tis: <ide> ti_mutation_hook(ti) <ide> task_ids.add(ti.task_id) <del> task = None <ide> try: <ide> task = dag.get_task(ti.task_id) <ide> <ide> def _check_for_removed_or_restored_tasks( <ide> ti.state = State.REMOVED <ide> continue <ide> <del> if not task.is_mapped: <add> try: <add> num_mapped_tis = task.get_parse_time_mapped_ti_count() <add> except NotMapped: <ide> continue <del> task = cast("MappedOperator", task) <del> num_mapped_tis = task.parse_time_mapped_ti_count <del> # Check if the number of mapped literals has changed and we need to mark this TI as removed <del> if num_mapped_tis is not None: <del> if ti.map_index >= num_mapped_tis: <del> self.log.debug( <del> "Removing task '%s' as the map_index is longer than the literal mapping list (%s)", <del> ti, <del> num_mapped_tis, <del> ) <del> ti.state = State.REMOVED <del> elif ti.map_index < 0: <del> self.log.debug("Removing the unmapped TI '%s' as the mapping can now be performed", ti) <del> ti.state = State.REMOVED <del> else: <del> # What if it is _now_ dynamically mapped, but wasn't before? <del> task.get_mapped_ti_count.cache_clear() # type: ignore[attr-defined] <del> total_length = task.get_mapped_ti_count(self.run_id, session=session) <del> <del> if total_length is None: <add> except NotFullyPopulated: <add> # What if it is _now_ dynamically mapped, but wasn't before? <add> try: <add> total_length = task.get_mapped_ti_count(self.run_id, session=session) <add> except NotFullyPopulated: <ide> # Not all upstreams finished, so we can't tell what should be here. Remove everything. <ide> if ti.map_index >= 0: <ide> self.log.debug( <ide> def _check_for_removed_or_restored_tasks( <ide> total_length, <ide> ) <ide> ti.state = State.REMOVED <add> else: <add> # Check if the number of mapped literals has changed and we need to mark this TI as removed. <add> if ti.map_index >= num_mapped_tis: <add> self.log.debug( <add> "Removing task '%s' as the map_index is longer than the literal mapping list (%s)", <add> ti, <add> num_mapped_tis, <add> ) <add> ti.state = State.REMOVED <add> elif ti.map_index < 0: <add> self.log.debug("Removing the unmapped TI '%s' as the mapping can now be performed", ti) <add> ti.state = State.REMOVED <ide> <ide> return task_ids <ide> <ide> def _create_tasks( <ide> :param tasks: Tasks to create jobs for in the DAG run <ide> :param task_creator: Function to create task instances <ide> """ <add> map_indexes: Iterable[int] <ide> for task in tasks: <del> if not task.is_mapped: <del> yield from task_creator(task, (-1,)) <del> continue <del> count = cast(MappedOperator, task).get_mapped_ti_count(self.run_id, session=session) <del> if count: <del> yield from task_creator(task, range(count)) <del> continue <del> yield from task_creator(task, (-1,)) <add> try: <add> count = task.get_mapped_ti_count(self.run_id, session=session) <add> except (NotMapped, NotFullyPopulated): <add> map_indexes = (-1,) <add> else: <add> if count: <add> map_indexes = range(count) <add> else: <add> # Make sure to always create at least one ti; this will be <add> # marked as REMOVED later at runtime. <add> map_indexes = (-1,) <add> yield from task_creator(task, map_indexes) <ide> <ide> def _create_task_instances( <ide> self, <ide> def _revise_mapped_task_indexes(self, task: MappedOperator, session: Session) -> <ide> """Check if task increased or reduced in length and handle appropriately""" <ide> from airflow.settings import task_instance_mutation_hook <ide> <del> task.get_mapped_ti_count.cache_clear() # type: ignore[attr-defined] <del> total_length = task.get_mapped_ti_count(self.run_id, session=session) <del> if total_length is None: # Upstreams not ready, don't need to revise this yet. <add> try: <add> total_length = task.get_mapped_ti_count(self.run_id, session=session) <add> except NotFullyPopulated: # Upstreams not ready, don't need to revise this yet. <ide> return [] <ide> <ide> query = session.query(TI.map_index).filter( <ide><path>airflow/models/expandinput.py <ide> import operator <ide> from typing import TYPE_CHECKING, Any, Dict, Iterable, Mapping, NamedTuple, Sequence, Sized, Union <ide> <del>from airflow.compat.functools import cache <add>import attr <add> <add>from airflow.typing_compat import TypeGuard <ide> from airflow.utils.context import Context <add>from airflow.utils.mixins import ResolveMixin <add>from airflow.utils.session import NEW_SESSION, provide_session <ide> <ide> if TYPE_CHECKING: <ide> from sqlalchemy.orm import Session <ide> <ide> # Each keyword argument to expand() can be an XComArg, sequence, or dict (not <ide> # any mapping since we need the value to be ordered). <del>OperatorExpandArgument = Union["XComArg", Sequence, Dict[str, Any]] <add>OperatorExpandArgument = Union["MappedArgument", "XComArg", Sequence, Dict[str, Any]] <ide> <ide> # The single argument of expand_kwargs() can be an XComArg, or a list with each <ide> # element being either an XComArg or a dict. <ide> OperatorExpandKwargsArgument = Union["XComArg", Sequence[Union["XComArg", Mapping[str, Any]]]] <ide> <ide> <del># For isinstance() check. <del>@cache <del>def get_mappable_types() -> tuple[type, ...]: <add>@attr.define(kw_only=True) <add>class MappedArgument(ResolveMixin): <add> """Stand-in stub for task-group-mapping arguments. <add> <add> This is very similar to an XComArg, but resolved differently. Declared here <add> (instead of in the task group module) to avoid import cycles. <add> """ <add> <add> _input: ExpandInput <add> _key: str <add> <add> def get_task_map_length(self, run_id: str, *, session: Session) -> int | None: <add> # TODO (AIP-42): Implement run-time task map length inspection. <add> # This simply marks the value as un-expandable at parse-time. <add> return None <add> <add> @provide_session <add> def resolve(self, context: Context, *, session: Session = NEW_SESSION) -> Any: <add> data, _ = self._input.resolve(context, session=session) <add> return data[self._key] <add> <add> <add># To replace tedious isinstance() checks. <add>def is_mappable(v: Any) -> TypeGuard[OperatorExpandArgument]: <add> from airflow.models.xcom_arg import XComArg <add> <add> return isinstance(v, (MappedArgument, XComArg, Mapping, Sequence)) and not isinstance(v, str) <add> <add> <add># To replace tedious isinstance() checks. <add>def _is_parse_time_mappable(v: OperatorExpandArgument) -> TypeGuard[Mapping | Sequence]: <add> from airflow.models.xcom_arg import XComArg <add> <add> return not isinstance(v, (MappedArgument, XComArg)) <add> <add> <add># To replace tedious isinstance() checks. <add>def _needs_run_time_resolution(v: OperatorExpandArgument) -> TypeGuard[MappedArgument | XComArg]: <ide> from airflow.models.xcom_arg import XComArg <ide> <del> return (XComArg, list, tuple, dict) <add> return isinstance(v, (MappedArgument, XComArg)) <ide> <ide> <ide> class NotFullyPopulated(RuntimeError): <ide> class DictOfListsExpandInput(NamedTuple): <ide> <ide> def _iter_parse_time_resolved_kwargs(self) -> Iterable[tuple[str, Sized]]: <ide> """Generate kwargs with values available on parse-time.""" <del> from airflow.models.xcom_arg import XComArg <add> return ((k, v) for k, v in self.value.items() if _is_parse_time_mappable(v)) <ide> <del> return ((k, v) for k, v in self.value.items() if not isinstance(v, XComArg)) <del> <del> def get_parse_time_mapped_ti_count(self) -> int | None: <add> def get_parse_time_mapped_ti_count(self) -> int: <ide> if not self.value: <ide> return 0 <ide> literal_values = [len(v) for _, v in self._iter_parse_time_resolved_kwargs()] <ide> if len(literal_values) != len(self.value): <del> return None # None-literal type encountered, so give up. <add> literal_keys = (k for k, _ in self._iter_parse_time_resolved_kwargs()) <add> raise NotFullyPopulated(set(self.value).difference(literal_keys)) <ide> return functools.reduce(operator.mul, literal_values, 1) <ide> <ide> def _get_map_lengths(self, run_id: str, *, session: Session) -> dict[str, int]: <ide> def _get_map_lengths(self, run_id: str, *, session: Session) -> dict[str, int]: <ide> If any arguments are not known right now (upstream task not finished), <ide> they will not be present in the dict. <ide> """ <del> from airflow.models.xcom_arg import XComArg <del> <ide> # TODO: This initiates one database call for each XComArg. Would it be <ide> # more efficient to do one single db call and unpack the value here? <del> map_lengths_iterator = ( <del> (k, (v.get_task_map_length(run_id, session=session) if isinstance(v, XComArg) else len(v))) <del> for k, v in self.value.items() <del> ) <add> def _get_length(v: OperatorExpandArgument) -> int | None: <add> if _needs_run_time_resolution(v): <add> return v.get_task_map_length(run_id, session=session) <add> # Unfortunately a user-defined TypeGuard cannot apply negative type <add> # narrowing. https://github.com/python/typing/discussions/1013 <add> if TYPE_CHECKING: <add> assert isinstance(v, Sized) <add> return len(v) <add> <add> map_lengths_iterator = ((k, _get_length(v)) for k, v in self.value.items()) <ide> <ide> map_lengths = {k: v for k, v in map_lengths_iterator if v is not None} <ide> if len(map_lengths) < len(self.value): <ide> def get_total_map_length(self, run_id: str, *, session: Session) -> int: <ide> return functools.reduce(operator.mul, (lengths[name] for name in self.value), 1) <ide> <ide> def _expand_mapped_field(self, key: str, value: Any, context: Context, *, session: Session) -> Any: <del> from airflow.models.xcom_arg import XComArg <del> <del> if isinstance(value, XComArg): <add> if _needs_run_time_resolution(value): <ide> value = value.resolve(context, session=session) <ide> map_index = context["ti"].map_index <ide> if map_index < 0: <ide> class ListOfDictsExpandInput(NamedTuple): <ide> <ide> value: OperatorExpandKwargsArgument <ide> <del> def get_parse_time_mapped_ti_count(self) -> int | None: <add> def get_parse_time_mapped_ti_count(self) -> int: <ide> if isinstance(self.value, collections.abc.Sized): <ide> return len(self.value) <del> return None <add> raise NotFullyPopulated({"expand_kwargs() argument"}) <ide> <ide> def get_total_map_length(self, run_id: str, *, session: Session) -> int: <ide> if isinstance(self.value, collections.abc.Sized): <ide><path>airflow/models/mappedoperator.py <ide> from sqlalchemy.orm.session import Session <ide> <ide> from airflow import settings <del>from airflow.compat.functools import cache, cached_property <add>from airflow.compat.functools import cache <ide> from airflow.exceptions import AirflowException, UnmappableOperator <ide> from airflow.models.abstractoperator import ( <ide> DEFAULT_IGNORE_FIRST_DEPENDS_ON_PAST, <ide> DEFAULT_TRIGGER_RULE, <ide> DEFAULT_WEIGHT_RULE, <ide> AbstractOperator, <add> NotMapped, <ide> TaskStateChangeCallback, <ide> ) <ide> from airflow.models.expandinput import ( <ide> NotFullyPopulated, <ide> OperatorExpandArgument, <ide> OperatorExpandKwargsArgument, <del> get_mappable_types, <add> is_mappable, <ide> ) <ide> from airflow.models.param import ParamsDict <ide> from airflow.models.pool import Pool <ide> def validate_mapping_kwargs(op: type[BaseOperator], func: ValidationSource, valu <ide> continue <ide> if value is NOTSET: <ide> continue <del> if isinstance(value, get_mappable_types()): <add> if is_mappable(value): <ide> continue <ide> type_name = type(value).__name__ <ide> error = f"{op.__name__}.expand() got an unexpected type {type_name!r} for keyword argument {name}" <ide> def iter_mapped_dependencies(self) -> Iterator[Operator]: <ide> for operator, _ in ref.iter_references(): <ide> yield operator <ide> <del> @cached_property <del> def parse_time_mapped_ti_count(self) -> int | None: <del> """Number of mapped TaskInstances that can be created at DagRun create time. <del> <del> This only considers literal mapped arguments, and would return *None* <del> when any non-literal values are used for mapping. <del> <del> :return: None if non-literal mapped arg encountered, or the total <del> number of mapped TIs this task should have. <del> """ <del> return self._get_specified_expand_input().get_parse_time_mapped_ti_count() <del> <ide> @cache <del> def get_mapped_ti_count(self, run_id: str, *, session: Session) -> int | None: <del> """Number of mapped TaskInstances that can be created at run time. <del> <del> This considers both literal and non-literal mapped arguments, and the <del> result is therefore available when all depended tasks have finished. The <del> return value should be identical to ``parse_time_mapped_ti_count`` if <del> all mapped arguments are literal. <add> def get_parse_time_mapped_ti_count(self) -> int: <add> current_count = self._get_specified_expand_input().get_parse_time_mapped_ti_count() <add> try: <add> parent_count = super().get_parse_time_mapped_ti_count() <add> except NotMapped: <add> return current_count <add> return parent_count * current_count <ide> <del> :return: None if upstream tasks are not complete yet, or the total <del> number of mapped TIs this task should have. <del> """ <add> def get_mapped_ti_count(self, run_id: str, *, session: Session) -> int: <add> current_count = self._get_specified_expand_input().get_total_map_length(run_id, session=session) <ide> try: <del> return self._get_specified_expand_input().get_total_map_length(run_id, session=session) <del> except NotFullyPopulated: <del> return None <add> parent_count = super().get_mapped_ti_count(run_id, session=session) <add> except NotMapped: <add> return current_count <add> return parent_count * current_count <ide> <ide> def render_template_fields( <ide> self, <ide><path>airflow/typing_compat.py <ide> "ParamSpec", <ide> "Protocol", <ide> "TypedDict", <add> "TypeGuard", <ide> "runtime_checkable", <ide> ] <ide> <ide> from typing_extensions import Literal <ide> <ide> if sys.version_info >= (3, 10): <del> from typing import ParamSpec <add> from typing import ParamSpec, TypeGuard <ide> else: <del> from typing_extensions import ParamSpec <add> from typing_extensions import ParamSpec, TypeGuard <ide><path>airflow/utils/task_group.py <ide> import weakref <ide> from typing import TYPE_CHECKING, Any, Generator, Sequence <ide> <add>from airflow.compat.functools import cache <ide> from airflow.exceptions import ( <ide> AirflowDagCycleException, <ide> AirflowException, <ide> from airflow.utils.helpers import validate_group_key <ide> <ide> if TYPE_CHECKING: <add> from sqlalchemy.orm import Session <add> <ide> from airflow.models.baseoperator import BaseOperator <ide> from airflow.models.dag import DAG <ide> from airflow.models.expandinput import ExpandInput <ide> def __init__(self, *, expand_input: ExpandInput, **kwargs: Any) -> None: <ide> super().__init__(**kwargs) <ide> self._expand_input = expand_input <ide> <add> @cache <add> def get_parse_time_mapped_ti_count(self) -> int: <add> """Number of instances a task in this group should be mapped to, when a DAG run is created. <add> <add> This only considers literal mapped arguments, and would return *None* <add> when any non-literal values are used for mapping. This also does not <add> account for nested mapped groups; only the number expanded due to this <add> specific group is returned, regardless of whether any of its parent <add> groups are mapped. <add> <add> :raise NotFullyPopulated: If any non-literal mapped arguments are encountered. <add> :return: The total number of mapped instances each task should have. <add> """ <add> return self._expand_input.get_parse_time_mapped_ti_count() <add> <add> def get_mapped_ti_count(self, run_id: str, *, session: Session) -> int: <add> """Number of instances a task in this group should be mapped to at run time. <add> <add> This considers both literal and non-literal mapped arguments, and the <add> result is therefore available when all depended tasks have finished. The <add> return value should be identical to ``parse_time_mapped_ti_count`` if <add> all mapped arguments are literal. <add> <add> :raise NotFullyPopulated: If upstream tasks are not all complete yet. <add> :return: Total number of mapped TIs this task should have. <add> """ <add> return self._expand_input.get_total_map_length(run_id, session=session) <add> <ide> <ide> class TaskGroupContext: <ide> """TaskGroup context is used to keep the current TaskGroup when TaskGroup is used as ContextManager.""" <ide><path>tests/decorators/test_task_group.py <ide> import pytest <ide> <ide> from airflow.decorators import dag, task_group <del>from airflow.decorators.task_group import _MappedArgument <del>from airflow.models.expandinput import DictOfListsExpandInput, ListOfDictsExpandInput <add>from airflow.models.expandinput import DictOfListsExpandInput, ListOfDictsExpandInput, MappedArgument <ide> from airflow.utils.task_group import MappedTaskGroup <ide> <ide> <ide> def tg(a, b): <ide> assert isinstance(tg, MappedTaskGroup) <ide> assert tg._expand_input == DictOfListsExpandInput({"b": ["x", "y"]}) <ide> <del> assert saved == {"a": 1, "b": _MappedArgument(input=tg._expand_input, key="b")} <add> assert saved == {"a": 1, "b": MappedArgument(input=tg._expand_input, key="b")} <ide> <ide> <ide> def test_expand_kwargs_no_wildcard(): <ide> def tg(a, b): <ide> assert isinstance(tg, MappedTaskGroup) <ide> assert tg._expand_input == ListOfDictsExpandInput([{"b": "x"}, {"b": None}]) <ide> <del> assert saved == {"a": 1, "b": _MappedArgument(input=tg._expand_input, key="b")} <add> assert saved == {"a": 1, "b": MappedArgument(input=tg._expand_input, key="b")} <ide><path>tests/models/test_dagrun.py <ide> <ide> from airflow import settings <ide> from airflow.callbacks.callback_requests import DagCallbackRequest <del>from airflow.decorators import task <add>from airflow.decorators import task, task_group <ide> from airflow.models import DAG, DagBag, DagModel, DagRun, TaskInstance as TI, clear_task_instances <ide> from airflow.models.baseoperator import BaseOperator <ide> from airflow.models.taskmap import TaskMap <ide> def task_2(arg2): <ide> <ide> <ide> @pytest.mark.need_serialized_dag <del>def test_mapped_mixed__literal_not_expanded_at_create(dag_maker, session): <add>def test_mapped_mixed_literal_not_expanded_at_create(dag_maker, session): <ide> literal = [1, 2, 3, 4] <ide> with dag_maker(session=session): <ide> task = BaseOperator(task_id="task_1") <ide> def test_mapped_mixed__literal_not_expanded_at_create(dag_maker, session): <ide> assert query.all() == [(-1, None)] <ide> <ide> <add>def test_mapped_task_group_expands_at_create(dag_maker, session): <add> literal = [[1, 2], [3, 4]] <add> <add> with dag_maker(session=session): <add> <add> @task_group <add> def tg(x): <add> # Normal operator in mapped task group, expands to 2 tis. <add> MockOperator(task_id="t1") <add> # Mapped operator expands *again* against mapped task group arguments to 4 tis. <add> MockOperator.partial(task_id="t2").expand(arg1=literal) <add> # Normal operator referencing mapped task group arguments does not further expand, only 2 tis. <add> MockOperator(task_id="t3", arg1=x) <add> # It can expand *again* (since each item in x is a list) but this is not done at parse time. <add> MockOperator.partial(task_id="t4").expand(arg1=x) <add> <add> tg.expand(x=literal) <add> <add> dr = dag_maker.create_dagrun() <add> query = ( <add> session.query(TI.task_id, TI.map_index, TI.state) <add> .filter_by(dag_id=dr.dag_id, run_id=dr.run_id) <add> .order_by(TI.task_id, TI.map_index) <add> ) <add> assert query.all() == [ <add> ("tg.t1", 0, None), <add> ("tg.t1", 1, None), <add> ("tg.t2", 0, None), <add> ("tg.t2", 1, None), <add> ("tg.t2", 2, None), <add> ("tg.t2", 3, None), <add> ("tg.t3", 0, None), <add> ("tg.t3", 1, None), <add> ("tg.t4", -1, None), <add> ] <add> <add> <ide> def test_ti_scheduling_mapped_zero_length(dag_maker, session): <ide> with dag_maker(session=session): <ide> task = BaseOperator(task_id="task_1") <ide><path>tests/models/test_taskinstance.py <ide> XCom, <ide> ) <ide> from airflow.models.dataset import DatasetDagRunQueue, DatasetEvent, DatasetModel <del>from airflow.models.expandinput import EXPAND_INPUT_EMPTY <add>from airflow.models.expandinput import EXPAND_INPUT_EMPTY, NotFullyPopulated <ide> from airflow.models.param import process_params <ide> from airflow.models.serialized_dag import SerializedDagModel <ide> from airflow.models.taskfail import TaskFail <ide> def show(a, b): <ide> ti.run() <ide> <ide> show_task = dag.get_task("show") <del> assert show_task.parse_time_mapped_ti_count is None <add> with pytest.raises(NotFullyPopulated): <add> assert show_task.get_parse_time_mapped_ti_count() <ide> mapped_tis, max_map_index = show_task.expand_mapped_task(dag_run.run_id, session=session) <ide> assert max_map_index + 1 == len(mapped_tis) == 4 <ide> <ide> def show(a, b): <ide> dag_run = dag_maker.create_dagrun() <ide> <ide> show_task = dag.get_task("show") <del> assert show_task.parse_time_mapped_ti_count == 6 <add> assert show_task.get_parse_time_mapped_ti_count() == 6 <ide> mapped_tis, max_map_index = show_task.expand_mapped_task(dag_run.run_id, session=session) <ide> assert len(mapped_tis) == 0 # Expanded at parse! <ide> assert max_map_index == 5 <ide><path>tests/test_utils/mapping.py <ide> def expand_mapped_task( <ide> session.flush() <ide> <ide> mapped.expand_mapped_task(run_id, session=session) <del> mapped.get_mapped_ti_count.cache_clear() # type: ignore[attr-defined]
12
Javascript
Javascript
add browserify support - fixes
85a7725cbafed1d892e156a0570e178198bef26a
<ide><path>src/Three.js <ide> <ide> var THREE = { REVISION: '68dev' }; <ide> <add>// browserify support <add>if (typeof module === 'object') { <add> module.exports = THREE; <add>} <add> <ide> self.console = self.console || { <ide> <ide> info: function () {},
1
PHP
PHP
fix docblock type
52b182cdff0a115ae31b2c1f03007e73e06e12b3
<ide><path>src/Illuminate/Foundation/helpers.php <ide> function auth($guard = null) <ide> /** <ide> * Create a new redirect response to the previous location. <ide> * <del> * @param int $status <del> * @param array $headers <del> * @param bool $fallback <add> * @param int $status <add> * @param array $headers <add> * @param string $fallback <ide> * @return \Illuminate\Http\RedirectResponse <ide> */ <ide> function back($status = 302, $headers = [], $fallback = false)
1
Mixed
Go
add --uts=host to allow sharing the uts namespace
f2e5207fc989288ad136d48222df8e7754eb0e9b
<ide><path>daemon/container.go <ide> func populateCommand(c *Container, env []string) error { <ide> pid := &execdriver.Pid{} <ide> pid.HostPid = c.hostConfig.PidMode.IsHost() <ide> <add> uts := &execdriver.UTS{ <add> HostUTS: c.hostConfig.UTSMode.IsHost(), <add> } <add> <ide> // Build lists of devices allowed and created within the container. <ide> var userSpecifiedDevices []*configs.Device <ide> for _, deviceMapping := range c.hostConfig.Devices { <ide> func populateCommand(c *Container, env []string) error { <ide> Network: en, <ide> Ipc: ipc, <ide> Pid: pid, <add> UTS: uts, <ide> Resources: resources, <ide> AllowedDevices: allowedDevices, <ide> AutoCreatedDevices: autoCreatedDevices, <ide><path>daemon/execdriver/driver.go <ide> type Pid struct { <ide> HostPid bool `json:"host_pid"` <ide> } <ide> <add>// UTS settings of the container <add>type UTS struct { <add> HostUTS bool `json:"host_uts"` <add>} <add> <ide> type NetworkInterface struct { <ide> Gateway string `json:"gateway"` <ide> IPAddress string `json:"ip"` <ide> type Command struct { <ide> Network *Network `json:"network"` <ide> Ipc *Ipc `json:"ipc"` <ide> Pid *Pid `json:"pid"` <add> UTS *UTS `json:"uts"` <ide> Resources *Resources `json:"resources"` <ide> Mounts []Mount `json:"mounts"` <ide> AllowedDevices []*configs.Device `json:"allowed_devices"` <ide><path>daemon/execdriver/native/create.go <ide> func (d *driver) createContainer(c *execdriver.Command) (*configs.Config, error) <ide> return nil, err <ide> } <ide> <add> if err := d.createUTS(container, c); err != nil { <add> return nil, err <add> } <add> <ide> if err := d.createNetwork(container, c); err != nil { <ide> return nil, err <ide> } <ide> func (d *driver) createPid(container *configs.Config, c *execdriver.Command) err <ide> return nil <ide> } <ide> <add>func (d *driver) createUTS(container *configs.Config, c *execdriver.Command) error { <add> if c.UTS.HostUTS { <add> container.Namespaces.Remove(configs.NEWUTS) <add> container.Hostname = "" <add> return nil <add> } <add> <add> return nil <add>} <add> <ide> func (d *driver) setPrivileged(container *configs.Config) (err error) { <ide> container.Capabilities = execdriver.GetAllCapabilities() <ide> container.Cgroups.AllowAllDevices = true <ide><path>docs/man/docker-create.1.md <ide> docker-create - Create a new container <ide> [**-P**|**--publish-all**[=*false*]] <ide> [**-p**|**--publish**[=*[]*]] <ide> [**--pid**[=*[]*]] <add>[**--uts**[=*[]*]] <ide> [**--privileged**[=*false*]] <ide> [**--read-only**[=*false*]] <ide> [**--restart**[=*RESTART*]] <ide> This value should always larger than **-m**, so you should alway use this with * <ide> **host**: use the host's PID namespace inside the container. <ide> Note: the host mode gives the container full access to local PID and is therefore considered insecure. <ide> <add>**--uts**=host <add> Set the UTS mode for the container <add> **host**: use the host's UTS namespace inside the container. <add> Note: the host mode gives the container access to changing the host's hostname and is therefore considered insecure. <add> <ide> **--privileged**=*true*|*false* <ide> Give extended privileges to this container. The default is *false*. <ide> <ide><path>docs/man/docker-run.1.md <ide> docker-run - Run a command in a new container <ide> [**-P**|**--publish-all**[=*false*]] <ide> [**-p**|**--publish**[=*[]*]] <ide> [**--pid**[=*[]*]] <add>[**--uts**[=*[]*]] <ide> [**--privileged**[=*false*]] <ide> [**--read-only**[=*false*]] <ide> [**--restart**[=*RESTART*]] <ide> ports and the exposed ports, use `docker port`. <ide> **host**: use the host's PID namespace inside the container. <ide> Note: the host mode gives the container full access to local PID and is therefore considered insecure. <ide> <add>**--uts**=host <add> Set the UTS mode for the container <add> **host**: use the host's UTS namespace inside the container. <add> Note: the host mode gives the container access to changing the host's hostname and is therefore considered insecure. <add> <ide> **--privileged**=*true*|*false* <ide> Give extended privileges to this container. The default is *false*. <ide> <ide><path>docs/sources/reference/commandline/cli.md <ide> Creates a new container. <ide> --oom-kill-disable=false Whether to disable OOM Killer for the container or not <ide> -P, --publish-all=false Publish all exposed ports to random ports <ide> -p, --publish=[] Publish a container's port(s) to the host <add> --pid="" PID namespace to use <add> --uts="" UTS namespace to use <ide> --privileged=false Give extended privileges to this container <ide> --read-only=false Mount the container's root filesystem as read only <ide> --restart="no" Restart policy (no, on-failure[:max-retry], always) <ide> To remove an image using its digest: <ide> -P, --publish-all=false Publish all exposed ports to random ports <ide> -p, --publish=[] Publish a container's port(s) to the host <ide> --pid="" PID namespace to use <add> --uts="" UTS namespace to use <ide> --privileged=false Give extended privileges to this container <ide> --read-only=false Mount the container's root filesystem as read only <ide> --restart="no" Restart policy (no, on-failure[:max-retry], always) <ide><path>docs/sources/reference/run.md <ide> called a digest. As long as the input used to generate the image is unchanged, <ide> the digest value is predictable and referenceable. <ide> <ide> ## PID settings (--pid) <add> <ide> --pid="" : Set the PID (Process) Namespace mode for the container, <ide> 'host': use the host's PID namespace inside the container <ide> <ide> within the container. <ide> This command would allow you to use `strace` inside the container on pid 1234 on <ide> the host. <ide> <add>## UTS settings (--uts) <add> <add> --uts="" : Set the UTS namespace mode for the container, <add> 'host': use the host's UTS namespace inside the container <add> <add>The UTS namespace is for setting the hostname and the domain that is visible <add>to running processes in that namespace. By default, all containers, including <add>those with `--net=host`, have their own UTS namespace. The `host` setting will <add>result in the container using the same UTS namespace as the host. <add> <add>You may wish to share the UTS namespace with the host if you would like the <add>hostname of the container to change as the hostname of the host changes. A <add>more advanced use case would be changing the host's hostname from a container. <add> <add>> **Note**: `--uts="host"` gives the container full access to change the <add>> hostname of the host and is therefore considered insecure. <add> <ide> ## IPC settings (--ipc) <ide> <ide> --ipc="" : Set the IPC mode for the container, <ide><path>integration-cli/docker_cli_run_test.go <ide> func (s *DockerSuite) TestRunModePidHost(c *check.C) { <ide> } <ide> } <ide> <add>func (s *DockerSuite) TestRunModeUTSHost(c *check.C) { <add> testRequires(c, NativeExecDriver, SameHostDaemon) <add> defer deleteAllContainers() <add> <add> hostUTS, err := os.Readlink("/proc/1/ns/uts") <add> if err != nil { <add> c.Fatal(err) <add> } <add> <add> cmd := exec.Command(dockerBinary, "run", "--uts=host", "busybox", "readlink", "/proc/self/ns/uts") <add> out2, _, err := runCommandWithOutput(cmd) <add> if err != nil { <add> c.Fatal(err, out2) <add> } <add> <add> out2 = strings.Trim(out2, "\n") <add> if hostUTS != out2 { <add> c.Fatalf("UTS different with --uts=host %s != %s\n", hostUTS, out2) <add> } <add> <add> cmd = exec.Command(dockerBinary, "run", "busybox", "readlink", "/proc/self/ns/uts") <add> out2, _, err = runCommandWithOutput(cmd) <add> if err != nil { <add> c.Fatal(err, out2) <add> } <add> <add> out2 = strings.Trim(out2, "\n") <add> if hostUTS == out2 { <add> c.Fatalf("UTS should be different without --uts=host %s == %s\n", hostUTS, out2) <add> } <add>} <add> <ide> func (s *DockerSuite) TestRunTLSverify(c *check.C) { <ide> cmd := exec.Command(dockerBinary, "ps") <ide> out, ec, err := runCommandWithOutput(cmd) <ide><path>runconfig/hostconfig.go <ide> func (n IpcMode) Container() string { <ide> return "" <ide> } <ide> <add>type UTSMode string <add> <add>// IsPrivate indicates whether container use it's private UTS namespace <add>func (n UTSMode) IsPrivate() bool { <add> return !(n.IsHost()) <add>} <add> <add>func (n UTSMode) IsHost() bool { <add> return n == "host" <add>} <add> <add>func (n UTSMode) Valid() bool { <add> parts := strings.Split(string(n), ":") <add> switch mode := parts[0]; mode { <add> case "", "host": <add> default: <add> return false <add> } <add> return true <add>} <add> <ide> type PidMode string <ide> <ide> // IsPrivate indicates whether container use it's private pid stack <ide> type HostConfig struct { <ide> NetworkMode NetworkMode <ide> IpcMode IpcMode <ide> PidMode PidMode <add> UTSMode UTSMode <ide> CapAdd []string <ide> CapDrop []string <ide> RestartPolicy RestartPolicy <ide><path>runconfig/parse.go <ide> func Parse(cmd *flag.FlagSet, args []string) (*Config, *HostConfig, *flag.FlagSe <ide> flNetwork = cmd.Bool([]string{"#n", "#-networking"}, true, "Enable networking for this container") <ide> flPrivileged = cmd.Bool([]string{"#privileged", "-privileged"}, false, "Give extended privileges to this container") <ide> flPidMode = cmd.String([]string{"-pid"}, "", "PID namespace to use") <add> flUTSMode = cmd.String([]string{"-uts"}, "", "UTS namespace to use") <ide> flPublishAll = cmd.Bool([]string{"P", "-publish-all"}, false, "Publish all exposed ports to random ports") <ide> flStdin = cmd.Bool([]string{"i", "-interactive"}, false, "Keep STDIN open even if not attached") <ide> flTty = cmd.Bool([]string{"t", "-tty"}, false, "Allocate a pseudo-TTY") <ide> func Parse(cmd *flag.FlagSet, args []string) (*Config, *HostConfig, *flag.FlagSe <ide> return nil, nil, cmd, fmt.Errorf("--pid: invalid PID mode") <ide> } <ide> <add> utsMode := UTSMode(*flUTSMode) <add> if !utsMode.Valid() { <add> return nil, nil, cmd, fmt.Errorf("--uts: invalid UTS mode") <add> } <add> <ide> restartPolicy, err := ParseRestartPolicy(*flRestartPolicy) <ide> if err != nil { <ide> return nil, nil, cmd, err <ide> func Parse(cmd *flag.FlagSet, args []string) (*Config, *HostConfig, *flag.FlagSe <ide> NetworkMode: netMode, <ide> IpcMode: ipcMode, <ide> PidMode: pidMode, <add> UTSMode: utsMode, <ide> Devices: deviceMappings, <ide> CapAdd: flCapAdd.GetAll(), <ide> CapDrop: flCapDrop.GetAll(),
10
Python
Python
fix usage of transaction.non_atomic_requests
a44cb679888e59e366ea8e932f80699800589d7f
<ide><path>tests/test_atomic_requests.py <ide> from django.db import connection, connections, transaction <ide> from django.http import Http404 <ide> from django.test import TestCase, TransactionTestCase, override_settings <del>from django.utils.decorators import method_decorator <ide> <ide> from rest_framework import status <ide> from rest_framework.exceptions import APIException <ide> def post(self, request, *args, **kwargs): <ide> <ide> <ide> class NonAtomicAPIExceptionView(APIView): <del> @method_decorator(transaction.non_atomic_requests) <add> @transaction.non_atomic_requests <ide> def dispatch(self, *args, **kwargs): <ide> return super(NonAtomicAPIExceptionView, self).dispatch(*args, **kwargs) <ide>
1
Mixed
Go
fix implicit devicemapper selection
0a376291b2213699f986a7bca1cc8c4f4ed00f8d
<ide><path>daemon/graphdriver/devmapper/deviceset.go <ide> var ( <ide> DefaultDataLoopbackSize int64 = 100 * 1024 * 1024 * 1024 <ide> DefaultMetaDataLoopbackSize int64 = 2 * 1024 * 1024 * 1024 <ide> DefaultBaseFsSize uint64 = 10 * 1024 * 1024 * 1024 <del> DefaultThinpBlockSize uint32 = 128 // 64K = 128 512b sectors <del> DefaultUdevSyncOverride bool = false <add> DefaultThinpBlockSize uint32 = 128 // 64K = 128 512b sectors <ide> MaxDeviceId int = 0xffffff // 24 bit, pool limit <ide> DeviceIdMapSz int = (MaxDeviceId + 1) / 8 <ide> // We retry device removal so many a times that even error messages <ide> type DeviceSet struct { <ide> deviceIdMap []byte <ide> <ide> // Options <del> dataLoopbackSize int64 <del> metaDataLoopbackSize int64 <del> baseFsSize uint64 <del> filesystem string <del> mountOptions string <del> mkfsArgs []string <del> dataDevice string // block or loop dev <del> dataLoopFile string // loopback file, if used <del> metadataDevice string // block or loop dev <del> metadataLoopFile string // loopback file, if used <del> doBlkDiscard bool <del> thinpBlockSize uint32 <del> thinPoolDevice string <del> Transaction `json:"-"` <del> overrideUdevSyncCheck bool <del> deferredRemove bool // use deferred removal <del> BaseDeviceUUID string //save UUID of base device <add> dataLoopbackSize int64 <add> metaDataLoopbackSize int64 <add> baseFsSize uint64 <add> filesystem string <add> mountOptions string <add> mkfsArgs []string <add> dataDevice string // block or loop dev <add> dataLoopFile string // loopback file, if used <add> metadataDevice string // block or loop dev <add> metadataLoopFile string // loopback file, if used <add> doBlkDiscard bool <add> thinpBlockSize uint32 <add> thinPoolDevice string <add> Transaction `json:"-"` <add> deferredRemove bool // use deferred removal <add> BaseDeviceUUID string //save UUID of base device <ide> } <ide> <ide> type DiskUsage struct { <ide> func (devices *DeviceSet) initDevmapper(doInit bool) error { <ide> <ide> // https://github.com/docker/docker/issues/4036 <ide> if supported := devicemapper.UdevSetSyncSupport(true); !supported { <del> logrus.Errorf("Udev sync is not supported. This will lead to unexpected behavior, data loss and errors. For more information, see https://docs.docker.com/reference/commandline/cli/#daemon-storage-driver-option") <del> if !devices.overrideUdevSyncCheck { <del> return graphdriver.ErrNotSupported <del> } <add> logrus.Warn("Udev sync is not supported. This will lead to unexpected behavior, data loss and errors. For more information, see https://docs.docker.com/reference/commandline/cli/#daemon-storage-driver-option") <ide> } <ide> <ide> if err := os.MkdirAll(devices.metadataDir(), 0700); err != nil && !os.IsExist(err) { <ide> func NewDeviceSet(root string, doInit bool, options []string) (*DeviceSet, error <ide> devicemapper.SetDevDir("/dev") <ide> <ide> devices := &DeviceSet{ <del> root: root, <del> MetaData: MetaData{Devices: make(map[string]*DevInfo)}, <del> dataLoopbackSize: DefaultDataLoopbackSize, <del> metaDataLoopbackSize: DefaultMetaDataLoopbackSize, <del> baseFsSize: DefaultBaseFsSize, <del> overrideUdevSyncCheck: DefaultUdevSyncOverride, <del> filesystem: "ext4", <del> doBlkDiscard: true, <del> thinpBlockSize: DefaultThinpBlockSize, <del> deviceIdMap: make([]byte, DeviceIdMapSz), <add> root: root, <add> MetaData: MetaData{Devices: make(map[string]*DevInfo)}, <add> dataLoopbackSize: DefaultDataLoopbackSize, <add> metaDataLoopbackSize: DefaultMetaDataLoopbackSize, <add> baseFsSize: DefaultBaseFsSize, <add> filesystem: "ext4", <add> doBlkDiscard: true, <add> thinpBlockSize: DefaultThinpBlockSize, <add> deviceIdMap: make([]byte, DeviceIdMapSz), <ide> } <ide> <ide> foundBlkDiscard := false <ide> func NewDeviceSet(root string, doInit bool, options []string) (*DeviceSet, error <ide> } <ide> // convert to 512b sectors <ide> devices.thinpBlockSize = uint32(size) >> 9 <del> case "dm.override_udev_sync_check": <del> devices.overrideUdevSyncCheck, err = strconv.ParseBool(val) <del> if err != nil { <del> return nil, err <del> } <del> <ide> case "dm.use_deferred_removal": <ide> EnableDeferredRemoval, err = strconv.ParseBool(val) <ide> if err != nil { <ide><path>daemon/graphdriver/devmapper/devmapper_test.go <ide> func init() { <ide> DefaultDataLoopbackSize = 300 * 1024 * 1024 <ide> DefaultMetaDataLoopbackSize = 200 * 1024 * 1024 <ide> DefaultBaseFsSize = 300 * 1024 * 1024 <del> DefaultUdevSyncOverride = true <ide> if err := graphtest.InitLoopbacks(); err != nil { <ide> panic(err) <ide> } <ide><path>daemon/graphdriver/driver.go <ide> import ( <ide> "strings" <ide> <ide> "github.com/Sirupsen/logrus" <add> "github.com/docker/docker/autogen/dockerversion" <ide> "github.com/docker/docker/pkg/archive" <ide> ) <ide> <ide> var ( <ide> // All registred drivers <ide> drivers map[string]InitFunc <ide> <del> ErrNotSupported = errors.New("driver not supported") <del> ErrPrerequisites = errors.New("prerequisites for driver not satisfied (wrong filesystem?)") <del> ErrIncompatibleFS = fmt.Errorf("backing file system is unsupported for this graph driver") <add> ErrNotSupported = errors.New("driver not supported") <add> ErrPrerequisites = errors.New("prerequisites for driver not satisfied (wrong filesystem?)") <add> ErrIncompatibleFS = fmt.Errorf("backing file system is unsupported for this graph driver") <add> ErrDeviceMapperWithStaticDocker = fmt.Errorf("devicemapper storage driver cannot reliably be used with a statically linked docker binary: please either pick a different storage driver, install a dynamically linked docker binary, or force this unreliable setup anyway by specifying --storage-driver=devicemapper") <ide> ) <ide> <ide> type InitFunc func(root string, options []string) (Driver, error) <ide> func New(root string, options []string) (driver Driver, err error) { <ide> } <ide> <ide> // Guess for prior driver <del> priorDrivers := scanPriorDrivers(root) <del> for _, name := range priority { <del> if name == "vfs" { <del> // don't use vfs even if there is state present. <del> continue <add> priorDriver, err := scanPriorDrivers(root) <add> if err != nil { <add> return nil, err <add> } <add> <add> if len(priorDriver) != 0 { <add> // Do not allow devicemapper when it's not explicit and the Docker binary was built statically. <add> if staticWithDeviceMapper(priorDriver) { <add> return nil, ErrDeviceMapperWithStaticDocker <ide> } <del> for _, prior := range priorDrivers { <del> // of the state found from prior drivers, check in order of our priority <del> // which we would prefer <del> if prior == name { <del> driver, err = GetDriver(name, root, options) <del> if err != nil { <del> // unlike below, we will return error here, because there is prior <del> // state, and now it is no longer supported/prereq/compatible, so <del> // something changed and needs attention. Otherwise the daemon's <del> // images would just "disappear". <del> logrus.Errorf("[graphdriver] prior storage driver %q failed: %s", name, err) <del> return nil, err <del> } <del> if err := checkPriorDriver(name, root); err != nil { <del> return nil, err <del> } <del> logrus.Infof("[graphdriver] using prior storage driver %q", name) <del> return driver, nil <del> } <add> <add> driver, err = GetDriver(priorDriver, root, options) <add> if err != nil { <add> // unlike below, we will return error here, because there is prior <add> // state, and now it is no longer supported/prereq/compatible, so <add> // something changed and needs attention. Otherwise the daemon's <add> // images would just "disappear". <add> logrus.Errorf("[graphdriver] prior storage driver %q failed: %s", priorDriver, err) <add> return nil, err <ide> } <add> logrus.Infof("[graphdriver] using prior storage driver %q", priorDriver) <add> return driver, nil <ide> } <ide> <ide> // Check for priority drivers first <ide> for _, name := range priority { <add> if staticWithDeviceMapper(name) { <add> continue <add> } <ide> driver, err = GetDriver(name, root, options) <ide> if err != nil { <ide> if err == ErrNotSupported || err == ErrPrerequisites || err == ErrIncompatibleFS { <ide> func New(root string, options []string) (driver Driver, err error) { <ide> } <ide> <ide> // Check all registered drivers if no priority driver is found <del> for _, initFunc := range drivers { <add> for name, initFunc := range drivers { <add> if staticWithDeviceMapper(name) { <add> continue <add> } <ide> if driver, err = initFunc(root, options); err != nil { <ide> if err == ErrNotSupported || err == ErrPrerequisites || err == ErrIncompatibleFS { <ide> continue <ide> func New(root string, options []string) (driver Driver, err error) { <ide> return nil, fmt.Errorf("No supported storage backend found") <ide> } <ide> <del>// scanPriorDrivers returns an un-ordered scan of directories of prior storage drivers <del>func scanPriorDrivers(root string) []string { <del> priorDrivers := []string{} <add>// scanPriorDrivers returns a previosly used driver. <add>// it returns an error when there are several drivers scanned. <add>func scanPriorDrivers(root string) (string, error) { <add> var priorDrivers []string <ide> for driver := range drivers { <ide> p := filepath.Join(root, driver) <del> if _, err := os.Stat(p); err == nil { <add> if _, err := os.Stat(p); err == nil && driver != "vfs" { <ide> priorDrivers = append(priorDrivers, driver) <ide> } <ide> } <del> return priorDrivers <del>} <ide> <del>func checkPriorDriver(name, root string) error { <del> priorDrivers := []string{} <del> for _, prior := range scanPriorDrivers(root) { <del> if prior != name && prior != "vfs" { <del> if _, err := os.Stat(filepath.Join(root, prior)); err == nil { <del> priorDrivers = append(priorDrivers, prior) <del> } <del> } <add> if len(priorDrivers) > 1 { <add> return "", multipleDriversError(root, priorDrivers) <ide> } <ide> <del> if len(priorDrivers) > 0 { <del> <del> return errors.New(fmt.Sprintf("%q contains other graphdrivers: %s; Please cleanup or explicitly choose storage driver (-s <DRIVER>)", root, strings.Join(priorDrivers, ","))) <add> if len(priorDrivers) == 0 { <add> return "", nil <ide> } <del> return nil <add> return priorDrivers[0], nil <add>} <add> <add>func multipleDriversError(root string, drivers []string) error { <add> return fmt.Errorf("%q contains several graphdrivers: %s; Please cleanup or explicitly choose storage driver (--storage-driver <DRIVER>)", root, strings.Join(drivers, ", ")) <add>} <add> <add>func staticWithDeviceMapper(name string) bool { <add> return name == "devicemapper" && dockerversion.IAMSTATIC == "true" <ide> } <ide><path>docs/reference/commandline/daemon.md <ide> options for `zfs` start with `zfs`. <ide> <ide> $ docker -d --storage-opt dm.blkdiscard=false <ide> <del> * `dm.override_udev_sync_check` <del> <del> Overrides the `udev` synchronization checks between `devicemapper` and `udev`. <del> `udev` is the device manager for the Linux kernel. <del> <del> To view the `udev` sync support of a Docker daemon that is using the <del> `devicemapper` driver, run: <del> <del> $ docker info <del> [...] <del> Udev Sync Supported: true <del> [...] <del> <del> When `udev` sync support is `true`, then `devicemapper` and udev can <del> coordinate the activation and deactivation of devices for containers. <del> <del> When `udev` sync support is `false`, a race condition occurs between <del> the`devicemapper` and `udev` during create and cleanup. The race condition <del> results in errors and failures. (For information on these failures, see <del> [docker#4036](https://github.com/docker/docker/issues/4036)) <del> <del> To allow the `docker` daemon to start, regardless of `udev` sync not being <del> supported, set `dm.override_udev_sync_check` to true: <del> <del> $ docker -d --storage-opt dm.override_udev_sync_check=true <del> <del> When this value is `true`, the `devicemapper` continues and simply warns <del> you the errors are happening. <del> <del> > **Note:** <del> > The ideal is to pursue a `docker` daemon and environment that does <del> > support synchronizing with `udev`. For further discussion on this <del> > topic, see [docker#4036](https://github.com/docker/docker/issues/4036). <del> > Otherwise, set this flag for migrating existing Docker daemons to <del> > a daemon with a supported environment. <del> <ide> <ide> ## Docker execdriver option <ide> <ide><path>man/docker.1.md <ide> removed. <ide> <ide> Example use: `docker -d --storage-opt dm.blkdiscard=false` <ide> <del>#### dm.override_udev_sync_check <del> <del>By default, the devicemapper backend attempts to synchronize with the <del>`udev` device manager for the Linux kernel. This option allows <del>disabling that synchronization, to continue even though the <del>configuration may be buggy. <del> <del>To view the `udev` sync support of a Docker daemon that is using the <del>`devicemapper` driver, run: <del> <del> $ docker info <del> [...] <del> Udev Sync Supported: true <del> [...] <del> <del>When `udev` sync support is `true`, then `devicemapper` and `udev` can <del>coordinate the activation and deactivation of devices for containers. <del> <del>When `udev` sync support is `false`, a race condition occurs between <del>the`devicemapper` and `udev` during create and cleanup. The race <del>condition results in errors and failures. (For information on these <del>failures, see <del>[docker#4036](https://github.com/docker/docker/issues/4036)) <del> <del>To allow the `docker` daemon to start, regardless of whether `udev` sync is <del>`false`, set `dm.override_udev_sync_check` to true: <del> <del> $ docker -d --storage-opt dm.override_udev_sync_check=true <del> <del>When this value is `true`, the driver continues and simply warns you <del>the errors are happening. <del> <del>**Note**: The ideal is to pursue a `docker` daemon and environment <del>that does support synchronizing with `udev`. For further discussion on <del>this topic, see <del>[docker#4036](https://github.com/docker/docker/issues/4036). <del>Otherwise, set this flag for migrating existing Docker daemons to a <del>daemon with a supported environment. <del> <ide> # EXEC DRIVER OPTIONS <ide> <ide> Use the **--exec-opt** flags to specify options to the exec-driver. The only
5
Javascript
Javascript
replace assert.throws w/ common.expectserror
094bfaf769f5b6bc8ca6fbcc289cdf5e0f07073f
<ide><path>test/async-hooks/test-embedder.api.async-resource.js <ide> common.expectsError( <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> type: TypeError, <ide> }); <del>assert.throws(() => { <add>common.expectsError(() => { <ide> new AsyncResource('invalid_trigger_id', { triggerAsyncId: null }); <del>}, common.expectsError({ <add>}, { <ide> code: 'ERR_INVALID_ASYNC_ID', <ide> type: RangeError, <del>})); <add>}); <ide> <ide> assert.strictEqual( <ide> new AsyncResource('default_trigger_id').triggerAsyncId(), <ide><path>test/parallel/test-assert-fail.js <ide> 'use strict'; <ide> <add>/* eslint-disable prefer-common-expectserror */ <add> <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide> <ide><path>test/parallel/test-assert.js <ide> // USE OR OTHER DEALINGS IN THE SOFTWARE. <ide> <ide> 'use strict'; <add> <add>/* eslint-disable prefer-common-expectserror */ <add> <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide> const a = assert; <ide><path>test/parallel/test-buffer-alloc.js <ide> assert.strictEqual(SlowBuffer.prototype.offset, undefined); <ide> } <ide> <ide> // ParseArrayIndex() should reject values that don't fit in a 32 bits size_t. <del>assert.throws(() => { <add>common.expectsError(() => { <ide> const a = Buffer.alloc(1); <ide> const b = Buffer.alloc(1); <ide> a.copy(b, 0, 0x100000000, 0x100000001); <del>}, common.expectsError( <del> { code: undefined, type: RangeError, message: 'Index out of range' })); <add>}, { code: undefined, type: RangeError, message: 'Index out of range' }); <ide> <ide> // Unpooled buffer (replaces SlowBuffer) <ide> { <ide><path>test/parallel/test-buffer-fill.js <ide> common.expectsError(() => { <ide> <ide> // Testing process.binding. Make sure "end" is properly checked for -1 wrap <ide> // around. <del>assert.throws(() => { <add>common.expectsError(() => { <ide> process.binding('buffer').fill(Buffer.alloc(1), 1, 1, -2, 1); <del>}, common.expectsError( <del> { code: undefined, type: RangeError, message: 'Index out of range' })); <add>}, { code: undefined, type: RangeError, message: 'Index out of range' }); <ide> <ide> // Test that bypassing 'length' won't cause an abort. <del>assert.throws(() => { <add>common.expectsError(() => { <ide> const buf = new Buffer('w00t'); <ide> Object.defineProperty(buf, 'length', { <ide> value: 1337, <ide> enumerable: true <ide> }); <ide> buf.fill(''); <del>}, common.expectsError( <del> { code: undefined, type: RangeError, message: 'Index out of range' })); <add>}, { code: undefined, type: RangeError, message: 'Index out of range' }); <ide> <ide> assert.deepStrictEqual( <ide> Buffer.allocUnsafeSlow(16).fill('ab', 'utf16le'), <ide><path>test/parallel/test-console-instance.js <ide> common.expectsError( <ide> ); <ide> <ide> // Console constructor should throw if stderr exists but is not writable <del>assert.throws( <add>common.expectsError( <ide> () => { <ide> out.write = () => {}; <ide> err.write = undefined; <ide> new Console(out, err); <ide> }, <del> common.expectsError({ <add> { <ide> code: 'ERR_CONSOLE_WRITABLE_STREAM', <ide> type: TypeError, <ide> message: /stderr/ <del> }) <add> } <ide> ); <ide> <ide> out.write = err.write = (d) => {}; <ide><path>test/parallel/test-dns.js <ide> assert.doesNotThrow(() => { <ide> }, common.mustCall()); <ide> }); <ide> <del>assert.throws(() => dns.lookupService('0.0.0.0'), common.expectsError({ <add>common.expectsError(() => dns.lookupService('0.0.0.0'), { <ide> code: 'ERR_MISSING_ARGS', <ide> type: TypeError, <ide> message: 'The "host", "port", and "callback" arguments must be specified' <del>})); <add>}); <ide> <ide> const invalidHost = 'fasdfdsaf'; <del>assert.throws(() => { <add>common.expectsError(() => { <ide> dns.lookupService(invalidHost, 0, common.mustNotCall()); <del>}, common.expectsError({ <add>}, { <ide> code: 'ERR_INVALID_OPT_VALUE', <ide> type: TypeError, <ide> message: `The value "${invalidHost}" is invalid for option "host"` <del>})); <add>}); <ide> <ide> const portErr = (port) => { <ide> common.expectsError( <ide> portErr(undefined); <ide> portErr(65538); <ide> portErr('test'); <ide> <del>assert.throws(() => { <add>common.expectsError(() => { <ide> dns.lookupService('0.0.0.0', 80, null); <del>}, common.expectsError({ <add>}, { <ide> code: 'ERR_INVALID_CALLBACK', <ide> type: TypeError <del>})); <add>}); <ide><path>test/parallel/test-http-outgoing-proto.js <ide> assert.strictEqual( <ide> typeof ServerResponse.prototype._implicitHeader, 'function'); <ide> <ide> // validateHeader <del>assert.throws(() => { <add>common.expectsError(() => { <ide> const outgoingMessage = new OutgoingMessage(); <ide> outgoingMessage.setHeader(); <del>}, common.expectsError({ <add>}, { <ide> code: 'ERR_INVALID_HTTP_TOKEN', <ide> type: TypeError, <ide> message: 'Header name must be a valid HTTP token ["undefined"]' <del>})); <add>}); <ide> <del>assert.throws(() => { <add>common.expectsError(() => { <ide> const outgoingMessage = new OutgoingMessage(); <ide> outgoingMessage.setHeader('test'); <del>}, common.expectsError({ <add>}, { <ide> code: 'ERR_HTTP_INVALID_HEADER_VALUE', <ide> type: TypeError, <ide> message: 'Invalid value "undefined" for header "test"' <del>})); <add>}); <ide> <del>assert.throws(() => { <add>common.expectsError(() => { <ide> const outgoingMessage = new OutgoingMessage(); <ide> outgoingMessage.setHeader(404); <del>}, common.expectsError({ <add>}, { <ide> code: 'ERR_INVALID_HTTP_TOKEN', <ide> type: TypeError, <ide> message: 'Header name must be a valid HTTP token ["404"]' <del>})); <add>}); <ide> <del>assert.throws(() => { <add>common.expectsError(() => { <ide> const outgoingMessage = new OutgoingMessage(); <ide> outgoingMessage.setHeader.call({ _header: 'test' }, 'test', 'value'); <del>}, common.expectsError({ <add>}, { <ide> code: 'ERR_HTTP_HEADERS_SENT', <ide> type: Error, <ide> message: 'Cannot set headers after they are sent to the client' <del>})); <add>}); <ide> <del>assert.throws(() => { <add>common.expectsError(() => { <ide> const outgoingMessage = new OutgoingMessage(); <ide> outgoingMessage.setHeader('200', 'あ'); <del>}, common.expectsError({ <add>}, { <ide> code: 'ERR_INVALID_CHAR', <ide> type: TypeError, <ide> message: 'Invalid character in header content ["200"]' <del>})); <add>}); <ide> <ide> // write <del>assert.throws(() => { <add>common.expectsError(() => { <ide> const outgoingMessage = new OutgoingMessage(); <ide> outgoingMessage.write(); <del>}, common.expectsError({ <add>}, { <ide> code: 'ERR_METHOD_NOT_IMPLEMENTED', <ide> type: Error, <ide> message: 'The _implicitHeader() method is not implemented' <del>})); <add>}); <ide> <ide> assert(OutgoingMessage.prototype.write.call({ _header: 'test' })); <ide> <del>assert.throws(() => { <add>common.expectsError(() => { <ide> const outgoingMessage = new OutgoingMessage(); <ide> outgoingMessage.write.call({ _header: 'test', _hasBody: 'test' }); <del>}, common.expectsError({ <add>}, { <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> type: TypeError, <ide> message: 'The first argument must be one of type string or Buffer' <del>})); <add>}); <ide> <del>assert.throws(() => { <add>common.expectsError(() => { <ide> const outgoingMessage = new OutgoingMessage(); <ide> outgoingMessage.write.call({ _header: 'test', _hasBody: 'test' }, 1); <del>}, common.expectsError({ <add>}, { <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> type: TypeError, <ide> message: 'The first argument must be one of type string or Buffer' <del>})); <add>}); <ide> <ide> // addTrailers() <ide> // The `Error` comes from the JavaScript engine so confirm that it is a <ide> assert.throws(() => { <ide> outgoingMessage.addTrailers(); <ide> }, TypeError); <ide> <del>assert.throws(() => { <add>common.expectsError(() => { <ide> const outgoingMessage = new OutgoingMessage(); <ide> outgoingMessage.addTrailers({ 'あ': 'value' }); <del>}, common.expectsError({ <add>}, { <ide> code: 'ERR_INVALID_HTTP_TOKEN', <ide> type: TypeError, <ide> message: 'Trailer name must be a valid HTTP token ["あ"]' <del>})); <add>}); <ide> <del>assert.throws(() => { <add>common.expectsError(() => { <ide> const outgoingMessage = new OutgoingMessage(); <ide> outgoingMessage.addTrailers({ 404: 'あ' }); <del>}, common.expectsError({ <add>}, { <ide> code: 'ERR_INVALID_CHAR', <ide> type: TypeError, <ide> message: 'Invalid character in trailer content ["404"]' <del>})); <add>}); <ide><path>test/parallel/test-http2-client-request-options-errors.js <ide> const common = require('../common'); <ide> if (!common.hasCrypto) <ide> common.skip('missing crypto'); <del>const assert = require('assert'); <ide> const http2 = require('http2'); <ide> <ide> // Check if correct errors are emitted when wrong type of data is passed <ide> server.listen(0, common.mustCall(() => { <ide> return; <ide> } <ide> <del> assert.throws( <add> common.expectsError( <ide> () => client.request({ <ide> ':method': 'CONNECT', <ide> ':authority': `localhost:${port}` <ide> }, { <ide> [option]: types[type] <ide> }), <del> common.expectsError({ <add> { <ide> type: TypeError, <ide> code: 'ERR_INVALID_OPT_VALUE', <ide> message: `The value "${String(types[type])}" is invalid ` + <ide> `for option "${option}"` <del> }) <add> } <ide> ); <ide> }); <ide> }); <ide><path>test/parallel/test-http2-connect-method.js <ide> server.listen(0, common.mustCall(() => { <ide> const client = http2.connect(`http://localhost:${proxy.address().port}`); <ide> <ide> // confirm that :authority is required and :scheme & :path are forbidden <del> assert.throws( <add> common.expectsError( <ide> () => client.request({ <ide> [HTTP2_HEADER_METHOD]: 'CONNECT' <ide> }), <del> common.expectsError({ <add> { <ide> code: 'ERR_HTTP2_CONNECT_AUTHORITY', <ide> message: ':authority header is required for CONNECT requests' <del> }) <add> } <ide> ); <del> assert.throws( <add> common.expectsError( <ide> () => client.request({ <ide> [HTTP2_HEADER_METHOD]: 'CONNECT', <ide> [HTTP2_HEADER_AUTHORITY]: `localhost:${port}`, <ide> [HTTP2_HEADER_SCHEME]: 'http' <ide> }), <del> common.expectsError({ <add> { <ide> code: 'ERR_HTTP2_CONNECT_SCHEME', <ide> message: 'The :scheme header is forbidden for CONNECT requests' <del> }) <add> } <ide> ); <del> assert.throws( <add> common.expectsError( <ide> () => client.request({ <ide> [HTTP2_HEADER_METHOD]: 'CONNECT', <ide> [HTTP2_HEADER_AUTHORITY]: `localhost:${port}`, <ide> [HTTP2_HEADER_PATH]: '/' <ide> }), <del> common.expectsError({ <add> { <ide> code: 'ERR_HTTP2_CONNECT_PATH', <ide> message: 'The :path header is forbidden for CONNECT requests' <del> }) <add> } <ide> ); <ide> <ide> // valid CONNECT request <ide><path>test/parallel/test-http2-respond-file-204.js <ide> if (!common.hasCrypto) <ide> common.skip('missing crypto'); <ide> const fixtures = require('../common/fixtures'); <ide> const http2 = require('http2'); <del>const assert = require('assert'); <ide> <ide> const { <ide> HTTP2_HEADER_CONTENT_TYPE, <ide> const fname = fixtures.path('elipses.txt'); <ide> <ide> const server = http2.createServer(); <ide> server.on('stream', (stream) => { <del> assert.throws(() => { <add> common.expectsError(() => { <ide> stream.respondWithFile(fname, { <ide> [HTTP2_HEADER_STATUS]: 204, <ide> [HTTP2_HEADER_CONTENT_TYPE]: 'text/plain' <ide> }); <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_HTTP2_PAYLOAD_FORBIDDEN', <ide> type: Error, <ide> message: 'Responses with 204 status must not have a payload' <del> })); <add> }); <ide> stream.respond({}); <ide> stream.end(); <ide> }); <ide><path>test/parallel/test-http2-server-push-disabled.js <ide> server.on('stream', common.mustCall((stream) => { <ide> // and pushStream() must throw. <ide> assert.strictEqual(stream.pushAllowed, false); <ide> <del> assert.throws(() => { <add> common.expectsError(() => { <ide> stream.pushStream({ <ide> ':scheme': 'http', <ide> ':path': '/foobar', <ide> ':authority': `localhost:${server.address().port}`, <ide> }, common.mustNotCall()); <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_HTTP2_PUSH_DISABLED', <ide> type: Error <del> })); <add> }); <ide> <ide> stream.respond({ ':status': 200 }); <ide> stream.end('test'); <ide><path>test/parallel/test-http2-server-rst-before-respond.js <ide> server.on('stream', common.mustCall(onStream)); <ide> function onStream(stream, headers, flags) { <ide> stream.rstStream(); <ide> <del> assert.throws(() => { <add> common.expectsError(() => { <ide> stream.additionalHeaders({ <ide> ':status': 123, <ide> abc: 123 <ide> }); <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_HTTP2_INVALID_STREAM', <ide> message: /^The stream has been destroyed$/ <del> })); <add> }); <ide> } <ide> <ide> server.listen(0); <ide><path>test/parallel/test-https-options-boolean-check.js <ide> const invalidCertRE = /^The "cert" argument must be one of type string, Buffer, <ide> [[keyStr, keyStr2], true, invalidCertRE], <ide> [true, [certBuff, certBuff2], invalidKeyRE] <ide> ].map((params) => { <del> assert.throws(() => { <add> common.expectsError(() => { <ide> https.createServer({ <ide> key: params[0], <ide> cert: params[1] <ide> }); <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> type: TypeError, <ide> message: params[2] <del> })); <add> }); <ide> }); <ide> <ide> // Checks to ensure https.createServer works with the CA parameter <ide> const invalidCertRE = /^The "cert" argument must be one of type string, Buffer, <ide> [keyBuff, certBuff, true], <ide> [keyBuff, certBuff, [caCert, true]] <ide> ].map((params) => { <del> assert.throws(() => { <add> common.expectsError(() => { <ide> https.createServer({ <ide> key: params[0], <ide> cert: params[1], <ide> ca: params[2] <ide> }); <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> type: TypeError, <ide> message: /^The "ca" argument must be one of type string, Buffer, TypedArray, or DataView$/ <del> })); <add> }); <ide> }); <ide><path>test/parallel/test-internal-errors.js <ide> common.expectsError( <ide> <ide> // Tests for common.expectsError <ide> assert.doesNotThrow(() => { <del> assert.throws(() => { <add> common.expectsError(() => { <ide> throw new errors.TypeError('TEST_ERROR_1', 'a'); <del> }, common.expectsError({ code: 'TEST_ERROR_1' })); <add> }, { code: 'TEST_ERROR_1' }); <ide> }); <ide> <ide> assert.doesNotThrow(() => { <del> assert.throws(() => { <add> common.expectsError(() => { <ide> throw new errors.TypeError('TEST_ERROR_1', 'a'); <del> }, common.expectsError({ code: 'TEST_ERROR_1', <del> type: TypeError, <del> message: /^Error for testing/ })); <add> }, { code: 'TEST_ERROR_1', <add> type: TypeError, <add> message: /^Error for testing/ }); <ide> }); <ide> <ide> assert.doesNotThrow(() => { <del> assert.throws(() => { <add> common.expectsError(() => { <ide> throw new errors.TypeError('TEST_ERROR_1', 'a'); <del> }, common.expectsError({ code: 'TEST_ERROR_1', type: TypeError })); <add> }, { code: 'TEST_ERROR_1', type: TypeError }); <ide> }); <ide> <ide> assert.doesNotThrow(() => { <del> assert.throws(() => { <add> common.expectsError(() => { <ide> throw new errors.TypeError('TEST_ERROR_1', 'a'); <del> }, common.expectsError({ code: 'TEST_ERROR_1', type: Error })); <add> }, { code: 'TEST_ERROR_1', type: Error }); <ide> }); <ide> <ide> common.expectsError(() => { <ide><path>test/parallel/test-performance.js <ide> assert.strictEqual(typeof performance.timeOrigin, 'number'); <ide> }); <ide> <ide> [undefined, null, 'foo', 1].forEach((i) => { <del> assert.throws(() => performance.measure('test', 'A', i), <del> common.expectsError({ <del> code: 'ERR_INVALID_PERFORMANCE_MARK', <del> type: Error, <del> message: `The "${i}" performance mark has not been set` <del> })); <add> common.expectsError( <add> () => performance.measure('test', 'A', i), <add> { <add> code: 'ERR_INVALID_PERFORMANCE_MARK', <add> type: Error, <add> message: `The "${i}" performance mark has not been set` <add> }); <ide> }); <ide> <ide> performance.clearMeasures(); <ide><path>test/parallel/test-performanceobserver.js <ide> assert.strictEqual(counts[NODE_PERFORMANCE_ENTRY_TYPE_FUNCTION], 0); <ide> <ide> { <ide> [1, null, undefined, {}, [], Infinity].forEach((i) => { <del> assert.throws(() => new PerformanceObserver(i), <del> common.expectsError({ <del> code: 'ERR_INVALID_CALLBACK', <del> type: TypeError, <del> message: 'Callback must be a function' <del> })); <add> common.expectsError(() => new PerformanceObserver(i), <add> { <add> code: 'ERR_INVALID_CALLBACK', <add> type: TypeError, <add> message: 'Callback must be a function' <add> }); <ide> }); <ide> const observer = new PerformanceObserver(common.mustNotCall()); <ide> <ide> [1, null, undefined].forEach((i) => { <ide> //observer.observe(i); <del> assert.throws(() => observer.observe(i), <del> common.expectsError({ <del> code: 'ERR_INVALID_ARG_TYPE', <del> type: TypeError, <del> message: 'The "options" argument must be of type Object' <del> })); <add> common.expectsError( <add> () => observer.observe(i), <add> { <add> code: 'ERR_INVALID_ARG_TYPE', <add> type: TypeError, <add> message: 'The "options" argument must be of type Object' <add> }); <ide> }); <ide> <ide> [1, undefined, null, {}, Infinity].forEach((i) => { <del> assert.throws(() => observer.observe({ entryTypes: i }), <del> common.expectsError({ <del> code: 'ERR_INVALID_OPT_VALUE', <del> type: TypeError, <del> message: 'The value "[object Object]" is invalid for ' + <del> 'option "entryTypes"' <del> })); <add> common.expectsError(() => observer.observe({ entryTypes: i }), <add> { <add> code: 'ERR_INVALID_OPT_VALUE', <add> type: TypeError, <add> message: 'The value "[object Object]" is invalid ' + <add> 'for option "entryTypes"' <add> }); <ide> }); <ide> } <ide> <ide><path>test/parallel/test-readline-interface.js <ide> function isWarned(emitter) { <ide> // constructor throws if completer is not a function or undefined <ide> { <ide> const fi = new FakeInput(); <del> assert.throws(function() { <add> common.expectsError(function() { <ide> readline.createInterface({ <ide> input: fi, <ide> completer: 'string is not valid' <ide> }); <del> }, common.expectsError({ <add> }, { <ide> type: TypeError, <ide> code: 'ERR_INVALID_OPT_VALUE' <del> })); <add> }); <ide> } <ide> <ide> // constructor throws if historySize is not a positive number <ide> { <ide> const fi = new FakeInput(); <del> assert.throws(function() { <add> common.expectsError(function() { <ide> readline.createInterface({ <ide> input: fi, historySize: 'not a number' <ide> }); <del> }, common.expectsError({ <add> }, { <ide> type: RangeError, <ide> code: 'ERR_INVALID_OPT_VALUE' <del> })); <add> }); <ide> <del> assert.throws(function() { <add> common.expectsError(function() { <ide> readline.createInterface({ <ide> input: fi, historySize: -1 <ide> }); <del> }, common.expectsError({ <add> }, { <ide> type: RangeError, <ide> code: 'ERR_INVALID_OPT_VALUE' <del> })); <add> }); <ide> <del> assert.throws(function() { <add> common.expectsError(function() { <ide> readline.createInterface({ <ide> input: fi, historySize: NaN <ide> }); <del> }, common.expectsError({ <add> }, { <ide> type: RangeError, <ide> code: 'ERR_INVALID_OPT_VALUE' <del> })); <add> }); <ide> } <ide> <ide> // duplicate lines are removed from history when <ide><path>test/sequential/test-tls-lookup.js <ide> const tls = require('tls'); <ide> lookup: input <ide> }; <ide> <del> assert.throws(function() { <add> common.expectsError(function() { <ide> tls.connect(opts); <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> type: TypeError <del> })); <add> }); <ide> }); <ide> <ide> connectDoesNotThrow(common.mustCall(() => {}));
19
Javascript
Javascript
fix typo in error message
fa44659c66c5a9a692b5d675eda8724308174317
<ide><path>test/common.js <ide> process.on('exit', function() { <ide> <ide> if (!found) { <ide> console.error('Unknown global: %s', x); <del> assert.ok(false, 'Unknown global founded'); <add> assert.ok(false, 'Unknown global found'); <ide> } <ide> } <ide> });
1
PHP
PHP
fix mysql deletes with join and alias
d2b6c8bc5cc443e41bcfe344973e105b728bebb5
<ide><path>src/Illuminate/Database/Query/Grammars/MySqlGrammar.php <ide> protected function compileDeleteWithJoins($query, $table, $where) <ide> { <ide> $joins = ' '.$this->compileJoins($query, $query->joins); <ide> <del> return trim("delete {$table} from {$table}{$joins} {$where}"); <add> $alias = $table; <add> <add> if (strpos(strtolower($table), ' as ') !== false) { <add> $alias = explode(' as ', $table)[1]; <add> } <add> <add> return trim("delete {$alias} from {$table}{$joins} {$where}"); <ide> } <ide> <ide> /** <ide><path>tests/Database/DatabaseQueryBuilderTest.php <ide> public function testDeleteWithJoinMethod() <ide> $result = $builder->from('users')->join('contacts', 'users.id', '=', 'contacts.id')->where('email', '=', 'foo')->orderBy('id')->limit(1)->delete(); <ide> $this->assertEquals(1, $result); <ide> <add> $builder = $this->getMySqlBuilder(); <add> $builder->getConnection()->shouldReceive('delete')->once()->with('delete `a` from `users` as `a` inner join `users` as `b` on `a`.`id` = `b`.`user_id` where `email` = ?', ['foo'])->andReturn(1); <add> $result = $builder->from('users AS a')->join('users AS b', 'a.id', '=', 'b.user_id')->where('email', '=', 'foo')->orderBy('id')->limit(1)->delete(); <add> $this->assertEquals(1, $result); <add> <ide> $builder = $this->getMySqlBuilder(); <ide> $builder->getConnection()->shouldReceive('delete')->once()->with('delete `users` from `users` inner join `contacts` on `users`.`id` = `contacts`.`id` where `users`.`id` = ?', [1])->andReturn(1); <ide> $result = $builder->from('users')->join('contacts', 'users.id', '=', 'contacts.id')->orderBy('id')->take(1)->delete(1);
2
Javascript
Javascript
remove comments from migration
688bfd6137b11bb865e8fb7d3ff2d9a4f9586e8f
<ide><path>loopbackMigration.js <ide> function createConnection(URI) { <ide> } <ide> <ide> function createQuery(db, collection, options, batchSize) { <del> return Rx.Observable.create(function (observer) { <add> return Rx.Observable.create(function(observer) { <ide> var cursor = db.collection(collection).find({}, options); <ide> cursor.batchSize(batchSize || 20); <ide> // Cursor.each will yield all doc from a batch in the same tick, <ide> // or schedule getting next batch on nextTick <ide> debug('opening cursor for %s', collection); <del> cursor.each(function (err, doc) { <add> cursor.each(function(err, doc) { <ide> if (err) { <ide> return observer.onError(err); <ide> } <ide> function createQuery(db, collection, options, batchSize) { <ide> observer.onNext(doc); <ide> }); <ide> <del> return Rx.Disposable.create(function () { <add> return Rx.Disposable.create(function() { <ide> debug('closing cursor for %s', collection); <ide> cursor.close(); <ide> }); <ide> var storyCount = dbObservable <ide> }) <ide> .count(); <ide> <del>var commentCount = dbObservable <del> .flatMap(function(db) { <del> return createQuery(db, 'comments', {}); <del> }) <del> .bufferWithCount(20) <del> .withLatestFrom(dbObservable, function(comments, db) { <del> return { <del> comments: comments, <del> db: db <del> }; <del> }) <del> .flatMap(function(dats) { <del> return insertMany(dats.db, 'comment', dats.comments, { w: 1 }); <del> }) <del> .count(); <del> <ide> Rx.Observable.combineLatest( <ide> userIdentityCount, <ide> userSavesCount, <ide> storyCount, <del> commentCount, <del> function(userIdentCount, userCount, storyCount, commentCount) { <add> function(userIdentCount, userCount, storyCount) { <ide> return { <ide> userIdentCount: userIdentCount * 20, <ide> userCount: userCount * 20, <del> storyCount: storyCount * 20, <del> commentCount: commentCount * 20 <add> storyCount: storyCount * 20 <ide> }; <ide> }) <ide> .subscribe(
1
Javascript
Javascript
add negation to test name
6f6cdf6eebd552f162fd564afd191b64c8ef68c8
<ide><path>test/compareLocations.unittest.js <ide> describe("compareLocations", () => { <ide> expect(compareLocations("alpha", createLocation())).toBe(-1); <ide> }); <ide> <del> it("returns 0 when both the first parameter and the second parameter is an object", () => { <add> it("returns 0 when both the first parameter and the second parameter are not objects", () => { <ide> expect(compareLocations(123, 456)).toBe(0); <ide> }); <ide> });
1
Javascript
Javascript
fix typo in .eslintrc.js
2f1a23e5be9e1774a579d4201da24adaf3df2f1e
<ide><path>.eslintrc.js <ide> module.exports = { <ide> { <ide> object: 'assert', <ide> property: 'equal', <del> message: 'Use assert.astrictEqual() rather than assert.equal().', <add> message: 'Use assert.strictEqual() rather than assert.equal().', <ide> }, <ide> { <ide> object: 'assert',
1
Go
Go
add devmapper struct doc
d233894c25e2b1b7124d69bddece94c88fb44452
<ide><path>graphdriver/devmapper/devmapper_doc.go <add>package devmapper <add> <add>// Definition of struct dm_task and sub structures (from lvm2) <add>// <add>// struct dm_ioctl { <add>// /* <add>// * The version number is made up of three parts: <add>// * major - no backward or forward compatibility, <add>// * minor - only backwards compatible, <add>// * patch - both backwards and forwards compatible. <add>// * <add>// * All clients of the ioctl interface should fill in the <add>// * version number of the interface that they were <add>// * compiled with. <add>// * <add>// * All recognised ioctl commands (ie. those that don't <add>// * return -ENOTTY) fill out this field, even if the <add>// * command failed. <add>// */ <add>// uint32_t version[3]; /* in/out */ <add>// uint32_t data_size; /* total size of data passed in <add>// * including this struct */ <add> <add>// uint32_t data_start; /* offset to start of data <add>// * relative to start of this struct */ <add> <add>// uint32_t target_count; /* in/out */ <add>// int32_t open_count; /* out */ <add>// uint32_t flags; /* in/out */ <add> <add>// /* <add>// * event_nr holds either the event number (input and output) or the <add>// * udev cookie value (input only). <add>// * The DM_DEV_WAIT ioctl takes an event number as input. <add>// * The DM_SUSPEND, DM_DEV_REMOVE and DM_DEV_RENAME ioctls <add>// * use the field as a cookie to return in the DM_COOKIE <add>// * variable with the uevents they issue. <add>// * For output, the ioctls return the event number, not the cookie. <add>// */ <add>// uint32_t event_nr; /* in/out */ <add>// uint32_t padding; <add> <add>// uint64_t dev; /* in/out */ <add> <add>// char name[DM_NAME_LEN]; /* device name */ <add>// char uuid[DM_UUID_LEN]; /* unique identifier for <add>// * the block device */ <add>// char data[7]; /* padding or data */ <add>// }; <add> <add>// struct target { <add>// uint64_t start; <add>// uint64_t length; <add>// char *type; <add>// char *params; <add> <add>// struct target *next; <add>// }; <add> <add>// typedef enum { <add>// DM_ADD_NODE_ON_RESUME, /* add /dev/mapper node with dmsetup resume */ <add>// DM_ADD_NODE_ON_CREATE /* add /dev/mapper node with dmsetup create */ <add>// } dm_add_node_t; <add> <add>// struct dm_task { <add>// int type; <add>// char *dev_name; <add>// char *mangled_dev_name; <add> <add>// struct target *head, *tail; <add> <add>// int read_only; <add>// uint32_t event_nr; <add>// int major; <add>// int minor; <add>// int allow_default_major_fallback; <add>// uid_t uid; <add>// gid_t gid; <add>// mode_t mode; <add>// uint32_t read_ahead; <add>// uint32_t read_ahead_flags; <add>// union { <add>// struct dm_ioctl *v4; <add>// } dmi; <add>// char *newname; <add>// char *message; <add>// char *geometry; <add>// uint64_t sector; <add>// int no_flush; <add>// int no_open_count; <add>// int skip_lockfs; <add>// int query_inactive_table; <add>// int suppress_identical_reload; <add>// dm_add_node_t add_node; <add>// uint64_t existing_table_size; <add>// int cookie_set; <add>// int new_uuid; <add>// int secure_data; <add>// int retry_remove; <add>// int enable_checks; <add>// int expected_errno; <add> <add>// char *uuid; <add>// char *mangled_uuid; <add>// }; <add>//
1
Go
Go
fix overlay use of rootdir and defer
36a82c20321936a71b30fcfde8bc6c76d6cc8d1f
<ide><path>daemon/graphdriver/overlay/overlay.go <ide> func (d *Driver) Get(id string, mountLabel string) (s string, err error) { <ide> if _, err := os.Stat(dir); err != nil { <ide> return "", err <ide> } <add> // If id has a root, just return it <add> rootDir := path.Join(dir, "root") <add> if _, err := os.Stat(rootDir); err == nil { <add> return rootDir, nil <add> } <ide> mergedDir := path.Join(dir, "merged") <ide> if count := d.ctr.Increment(mergedDir); count > 1 { <ide> return mergedDir, nil <ide> } <ide> defer func() { <ide> if err != nil { <del> d.ctr.Decrement(mergedDir) <del> syscall.Unmount(mergedDir, 0) <add> if c := d.ctr.Decrement(mergedDir); c <= 0 { <add> syscall.Unmount(mergedDir, 0) <add> } <ide> } <ide> }() <del> <del> // If id has a root, just return it <del> rootDir := path.Join(dir, "root") <del> if _, err := os.Stat(rootDir); err == nil { <del> return rootDir, nil <del> } <del> <ide> lowerID, err := ioutil.ReadFile(path.Join(dir, "lower-id")) <ide> if err != nil { <ide> return "", err
1
Javascript
Javascript
remove cache of page text content in core
8eaf0cdb18d0c3994465b8890b004a04cf123f35
<ide><path>src/core.js <ide> var Page = (function PageClosure() { <ide> return pe.getOperatorList(content, resources, dependency); <ide> }, <ide> extractTextContent: function Page_extractTextContent() { <del> if ('textContent' in this) { <del> // text content was extracted <del> return this.textContent; <del> } <del> <ide> var handler = { <ide> on: function nullHandlerOn() {}, <ide> send: function nullHandlerSend() {} <ide> var Page = (function PageClosure() { <ide> for (i = 0; i < n; ++i) <ide> streams.push(xref.fetchIfRef(content[i])); <ide> content = new StreamsSequenceStream(streams); <del> } else if (isStream(content)) <add> } else if (isStream(content)) { <ide> content.reset(); <add> } <ide> <ide> var pe = new PartialEvaluator( <ide> xref, handler, 'p' + this.pageNumber + '_'); <del> var text = pe.getTextContent(content, resources); <del> return (this.textContent = text); <add> return pe.getTextContent(content, resources); <ide> }, <ide> <ide> ensureFonts: function Page_ensureFonts(fonts, callback) {
1
Javascript
Javascript
add sanity checks for scale options
3f23aaba9a18c6ff70eee9ec1ce51cc4b6e62634
<ide><path>src/core/core.config.js <ide> function mergeScaleConfig(config, options) { <ide> // First figure out first scale id's per axis. <ide> Object.keys(configScales).forEach(id => { <ide> const scaleConf = configScales[id]; <add> if (!isObject(scaleConf)) { <add> return console.error(`Invalid scale configuration for scale: ${id}`); <add> } <add> if (scaleConf._proxy) { <add> return console.warn(`Ignoring resolver passed as options for scale: ${id}`); <add> } <ide> const axis = determineAxis(id, scaleConf); <ide> const defaultId = getDefaultScaleIDFromAxis(axis, chartIndexAxis); <ide> const defaultScaleOptions = chartDefaults.scales || {}; <ide><path>test/specs/core.controller.tests.js <ide> describe('Chart', function() { <ide> expect(Chart.defaults.scales.linear._jasmineCheck).not.toBeDefined(); <ide> expect(Chart.defaults.scales.category._jasmineCheck).not.toBeDefined(); <ide> }); <add> <add> it('should ignore proxy passed as scale options', function() { <add> let failure = false; <add> const chart = acquireChart({ <add> type: 'line', <add> data: [], <add> options: { <add> scales: { <add> x: { <add> grid: { <add> color: ctx => { <add> if (!ctx.tick) { <add> failure = true; <add> } <add> } <add> } <add> } <add> } <add> } <add> }); <add> chart.options.scales = { <add> x: chart.options.scales.x, <add> y: { <add> type: 'linear', <add> position: 'right' <add> } <add> }; <add> chart.update(); <add> expect(failure).toEqual(false); <add> }); <add> <add> it('should ignore array passed as scale options', function() { <add> const chart = acquireChart({ <add> type: 'line', <add> data: [], <add> options: { <add> scales: { <add> xAxes: [{id: 'xAxes', type: 'category'}] <add> } <add> } <add> }); <add> expect(chart.scales.xAxes).not.toBeDefined(); <add> }); <ide> }); <ide> <ide> describe('Updating options', function() {
2
Javascript
Javascript
avoid webpack build dependencies in test
aebca14af8981b596ce20a1d1dadf5a14424b028
<ide><path>test/ConfigCacheTestCases.test.js <ide> const { describeCases } = require("./ConfigTestCases.template"); <ide> describeCases({ <ide> name: "ConfigCacheTestCases", <ide> cache: { <del> type: "filesystem" <add> type: "filesystem", <add> buildDependencies: { <add> defaultWebpack: [] <add> } <ide> }, <ide> snapshot: { <ide> managedPaths: [path.resolve(__dirname, "../node_modules")]
1
Javascript
Javascript
fix minor typo in index.test.js
16c3e6f613bfd4051a3bc6aed736fa145394cc0a
<ide><path>test/integration/app-document/test/index.test.js <ide> import { <ide> killApp, <ide> } from 'next-test-utils' <ide> <del>// test suits <add>// test suites <ide> import rendering from './rendering' <ide> import client from './client' <ide> import csp from './csp'
1
PHP
PHP
add prefix to has table call for mysql
1553f0ca825b255ca958168f2d3a06c0cee54904
<ide><path>src/Illuminate/Database/Schema/MySqlBuilder.php <ide> public function hasTable($table) <ide> <ide> $database = $this->connection->getDatabaseName(); <ide> <add> $table = $this->connection->getTablePrefix().$table; <add> <ide> return count($this->connection->select($sql, array($database, $table))) > 0; <ide> } <ide>
1
Python
Python
add tests for the y2038 problem
6a3ca96df7179e745c76dc09a67bf37af3d818ce
<ide><path>numpy/core/tests/test_datetime.py <ide> def test_datetime_is_busday(self): <ide> assert_equal(np.is_busday(holidays, busdaycal=bdd), <ide> np.zeros(len(holidays), dtype='?')) <ide> <add> def test_datetime_y2038(self): <add> # Test parsing on either side of the Y2038 boundary <add> a = np.datetime64('2038-01-19T03:14:07Z') <add> assert_equal(a.view(np.int64), 2**31 - 1) <add> a = np.datetime64('2038-01-19T03:14:08Z') <add> assert_equal(a.view(np.int64), 2**31) <add> <add> # Test parsing on either side of the Y2038 boundary with <add> # a manually specified timezone offset <add> a = np.datetime64('2038-01-19T04:14:07+0100') <add> assert_equal(a.view(np.int64), 2**31 - 1) <add> a = np.datetime64('2038-01-19T04:14:08+0100') <add> assert_equal(a.view(np.int64), 2**31) <add> <add> # Test parsing a date after Y2038 in the local timezone <add> a = np.datetime64('2038-01-20T13:21:14') <add> assert_equal(str(a)[:-5], '2038-01-20T13:21:14') <add> <ide> class TestDateTimeData(TestCase): <ide> <ide> def test_basic(self):
1
Javascript
Javascript
simplify state transitions in http.client
735b9d50a3cb09c9a87045fce1493036fc742295
<ide><path>lib/http.js <ide> function Client ( ) { <ide> net.Stream.call(this, { allowHalfOpen: true }); <ide> var self = this; <ide> <add> // Possible states: <add> // - disconnected <add> // - connecting <add> // - connected <add> this._state = 'disconnected'; <add> <ide> httpSocketSetup(self); <ide> <ide> function onData(d, start, end) { <ide> function Client ( ) { <ide> self.ondata = onData; <ide> self.onend = onEnd; <ide> <add> self._state = "connected"; <add> <ide> self._initParser(); <ide> debug('CLIENT requests: ' + util.inspect(self._outgoing.map(function (r) { return r.method; }))); <ide> outgoingFlush(self); <ide> }); <ide> <ide> function onEnd() { <ide> if (self.parser) self.parser.finish(); <del> debug("CLIENT got end closing. readyState = " + self.readyState); <add> debug("CLIENT got end closing. state = " + self._state); <ide> self.end(); <ide> }; <ide> <ide> self.addListener("close", function (e) { <add> self._state = "disconnected"; <ide> if (e) return; <ide> <del> debug("CLIENT onClose. readyState = " + self.readyState); <add> debug("CLIENT onClose. state = " + self._state); <ide> <ide> // finally done with the request <ide> self._outgoing.shift(); <ide> <ide> // If there are more requests to handle, reconnect. <ide> if (self._outgoing.length) { <del> self._reconnect(); <add> self._ensureConnection(); <ide> } else if (self.parser) { <ide> parsers.free(self.parser); <ide> self.parser = null; <ide> Client.prototype._initParser = function () { <ide> } <ide> <ide> res.addListener('end', function ( ) { <del> debug("CLIENT request complete disconnecting. readyState = " + self.readyState); <add> debug("CLIENT request complete disconnecting. state = " + self._state); <ide> // For the moment we reconnect for every request. FIXME! <ide> // All that should be required for keep-alive is to not reconnect, <ide> // but outgoingFlush instead. <ide> Client.prototype._onOutgoingSent = function (message) { <ide> // <ide> // Instead, we just check if the connection is closed, and if so <ide> // reconnect if we have pending messages. <del> if (this._outgoing.length && this.readyState == "closed") { <del> debug("CLIENT request flush. reconnect. readyState = " + this.readyState); <del> this._reconnect(); <add> if (this._outgoing.length) { <add> debug("CLIENT request flush. ensure connection. state = " + this._state); <add> this._ensureConnection(); <ide> } <ide> }; <ide> <ide> <del>Client.prototype._reconnect = function () { <del> if (this.readyState === "closed") { <del> debug("CLIENT reconnecting readyState = " + this.readyState); <add>Client.prototype._ensureConnection = function () { <add> if (this._state == 'disconnected') { <add> debug("CLIENT reconnecting state = " + this._state); <ide> this.connect(this.port, this.host); <add> this._state = "connecting"; <ide> } <ide> }; <ide> <ide> Client.prototype.request = function (method, url, headers) { <ide> } <ide> var req = new ClientRequest(this, method, url, headers); <ide> this._outgoing.push(req); <del> if (this.readyState === 'closed') this._reconnect(); <add> this._ensureConnection(); <ide> return req; <ide> }; <ide> <ide><path>test/simple/test-http-allow-req-after-204-res.js <add>var common = require('../common'); <add>var http = require('http'); <add>var assert = require('assert'); <add> <add>// first 204 or 304 works, subsequent anything fails <add>var codes = [ 204, 200 ]; <add> <add>// Methods don't really matter, but we put in something realistic. <add>var methods = ['DELETE', 'DELETE']; <add> <add>var server = http.createServer(function (req, res) { <add> var code = codes.shift(); <add> assert.equal('number', typeof code); <add> assert.ok(code > 0); <add> console.error('writing %d response', code); <add> res.writeHead(code, {}); <add> res.end(); <add>}); <add> <add>var client = http.createClient(common.PORT); <add> <add>function nextRequest() { <add> var method = methods.shift(); <add> console.error("writing request: %s", method); <add> <add> var request = client.request(method, '/'); <add> request.on('response', function (response) { <add> response.on('end', function() { <add> if (methods.length == 0) { <add> console.error("close server"); <add> server.close(); <add> } else { <add> // throws error: <add> nextRequest(); <add> // works just fine: <add> //process.nextTick(nextRequest); <add> } <add> }); <add> }); <add> request.end(); <add>} <add> <add>server.listen(common.PORT, nextRequest);
2
Javascript
Javascript
add k and kk formatting tokens
46093762bd4fcd7dde7ed84151ff55605465ab17
<ide><path>src/lib/format/format.js <ide> import zeroFill from '../utils/zero-fill'; <ide> <del>export var formattingTokens = /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g; <add>export var formattingTokens = /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g; <ide> <ide> var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g; <ide> <ide> export function expandFormat(format, locale) { <ide> <ide> return format; <ide> } <del> <ide><path>src/lib/units/hour.js <ide> function hFormat() { <ide> return this.hours() % 12 || 12; <ide> } <ide> <add>function kFormat() { <add> return this.hours() || 24; <add>} <add> <ide> addFormatToken('H', ['HH', 2], 0, 'hour'); <ide> addFormatToken('h', ['hh', 2], 0, hFormat); <add>addFormatToken('k', ['kk', 2], 0, kFormat); <ide> <ide> addFormatToken('hmm', 0, 0, function () { <ide> return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2); <ide><path>src/test/moment/format.js <ide> test('Hmm and Hmmss', function (assert) { <ide> assert.equal(moment('18:34:56', 'HH:mm:ss').format('Hmmss'), '183456'); <ide> }); <ide> <add>test('k and kk', function (assert) { <add> assert.equal(moment('01:23:45', 'HH:mm:ss').format('k'), '1'); <add> assert.equal(moment('12:34:56', 'HH:mm:ss').format('k'), '12'); <add> assert.equal(moment('01:23:45', 'HH:mm:ss').format('kk'), '01'); <add> assert.equal(moment('12:34:56', 'HH:mm:ss').format('kk'), '12'); <add> assert.equal(moment('00:34:56', 'HH:mm:ss').format('kk'), '24'); <add> assert.equal(moment('00:00:00', 'HH:mm:ss').format('kk'), '24'); <add>}); <add> <ide> test('Y token', function (assert) { <ide> assert.equal(moment('2010-01-01', 'YYYY-MM-DD', true).format('Y'), '2010', 'format 2010 with Y'); <ide> assert.equal(moment('-123-01-01', 'Y-MM-DD', true).format('Y'), '-123', 'format -123 with Y');
3
Text
Text
add missing options for crypto sign.sign()
cb3d6d5113a3bb076106e2b7c35e2471744bf218
<ide><path>doc/api/crypto.md <ide> changes: <ide> * `privateKey` {string | Object} <ide> - `key` {string} <ide> - `passphrase` {string} <add> - `padding` {integer} <add> - `saltLength` {integer} <ide> * `outputFormat` {string} <ide> * Returns: {Buffer | string} <ide>
1
Javascript
Javascript
optimize emit for two arguments
ae8f8e7258bb9db0bc6928e9dc1cd535d95a7910
<ide><path>lib/events.js <ide> process.EventEmitter.prototype.emit = function (type) { <ide> if (!this._events[type]) return false; <ide> <ide> if (typeof this._events[type] == 'function') { <del> if (arguments.length < 3) { <add> if (arguments.length <= 3) { <ide> // fast case <ide> this._events[type].call( this <ide> , arguments[1]
1
Python
Python
return extra_specs in openstacknodesize
a6c19b6ce97a6c7d151ede99627bcdc8f6590f12
<ide><path>libcloud/compute/drivers/openstack.py <ide> def _to_size(self, el): <ide> # XXX: needs hardcode <ide> vcpus=vcpus, <ide> bandwidth=None, <add> extra=el.get('extra_specs') <ide> # Hardcoded <ide> price=self._get_size_price(el.get('id')), <ide> driver=self.connection.driver)
1
Python
Python
remove reference to voting on issue
0f07defe2ca0ba7a726aafb4a30c89627510bae1
<ide><path>spacy/errors.py <ide> class Errors(metaclass=ErrorsWithCodes): <ide> E198 = ("Unable to return {n} most similar vectors for the current vectors " <ide> "table, which contains {n_rows} vectors.") <ide> E199 = ("Unable to merge 0-length span at `doc[{start}:{end}]`.") <del> E200 = ("Can't yet set {attr} from Span. Vote for this feature on the " <del> "issue tracker: http://github.com/explosion/spaCy/issues") <add> E200 = ("Can't set {attr} from Span.") <ide> E202 = ("Unsupported {name} mode '{mode}'. Supported modes: {modes}.") <ide> <ide> # New errors added in v3.x
1
PHP
PHP
allow customization of schedule mutex cache store
20e29199365a11b31e35179bbfe3e83485e05a03
<ide><path>src/Illuminate/Console/Scheduling/CacheEventMutex.php <ide> <ide> namespace Illuminate\Console\Scheduling; <ide> <del>use Illuminate\Contracts\Cache\Repository as Cache; <add>use Illuminate\Contracts\Cache\Factory as Cache; <ide> <ide> class CacheEventMutex implements EventMutex <ide> { <ide> /** <ide> * The cache repository implementation. <ide> * <del> * @var \Illuminate\Contracts\Cache\Repository <add> * @var \Illuminate\Contracts\Cache\Factory <ide> */ <ide> public $cache; <ide> <add> /** <add> * The cache store that should be used. <add> * <add> * @var string|null <add> */ <add> public $store; <add> <ide> /** <ide> * Create a new overlapping strategy. <ide> * <del> * @param \Illuminate\Contracts\Cache\Repository $cache <add> * @param \Illuminate\Contracts\Cache\Factory $cache <ide> * @return void <ide> */ <ide> public function __construct(Cache $cache) <ide> public function __construct(Cache $cache) <ide> */ <ide> public function create(Event $event) <ide> { <del> return $this->cache->add( <add> return $this->cache->store($this->store)->add( <ide> $event->mutexName(), true, $event->expiresAt <ide> ); <ide> } <ide> public function create(Event $event) <ide> */ <ide> public function exists(Event $event) <ide> { <del> return $this->cache->has($event->mutexName()); <add> return $this->cache->store($this->store)->has($event->mutexName()); <ide> } <ide> <ide> /** <ide> public function exists(Event $event) <ide> */ <ide> public function forget(Event $event) <ide> { <del> $this->cache->forget($event->mutexName()); <add> $this->cache->store($this->store)->forget($event->mutexName()); <add> } <add> <add> /** <add> * Specify the cache store that should be used. <add> * <add> * @param string $store <add> * @return $this <add> */ <add> public function useStore($store) <add> { <add> $this->store = $store; <add> <add> return $this; <ide> } <ide> } <ide><path>src/Illuminate/Console/Scheduling/CacheSchedulingMutex.php <ide> namespace Illuminate\Console\Scheduling; <ide> <ide> use DateTimeInterface; <del>use Illuminate\Contracts\Cache\Repository as Cache; <add>use Illuminate\Contracts\Cache\Factory as Cache; <ide> <ide> class CacheSchedulingMutex implements SchedulingMutex <ide> { <ide> /** <del> * The cache repository implementation. <add> * The cache factory implementation. <ide> * <del> * @var \Illuminate\Contracts\Cache\Repository <add> * @var \Illuminate\Contracts\Cache\Factory <ide> */ <ide> public $cache; <ide> <add> /** <add> * The cache store that should be used. <add> * <add> * @var string|null <add> */ <add> public $store; <add> <ide> /** <ide> * Create a new overlapping strategy. <ide> * <del> * @param \Illuminate\Contracts\Cache\Repository $cache <add> * @param \Illuminate\Contracts\Cache\Factory $cache <ide> * @return void <ide> */ <ide> public function __construct(Cache $cache) <ide> public function __construct(Cache $cache) <ide> */ <ide> public function create(Event $event, DateTimeInterface $time) <ide> { <del> return $this->cache->add($event->mutexName().$time->format('Hi'), true, 60); <add> return $this->cache->store($this->store)->add( <add> $event->mutexName().$time->format('Hi'), true, 60 <add> ); <ide> } <ide> <ide> /** <ide> public function create(Event $event, DateTimeInterface $time) <ide> */ <ide> public function exists(Event $event, DateTimeInterface $time) <ide> { <del> return $this->cache->has($event->mutexName().$time->format('Hi')); <add> return $this->cache->store($this->store)->has( <add> $event->mutexName().$time->format('Hi') <add> ); <add> } <add> <add> /** <add> * Specify the cache store that should be used. <add> * <add> * @param string $store <add> * @return $this <add> */ <add> public function useStore($store) <add> { <add> $this->store = $store; <add> <add> return $this; <ide> } <ide> } <ide><path>src/Illuminate/Console/Scheduling/Schedule.php <ide> public function events() <ide> { <ide> return $this->events; <ide> } <add> <add> /** <add> * Specify the cache store that should be used to store mutexes. <add> * <add> * @param string $store <add> * @return $this <add> */ <add> public function useCache($store) <add> { <add> if ($this->eventMutex instanceof CacheEventMutex) { <add> $this->eventMutex->useStore($store); <add> } <add> <add> if ($this->schedulingMutex instanceof CacheSchedulingMutex) { <add> $this->schedulingMutex->useStore($store); <add> } <add> <add> return $this; <add> } <ide> } <ide><path>tests/Console/ConsoleEventSchedulerTest.php <ide> <ide> use Mockery as m; <ide> use PHPUnit\Framework\TestCase; <add>use Illuminate\Container\Container; <ide> use Illuminate\Console\Scheduling\Schedule; <add>use Illuminate\Console\Scheduling\EventMutex; <add>use Illuminate\Console\Scheduling\SchedulingMutex; <ide> <ide> class ConsoleEventSchedulerTest extends TestCase <ide> { <ide> public function setUp() <ide> { <ide> parent::setUp(); <ide> <del> $container = \Illuminate\Container\Container::getInstance(); <add> $container = Container::getInstance(); <ide> <ide> $container->instance('Illuminate\Console\Scheduling\EventMutex', m::mock('Illuminate\Console\Scheduling\CacheEventMutex')); <ide> <ide> public function tearDown() <ide> m::close(); <ide> } <ide> <add> public function testMutexCanReceiveCustomStore() <add> { <add> Container::getInstance()->make(EventMutex::class)->shouldReceive('useStore')->once()->with('test'); <add> Container::getInstance()->make(SchedulingMutex::class)->shouldReceive('useStore')->once()->with('test'); <add> <add> $this->schedule->useCache('test'); <add> } <add> <ide> public function testExecCreatesNewCommand() <ide> { <ide> $escape = '\\' === DIRECTORY_SEPARATOR ? '"' : '\''; <ide><path>tests/Console/Scheduling/CacheEventMutexTest.php <ide> class CacheEventMutexTest extends TestCase <ide> */ <ide> protected $event; <ide> <add> /** <add> * @var \Illuminate\Contracts\Cache\Factory <add> */ <add> protected $cacheFactory; <add> <ide> /** <ide> * @var \Illuminate\Contracts\Cache\Repository <ide> */ <ide> public function setUp() <ide> { <ide> parent::setUp(); <ide> <add> $this->cacheFactory = m::mock('Illuminate\Contracts\Cache\Factory'); <ide> $this->cacheRepository = m::mock('Illuminate\Contracts\Cache\Repository'); <del> $this->cacheMutex = new CacheEventMutex($this->cacheRepository); <add> $this->cacheFactory->shouldReceive('store')->andReturn($this->cacheRepository); <add> $this->cacheMutex = new CacheEventMutex($this->cacheFactory); <ide> $this->event = new Event($this->cacheMutex, 'command'); <ide> } <ide> <ide> public function testPreventOverlap() <ide> $this->cacheMutex->create($this->event); <ide> } <ide> <add> public function testCustomConnection() <add> { <add> $this->cacheFactory->shouldReceive('store')->with('test')->andReturn($this->cacheRepository); <add> $this->cacheRepository->shouldReceive('add')->once(); <add> $this->cacheMutex->useStore('test'); <add> <add> $this->cacheMutex->create($this->event); <add> } <add> <ide> public function testPreventOverlapFails() <ide> { <ide> $this->cacheRepository->shouldReceive('add')->once()->andReturn(false); <ide><path>tests/Console/Scheduling/CacheSchedulingMutexTest.php <ide> class CacheSchedulingMutexTest extends TestCase <ide> */ <ide> protected $time; <ide> <add> /** <add> * @var \Illuminate\Contracts\Cache\Factory <add> */ <add> protected $cacheFactory; <add> <ide> /** <ide> * @var \Illuminate\Contracts\Cache\Repository <ide> */ <ide> public function setUp() <ide> { <ide> parent::setUp(); <ide> <add> $this->cacheFactory = m::mock('Illuminate\Contracts\Cache\Factory'); <ide> $this->cacheRepository = m::mock('Illuminate\Contracts\Cache\Repository'); <del> $this->cacheMutex = new CacheSchedulingMutex($this->cacheRepository); <del> $this->event = new Event(new CacheEventMutex($this->cacheRepository), 'command'); <add> $this->cacheFactory->shouldReceive('store')->andReturn($this->cacheRepository); <add> $this->cacheMutex = new CacheSchedulingMutex($this->cacheFactory); <add> $this->event = new Event(new CacheEventMutex($this->cacheFactory), 'command'); <ide> $this->time = Carbon::now(); <ide> } <ide> <ide> public function testMutexReceviesCorrectCreate() <ide> $this->assertTrue($this->cacheMutex->create($this->event, $this->time)); <ide> } <ide> <add> public function testCanUseCustomConnection() <add> { <add> $this->cacheFactory->shouldReceive('store')->with('test')->andReturn($this->cacheRepository); <add> $this->cacheRepository->shouldReceive('add')->once()->with($this->event->mutexName().$this->time->format('Hi'), true, 60)->andReturn(true); <add> $this->cacheMutex->useStore('test'); <add> <add> $this->assertTrue($this->cacheMutex->create($this->event, $this->time)); <add> } <add> <ide> public function testPreventsMultipleRuns() <ide> { <ide> $this->cacheRepository->shouldReceive('add')->once()->with($this->event->mutexName().$this->time->format('Hi'), true, 60)->andReturn(false);
6
Mixed
Python
fix readme + argparse
d067ce0a0861ba1a200e9e7ccdec529994a55e7c
<ide><path>tutorials/image/cifar10_estimator/README.md <ide> $ python cifar10_main.py --data-dir=/prefix/to/downloaded/data/cifar-10-batches- <ide> --is-cpu-ps=False \ <ide> --force-gpu-compatible=True \ <ide> --num-gpus=2 \ <del> --train-steps=1000 <del> <add> <ide> <ide> # There are more command line flags to play with; check cifar10_main.py for details. <ide> ``` <ide> Then run the following command from the `tutorials/image` directory of this repo <ide> ``` <ide> gcloud ml-engine jobs submit training cifarmultigpu \ <ide> --runtime-version 1.2 \ <del> --staging-bucket $MY_BUCKET \ <del> --config cifar10_estimator/job_config.yaml \ <add> --job-dir=$MY_BUCKET/model_dirs/cifarmultigpu \ <add> --config cifar10_estimator/cmle_config.yaml \ <ide> --package-path cifar10_estimator/ \ <del> --region us-central1 \ <ide> --module-name cifar10_estimator.cifar10_main \ <ide> -- \ <ide> --data-dir=$MY_BUCKET/cifar-10-batches-py \ <del> --job-dir=$MY_BUCKLET/model_dirs/cifarmultigpu \ <ide> --is-cpu-ps=True \ <ide> --force-gpu-compatible=True \ <ide> --num-gpus=4 \ <del> --train-steps=1000 \ <del> <add> --train-steps=1000 <ide> ``` <ide> <ide> <ide><path>tutorials/image/cifar10_estimator/cifar10_main.py <ide> def main(job_dir, <ide> If present when running in a distributed environment will run on sync mode.\ <ide> """ <ide> ) <del> parser.add_argument( <del> '--num-workers', <del> type=int, <del> default=1, <del> help='Number of workers.' <del> ) <ide> parser.add_argument( <ide> '--num-intra-threads', <ide> type=int,
2
PHP
PHP
add missing docblock
a9e332988f707a3e721dd24b7881fc2c8f07daa5
<ide><path>src/Illuminate/Console/Parser.php <ide> public static function parse($expression) <ide> * <ide> * @param string $expression <ide> * @return string <add> * <add> * @throws \InvalidArgumentException <ide> */ <ide> protected static function name($expression) <ide> {
1
Javascript
Javascript
add message for dispose deprecation
3b8ec68a3a4cb014fdc7770bb0fec5248aee2691
<ide><path>lib/domain.js <ide> Domain.prototype.dispose = util.deprecate(function() { <ide> // mark this domain as 'no longer relevant' <ide> // so that it can't be entered or activated. <ide> this._disposed = true; <del>}); <add>}, 'Domain.dispose is deprecated. Recover from failed I/O actions explicitly ' + <add> 'via error event handlers set on the domain instead.');
1
Java
Java
fix dispatchviewmanagercommand ordering for nodes
754d2848a4766355534c2c3317c0ca3628048bef
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/FlatUIImplementation.java <ide> public void addAnimation(int reactTag, int animationID, Callback onSuccess) { <ide> @Override <ide> public void dispatchViewManagerCommand(int reactTag, int commandId, ReadableArray commandArgs) { <ide> ensureMountsToViewAndBackingViewIsCreated(reactTag); <add> // need to make sure any ui operations (UpdateViewGroup, for example, etc) have already <add> // happened before we actually dispatch the view manager command (since otherwise, the command <add> // may go to an empty shell parent without its children, which is against the specs). <add> mStateBuilder.applyUpdates((FlatShadowNode) resolveShadowNode(reactTag)); <ide> super.dispatchViewManagerCommand(reactTag, commandId, commandArgs); <ide> } <ide>
1
Ruby
Ruby
fix cache#fetch instrumentation
edd33c08d98723ae9bb89cf7f019277117ed6414
<ide><path>activesupport/lib/active_support/cache.rb <ide> def fetch(name, options = nil) <ide> options = merged_options(options) <ide> key = namespaced_key(name, options) <ide> <del> cached_entry = find_cached_entry(key, name, options) unless options[:force] <del> entry = handle_expired_entry(cached_entry, key, options) <add> instrument(:read, name, options) do |payload| <add> cached_entry = read_entry(key, options) unless options[:force] <add> payload[:super_operation] = :fetch if payload <add> entry = handle_expired_entry(cached_entry, key, options) <ide> <del> if entry <del> get_entry_value(entry, name, options) <del> else <del> save_block_result_to_cache(name, options) { |_name| yield _name } <add> if entry <add> payload[:hit] = true if payload <add> get_entry_value(entry, name, options) <add> else <add> payload[:hit] = false if payload <add> save_block_result_to_cache(name, options) { |_name| yield _name } <add> end <ide> end <ide> else <ide> read(name, options) <ide> def log <ide> logger.debug(yield) <ide> end <ide> <del> def find_cached_entry(key, name, options) <del> instrument(:read, name, options) do |payload| <del> payload[:super_operation] = :fetch if payload <del> read_entry(key, options) <del> end <del> end <del> <ide> def handle_expired_entry(entry, key, options) <ide> if entry && entry.expired? <ide> race_ttl = options[:race_condition_ttl].to_i
1
Javascript
Javascript
remove some hacks to uimanager
87e02702a9e1d5b8839e043ca1e3a84f6be713b1
<ide><path>Libraries/ReactNative/PaperUIManager.js <ide> if (Platform.OS === 'ios') { <ide> lazifyViewManagerConfig(viewName); <ide> }); <ide> } else if (getConstants().ViewManagerNames) { <del> // We want to add all the view managers to the UIManager. <del> // However, the way things are set up, the list of view managers is not known at compile time. <del> // As Prepack runs at compile it, it cannot process this loop. <del> // So we wrap it in a special __residual call, which basically tells Prepack to ignore it. <del> let residual = global.__residual <del> ? global.__residual <del> : (_, f, ...args) => f.apply(undefined, args); <del> residual( <del> 'void', <del> (UIManager, defineLazyObjectProperty) => { <del> UIManager.getConstants().ViewManagerNames.forEach(viewManagerName => { <del> defineLazyObjectProperty(UIManager, viewManagerName, { <del> get: () => UIManager.getConstantsForViewManager(viewManagerName), <del> }); <del> }); <del> }, <del> NativeUIManager, <del> defineLazyObjectProperty, <del> ); <del> <del> // As Prepack now no longer knows which properties exactly the UIManager has, <del> // we also tell Prepack that it has only partial knowledge of the UIManager, <del> // so that any accesses to unknown properties along the global code will fail <del> // when Prepack encounters them. <del> if (global.__makePartial) { <del> global.__makePartial(NativeUIManager); <del> } <add> NativeUIManager.getConstants().ViewManagerNames.forEach(viewManagerName => { <add> defineLazyObjectProperty(NativeUIManager, viewManagerName, { <add> get: () => NativeUIManager.getConstantsForViewManager(viewManagerName), <add> }); <add> }); <ide> } <ide> <ide> if (!global.nativeCallSyncHook) {
1
Javascript
Javascript
add styles to experimental-amp example
23178db57564ada957a53e0b96094a324f29108b
<ide><path>examples/experimental-amp/components/Layout.js <add>export default function Layout ({ children }) { <add> return ( <add> <> <add> {children} <add> <style jsx global>{` <add> body {font-family: Roboto, sans-serif; padding: 30px; color: #444;} <add> `}</style> <add> </> <add> ) <add>} <ide><path>examples/experimental-amp/pages/index.js <ide> import Head from 'next/head' <ide> import { useAmp } from 'next/amp' <add>import Layout from '../components/Layout' <ide> import Byline from '../components/Byline' <ide> <ide> export default () => { <ide> const isAmp = useAmp() <ide> <ide> return ( <del> <> <add> <Layout> <ide> <Head> <ide> <title>The Cat</title> <ide> </Head> <ide> export default () => { <ide> belly and purr when you are asleep. Lounge in doorway poop on grasses <ide> for lounge in doorway for chew iPad power cord. <ide> </p> <del> </> <add> <style jsx>{` <add> h1 {margin-bottom: 5px;} <add> p {font-size: 18px; line-height: 30px; margin-top: 30px;} <add> .caption {color: #ccc; margin-top: 0; font-size: 14px; text-align: center;} <add> `}</style> <add> </Layout> <ide> ) <ide> }
2
Javascript
Javascript
add option of specifying literal regexp
c8d349870812284a82896087c05c2d19c8f5cdfd
<ide><path>src/ng/directive/validators.js <ide> var requiredDirective = function() { <ide> * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls. <ide> * <ide> * The validator sets the `pattern` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`} <del> * does not match a RegExp which is obtained by evaluating the AngularJS expression given in the <del> * `ngPattern` attribute value: <del> * * If the expression evaluates to a RegExp object, then this is used directly. <del> * * If the expression evaluates to a string, then it will be converted to a RegExp after wrapping it <del> * in `^` and `$` characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`. <add> * does not match a RegExp which is obtained from the `ngPattern` attribute value: <add> * - the value is an AngularJS expression: <add> * - If the expression evaluates to a RegExp object, then this is used directly. <add> * - If the expression evaluates to a string, then it will be converted to a RegExp after wrapping it <add> * in `^` and `$` characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`. <add> * - If the value is a RegExp literal, e.g. `ngPattern="/^\d+$/"`, it is used directly. <ide> * <ide> * <div class="alert alert-info"> <ide> * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
1
PHP
PHP
move php8 only attributes inside docblock
4c07d7757fcd1bb0e89cd2f710559f6a85d6592b
<ide><path>src/Collection/Iterator/BufferedIterator.php <ide> <ide> use Cake\Collection\Collection; <ide> use Countable; <del>use ReturnTypeWillChange; <ide> use Serializable; <ide> use SplDoublyLinkedList; <ide> <ide> public function __construct(iterable $items) <ide> * <ide> * @return mixed <ide> */ <del> #[ReturnTypeWillChange] <add> #[\ReturnTypeWillChange] <ide> public function key() <ide> { <ide> return $this->_key; <ide> public function key() <ide> * <ide> * @return mixed <ide> */ <del> #[ReturnTypeWillChange] <add> #[\ReturnTypeWillChange] <ide> public function current() <ide> { <ide> return $this->_current; <ide><path>src/Collection/Iterator/ExtractIterator.php <ide> use ArrayIterator; <ide> use Cake\Collection\Collection; <ide> use Cake\Collection\CollectionInterface; <del>use ReturnTypeWillChange; <ide> use Traversable; <ide> <ide> /** <ide> public function __construct(iterable $items, $path) <ide> * <ide> * @return mixed <ide> */ <del> #[ReturnTypeWillChange] <add> #[\ReturnTypeWillChange] <ide> public function current() <ide> { <ide> $extractor = $this->_extractor; <ide><path>src/Collection/Iterator/InsertIterator.php <ide> namespace Cake\Collection\Iterator; <ide> <ide> use Cake\Collection\Collection; <del>use ReturnTypeWillChange; <ide> <ide> /** <ide> * This iterator will insert values into a property of each of the records returned. <ide> public function next(): void <ide> * <ide> * @return mixed <ide> */ <del> #[ReturnTypeWillChange] <add> #[\ReturnTypeWillChange] <ide> public function current() <ide> { <ide> $row = parent::current(); <ide><path>src/Collection/Iterator/ReplaceIterator.php <ide> use ArrayIterator; <ide> use Cake\Collection\Collection; <ide> use Cake\Collection\CollectionInterface; <del>use ReturnTypeWillChange; <ide> use Traversable; <ide> <ide> /** <ide> public function __construct(iterable $items, callable $callback) <ide> * <ide> * @return mixed <ide> */ <del> #[ReturnTypeWillChange] <add> #[\ReturnTypeWillChange] <ide> public function current() <ide> { <ide> $callback = $this->_callback; <ide><path>src/Collection/Iterator/TreePrinter.php <ide> use Cake\Collection\CollectionTrait; <ide> use RecursiveIterator; <ide> use RecursiveIteratorIterator; <del>use ReturnTypeWillChange; <ide> <ide> /** <ide> * Iterator for flattening elements in a tree structure while adding some <ide> public function __construct( <ide> * <ide> * @return mixed <ide> */ <del> #[ReturnTypeWillChange] <add> #[\ReturnTypeWillChange] <ide> public function key() <ide> { <ide> $extractor = $this->_key; <ide><path>src/Collection/Iterator/ZipIterator.php <ide> use Cake\Collection\CollectionInterface; <ide> use Cake\Collection\CollectionTrait; <ide> use MultipleIterator; <del>use ReturnTypeWillChange; <ide> use Serializable; <ide> <ide> /** <ide> public function __construct(array $sets, ?callable $callable = null) <ide> * <ide> * @return array <ide> */ <del> #[ReturnTypeWillChange] <add> #[\ReturnTypeWillChange] <ide> public function current() <ide> { <ide> if ($this->_callback === null) { <ide><path>src/Database/Driver/Mysql.php <ide> class Mysql extends Driver <ide> <ide> /** <ide> * @inheritDoc <add> * @var int <ide> */ <ide> protected const MAX_ALIAS_LENGTH = 256; <ide> <ide><path>src/Database/Driver/Postgres.php <ide> class Postgres extends Driver <ide> <ide> /** <ide> * @inheritDoc <add> * @var int <ide> */ <ide> protected const MAX_ALIAS_LENGTH = 63; <ide> <ide><path>src/Database/Query.php <ide> use Closure; <ide> use InvalidArgumentException; <ide> use IteratorAggregate; <del>use ReturnTypeWillChange; <ide> use RuntimeException; <ide> <ide> /** <ide> public function func(): FunctionsBuilder <ide> * @return \Cake\Database\StatementInterface <ide> * @psalm-suppress ImplementedReturnTypeMismatch <ide> */ <del> #[ReturnTypeWillChange] <add> #[\ReturnTypeWillChange] <ide> public function getIterator() <ide> { <ide> if ($this->_iterator === null || $this->_dirty) { <ide><path>src/Database/Statement/BufferedStatement.php <ide> use Cake\Database\StatementInterface; <ide> use Cake\Database\TypeConverterTrait; <ide> use Iterator; <del>use ReturnTypeWillChange; <ide> <ide> /** <ide> * A statement decorator that implements buffered results. <ide> protected function _reset(): void <ide> * <ide> * @return mixed <ide> */ <del> #[ReturnTypeWillChange] <add> #[\ReturnTypeWillChange] <ide> public function key() <ide> { <ide> return $this->index; <ide> public function key() <ide> * <ide> * @return mixed <ide> */ <del> #[ReturnTypeWillChange] <add> #[\ReturnTypeWillChange] <ide> public function current() <ide> { <ide> return $this->buffer[$this->index]; <ide><path>src/Database/Statement/StatementDecorator.php <ide> use Cake\Database\TypeConverterTrait; <ide> use Countable; <ide> use IteratorAggregate; <del>use ReturnTypeWillChange; <ide> <ide> /** <ide> * Represents a database statement. Statements contains queries that can be <ide> public function rowCount(): int <ide> * @return \Cake\Database\StatementInterface <ide> * @psalm-suppress ImplementedReturnTypeMismatch <ide> */ <del> #[ReturnTypeWillChange] <add> #[\ReturnTypeWillChange] <ide> public function getIterator() <ide> { <ide> if (!$this->_hasExecuted) { <ide><path>src/Datasource/EntityTrait.php <ide> use Cake\Utility\Hash; <ide> use Cake\Utility\Inflector; <ide> use InvalidArgumentException; <del>use ReturnTypeWillChange; <ide> use Traversable; <ide> <ide> /** <ide> public function offsetExists($offset): bool <ide> * @param string $offset The offset to get. <ide> * @return mixed <ide> */ <del> #[ReturnTypeWillChange] <add> #[\ReturnTypeWillChange] <ide> public function &offsetGet($offset) <ide> { <ide> return $this->get($offset); <ide><path>src/Event/EventList.php <ide> <ide> use ArrayAccess; <ide> use Countable; <del>use ReturnTypeWillChange; <ide> <ide> /** <ide> * The Event List <ide> public function offsetExists($offset): bool <ide> * @param mixed $offset The offset to retrieve. <ide> * @return mixed Can return all value types. <ide> */ <del> #[ReturnTypeWillChange] <add> #[\ReturnTypeWillChange] <ide> public function offsetGet($offset) <ide> { <ide> if ($this->offsetExists($offset)) { <ide><path>src/Http/Session/CacheSession.php <ide> <ide> use Cake\Cache\Cache; <ide> use InvalidArgumentException; <del>use ReturnTypeWillChange; <ide> use SessionHandlerInterface; <ide> <ide> /** <ide> public function close(): bool <ide> * @param string $id ID that uniquely identifies session in cache. <ide> * @return string|false Session data or false if it does not exist. <ide> */ <del> #[ReturnTypeWillChange] <add> #[\ReturnTypeWillChange] <ide> public function read($id) <ide> { <ide> $value = Cache::read($id, $this->_options['config']); <ide> public function destroy($id): bool <ide> * @param int $maxlifetime Sessions that have not updated for the last maxlifetime seconds will be removed. <ide> * @return int|false <ide> */ <del> #[ReturnTypeWillChange] <add> #[\ReturnTypeWillChange] <ide> public function gc($maxlifetime) <ide> { <ide> return 0; <ide><path>src/Http/Session/DatabaseSession.php <ide> namespace Cake\Http\Session; <ide> <ide> use Cake\ORM\Locator\LocatorAwareTrait; <del>use ReturnTypeWillChange; <ide> use SessionHandlerInterface; <ide> <ide> /** <ide> public function close(): bool <ide> * @param string $id ID that uniquely identifies session in database. <ide> * @return string|false Session data or false if it does not exist. <ide> */ <del> #[ReturnTypeWillChange] <add> #[\ReturnTypeWillChange] <ide> public function read($id) <ide> { <ide> /** @var string $pkField */ <ide> public function destroy($id): bool <ide> * @param int $maxlifetime Sessions that have not updated for the last maxlifetime seconds will be removed. <ide> * @return int|false The number of deleted sessions on success, or false on failure. <ide> */ <del> #[ReturnTypeWillChange] <add> #[\ReturnTypeWillChange] <ide> public function gc($maxlifetime) <ide> { <ide> return $this->_table->deleteAll(['expires <' => time()]); <ide><path>src/I18n/DateFormatTrait.php <ide> use DateTime; <ide> use DateTimeZone; <ide> use IntlDateFormatter; <del>use ReturnTypeWillChange; <ide> use RuntimeException; <ide> <ide> /** <ide> public static function parseTime(string $time, $format = null) <ide> * <ide> * @return string|int <ide> */ <del> #[ReturnTypeWillChange] <add> #[\ReturnTypeWillChange] <ide> public function jsonSerialize() <ide> { <ide> if (static::$_jsonEncodeFormat instanceof Closure) { <ide><path>src/I18n/Parser/MoFileParser.php <ide> class MoFileParser <ide> * Magic used for validating the format of a MO file as well as <ide> * detecting if the machine used to create that file was little endian. <ide> * <del> * @var float <add> * @var int <ide> */ <ide> public const MO_LITTLE_ENDIAN_MAGIC = 0x950412de; <ide> <ide> /** <ide> * Magic used for validating the format of a MO file as well as <ide> * detecting if the machine used to create that file was big endian. <ide> * <del> * @var float <add> * @var int <ide> */ <ide> public const MO_BIG_ENDIAN_MAGIC = 0xde120495; <ide> <ide><path>src/ORM/ResultSet.php <ide> use Cake\Database\StatementInterface; <ide> use Cake\Datasource\EntityInterface; <ide> use Cake\Datasource\ResultSetInterface; <del>use ReturnTypeWillChange; <ide> use SplFixedArray; <ide> <ide> /** <ide> public function __construct(Query $query, StatementInterface $statement) <ide> * <ide> * @return object|array <ide> */ <del> #[ReturnTypeWillChange] <add> #[\ReturnTypeWillChange] <ide> public function current() <ide> { <ide> return $this->_current; <ide><path>tests/test_app/Plugin/TestPlugin/src/Http/Session/TestPluginSession.php <ide> <ide> namespace TestPlugin\Http\Session; <ide> <del>use ReturnTypeWillChange; <ide> use SessionHandlerInterface; <ide> <ide> /** <ide> public function close(): bool <ide> /** <ide> * @inheritDoc <ide> */ <del> #[ReturnTypeWillChange] <add> #[\ReturnTypeWillChange] <ide> public function read($id) <ide> { <ide> } <ide> public function destroy($id): bool <ide> /** <ide> * @inheritDoc <ide> */ <del> #[ReturnTypeWillChange] <add> #[\ReturnTypeWillChange] <ide> public function gc($maxlifetime) <ide> { <ide> return 0; <ide><path>tests/test_app/TestApp/Database/Driver/TestDriver.php <ide> <ide> class TestDriver extends Sqlite <ide> { <add> /** <add> * @inheritDoc <add> */ <ide> public function enabled(): bool <ide> { <ide> return true; <ide><path>tests/test_app/TestApp/Http/Client/Adapter/CakeStreamWrapper.php <ide> <ide> use ArrayAccess; <ide> use Exception; <del>use ReturnTypeWillChange; <ide> <ide> class CakeStreamWrapper implements ArrayAccess <ide> { <ide> public function offsetExists($offset): bool <ide> /** <ide> * @inheritDoc <ide> */ <del> #[ReturnTypeWillChange] <add> #[\ReturnTypeWillChange] <ide> public function offsetGet($offset) <ide> { <ide> return $this->_data[$offset]; <ide><path>tests/test_app/TestApp/Http/Session/TestAppLibSession.php <ide> <ide> namespace TestApp\Http\Session; <ide> <del>use ReturnTypeWillChange; <ide> use SessionHandlerInterface; <ide> <ide> /** <ide> public function close(): bool <ide> /** <ide> * @inheritDoc <ide> */ <del> #[ReturnTypeWillChange] <add> #[\ReturnTypeWillChange] <ide> public function read($id) <ide> { <ide> } <ide> public function destroy($id): bool <ide> /** <ide> * @inheritDoc <ide> */ <del> #[ReturnTypeWillChange] <add> #[\ReturnTypeWillChange] <ide> public function gc($maxlifetime) <ide> { <ide> return 0;
22
Javascript
Javascript
add test for js1 build viewconfigs
3ccfbd6c399f4adc9b821f754c63b627dd71665d
<ide><path>packages/react-native-codegen/buck_tests/generate-view-configs-cli.js <ide> * This source code is licensed under the MIT license found in the <ide> * LICENSE file in the root directory of this source tree. <ide> * <del> * @emails oncall+react_native <ide> * @flow <ide> * @format <ide> */ <ide> <ide> 'use strict'; <ide> <ide> const generate = require('./generate-view-configs'); <add>const yargs = require('yargs'); <ide> <del>const [fileList] = process.argv.slice(2); <add>const yargv = yargs.strict().option('t', { <add> alias: 'test', <add> describe: 'Test the changes and do not write files', <add> requiresArg: false, <add> type: 'boolean', <add>}); <ide> <del>const CURRENT_VIEW_CONFIG_SCHEMAS = ['SliderSchema.js']; <add>const argv = yargv.argv; <add>const fileList = argv._[0].split('\n'); <add> <add>const CURRENT_VIEW_CONFIG_SCHEMAS = ['']; <ide> <ide> generate( <del> fileList <del> .split('\n') <del> .filter(fileName => <del> CURRENT_VIEW_CONFIG_SCHEMAS.find(supportedFileName => <del> fileName.endsWith(supportedFileName), <del> ), <add> fileList.filter(fileName => <add> CURRENT_VIEW_CONFIG_SCHEMAS.find(supportedFileName => <add> fileName.endsWith(supportedFileName), <ide> ), <add> ), <add> // $FlowFixMe Type argv <add> argv.test, <ide> ); <ide><path>packages/react-native-codegen/buck_tests/generate-view-configs.js <ide> const RNParser = require('../src/generators/RNParser.js'); <ide> <ide> const path = require('path'); <ide> <del>function generate(files: Array<string>): void { <del> files.forEach(filename => { <add>type Result = $ReadOnly<{| <add> libraryName: string, <add> success: boolean, <add>|}>; <add> <add>function generateFilesWithResults( <add> files: Array<string>, <add> test: boolean, <add>): Array<Result> { <add> return files.reduce((aggregated, filename) => { <ide> const schema = RNParser.parse(filename); <ide> if (schema && schema.modules) { <del> RNCodegen.generate( <add> const libraryName = path.basename(filename).replace('Schema.js', ''); <add> const success = RNCodegen.generate( <ide> { <ide> schema, <add> libraryName, <ide> outputDirectory: path.dirname(filename), <del> libraryName: path.basename(filename).replace('Schema.js', ''), <ide> }, <del> {generators: ['view-configs']}, <add> {generators: ['view-configs'], test}, <ide> ); <add> <add> aggregated.push({ <add> libraryName, <add> success, <add> }); <add> } <add> return aggregated; <add> }, []); <add>} <add> <add>function generate(files: Array<string>, test: boolean): void { <add> console.log(`${test ? 'Testing' : 'Generating'} view configs`); <add> <add> const results = generateFilesWithResults(files, test); <add> <add> const failed = results.filter(result => !result.success); <add> const totalCount = results.length; <add> <add> console.log(`\n${test ? 'Tested' : 'Generated'} ${totalCount} view configs`); <add> <add> if (failed.length) { <add> if (test === true) { <add> console.error(`${failed.length} configs changed`); <add> console.error("Please re-run 'js1 build viewconfigs'"); <ide> } <del> }); <add> process.exit(1); <add> } <ide> } <ide> <ide> module.exports = generate; <ide><path>packages/react-native-codegen/src/generators/RNCodegen.js <ide> type Generators = <ide> <ide> type Config = $ReadOnly<{| <ide> generators: Array<Generators>, <add> test?: boolean, <ide> |}>; <ide> <ide> const GENERATORS = { <ide> const GENERATORS = { <ide> 'view-configs': [generateViewConfigJs.generate], <ide> }; <ide> <del>function writeMapToFiles(map: Map<string, string>, outputDirectory: string) { <add>function writeMapToFiles(map: Map<string, string>, outputDir: string) { <add> let success = true; <ide> map.forEach((contents: string, fileName: string) => { <del> const location = path.join(outputDirectory, fileName); <del> fs.writeFileSync(location, contents); <add> try { <add> const location = path.join(outputDir, fileName); <add> fs.writeFileSync(location, contents); <add> } catch (error) { <add> success = false; <add> console.error(`Failed to write ${fileName} to ${outputDir}`, error); <add> } <ide> }); <add> <add> return success; <add>} <add> <add>function checkFilesForChanges( <add> map: Map<string, string>, <add> outputDir: string, <add>): boolean { <add> let hasChanged = false; <add> <add> map.forEach((contents: string, fileName: string) => { <add> const location = path.join(outputDir, fileName); <add> const currentContents = fs.readFileSync(location, 'utf8'); <add> if (currentContents !== contents) { <add> console.error(`- ${fileName} has changed`); <add> <add> hasChanged = true; <add> } <add> }); <add> <add> return !hasChanged; <ide> } <ide> <ide> module.exports = { <ide> generate( <ide> {libraryName, schema, outputDirectory}: Options, <del> {generators}: Config, <del> ) { <add> {generators, test}: Config, <add> ): boolean { <ide> schemaValidator.validate(schema); <ide> <ide> const generatedFiles = []; <ide> module.exports = { <ide> } <ide> } <ide> <del> writeMapToFiles(new Map([...generatedFiles]), outputDirectory); <add> const filesToUpdate = new Map([...generatedFiles]); <add> <add> if (test === true) { <add> return checkFilesForChanges(filesToUpdate, outputDirectory); <add> } <add> <add> return writeMapToFiles(filesToUpdate, outputDirectory); <ide> }, <ide> };
3
Ruby
Ruby
update documentation for default_scope
c4023cbe206415cf3ca1ca92cd9980a4aa4aed00
<ide><path>activerecord/lib/active_record/base.rb <ide> def subclasses #:nodoc: <ide> end <ide> <ide> # Sets the default options for the model. The format of the <del> # <tt>method_scoping</tt> argument is the same as in with_scope. <add> # <tt>options</tt> argument is the same as in find. <ide> # <ide> # class Person < ActiveRecord::Base <del> # default_scope :find => { :order => 'last_name, first_name' } <add> # default_scope :order => 'last_name, first_name' <ide> # end <ide> def default_scope(options = {}) <ide> self.default_scoping << { :find => options, :create => (options.is_a?(Hash) && options.has_key?(:conditions)) ? options[:conditions] : {} }
1
Ruby
Ruby
add tests for vendored deps
64a929184a45f530a49af7b047d5b6605b50b1f8
<ide><path>Library/Homebrew/rubocops/lines_cop.rb <ide> def audit_formula(_node, _class_node, _parent_class_node, body_node) <ide> problem "\"\#\{prefix}#{match[1]}\" should be \"\#{#{match[2].downcase}}\"" <ide> end <ide> end <add> find_every_method_call_by_name(body_node, :depends_on).each do |m| <add> key, value = destructure_hash(parameters(m).first) <add> next if (key.nil? || value.nil?) <add> next unless match = regex_match_group(value, %r{(lua|perl|python|ruby)(\d*)}) <add> problem "#{match[1]} modules should be vendored rather than use deprecated #{m.source}`" <add> end <ide> <del> # find_every_method_call_by_name(body_node, :depends_on) do |m| <del> # key, value = destructure_hash(paramters(m).first) <del> # next unless key.str_type? <del> # next unless match = regex_match_group(value, %r{(lua|perl|python|ruby)(\d*)}) <del> # problem "#{match[1]} modules should be vendored rather than use deprecated #{m.source}`" <del> # end <del> # <ide> # find_every_method_call_by_name(body_node, :system).each do |m| <ide> # next unless match = regex_match_group(parameters(m).first, %r{(env|export)(\s+)?}) <ide> # problem "Use ENV instead of invoking '#{match[1]}' to modify the environment" <ide> def modifier?(node) <ide> $(hash (pair $(str _) (array $(str _) ...)))} <ide> EOS <ide> <del> def_node_search :destructure_hash, <<-EOS.undent <del> (hash (pair $_ $_)) <add> def_node_matcher :destructure_hash, <<-EOS.undent <add> (hash (pair $(str _) $(sym _))) <ide> EOS <ide> <ide> def_node_search :formula_path_strings, <<-EOS.undent <ide><path>Library/Homebrew/test/rubocops/lines_cop_spec.rb <ide> def install <ide> end <ide> end <ide> <add> it "with dependecies which have to vendored" do <add> source = <<-EOS.undent <add> class Foo < Formula <add> desc "foo" <add> url 'http://example.com/foo-1.0.tgz' <add> depends_on "lpeg" => :lua51 <add> end <add> EOS <add> <add> expected_offenses = [{ message: "lua modules should be vendored rather than use deprecated depends_on \"lpeg\" => :lua51`", <add> severity: :convention, <add> line: 4, <add> column: 24, <add> source: source }] <add> <add> inspect_source(cop, source) <add> <add> expected_offenses.zip(cop.offenses).each do |expected, actual| <add> expect_offense(expected, actual) <add> end <add> end <add> <ide> end <ide> def expect_offense(expected, actual) <ide> expect(actual.message).to eq(expected[:message])
2
Java
Java
fix compiler error
1aeae5d40ddf87deb6268d5d470b5c59cba3c176
<ide><path>spring-web/src/main/java/org/springframework/http/codec/json/Jackson2SmileEncoder.java <ide> package org.springframework.http.codec.json; <ide> <ide> import java.nio.charset.StandardCharsets; <add>import java.util.Collections; <ide> import java.util.List; <ide> <ide> import com.fasterxml.jackson.databind.ObjectMapper;
1
Go
Go
improve the ut
e0de1718ee269776c7b23a1b03d796800ed4f451
<ide><path>integration-cli/docker_cli_events_unix_test.go <ide> func (s *DockerSuite) TestEventsContainerWithMultiNetwork(c *check.C) { <ide> out, _ := dockerCmd(c, "events", "--since", since, "--until", until, "-f", "type=network") <ide> netEvents := strings.Split(strings.TrimSpace(out), "\n") <ide> <del> // NOTE: order in which disconnect takes place is undetermined, <del> // so don't check for the *full* name <add> // received two network disconnect events <ide> c.Assert(len(netEvents), checker.Equals, 2) <ide> c.Assert(netEvents[0], checker.Contains, "disconnect") <del> c.Assert(netEvents[0], checker.Contains, "test-event-network-local-") <del> <ide> c.Assert(netEvents[1], checker.Contains, "disconnect") <del> c.Assert(netEvents[1], checker.Contains, "test-event-network-local-") <add> <add> //both networks appeared in the network event output <add> c.Assert(out, checker.Contains, "test-event-network-local-1") <add> c.Assert(out, checker.Contains, "test-event-network-local-2") <ide> } <ide> <ide> func (s *DockerSuite) TestEventsStreaming(c *check.C) {
1
Ruby
Ruby
add a /rails.rb for each framework for consistency
a23f4b6aeed6b49f90f5c544c818798840f090b7
<ide><path>actionpack/lib/action_controller/rails.rb <add>require "action_controller" <add> <ide> module ActionController <ide> class Plugin < Rails::Plugin <ide> plugin_name :action_controller <ide><path>actionpack/lib/action_view/rails.rb <add>require "action_view" <ide>\ No newline at end of file <ide><path>activemodel/lib/active_model/rails.rb <add>require "active_model" <ide>\ No newline at end of file <ide><path>activerecord/lib/active_record/rails.rb <ide> # rails, so let's make sure that it gets required before <ide> # here. This is needed for correctly setting up the middleware. <ide> # In the future, this might become an optional require. <add>require "active_record" <ide> require "action_controller/rails" <ide> <ide> module ActiveRecord <ide><path>activeresource/lib/active_resource/rails.rb <add>require "active_resource" <ide>\ No newline at end of file <ide><path>railties/lib/rails.rb <ide> require "rails/core" <ide> <del>%w(active_model active_record action_controller action_view action_mailer active_resource).each do |framework| <add>%w( <add> active_model <add> active_record <add> action_controller <add> action_view <add> action_mailer <add> active_resource <add>).each do |framework| <ide> begin <del> require framework <ide> require "#{framework}/rails" <ide> rescue LoadError <ide> end <ide><path>railties/lib/rails/generators/rails/app/templates/config/boot.rb <ide> end <ide> <ide> require 'rails' <del># To skip frameworks you're not going to use, remove require "rails" and <del># list the frameworks that you are going to use. <add># To skip frameworks you're not going to use, change require "rails" <add># to require "rails/core" and list the frameworks that you are going <add># to use. <ide> # <add># require "rails/core" <ide> # require "active_model/rails" <ide> # require "active_record/rails" <ide> # require "action_controller/rails"
7
PHP
PHP
fix serverrequesttest cases
f1a647f42ff27b9f403c19c9035b0f0918d70590
<ide><path>tests/TestCase/Http/ServerRequestTest.php <ide> public function testCustomArgsDetector() <ide> return $request->param('controller') === $name; <ide> }); <ide> <del> $request->params = ['controller' => 'cake']; <add> $request = $request->withQueryParams(['controller' => 'cake']); <ide> $this->assertTrue($request->is('controller', 'cake')); <ide> $this->assertFalse($request->is('controller', 'nonExistingController')); <ide> $this->assertTrue($request->isController('cake')); <ide> public function testHeaderDetector() <ide> $request = new ServerRequest(); <ide> $request->addDetector('host', ['header' => ['host' => 'cakephp.org']]); <ide> <del> $request->env('HTTP_HOST', 'cakephp.org'); <add> $request = $request->withEnv('HTTP_HOST', 'cakephp.org'); <ide> $this->assertTrue($request->is('host')); <ide> <del> $request->env('HTTP_HOST', 'php.net'); <add> $request = $request->withEnv('HTTP_HOST', 'php.net'); <ide> $this->assertFalse($request->is('host')); <ide> } <ide> <ide> public function testHeaderDetector() <ide> public function testExtensionDetector() <ide> { <ide> $request = new ServerRequest(); <del> $request->params['_ext'] = 'json'; <add> $request = $request->withParam('_ext', 'json'); <ide> $this->assertTrue($request->is('json')); <ide> <ide> $request = new ServerRequest(); <del> $request->params['_ext'] = 'xml'; <add> $request = $request->withParam('_ext', 'xml'); <ide> $this->assertFalse($request->is('json')); <ide> } <ide> <ide> public function testExtensionDetector() <ide> public function testAcceptHeaderDetector() <ide> { <ide> $request = new ServerRequest(); <del> $request->env('HTTP_ACCEPT', 'application/json, text/plain, */*'); <add> $request = $request->withEnv('HTTP_ACCEPT', 'application/json, text/plain, */*'); <ide> $this->assertTrue($request->is('json')); <ide> <ide> $request = new ServerRequest(); <del> $request->env('HTTP_ACCEPT', 'text/plain, */*'); <add> $request = $request->withEnv('HTTP_ACCEPT', 'text/plain, */*'); <ide> $this->assertFalse($request->is('json')); <ide> } <ide> <ide> public function testUrlInPath() <ide> public function testAddParams() <ide> { <ide> $request = new ServerRequest(); <del> $request->params = ['controller' => 'posts', 'action' => 'view']; <add> $request = $request <add> ->withParam('controller', 'posts') <add> ->withParam('action', 'view'); <ide> $result = $request->addParams(['plugin' => null, 'action' => 'index']); <ide> <ide> $this->assertSame($result, $request, 'Method did not return itself. %s'); <ide> <del> $this->assertEquals('posts', $request->controller); <del> $this->assertEquals('index', $request->action); <del> $this->assertEquals(null, $request->plugin); <add> $this->assertEquals('posts', $request->getParam('controller')); <add> $this->assertEquals('index', $request->getParam('action')); <add> $this->assertEquals(null, $request->getParam('plugin')); <ide> } <ide> <ide> /** <ide> public function testMethodOverrides() <ide> { <ide> $post = ['_method' => 'POST']; <ide> $request = new ServerRequest(compact('post')); <del> $this->assertEquals('POST', $request->env('REQUEST_METHOD')); <add> $this->assertEquals('POST', $request->getEnv('REQUEST_METHOD')); <ide> <ide> $post = ['_method' => 'DELETE']; <ide> $request = new ServerRequest(compact('post')); <del> $this->assertEquals('DELETE', $request->env('REQUEST_METHOD')); <add> $this->assertEquals('DELETE', $request->getEnv('REQUEST_METHOD')); <ide> <ide> $request = new ServerRequest(['environment' => ['HTTP_X_HTTP_METHOD_OVERRIDE' => 'PUT']]); <del> $this->assertEquals('PUT', $request->env('REQUEST_METHOD')); <add> $this->assertEquals('PUT', $request->getEnv('REQUEST_METHOD')); <ide> <ide> $request = new ServerRequest([ <ide> 'environment' => ['REQUEST_METHOD' => 'POST'], <ide> 'post' => ['_method' => 'PUT'] <ide> ]); <del> $this->assertEquals('PUT', $request->env('REQUEST_METHOD')); <del> $this->assertEquals('POST', $request->env('ORIGINAL_REQUEST_METHOD')); <add> $this->assertEquals('PUT', $request->getEnv('REQUEST_METHOD')); <add> $this->assertEquals('POST', $request->getEnv('ORIGINAL_REQUEST_METHOD')); <ide> } <ide> <ide> /** <ide> * Tests the env() method returning a default value in case the requested environment variable is not set. <ide> */ <ide> public function testDefaultEnvValue() <ide> { <del> $_ENV['DOES_NOT_EXIST'] = null; <del> $request = new ServerRequest(); <del> $this->assertNull($request->env('DOES_NOT_EXIST')); <del> $this->assertEquals('default', $request->env('DOES_NOT_EXIST', null, 'default')); <del> <del> $_ENV['DOES_EXIST'] = 'some value'; <del> $request = new ServerRequest(); <del> $this->assertEquals('some value', $request->env('DOES_EXIST')); <del> $this->assertEquals('some value', $request->env('DOES_EXIST', null, 'default')); <del> <del> $_ENV['EMPTY_VALUE'] = ''; <del> $request = new ServerRequest(); <del> $this->assertEquals('', $request->env('EMPTY_VALUE')); <del> $this->assertEquals('', $request->env('EMPTY_VALUE', null, 'default')); <del> <del> $_ENV['ZERO'] = '0'; <del> $request = new ServerRequest(); <del> $this->assertEquals('0', $request->env('ZERO')); <del> $this->assertEquals('0', $request->env('ZERO', null, 'default')); <add> $this->deprecated(function () { <add> $_ENV['DOES_NOT_EXIST'] = null; <add> $request = new ServerRequest(); <add> $this->assertNull($request->getEnv('DOES_NOT_EXIST')); <add> $this->assertEquals('default', $request->env('DOES_NOT_EXIST', null, 'default')); <add> <add> $_ENV['DOES_EXIST'] = 'some value'; <add> $request = new ServerRequest(); <add> $this->assertEquals('some value', $request->env('DOES_EXIST')); <add> $this->assertEquals('some value', $request->env('DOES_EXIST', null, 'default')); <add> <add> $_ENV['EMPTY_VALUE'] = ''; <add> $request = new ServerRequest(); <add> $this->assertEquals('', $request->env('EMPTY_VALUE')); <add> $this->assertEquals('', $request->env('EMPTY_VALUE', null, 'default')); <add> <add> $_ENV['ZERO'] = '0'; <add> $request = new ServerRequest(); <add> $this->assertEquals('0', $request->env('ZERO')); <add> $this->assertEquals('0', $request->env('ZERO', null, 'default')); <add> }); <ide> } <ide> <ide> /** <ide> public function testIsHttpMethods() <ide> <ide> $this->assertFalse($request->is('undefined-behavior')); <ide> <del> $request->env('REQUEST_METHOD', 'GET'); <add> $request = $request->withEnv('REQUEST_METHOD', 'GET'); <ide> $this->assertTrue($request->is('get')); <ide> <del> $request->env('REQUEST_METHOD', 'POST'); <add> $request = $request->withEnv('REQUEST_METHOD', 'POST'); <ide> $this->assertTrue($request->is('POST')); <ide> <del> $request->env('REQUEST_METHOD', 'PUT'); <add> $request = $request->withEnv('REQUEST_METHOD', 'PUT'); <ide> $this->assertTrue($request->is('put')); <ide> $this->assertFalse($request->is('get')); <ide> <del> $request->env('REQUEST_METHOD', 'DELETE'); <add> $request = $request->withEnv('REQUEST_METHOD', 'DELETE'); <ide> $this->assertTrue($request->is('delete')); <ide> $this->assertTrue($request->isDelete()); <ide> <del> $request->env('REQUEST_METHOD', 'delete'); <add> $request = $request->withEnv('REQUEST_METHOD', 'delete'); <ide> $this->assertFalse($request->is('delete')); <ide> } <ide> <ide> public function testIsHttpMethods() <ide> public function testIsJsonAndXml() <ide> { <ide> $request = new ServerRequest(); <del> $request->env('HTTP_ACCEPT', 'application/json, text/plain, */*'); <add> $request = $request->withEnv('HTTP_ACCEPT', 'application/json, text/plain, */*'); <ide> $this->assertTrue($request->is('json')); <ide> <ide> $request = new ServerRequest(); <del> $request->env('HTTP_ACCEPT', 'application/xml, text/plain, */*'); <add> $request = $request->withEnv('HTTP_ACCEPT', 'application/xml, text/plain, */*'); <ide> $this->assertTrue($request->is('xml')); <ide> <ide> $request = new ServerRequest(); <del> $request->env('HTTP_ACCEPT', 'text/xml, */*'); <add> $request = $request->withEnv('HTTP_ACCEPT', 'text/xml, */*'); <ide> $this->assertTrue($request->is('xml')); <ide> } <ide> <ide> public function testIsMultiple() <ide> { <ide> $request = new ServerRequest(); <ide> <del> $request->env('REQUEST_METHOD', 'GET'); <add> $request = $request->withEnv('REQUEST_METHOD', 'GET'); <ide> $this->assertTrue($request->is(['get', 'post'])); <ide> <del> $request->env('REQUEST_METHOD', 'POST'); <add> $request = $request->withEnv('REQUEST_METHOD', 'POST'); <ide> $this->assertTrue($request->is(['get', 'post'])); <ide> <del> $request->env('REQUEST_METHOD', 'PUT'); <add> $request = $request->withEnv('REQUEST_METHOD', 'PUT'); <ide> $this->assertFalse($request->is(['get', 'post'])); <ide> } <ide> <ide> public function testIsAll() <ide> { <ide> $request = new ServerRequest(); <ide> <del> $request->env('HTTP_X_REQUESTED_WITH', 'XMLHttpRequest'); <del> $request->env('REQUEST_METHOD', 'GET'); <add> $request = $request->withEnv('HTTP_X_REQUESTED_WITH', 'XMLHttpRequest'); <add> $request = $request->withEnv('REQUEST_METHOD', 'GET'); <ide> <ide> $this->assertTrue($request->isAll(['ajax', 'get'])); <ide> $this->assertFalse($request->isAll(['post', 'get'])); <ide> public function testIsAll() <ide> */ <ide> public function testMethod() <ide> { <del> $request = new ServerRequest(['environment' => ['REQUEST_METHOD' => 'delete']]); <add> $this->deprecated(function () { <add> $request = new ServerRequest(['environment' => ['REQUEST_METHOD' => 'delete']]); <ide> <del> $this->assertEquals('delete', $request->method()); <add> $this->assertEquals('delete', $request->method()); <add> }); <ide> } <ide> <ide> /** <ide> public function testPort() <ide> <ide> $this->assertEquals('80', $request->port()); <ide> <del> $request->env('SERVER_PORT', '443'); <del> $request->env('HTTP_X_FORWARDED_PORT', '80'); <add> $request = $request->withEnv('SERVER_PORT', '443'); <add> $request = $request->withEnv('HTTP_X_FORWARDED_PORT', '80'); <ide> $this->assertEquals('443', $request->port()); <ide> <ide> $request->trustProxy = true; <ide> public function testDomain() <ide> <ide> $this->assertEquals('example.com', $request->domain()); <ide> <del> $request->env('HTTP_HOST', 'something.example.co.uk'); <add> $request = $request->withEnv('HTTP_HOST', 'something.example.co.uk'); <ide> $this->assertEquals('example.co.uk', $request->domain(2)); <ide> } <ide> <ide> public function testScheme() <ide> <ide> $this->assertEquals('https', $request->scheme()); <ide> <del> $request->env('HTTPS', ''); <add> $request = $request->withEnv('HTTPS', ''); <ide> $this->assertEquals('http', $request->scheme()); <ide> <del> $request->env('HTTP_X_FORWARDED_PROTO', 'https'); <add> $request = $request->withEnv('HTTP_X_FORWARDED_PROTO', 'https'); <ide> $request->trustProxy = true; <ide> $this->assertEquals('https', $request->scheme()); <ide> } <ide> public function testSubdomain() <ide> <ide> $this->assertEquals(['something'], $request->subdomains()); <ide> <del> $request->env('HTTP_HOST', 'www.something.example.com'); <add> $request = $request->withEnv('HTTP_HOST', 'www.something.example.com'); <ide> $this->assertEquals(['www', 'something'], $request->subdomains()); <ide> <del> $request->env('HTTP_HOST', 'www.something.example.co.uk'); <add> $request = $request->withEnv('HTTP_HOST', 'www.something.example.co.uk'); <ide> $this->assertEquals(['www', 'something'], $request->subdomains(2)); <ide> <del> $request->env('HTTP_HOST', 'example.co.uk'); <add> $request = $request->withEnv('HTTP_HOST', 'example.co.uk'); <ide> $this->assertEquals([], $request->subdomains(2)); <ide> } <ide> <ide> public function testisAjaxFlashAndFriends() <ide> { <ide> $request = new ServerRequest(); <ide> <del> $request->env('HTTP_USER_AGENT', 'Shockwave Flash'); <add> $request = $request->withEnv('HTTP_USER_AGENT', 'Shockwave Flash'); <ide> $this->assertTrue($request->is('flash')); <ide> <del> $request->env('HTTP_USER_AGENT', 'Adobe Flash'); <add> $request = $request->withEnv('HTTP_USER_AGENT', 'Adobe Flash'); <ide> $this->assertTrue($request->is('flash')); <ide> <del> $request->env('HTTP_X_REQUESTED_WITH', 'XMLHttpRequest'); <add> $request = $request->withEnv('HTTP_X_REQUESTED_WITH', 'XMLHttpRequest'); <ide> $this->assertTrue($request->is('ajax')); <ide> <del> $request->env('HTTP_X_REQUESTED_WITH', 'XMLHTTPREQUEST'); <add> $request = $request->withEnv('HTTP_X_REQUESTED_WITH', 'XMLHTTPREQUEST'); <ide> $this->assertFalse($request->is('ajax')); <ide> $this->assertFalse($request->isAjax()); <ide> } <ide> public function testIsSsl() <ide> { <ide> $request = new ServerRequest(); <ide> <del> $request->env('HTTPS', 1); <add> $request = $request->withEnv('HTTPS', 1); <ide> $this->assertTrue($request->is('ssl')); <ide> <del> $request->env('HTTPS', 'on'); <add> $request = $request->withEnv('HTTPS', 'on'); <ide> $this->assertTrue($request->is('ssl')); <ide> <del> $request->env('HTTPS', '1'); <add> $request = $request->withEnv('HTTPS', '1'); <ide> $this->assertTrue($request->is('ssl')); <ide> <del> $request->env('HTTPS', 'I am not empty'); <add> $request = $request->withEnv('HTTPS', 'I am not empty'); <ide> $this->assertFalse($request->is('ssl')); <ide> <del> $request->env('HTTPS', 'off'); <add> $request = $request->withEnv('HTTPS', 'off'); <ide> $this->assertFalse($request->is('ssl')); <ide> <del> $request->env('HTTPS', false); <add> $request = $request->withEnv('HTTPS', false); <ide> $this->assertFalse($request->is('ssl')); <ide> <del> $request->env('HTTPS', ''); <add> $request = $request->withEnv('HTTPS', ''); <ide> $this->assertFalse($request->is('ssl')); <ide> } <ide> <ide> public function testIsSsl() <ide> */ <ide> public function testMagicget() <ide> { <del> $request = new ServerRequest(); <del> $request->params = ['controller' => 'posts', 'action' => 'view', 'plugin' => 'blogs']; <add> $this->deprecated(function () { <add> $request = new ServerRequest(); <add> $request->params = ['controller' => 'posts', 'action' => 'view', 'plugin' => 'blogs']; <ide> <del> $this->assertEquals('posts', $request->controller); <del> $this->assertEquals('view', $request->action); <del> $this->assertEquals('blogs', $request->plugin); <del> $this->assertNull($request->banana); <add> $this->assertEquals('posts', $request->controller); <add> $this->assertEquals('view', $request->action); <add> $this->assertEquals('blogs', $request->plugin); <add> $this->assertNull($request->banana); <add> }); <ide> } <ide> <ide> /** <ide> public function testMagicget() <ide> */ <ide> public function testMagicisset() <ide> { <del> $request = new ServerRequest(); <del> $request->params = [ <del> 'controller' => 'posts', <del> 'action' => 'view', <del> 'plugin' => 'blogs', <del> ]; <del> <del> $this->assertTrue(isset($request->controller)); <del> $this->assertFalse(isset($request->notthere)); <del> $this->assertNotEmpty($request->controller); <add> $this->deprecated(function () { <add> $request = new ServerRequest(); <add> $request->params = [ <add> 'controller' => 'posts', <add> 'action' => 'view', <add> 'plugin' => 'blogs', <add> ]; <add> <add> $this->assertTrue(isset($request->controller)); <add> $this->assertFalse(isset($request->notthere)); <add> $this->assertNotEmpty($request->controller); <add> }); <ide> } <ide> <ide> /** <ide> public function testMagicisset() <ide> */ <ide> public function testArrayAccess() <ide> { <del> $request = new ServerRequest(); <del> $request->params = ['controller' => 'posts', 'action' => 'view', 'plugin' => 'blogs']; <add> $this->deprecated(function () { <add> $request = new ServerRequest(); <add> $request->params = ['controller' => 'posts', 'action' => 'view', 'plugin' => 'blogs']; <ide> <del> $this->assertEquals('posts', $request['controller']); <add> $this->assertEquals('posts', $request['controller']); <ide> <del> $request['slug'] = 'speedy-slug'; <del> $this->assertEquals('speedy-slug', $request->slug); <del> $this->assertEquals('speedy-slug', $request['slug']); <add> $request['slug'] = 'speedy-slug'; <add> $this->assertEquals('speedy-slug', $request->slug); <add> $this->assertEquals('speedy-slug', $request['slug']); <ide> <del> $this->assertTrue(isset($request['action'])); <del> $this->assertFalse(isset($request['wrong-param'])); <add> $this->assertTrue(isset($request['action'])); <add> $this->assertFalse(isset($request['wrong-param'])); <ide> <del> $this->assertTrue(isset($request['plugin'])); <del> unset($request['plugin']); <del> $this->assertFalse(isset($request['plugin'])); <del> $this->assertNull($request['plugin']); <del> $this->assertNull($request->plugin); <add> $this->assertTrue(isset($request['plugin'])); <add> unset($request['plugin']); <add> $this->assertFalse(isset($request['plugin'])); <add> $this->assertNull($request['plugin']); <add> $this->assertNull($request->plugin); <ide> <del> $request = new ServerRequest(['url' => 'some/path?one=something&two=else']); <del> $this->assertTrue(isset($request['url']['one'])); <add> $request = new ServerRequest(['url' => 'some/path?one=something&two=else']); <add> $this->assertTrue(isset($request['url']['one'])); <ide> <del> $request->data = ['Post' => ['title' => 'something']]; <del> $this->assertEquals('something', $request['data']['Post']['title']); <add> $request->data = ['Post' => ['title' => 'something']]; <add> $this->assertEquals('something', $request['data']['Post']['title']); <add> }); <ide> } <ide> <ide> /** <ide> public function testHeader() <ide> 'HTTP_CONTENT_MD5' => 'abc123' <ide> ]]); <ide> <del> $this->assertEquals($request->env('HTTP_HOST'), $request->header('host')); <del> $this->assertEquals($request->env('HTTP_USER_AGENT'), $request->header('User-Agent')); <del> $this->assertEquals($request->env('CONTENT_LENGTH'), $request->header('content-length')); <del> $this->assertEquals($request->env('CONTENT_TYPE'), $request->header('content-type')); <del> $this->assertEquals($request->env('HTTP_CONTENT_MD5'), $request->header('content-md5')); <add> $this->assertEquals($request->getEnv('HTTP_HOST'), $request->getHeaderLine('host')); <add> $this->assertEquals($request->getEnv('HTTP_USER_AGENT'), $request->getHeaderLine('User-Agent')); <add> $this->assertEquals($request->getEnv('CONTENT_LENGTH'), $request->getHeaderLine('content-length')); <add> $this->assertEquals($request->getEnv('CONTENT_TYPE'), $request->getHeaderLine('content-type')); <add> $this->assertEquals($request->getEnv('HTTP_CONTENT_MD5'), $request->getHeaderLine('content-md5')); <ide> } <ide> <ide> /** <ide> public function testGetHeader() <ide> ]]); <ide> $this->assertEquals([], $request->getHeader('Not-there')); <ide> <del> $expected = [$request->env('HTTP_HOST')]; <add> $expected = [$request->getEnv('HTTP_HOST')]; <ide> $this->assertEquals($expected, $request->getHeader('Host')); <ide> $this->assertEquals($expected, $request->getHeader('host')); <ide> $this->assertEquals($expected, $request->getHeader('HOST')); <ide> public function testGetHeaderLine() <ide> ]]); <ide> $this->assertEquals('', $request->getHeaderLine('Authorization')); <ide> <del> $expected = $request->env('CONTENT_LENGTH'); <add> $expected = $request->getEnv('CONTENT_LENGTH'); <ide> $this->assertEquals($expected, $request->getHeaderLine('Content-Length')); <ide> $this->assertEquals($expected, $request->getHeaderLine('content-Length')); <ide> $this->assertEquals($expected, $request->getHeaderLine('ConTent-LenGth')); <ide> public function testWithHeader() <ide> <ide> $this->assertEquals(1337, $request->getHeaderLine('Content-length'), 'old request is unchanged'); <ide> $this->assertEquals(999, $new->getHeaderLine('Content-length'), 'new request is correct'); <del> $this->assertEquals(999, $new->header('Content-Length')); <add> $this->deprecated(function () use ($new) { <add> $this->assertEquals(999, $new->header('Content-Length')); <add> }); <ide> <ide> $new = $request->withHeader('Double', ['a']); <ide> $this->assertEquals(['a'], $new->getHeader('Double'), 'List values are overwritten'); <del> $this->assertEquals(['a'], $new->header('Double'), 'headers written in bc way.'); <add> <add> $this->deprecated(function () use ($new) { <add> $this->assertEquals(['a'], $new->header('Double'), 'headers written in bc way.'); <add> }); <ide> } <ide> <ide> /** <ide> public function testGetParamsWithDot() <ide> $_SERVER['REQUEST_URI'] = '/posts/index/add.add'; <ide> $request = ServerRequestFactory::fromGlobals(); <ide> $this->assertEquals('', $request->base); <del> $this->assertEquals([], $request->query); <add> $this->assertEquals([], $request->getQueryParams()); <ide> <ide> $_GET = []; <ide> $_GET['/cake_dev/posts/index/add_add'] = ''; <ide> $_SERVER['PHP_SELF'] = '/cake_dev/webroot/index.php'; <ide> $_SERVER['REQUEST_URI'] = '/cake_dev/posts/index/add.add'; <ide> $request = ServerRequestFactory::fromGlobals(); <ide> $this->assertEquals('/cake_dev', $request->base); <del> $this->assertEquals([], $request->query); <add> $this->assertEquals([], $request->getQueryParams()); <ide> } <ide> <ide> /** <ide> public function testGetParamWithUrlencodedElement() <ide> $_SERVER['REQUEST_URI'] = '/posts/add/%E2%88%82%E2%88%82'; <ide> $request = ServerRequestFactory::fromGlobals(); <ide> $this->assertEquals('', $request->base); <del> $this->assertEquals([], $request->query); <add> $this->assertEquals([], $request->getQueryParams()); <ide> <ide> $_GET = []; <ide> $_GET['/cake_dev/posts/add/∂∂'] = ''; <ide> $_SERVER['PHP_SELF'] = '/cake_dev/webroot/index.php'; <ide> $_SERVER['REQUEST_URI'] = '/cake_dev/posts/add/%E2%88%82%E2%88%82'; <ide> $request = ServerRequestFactory::fromGlobals(); <ide> $this->assertEquals('/cake_dev', $request->base); <del> $this->assertEquals([], $request->query); <add> $this->assertEquals([], $request->getQueryParams()); <ide> } <ide> <ide> /** <ide> public function testParamWriting() <ide> 'action' => 'index', <ide> ]); <ide> <del> $this->assertInstanceOf('Cake\Http\ServerRequest', $request->param('some', 'thing'), 'Method has not returned $this'); <add> $this->assertInstanceOf( <add> 'Cake\Http\ServerRequest', <add> $request->withParam('some', 'thing'), <add> 'Method has not returned $this' <add> ); <ide> <ide> $request->param('Post.null', null); <del> $this->assertNull($request->params['Post']['null']); <add> $this->assertNull($request->getQueryParams()['Post']['null']); <ide> <ide> $request->param('Post.false', false); <del> $this->assertFalse($request->params['Post']['false']); <add> $this->assertFalse($request->getQueryParams()['Post']['false']); <ide> <ide> $request->param('Post.zero', 0); <del> $this->assertSame(0, $request->params['Post']['zero']); <add> $this->assertSame(0, $request->getQueryParams()['Post']['zero']); <ide> <ide> $request->param('Post.empty', ''); <del> $this->assertSame('', $request->params['Post']['empty']); <add> $this->assertSame('', $request->getQueryParams()['Post']['empty']); <ide> <del> $this->assertSame('index', $request->action); <add> $this->assertSame('index', $request->getParam('action')); <ide> $request->param('action', 'edit'); <del> $this->assertSame('edit', $request->action); <add> $this->assertSame('edit', $request->getParam('action')); <ide> } <ide> <ide> /** <ide> public function testAcceptLanguage() <ide> $request = new ServerRequest(); <ide> <ide> // Weird language <del> $request->env('HTTP_ACCEPT_LANGUAGE', 'inexistent,en-ca'); <add> $request = $request->withEnv('HTTP_ACCEPT_LANGUAGE', 'inexistent,en-ca'); <ide> $result = $request->acceptLanguage(); <ide> $this->assertEquals(['inexistent', 'en-ca'], $result, 'Languages do not match'); <ide> <ide> // No qualifier <del> $request->env('HTTP_ACCEPT_LANGUAGE', 'es_mx,en_ca'); <add> $request = $request->withEnv('HTTP_ACCEPT_LANGUAGE', 'es_mx,en_ca'); <ide> $result = $request->acceptLanguage(); <ide> $this->assertEquals(['es-mx', 'en-ca'], $result, 'Languages do not match'); <ide> <ide> // With qualifier <del> $request->env('HTTP_ACCEPT_LANGUAGE', 'en-US,en;q=0.8,pt-BR;q=0.6,pt;q=0.4'); <add> $request = $request->withEnv('HTTP_ACCEPT_LANGUAGE', 'en-US,en;q=0.8,pt-BR;q=0.6,pt;q=0.4'); <ide> $result = $request->acceptLanguage(); <ide> $this->assertEquals(['en-us', 'en', 'pt-br', 'pt'], $result, 'Languages do not match'); <ide> <ide> // With spaces <del> $request->env('HTTP_ACCEPT_LANGUAGE', 'da, en-gb;q=0.8, en;q=0.7'); <add> $request = $request->withEnv('HTTP_ACCEPT_LANGUAGE', 'da, en-gb;q=0.8, en;q=0.7'); <ide> $result = $request->acceptLanguage(); <ide> $this->assertEquals(['da', 'en-gb', 'en'], $result, 'Languages do not match'); <ide> <ide> // Checking if requested <del> $request->env('HTTP_ACCEPT_LANGUAGE', 'es_mx,en_ca'); <del> $result = $request->acceptLanguage(); <add> $request = $request->withEnv('HTTP_ACCEPT_LANGUAGE', 'es_mx,en_ca'); <ide> <ide> $result = $request->acceptLanguage('en-ca'); <ide> $this->assertTrue($result); <ide> public function testAcceptLanguage() <ide> */ <ide> public function testHere() <ide> { <del> Configure::write('App.base', '/base_path'); <del> $q = ['test' => 'value']; <del> $request = new ServerRequest([ <del> 'query' => $q, <del> 'url' => '/posts/add/1/value', <del> 'base' => '/base_path' <del> ]); <del> <del> $result = $request->here(); <del> $this->assertEquals('/base_path/posts/add/1/value?test=value', $result); <del> <del> $result = $request->here(false); <del> $this->assertEquals('/posts/add/1/value?test=value', $result); <del> <del> $request = new ServerRequest([ <del> 'url' => '/posts/base_path/1/value', <del> 'query' => ['test' => 'value'], <del> 'base' => '/base_path' <del> ]); <del> $result = $request->here(); <del> $this->assertEquals('/base_path/posts/base_path/1/value?test=value', $result); <del> <del> $result = $request->here(false); <del> $this->assertEquals('/posts/base_path/1/value?test=value', $result); <add> $this->deprecated(function () { <add> Configure::write('App.base', '/base_path'); <add> $q = ['test' => 'value']; <add> $request = new ServerRequest([ <add> 'query' => $q, <add> 'url' => '/posts/add/1/value', <add> 'base' => '/base_path' <add> ]); <add> <add> $result = $request->here(); <add> $this->assertEquals('/base_path/posts/add/1/value?test=value', $result); <add> <add> $result = $request->here(false); <add> $this->assertEquals('/posts/add/1/value?test=value', $result); <add> <add> $request = new ServerRequest([ <add> 'url' => '/posts/base_path/1/value', <add> 'query' => ['test' => 'value'], <add> 'base' => '/base_path' <add> ]); <add> $result = $request->here(); <add> $this->assertEquals('/base_path/posts/base_path/1/value?test=value', $result); <add> <add> $result = $request->here(false); <add> $this->assertEquals('/posts/base_path/1/value?test=value', $result); <add> }); <ide> } <ide> <ide> /** <ide> public function testHere() <ide> */ <ide> public function testHereWithSpaceInUrl() <ide> { <del> Configure::write('App.base', ''); <del> $_GET = ['/admin/settings/settings/prefix/Access_Control' => '']; <del> $request = new ServerRequest('/admin/settings/settings/prefix/Access%20Control'); <add> $this->deprecated(function () { <add> Configure::write('App.base', ''); <add> $_GET = ['/admin/settings/settings/prefix/Access_Control' => '']; <add> $request = new ServerRequest('/admin/settings/settings/prefix/Access%20Control'); <ide> <del> $result = $request->here(); <del> $this->assertEquals('/admin/settings/settings/prefix/Access%20Control', $result); <add> $result = $request->here(); <add> $this->assertEquals('/admin/settings/settings/prefix/Access%20Control', $result); <add> }); <ide> } <ide> <ide> /** <ide> public function testHereWithSpaceInUrl() <ide> */ <ide> public function testSetInput() <ide> { <del> $request = new ServerRequest(); <add> $this->deprecated(function () { <add> $request = new ServerRequest(); <ide> <del> $request->setInput('I came from setInput'); <del> $result = $request->input(); <del> $this->assertEquals('I came from setInput', $result); <add> $request->setInput('I came from setInput'); <add> $result = $request->input(); <add> $this->assertEquals('I came from setInput', $result); <add> }); <ide> } <ide> <ide> /** <ide> public function testGetCookie() <ide> ] <ide> ] <ide> ]); <del> $this->assertEquals('A value in the cookie', $request->cookie('testing')); <add> <add> $this->deprecated(function () use ($request) { <add> $this->assertEquals('A value in the cookie', $request->cookie('testing')); <add> }); <ide> $this->assertEquals('A value in the cookie', $request->getCookie('testing')); <ide> <del> $this->assertNull($request->cookie('not there')); <add> $this->deprecated(function () use ($request) { <add> $this->assertNull($request->cookie('not there')); <add> }); <add> <ide> $this->assertNull($request->getCookie('not there')); <ide> $this->assertSame('default', $request->getCookie('not there', 'default')); <ide> <ide> public function testAllowMethod() <ide> <ide> $this->assertTrue($request->allowMethod('put')); <ide> <del> $request->env('REQUEST_METHOD', 'DELETE'); <add> $request = $request->withEnv('REQUEST_METHOD', 'DELETE'); <ide> $this->assertTrue($request->allowMethod(['post', 'delete'])); <ide> } <ide> <ide> public function testAllowMethodException() <ide> */ <ide> public function testSession() <ide> { <del> $session = new Session; <del> $request = new ServerRequest(['session' => $session]); <del> $this->assertSame($session, $request->session()); <add> $this->deprecated(function () { <add> $session = new Session; <add> $request = new ServerRequest(['session' => $session]); <add> $this->assertSame($session, $request->session()); <ide> <del> $request = ServerRequestFactory::fromGlobals(); <del> $this->assertEquals($session, $request->session()); <add> $request = ServerRequestFactory::fromGlobals(); <add> $this->assertEquals($session, $request->session()); <add> }); <ide> } <ide> <ide> /** <ide> public function testMethodOverrideEmptyData() <ide> 'post' => $post, <ide> 'environment' => ['REQUEST_METHOD' => 'POST'] <ide> ]); <del> $this->assertEmpty($request->data); <add> $this->assertEmpty($request->getData()); <ide> <ide> $post = ['_method' => 'GET', 'foo' => 'bar']; <ide> $request = new ServerRequest([ <ide> public function testMethodOverrideEmptyData() <ide> 'HTTP_X_HTTP_METHOD_OVERRIDE' => 'GET' <ide> ] <ide> ]); <del> $this->assertEmpty($request->data); <add> $this->assertEmpty($request->getData()); <ide> } <ide> <ide> /** <ide> public function testWithParam() <ide> ]); <ide> $result = $request->withParam('action', 'view'); <ide> $this->assertNotSame($result, $request, 'New instance should be made'); <del> $this->assertFalse($request->param('action'), 'No side-effect on original'); <del> $this->assertSame('view', $result->param('action')); <add> $this->assertFalse($request->getParam('action'), 'No side-effect on original'); <add> $this->assertSame('view', $result->getParam('action')); <ide> <ide> $result = $request->withParam('action', 'index') <ide> ->withParam('plugin', 'DebugKit') <ide> ->withParam('prefix', 'Admin'); <ide> $this->assertNotSame($result, $request, 'New instance should be made'); <del> $this->assertFalse($request->param('action'), 'No side-effect on original'); <del> $this->assertSame('index', $result->param('action')); <del> $this->assertSame('DebugKit', $result->param('plugin')); <del> $this->assertSame('Admin', $result->param('prefix')); <add> $this->assertFalse($request->getParam('action'), 'No side-effect on original'); <add> $this->assertSame('index', $result->getParam('action')); <add> $this->assertSame('DebugKit', $result->getParam('plugin')); <add> $this->assertSame('Admin', $result->getParam('prefix')); <ide> } <ide> <ide> /** <ide> public function testWithData() <ide> ] <ide> ]); <ide> $result = $request->withData('Model.new_value', 'new value'); <del> $this->assertNull($request->data('Model.new_value'), 'Original request should not change.'); <add> $this->assertNull($request->getData('Model.new_value'), 'Original request should not change.'); <ide> $this->assertNotSame($result, $request); <del> $this->assertEquals('new value', $result->data('Model.new_value')); <del> $this->assertEquals('new value', $result->data['Model']['new_value']); <del> $this->assertEquals('value', $result->data('Model.field')); <add> $this->assertEquals('new value', $result->getData('Model.new_value')); <add> $this->assertEquals('new value', $result->getData()['Model']['new_value']); <add> $this->assertEquals('value', $result->getData('Model.field')); <ide> } <ide> <ide> /** <ide> public function testWithDataMissingIntermediaryKeys() <ide> $result = $request->withData('Model.field.new_value', 'new value'); <ide> $this->assertEquals( <ide> 'new value', <del> $result->data('Model.field.new_value') <add> $result->getData('Model.field.new_value') <ide> ); <ide> $this->assertEquals( <ide> 'new value', <del> $result->data['Model']['field']['new_value'] <add> $result->getData()['Model']['field']['new_value'] <ide> ); <ide> } <ide> <ide> public function testWithDataFalseyValues() <ide> 'zero' => 0, <ide> 'zero_string' => '0' <ide> ]; <del> $this->assertSame($expected, $result->data()); <add> $this->assertSame($expected, $result->getData()); <ide> } <ide> <ide> /** <ide> public function testGetAttributesCompatibility($prop) <ide> ]); <ide> <ide> if ($prop === 'session') { <del> $this->assertSame($request->session(), $request->getAttribute($prop)); <add> $this->assertSame($request->getSession(), $request->getAttribute($prop)); <ide> } else { <ide> $this->assertSame($request->{$prop}, $request->getAttribute($prop)); <ide> }
1
Javascript
Javascript
add missing closing square bracket in example
77b302ab00b28294d31948cfcb702219b84c9227
<ide><path>src/ngResource/resource.js <ide> angular.module('ngResource', ['ng']). <ide> * $resourceProvider.defaults.actions.update = { <ide> * method: 'PUT' <ide> * }; <del> * }); <add> * }]); <ide> * ``` <ide> * <ide> * Or you can even overwrite the whole `actions` list and specify your own:
1
Ruby
Ruby
move kismet to the boneyard
4f466b6c10bbc35fb1cdef2691b07856ed3d6e9f
<ide><path>Library/Homebrew/tap_migrations.rb <ide> "jscoverage" => "homebrew/boneyard", <ide> "jsl" => "homebrew/binary", <ide> "kerl" => "homebrew/headonly", <add> "kismet" => "homebrew/boneyard", <ide> "libgtextutils" => "homebrew/science", <ide> "librets" => "homebrew/boneyard", <ide> "lmutil" => "homebrew/binary",
1
Text
Text
update set image card
15515e62eafe47a7a2b81c9f5070115a75ddfb51
<ide><path>client/src/pages/guide/english/bootstrap/cards/index.md <ide> The structure of the card can be enhanced by the addition of a header and a foot <ide> <div class="card-img-overlay">Overlay content</div> <ide> </div> <ide> ``` <add>### Card is balanced with the image <add> <add><div class="card" style="width: 18rem;"> <add> <img class="card-img-top" src="..." alt="Card image cap"> <add> <div class="card-body"> <add> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> <add> </div> <add></div> <add><!--You must set the image height on all cards -->
1
Text
Text
add note to contributing about docs manifest
f6de29f9d431742899e6010c198fcbc95f7fe78f
<ide><path>contributing.md <ide> This will use the version of `next` built inside of the Next.js monorepo and the <ide> main `yarn dev` monorepo command can be running to make changes to the local <ide> Next.js version at the same time (some changes might require re-running `yarn next-with-deps` to take effect). <ide> <add>## Updating documentation paths <add> <add>Our documentation currently leverages a [manifest file](/docs/manifest.json) which is how documentation entries are checked. <add> <add>When adding a new entry under an existing category you only need to add an entry with `{title: '', path: '/docs/path/to/file.md'}`. The "title" is what is shown on the sidebar. <add> <add>When moving the location/url of an entry the "title" field can be removed from the existing entry and the ".md" extension removed from the "path", then a "redirect" field with the shape of `{permanent: true/false, destination: '/some-url'}` can be added. A new entry should be added with the "title" and "path" fields if the document was renamed within the [`docs` folder](/docs) that points to the new location in the folder e.g. `/docs/some-url.md` <add> <add>Example of moving documentation file: <add> <add>Before: <add> <add>```json <add>[ <add> { <add> "path": "/docs/original.md", <add> "title": "Hello world" <add> } <add>] <add>``` <add> <add>After: <add> <add>```json <add>[ <add> { <add> "path": "/docs/original", <add> "redirect": { <add> "permanent": false, <add> "destination": "/new" <add> } <add> } <add> { <add> "path": "/docs/new.md", <add> "title": "Hello world" <add> }, <add>] <add>``` <add> <add>Note: the manifest is checked automatically in the "lint" step in CI when opening a PR. <add> <ide> ## Adding warning/error descriptions <ide> <ide> In Next.js we have a system to add helpful links to warnings and errors.
1
Text
Text
update local setup guide
8ccb50a67f5dc9c621010292be3aaa92777adf23
<ide><path>docs/how-to-setup-freecodecamp-locally.md <ide> Follow these steps: <ide> translate/add-spanish-basic-html <ide> ``` <ide> <del> And these are really bad name: <del> <del> ```shell <del> challenges-branch <del> update-guide <del> fix/#12345 <del> fix-#123 <del> changes-for-1234 <del> ``` <del> <ide> 4. Next, you can work on the editing pages and working on the code in your favorite text editor. <ide> <ide> 5. Once you are happy with the changes you should optionally run freeCodeCamp locally to preview the changes.
1
PHP
PHP
update typehints for controller/
c98e585cc1d539d2b98fc469a170f996f512513b
<ide><path>src/Controller/Component/RequestHandlerComponent.php <ide> public function convertXml(string $xml): array <ide> * @return void <ide> * @throws \Cake\Http\Exception\NotFoundException If invoked extension is not configured. <ide> */ <del> public function beforeRender(EventInterface $event) <add> public function beforeRender(EventInterface $event): void <ide> { <ide> /** @var \Cake\Controller\Controller $controller */ <ide> $controller = $event->getSubject(); <ide><path>src/Controller/Component/SecurityComponent.php <ide> use Cake\Core\Configure; <ide> use Cake\Event\EventInterface; <ide> use Cake\Http\Exception\BadRequestException; <add>use Cake\Http\Response; <ide> use Cake\Http\ServerRequest; <ide> use Cake\Routing\Router; <ide> use Cake\Utility\Hash; <ide> class SecurityComponent extends Component <ide> * @param \Cake\Event\EventInterface $event An Event instance <ide> * @return \Cake\Http\Response|null <ide> */ <del> public function startup(EventInterface $event) <add> public function startup(EventInterface $event): ?Response <ide> { <ide> /** @var \Cake\Controller\Controller $controller */ <ide> $controller = $event->getSubject(); <ide> public function startup(EventInterface $event) <ide> $request = $request->withoutData('_Token'); <ide> } <ide> $controller->setRequest($request); <add> <add> return null; <ide> } <ide> <ide> /** <ide><path>src/Controller/ComponentRegistry.php <ide> public function setController(Controller $controller) <ide> * @param string $class Partial classname to resolve. <ide> * @return string|null Either the correct class name or null. <ide> */ <del> protected function _resolveClassName($class) <add> protected function _resolveClassName($class): ?string <ide> { <ide> return App::className($class, 'Controller/Component', 'Component'); <ide> } <ide><path>src/Controller/Controller.php <ide> public function loadComponent(string $name, array $config = []): Component <ide> * @param string $name Property name <ide> * @return \Cake\Datasource\RepositoryInterface|null The model instance or null <ide> */ <del> public function __get(string $name) <add> public function __get(string $name): ?\Cake\Datasource\RepositoryInterface <ide> { <ide> if (!empty($this->modelClass)) { <ide> [$plugin, $class] = pluginSplit($this->modelClass, true); <ide><path>src/Controller/Exception/MissingComponentException.php <ide> */ <ide> class MissingComponentException extends Exception <ide> { <add> /** <add> * @inheritDoc <add> */ <ide> protected $_messageTemplate = 'Component class %s could not be found.'; <ide> }
5
Text
Text
upgrade example to docker compose v2
43a4a8e6a6fd1ebd42769dc2b24f63fb8b89e9b6
<ide><path>examples/with-docker-compose/README.md <ide> First, run the development server: <ide> docker network create my_network <ide> <ide> # Build dev using new BuildKit engine <del>COMPOSE_DOCKER_CLI_BUILD=1 DOCKER_BUILDKIT=1 docker-compose -f docker-compose.dev.yml build --parallel <add>docker compose -f docker-compose.dev.yml build <ide> <ide> # Up dev <del>docker-compose -f docker-compose.dev.yml up <add>docker compose -f docker-compose.dev.yml up <ide> ``` <ide> <ide> Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. <ide> First, run the production server (Final image approximately 110 MB). <ide> docker network create my_network <ide> <ide> # Build prod using new BuildKit engine <del>COMPOSE_DOCKER_CLI_BUILD=1 DOCKER_BUILDKIT=1 docker-compose -f docker-compose.prod.yml build --parallel <add>docker compose -f docker-compose.prod.yml build <ide> <ide> # Up prod in detached mode <del>docker-compose -f docker-compose.prod.yml up -d <add>docker compose -f docker-compose.prod.yml up -d <ide> ``` <ide> <ide> Alternatively, run the production server without without multistage builds (Final image approximately 1 GB). <ide> Alternatively, run the production server without without multistage builds (Fina <ide> docker network create my_network <ide> <ide> # Build prod without multistage using new BuildKit engine <del>COMPOSE_DOCKER_CLI_BUILD=1 DOCKER_BUILDKIT=1 docker-compose -f docker-compose.prod-without-multistage.yml build --parallel <add>docker compose -f docker-compose.prod-without-multistage.yml build <ide> <ide> # Up prod without multistage in detached mode <del>docker-compose -f docker-compose.prod-without-multistage.yml up -d <add>docker compose -f docker-compose.prod-without-multistage.yml up -d <ide> ``` <ide> <ide> Open [http://localhost:3000](http://localhost:3000).
1
Python
Python
fix issues with eager tensor capture in graph mode
c457f769cca3c8e090a33f2e80bbc13c07ad5ae4
<ide><path>keras/layers/preprocessing/index_lookup.py <ide> def get_config(self): <ide> "vocabulary_dtype": self.vocabulary_dtype, <ide> "idf_weights": utils.listify_tensors(self.input_idf_weights), <ide> "vocabulary": utils.listify_tensors(self.input_vocabulary), <del> "vocabulary_size": self.vocabulary_size(), <add> "vocabulary_size": self._frozen_vocab_size, <ide> } <ide> base_config = super().get_config() <ide> return dict(list(base_config.items()) + list(config.items()))
1
Python
Python
revive sunos support, lost in 6b98a63
1e7a0aa8837dd9244a4941560b2a20da1b4aa60d
<ide><path>tools/gyp/pylib/gyp/generator/make.py <ide> <ide> def GetFlavor(params): <ide> """Returns |params.flavor| if it's set, the system's default flavor else.""" <del> return params.get('flavor', 'mac' if sys.platform == 'darwin' else 'linux') <add> flavors = { <add> 'darwin': 'mac', <add> 'sunos5': 'solaris', <add> } <add> flavor = flavors.get(sys.platform, 'linux') <add> return params.get('flavor', flavor) <ide> <ide> <ide> def CalculateVariables(default_variables, params): <ide> def CalculateVariables(default_variables, params): <ide> default_variables['LINKER_SUPPORTS_ICF'] = \ <ide> gyp.system_test.TestLinkerSupportsICF(cc_command=cc_target) <ide> <del> if GetFlavor(params) == 'mac': <add> flavor = GetFlavor(params) <add> if flavor == 'mac': <ide> default_variables.setdefault('OS', 'mac') <ide> default_variables.setdefault('SHARED_LIB_SUFFIX', '.dylib') <ide> default_variables.setdefault('SHARED_LIB_DIR', <ide> def CalculateVariables(default_variables, params): <ide> global COMPILABLE_EXTENSIONS <ide> COMPILABLE_EXTENSIONS.update({'.m': 'objc', '.mm' : 'objcxx'}) <ide> else: <del> default_variables.setdefault('OS', 'linux') <add> default_variables.setdefault('OS', flavor) <ide> default_variables.setdefault('SHARED_LIB_SUFFIX', '.so') <ide> default_variables.setdefault('SHARED_LIB_DIR','$(builddir)/lib.$(TOOLSET)') <ide> default_variables.setdefault('LIB_DIR', '$(obj).$(TOOLSET)') <ide> def ensure_directory_exists(path): <ide> <ide> quiet_cmd_cxx = CXX($(TOOLSET)) $@ <ide> cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< <del>%(mac_commands)s <add>%(extra_commands)s <ide> quiet_cmd_touch = TOUCH $@ <ide> cmd_touch = touch $@ <ide> <ide> def ensure_directory_exists(path): <ide> cmd_mac_package_framework = ./gyp-mac-tool package-framework "$@" $(4) <ide> """ <ide> <add>SHARED_HEADER_SUN_COMMANDS = """ <add># gyp-sun-tool is written next to the root Makefile by gyp. <add># Use $(4) for the command, since $(2) and $(3) are used as flag by do_cmd <add># already. <add>quiet_cmd_sun_tool = SUNTOOL $(4) $< <add>cmd_sun_tool = ./gyp-sun-tool $(4) $< "$@" <add>""" <add> <ide> <ide> def WriteRootHeaderSuffixRules(writer): <ide> extensions = sorted(COMPILABLE_EXTENSIONS.keys(), key=str.lower) <ide> def RunSystemTests(flavor): <ide> 'LINK_flags': link_flags } <ide> <ide> <del>def CopyMacTool(out_path): <del> """Finds mac_tool.gyp in the gyp directory and copies it to |out_path|.""" <add>def CopyTool(flavor, out_path): <add> """Finds (mac|sun)_tool.gyp in the gyp directory and copies it to |out_path|.""" <add> prefix = { 'solaris': 'sun', 'mac': 'mac' }.get(flavor, None) <add> if not prefix: <add> return <add> <add> tool_path = os.path.join(out_path, 'gyp-%s-tool' % prefix) <add> if os.path.exists(tool_path): <add> os.remove(tool_path) <add> <add> # Slurp input file. <ide> source_path = os.path.join( <del> os.path.dirname(os.path.abspath(__file__)), '..', 'mac_tool.py') <add> os.path.dirname(os.path.abspath(__file__)), '..', '%s_tool.py' % prefix) <ide> source_file = open(source_path) <ide> source = source_file.readlines() <ide> source_file.close() <del> mactool_file = open(out_path, 'w') <del> mactool_file.write( <add> <add> # Add header and write it out. <add> tool_file = open(tool_path, 'w') <add> tool_file.write( <ide> ''.join([source[0], '# Generated by gyp. Do not edit.\n'] + source[1:])) <del> mactool_file.close() <add> tool_file.close() <add> <add> # Make file executable. <add> os.chmod(tool_path, 0o755) <ide> <ide> <ide> def GenerateOutput(target_list, target_dicts, data, params): <ide> def CalculateMakefilePath(build_file, base_name): <ide> 'flock': 'flock', <ide> 'flock_index': 1, <ide> 'link_commands': LINK_COMMANDS_LINUX, <del> 'mac_commands': '', <add> 'extra_commands': '', <ide> 'srcdir': srcdir, <ide> } <ide> if flavor == 'mac': <ide> header_params.update({ <ide> 'flock': './gyp-mac-tool flock', <ide> 'flock_index': 2, <ide> 'link_commands': LINK_COMMANDS_MAC, <del> 'mac_commands': SHARED_HEADER_MAC_COMMANDS, <add> 'extra_commands': SHARED_HEADER_MAC_COMMANDS, <ide> }) <add> elif flavor == 'solaris': <add> header_params.update({ <add> 'flock': './gyp-sun-tool flock', <add> 'flock_index': 2, <add> 'extra_commands': SHARED_HEADER_SUN_COMMANDS, <add> }) <add> <ide> if flavor == 'android': <ide> header_params.update({ <ide> 'link_commands': LINK_COMMANDS_ANDROID, <ide> def CalculateMakefilePath(build_file, base_name): <ide> root_makefile.write('TOOLSET := %s\n' % toolset) <ide> WriteRootHeaderSuffixRules(root_makefile) <ide> <del> # Put mac_tool next to the root Makefile. <del> if flavor == 'mac': <del> mactool_path = os.path.join(os.path.dirname(makefile_path), 'gyp-mac-tool') <del> if os.path.exists(mactool_path): <del> os.remove(mactool_path) <del> CopyMacTool(mactool_path) <del> # Make file executable. <del> os.chmod(mactool_path, 0755) <add> # Put platform tool next to the root Makefile. <add> dest_path = os.path.dirname(makefile_path) <add> CopyTool(flavor, dest_path) <ide> <ide> # Find the list of targets that derive from the gyp file(s) being built. <ide> needed_targets = set()
1
PHP
PHP
fix plural messages not falling back to key
31033e9089e0b54ed66d00b8cd23d3abc283ff6f
<ide><path>src/I18n/Formatter/IcuFormatter.php <ide> class IcuFormatter implements FormatterInterface <ide> * Returns a string with all passed variables interpolated into the original <ide> * message. Variables are interpolated using the MessageFormatter class. <ide> * <del> * If an array is passed in `$message`, it will trigger the plural selection <del> * routine. Plural forms are selected depending on the locale and the `_count` <del> * key passed in `$vars`. <del> * <ide> * @param string $locale The locale in which the message is presented. <ide> * @param string|array $message The message to be translated <ide> * @param array $vars The list of values to interpolate in the message <ide> * @return string The formatted message <ide> */ <ide> public function format($locale, $message, array $vars) <ide> { <del> $isString = is_string($message); <del> if ($isString && isset($vars['_singular'])) { <del> $message = [$vars['_singular'], $message]; <del> unset($vars['_singular']); <del> $isString = false; <del> } <del> <del> if ($isString) { <del> return $this->_formatMessage($locale, $message, $vars); <del> } <del> <del> if (!is_string($message)) { <del> $count = isset($vars['_count']) ? $vars['_count'] : 0; <del> unset($vars['_count'], $vars['_singular']); <del> $form = PluralRules::calculate($locale, $count); <del> $message = isset($message[$form]) ? $message[$form] : (string)end($message); <del> } <add> unset($vars['_singular'], $vars['_count']); <ide> <ide> return $this->_formatMessage($locale, $message, $vars); <ide> } <ide><path>src/I18n/Formatter/SprintfFormatter.php <ide> class SprintfFormatter implements FormatterInterface <ide> * Returns a string with all passed variables interpolated into the original <ide> * message. Variables are interpolated using the sprintf format. <ide> * <del> * If an array is passed in `$message`, it will trigger the plural selection <del> * routine. Plural forms are selected depending on the locale and the `_count` <del> * key passed in `$vars`. <del> * <ide> * @param string $locale The locale in which the message is presented. <ide> * @param string|array $message The message to be translated <ide> * @param array $vars The list of values to interpolate in the message <ide> * @return string The formatted message <ide> */ <ide> public function format($locale, $message, array $vars) <ide> { <del> if (is_string($message) && isset($vars['_singular'])) { <del> $message = [$vars['_singular'], $message]; <del> unset($vars['_singular']); <del> } <del> <del> if (is_string($message)) { <del> return vsprintf($message, $vars); <del> } <del> <del> if (isset($vars['_context']) && isset($message['_context'])) { <del> $message = $message['_context'][$vars['_context']]; <del> unset($vars['_context']); <del> } <del> <del> // Assume first context when no context key was passed <del> if (isset($message['_context'])) { <del> $message = current($message['_context']); <del> } <del> <del> if (!is_string($message)) { <del> $count = isset($vars['_count']) ? $vars['_count'] : 0; <del> unset($vars['_singular']); <del> $form = PluralRules::calculate($locale, $count); <del> $message = $message[$form]; <del> } <add> unset($vars['_singular']); <ide> <ide> return vsprintf($message, $vars); <ide> } <ide><path>src/I18n/Translator.php <ide> use Aura\Intl\FormatterInterface; <ide> use Aura\Intl\Package; <ide> use Aura\Intl\TranslatorInterface; <add>use Cake\I18n\PluralRules; <ide> <ide> /** <ide> * Provides missing message behavior for CakePHP internal message formats. <ide> public function translate($key, array $tokensValues = []) <ide> <ide> // Check for missing/invalid context <ide> if (isset($message['_context'])) { <del> $context = isset($tokensValues['_context']) ? $tokensValues['_context'] : null; <add> $message = $this->resolveContext($key, $message, $tokensValues); <ide> unset($tokensValues['_context']); <del> <del> // No or missing context, fallback to the key/first message <del> if ($context === null) { <del> if (isset($message['_context'][''])) { <del> $message = $message['_context']['']; <del> } else { <del> $message = current($message['_context']); <del> } <del> } elseif (!isset($message['_context'][$context])) { <del> $message = $key; <del> } elseif (is_string($message['_context'][$context]) && <del> strlen($message['_context'][$context]) === 0 <del> ) { <del> $message = $key; <del> } else { <del> $message = $message['_context'][$context]; <del> } <ide> } <ide> <ide> if (!$tokensValues) { <ide> public function translate($key, array $tokensValues = []) <ide> return $message; <ide> } <ide> <add> // Singular message, but plural call <add> if (is_string($message) && isset($tokensValues['_singular'])) { <add> $message = [$tokensValues['_singular'], $message]; <add> } <add> <add> // Resolve plural form. <add> if (is_array($message)) { <add> $count = isset($tokensValues['_count']) ? $tokensValues['_count'] : 0; <add> $form = PluralRules::calculate($this->locale, $count); <add> $message = isset($message[$form]) ? $message[$form] : (string)end($message); <add> } <add> <add> if (strlen($message) === 0) { <add> $message = $key; <add> } <add> <ide> return $this->formatter->format($this->locale, $message, $tokensValues); <ide> } <ide> <add> /** <add> * Resolve a message's context structure. <add> * <add> * @param string $key The message key being handled. <add> * @param string|array $message The message content. <add> * @param array $vars The variables containing the `_context` key. <add> * @return string <add> */ <add> protected function resolveContext($key, $message, array $vars) <add> { <add> $context = isset($vars['_context']) ? $vars['_context'] : null; <add> <add> // No or missing context, fallback to the key/first message <add> if ($context === null) { <add> if (isset($message['_context'][''])) { <add> return $message['_context']['']; <add> } <add> <add> return current($message['_context']); <add> } <add> if (!isset($message['_context'][$context])) { <add> return $key; <add> } <add> if (is_string($message['_context'][$context]) && <add> strlen($message['_context'][$context]) === 0 <add> ) { <add> return $key; <add> } <add> <add> return $message['_context'][$context]; <add> } <add> <ide> /** <ide> * An object of type Package <ide> * <ide><path>tests/TestCase/I18n/Formatter/IcuFormatterTest.php <ide> public function testFormatSimple() <ide> $this->assertEquals('1 Orange', $result); <ide> } <ide> <del> /** <del> * Tests that plural forms can be selected using the PO file format plural forms <del> * <del> * @return void <del> */ <del> public function testFormatPlural() <del> { <del> $formatter = new IcuFormatter(); <del> $messages = [ <del> '{0} is 0', <del> '{0} is 1', <del> '{0} is 2', <del> '{0} is 3', <del> '{0} > 11' <del> ]; <del> $this->assertEquals('1 is 1', $formatter->format('ar', $messages, ['_count' => 1, 1])); <del> $this->assertEquals('2 is 2', $formatter->format('ar', $messages, ['_count' => 2, 2])); <del> $this->assertEquals('20 > 11', $formatter->format('ar', $messages, ['_count' => 20, 20])); <del> } <del> <ide> /** <ide> * Tests that plurals can instead be selected using ICU's native selector <ide> * <ide> public function testBadMessageFormatPHP7() <ide> $formatter = new IcuFormatter(); <ide> $formatter->format('en_US', '{crazy format', ['some', 'vars']); <ide> } <del> <del> /** <del> * Tests that it is possible to provide a singular fallback when passing a string message. <del> * This is useful for getting quick feedback on the code during development instead of <del> * having to provide all plural forms even for the default language <del> * <del> * @return void <del> */ <del> public function testSingularFallback() <del> { <del> $formatter = new IcuFormatter(); <del> $singular = 'one thing'; <del> $plural = 'many things'; <del> $this->assertEquals($singular, $formatter->format('en_US', $plural, ['_count' => 1, '_singular' => $singular])); <del> $this->assertEquals($plural, $formatter->format('en_US', $plural, ['_count' => 2, '_singular' => $singular])); <del> } <ide> } <ide><path>tests/TestCase/I18n/Formatter/SprintfFormatterTest.php <ide> public function testFormatSimple() <ide> $this->assertEquals('Hello José', $formatter->format('en_US', 'Hello %s', ['José'])); <ide> $this->assertEquals('1 Orange', $formatter->format('en_US', '%d %s', [1, 'Orange'])); <ide> } <del> <del> /** <del> * Tests that plural forms are selected for the passed locale <del> * <del> * @return void <del> */ <del> public function testFormatPlural() <del> { <del> $formatter = new SprintfFormatter(); <del> $messages = ['%d is 0', '%d is 1', '%d is 2', '%d is 3', '%d > 11']; <del> $this->assertEquals('1 is 1', $formatter->format('ar', $messages, ['_count' => 1])); <del> $this->assertEquals('2 is 2', $formatter->format('ar', $messages, ['_count' => 2])); <del> $this->assertEquals('20 > 11', $formatter->format('ar', $messages, ['_count' => 20])); <del> } <del> <del> /** <del> * Tests that strings stored inside context namespaces can also be formatted <del> * <del> * @return void <del> */ <del> public function testFormatWithContext() <del> { <del> $messages = [ <del> 'simple' => [ <del> '_context' => [ <del> 'context a' => 'Text "a" %s', <del> 'context b' => 'Text "b" %s' <del> ] <del> ], <del> 'complex' => [ <del> '_context' => [ <del> 'context b' => [ <del> 0 => 'Only one', <del> 1 => 'there are %d' <del> ] <del> ] <del> ] <del> ]; <del> <del> $formatter = new SprintfFormatter(); <del> $this->assertEquals( <del> 'Text "a" is good', <del> $formatter->format('en', $messages['simple'], ['_context' => 'context a', 'is good']) <del> ); <del> $this->assertEquals( <del> 'Text "b" is good', <del> $formatter->format('en', $messages['simple'], ['_context' => 'context b', 'is good']) <del> ); <del> $this->assertEquals( <del> 'Text "a" is good', <del> $formatter->format('en', $messages['simple'], ['is good']) <del> ); <del> <del> $this->assertEquals( <del> 'Only one', <del> $formatter->format('en', $messages['complex'], ['_context' => 'context b', '_count' => 1]) <del> ); <del> <del> $this->assertEquals( <del> 'there are 2', <del> $formatter->format('en', $messages['complex'], ['_context' => 'context b', '_count' => 2]) <del> ); <del> } <del> <del> /** <del> * Tests that it is possible to provide a singular fallback when passing a string message. <del> * This is useful for getting quick feedback on the code during development instead of <del> * having to provide all plural forms even for the default language <del> * <del> * @return void <del> */ <del> public function testSingularFallback() <del> { <del> $formatter = new SprintfFormatter(); <del> $singular = 'one thing'; <del> $plural = 'many things'; <del> $this->assertEquals($singular, $formatter->format('en_US', $plural, ['_count' => 1, '_singular' => $singular])); <del> $this->assertEquals($plural, $formatter->format('en_US', $plural, ['_count' => 2, '_singular' => $singular])); <del> } <ide> } <ide><path>tests/TestCase/I18n/I18nTest.php <ide> public function testBasicTranslateFunctionsWithNullParam() <ide> } <ide> <ide> /** <del> * Tests the __() function on a plural key <add> * Tests the __() function on a plural key works <ide> * <ide> * @return void <ide> */ <ide> public function testBasicTranslatePluralFunction() <ide> $this->assertEquals('1 red and blue are good', $result); <ide> } <ide> <add> /** <add> * Tests the __n() function on singular keys <add> * <add> * @return void <add> */ <add> public function testBasicTranslatePluralFunctionSingularMessage() <add> { <add> I18n::defaultFormatter('sprintf'); <add> $result = __n('No translation needed', 'not used', 1); <add> $this->assertEquals('No translation needed', $result); <add> } <add> <ide> /** <ide> * Tests the __d() function <ide> * <ide> public function testBasicDomainFunction() <ide> 'Cow' => 'Le moo', <ide> 'The {0} is tasty' => 'The {0} is delicious', <ide> 'Average price {0}' => 'Price Average {0}', <add> 'Unknown' => '', <ide> ]); <ide> <ide> return $package; <ide> }); <ide> $this->assertEquals('Le moo', __d('custom', 'Cow')); <add> $this->assertEquals('Unknown', __d('custom', 'Unknown')); <ide> <ide> $result = __d('custom', 'The {0} is tasty', ['fruit']); <ide> $this->assertEquals('The fruit is delicious', $result); <ide> public function testBasicDomainPluralFunction() <ide> 'Cows' => [ <ide> 'Le Moo', <ide> 'Les Moos' <add> ], <add> '{0} years' => [ <add> '', <add> '' <ide> ] <ide> ]); <ide> <ide> return $package; <ide> }); <ide> $this->assertEquals('Le Moo', __dn('custom', 'Cow', 'Cows', 1)); <ide> $this->assertEquals('Les Moos', __dn('custom', 'Cow', 'Cows', 2)); <add> $this->assertEquals('{0} years', __dn('custom', '{0} year', '{0} years', 1)); <add> $this->assertEquals('{0} years', __dn('custom', '{0} year', '{0} years', 2)); <ide> } <ide> <ide> /**
6
Javascript
Javascript
implement defs and use nodes. first test
10ba26e9fa3b060b132c7e0c3cc17a4188e734d9
<ide><path>examples/jsm/loaders/SVGLoader.js <ide> SVGLoader.prototype = Object.assign( Object.create( Loader.prototype ), { <ide> <ide> var transform = getNodeTransform( node ); <ide> <add> var traverseChildNodes = true; <add> <ide> var path = null; <ide> <ide> switch ( node.nodeName ) { <ide> SVGLoader.prototype = Object.assign( Object.create( Loader.prototype ), { <ide> path = parseLineNode( node ); <ide> break; <ide> <add> case 'defs': <add> traverseChildNodes = false; <add> break; <add> <add> case 'use': <add> var usedNode = node.viewportElement.getElementById( node.href.baseVal.substring( 1 ) ); <add> parseNode( usedNode, style ); <add> break; <add> <add> break; <add> <ide> default: <ide> // console.log( node ); <ide> <ide> SVGLoader.prototype = Object.assign( Object.create( Loader.prototype ), { <ide> <ide> } <ide> <del> var nodes = node.childNodes; <add> if ( traverseChildNodes ) { <add> <add> var nodes = node.childNodes; <ide> <del> for ( var i = 0; i < nodes.length; i ++ ) { <add> for ( var i = 0; i < nodes.length; i ++ ) { <ide> <del> parseNode( nodes[ i ], style ); <add> parseNode( nodes[ i ], style ); <add> <add> } <ide> <ide> } <ide> <ide> SVGLoader.prototype = Object.assign( Object.create( Loader.prototype ), { <ide> <ide> function getNodeTransform( node ) { <ide> <del> if ( ! node.hasAttribute( 'transform' ) ) { <add> if ( ! ( node.hasAttribute( 'transform' ) || node.nodeName === 'use' ) ) { <ide> <ide> return null; <ide> <ide> SVGLoader.prototype = Object.assign( Object.create( Loader.prototype ), { <ide> <ide> var transform = new Matrix3(); <ide> var currentTransform = tempTransform0; <del> var transformsTexts = node.getAttribute( 'transform' ).split( ')' ); <ide> <del> for ( var tIndex = transformsTexts.length - 1; tIndex >= 0; tIndex -- ) { <add> if ( node.nodeName === 'use' ) { <add> <add> var tx = parseFloatWithUnits( node.getAttribute( 'x' ) ); <add> var ty = parseFloatWithUnits( node.getAttribute( 'y' ) ); <ide> <del> var transformText = transformsTexts[ tIndex ].trim(); <add> transform.translate( tx, ty ); <ide> <del> if ( transformText === '' ) continue; <add> } <add> else { <ide> <del> var openParPos = transformText.indexOf( '(' ); <del> var closeParPos = transformText.length; <add> var transformsTexts = node.getAttribute( 'transform' ).split( ')' ); <ide> <del> if ( openParPos > 0 && openParPos < closeParPos ) { <add> for ( var tIndex = transformsTexts.length - 1; tIndex >= 0; tIndex -- ) { <ide> <del> var transformType = transformText.substr( 0, openParPos ); <add> var transformText = transformsTexts[ tIndex ].trim(); <ide> <del> var array = parseFloats( transformText.substr( openParPos + 1, closeParPos - openParPos - 1 ) ); <add> if ( transformText === '' ) continue; <ide> <del> currentTransform.identity(); <add> var openParPos = transformText.indexOf( '(' ); <add> var closeParPos = transformText.length; <add> <add> if ( openParPos > 0 && openParPos < closeParPos ) { <add> <add> var transformType = transformText.substr( 0, openParPos ); <add> <add> var array = parseFloats( transformText.substr( openParPos + 1, closeParPos - openParPos - 1 ) ); <ide> <del> switch ( transformType ) { <add> currentTransform.identity(); <ide> <del> case "translate": <add> switch ( transformType ) { <ide> <del> if ( array.length >= 1 ) { <add> case "translate": <ide> <del> var tx = array[ 0 ]; <del> var ty = tx; <add> if ( array.length >= 1 ) { <ide> <del> if ( array.length >= 2 ) { <add> var tx = array[ 0 ]; <add> var ty = tx; <ide> <del> ty = array[ 1 ]; <add> if ( array.length >= 2 ) { <add> <add> ty = array[ 1 ]; <add> <add> } <add> <add> currentTransform.translate( tx, ty ); <ide> <ide> } <ide> <del> currentTransform.translate( tx, ty ); <add> break; <ide> <del> } <add> case "rotate": <ide> <del> break; <add> if ( array.length >= 1 ) { <ide> <del> case "rotate": <add> var angle = 0; <add> var cx = 0; <add> var cy = 0; <ide> <del> if ( array.length >= 1 ) { <add> // Angle <add> angle = - array[ 0 ] * Math.PI / 180; <ide> <del> var angle = 0; <del> var cx = 0; <del> var cy = 0; <add> if ( array.length >= 3 ) { <ide> <del> // Angle <del> angle = - array[ 0 ] * Math.PI / 180; <add> // Center x, y <add> cx = array[ 1 ]; <add> cy = array[ 2 ]; <ide> <del> if ( array.length >= 3 ) { <add> } <ide> <del> // Center x, y <del> cx = array[ 1 ]; <del> cy = array[ 2 ]; <add> // Rotate around center (cx, cy) <add> tempTransform1.identity().translate( - cx, - cy ); <add> tempTransform2.identity().rotate( angle ); <add> tempTransform3.multiplyMatrices( tempTransform2, tempTransform1 ); <add> tempTransform1.identity().translate( cx, cy ); <add> currentTransform.multiplyMatrices( tempTransform1, tempTransform3 ); <ide> <ide> } <ide> <del> // Rotate around center (cx, cy) <del> tempTransform1.identity().translate( - cx, - cy ); <del> tempTransform2.identity().rotate( angle ); <del> tempTransform3.multiplyMatrices( tempTransform2, tempTransform1 ); <del> tempTransform1.identity().translate( cx, cy ); <del> currentTransform.multiplyMatrices( tempTransform1, tempTransform3 ); <add> break; <ide> <del> } <add> case "scale": <ide> <del> break; <add> if ( array.length >= 1 ) { <ide> <del> case "scale": <add> var scaleX = array[ 0 ]; <add> var scaleY = scaleX; <ide> <del> if ( array.length >= 1 ) { <add> if ( array.length >= 2 ) { <ide> <del> var scaleX = array[ 0 ]; <del> var scaleY = scaleX; <add> scaleY = array[ 1 ]; <ide> <del> if ( array.length >= 2 ) { <add> } <ide> <del> scaleY = array[ 1 ]; <add> currentTransform.scale( scaleX, scaleY ); <ide> <ide> } <ide> <del> currentTransform.scale( scaleX, scaleY ); <add> break; <ide> <del> } <del> <del> break; <add> case "skewX": <ide> <del> case "skewX": <add> if ( array.length === 1 ) { <ide> <del> if ( array.length === 1 ) { <add> currentTransform.set( <add> 1, Math.tan( array[ 0 ] * Math.PI / 180 ), 0, <add> 0, 1, 0, <add> 0, 0, 1 <add> ); <ide> <del> currentTransform.set( <del> 1, Math.tan( array[ 0 ] * Math.PI / 180 ), 0, <del> 0, 1, 0, <del> 0, 0, 1 <del> ); <add> } <ide> <del> } <add> break; <ide> <del> break; <add> case "skewY": <ide> <del> case "skewY": <add> if ( array.length === 1 ) { <ide> <del> if ( array.length === 1 ) { <add> currentTransform.set( <add> 1, 0, 0, <add> Math.tan( array[ 0 ] * Math.PI / 180 ), 1, 0, <add> 0, 0, 1 <add> ); <ide> <del> currentTransform.set( <del> 1, 0, 0, <del> Math.tan( array[ 0 ] * Math.PI / 180 ), 1, 0, <del> 0, 0, 1 <del> ); <add> } <ide> <del> } <add> break; <ide> <del> break; <add> case "matrix": <ide> <del> case "matrix": <add> if ( array.length === 6 ) { <ide> <del> if ( array.length === 6 ) { <add> currentTransform.set( <add> array[ 0 ], array[ 2 ], array[ 4 ], <add> array[ 1 ], array[ 3 ], array[ 5 ], <add> 0, 0, 1 <add> ); <ide> <del> currentTransform.set( <del> array[ 0 ], array[ 2 ], array[ 4 ], <del> array[ 1 ], array[ 3 ], array[ 5 ], <del> 0, 0, 1 <del> ); <add> } <ide> <del> } <add> break; <ide> <del> break; <add> } <ide> <ide> } <ide> <del> } <add> transform.premultiply( currentTransform ); <ide> <del> transform.premultiply( currentTransform ); <add> } <ide> <ide> } <ide>
1
Javascript
Javascript
remove api no longer present in qunit 2.0
ce3ab8f23c5be2dac4bdc944c911b92342aa04f9
<ide><path>packages/ember/tests/helpers/link_to_test.js <ide> function assertNav(options, callback) { <ide> let nav = false; <ide> <ide> function check(event) { <del> QUnit.equal(event.defaultPrevented, options.prevented, `expected defaultPrevented=${options.prevented}`); <add> QUnit.assert.equal(event.defaultPrevented, options.prevented, `expected defaultPrevented=${options.prevented}`); <ide> nav = true; <ide> event.preventDefault(); <ide> } <ide> function assertNav(options, callback) { <ide> callback(); <ide> } finally { <ide> document.removeEventListener('click', check); <del> QUnit.ok(nav, 'Expected a link to be clicked'); <add> QUnit.assert.ok(nav, 'Expected a link to be clicked'); <ide> } <ide> }
1
Text
Text
add sponsors to readme
d3760f7fbf414a21d0010368c8dad5f9299df204
<ide><path>readme.md <ide> Laravel has the most extensive and thorough documentation and video tutorial lib <ide> <ide> If you're not in the mood to read, [Laracasts](https://laracasts.com) contains over 900 video tutorials on a range of topics including Laravel, modern PHP, unit testing, JavaScript, and more. Boost the skill level of yourself and your entire team by digging into our comprehensive video library. <ide> <add>## Laravel Sponsors <add> <add>We would like to extend our thanks to the following sponsors for helping fund on-going Laravel development. If you are interested in becoming a sponsor, please visit the Laravel [Patreon page](http://patreon.com/taylorotwell): <add> <add>- **[Vehikl](https://vehikl.com)** <add>- **[Tighten Co.](https://tighten.co)** <add>- **[British Software Development](https://www.britishsoftware.com)** <add>- **[Styde](https://styde.net)** <add>- **[Codecourse](https://www.codecourse.com)** <add>- [Fragrantica](https://www.fragrantica.com) <add> <ide> ## Contributing <ide> <ide> Thank you for considering contributing to the Laravel framework! The contribution guide can be found in the [Laravel documentation](http://laravel.com/docs/contributions).
1
Ruby
Ruby
add a test for select argument error with block
246417c74edeb1d957f9a341862c33aff645d22c
<ide><path>activerecord/test/cases/relations_test.rb <ide> def test_select_argument_error <ide> assert_raises(ArgumentError) { Developer.select } <ide> end <ide> <add> def test_select_argument_error_with_block <add> assert_raises(ArgumentError) { Developer.select(:id) { |d| d.id % 2 == 0 } } <add> end <add> <ide> def test_count <ide> posts = Post.all <ide>
1
Go
Go
add deviceset singleton
f317a6b6fe31685445ac97a1475136c5ab7860b5
<ide><path>runtime.go <ide> type Runtime struct { <ide> volumes *Graph <ide> srv *Server <ide> Dns []string <add> deviceSet DeviceSet <ide> } <ide> <ide> var sysInitPath string <ide> func (runtime *Runtime) getContainerElement(id string) *list.Element { <ide> return nil <ide> } <ide> <add>func (runtime *Runtime) GetDeviceSet() (DeviceSet, error) { <add> if runtime.deviceSet == nil { <add> return nil, fmt.Errorf("No device set available") <add> } <add> return runtime.deviceSet, nil <add>} <add> <ide> // Get looks for a container by the specified ID or name, and returns it. <ide> // If the container is not found, or if an error occurs, nil is returned. <ide> func (runtime *Runtime) Get(name string) *Container { <ide> func (runtime *Runtime) Commit(container *Container, repository, tag, comment, a <ide> } <ide> <ide> // FIXME: harmonize with NewGraph() <del>func NewRuntime(flGraphPath string, autoRestart bool, dns []string) (*Runtime, error) { <del> runtime, err := NewRuntimeFromDirectory(flGraphPath, autoRestart) <add>func NewRuntime(flGraphPath string, deviceSet DeviceSet, autoRestart bool, dns []string) (*Runtime, error) { <add> runtime, err := NewRuntimeFromDirectory(flGraphPath, deviceSet, autoRestart) <ide> if err != nil { <ide> return nil, err <ide> } <ide> func NewRuntime(flGraphPath string, autoRestart bool, dns []string) (*Runtime, e <ide> return runtime, nil <ide> } <ide> <del>func NewRuntimeFromDirectory(root string, autoRestart bool) (*Runtime, error) { <add>func NewRuntimeFromDirectory(root string, deviceSet DeviceSet, autoRestart bool) (*Runtime, error) { <ide> runtimeRepo := path.Join(root, "containers") <ide> <ide> if err := os.MkdirAll(runtimeRepo, 0700); err != nil && !os.IsExist(err) { <ide> func NewRuntimeFromDirectory(root string, autoRestart bool) (*Runtime, error) { <ide> capabilities: &Capabilities{}, <ide> autoRestart: autoRestart, <ide> volumes: volumes, <add> deviceSet: deviceSet, <ide> } <ide> <ide> if err := runtime.restore(); err != nil { <ide><path>runtime_test.go <ide> import ( <ide> "bytes" <ide> "fmt" <ide> "github.com/dotcloud/docker/utils" <add> "github.com/dotcloud/docker/devmapper" <ide> "io" <ide> "log" <ide> "net" <ide> func init() { <ide> NetworkBridgeIface = unitTestNetworkBridge <ide> <ide> // Make it our Store root <del> if runtime, err := NewRuntimeFromDirectory(unitTestStoreBase, false); err != nil { <add> if runtime, err := NewRuntimeFromDirectory(unitTestStoreBase, devmapper.NewDeviceSetDM(unitTestStoreBase), false); err != nil { <ide> panic(err) <ide> } else { <ide> globalRuntime = runtime <ide> func TestRestore(t *testing.T) { <ide> <ide> // Here are are simulating a docker restart - that is, reloading all containers <ide> // from scratch <del> runtime2, err := NewRuntimeFromDirectory(runtime1.root, false) <add> runtime2, err := NewRuntimeFromDirectory(runtime1.root, devmapper.NewDeviceSetDM(runtime1.root), false) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide><path>server.go <ide> func NewServer(flGraphPath string, deviceSet DeviceSet, autoRestart, enableCors <ide> if runtime.GOARCH != "amd64" { <ide> log.Fatalf("The docker runtime currently only supports amd64 (not %s). This will change in the future. Aborting.", runtime.GOARCH) <ide> } <del> runtime, err := NewRuntime(flGraphPath, autoRestart, dns) <add> runtime, err := NewRuntime(flGraphPath, deviceSet, autoRestart, dns) <ide> if err != nil { <ide> return nil, err <ide> } <ide><path>utils_test.go <ide> package docker <ide> <ide> import ( <ide> "github.com/dotcloud/docker/utils" <add> "github.com/dotcloud/docker/devmapper" <ide> "io" <ide> "io/ioutil" <ide> "os" <ide> func newTestRuntime() (*Runtime, error) { <ide> return nil, err <ide> } <ide> <del> runtime, err := NewRuntimeFromDirectory(root, false) <add> runtime, err := NewRuntimeFromDirectory(root, devmapper.NewDeviceSetDM(root), false) <ide> if err != nil { <ide> return nil, err <ide> }
4
Ruby
Ruby
avoid uninitialized variable warnings on ruby 2.7
890015ae46ad023fdc9459c943dc77ba9683b42d
<ide><path>activesupport/lib/active_support/error_reporter.rb <ide> def set_context(...) <ide> # Rails.error.report(error) <ide> # <ide> def report(error, handled: true, severity: handled ? :warning : :error, context: {}, source: DEFAULT_SOURCE) <del> return if error.instance_variable_get(:@__rails_error_reported) <add> return if error.instance_variable_defined?(:@__rails_error_reported) <ide> <ide> unless SEVERITIES.include?(severity) <ide> raise ArgumentError, "severity must be one of #{SEVERITIES.map(&:inspect).join(", ")}, got: #{severity.inspect}"
1
Text
Text
add react native blog post
951adcdd4c260ccf6267c5470195b544ed5afde8
<ide><path>docs/_posts/2015-03-26-introducing-react-native.md <add>--- <add>title: "Introducing React Native" <add>author: Ben Alpert <add>--- <add> <add>In January at React.js Conf, we announced React Native, a new framework for building native apps using React. We're happy to announce that we're open-sourcing React Native and you can start building your apps with it today. <add> <add>For more details, see [Tom Occhino's post on the Facebook Engineering blog](https://code.facebook.com/posts/1014532261909640/react-native-bringing-modern-web-techniques-to-mobile/): <add> <add>> *What we really want is the user experience of the native mobile platforms, combined with the developer experience we have when building with React on the web.* <add>> <add>> *With a bit of work, we can make it so the exact same React that's on GitHub can power truly native mobile applications. The only difference in the mobile environment is that instead of running React in the browser and rendering to divs and spans, we run it an embedded instance of JavaScriptCore inside our apps and render to higher-level platform-specific components.* <add>> <add>> *It's worth noting that we're not chasing “write once, run anywhere.” Different platforms have different looks, feels, and capabilities, and as such, we should still be developing discrete apps for each platform, but the same set of engineers should be able to build applications for whatever platform they choose, without needing to learn a fundamentally different set of technologies for each. We call this approach “learn once, write anywhere.”* <add> <add>To learn more, visit the [React Native website](http://facebook.github.io/react-native/).
1
Javascript
Javascript
use template strings in parallel tests
a6ab883eaaceb25c1983ab8eae752bdad23f7bfc
<ide><path>test/parallel/test-buffer-bigint64.js <ide> const buf = Buffer.allocUnsafe(8); <ide> ['LE', 'BE'].forEach(function(endianness) { <ide> // Should allow simple BigInts to be written and read <ide> let val = 123456789n; <del> buf['writeBigInt64' + endianness](val, 0); <del> let rtn = buf['readBigInt64' + endianness](0); <add> buf[`writeBigInt64${endianness}`](val, 0); <add> let rtn = buf[`readBigInt64${endianness}`](0); <ide> assert.strictEqual(val, rtn); <ide> <ide> // Should allow INT64_MAX to be written and read <ide> val = 0x7fffffffffffffffn; <del> buf['writeBigInt64' + endianness](val, 0); <del> rtn = buf['readBigInt64' + endianness](0); <add> buf[`writeBigInt64${endianness}`](val, 0); <add> rtn = buf[`readBigInt64${endianness}`](0); <ide> assert.strictEqual(val, rtn); <ide> <ide> // Should read and write a negative signed 64-bit integer <ide> val = -123456789n; <del> buf['writeBigInt64' + endianness](val, 0); <del> assert.strictEqual(val, buf['readBigInt64' + endianness](0)); <add> buf[`writeBigInt64${endianness}`](val, 0); <add> assert.strictEqual(val, buf[`readBigInt64${endianness}`](0)); <ide> <ide> // Should read and write an unsigned 64-bit integer <ide> val = 123456789n; <del> buf['writeBigUInt64' + endianness](val, 0); <del> assert.strictEqual(val, buf['readBigUInt64' + endianness](0)); <add> buf[`writeBigUInt64${endianness}`](val, 0); <add> assert.strictEqual(val, buf[`readBigUInt64${endianness}`](0)); <ide> <ide> // Should throw a RangeError upon INT64_MAX+1 being written <ide> assert.throws(function() { <ide> const val = 0x8000000000000000n; <del> buf['writeBigInt64' + endianness](val, 0); <add> buf[`writeBigInt64${endianness}`](val, 0); <ide> }, RangeError); <ide> <ide> // Should throw a RangeError upon UINT64_MAX+1 being written <ide> assert.throws(function() { <ide> const val = 0x10000000000000000n; <del> buf['writeBigUInt64' + endianness](val, 0); <add> buf[`writeBigUInt64${endianness}`](val, 0); <ide> }, { <ide> code: 'ERR_OUT_OF_RANGE', <ide> message: 'The value of "value" is out of range. It must be ' + <del> '>= 0n and < 2n ** 64n. Received 18_446_744_073_709_551_616n' <add> '>= 0n and < 2n ** 64n. Received 18_446_744_073_709_551_616n' <ide> }); <ide> <ide> // Should throw a TypeError upon invalid input <ide> assert.throws(function() { <del> buf['writeBigInt64' + endianness]('bad', 0); <add> buf[`writeBigInt64${endianness}`]('bad', 0); <ide> }, TypeError); <ide> <ide> // Should throw a TypeError upon invalid input <ide> assert.throws(function() { <del> buf['writeBigUInt64' + endianness]('bad', 0); <add> buf[`writeBigUInt64${endianness}`]('bad', 0); <ide> }, TypeError); <ide> }); <ide><path>test/parallel/test-http-readable-data-event.js <ide> let next = null; <ide> <ide> const server = http.createServer((req, res) => { <ide> res.writeHead(200, { <del> 'Content-Length': '' + (helloWorld.length + helloAgainLater.length) <add> 'Content-Length': `${(helloWorld.length + helloAgainLater.length)}` <ide> }); <ide> <ide> // We need to make sure the data is flushed <ide> // before writing again <ide> next = () => { <ide> res.end(helloAgainLater); <del> next = () => {}; <add> next = () => { }; <ide> }; <ide> <ide> res.write(helloWorld); <ide><path>test/parallel/test-http2-origin.js <ide> const ca = readKey('fake-startcom-root-cert.pem', 'binary'); <ide> } <ide> ); <ide> }); <del> const longInput = 'http://foo.bar' + 'a'.repeat(16383); <add> const longInput = `http://foo.bar${'a'.repeat(16383)}`; <ide> throws( <ide> () => session.origin(longInput), <ide> { <ide> const ca = readKey('fake-startcom-root-cert.pem', 'binary'); <ide> <ide> // Test automatically sending origin on connection start <ide> { <del> const origins = [ 'https://foo.org/a/b/c', 'https://bar.org' ]; <add> const origins = ['https://foo.org/a/b/c', 'https://bar.org']; <ide> const server = createSecureServer({ key, cert, origins }); <ide> server.on('stream', mustCall((stream) => { <ide> stream.respond(); <ide><path>test/parallel/test-http2-server-session-destroy.js <ide> server.listen(0, common.localhostIPv4, common.mustCall(() => { <ide> <ide> const port = server.address().port; <ide> const host = common.localhostIPv4; <del> h2.connect('http://' + host + ':' + port, afterConnect); <add> h2.connect(`http://${host}:${port}`, afterConnect); <ide> })); <ide><path>test/parallel/test-promises-warning-on-unhandled-rejection.js <ide> process.on('warning', common.mustCall((warning) => { <ide> assert( <ide> /Unhandled promise rejection/.test(warning.message), <ide> 'Expected warning message to contain "Unhandled promise rejection" ' + <del> 'but did not. Had "' + warning.message + '" instead.' <add> `but did not. Had "${warning.message}" instead.` <ide> ); <ide> break; <ide> case 2: <ide> process.on('warning', common.mustCall((warning) => { <ide> assert( <ide> /Unhandled promise rejection/.test(warning.message), <ide> 'Expected warning message to contain "Unhandled promise rejection" ' + <del> 'but did not. Had "' + warning.message + '" instead.' <add> `but did not. Had "${warning.message}" instead.` <ide> ); <ide> break; <ide> case 5: <ide><path>test/parallel/test-tls-psk-server.js <ide> let gotWorld = false; <ide> server.listen(0, () => { <ide> const client = spawn(common.opensslCli, [ <ide> 's_client', <del> '-connect', '127.0.0.1:' + server.address().port, <add> '-connect', `127.0.0.1:${server.address().port}`, <ide> '-cipher', CIPHERS, <ide> '-psk', KEY, <ide> '-psk_identity', IDENTITY <ide><path>test/parallel/test-worker-relative-path.js <ide> const assert = require('assert'); <ide> const { Worker, isMainThread, parentPort } = require('worker_threads'); <ide> <ide> if (isMainThread) { <del> const w = new Worker('./' + path.relative('.', __filename)); <add> const w = new Worker(`./${path.relative('.', __filename)}`); <ide> w.on('message', common.mustCall((message) => { <ide> assert.strictEqual(message, 'Hello, world!'); <ide> }));
7