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 |
|---|---|---|---|---|---|
Text | Text | add a missing verb | c6091a2646c0960c537243c934051cfc413bf6b8 | <ide><path>docs/recipes/ServerRendering.md
<ide> function handleRender(req, res) {
<ide> }
<ide> ```
<ide>
<del>Because we `res.send()` inside of the callback, the server will hold open the connection and won’t send any data until that callback executes. You’ll notice a 500ms delay is now added to each server request as a result of our new API call. A more advanced usage would handle errors in the API gracefully, such as a bad response or timeout.
<add>Because we call `res.send()` inside of the callback, the server will hold open the connection and won’t send any data until that callback executes. You’ll notice a 500ms delay is now added to each server request as a result of our new API call. A more advanced usage would handle errors in the API gracefully, such as a bad response or timeout.
<ide>
<ide> ### Security Considerations
<ide> | 1 |
Javascript | Javascript | fix severe perf problems in component tree devtool | 3cc733add482fd0f855d15ae8cbd75cc077bd674 | <ide><path>src/isomorphic/devtools/ReactComponentTreeDevtool.js
<ide> var invariant = require('invariant');
<ide>
<ide> var tree = {};
<del>var rootIDs = [];
<add>var unmountedIDs = {};
<add>var rootIDs = {};
<ide>
<ide> function updateTree(id, update) {
<ide> if (!tree[id]) {
<ide> function updateTree(id, update) {
<ide> isMounted: false,
<ide> updateCount: 0,
<ide> };
<add> // TODO: We need to do this awkward dance because TopLevelWrapper "never
<add> // gets mounted" but its display name gets set in instantiateReactComponent
<add> // before its debug ID is set to 0.
<add> unmountedIDs[id] = true;
<ide> }
<ide> update(tree[id]);
<ide> }
<ide> var ReactComponentTreeDevtool = {
<ide>
<ide> onMountComponent(id) {
<ide> updateTree(id, item => item.isMounted = true);
<add> delete unmountedIDs[id];
<ide> },
<ide>
<ide> onMountRootComponent(id) {
<del> rootIDs.push(id);
<add> rootIDs[id] = true;
<ide> },
<ide>
<ide> onUpdateComponent(id) {
<ide> var ReactComponentTreeDevtool = {
<ide>
<ide> onUnmountComponent(id) {
<ide> updateTree(id, item => item.isMounted = false);
<del> rootIDs = rootIDs.filter(rootID => rootID !== id);
<add> unmountedIDs[id] = true;
<add> delete rootIDs[id];
<ide> },
<ide>
<ide> purgeUnmountedComponents() {
<ide> var ReactComponentTreeDevtool = {
<ide> return;
<ide> }
<ide>
<del> Object.keys(tree)
<del> .filter(id => !tree[id].isMounted)
<del> .forEach(purgeDeep);
<add> for (var id in unmountedIDs) {
<add> purgeDeep(id);
<add> }
<add> unmountedIDs = {};
<ide> },
<ide>
<ide> isMounted(id) {
<ide> var ReactComponentTreeDevtool = {
<ide> },
<ide>
<ide> getRootIDs() {
<del> return rootIDs;
<add> return Object.keys(rootIDs);
<ide> },
<ide>
<ide> getRegisteredIDs() { | 1 |
Text | Text | extend bash-mv and add fixes | 2fb4a6199ef82dced6023030fd93a9bce0c8b7e7 | <ide><path>guide/russian/bash/bash-mv/index.md
<ide> localeTitle: Bash mv
<ide> ---
<ide> ## Команда Bash: mv
<ide>
<add>Команда mv выполняет операции перемещения и переименования файлов в зависимости от особенностей использования. В любом случае исходный файл исчезает после операции. Команда mv используется почти так же, как команда `cp`.
<add>
<ide> **Перемещает файлы и папки.**
<del>```
<add>
<add>```bash
<ide> mv source target
<del> mv source ... directory
<add>mv source directory
<ide> ```
<ide>
<ide> Первый аргумент - это файл, который вы хотите переместить, а второй - местоположение для его перемещения.
<ide>
<ide> Обычно используемые опции:
<ide>
<del>* `-f` чтобы заставить их перемещать и перезаписывать файлы без проверки с пользователем.
<del>* `-i` запросить подтверждение перед перезаписью файлов.
<add>* `-f` не запрашивать подтверждения операций.
<add>* `-i` выводить запрос на подтверждение операции, когда существует файл, в который происходит переименование или перемещение.
<add>
<add>Команду mv можно также использовать для перемещения каталогов(папок):
<add>
<add>`$ mv dir2 dir4`
<add>
<add>Все содержимое каталога остается неизменным. Единственным атрибутом каталога, который изменяется, является имя каталога. Таким образом, команда mv действует намного быстрее по сравнению с командой cp.
<add>
<ide>
<ide> ### Дополнительная информация:
<ide>
<del>* [Википедия](https://en.wikipedia.org/wiki/Mv)
<ide>\ No newline at end of file
<add>* [Википедия](https://ru.wikipedia.org/wiki/Mv) | 1 |
Text | Text | fix matcher callback example (closes ) | d361e380b85ca3e907af9d9a8a720f6dc4bbcf27 | <ide><path>website/docs/usage/rule-based-matching.md
<ide> match on the uppercase versions, in case someone has written it as "Google i/o".
<ide>
<ide> ```python
<ide> ### {executable="true"}
<del>import spacy
<add>from spacy.lang.en import English
<ide> from spacy.matcher import Matcher
<ide> from spacy.tokens import Span
<ide>
<del>nlp = spacy.load("en_core_web_sm")
<add>nlp = English()
<ide> matcher = Matcher(nlp.vocab)
<ide>
<ide> def add_event_ent(matcher, doc, i, matches):
<ide> def add_event_ent(matcher, doc, i, matches):
<ide>
<ide> pattern = [{"ORTH": "Google"}, {"ORTH": "I"}, {"ORTH": "/"}, {"ORTH": "O"}]
<ide> matcher.add("GoogleIO", add_event_ent, pattern)
<del>doc = nlp(u"This is a text about Google I/O.")
<add>doc = nlp(u"This is a text about Google I/O")
<ide> matches = matcher(doc)
<ide> ```
<ide> | 1 |
Javascript | Javascript | fix tests + enable inline requires on react-native | d088750163bd45cb60c4c6796ed97624fb6f91bf | <ide><path>packager/react-packager/src/Activity/__tests__/Activity-test.js
<ide> describe('Activity', () => {
<ide>
<ide> expect(() => {
<ide> Activity.endEvent(eid);
<del> }).toThrow('event(3) has already ended!');
<add> }).toThrow('event(1) has already ended!');
<ide> });
<ide> });
<ide>
<ide> describe('Activity', () => {
<ide> Activity.signal(EVENT_NAME, DATA);
<ide> jest.runOnlyPendingTimers();
<ide>
<del> expect(console.log.mock.calls.length).toBe(3);
<del> const consoleMsg = console.log.mock.calls[2][0];
<add> expect(console.log.mock.calls.length).toBe(1);
<add> const consoleMsg = console.log.mock.calls[0][0];
<ide> expect(consoleMsg).toContain(EVENT_NAME);
<ide> expect(consoleMsg).toContain(JSON.stringify(DATA));
<ide> });
<ide><path>packager/react-packager/src/Cache/__tests__/Cache-test.js
<ide> jest
<ide>
<ide> var Promise = require('promise');
<ide> var fs = require('fs');
<add>var os = require('os');
<ide> var _ = require('underscore');
<ide>
<add>var Cache = require('../');
<add>
<ide> describe('JSTransformer Cache', () => {
<del> var Cache;
<ide> beforeEach(() => {
<del> require('os').tmpDir.mockImpl(() => 'tmpDir');
<del> Cache = require('../');
<add> os.tmpDir.mockImpl(() => 'tmpDir');
<ide> });
<ide>
<ide> describe('getting/setting', () => {
<ide><path>packager/react-packager/src/FileWatcher/__tests__/FileWatcher-test.js
<ide> jest
<ide> }
<ide> });
<ide>
<add>var FileWatcher = require('../');
<add>var sane = require('sane');
<add>
<ide> describe('FileWatcher', function() {
<del> var FileWatcher;
<ide> var Watcher;
<ide>
<ide> beforeEach(function() {
<del> require('mock-modules').dumpCache();
<del> FileWatcher = require('../');
<del> Watcher = require('sane').WatchmanWatcher;
<add> Watcher = sane.WatchmanWatcher;
<ide> Watcher.prototype.once.mockImplementation(function(type, callback) {
<ide> callback();
<ide> });
<ide><path>packager/react-packager/src/JSTransformer/__tests__/Transformer-test.js
<ide> jest
<ide> jest.mock('fs');
<ide>
<ide> var Cache = require('../../Cache');
<add>var Transformer = require('../');
<ide> var fs = require('fs');
<ide>
<ide> var options;
<ide>
<ide> describe('Transformer', function() {
<del> var Transformer;
<ide> var workers;
<ide>
<ide> beforeEach(function() {
<ide> describe('Transformer', function() {
<ide> transformModulePath: '/foo/bar',
<ide> cache: new Cache({}),
<ide> };
<del> Transformer = require('../');
<ide> });
<ide>
<ide> pit('should loadFileAndTransform', function() { | 4 |
Ruby | Ruby | remove old unavailable link with relevant fix | 29efc6ee05d00a55e6f901223c4db55ea66b9992 | <ide><path>actionpack/test/controller/redirect_test.rb
<ide> def redirect_to_url
<ide> end
<ide>
<ide> def redirect_to_url_with_unescaped_query_string
<del> redirect_to "http://dev.rubyonrails.org/query?status=new"
<add> redirect_to "http://example.com/query?status=new"
<ide> end
<ide>
<ide> def redirect_to_url_with_complex_scheme
<ide> def test_redirect_to_url
<ide> def test_redirect_to_url_with_unescaped_query_string
<ide> get :redirect_to_url_with_unescaped_query_string
<ide> assert_response :redirect
<del> assert_redirected_to "http://dev.rubyonrails.org/query?status=new"
<add> assert_redirected_to "http://example.com/query?status=new"
<ide> end
<ide>
<ide> def test_redirect_to_url_with_complex_scheme
<ide><path>activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
<ide> def supports_rename_index?
<ide> def configure_connection
<ide> variables = @config.fetch(:variables, {}).stringify_keys
<ide>
<del> # By default, MySQL 'where id is null' selects the last inserted id.
<del> # Turn this off. http://dev.rubyonrails.org/ticket/6778
<add> # By default, MySQL 'where id is null' selects the last inserted id; Turn this off.
<ide> variables['sql_auto_is_null'] = 0
<ide>
<ide> # Increase timeout so the server doesn't disconnect us.
<ide><path>activerecord/test/cases/finder_test.rb
<ide> def test_find_by_id_with_conditions_with_or
<ide> end
<ide> end
<ide>
<del> # http://dev.rubyonrails.org/ticket/6778
<ide> def test_find_ignores_previously_inserted_record
<ide> Post.create!(:title => 'test', :body => 'it out')
<ide> assert_equal [], Post.where(id: nil)
<ide><path>activerecord/test/cases/modules_test.rb
<ide> def test_assign_ids
<ide> end
<ide> end
<ide>
<del> # need to add an eager loading condition to force the eager loading model into
<del> # the old join model, to test that. See http://dev.rubyonrails.org/ticket/9640
<add> # An eager loading condition to force the eager loading model into the old join model.
<ide> def test_eager_loading_in_modules
<ide> clients = []
<ide> | 4 |
Ruby | Ruby | fix #inspect for new records. closes | a995b9cde074bec46ab4befc53f16ff91ec952f2 | <ide><path>activerecord/lib/active_record/base.rb
<ide> def attributes_before_type_cast
<ide>
<ide> # Format attributes nicely for inspect.
<ide> def attribute_for_inspect(attr_name)
<del> raise "Attribute not present #{attr_name}" unless has_attribute?(attr_name)
<add> raise "Attribute not present #{attr_name}" unless has_attribute?(attr_name) || new_record?
<ide> value = read_attribute(attr_name)
<ide>
<ide> if value.is_a?(String) && value.length > 50
<ide><path>activerecord/test/base_test.rb
<ide> def test_inspect
<ide> assert_equal topic.inspect, %(#<Topic id: 1, title: "The First Topic", author_name: "David", author_email_address: "david@loudthinking.com", written_on: "#{topic.written_on.to_s(:db)}", bonus_time: "#{topic.bonus_time.to_s(:db)}", last_read: "#{topic.last_read.to_s(:db)}", content: "Have a nice day", approved: false, replies_count: 1, parent_id: nil, type: nil>)
<ide> end
<ide>
<add> def test_inspect_new
<add> assert_match /Topic id: nil/, Topic.new.inspect
<add> end
<add>
<ide> def test_attribute_for_inspect
<ide> t = topics(:first)
<ide> t.content = %(This is some really long content, longer than 50 characters, so I can test that text is truncated correctly by the new ActiveRecord::Base#inspect method! Yay! BOOM!) | 2 |
PHP | PHP | use default request if necessary | 3a01c535cd1cc272a523558bb4b9b7d250b28387 | <ide><path>src/Illuminate/Foundation/Application.php
<ide> public function stack(Closure $stack)
<ide> */
<ide> public function run(SymfonyRequest $request = null)
<ide> {
<add> $request = $request ?: $this['request'];
<add>
<ide> with($response = $this->handleRequest($request))->send();
<ide>
<ide> $this->terminate($request, $response); | 1 |
Python | Python | use same tri format | bad3b6f78a39aa89e0bbab17fbb92ce1c6d9ca96 | <ide><path>numpy/lib/twodim_base.py
<ide> def tril_indices(n, k=0, m=None):
<ide> [-10, -10, -10, -10]])
<ide>
<ide> """
<del> tri = np.tri(n, m=m, k=k, dtype=bool)
<add> tri = np.tri(n, m, k=k, dtype=bool)
<ide>
<ide> return tuple(np.broadcast_to(inds, tri.shape)[tri]
<ide> for inds in np.indices(tri.shape, sparse=True)) | 1 |
Javascript | Javascript | remove unused parameter on module.instantiate | 517b0470c7e3147606425604dd9c8429cf0f4de4 | <ide><path>lib/internal/modules/esm/module_job.js
<ide> class ModuleJob {
<ide> const initWrapper = internalBinding('inspector').callAndPauseOnStart;
<ide> initWrapper(this.module.instantiate, this.module);
<ide> } else {
<del> this.module.instantiate(true);
<add> this.module.instantiate();
<ide> }
<ide> } catch (e) {
<ide> decorateErrorStack(e); | 1 |
Text | Text | provide replacements for deprecated util methods | bd6e0be0dfbbf6d10f1f054c43b0b82f25c60b16 | <ide><path>doc/api/util.md
<ide> added: v0.6.0
<ide> deprecated: v4.0.0
<ide> -->
<ide>
<del>> Stability: 0 - Deprecated
<add>> Stability: 0 - Deprecated: Use [`Array.isArray()`][] instead.
<ide>
<ide> * `object` {any}
<ide> * Returns: {boolean}
<ide>
<del>Internal alias for [`Array.isArray`][].
<add>Alias for [`Array.isArray()`][].
<ide>
<ide> Returns `true` if the given `object` is an `Array`. Otherwise, returns `false`.
<ide>
<ide> added: v0.11.5
<ide> deprecated: v4.0.0
<ide> -->
<ide>
<del>> Stability: 0 - Deprecated
<add>> Stability: 0 - Deprecated: Use `typeof value === 'boolean'` instead.
<ide>
<ide> * `object` {any}
<ide> * Returns: {boolean}
<ide> added: v0.11.5
<ide> deprecated: v4.0.0
<ide> -->
<ide>
<del>> Stability: 0 - Deprecated
<add>> Stability: 0 - Deprecated: Use `typeof value === 'function'` instead.
<ide>
<ide> * `object` {any}
<ide> * Returns: {boolean}
<ide> added: v0.11.5
<ide> deprecated: v4.0.0
<ide> -->
<ide>
<del>> Stability: 0 - Deprecated
<add>> Stability: 0 - Deprecated: Use `value === null` instead.
<ide>
<ide> * `object` {any}
<ide> * Returns: {boolean}
<ide> added: v0.11.5
<ide> deprecated: v4.0.0
<ide> -->
<ide>
<del>> Stability: 0 - Deprecated
<add>> Stability: 0 - Deprecated: Use
<add>> `value === undefined || value === null` instead.
<ide>
<ide> * `object` {any}
<ide> * Returns: {boolean}
<ide> added: v0.11.5
<ide> deprecated: v4.0.0
<ide> -->
<ide>
<del>> Stability: 0 - Deprecated
<add>> Stability: 0 - Deprecated: Use `typeof value === 'number'` instead.
<ide>
<ide> * `object` {any}
<ide> * Returns: {boolean}
<ide> added: v0.11.5
<ide> deprecated: v4.0.0
<ide> -->
<ide>
<del>> Stability: 0 - Deprecated
<add>> Stability: 0 - Deprecated:
<add>> Use `value !== null && typeof value === 'object'` instead.
<ide>
<ide> * `object` {any}
<ide> * Returns: {boolean}
<ide>
<ide> Returns `true` if the given `object` is strictly an `Object` **and** not a
<del>`Function`. Otherwise, returns `false`.
<add>`Function` (even though functions are objects in JavaScript).
<add>Otherwise, returns `false`.
<ide>
<ide> ```js
<ide> const util = require('util');
<ide> added: v0.11.5
<ide> deprecated: v4.0.0
<ide> -->
<ide>
<del>> Stability: 0 - Deprecated
<add>> Stability: 0 - Deprecated: Use
<add>> `(typeof value !== 'object' && typeof value !== 'function') || value === null`
<add>> instead.
<ide>
<ide> * `object` {any}
<ide> * Returns: {boolean}
<ide> added: v0.11.5
<ide> deprecated: v4.0.0
<ide> -->
<ide>
<del>> Stability: 0 - Deprecated
<add>> Stability: 0 - Deprecated: Use `typeof value === 'string'` instead.
<ide>
<ide> * `object` {any}
<ide> * Returns: {boolean}
<ide> added: v0.11.5
<ide> deprecated: v4.0.0
<ide> -->
<ide>
<del>> Stability: 0 - Deprecated
<add>> Stability: 0 - Deprecated: Use `typeof value === 'symbol'` instead.
<ide>
<ide> * `object` {any}
<ide> * Returns: {boolean}
<ide> added: v0.11.5
<ide> deprecated: v4.0.0
<ide> -->
<ide>
<del>> Stability: 0 - Deprecated
<add>> Stability: 0 - Deprecated: Use `value === undefined` instead.
<ide>
<ide> * `object` {any}
<ide> * Returns: {boolean}
<ide> deprecated: v0.11.3
<ide> Deprecated predecessor of `console.log`.
<ide>
<ide> [`'uncaughtException'`]: process.html#process_event_uncaughtexception
<del>[`Array.isArray`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
<add>[`Array.isArray()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
<ide> [`Buffer.isBuffer()`]: buffer.html#buffer_class_method_buffer_isbuffer_obj
<ide> [`Error`]: errors.html#errors_class_error
<ide> [`Object.assign()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign | 1 |
Javascript | Javascript | add some test cases for small u.s. counties | 4d268a796644a2036336738889b7e095cbae3e98 | <ide><path>test/geo/path-test.js
<ide> suite.addBatch({
<ide> },
<ide>
<ide> "antemeridian cutting": {
<add> "rotate([98, 0])": {
<add> topic: function() {
<add> return d3.geo.path()
<add> .context(testContext)
<add> .projection(d3.geo.equirectangular()
<add> .scale(900 / Math.PI)
<add> .rotate([98, 0])
<add> .precision(0));
<add> },
<add> "small U.S. county polygons": {
<add> "Keweenaw": function(path) {
<add> path({
<add> type: "Polygon",
<add> coordinates: [[[-88.23013, 47.198326], [-88.514931, 47.285957], [-88.383484, 47.285957], [-88.23013, 47.198326]]]
<add> });
<add> assert.equal(testContext.buffer().filter(function(d) { return d.type === "moveTo"; }).length, 1);
<add> },
<add> "Accomack": function(path) {
<add> path({
<add> type: "MultiPolygon",
<add> coordinates: [
<add> [[[-75.397659, 38.013497], [-75.244304, 38.029928], [-75.666029, 37.465803], [-75.939876, 37.547957], [-75.671506, 37.95325], [-75.622213, 37.991589], [-75.397659, 38.013497]]],
<add> [[[-76.016553, 37.95325], [-76.043938, 37.95325], [-75.994645, 37.95325], [-76.016553, 37.95325]]]
<add> ]
<add> });
<add> assert.equal(testContext.buffer().filter(function(d) { return d.type === "moveTo"; }).length, 2);
<add> },
<add> "Hopewell": function(path) {
<add> path({
<add> type: "Polygon",
<add> coordinates: [[[-77.298157, 37.312448], [-77.298157, 37.312448], [-77.336496, 37.312448], [-77.281726, 37.312448], [-77.298157, 37.312448]]]
<add> });
<add> assert.equal(testContext.buffer().filter(function(d) { return d.type === "moveTo"; }).length, 1);
<add> }
<add> }
<add> },
<ide> "rotate([330, 232])": {
<ide> topic: function() {
<ide> return d3.geo.path() | 1 |
Javascript | Javascript | define @@tostringtag as a data property | 06ecf4dec70bc35dcdc32993a23ed6360a82a8b2 | <ide><path>lib/internal/url.js
<ide> class URL {
<ide> parse(this, input, base);
<ide> }
<ide>
<del> get [Symbol.toStringTag]() {
<del> return this instanceof URL ? 'URL' : 'URLPrototype';
<del> }
<del>
<ide> get [special]() {
<ide> return (this[context].flags & binding.URL_FLAGS_SPECIAL) !== 0;
<ide> }
<ide> Object.defineProperties(URL.prototype, {
<ide> return ret;
<ide> }
<ide> },
<add> [Symbol.toStringTag]: {
<add> configurable: true,
<add> value: 'URL'
<add> },
<ide> href: {
<ide> enumerable: true,
<ide> configurable: true,
<ide><path>test/parallel/test-whatwg-url-properties.js
<ide> assert.strictEqual(url.searchParams, oldParams); // [SameObject]
<ide> // Note: this error message is subject to change in V8 updates
<ide> assert.throws(() => url.origin = 'http://foo.bar.com:22',
<ide> new RegExp('TypeError: Cannot set property origin of' +
<del> ' \\[object Object\\] which has only a getter'));
<add> ' \\[object URL\\] which has only a getter'));
<ide> assert.strictEqual(url.origin, 'http://foo.bar.com:21');
<ide> assert.strictEqual(url.toString(),
<ide> 'http://user:pass@foo.bar.com:21/aaa/zzz?l=25#test');
<ide> assert.strictEqual(url.hash, '#abcd');
<ide> // Note: this error message is subject to change in V8 updates
<ide> assert.throws(() => url.searchParams = '?k=88',
<ide> new RegExp('TypeError: Cannot set property searchParams of' +
<del> ' \\[object Object\\] which has only a getter'));
<add> ' \\[object URL\\] which has only a getter'));
<ide> assert.strictEqual(url.searchParams, oldParams);
<ide> assert.strictEqual(url.toString(),
<ide> 'https://user2:pass2@foo.bar.org:23/aaa/bbb?k=99#abcd');
<ide><path>test/parallel/test-whatwg-url-tostringtag.js
<ide> const sp = url.searchParams;
<ide>
<ide> const test = [
<ide> [toString.call(url), 'URL'],
<del> [toString.call(Object.getPrototypeOf(url)), 'URLPrototype'],
<ide> [toString.call(sp), 'URLSearchParams'],
<del> [toString.call(Object.getPrototypeOf(sp)), 'URLSearchParamsPrototype']
<add> [toString.call(Object.getPrototypeOf(sp)), 'URLSearchParamsPrototype'],
<add> // Web IDL spec says we have to return 'URLPrototype', but it is too
<add> // expensive to implement; therefore, use Chrome's behavior for now, until
<add> // spec is changed.
<add> [toString.call(Object.getPrototypeOf(url)), 'URL']
<ide> ];
<ide>
<ide> test.forEach((row) => { | 3 |
Ruby | Ruby | handle dirs with restricted permissions | a6e7858cbc95b2526ac481248ac72e8bdc2dc786 | <ide><path>Library/Homebrew/mktemp.rb
<ide> def run
<ide> begin
<ide> Dir.chdir(tmpdir) { yield self }
<ide> ensure
<del> ignore_interrupts { rm_rf(tmpdir) } unless retain?
<add> ignore_interrupts { chmod_rm_rf(tmpdir) } unless retain?
<ide> end
<ide> ensure
<ide> ohai "Temporary files retained at:", @tmpdir.to_s if retain? && !@tmpdir.nil? && !@quiet
<ide> end
<add>
<add> private
<add>
<add> def chmod_rm_rf(path)
<add> if path.directory? && !path.symlink?
<add> chmod("u+rw", path) if path.owned? # Need permissions in order to see the contents
<add> path.children.each { |child| chmod_rm_rf(child) }
<add> rmdir(path)
<add> else
<add> rm_f(path)
<add> end
<add> rescue
<add> nil # Just skip this directory.
<add> end
<ide> end | 1 |
Javascript | Javascript | notify user on error | a17143ee628b7c6ccad842be171abfe9e9bb4e3f | <ide><path>src/state-store.js
<ide> module.exports = class StateStore {
<ide> const dbOpenRequest = indexedDB.open(this.databaseName, this.version);
<ide> dbOpenRequest.onupgradeneeded = event => {
<ide> let db = event.target.result;
<del> db.onerror = event => {
<del> console.error('Error loading database', event);
<add> db.onerror = error => {
<add> atom.notifications.addError('Error loading database', {
<add> stack: new Error('Error loading database').stack,
<add> dismissable: true
<add> });
<add> console.error('Error loading database', error);
<ide> };
<ide> db.createObjectStore('states');
<ide> };
<ide> module.exports = class StateStore {
<ide> resolve(dbOpenRequest.result);
<ide> };
<ide> dbOpenRequest.onerror = error => {
<add> atom.notifications.addError('Could not connect to indexedDB', {
<add> stack: new Error('Could not connect to indexedDB').stack,
<add> dismissable: true
<add> });
<ide> console.error('Could not connect to indexedDB', error);
<ide> this.connected = false;
<ide> resolve(null); | 1 |
Python | Python | add spatial dropout and 3d global pooling to docs | 67e242d926b577f440217d9d10b890f54bb875c3 | <ide><path>docs/autogen.py
<ide> layers.Lambda,
<ide> layers.ActivityRegularization,
<ide> layers.Masking,
<add> layers.SpatialDropout1D,
<add> layers.SpatialDropout2D,
<add> layers.SpatialDropout3D,
<ide> ],
<ide> },
<ide> {
<ide> layers.GlobalAveragePooling1D,
<ide> layers.GlobalMaxPooling2D,
<ide> layers.GlobalAveragePooling2D,
<add> layers.GlobalMaxPooling3D,
<add> layers.GlobalAveragePooling3D,
<ide> ],
<ide> },
<ide> { | 1 |
Python | Python | fix issue #258 | 4355f4053f20f079d3f408b78c9145afc89b11f3 | <ide><path>glances/glances.py
<ide> def displayHelp(self, core):
<ide>
<ide> def displayBat(self, batpercent):
<ide> # Display the current batteries capacities % - Center
<del> if not batinfo_lib_tag and batpercent != []:
<add> if not batinfo_lib_tag or batpercent == []:
<ide> return 0
<ide> screen_x = self.screen.getmaxyx()[1]
<ide> screen_y = self.screen.getmaxyx()[0] | 1 |
Mixed | Ruby | add dbm_test_read analytics | 752714b71ceeb473bdbdb008e645c645cb428d96 | <ide><path>Library/Homebrew/cache_store.rb
<ide> def db
<ide> end
<ide> false
<ide> end
<add> Utils::Analytics.report_event("dbm_test_read", dbm_test_read_success.to_s)
<ide> cache_path.delete unless dbm_test_read_success
<ide> end
<ide> DBM.open(dbm_file_path, DATABASE_MODE, DBM::WRCREAT)
<ide><path>docs/Analytics.md
<ide> Homebrew's analytics records the following different events:
<ide> - an `event` hit type with the `install` event category and the Homebrew formula from a non-private GitHub tap you install plus any used options, e.g. `wget --with-pcre` as the action and an event label e.g. `macOS 10.12, non-/usr/local, CI` to indicate the OS version, non-standard installation location and invocation as part of CI. This allows us to identify the formulae that need fixing and where more easily.
<ide> - an `event` hit type with the `install_on_request` event category and the Homebrew formula from a non-private GitHub tap you have requested to install (e.g. explicitly named it with a `brew install`) plus options and an event label as above. This allows us to differentiate the formulae that users intend to install from those pulled in as dependencies.
<ide> - an `event` hit type with the `cask_install` event category and the Homebrew cask from a non-private GitHub tap you install as the action and an event label as above. This allows us to identify the casks that need fixing and where more easily.
<del>- an `event` hit type with the `BuildError` event category and the Homebrew formula that failed to install, e.g. `wget` as the action and an event label e.g. `macOS 10.12`
<add>- an `event` hit type with the `BuildError` event category and the Homebrew formula that failed to install, e.g. `wget` as the action and an event label e.g. `macOS 10.12`.
<add>- an `event` hit type with the `dbm_test_read` event category and `true` or `false` as the action (depending on if a corrupt DBM database was detected) and an event label e.g. `macOS 10.12`.
<ide>
<ide> You can also view all the information that is sent by Homebrew's analytics by setting `HOMEBREW_ANALYTICS_DEBUG=1` in your environment. Please note this will also stop any analytics from being sent.
<ide> | 2 |
Java | Java | fix checkstyle issue | 94c14c469e6cc7a7b568a08589b159dc27489411 | <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/function/DefaultEntityResponseBuilder.java
<ide> * you may not use this file except in compliance with the License.
<ide> * You may obtain a copy of the License at
<ide> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<add> * https://www.apache.org/licenses/LICENSE-2.0
<ide> *
<ide> * Unless required by applicable law or agreed to in writing, software
<ide> * distributed under the License is distributed on an "AS IS" BASIS, | 1 |
Go | Go | remove unused variable from container struct | 7a565a0479b6a797a0cdc9a4156e57ce811032b3 | <ide><path>container.go
<ide> type Container struct {
<ide> stdin io.ReadCloser
<ide> stdinPipe io.WriteCloser
<ide>
<del> stdoutLog *os.File
<del> stderrLog *os.File
<del> runtime *Runtime
<add> runtime *Runtime
<ide> }
<ide>
<ide> type Config struct { | 1 |
Javascript | Javascript | update loader.js texture double slash fix | 06522053e208bbba7ac00c41b244100c977c86b8 | <ide><path>src/loaders/Loader.js
<ide> THREE.Loader.prototype = {
<ide> function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
<ide>
<ide> var isCompressed = /\.dds$/i.test( sourceFile );
<del> var fullPath = texturePath + "/" + sourceFile;
<add>
<add> var fullPath = texturePath + texturePath.slice(-1) === '/' : '' : '/' + sourceFile;
<ide>
<ide> if ( isCompressed ) {
<ide> | 1 |
Javascript | Javascript | exclude the e2e test that fails on safari | deafb5e5459fce863d9254bfe621df18dd457648 | <ide><path>src/ng/filter/limitTo.js
<ide> expect(limitedLongNumber.getText()).toEqual('Output long number: 234');
<ide> });
<ide>
<del> it('should update the output when -3 is entered', function() {
<add> // There is a bug in safari and protractor that doesn't like the minus key
<add> xit('should update the output when -3 is entered', function() {
<ide> numLimitInput.clear();
<ide> numLimitInput.sendKeys('-3');
<ide> letterLimitInput.clear(); | 1 |
PHP | PHP | fix colours in dark terminals | 02f8709258369dc3f3dc84b6f2ce5b12fa939007 | <ide><path>src/Error/Debug/ConsoleFormatter.php
<ide> class ConsoleFormatter implements FormatterInterface
<ide> // cyan
<ide> 'class' => '0;36',
<ide> // grey
<del> 'punct' => '0;8',
<del> // black
<del> 'property' => '0;30',
<add> 'punct' => '0;90',
<add> // default foreground
<add> 'property' => '0;39',
<ide> // magenta
<ide> 'visibility' => '0;35',
<ide> // red | 1 |
PHP | PHP | add sftp to supported storage drivers | 2572ce1e3698cfdb6563a725aa5d36692665e805 | <ide><path>config/filesystems.php
<ide> | may even configure multiple disks of the same driver. Defaults have
<ide> | been setup for each driver as an example of the required options.
<ide> |
<del> | Supported Drivers: "local", "ftp", "s3", "rackspace"
<add> | Supported Drivers: "local", "ftp", "sftp", "s3", "rackspace"
<ide> |
<add> | Note: SFTP driver is supported as of Laravel 5.6.6.
<ide> */
<ide>
<ide> 'disks' => [ | 1 |
Text | Text | add v3.15.0-beta.4 to changelog | a590298a3ac9d3199217ae02c56e0d21e809f2fd | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### v3.15.0-beta.4 (November 25, 2019)
<add>
<add>- [#17834](https://github.com/emberjs/ember.js/pull/17834) [BUGFIX] Prevents autotracking ArrayProxy creation
<add>- [#18554](https://github.com/emberjs/ember.js/pull/18554) [BREAKING BUGFIX] Adds autotracking transaction
<add>
<ide> ### v3.15.0-beta.3 (November 18, 2019)
<ide>
<ide> - [#18549](https://github.com/emberjs/ember.js/pull/18549) [BUGFIX] Add component reference to the mouse event handler deprecation warnings | 1 |
PHP | PHP | convert iniacl to use the instanceconfigtrait | b9bad846bfc6056ec9372e9a7e96a8300933da83 | <ide><path>src/Controller/Component/Acl/IniAcl.php
<ide>
<ide> use Cake\Configure\Engine\IniConfig;
<ide> use Cake\Controller\Component;
<add>use Cake\Core\InstanceConfigTrait;
<ide> use Cake\Core\Object;
<ide> use Cake\Utility\Hash;
<ide>
<ide> */
<ide> class IniAcl extends Object implements AclInterface {
<ide>
<del>/**
<del> * Array with configuration, parsed from ini file
<del> *
<del> * @var array
<del> */
<del> public $config = null;
<add> use InstanceConfigTrait {
<add> config as protected _traitConfig;
<add> }
<ide>
<ide> /**
<ide> * The Hash::extract() path to the user/aro identifier in the
<ide> class IniAcl extends Object implements AclInterface {
<ide> */
<ide> public $userPath = 'User.username';
<ide>
<add>/**
<add> * Default config for this class
<add> *
<add> * @var array
<add> */
<add> protected $_defaultConfig = [];
<add>
<add>/**
<add> * read/write config
<add> *
<add> * Load acl config on first access. Wraps the InstanceConfigTrait method, taking
<add> * care of the trait's implementation of determining intent from tne number of
<add> * passed arguments
<add> *
<add> * @param string|array|null $key The key to get/set, or a complete array of configs.
<add> * @param mixed|null $value The value to set.
<add> * @param bool $merge Whether to merge or overwrite existing config defaults to true.
<add> * @return mixed Config value being read, or the object itself on write operations.
<add> * @throws \Cake\Error\Exception When trying to set a key that is invalid.
<add> */
<add> public function config($key = null, $value = null, $merge = true) {
<add> if (!$this->_configInitialized) {
<add> $this->_defaultConfig = $this->readConfigFile(APP . 'Config/acl.ini.php');
<add> }
<add>
<add> if (is_array($key) || func_num_args() >= 2) {
<add> return $this->_traitConfig($key, $value, $merge);
<add> }
<add>
<add> return $this->_traitConfig($key);
<add> }
<add>
<ide> /**
<ide> * Initialize method
<ide> *
<ide> public function inherit($aro, $aco, $action = "*") {
<ide> * @return boolean Success
<ide> */
<ide> public function check($aro, $aco, $action = null) {
<del> if (!$this->config) {
<del> $this->config = $this->readConfigFile(APP . 'Config/acl.ini.php');
<del> }
<del> $aclConfig = $this->config;
<add> $aclConfig = $this->config();
<ide>
<ide> if (is_array($aro)) {
<ide> $aro = Hash::get($aro, $this->userPath); | 1 |
Mixed | Text | use correct brand name across codebase | 3b056aa7b4f3aa636058559f16e22a1504b4b2dd | <ide><path>client/src/pages/learn/apis-and-microservices/basic-node-and-express/index.md
<ide> Node.js is a JavaScript runtime that allows developers to write backend (server-
<ide>
<ide> Express, while not included with Node.js, is another module often used with it. Express runs between the server created by Node.js and the frontend pages of a web application. Express also handles an application's routing. Routing directs users to the correct page based on their interaction with the application. While there are alternatives to using Express, its simplicity makes it a good place to begin when learning the interaction between a backend powered by Node.js and the frontend.
<ide>
<del>Working on these challenges will involve you writing your code on Repl.it on our starter project. After completing each challenge you can copy your public Repl.it URL (to the homepage of your app) into the challenge screen to test it! Optionally you may choose to write your project on another platform but it must be publicly visible for our testing.
<add>Working on these challenges will involve you writing your code on Replit on our starter project. After completing each challenge you can copy your public Replit URL (to the homepage of your app) into the challenge screen to test it! Optionally you may choose to write your project on another platform but it must be publicly visible for our testing.
<ide>
<del>Start this project on Repl.it using <a href='https://repl.it/github/freeCodeCamp/boilerplate-express'>this link</a> or clone <a href='https://github.com/freeCodeCamp/boilerplate-express/'>this repository</a> on GitHub! If you use Repl.it, remember to save the link to your project somewhere safe!
<add>Start this project on Replit using <a href='https://replit.com/github/freeCodeCamp/boilerplate-express'>this link</a> or clone <a href='https://github.com/freeCodeCamp/boilerplate-express/'>this repository</a> on GitHub! If you use Replit, remember to save the link to your project somewhere safe!
<ide><path>client/src/pages/learn/apis-and-microservices/managing-packages-with-npm/index.md
<ide> npm saves packages in a folder named <code>node\_modules</code>. These packages
<ide> 2. locally within a project's own <code>node\_modules</code> folder, accessible only to that project.
<ide>
<ide> Most developers prefer to install packages local to each project to create a separation between the dependencies of different projects.
<del>Working on these challenges will involve you writing your code on Repl.it on our starter project. After completing each challenge you can copy your public Repl.it URL (to the homepage of your app) into the challenge screen to test it! Optionally you may choose to write your project on another platform but it must be publicly visible for our testing.
<add>Working on these challenges will involve you writing your code on Replit on our starter project. After completing each challenge you can copy your public Replit URL (to the homepage of your app) into the challenge screen to test it! Optionally you may choose to write your project on another platform but it must be publicly visible for our testing.
<ide>
<del>Start this project on Repl.it using <a href='https://repl.it/github/freeCodeCamp/boilerplate-npm'>this link</a> or clone <a href='https://github.com/freeCodeCamp/boilerplate-npm/'>this repository</a> on GitHub! If you use Repl.it, remember to save the link to your project somewhere safe!
<add>Start this project on Replit using <a href='https://replit.com/github/freeCodeCamp/boilerplate-npm'>this link</a> or clone <a href='https://github.com/freeCodeCamp/boilerplate-npm/'>this repository</a> on GitHub! If you use Replit, remember to save the link to your project somewhere safe!
<ide><path>client/src/pages/learn/apis-and-microservices/mongodb-and-mongoose/index.md
<ide> While there are many non-relational databases, Mongo's use of JSON as its docume
<ide>
<ide> Mongoose.js is an npm module for Node.js that allows you to write objects for Mongo as you would in JavaScript. This can make it easier to construct documents for storage in Mongo.
<ide>
<del>Working on these challenges will involve you writing your code on Repl.it on our starter project. After completing each challenge you can copy your public Repl.it URL (to the homepage of your app) into the challenge screen to test it! Optionally you may choose to write your project on another platform but it must be publicly visible for our testing.
<add>Working on these challenges will involve you writing your code on Replit on our starter project. After completing each challenge you can copy your public Replit URL (to the homepage of your app) into the challenge screen to test it! Optionally you may choose to write your project on another platform but it must be publicly visible for our testing.
<ide>
<del>Start this project on Repl.it using [this link](https://repl.it/github/freeCodeCamp/boilerplate-mongomongoose) or clone [this repository](https://github.com/freeCodeCamp/boilerplate-mongomongoose/) on GitHub! If you use Repl.it, remember to save the link to your project somewhere safe!
<add>Start this project on Replit using [this link](https://replit.com/github/freeCodeCamp/boilerplate-mongomongoose) or clone [this repository](https://github.com/freeCodeCamp/boilerplate-mongomongoose/) on GitHub! If you use Replit, remember to save the link to your project somewhere safe!
<ide>
<ide> ## Use MongoDB Atlas to host a free mongodb instance for your projects
<ide>
<ide><path>client/src/pages/learn/information-security/information-security-with-helmetjs/index.md
<ide> superBlock: Information Security
<ide>
<ide> HelmetJS is a type of middleware for Express-based applications that automatically sets HTTP headers to prevent sensitive information from unintentionally being passed between the server and client. While HelmetJS does not account for all situations, it does include support for common ones like Content Security Policy, XSS Filtering, and HTTP Strict Transport Security, among others. HelmetJS can be installed on an Express project from npm, after which each layer of protection can be configured to best fit the project.
<ide>
<del>Working on these challenges will involve you writing your code on Repl.it on our starter project. After completing each challenge, you can copy your public Repl.it URL (to the homepage of your app) into the challenge screen to test it! Optionally, you may choose to write your project on another platform, but it must be publicly visible for our testing.
<add>Working on these challenges will involve you writing your code on Replit on our starter project. After completing each challenge, you can copy your public Replit URL (to the homepage of your app) into the challenge screen to test it! Optionally, you may choose to write your project on another platform, but it must be publicly visible for our testing.
<ide>
<del>Start this project on Repl.it using <a rel='noopener noreferrer' target='_blank' href='https://repl.it/github/freeCodeCamp/boilerplate-infosec'>this link</a> or clone <a rel='noopener noreferrer' target='_blank' href='https://github.com/freeCodeCamp/boilerplate-infosec/'>this repository</a> on GitHub! If you use Repl.it, remember to save the link to your project somewhere safe!
<add>Start this project on Replit using <a rel='noopener noreferrer' target='_blank' href='https://replit.com/github/freeCodeCamp/boilerplate-infosec'>this link</a> or clone <a rel='noopener noreferrer' target='_blank' href='https://github.com/freeCodeCamp/boilerplate-infosec/'>this repository</a> on GitHub! If you use Replit, remember to save the link to your project somewhere safe!
<ide><path>client/src/pages/learn/quality-assurance/advanced-node-and-express/index.md
<ide> superBlock: Quality Assurance
<ide>
<ide> *Authentication* is the process or action of verifying the identity of a user or process. Up to this point you have not been able to create an app utilizing this key concept.
<ide>
<del>The most common and easiest way to use authentication middleware for Node.js is [Passport](http://passportjs.org/). It is easy to learn, light-weight, and extremely flexible allowing for many *strategies*, which we will talk about in later challenges. In addition to authentication we will also look at template engines which allow for use of *Pug* and web sockets which allow for real time communication between all your clients and your server. Working on these challenges will involve you writing your code on Repl.it on our starter project. After completing each challenge you can copy your public Repl.it URL (to the homepage of your app) into the challenge screen to test it! Optionally you may choose to write your project on another platform but it must be publicly visible for our testing.
<add>The most common and easiest way to use authentication middleware for Node.js is [Passport](http://passportjs.org/). It is easy to learn, light-weight, and extremely flexible allowing for many *strategies*, which we will talk about in later challenges. In addition to authentication we will also look at template engines which allow for use of *Pug* and web sockets which allow for real time communication between all your clients and your server. Working on these challenges will involve you writing your code on Replit on our starter project. After completing each challenge you can copy your public Replit URL (to the homepage of your app) into the challenge screen to test it! Optionally you may choose to write your project on another platform but it must be publicly visible for our testing.
<ide>
<del>Start this project on Repl.it using [this link](https://repl.it/github/freeCodeCamp/boilerplate-advancednode) or clone [this repository](https://github.com/freeCodeCamp/boilerplate-advancednode/) on GitHub! If you use Repl.it, remember to save the link to your project somewhere safe.
<add>Start this project on Replit using [this link](https://replit.com/github/freeCodeCamp/boilerplate-advancednode) or clone [this repository](https://github.com/freeCodeCamp/boilerplate-advancednode/) on GitHub! If you use Replit, remember to save the link to your project somewhere safe.
<ide><path>client/src/pages/learn/quality-assurance/quality-assurance-and-testing-with-chai/index.md
<ide> superBlock: Quality Assurance
<ide>
<ide> As your programs become more complex, you need to test them often to make sure any new code you add doesn't break the program's original functionality. Chai is a JavaScript testing library that helps you check that your program still behaves the way you expect it to after you make changes. Using Chai, you can write tests that describe your program's requirements and see if your program meets them.
<ide>
<del>Working on these challenges will involve you writing your code on Repl.it on our starter project. After completing each challenge you can copy your public Repl.it URL (to the homepage of your app) into the challenge screen to test it! Optionally you may choose to write your project on another platform but it must be publicly visible for our testing.
<add>Working on these challenges will involve you writing your code on Replit on our starter project. After completing each challenge you can copy your public Replit URL (to the homepage of your app) into the challenge screen to test it! Optionally you may choose to write your project on another platform but it must be publicly visible for our testing.
<ide>
<del>Start this project on Repl.it using [this link](https://repl.it/github/freeCodeCamp/boilerplate-mochachai) or clone [this repository](https://github.com/freeCodeCamp/boilerplate-mochachai/) on GitHub! If you use Repl.it, remember to save the link to your project somewhere safe!
<add>Start this project on Replit using [this link](https://replit.com/github/freeCodeCamp/boilerplate-mochachai) or clone [this repository](https://github.com/freeCodeCamp/boilerplate-mochachai/) on GitHub! If you use Replit, remember to save the link to your project somewhere safe!
<ide><path>client/src/templates/Challenges/projects/SolutionForm.js
<ide> export class SolutionForm extends Component {
<ide> solutionLink +
<ide> (description.includes('Colaboratory')
<ide> ? 'https://colab.research.google.com/drive/1i5EmInTWi1RFvFr2_aRXky96YxY6sbWy'
<del> : 'https://repl.it/@camperbot/hello');
<add> : 'https://replit.com/@camperbot/hello');
<ide> break;
<ide>
<ide> default:
<ide><path>curriculum/challenges/english/05-apis-and-microservices/apis-and-microservices-projects/exercise-tracker.md
<ide> dashedName: exercise-tracker
<ide> Build a full stack JavaScript app that is functionally similar to this: <https://exercise-tracker.freecodecamp.rocks/>. Working on this project will involve you writing your code using one of the following methods:
<ide>
<ide> - Clone [this GitHub repo](https://github.com/freeCodeCamp/boilerplate-project-exercisetracker/) and complete your project locally.
<del>- Use [our replit.com starter project](https://replit.com/github/freeCodeCamp/boilerplate-project-exercisetracker) to complete your project.
<add>- Use [our Replit starter project](https://replit.com/github/freeCodeCamp/boilerplate-project-exercisetracker) to complete your project.
<ide> - Use a site builder of your choice to complete the project. Be sure to incorporate all the files from our GitHub repo.
<ide>
<ide> When you are done, make sure a working demo of your project is hosted somewhere public. Then submit the URL to it in the `Solution Link` field. Optionally, also submit a link to your project's source code in the `GitHub Link` field.
<ide><path>curriculum/challenges/english/05-apis-and-microservices/apis-and-microservices-projects/file-metadata-microservice.md
<ide> dashedName: file-metadata-microservice
<ide> Build a full stack JavaScript app that is functionally similar to this: <https://file-metadata-microservice.freecodecamp.rocks/>. Working on this project will involve you writing your code using one of the following methods:
<ide>
<ide> - Clone [this GitHub repo](https://github.com/freeCodeCamp/boilerplate-project-filemetadata/) and complete your project locally.
<del>- Use [our replit.com starter project](https://replit.com/github/freeCodeCamp/boilerplate-project-filemetadata) to complete your project.
<add>- Use [our Replit starter project](https://replit.com/github/freeCodeCamp/boilerplate-project-filemetadata) to complete your project.
<ide> - Use a site builder of your choice to complete the project. Be sure to incorporate all the files from our GitHub repo.
<ide>
<ide> When you are done, make sure a working demo of your project is hosted somewhere public. Then submit the URL to it in the `Solution Link` field. Optionally, also submit a link to your projects source code in the `GitHub Link` field.
<ide><path>curriculum/challenges/english/05-apis-and-microservices/apis-and-microservices-projects/request-header-parser-microservice.md
<ide> dashedName: request-header-parser-microservice
<ide> Build a full stack JavaScript app that is functionally similar to this: <https://request-header-parser-microservice.freecodecamp.rocks/>. Working on this project will involve you writing your code using one of the following methods:
<ide>
<ide> - Clone [this GitHub repo](https://github.com/freeCodeCamp/boilerplate-project-headerparser/) and complete your project locally.
<del>- Use [our replit.com starter project](https://replit.com/github/freeCodeCamp/boilerplate-project-headerparser) to complete your project.
<add>- Use [our Replit starter project](https://replit.com/github/freeCodeCamp/boilerplate-project-headerparser) to complete your project.
<ide> - Use a site builder of your choice to complete the project. Be sure to incorporate all the files from our GitHub repo.
<ide>
<ide> When you are done, make sure a working demo of your project is hosted somewhere public. Then submit the URL to it in the `Solution Link` field. Optionally, also submit a link to your project's source code in the `GitHub Link` field.
<ide><path>curriculum/challenges/english/05-apis-and-microservices/apis-and-microservices-projects/timestamp-microservice.md
<ide> dashedName: timestamp-microservice
<ide> Build a full stack JavaScript app that is functionally similar to this: <https://timestamp-microservice.freecodecamp.rocks/>. Working on this project will involve you writing your code using one of the following methods:
<ide>
<ide> - Clone [this GitHub repo](https://github.com/freeCodeCamp/boilerplate-project-timestamp/) and complete your project locally.
<del>- Use [our replit.com starter project](https://replit.com/github/freeCodeCamp/boilerplate-project-timestamp) to complete your project.
<add>- Use [our Replit starter project](https://replit.com/github/freeCodeCamp/boilerplate-project-timestamp) to complete your project.
<ide> - Use a site builder of your choice to complete the project. Be sure to incorporate all the files from our GitHub repo.
<ide>
<ide> When you are done, make sure a working demo of your project is hosted somewhere public. Then submit the URL to it in the `Solution Link` field. Optionally, also submit a link to your projects source code in the `GitHub Link` field.
<ide><path>curriculum/challenges/english/05-apis-and-microservices/apis-and-microservices-projects/url-shortener-microservice.md
<ide> dashedName: url-shortener-microservice
<ide> Build a full stack JavaScript app that is functionally similar to this: <https://url-shortener-microservice.freecodecamp.rocks/>. Working on this project will involve you writing your code using one of the following methods:
<ide>
<ide> - Clone [this GitHub repo](https://github.com/freeCodeCamp/boilerplate-project-urlshortener/) and complete your project locally.
<del>- Use [our replit.com starter project](https://replit.com/github/freeCodeCamp/boilerplate-project-urlshortener) to complete your project.
<add>- Use [our Replit starter project](https://replit.com/github/freeCodeCamp/boilerplate-project-urlshortener) to complete your project.
<ide> - Use a site builder of your choice to complete the project. Be sure to incorporate all the files from our GitHub repo.
<ide>
<ide> When you are done, make sure a working demo of your project is hosted somewhere public. Then submit the URL to it in the `Solution Link` field. Optionally, also submit a link to your projects source code in the `GitHub Link` field.
<ide><path>curriculum/challenges/english/05-apis-and-microservices/basic-node-and-express/meet-the-node-console.md
<ide> dashedName: meet-the-node-console
<ide> Working on these challenges will involve you writing your code using one of the following methods:
<ide>
<ide> - Clone [this GitHub repo](https://github.com/freeCodeCamp/boilerplate-express/) and complete these challenges locally.
<del>- Use [our Replit.com starter project](https://replit.com/github/freeCodeCamp/boilerplate-express) to complete these challenges.
<add>- Use [our Replit starter project](https://replit.com/github/freeCodeCamp/boilerplate-express) to complete these challenges.
<ide> - Use a site builder of your choice to complete the project. Be sure to incorporate all the files from our GitHub repo.
<ide>
<ide> When you are done, make sure a working demo of your project is hosted somewhere public. Then submit the URL to it in the `Solution Link` field.
<ide>
<ide> During the development process, it is important to be able to check what’s going on in your code.
<ide>
<del>Node is just a JavaScript environment. Like client side JavaScript, you can use the console to display useful debug information. On your local machine, you would see console output in a terminal. On Replit.com, a terminal is open in the right pane by default.
<add>Node is just a JavaScript environment. Like client side JavaScript, you can use the console to display useful debug information. On your local machine, you would see console output in a terminal. On Replit, a terminal is open in the right pane by default.
<ide>
<ide> We recommend to keep the terminal open while working at these challenges. By reading the output in the terminal, you can see any errors that may occur.
<ide>
<ide><path>curriculum/challenges/english/05-apis-and-microservices/basic-node-and-express/start-a-working-express-server.md
<ide> will serve the string 'Response String'.
<ide>
<ide> # --instructions--
<ide>
<del>Use the `app.get()` method to serve the string "Hello Express" to GET requests matching the `/` (root) path. Be sure that your code works by looking at the logs, then see the results in the preview if you are using Replit.com.
<add>Use the `app.get()` method to serve the string "Hello Express" to GET requests matching the `/` (root) path. Be sure that your code works by looking at the logs, then see the results in the preview if you are using Replit.
<ide>
<ide> **Note:** All the code for these lessons should be added in between the few lines of code we have started you off with.
<ide>
<ide><path>curriculum/challenges/english/05-apis-and-microservices/managing-packages-with-npm/how-to-use-package.json-the-core-of-any-node.js-project-or-npm-package.md
<ide> dashedName: how-to-use-package-json-the-core-of-any-node-js-project-or-npm-packa
<ide> Working on these challenges will involve you writing your code using one of the following methods:
<ide>
<ide> - Clone [this GitHub repo](https://github.com/freeCodeCamp/boilerplate-npm/) and complete these challenges locally.
<del>- Use [our Replit.com starter project](https://replit.com/github/freeCodeCamp/boilerplate-npm) to complete these challenges.
<add>- Use [our Replit starter project](https://replit.com/github/freeCodeCamp/boilerplate-npm) to complete these challenges.
<ide> - Use a site builder of your choice to complete the project. Be sure to incorporate all the files from our GitHub repo.
<ide>
<ide> When you are done, make sure a working demo of your project is hosted somewhere public. Then submit the URL to it in the `Solution Link` field. Optionally, also submit a link to your project's source code in the `GitHub Link` field.
<ide><path>curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/create-a-model.md
<ide> dashedName: create-a-model
<ide>
<ide> First of all we need a Schema. Each schema maps to a MongoDB collection. It defines the shape of the documents within that collection. Schemas are building block for Models. They can be nested to create complex models, but in this case we'll keep things simple. A model allows you to create instances of your objects, called documents.
<ide>
<del>Replit.com is a real server, and in real servers the interactions with the database happen in handler functions. These functions are executed when some event happens (e.g. someone hits an endpoint on your API). We’ll follow the same approach in these exercises. The `done()` function is a callback that tells us that we can proceed after completing an asynchronous operation such as inserting, searching, updating, or deleting. It's following the Node convention, and should be called as `done(null, data)` on success, or `done(err)` on error.
<add>Replit is a real server, and in real servers the interactions with the database happen in handler functions. These functions are executed when some event happens (e.g. someone hits an endpoint on your API). We’ll follow the same approach in these exercises. The `done()` function is a callback that tells us that we can proceed after completing an asynchronous operation such as inserting, searching, updating, or deleting. It's following the Node convention, and should be called as `done(null, data)` on success, or `done(err)` on error.
<ide>
<ide> Warning - When interacting with remote services, errors may occur!
<ide>
<ide><path>curriculum/challenges/english/05-apis-and-microservices/mongodb-and-mongoose/install-and-set-up-mongoose.md
<ide> dashedName: install-and-set-up-mongoose
<ide> Working on these challenges will involve you writing your code using one of the following methods:
<ide>
<ide> - Clone [this GitHub repo](https://github.com/freeCodeCamp/boilerplate-mongomongoose/) and complete these challenges locally.
<del>- Use [our Replit.com starter project](https://replit.com/github/freeCodeCamp/boilerplate-mongomongoose) to complete these challenges.
<add>- Use [our Replit starter project](https://replit.com/github/freeCodeCamp/boilerplate-mongomongoose) to complete these challenges.
<ide> - Use a site builder of your choice to complete the project. Be sure to incorporate all the files from our GitHub repo.
<ide>
<ide> When you are done, make sure a working demo of your project is hosted somewhere public. Then submit the URL to it in the `Solution Link` field.
<ide><path>curriculum/challenges/english/06-quality-assurance/advanced-node-and-express/implementation-of-social-authentication.md
<ide> The basic path this kind of authentication will follow in your app is:
<ide>
<ide> Strategies with OAuth require you to have at least a *Client ID* and a *Client Secret* which is a way for the service to verify who the authentication request is coming from and if it is valid. These are obtained from the site you are trying to implement authentication with, such as GitHub, and are unique to your app--**THEY ARE NOT TO BE SHARED** and should never be uploaded to a public repository or written directly in your code. A common practice is to put them in your `.env` file and reference them like so: `process.env.GITHUB_CLIENT_ID`. For this challenge we're going to use the GitHub strategy.
<ide>
<del>Obtaining your *Client ID and Secret* from GitHub is done in your account profile settings under 'developer settings', then '[OAuth applications](https://github.com/settings/developers)'. Click 'Register a new application', name your app, paste in the url to your Replit.com homepage (**Not the project code's url**), and lastly, for the callback url, paste in the same url as the homepage but with `/auth/github/callback` added on. This is where users will be redirected for us to handle after authenticating on GitHub. Save the returned information as `'GITHUB_CLIENT_ID'` and `'GITHUB_CLIENT_SECRET'` in your `.env` file.
<add>Obtaining your *Client ID and Secret* from GitHub is done in your account profile settings under 'developer settings', then '[OAuth applications](https://github.com/settings/developers)'. Click 'Register a new application', name your app, paste in the url to your Replit homepage (**Not the project code's url**), and lastly, for the callback url, paste in the same url as the homepage but with `/auth/github/callback` added on. This is where users will be redirected for us to handle after authenticating on GitHub. Save the returned information as `'GITHUB_CLIENT_ID'` and `'GITHUB_CLIENT_SECRET'` in your `.env` file.
<ide>
<ide> In your `routes.js` file, add `showSocialAuth: true` to the homepage route, after `showRegistration: true`. Now, create 2 routes accepting GET requests: `/auth/github` and `/auth/github/callback`. The first should only call passport to authenticate `'github'`. The second should call passport to authenticate `'github'` with a failure redirect to `/`, and then if that is successful redirect to `/profile` (similar to our last project).
<ide>
<ide><path>curriculum/challenges/english/06-quality-assurance/advanced-node-and-express/set-up-a-template-engine.md
<ide> dashedName: set-up-a-template-engine
<ide> Working on these challenges will involve you writing your code using one of the following methods:
<ide>
<ide> - Clone [this GitHub repo](https://github.com/freeCodeCamp/boilerplate-advancednode/) and complete these challenges locally.
<del>- Use [our Replit.com starter project](https://replit.com/github/freeCodeCamp/boilerplate-advancednode) to complete these challenges.
<add>- Use [our Replit starter project](https://replit.com/github/freeCodeCamp/boilerplate-advancednode) to complete these challenges.
<ide> - Use a site builder of your choice to complete the project. Be sure to incorporate all the files from our GitHub repo.
<ide>
<ide> When you are done, make sure a working demo of your project is hosted somewhere public. Then submit the URL to it in the `Solution Link` field.
<ide><path>curriculum/challenges/english/06-quality-assurance/quality-assurance-and-testing-with-chai/assert-deep-equality-with-.deepequal-and-.notdeepequal.md
<ide> dashedName: assert-deep-equality-with--deepequal-and--notdeepequal
<ide>
<ide> # --description--
<ide>
<del>As a reminder, this project is being built upon the following starter project on [Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
<add>As a reminder, this project is being built upon the following starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
<ide>
<ide> `deepEqual()` asserts that two objects are deep equal.
<ide>
<ide><path>curriculum/challenges/english/06-quality-assurance/quality-assurance-and-testing-with-chai/compare-the-properties-of-two-elements.md
<ide> dashedName: compare-the-properties-of-two-elements
<ide>
<ide> # --description--
<ide>
<del>As a reminder, this project is being built upon the following starter project on [Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
<add>As a reminder, this project is being built upon the following starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
<ide>
<ide> # --instructions--
<ide>
<ide><path>curriculum/challenges/english/06-quality-assurance/quality-assurance-and-testing-with-chai/learn-how-javascript-assertions-work.md
<ide> dashedName: learn-how-javascript-assertions-work
<ide> Working on these challenges will involve you writing your code using one of the following methods:
<ide>
<ide> - Clone [this GitHub repo](https://github.com/freeCodeCamp/boilerplate-mochachai/) and complete these challenges locally.
<del>- Use [our Replit.com starter project](https://replit.com/github/freeCodeCamp/boilerplate-mochachai) to complete these challenges.
<add>- Use [our Replit starter project](https://replit.com/github/freeCodeCamp/boilerplate-mochachai) to complete these challenges.
<ide> - Use a site builder of your choice to complete the project. Be sure to incorporate all the files from our GitHub repo.
<ide>
<ide> When you are done, make sure a working demo of your project is hosted somewhere public. Then submit the URL to it in the `Solution Link` field.
<ide><path>curriculum/challenges/english/06-quality-assurance/quality-assurance-and-testing-with-chai/run-functional-tests-on-an-api-response-using-chai-http-iii---put-method.md
<ide> dashedName: run-functional-tests-on-an-api-response-using-chai-http-iii---put-me
<ide>
<ide> # --description--
<ide>
<del>As a reminder, this project is being built upon the following starter project on [Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
<add>As a reminder, this project is being built upon the following starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
<ide>
<ide> In the next example we'll see how to send data in a request payload (body). We are going to test a PUT request. The `'/travellers'` endpoint accepts a JSON object taking the structure:
<ide>
<ide><path>curriculum/challenges/english/06-quality-assurance/quality-assurance-and-testing-with-chai/run-functional-tests-on-an-api-response-using-chai-http-iv---put-method.md
<ide> dashedName: run-functional-tests-on-an-api-response-using-chai-http-iv---put-met
<ide>
<ide> # --description--
<ide>
<del>As a reminder, this project is being built upon the following starter project on [Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/). This exercise is similar to the preceding one. Look at it for the details.
<add>As a reminder, this project is being built upon the following starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/). This exercise is similar to the preceding one. Look at it for the details.
<ide>
<ide> Now that you have seen how it is done, it is your turn to do it from scratch.
<ide>
<ide><path>curriculum/challenges/english/06-quality-assurance/quality-assurance-and-testing-with-chai/run-functional-tests-on-api-endpoints-using-chai-http-ii.md
<ide> dashedName: run-functional-tests-on-api-endpoints-using-chai-http-ii
<ide>
<ide> # --description--
<ide>
<del>As a reminder, this project is being built upon the following starter project on [Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
<add>As a reminder, this project is being built upon the following starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
<ide>
<ide> # --instructions--
<ide>
<ide><path>curriculum/challenges/english/06-quality-assurance/quality-assurance-and-testing-with-chai/run-functional-tests-on-api-endpoints-using-chai-http.md
<ide> dashedName: run-functional-tests-on-api-endpoints-using-chai-http
<ide>
<ide> # --description--
<ide>
<del>As a reminder, this project is being built upon the following starter project on [Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
<add>As a reminder, this project is being built upon the following starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
<ide>
<ide> Mocha allows testing asyncronous operations. There is a small (BIG) difference. Can you spot it?
<ide>
<ide><path>curriculum/challenges/english/06-quality-assurance/quality-assurance-and-testing-with-chai/run-functional-tests-using-a-headless-browser-ii.md
<ide> dashedName: run-functional-tests-using-a-headless-browser-ii
<ide>
<ide> # --description--
<ide>
<del>As a reminder, this project is being built upon the following starter project on [Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
<add>As a reminder, this project is being built upon the following starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
<ide>
<ide> # --instructions--
<ide>
<ide><path>curriculum/challenges/english/06-quality-assurance/quality-assurance-and-testing-with-chai/run-functional-tests-using-a-headless-browser.md
<ide> dashedName: run-functional-tests-using-a-headless-browser
<ide>
<ide> # --description--
<ide>
<del>As a reminder, this project is being built upon the following starter project on [Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
<add>As a reminder, this project is being built upon the following starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
<ide>
<ide> In the HTML main view we provided a input form. It sends data to the `PUT /travellers` endpoint that we used above with an Ajax request. When the request successfully completes, the client code appends a `<div>` containing the info returned by the call to the DOM. Here is an example of how to interact with this form:
<ide>
<ide><path>curriculum/challenges/english/06-quality-assurance/quality-assurance-and-testing-with-chai/simulate-actions-using-a-headless-browser.md
<ide> dashedName: simulate-actions-using-a-headless-browser
<ide>
<ide> # --description--
<ide>
<del>As a reminder, this project is being built upon the following starter project on [Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
<add>As a reminder, this project is being built upon the following starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
<ide>
<ide> In the next challenges we are going to simulate the human interaction with a page using a device called 'Headless Browser'.
<ide>
<ide> A headless browser is a web browser without a graphical user interface. This kind of tool is particularly useful for testing web pages, as it is able to render and understand HTML, CSS, and JavaScript the same way a browser would.
<ide>
<del>For these challenges we are using Zombie.JS. It's a lightweight browser which is totally based on JS, without relying on additional binaries to be installed. This feature makes it usable in an environment such as Replit.com. There are many other (more powerful) options.
<add>For these challenges we are using Zombie.JS. It's a lightweight browser which is totally based on JS, without relying on additional binaries to be installed. This feature makes it usable in an environment such as Replit. There are many other (more powerful) options.
<ide>
<ide> Mocha allows you to prepare the ground running some code before the actual tests. This can be useful for example to create items in the database, which will be used in the successive tests.
<ide>
<ide><path>curriculum/challenges/english/06-quality-assurance/quality-assurance-and-testing-with-chai/test-for-truthiness.md
<ide> dashedName: test-for-truthiness
<ide>
<ide> # --description--
<ide>
<del>As a reminder, this project is being built upon the following starter project on [Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
<add>As a reminder, this project is being built upon the following starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
<ide>
<ide> `isTrue()` will test for the boolean value `true` and `isNotTrue()` will pass when given anything but the boolean value of `true`.
<ide>
<ide><path>curriculum/challenges/english/06-quality-assurance/quality-assurance-and-testing-with-chai/test-if-a-string-contains-a-substring.md
<ide> dashedName: test-if-a-string-contains-a-substring
<ide>
<ide> # --description--
<ide>
<del>As a reminder, this project is being built upon the following starter project on [Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
<add>As a reminder, this project is being built upon the following starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
<ide>
<ide> `include()` and `notInclude()` work for strings too! `include()` asserts that the actual string contains the expected substring.
<ide>
<ide><path>curriculum/challenges/english/06-quality-assurance/quality-assurance-and-testing-with-chai/test-if-a-value-falls-within-a-specific-range.md
<ide> dashedName: test-if-a-value-falls-within-a-specific-range
<ide>
<ide> # --description--
<ide>
<del>As a reminder, this project is being built upon the following starter project on [Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
<add>As a reminder, this project is being built upon the following starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
<ide>
<ide> ```javascript
<ide> .approximately(actual, expected, delta, [message])
<ide><path>curriculum/challenges/english/06-quality-assurance/quality-assurance-and-testing-with-chai/test-if-a-value-is-a-string.md
<ide> dashedName: test-if-a-value-is-a-string
<ide>
<ide> # --description--
<ide>
<del>As a reminder, this project is being built upon the following starter project on [Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
<add>As a reminder, this project is being built upon the following starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
<ide>
<ide> `isString` or `isNotString` asserts that the actual value is a string.
<ide>
<ide><path>curriculum/challenges/english/06-quality-assurance/quality-assurance-and-testing-with-chai/test-if-a-value-is-an-array.md
<ide> dashedName: test-if-a-value-is-an-array
<ide>
<ide> # --description--
<ide>
<del>As a reminder, this project is being built upon the following starter project on [Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
<add>As a reminder, this project is being built upon the following starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
<ide>
<ide> # --instructions--
<ide>
<ide><path>curriculum/challenges/english/06-quality-assurance/quality-assurance-and-testing-with-chai/test-if-a-value-is-of-a-specific-data-structure-type.md
<ide> dashedName: test-if-a-value-is-of-a-specific-data-structure-type
<ide>
<ide> # --description--
<ide>
<del>As a reminder, this project is being built upon the following starter project on [Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
<add>As a reminder, this project is being built upon the following starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
<ide>
<ide> `#typeOf` asserts that value's type is the given string, as determined by `Object.prototype.toString`.
<ide>
<ide><path>curriculum/challenges/english/06-quality-assurance/quality-assurance-and-testing-with-chai/test-if-a-variable-or-function-is-defined.md
<ide> dashedName: test-if-a-variable-or-function-is-defined
<ide>
<ide> # --description--
<ide>
<del>As a reminder, this project is being built upon the following starter project on [Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
<add>As a reminder, this project is being built upon the following starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
<ide>
<ide> # --instructions--
<ide>
<ide><path>curriculum/challenges/english/06-quality-assurance/quality-assurance-and-testing-with-chai/test-if-an-array-contains-an-item.md
<ide> dashedName: test-if-an-array-contains-an-item
<ide>
<ide> # --description--
<ide>
<del>As a reminder, this project is being built upon the following starter project on [Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
<add>As a reminder, this project is being built upon the following starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
<ide>
<ide> # --instructions--
<ide>
<ide><path>curriculum/challenges/english/06-quality-assurance/quality-assurance-and-testing-with-chai/test-if-an-object-has-a-property.md
<ide> dashedName: test-if-an-object-has-a-property
<ide>
<ide> # --description--
<ide>
<del>As a reminder, this project is being built upon the following starter project on [Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
<add>As a reminder, this project is being built upon the following starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
<ide>
<ide> `property` asserts that the actual object has a given property.
<ide>
<ide><path>curriculum/challenges/english/06-quality-assurance/quality-assurance-and-testing-with-chai/test-if-an-object-is-an-instance-of-a-constructor.md
<ide> dashedName: test-if-an-object-is-an-instance-of-a-constructor
<ide>
<ide> # --description--
<ide>
<del>As a reminder, this project is being built upon the following starter project on [Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
<add>As a reminder, this project is being built upon the following starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
<ide>
<ide> `#instanceOf` asserts that an object is an instance of a constructor.
<ide>
<ide><path>curriculum/challenges/english/06-quality-assurance/quality-assurance-and-testing-with-chai/test-if-one-value-is-below-or-at-least-as-large-as-another.md
<ide> dashedName: test-if-one-value-is-below-or-at-least-as-large-as-another
<ide>
<ide> # --description--
<ide>
<del>As a reminder, this project is being built upon the following starter project on [Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
<add>As a reminder, this project is being built upon the following starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
<ide>
<ide> # --instructions--
<ide>
<ide><path>curriculum/challenges/english/06-quality-assurance/quality-assurance-and-testing-with-chai/use-assert.isok-and-assert.isnotok.md
<ide> dashedName: use-assert-isok-and-assert-isnotok
<ide>
<ide> # --description--
<ide>
<del>As a reminder, this project is being built upon the following starter project on [Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
<add>As a reminder, this project is being built upon the following starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
<ide>
<ide> `isOk()` will test for a truthy value, and `isNotOk()` will test for a falsy value.
<ide>
<ide><path>curriculum/challenges/english/06-quality-assurance/quality-assurance-and-testing-with-chai/use-regular-expressions-to-test-a-string.md
<ide> dashedName: use-regular-expressions-to-test-a-string
<ide>
<ide> # --description--
<ide>
<del>As a reminder, this project is being built upon the following starter project on [Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
<add>As a reminder, this project is being built upon the following starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
<ide>
<ide> `match()` asserts that the actual value matches the second argument regular expression.
<ide>
<ide><path>curriculum/challenges/english/06-quality-assurance/quality-assurance-and-testing-with-chai/use-the-double-equals-to-assert-equality.md
<ide> dashedName: use-the-double-equals-to-assert-equality
<ide>
<ide> # --description--
<ide>
<del>As a reminder, this project is being built upon the following starter project on [Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
<add>As a reminder, this project is being built upon the following starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
<ide>
<ide> `equal()` compares objects using `==`.
<ide>
<ide><path>curriculum/challenges/english/06-quality-assurance/quality-assurance-and-testing-with-chai/use-the-triple-equals-to-assert-strict-equality.md
<ide> dashedName: use-the-triple-equals-to-assert-strict-equality
<ide>
<ide> # --description--
<ide>
<del>As a reminder, this project is being built upon the following starter project on [Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
<add>As a reminder, this project is being built upon the following starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
<ide>
<ide> `strictEqual()` compares objects using `===`.
<ide>
<ide><path>curriculum/challenges/english/06-quality-assurance/quality-assurance-projects/american-british-translator.md
<ide> dashedName: american-british-translator
<ide> Build a full stack JavaScript app that is functionally similar to this: <https://american-british-translator.freecodecamp.rocks/>. Working on this project will involve you writing your code using one of the following methods:
<ide>
<ide> - Clone [this GitHub repo](https://github.com/freeCodeCamp/boilerplate-project-american-british-english-translator/) and complete your project locally.
<del>- Use [our replit.com starter project](https://replit.com/github/freeCodeCamp/boilerplate-project-american-british-english-translator) to complete your project.
<add>- Use [our Replit starter project](https://replit.com/github/freeCodeCamp/boilerplate-project-american-british-english-translator) to complete your project.
<ide> - Use a site builder of your choice to complete the project. Be sure to incorporate all the files from our GitHub repo.
<ide>
<ide> When you are done, make sure a working demo of your project is hosted somewhere public. Then submit the URL to it in the `Solution Link` field. Optionally, also submit a link to your project's source code in the `GitHub Link` field.
<ide> When you are done, make sure a working demo of your project is hosted somewhere
<ide> - Complete the `/api/translate` route in `/routes/api.js`
<ide> - Create all of the unit/functional tests in `tests/1_unit-tests.js` and `tests/2_functional-tests.js`
<ide> - See the JavaScript files in `/components` for the different spelling and terms your application should translate
<del>- To run the tests on Replit.com, set `NODE_ENV` to `test` without quotes in the `.env` file
<del>- To run the tests in the console, use the command `npm run test`. To open the Replit.com console, press Ctrl+Shift+P (Cmd if on a Mac) and type "open shell"
<add>- To run the tests on Replit, set `NODE_ENV` to `test` without quotes in the `.env` file
<add>- To run the tests in the console, use the command `npm run test`. To open the Replit console, press Ctrl+Shift+P (Cmd if on a Mac) and type "open shell"
<ide>
<ide> Write the following tests in `tests/1_unit-tests.js`:
<ide>
<ide><path>curriculum/challenges/english/06-quality-assurance/quality-assurance-projects/issue-tracker.md
<ide> dashedName: issue-tracker
<ide> Build a full stack JavaScript app that is functionally similar to this: <https://issue-tracker.freecodecamp.rocks/>. Working on this project will involve you writing your code using one of the following methods:
<ide>
<ide> - Clone [this GitHub repo](https://github.com/freeCodeCamp/boilerplate-project-issuetracker/) and complete your project locally.
<del>- Use [this replit.com starter project](https://replit.com/github/freeCodeCamp/boilerplate-project-issuetracker) to complete your project.
<add>- Use [this Replit starter project](https://replit.com/github/freeCodeCamp/boilerplate-project-issuetracker) to complete your project.
<ide> - Use a site builder of your choice to complete the project. Be sure to incorporate all the files from our GitHub repo.
<ide>
<ide> When you are done, make sure a working demo of your project is hosted somewhere public. Then submit the URL to it in the `Solution Link` field. Optionally, also submit a link to your project's source code in the `GitHub Link` field.
<ide> When you are done, make sure a working demo of your project is hosted somewhere
<ide> - Create all of the functional tests in `tests/2_functional-tests.js`
<ide> - Copy the `sample.env` file to `.env` and set the variables appropriately
<ide> - To run the tests uncomment `NODE_ENV=test` in your `.env` file
<del>- To run the tests in the console, use the command `npm run test`. To open the Replit.com console, press Ctrl+Shift+P (Cmd if on a Mac) and type "open shell"
<add>- To run the tests in the console, use the command `npm run test`. To open the Replit console, press Ctrl+Shift+P (Cmd if on a Mac) and type "open shell"
<ide>
<ide> Write the following tests in `tests/2_functional-tests.js`:
<ide>
<ide><path>curriculum/challenges/english/06-quality-assurance/quality-assurance-projects/metric-imperial-converter.md
<ide> dashedName: metric-imperial-converter
<ide> Build a full stack JavaScript app that is functionally similar to this: <https://metric-imperial-converter.freecodecamp.rocks/>. Working on this project will involve you writing your code using one of the following methods:
<ide>
<ide> - Clone [this GitHub repo](https://github.com/freeCodeCamp/boilerplate-project-metricimpconverter/) and complete your project locally.
<del>- Use [our replit.com starter project](https://replit.com/github/freeCodeCamp/boilerplate-project-metricimpconverter) to complete your project.
<add>- Use [our Replit starter project](https://replit.com/github/freeCodeCamp/boilerplate-project-metricimpconverter) to complete your project.
<ide> - Use a site builder of your choice to complete the project. Be sure to incorporate all the files from our GitHub repo.
<ide>
<ide> When you are done, make sure a working demo of your project is hosted somewhere public. Then submit the URL to it in the `Solution Link` field. Optionally, also submit a link to your project's source code in the `GitHub Link` field.
<ide> When you are done, make sure a working demo of your project is hosted somewhere
<ide> - Complete the necessary routes in `/routes/api.js`
<ide> - Copy the `sample.env` file to `.env` and set the variables appropriately
<ide> - To run the tests uncomment `NODE_ENV=test` in your `.env` file
<del>- To run the tests in the console, use the command `npm run test`. To open the Replit.com console, press Ctrl+Shift+P (Cmd if on a Mac) and type "open shell"
<add>- To run the tests in the console, use the command `npm run test`. To open the Replit console, press Ctrl+Shift+P (Cmd if on a Mac) and type "open shell"
<ide>
<ide> Write the following tests in `tests/1_unit-tests.js`:
<ide>
<ide><path>curriculum/challenges/english/06-quality-assurance/quality-assurance-projects/personal-library.md
<ide> dashedName: personal-library
<ide> Build a full stack JavaScript app that is functionally similar to this: <https://personal-library.freecodecamp.rocks/>. Working on this project will involve you writing your code using one of the following methods:
<ide>
<ide> - Clone [this GitHub repo](https://github.com/freeCodeCamp/boilerplate-project-library) and complete your project locally.
<del>- Use [our replit.com starter project](https://replit.com/github/freeCodeCamp/boilerplate-project-library)) to complete your project.
<add>- Use [our Replit starter project](https://replit.com/github/freeCodeCamp/boilerplate-project-library) to complete your project.
<ide> - Use a site builder of your choice to complete the project. Be sure to incorporate all the files from our GitHub repo.
<ide>
<ide> When you are done, make sure a working demo of your project is hosted somewhere public. Then submit the URL to it in the `Solution Link` field. Optionally, also submit a link to your project's source code in the `GitHub Link` field.
<ide><path>curriculum/challenges/english/06-quality-assurance/quality-assurance-projects/sudoku-solver.md
<ide> dashedName: sudoku-solver
<ide> Build a full stack JavaScript app that is functionally similar to this: <https://sudoku-solver.freecodecamp.rocks/>. Working on this project will involve you writing your code using one of the following methods:
<ide>
<ide> - Clone [this GitHub repo](https://github.com/freecodecamp/boilerplate-project-sudoku-solver) and complete your project locally.
<del>- Use [our replit.com starter project](https://replit.com/github/freeCodeCamp/boilerplate-project-sudoku-solver) to complete your project.
<add>- Use [our Replit starter project](https://replit.com/github/freeCodeCamp/boilerplate-project-sudoku-solver) to complete your project.
<ide> - Use a site builder of your choice to complete the project. Be sure to incorporate all the files from our GitHub repo.
<ide>
<ide> When you are done, make sure a working demo of your project is hosted somewhere public. Then submit the URL to it in the `Solution Link` field. Optionally, also submit a link to your project's source code in the `GitHub Link` field.
<ide> When you are done, make sure a working demo of your project is hosted somewhere
<ide> - All routing logic can go into `/routes/api.js`
<ide> - See the `puzzle-strings.js` file in `/controllers` for some sample puzzles your application should solve
<ide> - To run the challenge tests on this page, set `NODE_ENV` to `test` without quotes in the `.env` file
<del>- To run the tests in the console, use the command `npm run test`. To open the Replit.com console, press Ctrl+Shift+P (Cmd if on a Mac) and type "open shell"
<add>- To run the tests in the console, use the command `npm run test`. To open the Replit console, press Ctrl+Shift+P (Cmd if on a Mac) and type "open shell"
<ide>
<ide> Write the following tests in `tests/1_unit-tests.js`:
<ide>
<ide><path>curriculum/challenges/english/07-scientific-computing-with-python/scientific-computing-with-python-projects/arithmetic-formatter.md
<ide> dashedName: arithmetic-formatter
<ide>
<ide> Create a function that receives a list of strings that are arithmetic problems and returns the problems arranged vertically and side-by-side.
<ide>
<del>You can access [the full project description and starter code on Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-arithmetic-formatter).
<add>You can access [the full project description and starter code on Replit](https://replit.com/github/freeCodeCamp/boilerplate-arithmetic-formatter).
<ide>
<ide> After going to that link, fork the project. Once you complete the project based on the instructions in 'README.md', submit your project link below.
<ide>
<ide><path>curriculum/challenges/english/07-scientific-computing-with-python/scientific-computing-with-python-projects/budget-app.md
<ide> dashedName: budget-app
<ide>
<ide> Create a "Category" class that can be used to create different budget categories.
<ide>
<del>You can access [the full project description and starter code on Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-budget-app).
<add>You can access [the full project description and starter code on Replit](https://replit.com/github/freeCodeCamp/boilerplate-budget-app).
<ide>
<ide> After going to that link, fork the project. Once you complete the project based on the instructions in 'README.md', submit your project link below.
<ide>
<ide><path>curriculum/challenges/english/07-scientific-computing-with-python/scientific-computing-with-python-projects/polygon-area-calculator.md
<ide> dashedName: polygon-area-calculator
<ide>
<ide> In this project you will use object oriented programming to create a Rectangle class and a Square class. The Square class should be a subclass of Rectangle and inherit methods and attributes.
<ide>
<del>You can access [the full project description and starter code on Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-polygon-area-calculator).
<add>You can access [the full project description and starter code on Replit](https://replit.com/github/freeCodeCamp/boilerplate-polygon-area-calculator).
<ide>
<ide> After going to that link, fork the project. Once you complete the project based on the instructions in 'README.md', submit your project link below.
<ide>
<ide><path>curriculum/challenges/english/07-scientific-computing-with-python/scientific-computing-with-python-projects/probability-calculator.md
<ide> dashedName: probability-calculator
<ide>
<ide> Write a program to determine the approximate probability of drawing certain balls randomly from a hat.
<ide>
<del>You can access [the full project description and starter code on Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-probability-calculator). After going to that link, fork the project. Once you complete the project based on the instructions in 'README.md', submit your project link below.
<add>You can access [the full project description and starter code on Replit](https://replit.com/github/freeCodeCamp/boilerplate-probability-calculator). After going to that link, fork the project. Once you complete the project based on the instructions in 'README.md', submit your project link below.
<ide>
<ide> We are still developing the interactive instructional part of the Python curriculum. For now, here are some videos on the freeCodeCamp.org YouTube channel that will teach you everything you need to know to complete this project:
<ide>
<ide><path>curriculum/challenges/english/07-scientific-computing-with-python/scientific-computing-with-python-projects/time-calculator.md
<ide> dashedName: time-calculator
<ide>
<ide> Write a function named "add_time" that can add a duration to a start time and return the result.
<ide>
<del>You can access [the full project description and starter code on Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-time-calculator). After going to that link, fork the project. Once you complete the project based on the instructions in 'README.md', submit your project link below.
<add>You can access [the full project description and starter code on Replit](https://replit.com/github/freeCodeCamp/boilerplate-time-calculator). After going to that link, fork the project. Once you complete the project based on the instructions in 'README.md', submit your project link below.
<ide>
<ide> We are still developing the interactive instructional part of the Python curriculum. For now, here are some videos on the freeCodeCamp.org YouTube channel that will teach you everything you need to know to complete this project:
<ide>
<ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-projects/demographic-data-analyzer.md
<ide> dashedName: demographic-data-analyzer
<ide>
<ide> In this challenge you must analyze demographic data using Pandas. You are given a dataset of demographic data that was extracted from the 1994 Census database.
<ide>
<del>You can access [the full project description and starter code on Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-demographic-data-analyzer).
<add>You can access [the full project description and starter code on Replit](https://replit.com/github/freeCodeCamp/boilerplate-demographic-data-analyzer).
<ide>
<ide> After going to that link, fork the project. Once you complete the project based on the instructions in 'README.md', submit your project link below.
<ide>
<ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-projects/mean-variance-standard-deviation-calculator.md
<ide> dashedName: mean-variance-standard-deviation-calculator
<ide>
<ide> Create a function that uses Numpy to output the mean, variance, and standard deviation of the rows, columns, and elements in a 3 x 3 matrix.
<ide>
<del>You can access [the full project description and starter code on Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-mean-variance-standard-deviation-calculator).
<add>You can access [the full project description and starter code on Replit](https://replit.com/github/freeCodeCamp/boilerplate-mean-variance-standard-deviation-calculator).
<ide>
<ide> After going to that link, fork the project. Once you complete the project based on the instructions in 'README.md', submit your project link below.
<ide>
<ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-projects/medical-data-visualizer.md
<ide> dashedName: medical-data-visualizer
<ide>
<ide> In this project, you will visualize and make calculations from medical examination data using matplotlib, seaborn, and pandas.
<ide>
<del>You can access [the full project description and starter code on Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-medical-data-visualizer).
<add>You can access [the full project description and starter code on Replit](https://replit.com/github/freeCodeCamp/boilerplate-medical-data-visualizer).
<ide>
<ide> After going to that link, fork the project. Once you complete the project based on the instructions in 'README.md', submit your project link below.
<ide>
<ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-projects/page-view-time-series-visualizer.md
<ide> dashedName: page-view-time-series-visualizer
<ide>
<ide> For this project you will visualize time series data using a line chart, bar chart, and box plots. You will use Pandas, matplotlib, and seaborn to visualize a dataset containing the number of page views each day on the freeCodeCamp.org forum from 2016-05-09 to 2019-12-03. The data visualizations will help you understand the patterns in visits and identify yearly and monthly growth.
<ide>
<del>You can access [the full project description and starter code on Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-page-view-time-series-visualizer).
<add>You can access [the full project description and starter code on Replit](https://replit.com/github/freeCodeCamp/boilerplate-page-view-time-series-visualizer).
<ide>
<ide> After going to that link, fork the project. Once you complete the project based on the instructions in 'README.md', submit your project link below.
<ide>
<ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-projects/sea-level-predictor.md
<ide> dashedName: sea-level-predictor
<ide>
<ide> In this project, you will analyze a dataset of the global average sea level change since 1880. You will use the data to predict the sea level change through year 2050.
<ide>
<del>You can access [the full project description and starter code on Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-sea-level-predictor).
<add>You can access [the full project description and starter code on Replit](https://replit.com/github/freeCodeCamp/boilerplate-sea-level-predictor).
<ide>
<ide> After going to that link, fork the project. Once you complete the project based on the instructions in 'README.md', submit your project link below.
<ide>
<ide><path>curriculum/challenges/english/09-information-security/information-security-projects/anonymous-message-board.md
<ide> Build a full stack JavaScript app that is functionally similar to this: <https:/
<ide> Working on this project will involve you writing your code using one of the following methods:
<ide>
<ide> - Clone [this GitHub repo](https://github.com/freeCodeCamp/boilerplate-project-messageboard/) and complete your project locally.
<del>- Use [our replit.com starter project](https://replit.com/github/freeCodeCamp/boilerplate-project-messageboard) to complete your project.
<add>- Use [our Replit starter project](https://replit.com/github/freeCodeCamp/boilerplate-project-messageboard) to complete your project.
<ide> - Use a site builder of your choice to complete the project. Be sure to incorporate all the files from our GitHub repo.
<ide>
<ide> When you are done, make sure a working demo of your project is hosted somewhere public. Then submit the URL to it in the `Solution Link` field. Optionally, also submit a link to your projects source code in the `GitHub Link` field.
<ide><path>curriculum/challenges/english/09-information-security/information-security-projects/port-scanner.md
<ide> dashedName: port-scanner
<ide>
<ide> Create a port scanner using Python.
<ide>
<del>You can access [the full project description and starter code on Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-port-scanner).
<add>You can access [the full project description and starter code on Replit](https://replit.com/github/freeCodeCamp/boilerplate-port-scanner).
<ide>
<ide> After going to that link, fork the project. Once you complete the project based on the instructions in 'README.md', submit your project link below.
<ide>
<ide><path>curriculum/challenges/english/09-information-security/information-security-projects/secure-real-time-multiplayer-game.md
<ide> dashedName: secure-real-time-multiplayer-game
<ide> Develop a 2D real time multiplayer game using the HTML Canvas API and [Socket.io](https://socket.io/) that is functionally similar to this: <https://secure-real-time-multiplayer-game.freecodecamp.rocks/>. Working on this project will involve you writing your code using one of the following methods:
<ide>
<ide> - Clone [this GitHub repo](https://github.com/freeCodeCamp/boilerplate-project-secure-real-time-multiplayer-game/) and complete your project locally.
<del>- Use [our replit.com starter project](https://replit.com/github/freeCodeCamp/boilerplate-project-secure-real-time-multiplayer-game) to complete your project.
<add>- Use [our Replit starter project](https://replit.com/github/freeCodeCamp/boilerplate-project-secure-real-time-multiplayer-game) to complete your project.
<ide> - Use a site builder of your choice to complete the project. Be sure to incorporate all the files from our GitHub repo.
<ide>
<ide> When you are done, make sure a working demo of your project is hosted somewhere public. Then submit the URL to it in the `Solution Link` field. Optionally, also submit a link to your project's source code in the `GitHub Link` field.
<ide><path>curriculum/challenges/english/09-information-security/information-security-projects/sha-1-password-cracker.md
<ide> dashedName: sha-1-password-cracker
<ide>
<ide> For this project you will learn about the importance of good security by creating a password cracker to figure out passwords that were hashed using SHA-1.
<ide>
<del>You can access [the full project description and starter code on Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-SHA-1-password-cracker).
<add>You can access [the full project description and starter code on Replit](https://replit.com/github/freeCodeCamp/boilerplate-SHA-1-password-cracker).
<ide>
<ide> After going to that link, fork the project. Once you complete the project based on the instructions in 'README.md', submit your project link below.
<ide>
<ide><path>curriculum/challenges/english/09-information-security/information-security-projects/stock-price-checker.md
<ide> Since all reliable stock price APIs require an API key, we've built a workaround
<ide> Working on this project will involve you writing your code using one of the following methods:
<ide>
<ide> - Clone [this GitHub repo](https://github.com/freeCodeCamp/boilerplate-project-stockchecker/) and complete your project locally.
<del>- Use [our replit.com starter project](https://replit.com/github/freeCodeCamp/boilerplate-project-stockchecker) to complete your project.
<add>- Use [our Replit starter project](https://replit.com/github/freeCodeCamp/boilerplate-project-stockchecker) to complete your project.
<ide> - Use a site builder of your choice to complete the project. Be sure to incorporate all the files from our GitHub repo.
<ide>
<ide> When you are done, make sure a working demo of your project is hosted somewhere public. Then submit the URL to it in the `Solution Link` field. Optionally, also submit a link to your projects source code in the `GitHub Link` field.
<ide><path>curriculum/challenges/english/09-information-security/information-security-with-helmetjs/ask-browsers-to-access-your-site-via-https-only-with-helmet.hsts.md
<ide> dashedName: ask-browsers-to-access-your-site-via-https-only-with-helmet-hsts
<ide>
<ide> # --description--
<ide>
<del>As a reminder, this project is being built upon the following starter project on [Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-infosec), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-infosec/).
<add>As a reminder, this project is being built upon the following starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-infosec), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-infosec/).
<ide>
<ide> HTTP Strict Transport Security (HSTS) is a web security policy which helps to protect websites against protocol downgrade attacks and cookie hijacking. If your website can be accessed via HTTPS you can ask user’s browsers to avoid using insecure HTTP. By setting the header Strict-Transport-Security, you tell the browsers to use HTTPS for the future requests in a specified amount of time. This will work for the requests coming after the initial request.
<ide>
<ide> # --instructions--
<ide>
<del>Configure `helmet.hsts()` to use HTTPS for the next 90 days. Pass the config object `{maxAge: timeInSeconds, force: true}`. You can create a variable `ninetyDaysInSeconds = 90*24*60*60;` to use for the `timeInSeconds`. Replit.com already has hsts enabled. To override its settings you need to set the field "force" to true in the config object. We will intercept and restore the Replit.com header, after inspecting it for testing.
<add>Configure `helmet.hsts()` to use HTTPS for the next 90 days. Pass the config object `{maxAge: timeInSeconds, force: true}`. You can create a variable `ninetyDaysInSeconds = 90*24*60*60;` to use for the `timeInSeconds`. Replit already has hsts enabled. To override its settings you need to set the field "force" to true in the config object. We will intercept and restore the Replit header, after inspecting it for testing.
<ide>
<ide> Note: Configuring HTTPS on a custom website requires the acquisition of a domain, and a SSL/TLS Certificate.
<ide>
<ide><path>curriculum/challenges/english/09-information-security/information-security-with-helmetjs/avoid-inferring-the-response-mime-type-with-helmet.nosniff.md
<ide> dashedName: avoid-inferring-the-response-mime-type-with-helmet-nosniff
<ide>
<ide> # --description--
<ide>
<del>As a reminder, this project is being built upon the following starter project on [Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-infosec), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-infosec/). Browsers can use content or MIME sniffing to override response `Content-Type` headers to guess and process the data using an implicit content type. While this can be convenient in some scenarios, it can also lead to some dangerous attacks. This middleware sets the X-Content-Type-Options header to `nosniff`, instructing the browser to not bypass the provided `Content-Type`.
<add>As a reminder, this project is being built upon the following starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-infosec), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-infosec/). Browsers can use content or MIME sniffing to override response `Content-Type` headers to guess and process the data using an implicit content type. While this can be convenient in some scenarios, it can also lead to some dangerous attacks. This middleware sets the X-Content-Type-Options header to `nosniff`, instructing the browser to not bypass the provided `Content-Type`.
<ide>
<ide> # --instructions--
<ide>
<ide><path>curriculum/challenges/english/09-information-security/information-security-with-helmetjs/configure-helmet-using-the-parent-helmet-middleware.md
<ide> dashedName: configure-helmet-using-the-parent-helmet-middleware
<ide>
<ide> # --description--
<ide>
<del>As a reminder, this project is being built upon the following starter project on [Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-infosec), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-infosec/).
<add>As a reminder, this project is being built upon the following starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-infosec), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-infosec/).
<ide>
<ide> `app.use(helmet())` will automatically include all the middleware introduced above, except `noCache()`, and `contentSecurityPolicy()`, but these can be enabled if necessary. You can also disable or configure any other middleware individually, using a configuration object.
<ide>
<ide><path>curriculum/challenges/english/09-information-security/information-security-with-helmetjs/disable-client-side-caching-with-helmet.nocache.md
<ide> dashedName: disable-client-side-caching-with-helmet-nocache
<ide>
<ide> # --description--
<ide>
<del>As a reminder, this project is being built upon the following starter project on [Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-infosec), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-infosec/).
<add>As a reminder, this project is being built upon the following starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-infosec), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-infosec/).
<ide>
<ide> If you are releasing an update for your website, and you want the users to always download the newer version, you can (try to) disable caching on client’s browser. It can be useful in development too. Caching has performance benefits, which you will lose, so only use this option when there is a real need.
<ide>
<ide><path>curriculum/challenges/english/09-information-security/information-security-with-helmetjs/disable-dns-prefetching-with-helmet.dnsprefetchcontrol.md
<ide> dashedName: disable-dns-prefetching-with-helmet-dnsprefetchcontrol
<ide>
<ide> # --description--
<ide>
<del>As a reminder, this project is being built upon the following starter project on [Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-infosec), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-infosec/).
<add>As a reminder, this project is being built upon the following starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-infosec), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-infosec/).
<ide>
<ide> To improve performance, most browsers prefetch DNS records for the links in a page. In that way the destination ip is already known when the user clicks on a link. This may lead to over-use of the DNS service (if you own a big website, visited by millions people…), privacy issues (one eavesdropper could infer that you are on a certain page), or page statistics alteration (some links may appear visited even if they are not). If you have high security needs you can disable DNS prefetching, at the cost of a performance penalty.
<ide>
<ide><path>curriculum/challenges/english/09-information-security/information-security-with-helmetjs/hash-and-compare-passwords-asynchronously.md
<ide> dashedName: hash-and-compare-passwords-asynchronously
<ide>
<ide> # --description--
<ide>
<del>As a reminder, this project is being built upon the following starter project on [Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-bcrypt), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-bcrypt/).
<add>As a reminder, this project is being built upon the following starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-bcrypt), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-bcrypt/).
<ide>
<ide> As hashing is designed to be computationally intensive, it is recommended to do so asynchronously on your server as to avoid blocking incoming connections while you hash. All you have to do to hash a password asynchronous is call
<ide>
<ide><path>curriculum/challenges/english/09-information-security/information-security-with-helmetjs/hash-and-compare-passwords-synchronously.md
<ide> dashedName: hash-and-compare-passwords-synchronously
<ide>
<ide> # --description--
<ide>
<del>As a reminder, this project is being built upon the following starter project on [Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-bcrypt), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-bcrypt/).
<add>As a reminder, this project is being built upon the following starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-bcrypt), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-bcrypt/).
<ide>
<ide> Hashing synchronously is just as easy to do but can cause lag if using it server side with a high cost or with hashing done very often. Hashing with this method is as easy as calling
<ide>
<ide><path>curriculum/challenges/english/09-information-security/information-security-with-helmetjs/hide-potentially-dangerous-information-using-helmet.hidepoweredby.md
<ide> dashedName: hide-potentially-dangerous-information-using-helmet-hidepoweredby
<ide>
<ide> # --description--
<ide>
<del>As a reminder, this project is being built upon the following starter project on [Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-infosec), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-infosec/).
<add>As a reminder, this project is being built upon the following starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-infosec), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-infosec/).
<ide>
<ide> Hackers can exploit known vulnerabilities in Express/Node if they see that your site is powered by Express. `X-Powered-By: Express` is sent in every request coming from Express by default. Use the `helmet.hidePoweredBy()` middleware to remove the X-Powered-By header.
<ide>
<ide><path>curriculum/challenges/english/09-information-security/information-security-with-helmetjs/install-and-require-helmet.md
<ide> dashedName: install-and-require-helmet
<ide> Working on these challenges will involve you writing your code using one of the following methods:
<ide>
<ide> - Clone [this GitHub repo](https://github.com/freeCodeCamp/boilerplate-infosec/) and complete these challenges locally.
<del>- Use [our Replit.com starter project](https://replit.com/github/freeCodeCamp/boilerplate-infosec) to complete these challenges.
<add>- Use [our Replit starter project](https://replit.com/github/freeCodeCamp/boilerplate-infosec) to complete these challenges.
<ide> - Use a site builder of your choice to complete the project. Be sure to incorporate all the files from our GitHub repo.
<ide>
<ide> When you are done, make sure a working demo of your project is hosted somewhere public. Then submit the URL to it in the `Solution Link` field.
<ide><path>curriculum/challenges/english/09-information-security/information-security-with-helmetjs/mitigate-the-risk-of-clickjacking-with-helmet.frameguard.md
<ide> dashedName: mitigate-the-risk-of-clickjacking-with-helmet-frameguard
<ide>
<ide> # --description--
<ide>
<del>As a reminder, this project is being built upon the following starter project on [Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-infosec), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-infosec/).
<add>As a reminder, this project is being built upon the following starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-infosec), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-infosec/).
<ide>
<ide> Your page could be put in a `<frame>` or `<iframe>` without your consent. This can result in clickjacking attacks, among other things. Clickjacking is a technique of tricking a user into interacting with a page different from what the user thinks it is. This can be obtained executing your page in a malicious context, by mean of iframing. In that context a hacker can put a hidden layer over your page. Hidden buttons can be used to run bad scripts. This middleware sets the X-Frame-Options header. It restricts who can put your site in a frame. It has three modes: DENY, SAMEORIGIN, and ALLOW-FROM.
<ide>
<ide><path>curriculum/challenges/english/09-information-security/information-security-with-helmetjs/mitigate-the-risk-of-cross-site-scripting-xss-attacks-with-helmet.xssfilter.md
<ide> dashedName: mitigate-the-risk-of-cross-site-scripting-xss-attacks-with-helmet-xs
<ide>
<ide> # --description--
<ide>
<del>As a reminder, this project is being built upon the following starter project on [Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-infosec), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-infosec/).
<add>As a reminder, this project is being built upon the following starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-infosec), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-infosec/).
<ide>
<ide> Cross-site scripting (XSS) is a frequent type of attack where malicious scripts are injected into vulnerable pages, with the purpose of stealing sensitive data like session cookies, or passwords.
<ide>
<ide><path>curriculum/challenges/english/09-information-security/information-security-with-helmetjs/prevent-ie-from-opening-untrusted-html-with-helmet.ienoopen.md
<ide> dashedName: prevent-ie-from-opening-untrusted-html-with-helmet-ienoopen
<ide>
<ide> # --description--
<ide>
<del>As a reminder, this project is being built upon the following starter project on [Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-infosec), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-infosec/).
<add>As a reminder, this project is being built upon the following starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-infosec), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-infosec/).
<ide>
<ide> Some web applications will serve untrusted HTML for download. Some versions of Internet Explorer by default open those HTML files in the context of your site. This means that an untrusted HTML page could start doing bad things in the context of your pages. This middleware sets the X-Download-Options header to noopen. This will prevent IE users from executing downloads in the trusted site’s context.
<ide>
<ide><path>curriculum/challenges/english/09-information-security/information-security-with-helmetjs/set-a-content-security-policy-with-helmet.contentsecuritypolicy.md
<ide> dashedName: set-a-content-security-policy-with-helmet-contentsecuritypolicy
<ide>
<ide> # --description--
<ide>
<del>As a reminder, this project is being built upon the following starter project on [Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-infosec), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-infosec/).
<add>As a reminder, this project is being built upon the following starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-infosec), or cloned from [GitHub](https://github.com/freeCodeCamp/boilerplate-infosec/).
<ide>
<ide> This challenge highlights one promising new defense that can significantly reduce the risk and impact of many type of attacks in modern browsers. By setting and configuring a Content Security Policy you can prevent the injection of anything unintended into your page. This will protect your app from XSS vulnerabilities, undesired tracking, malicious frames, and much more. CSP works by defining an allowed list of content sources which are trusted. You can configure them for each kind of resource a web page may need (scripts, stylesheets, fonts, frames, media, and so on…). There are multiple directives available, so a website owner can have a granular control. See HTML 5 Rocks, KeyCDN for more details. Unfortunately CSP is unsupported by older browser.
<ide>
<ide><path>curriculum/challenges/english/09-information-security/information-security-with-helmetjs/understand-bcrypt-hashes.md
<ide> dashedName: understand-bcrypt-hashes
<ide>
<ide> # --description--
<ide>
<del>For the following challenges, you will be working with a new starter project that is different from the previous one. You can find the new starter project on [Replit.com](https://replit.com/github/freeCodeCamp/boilerplate-bcrypt), or clone it from [GitHub](https://github.com/freeCodeCamp/boilerplate-bcrypt/).
<add>For the following challenges, you will be working with a new starter project that is different from the previous one. You can find the new starter project on [Replit](https://replit.com/github/freeCodeCamp/boilerplate-bcrypt), or clone it from [GitHub](https://github.com/freeCodeCamp/boilerplate-bcrypt/).
<ide>
<ide> BCrypt hashes are very secure. A hash is basically a fingerprint of the original data- always unique. This is accomplished by feeding the original data into an algorithm and returning a fixed length result. To further complicate this process and make it more secure, you can also *salt* your hash. Salting your hash involves adding random data to the original data before the hashing process which makes it even harder to crack the hash.
<ide>
<ide><path>curriculum/challenges/english/10-coding-interview-prep/take-home-projects/build-a-pinterest-clone.md
<ide> dashedName: build-a-pinterest-clone
<ide>
<ide> # --description--
<ide>
<del>**Objective:** Build a [Replit.com](https://replit.com/) app that is functionally similar to this: <https://build-a-pinterest-clone.freecodecamp.rocks/>.
<add>**Objective:** Build a [Replit](https://replit.com/) app that is functionally similar to this: <https://build-a-pinterest-clone.freecodecamp.rocks/>.
<ide>
<ide> Fulfill the below [user stories](https://en.wikipedia.org/wiki/User_story). Use whichever libraries or APIs you need. Give it your own personal style.
<ide>
<ide><path>curriculum/challenges/english/10-coding-interview-prep/take-home-projects/manage-a-book-trading-club.md
<ide> dashedName: manage-a-book-trading-club
<ide>
<ide> # --description--
<ide>
<del>**Objective:** Build a [Replit.com](https://replit.com/) app that is functionally similar to this: <https://manage-a-book-trading-club.freecodecamp.rocks/>.
<add>**Objective:** Build a [Replit](https://replit.com/) app that is functionally similar to this: <https://manage-a-book-trading-club.freecodecamp.rocks/>.
<ide>
<ide> Fulfill the below [user stories](https://en.wikipedia.org/wiki/User_story). Use whichever libraries or APIs you need. Give it your own personal style.
<ide>
<ide><path>curriculum/challenges/english/10-coding-interview-prep/take-home-projects/p2p-video-chat-application.md
<ide> dashedName: p2p-video-chat-application
<ide>
<ide> # --description--
<ide>
<del>**Objective:** Build a [Replit.com](https://replit.com/) app that is functionally similar to this: <https://p2p-video-chat-application.freecodecamp.rocks/>.
<add>**Objective:** Build a [Replit](https://replit.com/) app that is functionally similar to this: <https://p2p-video-chat-application.freecodecamp.rocks/>.
<ide>
<ide> Fulfill the below [user stories](https://en.wikipedia.org/wiki/User_story). Use whichever libraries or APIs you need. Give it your own personal style.
<ide>
<ide><path>curriculum/challenges/english/11-machine-learning-with-python/machine-learning-with-python-projects/rock-paper-scissors.md
<ide> dashedName: rock-paper-scissors
<ide>
<ide> For this challenge, you will create a program to play Rock, Paper, Scissors. A program that picks at random will usually win 50% of the time. To pass this challenge your program must play matches against four different bots, winning at least 60% of the games in each match.
<ide>
<del>You can access [the full project description and starter code on replit.com](https://replit.com/github/freeCodeCamp/boilerplate-rock-paper-scissors).
<add>You can access [the full project description and starter code on Replit](https://replit.com/github/freeCodeCamp/boilerplate-rock-paper-scissors).
<ide>
<ide> After going to that link, fork the project. Once you complete the project based on the instructions in 'README.md', submit your project link below.
<ide>
<ide><path>cypress/integration/learn/challenges/projects.js
<ide> describe('project submission', () => {
<ide> cy.visit(url);
<ide> cy.get('#dynamic-front-end-form')
<ide> .get('#solution')
<del> .type('https://repl.it/@camperbot/python-project#main.py');
<add> .type('https://replit.com/@camperbot/python-project#main.py');
<ide>
<ide> cy.contains("I've completed this challenge").click();
<ide> cy.contains('Go to next challenge'); | 83 |
PHP | PHP | fix issue with inputs() and plugin models | 78b23d8e31331d4890c2fdfb18cb663a33caba4c | <ide><path>lib/Cake/Test/Case/View/Helper/FormHelperTest.php
<ide> public function testFormInputs() {
<ide> $this->assertTags($result, $expected);
<ide> }
<ide>
<add>/**
<add> * Tests inputs() works with plugin models
<add> *
<add> * @return void
<add> */
<add> public function testInputsPluginModel() {
<add> $this->loadFixtures('Post');
<add> App::build(array(
<add> 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS)
<add> ));
<add> CakePlugin::load('TestPlugin');
<add> $this->Form->request['models'] = array(
<add> 'TestPluginPost' => array('plugin' => 'TestPlugin', 'className' => 'TestPluginPost')
<add> );
<add> $this->Form->create('TestPlugin.TestPluginPost');
<add> $result = $this->Form->inputs();
<add>
<add> $this->assertContains('data[TestPluginPost][id]', $result);
<add> $this->assertContains('data[TestPluginPost][author_id]', $result);
<add> $this->assertContains('data[TestPluginPost][title]', $result);
<add> $this->assertTrue(ClassRegistry::isKeySet('TestPluginPost'));
<add> $this->assertFalse(ClassRegistry::isKeySet('TestPlugin'));
<add> $this->assertEquals('TestPluginPost', $this->Form->model());
<add> }
<add>
<ide> /**
<ide> * testSelectAsCheckbox method
<ide> *
<ide><path>lib/Cake/View/Helper/FormHelper.php
<ide> public function create($model = null, $options = array()) {
<ide>
<ide> $key = null;
<ide> if ($model !== false) {
<del> $key = $this->_introspectModel($model, 'key');
<add> list($plugin, $model) = pluginSplit($model, true);
<add> $key = $this->_introspectModel($plugin . $model, 'key');
<ide> $this->setEntity($model, true);
<ide> }
<ide> | 2 |
PHP | PHP | fix deprecation warnings on php 7.4 | 8d86b1ccfaf79af2223dafc060a50a6386ccbc9f | <ide><path>src/Console/ConsoleOptionParser.php
<ide> protected function _optionExists($name)
<ide> if (substr($name, 0, 2) === '--') {
<ide> return isset($this->_options[substr($name, 2)]);
<ide> }
<del> if ($name{0} === '-' && $name{1} !== '-') {
<del> return isset($this->_shortOptions[$name{1}]);
<add> if ($name[0] === '-' && $name[1] !== '-') {
<add> return isset($this->_shortOptions[$name[1]]);
<ide> }
<ide>
<ide> return false;
<ide><path>src/Filesystem/Folder.php
<ide> public function tree($path = null, $exceptions = false, $type = null)
<ide> foreach ($iterator as $itemPath => $fsIterator) {
<ide> if ($skipHidden) {
<ide> $subPathName = $fsIterator->getSubPathname();
<del> if ($subPathName{0} === '.' || strpos($subPathName, DIRECTORY_SEPARATOR . '.') !== false) {
<add> if ($subPathName[0] === '.' || strpos($subPathName, DIRECTORY_SEPARATOR . '.') !== false) {
<ide> continue;
<ide> }
<ide> }
<ide><path>src/TestSuite/TestCase.php
<ide> public function assertHtml($expected, $string, $fullDebug = false)
<ide> $tags = (string)$tags;
<ide> }
<ide> $i++;
<del> if (is_string($tags) && $tags{0} === '<') {
<add> if (is_string($tags) && $tags[0] === '<') {
<ide> $tags = [substr($tags, 1) => []];
<ide> } elseif (is_string($tags)) {
<ide> $tagsTrimmed = preg_replace('/\s+/m', '', $tags);
<ide><path>src/View/Helper/FormHelper.php
<ide> public function submit($caption = null, array $options = [])
<ide> if ($isUrl) {
<ide> $options['src'] = $caption;
<ide> } elseif ($isImage) {
<del> if ($caption{0} !== '/') {
<add> if ($caption[0] !== '/') {
<ide> $url = $this->Url->webroot(Configure::read('App.imageBaseUrl') . $caption);
<ide> } else {
<ide> $url = $this->Url->webroot(trim($caption, '/')); | 4 |
Ruby | Ruby | remove outdated comment | c95c32fbb081d277ce943f65143b234c09582f8e | <ide><path>Library/Homebrew/extend/ENV/super.rb
<ide> def noop(*args); end
<ide> set_cpu_flags
<ide> macosxsdk remove_macosxsdk].each{|s| alias_method s, :noop }
<ide>
<del>### DEPRECATE THESE
<ide> def deparallelize
<ide> delete('MAKEFLAGS')
<ide> end | 1 |
Javascript | Javascript | ignore clicks on block decorations | eb1eeb3fde80d812e528df41fe34a5b0f9afdd9f | <ide><path>spec/text-editor-component-spec.js
<ide> describe('TextEditorComponent', () => {
<ide> expect(component.refs.blockDecorationMeasurementArea.offsetWidth).toBe(component.getScrollWidth())
<ide> })
<ide>
<add> it('does not change the cursor position when clicking on a block decoration', async () => {
<add> const {editor, component} = buildComponent()
<add>
<add> const decorationElement = document.createElement('div')
<add> decorationElement.textContent = 'Parent'
<add> const childElement = document.createElement('div')
<add> childElement.textContent = 'Child'
<add> decorationElement.appendChild(childElement)
<add> const marker = editor.markScreenPosition([4, 0])
<add> editor.decorateMarker(marker, {type: 'block', item: decorationElement})
<add> await component.getNextUpdatePromise()
<add>
<add> const decorationElementClientRect = decorationElement.getBoundingClientRect()
<add> component.didMouseDownOnContent({
<add> target: decorationElement,
<add> detail: 1,
<add> button: 0,
<add> clientX: decorationElementClientRect.left,
<add> clientY: decorationElementClientRect.top
<add> })
<add> expect(editor.getCursorScreenPosition()).toEqual([0, 0])
<add>
<add> const childElementClientRect = childElement.getBoundingClientRect()
<add> component.didMouseDownOnContent({
<add> target: childElement,
<add> detail: 1,
<add> button: 0,
<add> clientX: childElementClientRect.left,
<add> clientY: childElementClientRect.top
<add> })
<add> expect(editor.getCursorScreenPosition()).toEqual([0, 0])
<add> })
<add>
<ide> function createBlockDecorationAtScreenRow(editor, screenRow, {height, margin, position}) {
<ide> const marker = editor.markScreenPosition([screenRow, 0], {invalidate: 'never'})
<ide> const item = document.createElement('div')
<ide><path>src/text-editor-component.js
<ide> class TextEditorComponent {
<ide> const {target, button, detail, ctrlKey, shiftKey, metaKey} = event
<ide> const platform = this.getPlatform()
<ide>
<add> // Ignore clicks on block decorations.
<add> if (target) {
<add> let element = target
<add> while (element && element !== this.element) {
<add> if (this.blockDecorationsByElement.has(element)) {
<add> return
<add> }
<add>
<add> element = element.parentElement
<add> }
<add> }
<add>
<ide> // On Linux, position the cursor on middle mouse button click. A
<ide> // textInput event with the contents of the selection clipboard will be
<ide> // dispatched by the browser automatically on mouseup. | 2 |
Text | Text | use code markup/markdown in headers | b3ff0481ff8a8132ca097c5aec540c98a5fa631c | <ide><path>doc/api/esm.md
<ide> or when referenced by `import` statements within ES module code:
<ide> * Strings passed in as an argument to `--eval` or `--print`, or piped to
<ide> `node` via `STDIN`, with the flag `--input-type=commonjs`.
<ide>
<del>### <code>package.json</code> <code>"type"</code> field
<add>### `package.json` `"type"` field
<ide>
<ide> Files ending with `.js` or `.mjs`, or lacking any extension,
<ide> will be loaded as ES modules when the nearest parent `package.json` file
<ide> package scope:
<ide> extension (since both `.js` and `.cjs` files are treated as CommonJS within a
<ide> `"commonjs"` package scope).
<ide>
<del>### <code>--input-type</code> flag
<add>### `--input-type` flag
<ide>
<ide> Strings passed in as an argument to `--eval` or `--print` (or `-e` or `-p`), or
<ide> piped to `node` via `STDIN`, will be treated as ES modules when the
<ide> defined in `"exports"`. If package entry points are defined in both `"main"` and
<ide> `"exports"`. [Conditional Exports][] can also be used within `"exports"` to
<ide> define different package entry points per environment.
<ide>
<del>#### <code>package.json</code> <code>"main"</code>
<add>#### `package.json` `"main"`
<ide>
<ide> The `package.json` `"main"` field defines the entry point for a package,
<ide> whether the package is included into CommonJS via `require` or into an ES
<ide> If the `--experimental-conditional-exports` flag is dropped and therefore
<ide> easily updated to use conditional exports by adding conditions to the `"."`
<ide> path; while keeping `"./module"` for backward compatibility.
<ide>
<del>## <code>import</code> Specifiers
<add>## `import` Specifiers
<ide>
<ide> ### Terminology
<ide>
<ide> import 'data:text/javascript,console.log("hello!");';
<ide> import _ from 'data:application/json,"world!"';
<ide> ```
<ide>
<del>## import.meta
<add>## `import.meta`
<ide>
<ide> * {Object}
<ide>
<ide> indexes (e.g. `'./startup/index.js'`) must also be fully specified.
<ide> This behavior matches how `import` behaves in browser environments, assuming a
<ide> typically configured server.
<ide>
<del>### No <code>NODE_PATH</code>
<add>### No `NODE_PATH`
<ide>
<ide> `NODE_PATH` is not part of resolving `import` specifiers. Please use symlinks
<ide> if this behavior is desired.
<ide>
<del>### No <code>require</code>, <code>exports</code>, <code>module.exports</code>, <code>\_\_filename</code>, <code>\_\_dirname</code>
<add>### No `require`, `exports`, `module.exports`, `__filename`, `__dirname`
<ide>
<ide> These CommonJS variables are not available in ES modules.
<ide>
<ide> const __filename = fileURLToPath(import.meta.url);
<ide> const __dirname = dirname(__filename);
<ide> ```
<ide>
<del>### No <code>require.extensions</code>
<add>### No `require.extensions`
<ide>
<ide> `require.extensions` is not used by `import`. The expectation is that loader
<ide> hooks can provide this workflow in the future.
<ide>
<del>### No <code>require.cache</code>
<add>### No `require.cache`
<ide>
<ide> `require.cache` is not used by `import`. It has a separate cache.
<ide>
<ide> For now, only modules using the `file:` protocol can be loaded.
<ide>
<ide> ## Interoperability with CommonJS
<ide>
<del>### <code>require</code>
<add>### `require`
<ide>
<ide> `require` always treats the files it references as CommonJS. This applies
<ide> whether `require` is used the traditional way within a CommonJS environment, or
<ide> in an ES module environment using [`module.createRequire()`][].
<ide>
<ide> To include an ES module into CommonJS, use [`import()`][].
<ide>
<del>### <code>import</code> statements
<add>### `import` statements
<ide>
<ide> An `import` statement can reference an ES module or a CommonJS module. Other
<ide> file types such as JSON or Native modules are not supported. For those, use
<ide> import packageMain from 'commonjs-package'; // Works
<ide> import { method } from 'commonjs-package'; // Errors
<ide> ```
<ide>
<del>### <code>import()</code> expressions
<add>### `import()` expressions
<ide>
<ide> Dynamic `import()` is supported in both CommonJS and ES modules. It can be used
<ide> to include ES module files from CommonJS code. | 1 |
Go | Go | add support for multiple network in inspect | 7af9f988ac535e4ae2e87976db25d4f7047274db | <ide><path>api/client/network.go
<ide> func (cli *DockerCli) CmdNetworkLs(args ...string) error {
<ide>
<ide> // CmdNetworkInspect inspects the network object for more details
<ide> //
<del>// Usage: docker network inspect <NETWORK>
<add>// Usage: docker network inspect <NETWORK> [<NETWORK>]
<ide> // CmdNetworkInspect handles Network inspect UI
<ide> func (cli *DockerCli) CmdNetworkInspect(args ...string) error {
<ide> cmd := Cli.Subcmd("network inspect", []string{"NETWORK"}, "Displays detailed information on a network", false)
<del> cmd.Require(flag.Exact, 1)
<add> cmd.Require(flag.Min, 1)
<ide> err := cmd.ParseFlags(args, true)
<ide> if err != nil {
<ide> return err
<ide> }
<ide>
<del> obj, _, err := readBody(cli.call("GET", "/networks/"+cmd.Arg(0), nil, nil))
<del> if err != nil {
<del> return err
<add> status := 0
<add> var networks []*types.NetworkResource
<add> for _, name := range cmd.Args() {
<add> obj, _, err := readBody(cli.call("GET", "/networks/"+name, nil, nil))
<add> if err != nil {
<add> if strings.Contains(err.Error(), "not found") {
<add> fmt.Fprintf(cli.err, "Error: No such network: %s\n", name)
<add> } else {
<add> fmt.Fprintf(cli.err, "%s", err)
<add> }
<add> status = 1
<add> continue
<add> }
<add> networkResource := types.NetworkResource{}
<add> if err := json.NewDecoder(bytes.NewReader(obj)).Decode(&networkResource); err != nil {
<add> return err
<add> }
<add>
<add> networks = append(networks, &networkResource)
<ide> }
<del> networkResource := &types.NetworkResource{}
<del> if err := json.NewDecoder(bytes.NewReader(obj)).Decode(networkResource); err != nil {
<add>
<add> b, err := json.MarshalIndent(networks, "", " ")
<add> if err != nil {
<ide> return err
<ide> }
<ide>
<del> indented := new(bytes.Buffer)
<del> if err := json.Indent(indented, obj, "", " "); err != nil {
<add> if _, err := io.Copy(cli.out, bytes.NewReader(b)); err != nil {
<ide> return err
<ide> }
<del> if _, err := io.Copy(cli.out, indented); err != nil {
<del> return err
<add> io.WriteString(cli.out, "\n")
<add>
<add> if status != 0 {
<add> return Cli.StatusError{StatusCode: status}
<ide> }
<ide> return nil
<ide> }
<ide><path>integration-cli/docker_cli_network_unix_test.go
<ide> func isNwPresent(c *check.C, name string) bool {
<ide>
<ide> func getNwResource(c *check.C, name string) *types.NetworkResource {
<ide> out, _ := dockerCmd(c, "network", "inspect", name)
<del> nr := types.NetworkResource{}
<add> nr := []types.NetworkResource{}
<ide> err := json.Unmarshal([]byte(out), &nr)
<ide> c.Assert(err, check.IsNil)
<del> return &nr
<add> return &nr[0]
<ide> }
<ide>
<ide> func (s *DockerNetworkSuite) TestDockerNetworkLsDefault(c *check.C) {
<ide> func (s *DockerSuite) TestDockerNetworkDeleteNotExists(c *check.C) {
<ide> c.Assert(err, checker.NotNil, check.Commentf("%v", out))
<ide> }
<ide>
<add>func (s *DockerSuite) TestDockerInspectMultipleNetwork(c *check.C) {
<add> out, _ := dockerCmd(c, "network", "inspect", "host", "none")
<add> networkResources := []types.NetworkResource{}
<add> err := json.Unmarshal([]byte(out), &networkResources)
<add> c.Assert(err, check.IsNil)
<add> c.Assert(networkResources, checker.HasLen, 2)
<add>
<add> // Should print an error, return an exitCode 1 *but* should print the host network
<add> out, exitCode, err := dockerCmdWithError("network", "inspect", "host", "nonexistent")
<add> c.Assert(err, checker.NotNil)
<add> c.Assert(exitCode, checker.Equals, 1)
<add> c.Assert(out, checker.Contains, "Error: No such network: nonexistent")
<add> networkResources = []types.NetworkResource{}
<add> inspectOut := strings.SplitN(out, "\n", 2)[1]
<add> err = json.Unmarshal([]byte(inspectOut), &networkResources)
<add> c.Assert(networkResources, checker.HasLen, 1)
<add>
<add> // Should print an error and return an exitCode, nothing else
<add> out, exitCode, err = dockerCmdWithError("network", "inspect", "nonexistent")
<add> c.Assert(err, checker.NotNil)
<add> c.Assert(exitCode, checker.Equals, 1)
<add> c.Assert(out, checker.Contains, "Error: No such network: nonexistent")
<add>}
<add>
<ide> func (s *DockerNetworkSuite) TestDockerNetworkConnectDisconnect(c *check.C) {
<ide> dockerCmd(c, "network", "create", "test")
<ide> assertNwIsAvailable(c, "test") | 2 |
Javascript | Javascript | add fan of it to showcase | 825f5da652061fa72a2a3dbafcf81465a3bd97c5 | <ide><path>website/src/react-native/showcase.js
<ide> var apps = [
<ide> link: 'https://itunes.apple.com/us/app/facebook-ads-manager/id964397083?mt=8',
<ide> author: 'Facebook',
<ide> },
<add> {
<add> name: 'Fan of it',
<add> icon: 'http://a4.mzstatic.com/us/r30/Purple3/v4/c9/3f/e8/c93fe8fb-9332-e744-f04a-0f4f78e42aa8/icon350x350.png',
<add> link: 'https://itunes.apple.com/za/app/fan-of-it/id1017025530?mt=8',
<add> author: 'Fan of it (Pty) Ltd',
<add> },
<ide> {
<ide> name: 'FastPaper',
<ide> icon: 'http://a2.mzstatic.com/us/r30/Purple5/v4/72/b4/d8/72b4d866-90d2-3aad-d1dc-0315f2d9d045/icon350x350.jpeg', | 1 |
Javascript | Javascript | simplify condition in mobx example | c689bc9f8bb555a844eada2c279b4616ba804196 | <ide><path>examples/with-mobx/store.js
<ide> class Store {
<ide> }
<ide>
<ide> export function initStore (isServer, lastUpdate = Date.now()) {
<del> if (isServer && typeof window === 'undefined') {
<add> if (isServer) {
<ide> return new Store(isServer, lastUpdate)
<ide> } else {
<ide> if (store === null) { | 1 |
Javascript | Javascript | fix multibyte decoding in content_disposition.js | e992480baa0b91132431793b4a62dc20ae9c2eb2 | <ide><path>src/display/content_disposition.js
<ide> function getFilenameFromContentDispositionHeader(contentDisposition) {
<ide> }
<ide> function textdecode(encoding, value) {
<ide> if (encoding) {
<del> if (!/^[^\x00-\xFF]+$/.test(value)) {
<add> if (!/^[\x00-\xFF]+$/.test(value)) {
<ide> return value;
<ide> }
<ide> try {
<ide> let decoder = new TextDecoder(encoding, { fatal: true, });
<ide> let bytes = new Array(value.length);
<ide> for (let i = 0; i < value.length; ++i) {
<del> bytes[i] = value.charCodeAt(0);
<add> bytes[i] = value.charCodeAt(i);
<ide> }
<ide> value = decoder.decode(new Uint8Array(bytes));
<ide> needsEncodingFixup = false;
<ide> } catch (e) {
<ide> // TextDecoder constructor threw - unrecognized encoding.
<del> // Or TextDecoder API is not available.
<add> // Or TextDecoder API is not available (in IE / Edge).
<ide> if (/^utf-?8$/i.test(encoding)) {
<ide> // UTF-8 is commonly used, try to support it in another way:
<del> value = decodeURIComponent(escape(value));
<del> needsEncodingFixup = false;
<add> try {
<add> value = decodeURIComponent(escape(value));
<add> needsEncodingFixup = false;
<add> } catch (err) {
<add> }
<ide> }
<ide> }
<ide> } | 1 |
Javascript | Javascript | fix attr setting in glimmer components | 8dc7d58cd4c0f45cc5aaf79c3ccf03d10dd7445f | <ide><path>packages/ember-htmlbars/lib/node-managers/component-node-manager.js
<ide> ComponentNodeManager.prototype.destroy = function() {
<ide> export function createComponent(_component, isAngleBracket, _props, renderNode, env, attrs = {}, proto = _component.proto()) {
<ide> let props = assign({}, _props);
<ide>
<add> let snapshot = takeSnapshot(attrs);
<add> props.attrs = snapshot;
<add>
<ide> if (!isAngleBracket) {
<ide> let hasSuppliedController = 'controller' in attrs; // 2.0TODO remove
<ide> Ember.deprecate('controller= is deprecated', !hasSuppliedController, { id: 'ember-htmlbars.create-component', until: '3.0.0' });
<ide>
<del> let snapshot = takeSnapshot(attrs);
<del> props.attrs = snapshot;
<del>
<ide> mergeBindings(props, shadowedAttrs(proto, snapshot));
<ide> } else {
<ide> props._isAngleBracket = true; | 1 |
Javascript | Javascript | fix usage of dependencytemplates and types | ef40df2d1f7259fadc9909533eaa86b4e6f3e544 | <ide><path>lib/ChunkTemplate.js
<ide> const { SyncWaterfallHook, SyncHook } = require("tapable");
<ide> /** @typedef {import("./Chunk")} Chunk */
<ide> /** @typedef {import("./Module")} Module} */
<ide> /** @typedef {import("./util/createHash").Hash} Hash} */
<add>/** @typedef {import("./DependencyTemplates")} DependencyTemplates} */
<ide>
<ide> /**
<ide> * @typedef {Object} RenderManifestOptions
<ide> const { SyncWaterfallHook, SyncHook } = require("tapable");
<ide> * @property {string} fullHash
<ide> * @property {TODO} outputOptions
<ide> * @property {{javascript: ModuleTemplate, webassembly: ModuleTemplate}} moduleTemplates
<del> * @property {Map<TODO, TODO>} dependencyTemplates
<add> * @property {DependencyTemplates} dependencyTemplates
<ide> */
<ide>
<ide> module.exports = class ChunkTemplate {
<ide><path>lib/Compilation.js
<ide> const SortableSet = require("./util/SortableSet");
<ide> const GraphHelpers = require("./GraphHelpers");
<ide> const ModuleDependency = require("./dependencies/ModuleDependency");
<ide> const compareLocations = require("./compareLocations");
<add>const DependencyTemplates = require("./DependencyTemplates");
<ide>
<ide> /** @typedef {import("./Module")} Module */
<ide> /** @typedef {import("./Compiler")} Compiler */
<ide> class Compilation {
<ide> this.children = [];
<ide> /** @type {Map<DepConstructor, ModuleFactory>} */
<ide> this.dependencyFactories = new Map();
<del> /** @type {Map<DepConstructor|string, DependencyTemplate|string>} */
<del> this.dependencyTemplates = new Map();
<add> /** @type {DependencyTemplates} */
<add> this.dependencyTemplates = new DependencyTemplates();
<ide> this.childrenCounters = {};
<ide> /** @type {Set<number|string>} */
<ide> this.usedChunkIds = null;
<ide><path>lib/DependenciesBlockVariable.js
<ide> class DependenciesBlockVariable {
<ide> expressionSource(dependencyTemplates, runtimeTemplate) {
<ide> const source = new ReplaceSource(new RawSource(this.expression));
<ide> for (const dep of this.dependencies) {
<del> const template = dependencyTemplates.get(dep.constructor);
<add> const constructor =
<add> /** @type {new (...args: any[]) => Dependency} */ (dep.constructor);
<add> const template = dependencyTemplates.get(constructor);
<ide> if (!template) {
<ide> throw new Error(`No template for dependency: ${dep.constructor.name}`);
<ide> }
<ide><path>lib/DependencyTemplates.js
<ide>
<ide> const createHash = require("./util/createHash");
<ide>
<add>/** @typedef {import("./Dependency")} Dependency */
<ide> /** @typedef {import("./Dependency").DependencyTemplate} DependencyTemplate */
<add>/** @typedef {new (...args: any[]) => Dependency} DependencyConstructor */
<ide>
<ide> class DependencyTemplates {
<ide> constructor() {
<ide> class DependencyTemplates {
<ide> }
<ide>
<ide> /**
<del> * @param {Function} dependency Constructor of Dependency
<add> * @param {DependencyConstructor} dependency Constructor of Dependency
<ide> * @returns {DependencyTemplate} template for this dependency
<ide> */
<ide> get(dependency) {
<ide> return this._map.get(dependency);
<ide> }
<ide>
<ide> /**
<del> * @param {Function} dependency Constructor of Dependency
<add> * @param {DependencyConstructor} dependency Constructor of Dependency
<ide> * @param {DependencyTemplate} dependencyTemplate template for this dependency
<ide> * @returns {void}
<ide> */
<ide><path>lib/MainTemplate.js
<ide> const Template = require("./Template");
<ide> * @property {string} fullHash
<ide> * @property {TODO} outputOptions
<ide> * @property {{javascript: ModuleTemplate, webassembly: ModuleTemplate}} moduleTemplates
<del> * @property {Map<TODO, TODO>} dependencyTemplates
<add> * @property {DependencyTemplates} dependencyTemplates
<ide> */
<ide>
<ide> // require function shortcuts:
<ide><path>test/statsCases/define-plugin/webpack.config.js
<ide> var fs = require("fs");
<ide> var join = require("path").join;
<ide>
<ide> function read(path) {
<del> return JSON.stringify(fs.readFileSync(join(__dirname, path), "utf8"));
<add> return JSON.stringify(
<add> fs.readFileSync(join(__dirname, path), "utf8").replace(/\r\n?/g, "\n")
<add> );
<ide> }
<ide>
<ide> module.exports = [ | 6 |
Text | Text | remove reference to link_scripts | 1e7bff808180a35da545630ad75a6fab31cf7da5 | <ide><path>docs/Python-for-Formula-Authors.md
<ide> def install
<ide> venv = virtualenv_create(libexec)
<ide> # Install all of the resources declared on the formula into the virtualenv.
<ide> venv.pip_install resources
<del> # `link_scripts` takes a look at the virtualenv's bin directory before and
<del> # after executing the block which is passed into it. If the block caused any
<del> # new scripts to be written to the virtualenv's bin directory, link_scripts
<del> # will symlink those scripts into the path given as its argument (here, the
<del> # formula's `bin` directory in the Cellar.)
<del> # `pip_install buildpath` will install the package that the formula points to,
<del> # because buildpath is the location where the formula's tarball was unpacked.
<del> venv.link_scripts(bin) { venv.pip_install buildpath }
<add> # `pip_install_and_link` takes a look at the virtualenv's bin directory
<add> # before and after installing its argument. New scripts will be symlinked
<add> # into `bin`. `pip_install_and_link buildpath` will install the package
<add> # that the formula points to, because buildpath is the location where the
<add> # formula's tarball was unpacked.
<add> venv.pip_install_and_link buildpath
<ide> end
<ide> ```
<ide> | 1 |
Javascript | Javascript | add point to initializecore | a07de97754ec605222ebebf267534d38b3c11df5 | <ide><path>Libraries/Core/InitializeCore.js
<ide> */
<ide> 'use strict';
<ide>
<add>const startTime =
<add> global.nativePerformanceNow != null ? global.nativePerformanceNow() : null;
<add>
<ide> const {polyfillObjectProperty, polyfillGlobal} = require('PolyfillFunctions');
<ide>
<ide> if (global.GLOBAL === undefined) {
<ide> if (__DEV__) {
<ide> JSInspector.registerAgent(require('NetworkAgent'));
<ide> }
<ide> }
<add>
<add>if (startTime != null) {
<add> const PerformanceLogger = require('PerformanceLogger');
<add> PerformanceLogger.markPoint('InitializeCoreStartTime', startTime);
<add>} | 1 |
PHP | PHP | handle prefix update on route level prefix | 449c8056cc0f13e7e20428700045339bae6bdca2 | <ide><path>src/Illuminate/Routing/Route.php
<ide> public function __construct($methods, $uri, $action)
<ide> {
<ide> $this->uri = $uri;
<ide> $this->methods = (array) $methods;
<del> $this->action = $this->parseAction($action);
<add> $this->action = Arr::except($this->parseAction($action), ['prefix']);
<ide>
<ide> if (in_array('GET', $this->methods) && ! in_array('HEAD', $this->methods)) {
<ide> $this->methods[] = 'HEAD';
<ide> }
<ide>
<del> $this->prefix($this->action['prefix'] ?? '');
<add> $this->prefix(is_array($action) ? Arr::get($action, 'prefix') : '');
<ide> }
<ide>
<ide> /**
<ide> public function getPrefix()
<ide> */
<ide> public function prefix($prefix)
<ide> {
<add> $this->updatePrefixOnAction($prefix);
<add>
<ide> $uri = rtrim($prefix, '/').'/'.ltrim($this->uri, '/');
<ide>
<ide> return $this->setUri($uri !== '/' ? trim($uri, '/') : $uri);
<ide> }
<ide>
<add> /**
<add> * Update the "prefix" attribute on the action array.
<add> *
<add> * @param string $prefix
<add> * @return void
<add> */
<add> protected function updatePrefixOnAction($prefix)
<add> {
<add> if (! empty($newPrefix = trim(rtrim($prefix, '/').'/'.ltrim($this->action['prefix'] ?? '', '/'), '/'))) {
<add> $this->action['prefix'] = $newPrefix;
<add> }
<add> }
<add>
<ide> /**
<ide> * Get the URI associated with the route.
<ide> *
<ide><path>tests/Integration/Routing/CompiledRouteCollectionTest.php
<ide> public function testSlashPrefixIsProperlyHandled()
<ide> $this->assertSame('foo/bar', $route->uri());
<ide> }
<ide>
<add> public function testGroupPrefixAndRoutePrefixAreProperlyHandled()
<add> {
<add> $this->routeCollection->add($this->newRoute('GET', 'foo/bar', ['uses' => 'FooController@index', 'prefix' => '{locale}'])->prefix('pre'));
<add>
<add> $route = $this->collection()->getByAction('FooController@index');
<add>
<add> $this->assertSame('pre/{locale}', $route->getPrefix());
<add> }
<add>
<ide> public function testRouteBindingsAreProperlySaved()
<ide> {
<ide> $this->routeCollection->add($this->newRoute('GET', 'posts/{post:slug}/show', [ | 2 |
Text | Text | fix some grammar | dd25417f07f73277b9708162dc80e4549325d8af | <ide><path>docs/tutorials/essentials/part-1-overview-concepts.md
<ide> Redux helps you manage "global" state - state that is needed across many parts o
<ide>
<ide> ### When Should I Use Redux?
<ide>
<del>Redux helps you deal with shared state management, but like any tool, it has tradeoffs. There's more concepts to learn, and more code to write. It also adds some indirection to your code, and asks you to follow certain restrictions. It's a trade-off between short term and long term productivity.
<add>Redux helps you deal with shared state management, but like any tool, it has tradeoffs. There are more concepts to learn, and more code to write. It also adds some indirection to your code, and asks you to follow certain restrictions. It's a trade-off between short term and long term productivity.
<ide>
<ide> Redux is more useful when:
<ide>
<ide> For more info on how immutability works in JavaScript, see:
<ide>
<ide> ### Terminology
<ide>
<del>There's some important Redux terms that you'll need to be familiar with before we continue:
<add>There are some important Redux terms that you'll need to be familiar with before we continue:
<ide>
<ide> #### Actions
<ide> | 1 |
Go | Go | adjust tests for changes in go 1.12.8 / 1.11.13 | 683766613a8c1dca8f95b19ddb7e083bb3aef266 | <ide><path>opts/hosts_test.go
<ide> func TestParseHost(t *testing.T) {
<ide> func TestParseDockerDaemonHost(t *testing.T) {
<ide> invalids := map[string]string{
<ide>
<del> "tcp:a.b.c.d": "Invalid bind address format: tcp:a.b.c.d",
<del> "tcp:a.b.c.d/path": "Invalid bind address format: tcp:a.b.c.d/path",
<add> "tcp:a.b.c.d": "",
<add> "tcp:a.b.c.d/path": "",
<ide> "udp://127.0.0.1": "Invalid bind address format: udp://127.0.0.1",
<ide> "udp://127.0.0.1:2375": "Invalid bind address format: udp://127.0.0.1:2375",
<ide> "tcp://unix:///run/docker.sock": "Invalid proto, expected tcp: unix:///run/docker.sock",
<ide> func TestParseDockerDaemonHost(t *testing.T) {
<ide> "localhost:5555/path": "tcp://localhost:5555/path",
<ide> }
<ide> for invalidAddr, expectedError := range invalids {
<del> if addr, err := parseDaemonHost(invalidAddr); err == nil || err.Error() != expectedError {
<add> if addr, err := parseDaemonHost(invalidAddr); err == nil || expectedError != "" && err.Error() != expectedError {
<ide> t.Errorf("tcp %v address expected error %q return, got %q and addr %v", invalidAddr, expectedError, err, addr)
<ide> }
<ide> }
<ide> func TestParseTCP(t *testing.T) {
<ide> defaultHTTPHost = "tcp://127.0.0.1:2376"
<ide> )
<ide> invalids := map[string]string{
<del> "tcp:a.b.c.d": "Invalid bind address format: tcp:a.b.c.d",
<del> "tcp:a.b.c.d/path": "Invalid bind address format: tcp:a.b.c.d/path",
<add> "tcp:a.b.c.d": "",
<add> "tcp:a.b.c.d/path": "",
<ide> "udp://127.0.0.1": "Invalid proto, expected tcp: udp://127.0.0.1",
<ide> "udp://127.0.0.1:2375": "Invalid proto, expected tcp: udp://127.0.0.1:2375",
<ide> }
<ide> func TestParseTCP(t *testing.T) {
<ide> "localhost:5555/path": "tcp://localhost:5555/path",
<ide> }
<ide> for invalidAddr, expectedError := range invalids {
<del> if addr, err := ParseTCPAddr(invalidAddr, defaultHTTPHost); err == nil || err.Error() != expectedError {
<add> if addr, err := ParseTCPAddr(invalidAddr, defaultHTTPHost); err == nil || expectedError != "" && err.Error() != expectedError {
<ide> t.Errorf("tcp %v address expected error %v return, got %s and addr %v", invalidAddr, expectedError, err, addr)
<ide> }
<ide> } | 1 |
PHP | PHP | throw expection for invalid attachement | 80d86fda0dd8dcafcb0f817439ef3bc70f4348b6 | <ide><path>src/Mailer/Message.php
<ide> public function setAttachments(array $attachments)
<ide> /** @var string $name */
<ide> $name = $fileInfo['file']->getClientFilename();
<ide> }
<del> } else {
<add> } elseif (is_string($fileInfo['file'])) {
<ide> $fileName = $fileInfo['file'];
<ide> $fileInfo['file'] = realpath($fileInfo['file']);
<ide> if ($fileInfo['file'] === false || !file_exists($fileInfo['file'])) {
<ide> public function setAttachments(array $attachments)
<ide> if (is_int($name)) {
<ide> $name = basename($fileInfo['file']);
<ide> }
<add> } else {
<add> throw new InvalidArgumentException(sprintf(
<add> 'File must be a filepath or UploadedFileInterface instance. Found `%s` instead.',
<add> gettype($fileInfo['file'])
<add> ));
<ide> }
<del> if (!isset($fileInfo['mimetype'])
<add> if (
<add> !isset($fileInfo['mimetype'])
<ide> && isset($fileInfo['file'])
<ide> && is_string($fileInfo['file'])
<ide> && function_exists('mime_content_type')
<ide><path>tests/TestCase/Mailer/MessageTest.php
<ide> public function testSetAttachmentDataNoMimetype()
<ide> $this->assertSame($expected, $this->message->getAttachments());
<ide> }
<ide>
<add> public function testSetAttachmentInvalidFile()
<add> {
<add> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectExceptionMessage(
<add> 'File must be a filepath or UploadedFileInterface instance. Found `boolean` instead.'
<add> );
<add>
<add> $this->message->setAttachments(['cake.icon.gif' => [
<add> 'file' => true,
<add> ]]);
<add> }
<add>
<ide> /**
<ide> * testReset method
<ide> * | 2 |
Text | Text | add text inside content providers section | b3f76eea3ba9f200721a9a390be1fd9ea3cdee6b | <ide><path>guide/english/android-development/core-components/index.md
<ide> There are three kinds of services:
<ide> A _Broadcast receiver_ is another component without user interface (except an optional status bar notification) that provides a gateway for the system to deliver events from/to the app, even when the latter hasn't been previously launched. For example, the Android system sends broadcasts when various system events occur, such as when the system boots up or the device starts charging.
<ide>
<ide> ### [Content providers](https://developer.android.com/guide/topics/providers/content-providers)
<del>A _Content provider_ is a component used to manage a set of app data to share with other applications. Each item saved in the content provider is identified by a URI scheme.
<add>A _Content provider_ is a component used to manage a set of app data to share with other applications. Each item saved in the content provider is identified by a URI scheme. _content provider_ can help an application manage access to data stored by itself, stored by other apps, and provide a way to share data with other apps.
<ide>
<ide> For detailed information about the topic, see the official [Android fundamentals](https://developer.android.com/guide/components/fundamentals) documentation.
<ide> | 1 |
Text | Text | add command for git checkout previous branch | 3cfe00eafd9fe379e72cd267ece476a588b45abd | <ide><path>guide/english/git/git-checkout/index.md
<ide> git checkout BRANCH-NAME
<ide> ```
<ide> Generally, Git won't let you checkout another branch unless your working directory is clean, because you would lose any working directory changes that aren't committed. You have three options to handle your changes: 1) trash them, 2) <a href='https://guide.freecodecamp.org/git/git-commit/' target='_blank' rel='nofollow'>commit them</a>, or 3) <a href='https://guide.freecodecamp.org/git/git-stash/' target='_blank' rel='nofollow'>stash them</a>.
<ide>
<add>### Checkout Previous Branch
<add>To checkout previous branch, run the command:
<add>```shell
<add>git checkout -
<add>```
<add>`git checkout -` is a shorthand for `git checkout @{-1}`.
<add>
<ide> ### Checkout a New Branch
<ide> To create and checkout a new branch with a single command, you can use:
<ide> ```shell | 1 |
Go | Go | fix flaky testswarmservicewithgroup | ef4bcf23e6d2324f15628ed3c0e8e8200593bd5f | <ide><path>integration-cli/docker_cli_swarm_test.go
<ide> func (s *DockerSwarmSuite) TestSwarmServiceWithGroup(c *check.C) {
<ide> d := s.AddDaemon(c, true, true)
<ide>
<ide> name := "top"
<del> out, err := d.Cmd("service", "create", "--name", name, "--user", "root:root", "--group-add", "wheel", "--group-add", "audio", "--group-add", "staff", "--group-add", "777", "busybox", "sh", "-c", "id > /id && top")
<add> out, err := d.Cmd("service", "create", "--name", name, "--user", "root:root", "--group-add", "wheel", "--group-add", "audio", "--group-add", "staff", "--group-add", "777", "busybox", "top")
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "")
<ide>
<ide> func (s *DockerSwarmSuite) TestSwarmServiceWithGroup(c *check.C) {
<ide>
<ide> container := strings.TrimSpace(out)
<ide>
<del> out, err = d.Cmd("exec", container, "cat", "/id")
<add> out, err = d.Cmd("exec", container, "id")
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(strings.TrimSpace(out), checker.Equals, "uid=0(root) gid=0(root) groups=10(wheel),29(audio),50(staff),777")
<ide> } | 1 |
PHP | PHP | add test for guesser callback transfer | 6d700974d27da0af2729e68520ad901020acdf96 | <ide><path>tests/Auth/AuthAccessGateTest.php
<ide> public function test_for_user_method_attaches_a_new_user_to_a_new_gate_instance(
<ide> $this->assertTrue($gate->forUser((object) ['id' => 2])->check('foo'));
<ide> }
<ide>
<add> public function test_for_user_method_attaches_a_new_user_to_a_new_gate_instance_with_guess_callback()
<add> {
<add> $gate = $this->getBasicGate();
<add>
<add> $gate->define('foo', function () {
<add> return true;
<add> });
<add>
<add> $counter = 0;
<add> $guesserCallback = function () use (&$counter) {
<add> $counter++;
<add> };
<add> $gate->guessPolicyNamesUsing($guesserCallback);
<add> $gate->getPolicyFor('fooClass');
<add> $this->assertEquals(1, $counter);
<add>
<add> // now the guesser callback should be present on the new gate as well
<add> $newGate = $gate->forUser((object) ['id' => 1]);
<add>
<add> $newGate->getPolicyFor('fooClass');
<add> $this->assertEquals(2, $counter);
<add>
<add> $newGate->getPolicyFor('fooClass');
<add> $this->assertEquals(3, $counter);
<add> }
<add>
<ide> /**
<ide> * @dataProvider notCallableDataProvider
<ide> */ | 1 |
PHP | PHP | fix phpdoc collection union() return type | 0fecd603347b74c954d74d8b7c38658a2c344aa7 | <ide><path>src/Illuminate/Support/Collection.php
<ide> public function combine($values)
<ide> * Union the collection with the given items.
<ide> *
<ide> * @param mixed $items
<del> * @return void
<add> * @return static
<ide> */
<ide> public function union($items)
<ide> { | 1 |
Javascript | Javascript | remove internal errorcache property | 4d58c08865d7c996bb8cfbe15793443fd425410f | <ide><path>lib/assert.js
<ide> const { codes: {
<ide> ERR_INVALID_ARG_VALUE,
<ide> ERR_INVALID_RETURN_VALUE
<ide> } } = require('internal/errors');
<del>const { AssertionError, errorCache } = require('internal/assert');
<add>const { AssertionError } = require('internal/assert');
<ide> const { openSync, closeSync, readSync } = require('fs');
<ide> const { inspect, types: { isPromise, isRegExp } } = require('util');
<ide> const { EOL } = require('internal/constants');
<ide> const { NativeModule } = require('internal/bootstrap/loaders');
<ide>
<add>const errorCache = new Map();
<add>
<ide> let isDeepEqual;
<ide> let isDeepStrictEqual;
<ide> let parseExpressionAt;
<ide><path>lib/internal/assert.js
<ide> class AssertionError extends Error {
<ide> }
<ide>
<ide> module.exports = {
<del> AssertionError,
<del> errorCache: new Map()
<add> AssertionError
<ide> };
<ide><path>test/parallel/test-assert-builtins-not-read-from-filesystem.js
<ide> if (process.argv[2] !== 'child') {
<ide> e.emit('hello', false);
<ide> } catch (err) {
<ide> const frames = err.stack.split('\n');
<del> const [, filename, , ] = frames[1].match(/\((.+):(\d+):(\d+)\)/);
<add> const [, filename, line, column] = frames[1].match(/\((.+):(\d+):(\d+)\)/);
<ide> // Spawn a child process to avoid the error having been cached in the assert
<ide> // module's `errorCache` Map.
<ide>
<ide> const { output, status, error } =
<ide> spawnSync(process.execPath,
<del> [process.argv[1], 'child', filename],
<add> [process.argv[1], 'child', filename, line, column],
<ide> { cwd: tmpdir.path, env: process.env });
<ide> assert.ifError(error);
<ide> assert.strictEqual(status, 0, `Exit code: ${status}\n${output}`); | 3 |
Javascript | Javascript | compute the necessary inverse and reuse it | 26978c4e198ae481fcab3c3b3a1cecc93988715b | <ide><path>examples/js/controls/DragControls.js
<ide> THREE.DragControls = function ( _objects, _camera, _domElement ) {
<ide> var _offset = new THREE.Vector3();
<ide> var _intersection = new THREE.Vector3();
<ide> var _worldPosition = new THREE.Vector3();
<add> var _inverseMatrix = new THREE.Matrix4();
<add>
<ide> var _selected = null, _hovered = null;
<ide>
<ide> //
<ide> THREE.DragControls = function ( _objects, _camera, _domElement ) {
<ide>
<ide> if ( _raycaster.ray.intersectPlane( _plane, _intersection ) ) {
<ide>
<del> _selected.position.copy( _selected.parent.worldToLocal( _intersection.sub( _offset ) ) );
<add> _selected.position.copy( _intersection.sub( _offset ).applyMatrix4( _inverseMatrix ) );
<ide>
<ide> }
<ide>
<ide> THREE.DragControls = function ( _objects, _camera, _domElement ) {
<ide>
<ide> if ( _raycaster.ray.intersectPlane( _plane, _intersection ) ) {
<ide>
<add> _inverseMatrix.getInverse( _selected.parent.matrixWorld );
<ide> _offset.copy( _intersection ).sub( _worldPosition.setFromMatrixPosition( _selected.matrixWorld ) );
<ide>
<ide> }
<ide> THREE.DragControls = function ( _objects, _camera, _domElement ) {
<ide>
<ide> if ( _raycaster.ray.intersectPlane( _plane, _intersection ) ) {
<ide>
<del> _selected.position.copy( _selected.parent.worldToLocal( _intersection.sub( _offset ) ) );
<add> _selected.position.copy( _intersection.sub( _offset ).applyMatrix4( _inverseMatrix ) );
<ide>
<ide> }
<ide>
<ide> THREE.DragControls = function ( _objects, _camera, _domElement ) {
<ide>
<ide> if ( _raycaster.ray.intersectPlane( _plane, _intersection ) ) {
<ide>
<add> _inverseMatrix.getInverse( _selected.parent.matrixWorld );
<ide> _offset.copy( _intersection ).sub( _worldPosition.setFromMatrixPosition( _selected.matrixWorld ) );
<ide>
<ide> } | 1 |
Java | Java | name the newthreadscheduler threads | 56bd8db2f46237c648ea0f7e8004883847cfb763 | <ide><path>rxjava-core/src/main/java/rx/concurrency/NewThreadScheduler.java
<ide> public Subscription schedule(Func0<Subscription> action) {
<ide> public void run() {
<ide> discardableAction.call();
<ide> }
<del> });
<add> }, "RxNewThreadScheduler");
<ide>
<ide> t.start();
<ide> | 1 |
Javascript | Javascript | update flash message | 49101183663ffca913880f507a3071bdb4e86339 | <ide><path>server/boot/story.js
<ide> module.exports = function(app) {
<ide> function submitNew(req, res) {
<ide> if (!req.user.isGithubCool) {
<ide> req.flash('errors', {
<del> msg: 'You must authenticate with Github to post to Camper News'
<add> msg: 'You must link GitHub with your account before you can post' +
<add> ' on Camper News.'
<ide> });
<ide> return res.redirect('/news');
<ide> } | 1 |
Text | Text | correct markdown (shellsort) | cc6814bd1cdb6fe136400caaf838ba6af3210d0e | <ide><path>README.md
<ide> __Properties__
<ide> ### Shell
<ide> ![alt text][shell-image]
<ide>
<del>From [Wikipedia][shell-wiki]: Shellsort is a generalization of insertion sort that allows the exchange of items that are far apart. The idea is to arrange the list of elements so that, starting anywherem considereing every nth element gives a sorted list. Such a list is said to be h-sorted. Equivanelty, it can be thought of as h intterleaved lists, each individually sorted.
<add>From [Wikipedia][shell-wiki]: Shellsort is a generalization of insertion sort that allows the exchange of items that are far apart. The idea is to arrange the list of elements so that, starting anywhere, considering every nth element gives a sorted list. Such a list is said to be h-sorted. Equivalently, it can be thought of as h interleaved lists, each individually sorted.
<ide>
<ide> __Properties__
<ide> * Worst case performance O(nlog2 2n) | 1 |
PHP | PHP | add an exception when datefmt_create fails | 7a20e8b785d0d9388f76f3d34520702870ab0bdc | <ide><path>src/I18n/DateFormatTrait.php
<ide> use Cake\Chronos\Date as ChronosDate;
<ide> use Cake\Chronos\MutableDate;
<ide> use IntlDateFormatter;
<add>use RuntimeException;
<ide>
<ide> /**
<ide> * Trait for date formatting methods shared by both Time & Date.
<ide> protected function _formatObject($date, $format, $locale)
<ide> } elseif ($timezone[0] === '+' || $timezone[0] === '-') {
<ide> $timezone = 'GMT' . $timezone;
<ide> }
<del> static::$_formatters[$key] = datefmt_create(
<add> $formatter = datefmt_create(
<ide> $locale,
<ide> $dateFormat,
<ide> $timeFormat,
<ide> $timezone,
<ide> $calendar,
<ide> $pattern
<ide> );
<add> if (!$formatter) {
<add> throw new RuntimeException(
<add> 'Your version of icu does not support creating a date formatter for ' .
<add> "`$key`. You should try to upgrade libicu and the intl extension."
<add> );
<add> }
<add> static::$_formatters[$key] = $formatter;
<ide> }
<ide>
<ide> return static::$_formatters[$key]->format($date->format('U')); | 1 |
Python | Python | update slicehost for create_node api changes | c18fe5396a4ea6190e2cefb0bbdbfa256db463e1 | <ide><path>libcloud/drivers/slicehost.py
<ide> def list_sizes(self):
<ide> def list_images(self):
<ide> return self._to_images(self.connection.request('/images.xml').object)
<ide>
<del> def create_node(self, name, image, size, **kwargs):
<add> def create_node(self, **kwargs):
<add> name = kwargs['name']
<add> image = kwargs['image']
<add> size = kwargs['size']
<ide> uri = '/slices.xml'
<ide>
<ide> # create a slice obj
<ide><path>test/test_slicehost.py
<ide> def test_destroy_node(self):
<ide> def test_create_node(self):
<ide> image = NodeImage(id=11, name='ubuntu 8.10', driver=self.driver)
<ide> size = NodeSize(1, '256 slice', None, None, None, None, driver=self.driver)
<del> node = self.driver.create_node('slicetest', image, size)
<add> node = self.driver.create_node(name='slicetest', image=image, size=size)
<ide> self.assertEqual(node.name, 'slicetest')
<ide>
<ide> class SlicehostMockHttp(MockHttp): | 2 |
Javascript | Javascript | remove dead code | 83360899db901a3eace976adff749006fbcee8a7 | <ide><path>test/es-module/test-esm-dynamic-import.js
<ide> const common = require('../common');
<ide> const assert = require('assert');
<ide> const { URL } = require('url');
<del>const vm = require('vm');
<ide>
<ide> const relativePath = '../fixtures/es-modules/test-esm-ok.mjs';
<ide> const absolutePath = require.resolve('../fixtures/es-modules/test-esm-ok.mjs');
<ide> function expectMissingModuleError(result) {
<ide> expectErrorProperty(result, 'code', 'MODULE_NOT_FOUND');
<ide> }
<ide>
<del>function expectInvalidUrlError(result) {
<del> expectErrorProperty(result, 'code', 'ERR_INVALID_URL');
<del>}
<del>
<del>function expectInvalidReferrerError(result) {
<del> expectErrorProperty(result, 'code', 'ERR_INVALID_URL');
<del>}
<del>
<del>function expectInvalidProtocolError(result) {
<del> expectErrorProperty(result, 'code', 'ERR_INVALID_PROTOCOL');
<del>}
<del>
<del>function expectInvalidContextError(result) {
<del> expectErrorProperty(result,
<del> 'message', 'import() called outside of main context');
<del>}
<del>
<ide> function expectOkNamespace(result) {
<ide> Promise.resolve(result)
<ide> .then(common.mustCall(ns => { | 1 |
Ruby | Ruby | fix creation example in nested attributes | 10f3cf00b8cca86a088fc98fa46fdff0b027a495 | <ide><path>activerecord/lib/active_record/nested_attributes.rb
<ide> module NestedAttributes #:nodoc:
<ide> # create the member and avatar in one go:
<ide> #
<ide> # params = { :member => { :name => 'Jack', :avatar_attributes => { :icon => 'smiling' } } }
<del> # member = Member.create(params)
<add> # member = Member.create(params['member'])
<ide> # member.avatar.id # => 2
<ide> # member.avatar.icon # => 'smiling'
<ide> # | 1 |
Javascript | Javascript | remove some unintended changes | 948de2bdbe57a80433c87a2fe4fe27aeabf0ccae | <ide><path>src/canvas.js
<ide> var CanvasGraphics = (function CanvasGraphicsClosure() {
<ide>
<ide> this.restore();
<ide> },
<add>
<ide> paintImageMaskXObject: function canvasGraphicsPaintImageMaskXObject(
<ide> imgArray, inverseDecode, width, height) {
<ide> function applyStencilMask(buffer, inverseDecode) {
<ide><path>src/core.js
<ide> var verbosity = WARNINGS;
<ide> if (!globalScope.PDFJS) {
<ide> globalScope.PDFJS = {};
<ide> }
<add>
<ide> // getPdf()
<ide> // Convenience function to perform binary Ajax GET
<ide> // Usage: getPdf('http://...', callback)
<ide> var PDFDocModel = (function PDFDocModelClosure() {
<ide> this.startXRef,
<ide> this.mainXRefEntriesOffset);
<ide> this.catalog = new Catalog(this.xref);
<del> this.objs = new PDFObjects();
<ide> },
<ide> get numPages() {
<ide> var linearization = this.linearization;
<ide><path>src/image.js
<ide> var PDFImage = (function PDFImageClosure() {
<ide> }
<ide> function PDFImage(xref, res, image, inline, smask) {
<ide> this.image = image;
<del>
<ide> if (image.getParams) {
<ide> // JPX/JPEG2000 streams directly contain bits per component
<ide> // and color space mode information. | 3 |
Javascript | Javascript | fix a broken link | 8b54524c0704b33409ff6827e5f8830e046c4204 | <ide><path>src/ng/compile.js
<ide> * It is safe to do DOM transformation in the post-linking function on elements that are not waiting
<ide> * for their async templates to be resolved.
<ide> *
<del> * <a name="Attributes"></a>
<ide> * ### Attributes
<ide> *
<ide> * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
<ide> function $CompileProvider($provide, $$sanitizeUriProvider) {
<ide> * @param {string} key Normalized key. (ie ngAttribute) .
<ide> * @param {function(interpolatedValue)} fn Function that will be called whenever
<ide> the interpolated value of the attribute changes.
<del> * See the {@link guide/directive#Attributes Directives} guide for more info.
<add> * See {@link ng.$compile#attributes $compile} for more info.
<ide> * @returns {function()} Returns a deregistration function for this observer.
<ide> */
<ide> $observe: function(key, fn) { | 1 |
Javascript | Javascript | improve inspectoptions validation | bf36f0755c0a41702fe506bcfc90d156030d0497 | <ide><path>lib/internal/console/constructor.js
<ide> function Console(options /* or: stdout, stderr, ignoreErrors = true */) {
<ide> if (typeof colorMode !== 'boolean' && colorMode !== 'auto')
<ide> throw new ERR_INVALID_ARG_VALUE('colorMode', colorMode);
<ide>
<del> if (inspectOptions) {
<add> if (typeof inspectOptions === 'object' && inspectOptions !== null) {
<ide> if (inspectOptions.colors !== undefined &&
<ide> options.colorMode !== undefined) {
<ide> throw new ERR_INCOMPATIBLE_OPTION_PAIR(
<ide> 'inspectOptions.color', 'colorMode');
<ide> }
<ide> optionsMap.set(this, inspectOptions);
<add> } else if (inspectOptions !== undefined) {
<add> throw new ERR_INVALID_ARG_TYPE('inspectOptions', 'object', inspectOptions);
<ide> }
<ide>
<ide> // Bind the prototype functions to this Console instance
<ide><path>test/parallel/test-console-instance.js
<ide> out.write = err.write = (d) => {};
<ide> assert.throws(() => c2.warn('foo'), /^Error: err$/);
<ide> assert.throws(() => c2.dir('foo'), /^Error: out$/);
<ide> }
<add>
<add>// Console constructor throws if inspectOptions is not an object.
<add>[null, true, false, 'foo', 5, Symbol()].forEach((inspectOptions) => {
<add> assert.throws(
<add> () => {
<add> new Console({
<add> stdout: out,
<add> stderr: err,
<add> inspectOptions
<add> });
<add> },
<add> {
<add> message: 'The "inspectOptions" argument must be of type object.' +
<add> ` Received type ${typeof inspectOptions}`,
<add> code: 'ERR_INVALID_ARG_TYPE'
<add> }
<add> );
<add>}); | 2 |
Javascript | Javascript | add format information, minor code refactoring | 350e397f636cab00a54c87a3e88138880f1c687e | <ide><path>lib/serialization/FileMiddleware.js
<ide> const SerializerMiddleware = require("./SerializerMiddleware");
<ide> /** @typedef {import("../util/fs").IntermediateFileSystem} IntermediateFileSystem */
<ide> /** @typedef {import("./types").BufferSerializableType} BufferSerializableType */
<ide>
<add>/*
<add>Format:
<add>
<add>File -> Header Section*
<add>
<add>Version -> u32
<add>AmountOfSections -> u32
<add>SectionSize -> i32 (if less than zero represents lazy value)
<add>
<add>Header -> Version AmountOfSections SectionSize*
<add>
<add>Buffer -> n bytes
<add>Section -> Buffer
<add>
<add>*/
<add>
<add>// "wpc" + 0 in little-endian
<add>const VERSION = 0x00637077;
<ide> const hashForName = buffers => {
<ide> const hash = createHash("md4");
<ide> for (const buf of buffers) hash.update(buf);
<ide> const serialize = async (middleware, data, name, writeFile) => {
<ide> /** @type {Promise<Buffer[] | Buffer | SerializeResult>[]} */ (processedData)
<ide> )
<ide> ).map(item => {
<del> if (Array.isArray(item)) return item;
<del> if (Buffer.isBuffer(item)) return item;
<add> if (Array.isArray(item) || Buffer.isBuffer(item)) return item;
<ide>
<ide> backgroundJobs.push(item.backgroundJob);
<ide> // create pointer buffer from size and name
<ide> const serialize = async (middleware, data, name, writeFile) => {
<ide> }
<ide> });
<ide> const header = Buffer.allocUnsafe(8 + lengths.length * 4);
<del> header.writeUInt32LE(0x00637077, 0);
<add> header.writeUInt32LE(VERSION, 0);
<ide> header.writeUInt32LE(lengths.length, 4);
<ide> for (let i = 0; i < lengths.length; i++) {
<ide> header.writeInt32LE(lengths[i], 8 + i * 4);
<ide> const deserialize = async (middleware, name, readFile) => {
<ide> const content = await readFile(name);
<ide> if (content.length === 0) throw new Error("Empty file " + name);
<ide> const version = content.readUInt32LE(0);
<del> if (version !== 0x00637077) {
<del> // "wpc" + 0
<add> if (version !== VERSION) {
<ide> throw new Error("Invalid file version");
<ide> }
<ide> const sectionCount = content.readUInt32LE(4); | 1 |
Go | Go | add api test to rotate the swarm ca certificate | 376c75d13cedd22c578197a140ffc10e27e84d01 | <ide><path>integration-cli/docker_api_swarm_test.go
<ide> import (
<ide> "sync"
<ide> "time"
<ide>
<add> "github.com/cloudflare/cfssl/csr"
<ide> "github.com/cloudflare/cfssl/helpers"
<add> "github.com/cloudflare/cfssl/initca"
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/api/types/container"
<ide> "github.com/docker/docker/api/types/swarm"
<ide> "github.com/docker/docker/integration-cli/checker"
<ide> "github.com/docker/docker/integration-cli/daemon"
<add> "github.com/docker/swarmkit/ca"
<ide> "github.com/go-check/check"
<ide> )
<ide>
<ide> func (s *DockerSwarmSuite) TestAPISwarmHealthcheckNone(c *check.C) {
<ide> out, err = d.Cmd("exec", containers[0], "ping", "-c1", "-W3", "top")
<ide> c.Assert(err, checker.IsNil, check.Commentf(out))
<ide> }
<add>
<add>func (s *DockerSwarmSuite) TestSwarmRepeatedRootRotation(c *check.C) {
<add> m := s.AddDaemon(c, true, true)
<add> w := s.AddDaemon(c, true, false)
<add>
<add> info, err := m.SwarmInfo()
<add> c.Assert(err, checker.IsNil)
<add>
<add> currentTrustRoot := info.Cluster.TLSInfo.TrustRoot
<add>
<add> // rotate multiple times
<add> for i := 0; i < 4; i++ {
<add> var cert, key []byte
<add> if i%2 != 0 {
<add> cert, _, key, err = initca.New(&csr.CertificateRequest{
<add> CN: "newRoot",
<add> KeyRequest: csr.NewBasicKeyRequest(),
<add> CA: &csr.CAConfig{Expiry: ca.RootCAExpiration},
<add> })
<add> c.Assert(err, checker.IsNil)
<add> }
<add> expectedCert := string(cert)
<add> m.UpdateSwarm(c, func(s *swarm.Spec) {
<add> s.CAConfig.SigningCACert = expectedCert
<add> s.CAConfig.SigningCAKey = string(key)
<add> s.CAConfig.ForceRotate++
<add> })
<add>
<add> // poll to make sure update succeeds
<add> var clusterTLSInfo swarm.TLSInfo
<add> for j := 0; j < 18; j++ {
<add> info, err := m.SwarmInfo()
<add> c.Assert(err, checker.IsNil)
<add> c.Assert(info.Cluster.Spec.CAConfig.SigningCACert, checker.Equals, expectedCert)
<add> // the desired CA key is always redacted
<add> c.Assert(info.Cluster.Spec.CAConfig.SigningCAKey, checker.Equals, "")
<add>
<add> clusterTLSInfo = info.Cluster.TLSInfo
<add>
<add> if !info.Cluster.RootRotationInProgress {
<add> break
<add> }
<add>
<add> // root rotation not done
<add> time.Sleep(250 * time.Millisecond)
<add> }
<add> c.Assert(clusterTLSInfo.TrustRoot, checker.Not(checker.Equals), currentTrustRoot)
<add> if cert != nil {
<add> c.Assert(clusterTLSInfo.TrustRoot, checker.Equals, expectedCert)
<add> }
<add> // could take another second or two for the nodes to trust the new roots after the've all gotten
<add> // new TLS certificates
<add> for j := 0; j < 18; j++ {
<add> mInfo := m.GetNode(c, m.NodeID).Description.TLSInfo
<add> wInfo := m.GetNode(c, w.NodeID).Description.TLSInfo
<add>
<add> if mInfo.TrustRoot == clusterTLSInfo.TrustRoot && wInfo.TrustRoot == clusterTLSInfo.TrustRoot {
<add> break
<add> }
<add>
<add> // nodes don't trust root certs yet
<add> time.Sleep(250 * time.Millisecond)
<add> }
<add>
<add> c.Assert(m.GetNode(c, m.NodeID).Description.TLSInfo, checker.DeepEquals, clusterTLSInfo)
<add> c.Assert(m.GetNode(c, w.NodeID).Description.TLSInfo, checker.DeepEquals, clusterTLSInfo)
<add> currentTrustRoot = clusterTLSInfo.TrustRoot
<add> }
<add>} | 1 |
Ruby | Ruby | add test case about assigning nil in enum | f5ec5246241c736bb95e1a3e997c7581c92360cb | <ide><path>activerecord/test/cases/enum_test.rb
<ide> class EnumTest < ActiveRecord::TestCase
<ide> assert_nil @book.status
<ide> end
<ide>
<add> test "assign nil value to enum which defines nil value to hash" do
<add> @book.read_status = nil
<add> assert_equal "forgotten", @book.read_status
<add> end
<add>
<ide> test "assign empty string value" do
<ide> @book.status = ""
<ide> assert_nil @book.status | 1 |
Python | Python | ignore keyerrors from del() | 05cbe1a5e3292271be809423b0b1a2272d9740b6 | <ide><path>celery/app/base.py
<ide> def log(self):
<ide>
<ide> @cached_property
<ide> def events(self):
<add> """Sending/receiving events.
<add>
<add> See :class:`~celery.events.Events`.
<add>
<add> """
<ide> from celery.events import Events
<ide> return Events(app=self)
<ide><path>celery/utils/__init__.py
<ide> def __set__(self, obj, value):
<ide> def __delete__(self, obj):
<ide> if not obj:
<ide> return self
<del> if self.__del is not None:
<del> self.__del(obj)
<del> del(obj.__dict__[self.__name__])
<add> try:
<add> del(obj.__dict__[self.__name__])
<add> except KeyError:
<add> pass
<add> else:
<add> if self.__del is not None:
<add> self.__del(obj)
<ide>
<ide> def setter(self, fset):
<ide> return self.__class__(self.__get, fset, self.__del)
<ide><path>celery/worker/autoscale.py
<ide> def qty(self):
<ide> @property
<ide> def processes(self):
<ide> return self.pool._pool._processes
<del>
<del> | 3 |
Java | Java | remove unused private loggers | debf61b948fd44a8757c4a8c286202ca3b6762b5 | <ide><path>spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests.java
<ide> import java.lang.annotation.RetentionPolicy;
<ide> import java.lang.reflect.Method;
<ide>
<del>import org.apache.commons.logging.Log;
<del>import org.apache.commons.logging.LogFactory;
<ide> import org.aspectj.lang.JoinPoint;
<ide> import org.aspectj.lang.ProceedingJoinPoint;
<ide> import org.aspectj.lang.annotation.Around;
<ide> import org.springframework.beans.PropertyValue;
<ide> import org.springframework.beans.factory.FactoryBean;
<ide> import org.springframework.beans.factory.config.MethodInvokingFactoryBean;
<del>import org.springframework.beans.factory.support.DefaultListableBeanFactory;
<ide> import org.springframework.beans.factory.support.RootBeanDefinition;
<ide> import org.springframework.beans.testfixture.beans.ITestBean;
<ide> import org.springframework.beans.testfixture.beans.TestBean;
<ide> */
<ide> public class AspectJAutoProxyCreatorTests {
<ide>
<del> private static final Log factoryLog = LogFactory.getLog(DefaultListableBeanFactory.class);
<del>
<ide>
<ide> @Test
<ide> public void testAspectsAreApplied() {
<ide><path>spring-context/src/test/java/org/springframework/context/expression/ApplicationContextExpressionTests.java
<ide> import java.util.Optional;
<ide> import java.util.Properties;
<ide>
<del>import org.apache.commons.logging.Log;
<del>import org.apache.commons.logging.LogFactory;
<ide> import org.junit.jupiter.api.Test;
<ide>
<ide> import org.springframework.beans.factory.ObjectFactory;
<ide> import org.springframework.beans.factory.config.Scope;
<ide> import org.springframework.beans.factory.config.TypedStringValue;
<ide> import org.springframework.beans.factory.support.AutowireCandidateQualifier;
<del>import org.springframework.beans.factory.support.DefaultListableBeanFactory;
<ide> import org.springframework.beans.factory.support.GenericBeanDefinition;
<ide> import org.springframework.beans.factory.support.RootBeanDefinition;
<ide> import org.springframework.beans.testfixture.beans.TestBean;
<ide> */
<ide> class ApplicationContextExpressionTests {
<ide>
<del> private static final Log factoryLog = LogFactory.getLog(DefaultListableBeanFactory.class);
<del>
<del>
<ide> @Test
<ide> @SuppressWarnings("deprecation")
<ide> void genericApplicationContext() throws Exception {
<ide><path>spring-tx/src/main/java/org/springframework/transaction/support/TransactionSynchronizationManager.java
<ide> import java.util.Map;
<ide> import java.util.Set;
<ide>
<del>import org.apache.commons.logging.Log;
<del>import org.apache.commons.logging.LogFactory;
<del>
<ide> import org.springframework.core.NamedThreadLocal;
<ide> import org.springframework.core.OrderComparator;
<ide> import org.springframework.lang.Nullable;
<ide> */
<ide> public abstract class TransactionSynchronizationManager {
<ide>
<del> private static final Log logger = LogFactory.getLog(TransactionSynchronizationManager.class);
<del>
<ide> private static final ThreadLocal<Map<Object, Object>> resources =
<ide> new NamedThreadLocal<>("Transactional resources");
<ide>
<ide><path>spring-web/src/main/java/org/springframework/http/converter/json/Jackson2ObjectMapperBuilder.java
<ide> import com.fasterxml.jackson.dataformat.xml.JacksonXmlModule;
<ide> import com.fasterxml.jackson.dataformat.xml.XmlFactory;
<ide> import com.fasterxml.jackson.dataformat.xml.XmlMapper;
<del>import org.apache.commons.logging.Log;
<ide>
<ide> import org.springframework.beans.BeanUtils;
<ide> import org.springframework.beans.FatalBeanException;
<ide> import org.springframework.context.ApplicationContext;
<ide> import org.springframework.core.KotlinDetector;
<del>import org.springframework.http.HttpLogging;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.util.ClassUtils;
<ide> */
<ide> public class Jackson2ObjectMapperBuilder {
<ide>
<del> private final Log logger = HttpLogging.forLogName(getClass());
<del>
<ide> private final Map<Class<?>, Class<?>> mixIns = new LinkedHashMap<>();
<ide>
<ide> private final Map<Class<?>, JsonSerializer<?>> serializers = new LinkedHashMap<>(); | 4 |
Python | Python | improve cli error handling [ci skip] | 5c53a76021775b2ed4cb6904c132f6e7780c7dc4 | <ide><path>spacy/cli/_util.py
<ide> def show_validation_error(
<ide> )
<ide> print(f"{COMMAND} init fill-config {config_path} --base {config_path}\n")
<ide> sys.exit(1)
<del> except InterpolationError as e:
<del> msg.fail("Config validation error", e, exits=1)
<add> except Exception as e:
<add> msg.fail("Error while loading the config")
<add> print(e)
<add> sys.exit(1)
<ide>
<ide>
<ide> def import_code(code_path: Optional[Union[Path, str]]) -> None: | 1 |
Javascript | Javascript | defer readiness to the end of the run loop | 455b2ecbcd3e4fe72a9eec9ed9ddb1d52ba92ee7 | <ide><path>packages/ember-application/lib/system/application.js
<ide> Ember.Application = Ember.Namespace.extend(
<ide>
<ide> // jQuery 1.7 doesn't call the ready callback if already ready
<ide> if (Ember.$.isReady) {
<del> this.didBecomeReady();
<add> Ember.run.once(this, this.didBecomeReady);
<ide> } else {
<ide> var self = this;
<ide> Ember.$(document).ready(function() {
<del> self.didBecomeReady();
<add> Ember.run.once(self, self.didBecomeReady);
<ide> });
<ide> }
<ide> },
<ide> Ember.Application = Ember.Namespace.extend(
<ide> /** @private */
<ide> didBecomeReady: function() {
<ide> var eventDispatcher = get(this, 'eventDispatcher'),
<add> stateManager = get(this, 'stateManager'),
<ide> customEvents = get(this, 'customEvents');
<ide>
<ide> eventDispatcher.setup(customEvents);
<ide>
<ide> this.ready();
<add>
<add> if (stateManager) {
<add> this.setupStateManager(stateManager);
<add> }
<add> },
<add>
<add> /**
<add> @private
<add>
<add> If the application has a state manager, use it to route
<add> to the current URL, and trigger a new call to `route`
<add> whenever the URL changes.
<add> */
<add> setupStateManager: function(stateManager) {
<add> var location = get(stateManager, 'location');
<add>
<add> stateManager.route(location.getURL());
<add> location.onUpdateURL(function(url) {
<add> stateManager.route(url);
<add> });
<ide> },
<ide>
<ide> /**
<ide><path>packages/ember-application/tests/system/application_test.js
<ide> var set = Ember.set, get = Ember.get, getPath = Ember.getPath;
<ide> module("Ember.Application", {
<ide> setup: function() {
<ide> Ember.$("#qunit-fixture").html("<div id='one'><div id='one-child'>HI</div></div><div id='two'>HI</div>");
<del> application = Ember.Application.create({ rootElement: '#one' });
<add> Ember.run(function() {
<add> application = Ember.Application.create({ rootElement: '#one' });
<add> });
<ide> },
<ide>
<ide> teardown: function() {
<ide> module("Ember.Application", {
<ide> });
<ide>
<ide> test("you can make a new application in a non-overlapping element", function() {
<del> var app = Ember.Application.create({ rootElement: '#two' });
<del> app.destroy();
<add> var app;
<add> Ember.run(function() {
<add> app = Ember.Application.create({ rootElement: '#two' });
<add> });
<add> Ember.run(function() {
<add> app.destroy();
<add> });
<ide> ok(true, "should not raise");
<ide> });
<ide>
<ide> test("you cannot make a new application that is a parent of an existing application", function() {
<ide> raises(function() {
<del> Ember.Application.create({ rootElement: '#qunit-fixture' });
<add> Ember.run(function() {
<add> Ember.Application.create({ rootElement: '#qunit-fixture' });
<add> });
<ide> }, Error);
<ide> });
<ide>
<ide> test("you cannot make a new application that is a descendent of an existing application", function() {
<ide> raises(function() {
<del> Ember.Application.create({ rootElement: '#one-child' });
<add> Ember.run(function() {
<add> Ember.Application.create({ rootElement: '#one-child' });
<add> });
<ide> }, Error);
<ide> });
<ide>
<ide> test("you cannot make a new application that is a duplicate of an existing application", function() {
<ide> raises(function() {
<del> Ember.Application.create({ rootElement: '#one' });
<add> Ember.run(function() {
<add> Ember.Application.create({ rootElement: '#one' });
<add> });
<ide> }, Error);
<ide> });
<ide>
<ide> test("you cannot make two default applications without a rootElement error", function() {
<ide> // Teardown existing
<del> application.destroy();
<add> Ember.run(function() {
<add> application.destroy();
<add> });
<ide>
<del> application = Ember.Application.create();
<add> Ember.run(function() {
<add> application = Ember.Application.create();
<add> });
<ide> raises(function() {
<del> Ember.Application.create();
<add> Ember.run(function() {
<add> Ember.Application.create();
<add> });
<ide> }, Error);
<ide> });
<ide>
<ide> test("acts like a namespace", function() {
<del> var app = window.TestApp = Ember.Application.create({rootElement: '#two'});
<add> var app;
<add> Ember.run(function() {
<add> app = window.TestApp = Ember.Application.create({rootElement: '#two'});
<add> });
<ide> app.Foo = Ember.Object.extend();
<ide> equal(app.Foo.toString(), "TestApp.Foo", "Classes pick up their parent namespace");
<ide> app.destroy();
<ide> test("inject controllers into a state manager", function() {
<ide> equal(getPath(stateManager, 'fooController.stateManager'), stateManager, "the state manager is assigned");
<ide> equal(getPath(stateManager, 'barController.stateManager'), stateManager, "the state manager is assigned");
<ide> });
<add>
<add>module("Ember.Application initial route", function() {
<add> Ember.run(function() {
<add> app = Ember.Application.create({
<add> rootElement: '#qunit-fixture'
<add> });
<add>
<add> app.stateManager = Ember.StateManager.create({
<add> location: {
<add> getURL: function() {
<add> return '/';
<add> }
<add> },
<add>
<add> start: Ember.State.extend({
<add> index: Ember.State.extend({
<add> route: '/'
<add> })
<add> })
<add> });
<add> });
<add>
<add> equal(app.getPath('stateManager.currentState.path'), 'start.index', "The router moved the state into the right place");
<add>}); | 2 |
Go | Go | increase test coverage of pkg/templates | 27e771b714b599c449c8fb8f01547454912aeb28 | <ide><path>pkg/templates/templates_test.go
<ide> func TestParseTruncateFunction(t *testing.T) {
<ide> template: `{{truncate . 30}}`,
<ide> expected: "tupx5xzf6hvsrhnruz5cr8gwp",
<ide> },
<add> {
<add> template: `{{pad . 3 3}}`,
<add> expected: " tupx5xzf6hvsrhnruz5cr8gwp ",
<add> },
<ide> }
<ide>
<ide> for _, testCase := range testCases {
<ide> tm, err := Parse(testCase.template)
<ide> assert.NoError(t, err)
<ide>
<del> var b bytes.Buffer
<del> assert.NoError(t, tm.Execute(&b, source))
<del> assert.Equal(t, testCase.expected, b.String())
<add> t.Run("Non Empty Source Test with template: "+testCase.template, func(t *testing.T) {
<add> var b bytes.Buffer
<add> assert.NoError(t, tm.Execute(&b, source))
<add> assert.Equal(t, testCase.expected, b.String())
<add> })
<add>
<add> t.Run("Empty Source Test with template: "+testCase.template, func(t *testing.T) {
<add> var c bytes.Buffer
<add> assert.NoError(t, tm.Execute(&c, ""))
<add> assert.Equal(t, "", c.String())
<add> })
<add>
<add> t.Run("Nil Source Test with template: "+testCase.template, func(t *testing.T) {
<add> var c bytes.Buffer
<add> assert.Error(t, tm.Execute(&c, nil))
<add> assert.Equal(t, "", c.String())
<add> })
<ide> }
<ide> } | 1 |
Python | Python | add missing keys | d17cce227022594ba84dbb92bafc802fb41434df | <ide><path>src/transformers/modeling_albert.py
<ide> class AlbertPreTrainedModel(PreTrainedModel):
<ide>
<ide> config_class = AlbertConfig
<ide> base_model_prefix = "albert"
<add> authorized_missing_keys = [r"position_ids"]
<ide>
<ide> def _init_weights(self, module):
<ide> """ Initialize the weights. | 1 |
Text | Text | update pr template | 3ae560c3fa9963cf0a8c979a5ecc7dc8ee349534 | <ide><path>.github/PULL_REQUEST_TEMPLATE.md
<ide> <!-- Make sure that your PR is not a duplicate -->
<ide>
<ide> #### Pre-Submission Checklist
<del><!-- Go over all points below, and put an `x` in all the boxes that apply. -->
<del><!-- All points should be checked, otherwise, read the CONTRIBUTING guidelines from above-->
<add><!-- Go over all points below, and after creating the PR, tick all the checkboxes that apply. -->
<add><!-- All points should be verified, otherwise, read the CONTRIBUTING guidelines from above-->
<ide> <!-- If you're unsure about any of these, don't hesitate to ask. We're here to help! -->
<ide> - [ ] Your pull request targets the `staging` branch of FreeCodeCamp.
<ide> - [ ] Branch starts with either `fix/`, `feature/`, or `translate/` (e.g. `fix/signin-issue`)
<ide> - [ ] You have only one commit (if not, [squash](https://github.com/FreeCodeCamp/FreeCodeCamp/wiki/git-rebase#squashing-multiple-commits-into-one) them into one commit).
<ide> - [ ] All new and existing tests pass the command `npm run test-challenges`. Use `git commit --amend` to amend any fixes.
<ide>
<ide> #### Type of Change
<del><!-- What type of change does your code introduce? Put an `x` in the box that applies. -->
<add><!-- What type of change does your code introduce? After creating the PR, tick the checkboxes that apply. -->
<ide> - [ ] Small bug fix (non-breaking change which fixes an issue)
<ide> - [ ] New feature (non-breaking change which adds new functionality)
<ide> - [ ] Breaking change (fix or feature that would change existing functionality)
<ide> - [ ] Add new translation (feature adding new translations)
<ide>
<ide> #### Checklist:
<del><!-- Go over all points below, and put an `x` in all the boxes that apply. -->
<add><!-- Go over all points below, and after creating the PR, tick the checkboxes that apply. -->
<ide> <!-- If you're unsure about any of these, don't hesitate to ask in the Help Contributors room linked above. We're here to help! -->
<ide> - [ ] Tested changes locally.
<ide> - [ ] Closes currently open issue (replace XXXX with an issue no): Closes #XXXX | 1 |
Go | Go | fix spelling error, add noether and euler | ab31d9500ebe0c3bf039321bb8c83c7b01c21e4e | <ide><path>pkg/namesgenerator/names-generator.go
<ide> var (
<ide> // Euclid invented geometry. https://en.wikipedia.org/wiki/Euclid
<ide> "euclid",
<ide>
<add> // Leonhard Euler invented large parts of modern mathematics. https://de.wikipedia.org/wiki/Leonhard_Euler
<add> "euler",
<add>
<ide> // Pierre de Fermat pioneered several aspects of modern mathematics. https://en.wikipedia.org/wiki/Pierre_de_Fermat
<ide> "fermat",
<ide>
<ide> var (
<ide> // Johanna Mestorf - German prehistoric archaeologist and first female museum director in Germany - https://en.wikipedia.org/wiki/Johanna_Mestorf
<ide> "mestorf",
<ide>
<del> // Lise Meitner was an Austrian physicist who worked on radioactivity and nuclear physics. She played a major role in the discovery of nuclear fission. https://en.wikipedia.org/wiki/Lise_Meitner
<del> "mietner",
<del>
<ide> // Maryam Mirzakhani - an Iranian mathematician and the first woman to win the Fields Medal. https://en.wikipedia.org/wiki/Maryam_Mirzakhani
<ide> "mirzakhani",
<ide>
<ide> var (
<ide> // Alfred Nobel - a Swedish chemist, engineer, innovator, and armaments manufacturer (inventor of dynamite) - https://en.wikipedia.org/wiki/Alfred_Nobel
<ide> "nobel",
<ide>
<add> // Emmy Noether, German mathematician. Noether's Theorem is named after her. https://en.wikipedia.org/wiki/Emmy_Noether
<add> "noether",
<add>
<ide> // Poppy Northcutt. Poppy Northcutt was the first woman to work as part of NASA’s Mission Control. http://www.businessinsider.com/poppy-northcutt-helped-apollo-astronauts-2014-12?op=1
<ide> "northcutt",
<ide> | 1 |
Python | Python | add import in regression test | bdcecb3c96cef5b663b1ada22efa952b0882f1f0 | <ide><path>spacy/tests/regression/test_issue600.py
<ide> from __future__ import unicode_literals
<ide> from ...tokens import Doc
<ide> from ...vocab import Vocab
<add>from ...attrs import POS
<ide>
<ide>
<ide> def test_issue600(): | 1 |
Ruby | Ruby | use correct value in example [ci skip] | 7c7f4f96dfc3507f83ea23a9aa98bc6b5d1e5f51 | <ide><path>actioncable/lib/action_cable/helpers/action_cable_helper.rb
<ide> module ActionCableHelper
<ide> #
<ide> # <head>
<ide> # <%= action_cable_meta_tag %>
<del> # <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<add> # <%= javascript_include_tag 'application', 'data-turbolinks-track' => 'reload' %>
<ide> # </head>
<ide> #
<ide> # This is then used by Action Cable to determine the URL of your WebSocket server. | 1 |
Javascript | Javascript | simplify trystatsync with throwifnoentry option | 88153dc1753fea91cbf42a3c2812d2c5e6145f93 | <ide><path>lib/internal/modules/esm/resolve.js
<ide> function getConditionsSet(conditions) {
<ide> const realpathCache = new SafeMap();
<ide> const packageJSONCache = new SafeMap(); /* string -> PackageConfig */
<ide>
<del>function tryStatSync(path) {
<del> try {
<del> return statSync(path);
<del> } catch {
<del> return new Stats();
<del> }
<del>}
<add>const tryStatSync =
<add> (path) => statSync(path, { throwIfNoEntry: false }) ?? new Stats();
<ide>
<ide> function getPackageConfig(path, specifier, base) {
<ide> const existing = packageJSONCache.get(path); | 1 |
Python | Python | remove unused import | f0d523f8f240f945ed3d20c2e327852c8594162f | <ide><path>libcloud/common/google.py
<ide>
<ide> Please remember to secure your keys and access tokens.
<ide> """
<del>import contextlib
<ide> import os
<ide> import sys
<ide> import time | 1 |
PHP | PHP | adjust cookie serialization | 240d904606a101f5104bff8a1d09678c44f11903 | <ide><path>src/Illuminate/Cookie/Middleware/EncryptCookies.php
<ide> class EncryptCookies
<ide> *
<ide> * @var bool
<ide> */
<del> protected $serialize = false;
<add> protected static $serialize = false;
<ide>
<ide> /**
<ide> * Create a new CookieGuard instance.
<ide> protected function decryptCookie($name, $cookie)
<ide> {
<ide> return is_array($cookie)
<ide> ? $this->decryptArray($cookie)
<del> : $this->encrypter->decrypt($cookie, $this->serialize);
<add> : $this->encrypter->decrypt($cookie, static::serialized($name));
<ide> }
<ide>
<ide> /**
<ide> protected function decryptArray(array $cookie)
<ide>
<ide> foreach ($cookie as $key => $value) {
<ide> if (is_string($value)) {
<del> $decrypted[$key] = $this->encrypter->decrypt($value, $this->serialize);
<add> $decrypted[$key] = $this->encrypter->decrypt($value, static::serialized($key));
<ide> }
<ide> }
<ide>
<ide> protected function encrypt(Response $response)
<ide> }
<ide>
<ide> $response->headers->setCookie($this->duplicate(
<del> $cookie, $this->encrypter->encrypt($cookie->getValue(), $this->serialize)
<add> $cookie, $this->encrypter->encrypt($cookie->getValue(), static::serialized($cookie->getName()))
<ide> ));
<ide> }
<ide>
<ide> public function isDisabled($name)
<ide> {
<ide> return in_array($name, $this->except);
<ide> }
<add>
<add> /**
<add> * Determine if the cookie contents should be serialized.
<add> *
<add> * @param string $name
<add> * @return bool
<add> */
<add> public static function serialized($name)
<add> {
<add> return static::$serialize;
<add> }
<ide> }
<ide><path>src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php
<ide> use Symfony\Component\HttpFoundation\Cookie;
<ide> use Illuminate\Contracts\Encryption\Encrypter;
<ide> use Illuminate\Session\TokenMismatchException;
<add>use Illuminate\Cookie\Middleware\EncryptCookies;
<ide>
<ide> class VerifyCsrfToken
<ide> {
<ide> protected function getTokenFromRequest($request)
<ide> $token = $request->input('_token') ?: $request->header('X-CSRF-TOKEN');
<ide>
<ide> if (! $token && $header = $request->header('X-XSRF-TOKEN')) {
<del> $token = $this->encrypter->decrypt($header, false);
<add> $token = $this->encrypter->decrypt($header, static::serialized());
<ide> }
<ide>
<ide> return $token;
<ide> protected function addCookieToResponse($request, $response)
<ide>
<ide> return $response;
<ide> }
<add>
<add> /**
<add> * Determine if the cookie contents should be serialized.
<add> *
<add> * @return bool
<add> */
<add> public static function serialized()
<add> {
<add> return EncryptCookies::serialized('XSRF-TOKEN');
<add> }
<ide> } | 2 |
Javascript | Javascript | fix coding style in src/core/worker.js | 67b5c8868c79455e4e27026b9522c7fcc0f60726 | <ide><path>src/core/worker.js
<ide> var WorkerMessageHandler = PDFJS.WorkerMessageHandler = {
<ide> var encryptedPromise = pdfManager.ensureXRef('encrypt');
<ide> var javaScriptPromise = pdfManager.ensureCatalog('javaScript');
<ide> Promise.all([numPagesPromise, fingerprintPromise, outlinePromise,
<del> infoPromise, metadataPromise, encryptedPromise,
<del> javaScriptPromise]).then(
<del> function onDocReady(results) {
<add> infoPromise, metadataPromise, encryptedPromise,
<add> javaScriptPromise]).then(function onDocReady(results) {
<ide>
<ide> var doc = {
<ide> numPages: results[0],
<ide> var WorkerMessageHandler = PDFJS.WorkerMessageHandler = {
<ide> pdfManager.ensureDoc('checkHeader', []).then(function() {
<ide> pdfManager.ensureDoc('parseStartXRef', []).then(function() {
<ide> pdfManager.ensureDoc('parse', [recoveryMode]).then(
<del> parseSuccess, parseFailure);
<add> parseSuccess, parseFailure);
<ide> }, parseFailure);
<ide> }, parseFailure);
<ide>
<ide> var WorkerMessageHandler = PDFJS.WorkerMessageHandler = {
<ide>
<ide> onError: function onError(status) {
<ide> if (status == 404) {
<del> var exception = new MissingPDFException( 'Missing PDF "' +
<del> source.url + '".');
<add> var exception = new MissingPDFException('Missing PDF "' +
<add> source.url + '".');
<ide> handler.send('MissingPDF', { exception: exception });
<ide> } else {
<ide> handler.send('DocError', 'Unexpected server response (' +
<del> status + ') while retrieving PDF "' +
<del> source.url + '".');
<add> status + ') while retrieving PDF "' +
<add> source.url + '".');
<ide> }
<ide> },
<ide>
<ide> var WorkerMessageHandler = PDFJS.WorkerMessageHandler = {
<ide> if (ex instanceof PasswordException) {
<ide> // after password exception prepare to receive a new password
<ide> // to repeat loading
<del> pdfManager.passwordChangedPromise =
<del> new LegacyPromise();
<add> pdfManager.passwordChangedPromise = new LegacyPromise();
<ide> pdfManager.passwordChangedPromise.then(pdfManagerReady);
<ide> }
<ide>
<ide> var WorkerMessageHandler = PDFJS.WorkerMessageHandler = {
<ide> }, function(e) {
<ide>
<ide> var minimumStackMessage =
<del> 'worker.js: while trying to getPage() and getOperatorList()';
<add> 'worker.js: while trying to getPage() and getOperatorList()';
<ide>
<ide> var wrappedException;
<ide> | 1 |
Mixed | Javascript | add response headers to xhr response | fe42a28de12926c7b3254420ccb85bef5f46327f | <ide><path>Examples/UIExplorer/XHRExample.android.js
<ide> var {
<ide> View,
<ide> } = React;
<ide>
<add>var XHRExampleHeaders = require('./XHRExampleHeaders');
<add>
<ide> // TODO t7093728 This is a simlified XHRExample.ios.js.
<ide> // Once we have Camera roll, Toast, Intent (for opening URLs)
<ide> // we should make this consistent with iOS.
<ide> class FormUploader extends React.Component {
<ide> }
<ide> }
<ide>
<del>
<ide> exports.framework = 'React';
<ide> exports.title = 'XMLHttpRequest';
<ide> exports.description = 'Example that demonstrates upload and download requests ' +
<ide> exports.examples = [{
<ide> render() {
<ide> return <FormUploader/>;
<ide> }
<add>}, {
<add> title: 'Headers',
<add> render() {
<add> return <XHRExampleHeaders/>;
<add> }
<ide> }];
<ide>
<ide> var styles = StyleSheet.create({
<ide><path>Examples/UIExplorer/XHRExample.ios.js
<ide> var {
<ide> View,
<ide> } = React;
<ide>
<add>var XHRExampleHeaders = require('./XHRExampleHeaders');
<add>
<ide> class Downloader extends React.Component {
<ide>
<ide> xhr: XMLHttpRequest;
<ide> exports.examples = [{
<ide> render() {
<ide> return <FetchTest/>;
<ide> }
<add>}, {
<add> title: 'Headers',
<add> render() {
<add> return <XHRExampleHeaders/>;
<add> }
<ide> }];
<ide>
<ide> var styles = StyleSheet.create({
<ide><path>Examples/UIExplorer/XHRExampleHeaders.js
<add>/**
<add> * The examples provided by Facebook are for non-commercial testing and
<add> * evaluation purposes only.
<add> *
<add> * Facebook reserves all rights not expressly granted.
<add> *
<add> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
<add> * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
<add> * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL
<add> * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
<add> * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
<add> * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
<add> *
<add> */
<add>'use strict';
<add>
<add>var React = require('react-native');
<add>var {
<add> StyleSheet,
<add> Text,
<add> TouchableHighlight,
<add> View,
<add>} = React;
<add>
<add>class XHRExampleHeaders extends React.Component {
<add>
<add> xhr: XMLHttpRequest;
<add> cancelled: boolean;
<add>
<add> constructor(props) {
<add> super(props);
<add> this.cancelled = false;
<add> this.state = {
<add> status: '',
<add> headers: '',
<add> contentSize: 1,
<add> downloaded: 0,
<add> };
<add> }
<add>
<add> download() {
<add> this.xhr && this.xhr.abort();
<add>
<add> var xhr = this.xhr || new XMLHttpRequest();
<add> xhr.onreadystatechange = () => {
<add> if (xhr.readyState === xhr.DONE) {
<add> if (this.cancelled) {
<add> this.cancelled = false;
<add> return;
<add> }
<add> if (xhr.status === 200) {
<add> this.setState({
<add> status: 'Download complete!',
<add> headers: xhr.getAllResponseHeaders()
<add> });
<add> } else if (xhr.status !== 0) {
<add> this.setState({
<add> status: 'Error: Server returned HTTP status of ' + xhr.status + ' ' + xhr.responseText,
<add> });
<add> } else {
<add> this.setState({
<add> status: 'Error: ' + xhr.responseText,
<add> });
<add> }
<add> }
<add> };
<add> xhr.open('GET', 'https://httpbin.org/response-headers?header1=value&header2=value1&header2=value2');
<add> xhr.send();
<add> this.xhr = xhr;
<add>
<add> this.setState({status: 'Downloading...'});
<add> }
<add>
<add> componentWillUnmount() {
<add> this.cancelled = true;
<add> this.xhr && this.xhr.abort();
<add> }
<add>
<add> render() {
<add> var button = this.state.status === 'Downloading...' ? (
<add> <View style={styles.wrapper}>
<add> <View style={styles.button}>
<add> <Text>...</Text>
<add> </View>
<add> </View>
<add> ) : (
<add> <TouchableHighlight
<add> style={styles.wrapper}
<add> onPress={this.download.bind(this)}>
<add> <View style={styles.button}>
<add> <Text>Get headers</Text>
<add> </View>
<add> </TouchableHighlight>
<add> );
<add>
<add> return (
<add> <View>
<add> {button}
<add> <Text>{this.state.headers}</Text>
<add> </View>
<add> );
<add> }
<add>}
<add>
<add>var styles = StyleSheet.create({
<add> wrapper: {
<add> borderRadius: 5,
<add> marginBottom: 5,
<add> },
<add> button: {
<add> backgroundColor: '#eeeeee',
<add> padding: 8,
<add> },
<add>});
<add>
<add>module.exports = XHRExampleHeaders;
<ide>\ No newline at end of file
<ide><path>ReactAndroid/src/main/java/com/facebook/react/modules/network/NetworkingModule.java
<ide> import java.io.IOException;
<ide> import java.io.InputStream;
<ide>
<add>import com.facebook.react.bridge.Arguments;
<ide> import com.facebook.react.bridge.Callback;
<ide> import com.facebook.react.bridge.GuardedAsyncTask;
<ide> import com.facebook.react.bridge.ReactApplicationContext;
<ide> import com.facebook.react.bridge.ReactContextBaseJavaModule;
<ide> import com.facebook.react.bridge.ReactMethod;
<ide> import com.facebook.react.bridge.ReadableArray;
<ide> import com.facebook.react.bridge.ReadableMap;
<del>import com.facebook.react.modules.network.OkHttpClientProvider;
<add>import com.facebook.react.bridge.WritableMap;
<ide>
<ide> import com.squareup.okhttp.Headers;
<ide> import com.squareup.okhttp.MediaType;
<ide> public void onResponse(Response response) throws IOException {
<ide> if (mShuttingDown) {
<ide> return;
<ide> }
<del> // TODO(5472580) handle headers properly
<ide> String responseBody;
<ide> try {
<ide> responseBody = response.body().string();
<ide> public void onResponse(Response response) throws IOException {
<ide> callback.invoke(0, null, e.getMessage());
<ide> return;
<ide> }
<del> callback.invoke(response.code(), null, responseBody);
<add>
<add> WritableMap responseHeaders = Arguments.createMap();
<add> Headers headers = response.headers();
<add> for (int i = 0; i < headers.size(); i++) {
<add> String headerName = headers.name(i);
<add> // multiple values for the same header
<add> if (responseHeaders.hasKey(headerName)) {
<add> responseHeaders.putString(
<add> headerName,
<add> responseHeaders.getString(headerName) + ", " + headers.value(i));
<add> } else {
<add> responseHeaders.putString(headerName, headers.value(i));
<add> }
<add> }
<add>
<add> callback.invoke(response.code(), responseHeaders, responseBody);
<ide> }
<ide> });
<ide> } | 4 |
Text | Text | update user stylesheet docs to use styles.css | 73c714b62dbb3a52fe0bf92191c0526e2d4cd547 | <ide><path>docs/customizing-atom.md
<ide> make customizations. You have full access to Atom's API from code in this file.
<ide> If customizations become extensive, consider [creating a
<ide> package][create-a-package].
<ide>
<del>### user.less
<add>### styles.css
<ide>
<ide> If you want to apply quick-and-dirty personal styling changes without creating
<ide> an entire theme that you intend to distribute, you can add styles to
<del>_user.less_ in your _~/.atom_ directory.
<add>_styles.css_ in your _~/.atom_ directory.
<ide>
<ide> For example, to change the color of the highlighted line number for the line
<del>that contains the cursor, you could add the following style to _user.less_:
<add>that contains the cursor, you could add the following style to _styles.css_:
<ide>
<del>```less
<del>@highlight-color: pink;
<del>
<del>.editor .line-number.cursor-line {
<del> color: @highlight-color;
<add>```css
<add>.editor .cursor {
<add> border-color: pink;
<ide> }
<ide> ```
<ide>
<add>You can also name the file _styles.less_ if you want to style Atom using
<add>[LESS][LESS].
<add>
<ide> [create-a-package]: creating-packages.md
<ide> [create-theme]: creating-a-theme.md
<add>[LESS]: http://www.lesscss.org | 1 |
Text | Text | add danielleadams to collaborators | 9c11d5ce9df480b62ca1d5a0d90dd07fa55da98a | <ide><path>README.md
<ide> For information about the governance of the Node.js project, see
<ide> **Shelley Vohr** <codebytere@gmail.com> (she/her)
<ide> * [danbev](https://github.com/danbev) -
<ide> **Daniel Bevenius** <daniel.bevenius@gmail.com> (he/him)
<add>* [danielleadams](https://github.com/danielleadams) -
<add>**Danielle Adams** <adamzdanielle@gmail.com> (she/her)
<ide> * [davisjam](https://github.com/davisjam) -
<ide> **Jamie Davis** <davisjam@vt.edu> (he/him)
<ide> * [devnexen](https://github.com/devnexen) - | 1 |
Java | Java | add perf tests for cache(1) variant | d429110e6ae2d16183ecfa8243ab4ef36fff0c08 | <ide><path>rxjava-core/src/perf/java/rx/subjects/ReplaySubjectPerf.java
<ide> import java.util.concurrent.TimeUnit;
<ide> import java.util.concurrent.atomic.AtomicLong;
<ide>
<del>import org.openjdk.jmh.annotations.BenchmarkMode;
<ide> import org.openjdk.jmh.annotations.Benchmark;
<add>import org.openjdk.jmh.annotations.BenchmarkMode;
<ide> import org.openjdk.jmh.annotations.Mode;
<ide> import org.openjdk.jmh.annotations.OutputTimeUnit;
<ide> import org.openjdk.jmh.annotations.Param;
<ide> public static class Input {
<ide> }
<ide>
<ide> @Benchmark
<del> public void subscribeBeforeEvents(final Input input, final Blackhole bh) throws Exception {
<del> ReplaySubject<Object> subject = ReplaySubject.create();
<add> public void subscribeBeforeEventsUnbounded(final Input input, final Blackhole bh) throws Exception {
<add> subscribeBeforeEvents(ReplaySubject.create(), input, bh);
<add> }
<add>
<add> @Benchmark
<add> public void subscribeBeforeEventsCount1(final Input input, final Blackhole bh) throws Exception {
<add> subscribeBeforeEvents(ReplaySubject.create(1), input, bh);
<add> }
<add>
<add> private void subscribeBeforeEvents(ReplaySubject<Object> subject, final Input input, final Blackhole bh) throws Exception {
<ide> final CountDownLatch latch = new CountDownLatch(1);
<ide> final AtomicLong sum = new AtomicLong();
<ide>
<ide> public void onNext(Object o) {
<ide> }
<ide>
<ide> @Benchmark
<del> public void subscribeAfterEvents(final Input input, final Blackhole bh) throws Exception {
<del> ReplaySubject<Object> subject = ReplaySubject.create();
<add> public void subscribeAfterEventsUnbounded(final Input input, final Blackhole bh) throws Exception {
<add> subscribeAfterEvents(ReplaySubject.create(), input, bh);
<add> }
<add>
<add> @Benchmark
<add> public void subscribeAfterEventsCount1(final Input input, final Blackhole bh) throws Exception {
<add> subscribeAfterEvents(ReplaySubject.create(1), input, bh);
<add> }
<add>
<add> private void subscribeAfterEvents(ReplaySubject<Object> subject, final Input input, final Blackhole bh) throws Exception {
<ide> final CountDownLatch latch = new CountDownLatch(1);
<ide> final AtomicLong sum = new AtomicLong();
<ide> | 1 |
PHP | PHP | add env variable for mysql ssl cert | 9180f646d3a99e22d2d2a957df6ed7b550214b2f | <ide><path>config/database.php
<ide> 'prefix_indexes' => true,
<ide> 'strict' => true,
<ide> 'engine' => null,
<add> 'options' => array_filter([
<add> PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
<add> ]),
<ide> ],
<ide>
<ide> 'pgsql' => [ | 1 |
Python | Python | fix tf bart for saved model creation | 1558d191e66fe3b5b34c8d9a6ce657a39d5133ae | <ide><path>src/transformers/modeling_tf_utils.py
<ide> def shape_list(tensor: tf.Tensor) -> List[int]:
<ide> dynamic = tf.shape(tensor)
<ide>
<ide> if tensor.shape == tf.TensorShape(None):
<del> return dynamic.as_list()
<add> return dynamic
<ide>
<ide> static = tensor.shape.as_list()
<ide>
<ide><path>src/transformers/models/bart/modeling_tf_bart.py
<ide> def call(
<ide> raise ValueError("You have to specify either input_ids or inputs_embeds")
<ide>
<ide> if inputs["inputs_embeds"] is None:
<del> inputs_embeds = self.embed_tokens(inputs["input_ids"])
<add> inputs["inputs_embeds"] = self.embed_tokens(inputs["input_ids"])
<ide> else:
<del> inputs_embeds = inputs["inputs_embeds"]
<add> inputs["inputs_embeds"] = inputs["inputs_embeds"]
<ide>
<del> inputs_embeds = inputs_embeds * self.embed_scale
<add> inputs["inputs_embeds"] = inputs["inputs_embeds"] * self.embed_scale
<ide>
<ide> embed_pos = self.embed_positions(input_shape)
<del> hidden_states = inputs_embeds + embed_pos
<add> hidden_states = inputs["inputs_embeds"] + embed_pos
<ide> hidden_states = self.layernorm_embedding(hidden_states)
<ide> hidden_states = self.dropout(hidden_states, training=inputs["training"])
<ide>
<ide> # check attention mask and invert
<ide> if inputs["attention_mask"] is not None:
<ide> # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
<del> attention_mask = _expand_mask(inputs["attention_mask"])
<del> else:
<del> attention_mask = None
<add> inputs["attention_mask"] = _expand_mask(inputs["attention_mask"])
<ide>
<ide> encoder_states = () if inputs["output_hidden_states"] else None
<ide> all_attentions = () if inputs["output_attentions"] else None
<ide> def call(
<ide> if inputs["training"] and (dropout_probability < self.layerdrop): # skip the layer
<ide> continue
<ide>
<del> hidden_states, attn = encoder_layer(hidden_states, attention_mask)
<add> hidden_states, attn = encoder_layer(hidden_states, inputs["attention_mask"])
<ide>
<ide> if inputs["output_attentions"]:
<ide> all_attentions += (attn,)
<ide> def call(
<ide> # embed positions
<ide> positions = self.embed_positions(input_shape, past_key_values_length)
<ide>
<del> if inputs_embeds is None:
<del> inputs_embeds = self.embed_tokens(inputs["input_ids"])
<del> else:
<del> inputs_embeds = inputs["inputs_embeds"]
<add> if inputs["inputs_embeds"] is None:
<add> inputs["inputs_embeds"] = self.embed_tokens(inputs["input_ids"])
<ide>
<del> hidden_states = inputs_embeds * self.embed_scale
<add> hidden_states = inputs["inputs_embeds"] * self.embed_scale
<ide>
<ide> # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
<del> combined_attention_mask = None
<ide> if input_shape[-1] > 1:
<ide> combined_attention_mask = _make_causal_mask(input_shape, past_key_values_length=past_key_values_length)
<add> else:
<add> combined_attention_mask = _expand_mask(
<add> tf.ones((input_shape[0], input_shape[1] + past_key_values_length)), tgt_len=input_shape[-1]
<add> )
<ide>
<ide> if inputs["attention_mask"] is None and inputs["input_ids"] is not None and input_shape[-1] > 1:
<del> attention_mask = tf.cast(
<add> inputs["attention_mask"] = tf.cast(
<ide> tf.math.not_equal(inputs["input_ids"], self.config.pad_token_id), inputs["input_ids"].dtype
<ide> )
<del> attention_mask = tf.concat(
<del> [tf.ones((input_shape[0], past_key_values_length), dtype=attention_mask.dtype), attention_mask],
<add> inputs["attention_mask"] = tf.concat(
<add> [
<add> tf.ones((input_shape[0], past_key_values_length), dtype=inputs["attention_mask"].dtype),
<add> inputs["attention_mask"],
<add> ],
<ide> axis=-1,
<ide> )
<ide> else:
<del> attention_mask = tf.ones((input_shape[0], input_shape[1] + past_key_values_length), dtype=tf.int32)
<add> inputs["attention_mask"] = tf.ones(
<add> (input_shape[0], input_shape[1] + past_key_values_length), dtype=tf.int32
<add> )
<ide>
<del> if attention_mask is not None and combined_attention_mask is not None:
<del> # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
<del> combined_attention_mask = combined_attention_mask + _expand_mask(attention_mask, tgt_len=input_shape[-1])
<add> # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
<add> combined_attention_mask = combined_attention_mask + _expand_mask(
<add> inputs["attention_mask"], tgt_len=input_shape[-1]
<add> )
<ide>
<del> encoder_hidden_states = inputs["encoder_hidden_states"]
<del> if encoder_hidden_states is not None and inputs["encoder_attention_mask"] is not None:
<add> if inputs["encoder_hidden_states"] is not None and inputs["encoder_attention_mask"] is not None:
<ide> # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
<del> encoder_attention_mask = _expand_mask(inputs["encoder_attention_mask"], tgt_len=input_shape[-1])
<add> inputs["encoder_attention_mask"] = _expand_mask(inputs["encoder_attention_mask"], tgt_len=input_shape[-1])
<ide>
<ide> if self.do_blenderbot_90_layernorm:
<ide> hidden_states = self.layernorm_embedding(hidden_states) + positions
<ide> def call(
<ide> hidden_states, layer_self_attn, present_key_value = decoder_layer(
<ide> hidden_states,
<ide> attention_mask=combined_attention_mask,
<del> encoder_hidden_states=encoder_hidden_states,
<del> encoder_attention_mask=encoder_attention_mask,
<add> encoder_hidden_states=inputs["encoder_hidden_states"],
<add> encoder_attention_mask=inputs["encoder_attention_mask"],
<ide> past_key_value=past_key_value,
<ide> )
<ide>
<ide> def call(
<ide>
<ide> all_self_attns = list(all_self_attns) if inputs["output_attentions"] else None
<ide>
<del> present_key_values = (encoder_hidden_states, present_key_values) if inputs["use_cache"] else None
<add> present_key_values = (inputs["encoder_hidden_states"], present_key_values) if inputs["use_cache"] else None
<ide>
<ide> if not inputs["return_dict"]:
<ide> return hidden_states, present_key_values, all_hidden_states, all_self_attns | 2 |
Python | Python | implement masked loss reduction | db9f76ac8d1945630061582b03381939349bb59a | <ide><path>keras/backend.py
<ide> def sparse_categorical_crossentropy(
<ide> output = tf.reshape(output, [-1, output_shape[-1]])
<ide>
<ide> if ignore_class is not None:
<del> valid_mask = tf.not_equal(target, ignore_class)
<add> valid_mask = tf.not_equal(target, cast(ignore_class, target.dtype))
<ide> target = target[valid_mask]
<ide> output = output[valid_mask]
<ide>
<ide> def sparse_categorical_crossentropy(
<ide> if ignore_class is not None:
<ide> res_shape = cast(output_shape[:-1], "int64")
<ide> valid_mask = tf.reshape(valid_mask, res_shape)
<del>
<ide> res = tf.scatter_nd(tf.where(valid_mask), res, res_shape)
<del>
<del> if output_rank is not None and output_rank >= 3:
<del> # The output is a 2-dimensional (or higher) label map,
<del> # and some pixels might be zero. We reduce the loss among the
<del> # valid entries to prevent an artificial decrease of the loss
<del> # value when many of them are invalid.
<del> reduce_axis = list(range(1, output_rank - 1))
<del> res = tf.math.divide_no_nan(
<del> tf.reduce_sum(res, axis=reduce_axis),
<del> tf.reduce_sum(cast(valid_mask, res.dtype), axis=reduce_axis),
<del> )
<add> res._keras_mask = valid_mask
<ide>
<ide> return res
<ide>
<ide><path>keras/backend_test.py
<ide> from keras.layers import activation
<ide> from keras.layers.normalization import batch_normalization_v1
<ide> from keras.testing_infra import test_combinations
<add>from keras.utils import losses_utils
<ide> from keras.utils import tf_inspect
<ide> from keras.utils import tf_utils
<ide>
<ide> def test_sparse_categorical_crossentropy_loss(self):
<ide> test_combinations.combine(mode=["graph", "eager"])
<ide> )
<ide> def test_sparse_categorical_crossentropy_loss_with_ignore_class(self):
<del> t = backend.constant([255, 1, 2, 2])
<add> tests = (([255, 1, 2, 2], 255), ([-1, 1, 2, 2], -1))
<ide> p = backend.softmax(
<ide> backend.constant(
<ide> [
<ide> def test_sparse_categorical_crossentropy_loss_with_ignore_class(self):
<ide> ]
<ide> )
<ide> )
<del> result = backend.sparse_categorical_crossentropy(t, p, ignore_class=255)
<del> self.assertArrayNear(
<del> self.evaluate(result),
<del> [0.0, 0.07428224, 0.13980183, 0.11967831],
<del> 1e-3,
<del> )
<ide>
<del> t = backend.constant([-1, 1, 2, 2])
<del> p = backend.constant(
<del> [
<del> [1.8, 1.2, 0.5],
<del> [0.2, 3.8, 0.8],
<del> [1.1, 0.4, 3.4],
<del> [1.3, 0.7, 3.8],
<del> ]
<del> )
<del> result = backend.sparse_categorical_crossentropy(
<del> t, p, ignore_class=-1, from_logits=True
<del> )
<del> self.assertArrayNear(
<del> self.evaluate(result),
<del> [0.0, 0.07428224, 0.13980183, 0.11967831],
<del> 1e-3,
<del> )
<add> for t, ignore_class in tests:
<add> t = backend.constant(t)
<add> result = backend.sparse_categorical_crossentropy(
<add> t, p, ignore_class=ignore_class
<add> )
<add> self.assertArrayNear(
<add> self.evaluate(result),
<add> [0.0, 0.07428224, 0.13980183, 0.11967831],
<add> 1e-3,
<add> )
<ide>
<ide> @test_combinations.generate(
<ide> test_combinations.combine(mode=["graph", "eager"])
<ide> )
<ide> def test_sparse_cce_loss_with_ignore_class_for_segmentation(self):
<ide> t = backend.constant(
<del> [
<del> [[0, 2], [-1, -1]],
<del> [[0, 2], [-1, -1]],
<del> ]
<add> [[[0, 2], [-1, -1]], [[0, 2], [-1, -1]], [[0, 0], [0, 0]]]
<ide> )
<ide> p = backend.constant(
<ide> [
<ide> def test_sparse_cce_loss_with_ignore_class_for_segmentation(self):
<ide> [[1.0, 0.0, 0.0], [0.0, 0.5, 0.5]],
<ide> [[0.2, 0.5, 0.3], [0.0, 1.0, 0.0]],
<ide> ],
<add> [
<add> [[1.0, 0.0, 0.0], [1.0, 0.0, 0.0]],
<add> [[0.1, 0.9, 0.0], [0.2, 0.8, 0.0]],
<add> ],
<add> ]
<add> )
<add>
<add> expected_result = [
<add> [[0.0, 0.0], [0.0, 0.0]],
<add> [[0.0, 0.693148], [0.0, 0.0]],
<add> [[0.0, 0.0], [2.302585, 1.609438]],
<add> ]
<add>
<add> # total_entries = 12
<add> # valid_entries = 8
<add> expected_mask = backend.constant(
<add> [
<add> [[True, True], [False, False]],
<add> [[True, True], [False, False]],
<add> [[True, True], [True, True]],
<ide> ]
<ide> )
<ide>
<ide> result = backend.sparse_categorical_crossentropy(t, p, ignore_class=-1)
<del> self.assertArrayNear(
<del> self.evaluate(result), [2.3841855e-07, 3.4657377e-01], 1e-3
<add> mask = losses_utils.get_mask(result)
<add>
<add> self.assertIsNotNone(
<add> mask,
<add> "expected sparse_categorical_crossentropy to set the "
<add> "`_keras_mask` attribute when `ignore_class is not None`, "
<add> "which indicates which loss values are valid.",
<ide> )
<ide>
<add> result = self.evaluate(result)
<add> mask = self.evaluate(mask)
<add> self.assertAllEqual(mask, expected_mask)
<add> self.assertAllClose(result, expected_result, atol=1e-6)
<add>
<ide> @test_combinations.generate(test_combinations.combine(mode=["graph"]))
<ide> def test_sparse_categorical_crossentropy_loss_with_unknown_rank_tensor(
<ide> self,
<ide><path>keras/engine/compile_utils.py
<ide> def __call__(
<ide> continue
<ide>
<ide> y_t, y_p, sw = match_dtype_and_rank(y_t, y_p, sw)
<del> sw = apply_mask(y_p, sw, get_mask(y_p))
<add> sw = losses_utils.apply_mask(y_p, sw, losses_utils.get_mask(y_p))
<ide> loss_value = loss_obj(y_t, y_p, sample_weight=sw)
<ide>
<ide> total_loss_mean_value = loss_value
<ide> def update_state(self, y_true, y_pred, sample_weight=None):
<ide> continue
<ide>
<ide> y_t, y_p, sw = match_dtype_and_rank(y_t, y_p, sw)
<del> mask = get_mask(y_p)
<del> sw = apply_mask(y_p, sw, mask)
<add> mask = losses_utils.get_mask(y_p)
<add> sw = losses_utils.apply_mask(y_p, sw, mask)
<ide>
<ide> for metric_obj in metric_objs:
<ide> if metric_obj is None:
<ide> def match_dtype_and_rank(y_t, y_p, sw):
<ide> return y_t, y_p, sw
<ide>
<ide>
<del>def get_mask(y_p):
<del> """Returns Keras mask from tensor."""
<del> return getattr(y_p, "_keras_mask", None)
<del>
<del>
<del>def apply_mask(y_p, sw, mask):
<del> """Applies any mask on predictions to sample weights."""
<del> if mask is not None:
<del> mask = tf.cast(mask, y_p.dtype)
<del> if sw is not None:
<del> mask, _, sw = losses_utils.squeeze_or_expand_dimensions(
<del> mask, sample_weight=sw
<del> )
<del> sw *= mask
<del> else:
<del> sw = mask
<del> return sw
<del>
<del>
<ide> def get_custom_object_name(obj):
<ide> """Returns the name to use for a custom loss or metric callable.
<ide>
<ide><path>keras/losses.py
<ide> def __call__(self, y_true, y_pred, sample_weight=None):
<ide> self.call, tf.__internal__.autograph.control_status_ctx()
<ide> )
<ide> losses = call_fn(y_true, y_pred)
<add> mask = losses_utils.get_mask(losses)
<add> reduction = self._get_reduction()
<add> sample_weight = losses_utils.apply_valid_mask(
<add> losses, sample_weight, mask, reduction
<add> )
<ide> return losses_utils.compute_weighted_loss(
<del> losses, sample_weight, reduction=self._get_reduction()
<add> losses, sample_weight, reduction=reduction
<ide> )
<ide>
<ide> @classmethod
<ide> class SparseCategoricalCrossentropy(LossFunctionWrapper):
<ide> def __init__(
<ide> self,
<ide> from_logits=False,
<add> ignore_class=None,
<ide> reduction=losses_utils.ReductionV2.AUTO,
<ide> name="sparse_categorical_crossentropy",
<ide> ):
<ide> def __init__(
<ide> name=name,
<ide> reduction=reduction,
<ide> from_logits=from_logits,
<add> ignore_class=ignore_class,
<ide> )
<ide>
<ide>
<ide><path>keras/losses_test.py
<ide> def test_sparse_categorical_crossentropy_loss_with_ignore_class(self):
<ide> logits = backend.variable(np.random.random((5, 1)))
<ide> softmax_output = backend.softmax(logits)
<ide>
<del> valid_entries = tf.reshape(
<del> tf.constant([0, 1, 0, 1, 1], target.dtype), (5, 1)
<del> )
<del> target.assign(
<del> target * valid_entries + (1 - valid_entries) * ignore_class
<del> )
<add> _valid = tf.constant([[0], [1], [0], [1], [1]], target.dtype)
<add> target.assign(target * _valid + (1 - _valid) * ignore_class)
<ide>
<ide> output_from_logit = losses.sparse_categorical_crossentropy(
<ide> target, logits, ignore_class=ignore_class, from_logits=True
<ide> )
<ide> output_from_softmax = losses.sparse_categorical_crossentropy(
<ide> target, softmax_output, ignore_class=ignore_class
<ide> )
<add>
<add> # expected_mask = [False, True, False, True, True]
<add> # for o in (output_from_logit, output_from_softmax):
<add> # mask = backend.eval(losses_utils.get_mask(o))
<add> # np.testing.assert_array_equal(mask, expected_mask)
<add>
<ide> np.testing.assert_allclose(
<ide> backend.eval(output_from_logit),
<ide> backend.eval(output_from_softmax),
<ide> def test_unweighted(self):
<ide> loss = cce_obj(y_true, logits)
<ide> self.assertAlmostEqual(self.evaluate(loss), 0.0573, 3)
<ide>
<add> def test_unweighted_ignore_class(self):
<add> cce_obj = losses.SparseCategoricalCrossentropy(ignore_class=-1)
<add> y_true = tf.constant([0, 1, 2, -1])
<add> y_pred = tf.constant(
<add> [
<add> [0.9, 0.05, 0.05],
<add> [0.5, 0.89, 0.6],
<add> [0.05, 0.01, 0.94],
<add> [0.85, 0.14, 0.01],
<add> ],
<add> dtype=tf.float32,
<add> )
<add> loss = cce_obj(y_true, y_pred)
<add> self.assertAlmostEqual(self.evaluate(loss), 0.3239, 3)
<add>
<add> # Test with logits.
<add> logits = tf.constant(
<add> [[8.0, 1.0, 1.0], [0.0, 9.0, 1.0], [2.0, 3.0, 5.0], [7.8, 2.0, 1.0]]
<add> )
<add> cce_obj = losses.SparseCategoricalCrossentropy(
<add> ignore_class=-1, from_logits=True
<add> )
<add> loss = cce_obj(y_true, logits)
<add> self.assertAlmostEqual(self.evaluate(loss), 0.0573, 3)
<add>
<add> def test_unweighted_ignore_class_for_segmentation(self):
<add> cce_obj = losses.SparseCategoricalCrossentropy(ignore_class=-1)
<add> y_true = tf.constant(
<add> [[[0, 2], [-1, -1]], [[0, 2], [-1, -1]], [[0, 0], [0, 0]]]
<add> )
<add> y_pred = tf.constant(
<add> [
<add> [
<add> [[1.0, 0.0, 0.0], [0.0, 0.0, 1.0]],
<add> [[0.2, 0.5, 0.3], [0.0, 1.0, 0.0]],
<add> ],
<add> [
<add> [[1.0, 0.0, 0.0], [0.0, 0.5, 0.5]],
<add> [[0.2, 0.5, 0.3], [0.0, 1.0, 0.0]],
<add> ],
<add> [
<add> [[1.0, 0.0, 0.0], [1.0, 0.0, 0.0]],
<add> [[0.1, 0.9, 0.0], [0.2, 0.8, 0.0]],
<add> ],
<add> ],
<add> dtype=tf.float32,
<add> )
<add>
<add> # Expected loss values:
<add> # [[0.0, 0.0], [0.0, 0.0]],
<add> # [[0.0, 0.693148], [0.0, 0.0]],
<add> # [[0.0, 0.0], [2.302585, 1.609438]],
<add>
<add> loss = cce_obj(y_true, y_pred)
<add> self.assertAlmostEqual(self.evaluate(loss), 0.575646375, 3)
<add>
<add> # # Test with logits.
<add> # logits = tf.constant(
<add> # [[8.0, 1.0, 1.0], [0.0, 9.0, 1.0], [2.0, 3.0, 5.0]]
<add> # )
<add> # cce_obj = losses.SparseCategoricalCrossentropy(from_logits=True)
<add> # loss = cce_obj(y_true, logits)
<add> # self.assertAlmostEqual(self.evaluate(loss), 0.0573, 3)
<add>
<ide> def test_scalar_weighted(self):
<ide> cce_obj = losses.SparseCategoricalCrossentropy()
<ide> y_true = tf.constant([[0], [1], [2]])
<ide> def test_sample_weighted(self):
<ide> loss = cce_obj(y_true, logits, sample_weight=sample_weight)
<ide> self.assertAlmostEqual(self.evaluate(loss), 0.31829, 3)
<ide>
<add> def test_sample_weighted_ignore_class(self):
<add> cce_obj = losses.SparseCategoricalCrossentropy(ignore_class=-1)
<add> y_true = tf.constant([[0], [1], [2], [-1]])
<add> y_pred = tf.constant(
<add> [
<add> [0.9, 0.05, 0.05],
<add> [0.5, 0.89, 0.6],
<add> [0.05, 0.01, 0.94],
<add> [0.85, 0.14, 0.01],
<add> ],
<add> dtype=tf.float32,
<add> )
<add> sample_weight = tf.constant([[1.2], [3.4], [5.6], [10.4]], shape=(4, 1))
<add> loss = cce_obj(y_true, y_pred, sample_weight=sample_weight)
<add> self.assertAlmostEqual(self.evaluate(loss), 1.0696, 3)
<add>
<add> # Test with logits.
<add> logits = tf.constant(
<add> [[8.0, 1.0, 1.0], [0.0, 9.0, 1.0], [2.0, 3.0, 5.0], [7.8, 2.0, 1.0]]
<add> )
<add> cce_obj = losses.SparseCategoricalCrossentropy(
<add> ignore_class=-1, from_logits=True
<add> )
<add> loss = cce_obj(y_true, logits, sample_weight=sample_weight)
<add> self.assertAlmostEqual(self.evaluate(loss), 0.31829, 3)
<add>
<ide> def test_no_reduction(self):
<ide> y_true = tf.constant([[0], [1], [2]])
<ide> logits = tf.constant(
<ide><path>keras/metrics/base_metric.py
<ide> def update_state(self, y_true, y_pred, sample_weight=None):
<ide> self._fn, tf.__internal__.autograph.control_status_ctx()
<ide> )
<ide> matches = ag_fn(y_true, y_pred, **self._fn_kwargs)
<add> mask = losses_utils.get_mask(matches)
<add> sample_weight = losses_utils.apply_valid_mask(
<add> matches, sample_weight, mask, self.reduction
<add> )
<ide> return super().update_state(matches, sample_weight=sample_weight)
<ide>
<ide> def get_config(self):
<ide> def update_state(self, y_true, y_pred, sample_weight=None):
<ide> self._fn, tf.__internal__.autograph.control_status_ctx()
<ide> )
<ide> matches = ag_fn(y_true, y_pred, **self._fn_kwargs)
<add> mask = losses_utils.get_mask(matches)
<add> sample_weight = losses_utils.apply_valid_mask(
<add> matches, sample_weight, mask, self.reduction
<add> )
<ide> return super().update_state(matches, sample_weight=sample_weight)
<ide>
<ide> def get_config(self):
<ide><path>keras/metrics/metrics.py
<ide> def update_state(self, y_true, y_pred, sample_weight=None):
<ide> if y_true.shape.ndims > 1:
<ide> y_true = tf.reshape(y_true, [-1])
<ide>
<del> if self.ignore_class is not None:
<del> valid_mask = tf.not_equal(y_true, self.ignore_class)
<del> y_true = y_true[valid_mask]
<del> y_pred = y_pred[valid_mask]
<del>
<ide> if sample_weight is not None:
<ide> sample_weight = tf.cast(sample_weight, self._dtype)
<ide> if sample_weight.shape.ndims > 1:
<ide> sample_weight = tf.reshape(sample_weight, [-1])
<ide>
<add> if self.ignore_class is not None:
<add> ignore_class = tf.cast(self.ignore_class, y_true.dtype)
<add> valid_mask = tf.not_equal(y_true, ignore_class)
<add> y_true = y_true[valid_mask]
<add> y_pred = y_pred[valid_mask]
<add> if sample_weight is not None:
<add> sample_weight = sample_weight[valid_mask]
<add>
<ide> # Accumulate the prediction to current confusion matrix.
<ide> current_cm = tf.math.confusion_matrix(
<ide> y_true,
<ide><path>keras/metrics/metrics_test.py
<ide> def test_unweighted(self):
<ide>
<ide> self.assertAllClose(self.evaluate(result), 1.176, atol=1e-3)
<ide>
<add> def test_unweighted_ignore_class(self):
<add> scce_obj = metrics.SparseCategoricalCrossentropy(ignore_class=-1)
<add> self.evaluate(tf.compat.v1.variables_initializer(scce_obj.variables))
<add>
<add> y_true = np.asarray([-1, 2])
<add> y_pred = np.asarray([[0.05, 0.95, 0], [0.1, 0.8, 0.1]])
<add> result = scce_obj(y_true, y_pred)
<add>
<add> self.assertAllClose(self.evaluate(result), 2.3026, atol=1e-3)
<add>
<ide> def test_unweighted_from_logits(self):
<ide> scce_obj = metrics.SparseCategoricalCrossentropy(from_logits=True)
<ide> self.evaluate(tf.compat.v1.variables_initializer(scce_obj.variables))
<ide> def test_weighted(self):
<ide>
<ide> self.assertAllClose(self.evaluate(result), 1.338, atol=1e-3)
<ide>
<add> def test_weighted_ignore_class(self):
<add> scce_obj = metrics.SparseCategoricalCrossentropy(ignore_class=-1)
<add> self.evaluate(tf.compat.v1.variables_initializer(scce_obj.variables))
<add>
<add> y_true = np.asarray([1, 2, -1])
<add> y_pred = np.asarray([[0.05, 0.95, 0], [0.1, 0.8, 0.1], [0.1, 0.8, 0.1]])
<add> sample_weight = tf.constant([1.5, 2.0, 1.5])
<add> result = scce_obj(y_true, y_pred, sample_weight=sample_weight)
<add>
<add> self.assertAllClose(self.evaluate(result), 1.338, atol=1e-3)
<add>
<ide> def test_weighted_from_logits(self):
<ide> scce_obj = metrics.SparseCategoricalCrossentropy(from_logits=True)
<ide> self.evaluate(tf.compat.v1.variables_initializer(scce_obj.variables))
<ide><path>keras/utils/losses_utils.py
<ide> def cast_losses_to_common_dtype(losses):
<ide> if highest_float:
<ide> losses = [tf.cast(loss, highest_float) for loss in losses]
<ide> return losses
<add>
<add>
<add>def get_mask(y_p):
<add> """Returns Keras mask from tensor."""
<add> return getattr(y_p, "_keras_mask", None)
<add>
<add>
<add>def apply_mask(y_p, sw, mask):
<add> """Applies any mask on predictions to sample weights."""
<add> if mask is not None:
<add> mask = tf.cast(mask, y_p.dtype)
<add> if sw is not None:
<add> mask, _, sw = squeeze_or_expand_dimensions(mask, sample_weight=sw)
<add> sw *= mask
<add> else:
<add> sw = mask
<add> return sw
<add>
<add>
<add>def apply_valid_mask(losses, sw, mask, reduction):
<add> """Redistribute pair-wise weights considering only valid entries."""
<add> if mask is not None:
<add> mask = tf.cast(mask, losses.dtype)
<add>
<add> if reduction in (ReductionV2.AUTO, ReductionV2.SUM_OVER_BATCH_SIZE):
<add> # Valid entries have weight `# total / # valid`,
<add> # while invalid ones assume weight 0. When summed
<add> # over batch size, they will be reduced to:
<add> #
<add> # mean(loss * sample_weight * total / valid)
<add> # = sum(loss * sample_weight * total / valid) / total
<add> # = sum(loss * sample_weight) / total * total / valid
<add> # = sum(loss * sample_weight) / valid
<add>
<add> total = tf.cast(tf.size(mask), losses.dtype)
<add> valid = tf.reduce_sum(mask)
<add> mask *= total / valid
<add> elif reduction in (ReductionV2.NONE, ReductionV2.SUM):
<add> # Nothing to do. Nothing is being averaged.
<add> ...
<add> elif reduction == "weighted_mean":
<add> # Nothing to do. A binary mask is enough because
<add> # it will also be used in the mean operation's
<add> # denominator as `tf.reduce_sum(sample_weight)`.
<add> ...
<add>
<add> return apply_mask(losses, sw, mask) | 9 |
Java | Java | add writeandflushwith to reactivehttpoutputmessage | 7b2196b408eeb55668a1add6455a4fd52adfdf38 | <ide><path>spring-core/src/main/java/org/springframework/core/io/buffer/FlushingDataBuffer.java
<del>/*
<del> * Copyright 2002-2016 the original author or authors.
<del> *
<del> * Licensed under the Apache License, Version 2.0 (the "License");
<del> * you may not use this file except in compliance with the License.
<del> * You may obtain a copy of the License at
<del> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS,
<del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del> * See the License for the specific language governing permissions and
<del> * limitations under the License.
<del> */
<del>
<del>package org.springframework.core.io.buffer;
<del>
<del>import java.io.InputStream;
<del>import java.io.OutputStream;
<del>import java.nio.ByteBuffer;
<del>import java.util.function.IntPredicate;
<del>
<del>/**
<del> * Empty {@link DataBuffer} that indicates to the file or the socket writing it
<del> * that previously buffered data should be flushed.
<del> *
<del> * @author Sebastien Deleuze
<del> * @since 5.0
<del> * @see FlushingDataBuffer#INSTANCE
<del> */
<del>public class FlushingDataBuffer implements DataBuffer {
<del>
<del> /** Singleton instance of this class */
<del> public static final FlushingDataBuffer INSTANCE = new FlushingDataBuffer();
<del>
<del> private final DataBuffer buffer;
<del>
<del>
<del> private FlushingDataBuffer() {
<del> this.buffer = new DefaultDataBufferFactory().allocateBuffer(0);
<del> }
<del>
<del>
<del> @Override
<del> public DataBufferFactory factory() {
<del> return this.buffer.factory();
<del> }
<del>
<del> @Override
<del> public int indexOf(IntPredicate predicate, int fromIndex) {
<del> return this.buffer.indexOf(predicate, fromIndex);
<del> }
<del>
<del> @Override
<del> public int lastIndexOf(IntPredicate predicate, int fromIndex) {
<del> return this.buffer.lastIndexOf(predicate, fromIndex);
<del> }
<del>
<del> @Override
<del> public int readableByteCount() {
<del> return this.buffer.readableByteCount();
<del> }
<del>
<del> @Override
<del> public byte read() {
<del> return this.buffer.read();
<del> }
<del>
<del> @Override
<del> public DataBuffer read(byte[] destination) {
<del> return this.buffer.read(destination);
<del> }
<del>
<del> @Override
<del> public DataBuffer read(byte[] destination, int offset, int length) {
<del> return this.buffer.read(destination, offset, length);
<del> }
<del>
<del> @Override
<del> public DataBuffer write(byte b) {
<del> return this.buffer.write(b);
<del> }
<del>
<del> @Override
<del> public DataBuffer write(byte[] source) {
<del> return this.buffer.write(source);
<del> }
<del>
<del> @Override
<del> public DataBuffer write(byte[] source, int offset, int length) {
<del> return this.buffer.write(source, offset, length);
<del> }
<del>
<del> @Override
<del> public DataBuffer write(DataBuffer... buffers) {
<del> return this.buffer.write(buffers);
<del> }
<del>
<del> @Override
<del> public DataBuffer write(ByteBuffer... buffers) {
<del> return this.buffer.write(buffers);
<del> }
<del>
<del> @Override
<del> public DataBuffer slice(int index, int length) {
<del> return this.buffer.slice(index, length);
<del> }
<del>
<del> @Override
<del> public ByteBuffer asByteBuffer() {
<del> return this.buffer.asByteBuffer();
<del> }
<del>
<del> @Override
<del> public InputStream asInputStream() {
<del> return this.buffer.asInputStream();
<del> }
<del>
<del> @Override
<del> public OutputStream asOutputStream() {
<del> return this.buffer.asOutputStream();
<del> }
<del>
<del>}
<ide><path>spring-core/src/main/java/org/springframework/core/io/buffer/NettyDataBufferFactory.java
<ide> public NettyDataBuffer wrap(ByteBuf byteBuf) {
<ide> return new NettyDataBuffer(byteBuf, this);
<ide> }
<ide>
<add> /**
<add> * Returns the given Netty {@link DataBuffer} as a {@link ByteBuf}. Returns the
<add> * {@linkplain NettyDataBuffer#getNativeBuffer() native buffer} if {@code buffer} is
<add> * a {@link NettyDataBuffer}; returns {@link Unpooled#wrappedBuffer(ByteBuffer)}
<add> * otherwise.
<add> * @param buffer the {@code DataBuffer} to return a {@code ByteBuf} for.
<add> * @return the netty {@code ByteBuf}
<add> */
<add> public static ByteBuf toByteBuf(DataBuffer buffer) {
<add> if (buffer instanceof NettyDataBuffer) {
<add> return ((NettyDataBuffer) buffer).getNativeBuffer();
<add> }
<add> else {
<add> return Unpooled.wrappedBuffer(buffer.asByteBuffer());
<add> }
<add> }
<add>
<add>
<ide> @Override
<ide> public String toString() {
<ide> return "NettyDataBufferFactory (" + this.byteBufAllocator + ")";
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/config/WebReactiveConfiguration.java
<ide> import org.springframework.format.support.DefaultFormattingConversionService;
<ide> import org.springframework.format.support.FormattingConversionService;
<ide> import org.springframework.http.MediaType;
<del>import org.springframework.http.codec.SseEventEncoder;
<ide> import org.springframework.http.codec.json.JacksonJsonDecoder;
<ide> import org.springframework.http.codec.json.JacksonJsonEncoder;
<ide> import org.springframework.http.codec.xml.Jaxb2Decoder;
<ide> import org.springframework.http.converter.reactive.HttpMessageReader;
<ide> import org.springframework.http.converter.reactive.HttpMessageWriter;
<ide> import org.springframework.http.converter.reactive.ResourceHttpMessageWriter;
<add>import org.springframework.http.converter.reactive.SseEventHttpMessageWriter;
<ide> import org.springframework.util.ClassUtils;
<ide> import org.springframework.validation.Errors;
<ide> import org.springframework.validation.Validator;
<ide> protected final void addDefaultHttpMessageWriters(List<HttpMessageWriter<?>> wri
<ide> writers.add(new EncoderHttpMessageWriter<>(jacksonEncoder));
<ide> sseDataEncoders.add(jacksonEncoder);
<ide> }
<del> writers.add(new EncoderHttpMessageWriter<>(new SseEventEncoder(sseDataEncoders)));
<add> writers.add(new SseEventHttpMessageWriter(sseDataEncoders));
<ide> }
<ide> /**
<ide> * Override this to modify the list of message writers after it has been
<ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/result/method/annotation/SseIntegrationTests.java
<ide> package org.springframework.web.reactive.result.method.annotation;
<ide>
<ide> import java.time.Duration;
<del>import java.util.ArrayList;
<del>import java.util.List;
<ide>
<ide> import org.junit.Before;
<ide> import org.junit.Test;
<ide> import org.springframework.context.annotation.AnnotationConfigApplicationContext;
<ide> import org.springframework.context.annotation.Bean;
<ide> import org.springframework.context.annotation.Configuration;
<del>import org.springframework.core.codec.StringDecoder;
<ide> import org.springframework.http.MediaType;
<ide> import org.springframework.http.client.reactive.ReactorClientHttpConnector;
<ide> import org.springframework.http.codec.SseEvent;
<del>import org.springframework.http.codec.json.JacksonJsonDecoder;
<del>import org.springframework.http.converter.reactive.DecoderHttpMessageReader;
<del>import org.springframework.http.converter.reactive.HttpMessageReader;
<ide> import org.springframework.http.server.reactive.AbstractHttpHandlerIntegrationTests;
<ide> import org.springframework.http.server.reactive.HttpHandler;
<ide> import org.springframework.http.server.reactive.bootstrap.JettyHttpServer;
<ide><path>spring-web/src/main/java/org/springframework/http/ReactiveHttpOutputMessage.java
<ide>
<ide> import org.springframework.core.io.buffer.DataBuffer;
<ide> import org.springframework.core.io.buffer.DataBufferFactory;
<del>import org.springframework.core.io.buffer.FlushingDataBuffer;
<ide>
<ide> /**
<ide> * A "reactive" HTTP output message that accepts output as a {@link Publisher}.
<ide> public interface ReactiveHttpOutputMessage extends HttpMessage {
<ide>
<ide> /**
<ide> * Use the given {@link Publisher} to write the body of the message to the underlying
<del> * HTTP layer, and flush the data when the complete signal is received (data could be
<del> * flushed before depending on the configuration, the HTTP engine and the amount of
<del> * data sent).
<del> *
<del> * <p>Each {@link FlushingDataBuffer} element will trigger a flush.
<add> * HTTP layer.
<ide> *
<ide> * @param body the body content publisher
<ide> * @return a publisher that indicates completion or error.
<ide> */
<ide> Mono<Void> writeWith(Publisher<DataBuffer> body);
<ide>
<add> /**
<add> * Use the given {@link Publisher} of {@code Publishers} to write the body of the
<add> * message to the underlying HTTP layer, flushing after each
<add> * {@code Publisher<DataBuffer>}.
<add> *
<add> * @param body the body content publisher
<add> * @return a publisher that indicates completion or error.
<add> */
<add> Mono<Void> writeAndFlushWith(Publisher<Publisher<DataBuffer>> body);
<add>
<ide> /**
<ide> * Returns a {@link DataBufferFactory} that can be used for creating the body.
<ide> * @return a buffer factory
<ide><path>spring-web/src/main/java/org/springframework/http/client/reactive/ReactorClientHttpRequest.java
<ide> package org.springframework.http.client.reactive;
<ide>
<ide> import java.net.URI;
<add>import java.util.Collection;
<ide>
<ide> import io.netty.buffer.ByteBuf;
<del>import io.netty.buffer.Unpooled;
<ide> import io.netty.handler.codec.http.cookie.DefaultCookie;
<ide> import org.reactivestreams.Publisher;
<ide> import reactor.core.publisher.Flux;
<ide>
<ide> import org.springframework.core.io.buffer.DataBuffer;
<ide> import org.springframework.core.io.buffer.DataBufferFactory;
<del>import org.springframework.core.io.buffer.NettyDataBuffer;
<ide> import org.springframework.core.io.buffer.NettyDataBufferFactory;
<ide> import org.springframework.http.HttpMethod;
<ide>
<ide> public class ReactorClientHttpRequest extends AbstractClientHttpRequest {
<ide> private final NettyDataBufferFactory bufferFactory;
<ide>
<ide>
<del> public ReactorClientHttpRequest(HttpMethod httpMethod, URI uri, HttpClientRequest httpRequest) {
<add> public ReactorClientHttpRequest(HttpMethod httpMethod, URI uri,
<add> HttpClientRequest httpRequest) {
<ide> this.httpMethod = httpMethod;
<ide> this.uri = uri;
<ide> this.httpRequest = httpRequest;
<ide> public URI getURI() {
<ide>
<ide> @Override
<ide> public Mono<Void> writeWith(Publisher<DataBuffer> body) {
<del> return applyBeforeCommit()
<del> .then(httpRequest.send(Flux.from(body).map(this::toByteBuf)));
<add> return applyBeforeCommit().then(this.httpRequest
<add> .send(Flux.from(body).map(NettyDataBufferFactory::toByteBuf)));
<ide> }
<ide>
<ide> @Override
<del> public Mono<Void> setComplete() {
<del> return applyBeforeCommit().then(httpRequest.sendHeaders());
<add> public Mono<Void> writeAndFlushWith(Publisher<Publisher<DataBuffer>> body) {
<add> Publisher<Publisher<ByteBuf>> byteBufs = Flux.from(body).
<add> map(ReactorClientHttpRequest::toByteBufs);
<add> return applyBeforeCommit().then(this.httpRequest
<add> .sendAndFlush(byteBufs));
<add> }
<add>
<add> private static Publisher<ByteBuf> toByteBufs(Publisher<DataBuffer> dataBuffers) {
<add> return Flux.from(dataBuffers).
<add> map(NettyDataBufferFactory::toByteBuf);
<ide> }
<ide>
<del> private ByteBuf toByteBuf(DataBuffer buffer) {
<del> if (buffer instanceof NettyDataBuffer) {
<del> return ((NettyDataBuffer) buffer).getNativeBuffer();
<del> }
<del> else {
<del> return Unpooled.wrappedBuffer(buffer.asByteBuffer());
<del> }
<add> @Override
<add> public Mono<Void> setComplete() {
<add> return applyBeforeCommit().then(httpRequest.sendHeaders());
<ide> }
<ide>
<ide> @Override
<ide> protected void writeHeaders() {
<del> getHeaders().entrySet().stream()
<add> getHeaders().entrySet()
<ide> .forEach(e -> this.httpRequest.headers().set(e.getKey(), e.getValue()));
<ide> }
<ide>
<ide> @Override
<ide> protected void writeCookies() {
<del> getCookies().values()
<del> .stream().flatMap(cookies -> cookies.stream())
<add> getCookies().values().stream().flatMap(Collection::stream)
<ide> .map(cookie -> new DefaultCookie(cookie.getName(), cookie.getValue()))
<del> .forEach(cookie -> this.httpRequest.addCookie(cookie));
<add> .forEach(this.httpRequest::addCookie);
<ide> }
<ide>
<ide> }
<ide>\ No newline at end of file
<ide><path>spring-web/src/main/java/org/springframework/http/codec/SseEvent.java
<ide> package org.springframework.http.codec;
<ide>
<ide> import org.springframework.http.MediaType;
<del>import org.springframework.http.codec.SseEventEncoder;
<add>import org.springframework.http.converter.reactive.SseEventHttpMessageWriter;
<ide>
<ide> /**
<ide> * Representation for a Server-Sent Event for use with Spring's reactive Web
<ide> *
<ide> * @author Sebastien Deleuze
<ide> * @since 5.0
<del> * @see SseEventEncoder
<add> * @see SseEventHttpMessageWriter
<ide> * @see <a href="https://www.w3.org/TR/eventsource/">Server-Sent Events W3C recommendation</a>
<ide> */
<ide> public class SseEvent {
<ide> public String getName() {
<ide>
<ide> /**
<ide> * Set {@code data} SSE field. If a multiline {@code String} is provided, it will be
<del> * turned into multiple {@code data} field lines by as
<del> * defined in Server-Sent Events W3C recommendation.
<add> * turned into multiple {@code data} field lines as defined in Server-Sent Events
<add> * W3C recommendation.
<ide> *
<del> * If no {@code mediaType} is defined, default {@link SseEventEncoder} will:
<add> * If no {@code mediaType} is defined, default {@link SseEventHttpMessageWriter} will:
<ide> * - Turn single line {@code String} to a single {@code data} field
<ide> * - Turn multiline line {@code String} to multiple {@code data} fields
<ide> * - Serialize other {@code Object} as JSON
<ide> public Object getData() {
<ide>
<ide> /**
<ide> * Set the {@link MediaType} used to serialize the {@code data}.
<del> * {@link SseEventEncoder} should be configured with the relevant encoder to be
<add> * {@link SseEventHttpMessageWriter} should be configured with the relevant encoder to be
<ide> * able to serialize it.
<ide> */
<ide> public void setMediaType(MediaType mediaType) {
<ide> public Long getReconnectTime() {
<ide>
<ide> /**
<ide> * Set SSE comment. If a multiline comment is provided, it will be turned into multiple
<del> * SSE comment lines by {@link SseEventEncoder} as defined in Server-Sent Events W3C
<add> * SSE comment lines by {@link SseEventHttpMessageWriter} as defined in Server-Sent Events W3C
<ide> * recommendation.
<ide> */
<ide> public void setComment(String comment) {
<add><path>spring-web/src/main/java/org/springframework/http/converter/reactive/SseEventHttpMessageWriter.java
<del><path>spring-web/src/main/java/org/springframework/http/codec/SseEventEncoder.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.http.codec;
<add>package org.springframework.http.converter.reactive;
<ide>
<ide> import java.nio.charset.StandardCharsets;
<add>import java.util.Collections;
<ide> import java.util.List;
<ide> import java.util.Optional;
<ide>
<ide> import reactor.core.publisher.Mono;
<ide>
<ide> import org.springframework.core.ResolvableType;
<del>import org.springframework.core.codec.AbstractEncoder;
<ide> import org.springframework.core.codec.CodecException;
<ide> import org.springframework.core.codec.Encoder;
<ide> import org.springframework.core.io.buffer.DataBuffer;
<ide> import org.springframework.core.io.buffer.DataBufferFactory;
<del>import org.springframework.core.io.buffer.FlushingDataBuffer;
<ide> import org.springframework.http.MediaType;
<add>import org.springframework.http.ReactiveHttpOutputMessage;
<add>import org.springframework.http.codec.SseEvent;
<ide> import org.springframework.util.Assert;
<del>import org.springframework.util.MimeType;
<ide>
<ide> /**
<ide> * Encoder that supports a stream of {@link SseEvent}s and also plain
<ide> *
<ide> * @author Sebastien Deleuze
<ide> * @since 5.0
<add> * @author Arjen Poutsma
<ide> */
<del>public class SseEventEncoder extends AbstractEncoder<Object> {
<add>public class SseEventHttpMessageWriter implements HttpMessageWriter<Object> {
<ide>
<del> private final List<Encoder<?>> dataEncoders;
<add> private static final MediaType TEXT_EVENT_STREAM =
<add> new MediaType("text", "event-stream");
<ide>
<add> private final List<Encoder<?>> dataEncoders;
<ide>
<del> public SseEventEncoder(List<Encoder<?>> dataEncoders) {
<del> super(new MimeType("text", "event-stream"));
<add> public SseEventHttpMessageWriter(List<Encoder<?>> dataEncoders) {
<ide> Assert.notNull(dataEncoders, "'dataEncoders' must not be null");
<ide> this.dataEncoders = dataEncoders;
<ide> }
<ide>
<ide> @Override
<del> public Flux<DataBuffer> encode(Publisher<?> inputStream, DataBufferFactory bufferFactory,
<del> ResolvableType type, MimeType sseMimeType, Object... hints) {
<add> public boolean canWrite(ResolvableType type, MediaType mediaType) {
<add> return mediaType == null || TEXT_EVENT_STREAM.isCompatibleWith(mediaType);
<add> }
<add>
<add> @Override
<add> public List<MediaType> getWritableMediaTypes() {
<add> return Collections.singletonList(TEXT_EVENT_STREAM);
<add> }
<add>
<add> @Override
<add> public Mono<Void> write(Publisher<?> inputStream, ResolvableType type,
<add> MediaType contentType, ReactiveHttpOutputMessage outputMessage) {
<add>
<add> outputMessage.getHeaders().setContentType(TEXT_EVENT_STREAM);
<add>
<add> DataBufferFactory bufferFactory = outputMessage.bufferFactory();
<add> Flux<Publisher<DataBuffer>> body = encode(inputStream, bufferFactory, type);
<add>
<add> // Keep the SSE connection open even for cold stream in order to avoid
<add> // unexpected browser reconnection
<add> body = body.concatWith(Flux.never());
<add>
<add> return outputMessage.writeAndFlushWith(body);
<add> }
<add>
<add> private Flux<Publisher<DataBuffer>> encode(Publisher<?> inputStream,
<add> DataBufferFactory bufferFactory, ResolvableType type) {
<ide>
<del> return Flux.from(inputStream).flatMap(input -> {
<del> SseEvent event = (SseEvent.class.equals(type.getRawClass()) ?
<del> (SseEvent)input : new SseEvent(input));
<add> return Flux.from(inputStream).map(input -> {
<add> SseEvent event =
<add> (SseEvent.class.equals(type.getRawClass()) ? (SseEvent) input :
<add> new SseEvent(input));
<ide>
<ide> StringBuilder sb = new StringBuilder();
<ide>
<ide> public Flux<DataBuffer> encode(Publisher<?> inputStream, DataBufferFactory buffe
<ide>
<ide> Object data = event.getData();
<ide> Flux<DataBuffer> dataBuffer = Flux.empty();
<del> MediaType mediaType = (event.getMediaType() == null ? MediaType.ALL : event.getMediaType());
<add> MediaType mediaType =
<add> (event.getMediaType() == null ? MediaType.ALL : event.getMediaType());
<ide> if (data != null) {
<ide> sb.append("data:");
<ide> if (data instanceof String) {
<del> sb.append(((String)data).replaceAll("\\n", "\ndata:")).append("\n");
<add> sb.append(((String) data).replaceAll("\\n", "\ndata:")).append("\n");
<ide> }
<ide> else {
<ide> dataBuffer = applyEncoder(data, mediaType, bufferFactory);
<ide> }
<ide> }
<ide>
<del> // Keep the SSE connection open even for cold stream in order to avoid
<del> // unexpected browser reconnection
<del> return Flux.concat(
<del> encodeString(sb.toString(), bufferFactory),
<del> dataBuffer,
<del> encodeString("\n", bufferFactory),
<del> Mono.just(FlushingDataBuffer.INSTANCE),
<del> Flux.never()
<del> );
<add> return Flux.concat(encodeString(sb.toString(), bufferFactory), dataBuffer,
<add> encodeString("\n", bufferFactory));
<ide> });
<ide>
<ide> }
<ide> private <T> Flux<DataBuffer> applyEncoder(Object data, MediaType mediaType, Data
<ide> .stream()
<ide> .filter(e -> e.canEncode(elementType, mediaType))
<ide> .findFirst();
<del> if (!encoder.isPresent()) {
<del> return Flux.error(new CodecException("No suitable encoder found!"));
<del> }
<del> return ((Encoder<T>) encoder.get())
<add> return ((Encoder<T>) encoder.orElseThrow(() -> new CodecException("No suitable encoder found!")))
<ide> .encode(Mono.just((T) data), bufferFactory, elementType, mediaType)
<ide> .concatWith(encodeString("\n", bufferFactory));
<ide> }
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/AbstractListenerServerHttpResponse.java
<add>/*
<add> * Copyright 2002-2016 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.http.server.reactive;
<add>
<add>import java.util.concurrent.atomic.AtomicBoolean;
<add>
<add>import org.reactivestreams.Processor;
<add>import org.reactivestreams.Publisher;
<add>import reactor.core.publisher.Mono;
<add>
<add>import org.springframework.core.io.buffer.DataBuffer;
<add>import org.springframework.core.io.buffer.DataBufferFactory;
<add>
<add>/**
<add> * Abstract base class for listener-based server responses, i.e. Servlet 3.1 and Undertow.
<add> * @author Arjen Poutsma
<add> * @since 5.0
<add> */
<add>public abstract class AbstractListenerServerHttpResponse extends AbstractServerHttpResponse {
<add>
<add> private final AtomicBoolean writeCalled = new AtomicBoolean();
<add>
<add> public AbstractListenerServerHttpResponse(DataBufferFactory dataBufferFactory) {
<add> super(dataBufferFactory);
<add> }
<add>
<add> @Override
<add> protected final Mono<Void> writeWithInternal(Publisher<DataBuffer> body) {
<add> if (this.writeCalled.compareAndSet(false, true)) {
<add> Processor<DataBuffer, Void> bodyProcessor = createBodyProcessor();
<add> return Mono.from(subscriber -> {
<add> body.subscribe(bodyProcessor);
<add> bodyProcessor.subscribe(subscriber);
<add> });
<add>
<add> } else {
<add> return Mono.error(new IllegalStateException(
<add> "writeWith() or writeAndFlushWith() has already been called"));
<add> }
<add> }
<add>
<add> @Override
<add> protected final Mono<Void> writeAndFlushWithInternal(Publisher<Publisher<DataBuffer>> body) {
<add> if (this.writeCalled.compareAndSet(false, true)) {
<add> Processor<Publisher<DataBuffer>, Void> bodyProcessor =
<add> createBodyFlushProcessor();
<add> return Mono.from(subscriber -> {
<add> body.subscribe(bodyProcessor);
<add> bodyProcessor.subscribe(subscriber);
<add> });
<add> } else {
<add> return Mono.error(new IllegalStateException(
<add> "writeWith() or writeAndFlushWith() has already been called"));
<add> }
<add> }
<add>
<add> /**
<add> * Abstract template method to create a {@code Processor<DataBuffer, Void>} that
<add> * will write the response body to the underlying output. Called from
<add> * {@link #writeWithInternal(Publisher)}.
<add> */
<add> protected abstract Processor<DataBuffer, Void> createBodyProcessor();
<add>
<add> /**
<add> * Abstract template method to create a {@code Processor<Publisher<DataBuffer>, Void>}
<add> * that will write the response body with flushes to the underlying output. Called from
<add> * {@link #writeAndFlushWithInternal(Publisher)}.
<add> */
<add> protected abstract Processor<Publisher<DataBuffer>, Void> createBodyFlushProcessor();
<add>}
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/AbstractResponseBodyFlushProcessor.java
<add>/*
<add> * Copyright 2002-2016 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.http.server.reactive;
<add>
<add>import java.io.IOException;
<add>import java.util.Objects;
<add>import java.util.concurrent.atomic.AtomicReference;
<add>
<add>import org.apache.commons.logging.Log;
<add>import org.apache.commons.logging.LogFactory;
<add>import org.reactivestreams.Processor;
<add>import org.reactivestreams.Publisher;
<add>import org.reactivestreams.Subscriber;
<add>import org.reactivestreams.Subscription;
<add>
<add>import org.springframework.core.io.buffer.DataBuffer;
<add>
<add>/**
<add> * Abstract base class for {@code Processor} implementations that bridge between
<add> * event-listener APIs and Reactive Streams. Specifically, base class for the
<add> * Servlet 3.1 and Undertow support.
<add> *
<add> * @author Arjen Poutsma
<add> * @since 5.0
<add> * @see ServletServerHttpRequest
<add> * @see UndertowHttpHandlerAdapter
<add> * @see ServerHttpResponse#writeAndFlushWith(Publisher)
<add> */
<add>abstract class AbstractResponseBodyFlushProcessor
<add> implements Processor<Publisher<DataBuffer>, Void> {
<add>
<add> protected final Log logger = LogFactory.getLog(getClass());
<add>
<add> private final ResponseBodyWriteResultPublisher publisherDelegate =
<add> new ResponseBodyWriteResultPublisher();
<add>
<add> private final AtomicReference<State> state =
<add> new AtomicReference<>(State.UNSUBSCRIBED);
<add>
<add> private volatile boolean subscriberCompleted;
<add>
<add> private Subscription subscription;
<add>
<add> // Subscriber
<add>
<add> @Override
<add> public final void onSubscribe(Subscription subscription) {
<add> if (logger.isTraceEnabled()) {
<add> logger.trace(this.state + " onSubscribe: " + subscription);
<add> }
<add> this.state.get().onSubscribe(this, subscription);
<add> }
<add>
<add> @Override
<add> public final void onNext(Publisher<DataBuffer> publisher) {
<add> if (logger.isTraceEnabled()) {
<add> logger.trace(this.state + " onNext: " + publisher);
<add> }
<add> this.state.get().onNext(this, publisher);
<add> }
<add>
<add> @Override
<add> public final void onError(Throwable t) {
<add> if (logger.isErrorEnabled()) {
<add> logger.error(this.state + " onError: " + t, t);
<add> }
<add> this.state.get().onError(this, t);
<add> }
<add>
<add> @Override
<add> public final void onComplete() {
<add> if (logger.isTraceEnabled()) {
<add> logger.trace(this.state + " onComplete");
<add> }
<add> this.state.get().onComplete(this);
<add> }
<add>
<add> // Publisher
<add>
<add> @Override
<add> public final void subscribe(Subscriber<? super Void> subscriber) {
<add> this.publisherDelegate.subscribe(subscriber);
<add> }
<add>
<add> /**
<add> * Creates a new processor for subscribing to a body chunk.
<add> */
<add> protected abstract Processor<DataBuffer, Void> createBodyProcessor();
<add>
<add> /**
<add> * Flushes the output.
<add> */
<add> protected abstract void flush() throws IOException;
<add>
<add> private void writeComplete() {
<add> if (logger.isTraceEnabled()) {
<add> logger.trace(this.state + " writeComplete");
<add> }
<add> this.state.get().writeComplete(this);
<add>
<add> }
<add>
<add> private boolean changeState(State oldState, State newState) {
<add> return this.state.compareAndSet(oldState, newState);
<add> }
<add>
<add> private enum State {
<add> UNSUBSCRIBED {
<add> @Override
<add> public void onSubscribe(AbstractResponseBodyFlushProcessor processor,
<add> Subscription subscription) {
<add> Objects.requireNonNull(subscription, "Subscription cannot be null");
<add> if (processor.changeState(this, SUBSCRIBED)) {
<add> processor.subscription = subscription;
<add> subscription.request(1);
<add> }
<add> else {
<add> super.onSubscribe(processor, subscription);
<add> }
<add> }
<add> }, SUBSCRIBED {
<add> @Override
<add> public void onNext(AbstractResponseBodyFlushProcessor processor,
<add> Publisher<DataBuffer> chunk) {
<add> Processor<DataBuffer, Void> chunkProcessor =
<add> processor.createBodyProcessor();
<add> chunk.subscribe(chunkProcessor);
<add> chunkProcessor.subscribe(new WriteSubscriber(processor));
<add> }
<add>
<add> @Override
<add> void onComplete(AbstractResponseBodyFlushProcessor processor) {
<add> processor.subscriberCompleted = true;
<add> }
<add>
<add> @Override
<add> public void writeComplete(AbstractResponseBodyFlushProcessor processor) {
<add> if (processor.subscriberCompleted) {
<add> if (processor.changeState(this, COMPLETED)) {
<add> processor.subscriberCompleted = true;
<add> processor.publisherDelegate.publishComplete();
<add> }
<add> }
<add> else {
<add> try {
<add> processor.flush();
<add> }
<add> catch (IOException ex) {
<add> processor.onError(ex);
<add> }
<add> processor.subscription.request(1);
<add> }
<add> }
<add> }, COMPLETED {
<add> @Override
<add> public void onNext(AbstractResponseBodyFlushProcessor processor,
<add> Publisher<DataBuffer> publisher) {
<add> // ignore
<add>
<add> }
<add>
<add> @Override
<add> void onError(AbstractResponseBodyFlushProcessor processor, Throwable t) {
<add> // ignore
<add> }
<add>
<add> @Override
<add> void onComplete(AbstractResponseBodyFlushProcessor processor) {
<add> // ignore
<add> }
<add>
<add> @Override
<add> public void writeComplete(AbstractResponseBodyFlushProcessor processor) {
<add> // ignore
<add> }
<add> };
<add>
<add> public void onSubscribe(AbstractResponseBodyFlushProcessor processor,
<add> Subscription subscription) {
<add> subscription.cancel();
<add> }
<add>
<add> public void onNext(AbstractResponseBodyFlushProcessor processor,
<add> Publisher<DataBuffer> publisher) {
<add> throw new IllegalStateException(toString());
<add> }
<add>
<add> void onError(AbstractResponseBodyFlushProcessor processor, Throwable t) {
<add> if (processor.changeState(this, COMPLETED)) {
<add> processor.publisherDelegate.publishError(t);
<add> }
<add> }
<add>
<add> void onComplete(AbstractResponseBodyFlushProcessor processor) {
<add> throw new IllegalStateException(toString());
<add> }
<add>
<add> public void writeComplete(AbstractResponseBodyFlushProcessor processor) {
<add> throw new IllegalStateException(toString());
<add> }
<add>
<add> private static class WriteSubscriber implements Subscriber<Void> {
<add>
<add> private final AbstractResponseBodyFlushProcessor processor;
<add>
<add> public WriteSubscriber(AbstractResponseBodyFlushProcessor processor) {
<add> this.processor = processor;
<add> }
<add>
<add> @Override
<add> public void onSubscribe(Subscription s) {
<add> s.request(Long.MAX_VALUE);
<add> }
<add>
<add> @Override
<add> public void onNext(Void aVoid) {
<add> }
<add>
<add> @Override
<add> public void onError(Throwable t) {
<add> processor.onError(t);
<add> }
<add>
<add> @Override
<add> public void onComplete() {
<add> processor.writeComplete();
<add> }
<add> }
<add> }
<add>
<add>}
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/AbstractResponseBodyProcessor.java
<ide> import org.apache.commons.logging.Log;
<ide> import org.apache.commons.logging.LogFactory;
<ide> import org.reactivestreams.Processor;
<add>import org.reactivestreams.Publisher;
<ide> import org.reactivestreams.Subscriber;
<ide> import org.reactivestreams.Subscription;
<ide>
<ide> import org.springframework.core.io.buffer.DataBuffer;
<del>import org.springframework.core.io.buffer.FlushingDataBuffer;
<ide> import org.springframework.core.io.buffer.support.DataBufferUtils;
<ide> import org.springframework.util.Assert;
<ide>
<ide> /**
<del> * Abstract base class for {@code Subscriber} implementations that bridge between
<add> * Abstract base class for {@code Processor} implementations that bridge between
<ide> * event-listener APIs and Reactive Streams. Specifically, base class for the
<ide> * Servlet 3.1 and Undertow support.
<ide> *
<ide> * @author Arjen Poutsma
<ide> * @since 5.0
<ide> * @see ServletServerHttpRequest
<ide> * @see UndertowHttpHandlerAdapter
<add> * @see ServerHttpResponse#writeWith(Publisher)
<ide> */
<ide> abstract class AbstractResponseBodyProcessor implements Processor<DataBuffer, Void> {
<ide>
<ide> protected boolean isWritePossible() {
<ide> */
<ide> protected abstract boolean write(DataBuffer dataBuffer) throws IOException;
<ide>
<del> /**
<del> * Flushes the output.
<del> */
<del> protected abstract void flush() throws IOException;
<del>
<ide> private boolean changeState(State oldState, State newState) {
<ide> return this.state.compareAndSet(oldState, newState);
<ide> }
<ide> void onWritePossible(AbstractResponseBodyProcessor processor) {
<ide> try {
<ide> boolean writeCompleted = processor.write(dataBuffer);
<ide> if (writeCompleted) {
<del> if (dataBuffer instanceof FlushingDataBuffer) {
<del> processor.flush();
<del> }
<ide> processor.releaseBuffer();
<ide> if (!processor.subscriberCompleted) {
<ide> processor.changeState(WRITING, REQUESTED);
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/AbstractServerHttpResponse.java
<ide> public void beforeCommit(Supplier<? extends Mono<Void>> action) {
<ide> }
<ide>
<ide> @Override
<del> public Mono<Void> writeWith(Publisher<DataBuffer> publisher) {
<del> return new ChannelSendOperator<>(publisher, writePublisher ->
<del> applyBeforeCommit().then(() -> writeWithInternal(writePublisher)));
<add> public final Mono<Void> writeWith(Publisher<DataBuffer> body) {
<add> return new ChannelSendOperator<>(body, writePublisher -> applyBeforeCommit()
<add> .then(() -> writeWithInternal(writePublisher)));
<add> }
<add>
<add> @Override
<add> public final Mono<Void> writeAndFlushWith(Publisher<Publisher<DataBuffer>> body) {
<add> return new ChannelSendOperator<>(body, writePublisher -> applyBeforeCommit()
<add> .then(() -> writeAndFlushWithInternal(writePublisher)));
<ide> }
<ide>
<ide> protected Mono<Void> applyBeforeCommit() {
<ide> protected Mono<Void> applyBeforeCommit() {
<ide> */
<ide> protected abstract Mono<Void> writeWithInternal(Publisher<DataBuffer> body);
<ide>
<add> /**
<add> * Implement this method to write to the underlying the response, and flush after
<add> * each {@code Publisher<DataBuffer>}.
<add> * @param body the publisher to write and flush with
<add> */
<add> protected abstract Mono<Void> writeAndFlushWithInternal(
<add> Publisher<Publisher<DataBuffer>> body);
<add>
<ide> /**
<ide> * Implement this method to write the status code to the underlying response.
<ide> * This method is called once only.
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/ReactorServerHttpResponse.java
<ide> import java.io.File;
<ide>
<ide> import io.netty.buffer.ByteBuf;
<del>import io.netty.buffer.Unpooled;
<ide> import io.netty.handler.codec.http.HttpResponseStatus;
<ide> import io.netty.handler.codec.http.cookie.Cookie;
<ide> import io.netty.handler.codec.http.cookie.DefaultCookie;
<ide>
<ide> import org.springframework.core.io.buffer.DataBuffer;
<ide> import org.springframework.core.io.buffer.DataBufferFactory;
<del>import org.springframework.core.io.buffer.FlushingDataBuffer;
<del>import org.springframework.core.io.buffer.NettyDataBuffer;
<add>import org.springframework.core.io.buffer.NettyDataBufferFactory;
<ide> import org.springframework.http.HttpStatus;
<ide> import org.springframework.http.ResponseCookie;
<ide> import org.springframework.http.ZeroCopyHttpOutputMessage;
<ide> protected void writeStatusCode() {
<ide>
<ide> @Override
<ide> protected Mono<Void> writeWithInternal(Publisher<DataBuffer> publisher) {
<del> return Flux.from(publisher)
<del> .window()
<del> .concatMap(w -> this.channel.send(w
<del> .takeUntil(db -> db instanceof FlushingDataBuffer)
<del> .map(this::toByteBuf)))
<del> .then();
<add> Publisher<ByteBuf> body = toByteBufs(publisher);
<add> return this.channel.send(body);
<add> }
<add>
<add> @Override
<add> protected Mono<Void> writeAndFlushWithInternal(
<add> Publisher<Publisher<DataBuffer>> publisher) {
<add> Publisher<Publisher<ByteBuf>> body = Flux.from(publisher).
<add> map(ReactorServerHttpResponse::toByteBufs);
<add> return this.channel.sendAndFlush(body);
<ide> }
<ide>
<ide> @Override
<ide> protected void writeCookies() {
<ide> }
<ide> }
<ide>
<del> private ByteBuf toByteBuf(DataBuffer buffer) {
<del> if (buffer instanceof NettyDataBuffer) {
<del> return ((NettyDataBuffer) buffer).getNativeBuffer();
<del> }
<del> else {
<del> return Unpooled.wrappedBuffer(buffer.asByteBuffer());
<del> }
<del> }
<del>
<ide> @Override
<ide> public Mono<Void> writeWith(File file, long position, long count) {
<del> return applyBeforeCommit().then(() -> {
<del> return this.channel.sendFile(file, position, count);
<del> });
<add> return applyBeforeCommit().then(() -> this.channel.sendFile(file, position, count));
<add> }
<add>
<add> private static Publisher<ByteBuf> toByteBufs(Publisher<DataBuffer> dataBuffers) {
<add> return Flux.from(dataBuffers).
<add> map(NettyDataBufferFactory::toByteBuf);
<ide> }
<ide>
<add>
<add>
<ide> }
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/RxNettyServerHttpResponse.java
<ide> package org.springframework.http.server.reactive;
<ide>
<ide> import io.netty.buffer.ByteBuf;
<del>import io.netty.buffer.CompositeByteBuf;
<ide> import io.netty.buffer.Unpooled;
<ide> import io.netty.handler.codec.http.HttpResponseStatus;
<ide> import io.netty.handler.codec.http.cookie.Cookie;
<ide> import io.reactivex.netty.protocol.http.server.ResponseContentWriter;
<ide> import org.reactivestreams.Publisher;
<ide> import reactor.adapter.RxJava1Adapter;
<add>import reactor.core.publisher.Flux;
<ide> import reactor.core.publisher.Mono;
<ide> import rx.Observable;
<ide>
<ide> import org.springframework.core.io.buffer.DataBuffer;
<del>import org.springframework.core.io.buffer.FlushingDataBuffer;
<del>import org.springframework.core.io.buffer.NettyDataBuffer;
<ide> import org.springframework.core.io.buffer.NettyDataBufferFactory;
<ide> import org.springframework.http.HttpStatus;
<ide> import org.springframework.http.ResponseCookie;
<ide> public class RxNettyServerHttpResponse extends AbstractServerHttpResponse {
<ide>
<ide> private final HttpServerResponse<ByteBuf> response;
<ide>
<add> private static final ByteBuf FLUSH_SIGNAL = Unpooled.buffer(0, 0);
<ide>
<ide> public RxNettyServerHttpResponse(HttpServerResponse<ByteBuf> response,
<ide> NettyDataBufferFactory dataBufferFactory) {
<ide> protected void writeStatusCode() {
<ide>
<ide> @Override
<ide> protected Mono<Void> writeWithInternal(Publisher<DataBuffer> body) {
<del> Observable<ByteBuf> content = RxJava1Adapter.publisherToObservable(body).map(this::toByteBuf);
<del> ResponseContentWriter<ByteBuf> writer = this.response.write(content, bb -> bb instanceof FlushingByteBuf);
<del> return RxJava1Adapter.observableToFlux(writer).then();
<add> Observable<ByteBuf> content = RxJava1Adapter.publisherToObservable(body)
<add> .map(NettyDataBufferFactory::toByteBuf);
<add> return RxJava1Adapter.observableToFlux(this.response.write(content))
<add> .then();
<ide> }
<ide>
<del> private ByteBuf toByteBuf(DataBuffer buffer) {
<del> ByteBuf byteBuf = (buffer instanceof NettyDataBuffer ?
<del> ((NettyDataBuffer) buffer).getNativeBuffer() :
<del> Unpooled.wrappedBuffer(buffer.asByteBuffer()));
<del> return (buffer instanceof FlushingDataBuffer ? new FlushingByteBuf(byteBuf) : byteBuf);
<add> @Override
<add> protected Mono<Void> writeAndFlushWithInternal(
<add> Publisher<Publisher<DataBuffer>> body) {
<add> Flux<ByteBuf> bodyWithFlushSignals = Flux.from(body).
<add> flatMap(publisher -> {
<add> return Flux.from(publisher).
<add> map(NettyDataBufferFactory::toByteBuf).
<add> concatWith(Mono.just(FLUSH_SIGNAL));
<add> });
<add> Observable<ByteBuf> content = RxJava1Adapter.publisherToObservable(bodyWithFlushSignals);
<add> ResponseContentWriter<ByteBuf> writer = this.response.write(content, bb -> bb == FLUSH_SIGNAL);
<add> return RxJava1Adapter.observableToFlux(writer).then();
<ide> }
<ide>
<ide> @Override
<ide> protected void writeHeaders() {
<ide> for (String name : getHeaders().keySet()) {
<del> for (String value : getHeaders().get(name))
<add> for (String value : getHeaders().get(name)) {
<ide> this.response.addHeader(name, value);
<add> }
<ide> }
<ide> }
<ide>
<ide> protected void writeCookies() {
<ide> }
<ide> }
<ide>
<del> private class FlushingByteBuf extends CompositeByteBuf {
<ide>
<del> public FlushingByteBuf(ByteBuf byteBuf) {
<del> super(byteBuf.alloc(), byteBuf.isDirect(), 1);
<del> this.addComponent(true, byteBuf);
<del> }
<del> }
<del>
<del>/*
<add> /*
<ide> While the underlying implementation of {@link ZeroCopyHttpOutputMessage} seems to
<ide> work; it does bypass {@link #applyBeforeCommit} and more importantly it doesn't change
<ide> its {@linkplain #state()). Therefore it's commented out, for now.
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/ServletServerHttpResponse.java
<ide>
<ide> import java.io.IOException;
<ide> import java.io.InputStream;
<add>import java.io.UncheckedIOException;
<ide> import java.nio.charset.Charset;
<ide> import java.util.List;
<ide> import java.util.Map;
<add>import java.util.concurrent.atomic.AtomicBoolean;
<ide> import javax.servlet.ServletOutputStream;
<ide> import javax.servlet.WriteListener;
<ide> import javax.servlet.http.Cookie;
<ide> import javax.servlet.http.HttpServletResponse;
<ide>
<del>import org.reactivestreams.Publisher;
<del>import reactor.core.publisher.Mono;
<add>import org.reactivestreams.Processor;
<ide>
<ide> import org.springframework.core.io.buffer.DataBuffer;
<ide> import org.springframework.core.io.buffer.DataBufferFactory;
<ide>
<ide> /**
<ide> * Adapt {@link ServerHttpResponse} to the Servlet {@link HttpServletResponse}.
<del> *
<ide> * @author Rossen Stoyanchev
<ide> * @since 5.0
<ide> */
<del>public class ServletServerHttpResponse extends AbstractServerHttpResponse {
<add>public class ServletServerHttpResponse extends AbstractListenerServerHttpResponse {
<ide>
<del> private final Object bodyProcessorMonitor = new Object();
<add> private final AtomicBoolean listenerRegistered = new AtomicBoolean();
<ide>
<ide> private volatile ResponseBodyProcessor bodyProcessor;
<ide>
<ide> private final HttpServletResponse response;
<ide>
<ide> private final int bufferSize;
<ide>
<add> private volatile boolean flushOnNext;
<add>
<ide> public ServletServerHttpResponse(HttpServletResponse response,
<ide> DataBufferFactory dataBufferFactory, int bufferSize) throws IOException {
<ide> super(dataBufferFactory);
<ide> protected void writeStatusCode() {
<ide> }
<ide> }
<ide>
<del> @Override
<del> protected Mono<Void> writeWithInternal(Publisher<DataBuffer> publisher) {
<del> Assert.state(this.bodyProcessor == null,
<del> "Response body publisher is already provided");
<del> try {
<del> synchronized (this.bodyProcessorMonitor) {
<del> if (this.bodyProcessor == null) {
<del> this.bodyProcessor = createBodyProcessor();
<del> }
<del> else {
<del> throw new IllegalStateException(
<del> "Response body publisher is already provided");
<del> }
<del> }
<del> return Mono.from(subscriber -> {
<del> publisher.subscribe(this.bodyProcessor);
<del> this.bodyProcessor.subscribe(subscriber);
<del> });
<del> }
<del> catch (IOException ex) {
<del> return Mono.error(ex);
<del> }
<del> }
<del>
<del> private ResponseBodyProcessor createBodyProcessor() throws IOException {
<del> ResponseBodyProcessor bodyProcessor =
<del> new ResponseBodyProcessor(this.response.getOutputStream(),
<del> this.bufferSize);
<del> bodyProcessor.registerListener();
<del> return bodyProcessor;
<del> }
<del>
<ide> @Override
<ide> protected void writeHeaders() {
<ide> for (Map.Entry<String, List<String>> entry : getHeaders().entrySet()) {
<ide> protected void writeCookies() {
<ide> }
<ide> }
<ide>
<del> private static class ResponseBodyProcessor extends AbstractResponseBodyProcessor {
<add> private void registerListener() throws IOException {
<add> if (this.listenerRegistered.compareAndSet(false, true)) {
<add> ResponseBodyWriteListener writeListener = new ResponseBodyWriteListener();
<add> this.response.getOutputStream().setWriteListener(writeListener);
<add> }
<add> }
<add>
<add> private void flush() throws IOException {
<add> ServletOutputStream outputStream = this.response.getOutputStream();
<add> if (outputStream.isReady()) {
<add> try {
<add> outputStream.flush();
<add> this.flushOnNext = false;
<add> }
<add> catch (IOException ex) {
<add> this.flushOnNext = true;
<add> throw ex;
<add> }
<add> }
<add> else {
<add> this.flushOnNext = true;
<add> }
<add> }
<add>
<add> @Override
<add> protected ResponseBodyProcessor createBodyProcessor() {
<add> try {
<add> registerListener();
<add> this.bodyProcessor = new ResponseBodyProcessor(this.response.getOutputStream(),
<add> this.bufferSize);
<add> return this.bodyProcessor;
<add> }
<add> catch (IOException ex) {
<add> throw new UncheckedIOException(ex);
<add> }
<add> }
<add>
<add> @Override
<add> protected AbstractResponseBodyFlushProcessor createBodyFlushProcessor() {
<add> return new ResponseBodyFlushProcessor();
<add> }
<ide>
<del> private final ResponseBodyWriteListener writeListener =
<del> new ResponseBodyWriteListener();
<add> private class ResponseBodyProcessor extends AbstractResponseBodyProcessor {
<ide>
<ide> private final ServletOutputStream outputStream;
<ide>
<ide> private final int bufferSize;
<ide>
<del> private volatile boolean flushOnNext;
<del>
<ide> public ResponseBodyProcessor(ServletOutputStream outputStream, int bufferSize) {
<ide> this.outputStream = outputStream;
<ide> this.bufferSize = bufferSize;
<ide> }
<ide>
<del> public void registerListener() throws IOException {
<del> this.outputStream.setWriteListener(this.writeListener);
<del> }
<del>
<ide> @Override
<ide> protected boolean isWritePossible() {
<ide> return this.outputStream.isReady();
<ide> }
<ide>
<ide> @Override
<ide> protected boolean write(DataBuffer dataBuffer) throws IOException {
<del> if (this.flushOnNext) {
<add> if (ServletServerHttpResponse.this.flushOnNext) {
<add> if (logger.isTraceEnabled()) {
<add> logger.trace("flush");
<add> }
<ide> flush();
<ide> }
<ide>
<ide> protected boolean write(DataBuffer dataBuffer) throws IOException {
<ide> }
<ide> }
<ide>
<del> @Override
<del> protected void flush() throws IOException {
<del> if (this.outputStream.isReady()) {
<del> if (logger.isTraceEnabled()) {
<del> logger.trace("flush");
<del> }
<del> this.outputStream.flush();
<del> this.flushOnNext = false;
<del> return;
<del> }
<del> this.flushOnNext = true;
<del>
<del> }
<del>
<ide> private int writeDataBuffer(DataBuffer dataBuffer) throws IOException {
<ide> InputStream input = dataBuffer.asInputStream();
<ide>
<ide> private int writeDataBuffer(DataBuffer dataBuffer) throws IOException {
<ide> return bytesWritten;
<ide> }
<ide>
<del> private class ResponseBodyWriteListener implements WriteListener {
<add> }
<add>
<add> private class ResponseBodyWriteListener implements WriteListener {
<ide>
<del> @Override
<del> public void onWritePossible() throws IOException {
<del> ResponseBodyProcessor.this.onWritePossible();
<add> @Override
<add> public void onWritePossible() throws IOException {
<add> if (bodyProcessor != null) {
<add> bodyProcessor.onWritePossible();
<ide> }
<add> }
<ide>
<del> @Override
<del> public void onError(Throwable ex) {
<del> ResponseBodyProcessor.this.onError(ex);
<add> @Override
<add> public void onError(Throwable ex) {
<add> if (bodyProcessor != null) {
<add> bodyProcessor.onError(ex);
<ide> }
<ide> }
<ide> }
<add>
<add> private class ResponseBodyFlushProcessor extends AbstractResponseBodyFlushProcessor {
<add>
<add> @Override
<add> protected Processor<DataBuffer, Void> createBodyProcessor() {
<add> return ServletServerHttpResponse.this.createBodyProcessor();
<add> }
<add>
<add> @Override
<add> protected void flush() throws IOException {
<add> if (logger.isTraceEnabled()) {
<add> logger.trace("flush");
<add> }
<add> ServletServerHttpResponse.this.flush();
<add> }
<add>
<add> }
<add>
<ide> }
<ide>\ No newline at end of file
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/UndertowServerHttpResponse.java
<ide> import io.undertow.server.handlers.Cookie;
<ide> import io.undertow.server.handlers.CookieImpl;
<ide> import io.undertow.util.HttpString;
<del>import org.reactivestreams.Publisher;
<add>import org.reactivestreams.Processor;
<ide> import org.xnio.ChannelListener;
<ide> import org.xnio.channels.StreamSinkChannel;
<ide> import reactor.core.publisher.Mono;
<ide> * @author Arjen Poutsma
<ide> * @since 5.0
<ide> */
<del>public class UndertowServerHttpResponse extends AbstractServerHttpResponse
<add>public class UndertowServerHttpResponse extends AbstractListenerServerHttpResponse
<ide> implements ZeroCopyHttpOutputMessage {
<ide>
<del> private final Object bodyProcessorMonitor = new Object();
<del>
<del> private volatile ResponseBodyProcessor bodyProcessor;
<del>
<ide> private final HttpServerExchange exchange;
<ide>
<add> private StreamSinkChannel responseChannel;
<add>
<ide> public UndertowServerHttpResponse(HttpServerExchange exchange,
<ide> DataBufferFactory dataBufferFactory) {
<ide> super(dataBufferFactory);
<ide> protected void writeStatusCode() {
<ide> }
<ide> }
<ide>
<del> @Override
<del> protected Mono<Void> writeWithInternal(Publisher<DataBuffer> publisher) {
<del> Assert.state(this.bodyProcessor == null,
<del> "Response body publisher is already provided");
<del> try {
<del> synchronized (this.bodyProcessorMonitor) {
<del> if (this.bodyProcessor == null) {
<del> this.bodyProcessor = createBodyProcessor();
<del> }
<del> else {
<del> throw new IllegalStateException(
<del> "Response body publisher is already provided");
<del> }
<del> }
<del> return Mono.from(subscriber -> {
<del> publisher.subscribe(this.bodyProcessor);
<del> this.bodyProcessor.subscribe(subscriber);
<del> });
<del> }
<del> catch (IOException ex) {
<del> return Mono.error(ex);
<del> }
<del> }
<del>
<del> private ResponseBodyProcessor createBodyProcessor() throws IOException {
<del> ResponseBodyProcessor bodyProcessor = new ResponseBodyProcessor(this.exchange);
<del> bodyProcessor.registerListener();
<del> return bodyProcessor;
<del> }
<del>
<del>
<ide> @Override
<ide> public Mono<Void> writeWith(File file, long position, long count) {
<ide> writeHeaders();
<ide> protected void writeCookies() {
<ide> }
<ide> }
<ide>
<add> @Override
<add> protected ResponseBodyProcessor createBodyProcessor() {
<add> if (this.responseChannel == null) {
<add> this.responseChannel = this.exchange.getResponseChannel();
<add> }
<add> ResponseBodyProcessor bodyProcessor =
<add> new ResponseBodyProcessor( this.responseChannel);
<add> bodyProcessor.registerListener();
<add> return bodyProcessor;
<add> }
<add>
<add> @Override
<add> protected AbstractResponseBodyFlushProcessor createBodyFlushProcessor() {
<add> return new ResponseBodyFlushProcessor();
<add> }
<add>
<ide> private static class ResponseBodyProcessor extends AbstractResponseBodyProcessor {
<ide>
<ide> private final ChannelListener<StreamSinkChannel> listener = new WriteListener();
<ide> private static class ResponseBodyProcessor extends AbstractResponseBodyProcessor
<ide>
<ide> private volatile ByteBuffer byteBuffer;
<ide>
<del> public ResponseBodyProcessor(HttpServerExchange exchange) {
<del> this.responseChannel = exchange.getResponseChannel();
<add> public ResponseBodyProcessor(StreamSinkChannel responseChannel) {
<add> Assert.notNull(responseChannel, "'responseChannel' must not be null");
<add> this.responseChannel = responseChannel;
<ide> }
<ide>
<ide> public void registerListener() {
<ide> this.responseChannel.getWriteSetter().set(this.listener);
<ide> this.responseChannel.resumeWrites();
<ide> }
<ide>
<del> @Override
<del> protected void flush() throws IOException {
<del> if (logger.isTraceEnabled()) {
<del> logger.trace("flush");
<del> }
<del> this.responseChannel.flush();
<del> }
<del>
<ide> @Override
<ide> protected boolean write(DataBuffer dataBuffer) throws IOException {
<ide> if (this.byteBuffer == null) {
<ide> public void handleEvent(StreamSinkChannel channel) {
<ide> }
<ide>
<ide> }
<add>
<add> private class ResponseBodyFlushProcessor extends AbstractResponseBodyFlushProcessor {
<add>
<add> @Override
<add> protected Processor<DataBuffer, Void> createBodyProcessor() {
<add> return UndertowServerHttpResponse.this.createBodyProcessor();
<add> }
<add>
<add> @Override
<add> protected void flush() throws IOException {
<add> if (UndertowServerHttpResponse.this.responseChannel != null) {
<add> if (logger.isTraceEnabled()) {
<add> logger.trace("flush");
<add> }
<add> UndertowServerHttpResponse.this.responseChannel.flush();
<add> }
<add> }
<add>
<add> }
<ide> }
<ide><path>spring-web/src/test/java/org/springframework/http/codec/SseEventEncoderTests.java
<del>/*
<del> * Copyright 2002-2016 the original author or authors.
<del> *
<del> * Licensed under the Apache License, Version 2.0 (the "License");
<del> * you may not use this file except in compliance with the License.
<del> * You may obtain a copy of the License at
<del> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS,
<del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del> * See the License for the specific language governing permissions and
<del> * limitations under the License.
<del> */
<del>
<del>package org.springframework.http.codec;
<del>
<del>import java.util.Arrays;
<del>
<del>import static org.junit.Assert.*;
<del>import org.junit.Test;
<del>import reactor.core.publisher.Flux;
<del>import reactor.core.publisher.Mono;
<del>import reactor.test.TestSubscriber;
<del>
<del>import org.springframework.core.ResolvableType;
<del>import org.springframework.core.io.buffer.AbstractDataBufferAllocatingTestCase;
<del>import org.springframework.core.io.buffer.DataBuffer;
<del>import org.springframework.core.io.buffer.FlushingDataBuffer;
<del>import org.springframework.http.codec.json.JacksonJsonEncoder;
<del>import org.springframework.util.MimeType;
<del>
<del>/**
<del> * @author Sebastien Deleuze
<del> */
<del>public class SseEventEncoderTests extends AbstractDataBufferAllocatingTestCase {
<del>
<del> @Test
<del> public void nullMimeType() {
<del> SseEventEncoder encoder = new SseEventEncoder(Arrays.asList(new JacksonJsonEncoder()));
<del> assertTrue(encoder.canEncode(ResolvableType.forClass(Object.class), null));
<del> }
<del>
<del> @Test
<del> public void unsupportedMimeType() {
<del> SseEventEncoder encoder = new SseEventEncoder(Arrays.asList(new JacksonJsonEncoder()));
<del> assertFalse(encoder.canEncode(ResolvableType.forClass(Object.class), new MimeType("foo", "bar")));
<del> }
<del>
<del> @Test
<del> public void supportedMimeType() {
<del> SseEventEncoder encoder = new SseEventEncoder(Arrays.asList(new JacksonJsonEncoder()));
<del> assertTrue(encoder.canEncode(ResolvableType.forClass(Object.class), new MimeType("text", "event-stream")));
<del> }
<del>
<del> @Test
<del> public void encodeServerSentEvent() {
<del> SseEventEncoder encoder = new SseEventEncoder(Arrays.asList(new JacksonJsonEncoder()));
<del> SseEvent event = new SseEvent();
<del> event.setId("c42");
<del> event.setName("foo");
<del> event.setComment("bla\nbla bla\nbla bla bla");
<del> event.setReconnectTime(123L);
<del> Mono<SseEvent> source = Mono.just(event);
<del> Flux<DataBuffer> output = encoder.encode(source, this.bufferFactory,
<del> ResolvableType.forClass(SseEvent.class), new MimeType("text", "event-stream"));
<del> TestSubscriber
<del> .subscribe(output)
<del> .assertNoError()
<del> .assertValuesWith(
<del> stringConsumer(
<del> "id:c42\n" +
<del> "event:foo\n" +
<del> "retry:123\n" +
<del> ":bla\n:bla bla\n:bla bla bla\n"),
<del> stringConsumer("\n"),
<del> b -> assertEquals(FlushingDataBuffer.class, b.getClass())
<del> );
<del> }
<del>
<del> @Test
<del> public void encodeString() {
<del> SseEventEncoder encoder = new SseEventEncoder(Arrays.asList(new JacksonJsonEncoder()));
<del> Flux<String> source = Flux.just("foo", "bar");
<del> Flux<DataBuffer> output = encoder.encode(source, this.bufferFactory,
<del> ResolvableType.forClass(String.class), new MimeType("text", "event-stream"));
<del> TestSubscriber
<del> .subscribe(output)
<del> .assertNoError()
<del> .assertValuesWith(
<del> stringConsumer("data:foo\n"),
<del> stringConsumer("\n"),
<del> b -> assertEquals(FlushingDataBuffer.class, b.getClass()),
<del> stringConsumer("data:bar\n"),
<del> stringConsumer("\n"),
<del> b -> assertEquals(FlushingDataBuffer.class, b.getClass())
<del> );
<del> }
<del>
<del> @Test
<del> public void encodeMultilineString() {
<del> SseEventEncoder encoder = new SseEventEncoder(Arrays.asList(new JacksonJsonEncoder()));
<del> Flux<String> source = Flux.just("foo\nbar", "foo\nbaz");
<del> Flux<DataBuffer> output = encoder.encode(source, this.bufferFactory,
<del> ResolvableType.forClass(String.class), new MimeType("text", "event-stream"));
<del> TestSubscriber
<del> .subscribe(output)
<del> .assertNoError()
<del> .assertValuesWith(
<del> stringConsumer("data:foo\ndata:bar\n"),
<del> stringConsumer("\n"),
<del> b -> assertEquals(FlushingDataBuffer.class, b.getClass()),
<del> stringConsumer("data:foo\ndata:baz\n"),
<del> stringConsumer("\n"),
<del> b -> assertEquals(FlushingDataBuffer.class, b.getClass())
<del> );
<del> }
<del>
<del> @Test
<del> public void encodePojo() {
<del> SseEventEncoder encoder = new SseEventEncoder(Arrays.asList(new JacksonJsonEncoder()));
<del> Flux<Pojo> source = Flux.just(new Pojo("foofoo", "barbar"), new Pojo("foofoofoo", "barbarbar"));
<del> Flux<DataBuffer> output = encoder.encode(source, this.bufferFactory,
<del> ResolvableType.forClass(Pojo.class), new MimeType("text", "event-stream"));
<del> TestSubscriber
<del> .subscribe(output)
<del> .assertNoError()
<del> .assertValuesWith(
<del> stringConsumer("data:"),
<del> stringConsumer("{\"foo\":\"foofoo\",\"bar\":\"barbar\"}"),
<del> stringConsumer("\n"),
<del> stringConsumer("\n"),
<del> b -> assertEquals(FlushingDataBuffer.class, b.getClass()),
<del> stringConsumer("data:"),
<del> stringConsumer("{\"foo\":\"foofoofoo\",\"bar\":\"barbarbar\"}"),
<del> stringConsumer("\n"),
<del> stringConsumer("\n"),
<del> b -> assertEquals(FlushingDataBuffer.class, b.getClass())
<del> );
<del> }
<del>
<del>}
<ide><path>spring-web/src/test/java/org/springframework/http/converter/reactive/SseEventHttpMessageWriterTests.java
<add>/*
<add> * Copyright 2002-2016 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.http.converter.reactive;
<add>
<add>import java.util.Collections;
<add>
<add>import org.junit.Test;
<add>import org.reactivestreams.Publisher;
<add>import reactor.core.publisher.Flux;
<add>import reactor.core.publisher.Mono;
<add>import reactor.test.TestSubscriber;
<add>
<add>import org.springframework.core.ResolvableType;
<add>import org.springframework.core.io.buffer.AbstractDataBufferAllocatingTestCase;
<add>import org.springframework.core.io.buffer.DataBuffer;
<add>import org.springframework.http.MediaType;
<add>import org.springframework.http.codec.Pojo;
<add>import org.springframework.http.codec.SseEvent;
<add>import org.springframework.http.codec.json.JacksonJsonEncoder;
<add>import org.springframework.http.server.reactive.MockServerHttpResponse;
<add>
<add>import static org.junit.Assert.*;
<add>
<add>/**
<add> * @author Sebastien Deleuze
<add> */
<add>public class SseEventHttpMessageWriterTests
<add> extends AbstractDataBufferAllocatingTestCase {
<add>
<add> private SseEventHttpMessageWriter converter = new SseEventHttpMessageWriter(
<add> Collections.singletonList(new JacksonJsonEncoder()));
<add>
<add> @Test
<add> public void nullMimeType() {
<add> assertTrue(converter.canWrite(ResolvableType.forClass(Object.class), null));
<add> }
<add>
<add> @Test
<add> public void unsupportedMimeType() {
<add> assertFalse(converter.canWrite(ResolvableType.forClass(Object.class),
<add> new MediaType("foo", "bar")));
<add> }
<add>
<add> @Test
<add> public void supportedMimeType() {
<add> assertTrue(converter.canWrite(ResolvableType.forClass(Object.class),
<add> new MediaType("text", "event-stream")));
<add> }
<add>
<add> @Test
<add> public void encodeServerSentEvent() {
<add> SseEvent event = new SseEvent();
<add> event.setId("c42");
<add> event.setName("foo");
<add> event.setComment("bla\nbla bla\nbla bla bla");
<add> event.setReconnectTime(123L);
<add> Mono<SseEvent> source = Mono.just(event);
<add> MockServerHttpResponse outputMessage = new MockServerHttpResponse();
<add> converter.write(source, ResolvableType.forClass(SseEvent.class),
<add> new MediaType("text", "event-stream"), outputMessage);
<add>
<add> Publisher<Publisher<DataBuffer>> result = outputMessage.getBodyWithFlush();
<add> TestSubscriber.subscribe(result).
<add> assertNoError().
<add> assertValuesWith(publisher -> {
<add> TestSubscriber.subscribe(publisher).assertNoError().assertValuesWith(
<add> stringConsumer("id:c42\n" + "event:foo\n" + "retry:123\n" +
<add> ":bla\n:bla bla\n:bla bla bla\n"),
<add> stringConsumer("\n"));
<add>
<add> });
<add> }
<add>
<add> @Test
<add> public void encodeString() {
<add> Flux<String> source = Flux.just("foo", "bar");
<add> MockServerHttpResponse outputMessage = new MockServerHttpResponse();
<add> converter.write(source, ResolvableType.forClass(String.class),
<add> new MediaType("text", "event-stream"), outputMessage);
<add>
<add> Publisher<Publisher<DataBuffer>> result = outputMessage.getBodyWithFlush();
<add> TestSubscriber.subscribe(result).
<add> assertNoError().
<add> assertValuesWith(publisher -> {
<add> TestSubscriber.subscribe(publisher).assertNoError()
<add> .assertValuesWith(stringConsumer("data:foo\n"),
<add> stringConsumer("\n"));
<add>
<add> }, publisher -> {
<add> TestSubscriber.subscribe(publisher).assertNoError()
<add> .assertValuesWith(stringConsumer("data:bar\n"),
<add> stringConsumer("\n"));
<add>
<add> });
<add> }
<add>
<add> @Test
<add> public void encodeMultiLineString() {
<add> Flux<String> source = Flux.just("foo\nbar", "foo\nbaz");
<add> MockServerHttpResponse outputMessage = new MockServerHttpResponse();
<add> converter.write(source, ResolvableType.forClass(String.class),
<add> new MediaType("text", "event-stream"), outputMessage);
<add>
<add> Publisher<Publisher<DataBuffer>> result = outputMessage.getBodyWithFlush();
<add> TestSubscriber.subscribe(result).
<add> assertNoError().
<add> assertValuesWith(publisher -> {
<add> TestSubscriber.subscribe(publisher).assertNoError()
<add> .assertValuesWith(stringConsumer("data:foo\ndata:bar\n"),
<add> stringConsumer("\n"));
<add>
<add> }, publisher -> {
<add> TestSubscriber.subscribe(publisher).assertNoError()
<add> .assertValuesWith(stringConsumer("data:foo\ndata:baz\n"),
<add> stringConsumer("\n"));
<add>
<add> });
<add> }
<add>
<add> @Test
<add> public void encodePojo() {
<add> Flux<Pojo> source = Flux.just(new Pojo("foofoo", "barbar"),
<add> new Pojo("foofoofoo", "barbarbar"));
<add> MockServerHttpResponse outputMessage = new MockServerHttpResponse();
<add> converter.write(source, ResolvableType.forClass(Pojo.class),
<add> new MediaType("text", "event-stream"), outputMessage);
<add>
<add> Publisher<Publisher<DataBuffer>> result = outputMessage.getBodyWithFlush();
<add> TestSubscriber.subscribe(result).
<add> assertNoError().
<add> assertValuesWith(publisher -> {
<add> TestSubscriber.subscribe(publisher).assertNoError()
<add> .assertValuesWith(stringConsumer("data:"), stringConsumer(
<add> "{\"foo\":\"foofoo\",\"bar\":\"barbar\"}"),
<add> stringConsumer("\n"), stringConsumer("\n"));
<add>
<add> }, publisher -> {
<add> TestSubscriber.subscribe(publisher).assertNoError()
<add> .assertValuesWith(stringConsumer("data:"), stringConsumer(
<add> "{\"foo\":\"foofoofoo\",\"bar\":\"barbarbar\"}"),
<add> stringConsumer("\n"), stringConsumer("\n"));
<add>
<add> });
<add> }
<add>
<add>}
<ide><path>spring-web/src/test/java/org/springframework/http/server/reactive/FlushingIntegrationTests.java
<ide>
<ide> import org.junit.Before;
<ide> import org.junit.Test;
<del>
<add>import org.reactivestreams.Publisher;
<ide> import reactor.core.publisher.Flux;
<ide> import reactor.core.publisher.Mono;
<ide> import reactor.test.TestSubscriber;
<ide>
<ide> import org.springframework.core.io.buffer.DataBuffer;
<del>import org.springframework.core.io.buffer.FlushingDataBuffer;
<ide> import org.springframework.http.client.reactive.ReactorClientHttpConnector;
<add>import org.springframework.http.server.reactive.bootstrap.ReactorHttpServer;
<ide> import org.springframework.web.client.reactive.ClientWebRequestBuilders;
<ide> import org.springframework.web.client.reactive.ResponseExtractors;
<ide> import org.springframework.web.client.reactive.WebClient;
<ide>
<add>import static org.junit.Assume.assumeFalse;
<add>
<ide> /**
<ide> * @author Sebastien Deleuze
<ide> */
<ide> public void testFlushing() throws Exception {
<ide> .assertValues("data0data1");
<ide> }
<ide>
<del>
<ide> @Override
<ide> protected HttpHandler createHttpHandler() {
<ide> return new FlushingHandler();
<ide> }
<ide>
<del> // Handler that never completes designed to test if flushing is perform correctly when
<del> // a FlushingDataBuffer is written
<ide> private static class FlushingHandler implements HttpHandler {
<ide>
<ide> @Override
<ide> public Mono<Void> handle(ServerHttpRequest request, ServerHttpResponse response) {
<del> Flux<DataBuffer> responseBody = Flux
<add> Flux<Publisher<DataBuffer>> responseBody = Flux
<ide> .intervalMillis(50)
<ide> .map(l -> {
<ide> byte[] data = ("data" + l).getBytes();
<ide> public Mono<Void> handle(ServerHttpRequest request, ServerHttpResponse response)
<ide> return buffer;
<ide> })
<ide> .take(2)
<del> .concatWith(Mono.just(FlushingDataBuffer.INSTANCE))
<del> .concatWith(Flux.never());
<del> return response.writeWith(responseBody);
<add> .map(Flux::just);
<add>
<add> responseBody = responseBody.concatWith(Flux.never());
<add>
<add> return response.writeAndFlushWith(responseBody);
<ide> }
<ide> }
<ide>
<ide><path>spring-web/src/test/java/org/springframework/http/server/reactive/MockServerHttpResponse.java
<ide> public class MockServerHttpResponse implements ServerHttpResponse {
<ide>
<ide> private Publisher<DataBuffer> body;
<ide>
<add> private Publisher<Publisher<DataBuffer>> bodyWithFlushes;
<add>
<ide> private DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
<ide>
<ide>
<ide> public Publisher<DataBuffer> getBody() {
<ide> return this.body;
<ide> }
<ide>
<add> public Publisher<Publisher<DataBuffer>> getBodyWithFlush() {
<add> return this.bodyWithFlushes;
<add> }
<add>
<ide> @Override
<ide> public Mono<Void> writeWith(Publisher<DataBuffer> body) {
<ide> this.body = body;
<ide> return Flux.from(this.body).then();
<ide> }
<ide>
<add> @Override
<add> public Mono<Void> writeAndFlushWith(Publisher<Publisher<DataBuffer>> body) {
<add> this.bodyWithFlushes = body;
<add> return Flux.from(this.bodyWithFlushes).then();
<add> }
<add>
<ide> @Override
<ide> public void beforeCommit(Supplier<? extends Mono<Void>> action) {
<ide> }
<ide> public Mono<Void> setComplete() {
<ide> public DataBufferFactory bufferFactory() {
<ide> return this.dataBufferFactory;
<ide> }
<del>
<ide> }
<ide><path>spring-web/src/test/java/org/springframework/http/server/reactive/ServerHttpResponseTests.java
<ide> protected Mono<Void> writeWithInternal(Publisher<DataBuffer> body) {
<ide> return b;
<ide> }).then();
<ide> }
<add>
<add> @Override
<add> protected Mono<Void> writeAndFlushWithInternal(
<add> Publisher<Publisher<DataBuffer>> body) {
<add> return Mono.error(new UnsupportedOperationException());
<add> }
<ide> }
<ide>
<ide> } | 21 |
Javascript | Javascript | remove backandroid warning | 1a926ab807fa58d41813226edb495feec04f597d | <ide><path>Libraries/Utilities/BackAndroid.ios.js
<ide>
<ide> 'use strict';
<ide>
<del>var warning = require('warning');
<add>function emptyFunction() {}
<ide>
<del>function platformWarn() {
<del> warning(false, 'BackAndroid is not supported on this platform.');
<del>}
<del>
<del>var BackAndroid = {
<del> exitApp: platformWarn,
<del> addEventListener: platformWarn,
<del> removeEventListener: platformWarn,
<add>const BackAndroid = {
<add> exitApp: emptyFunction,
<add> addEventListener: emptyFunction,
<add> removeEventListener: emptyFunction,
<ide> };
<ide>
<ide> module.exports = BackAndroid; | 1 |
Python | Python | change constant torch.tensor to torch.full | 707b12a353b69feecf11557e13d3041982bf023f | <ide><path>src/transformers/models/decision_transformer/modeling_decision_transformer.py
<ide> def _attn(self, query, key, value, attention_mask=None, head_mask=None):
<ide> attn_weights = torch.matmul(query, key.transpose(-1, -2))
<ide>
<ide> if self.scale_attn_weights:
<del> attn_weights = attn_weights / torch.tensor(
<del> value.size(-1) ** 0.5, dtype=attn_weights.dtype, device=attn_weights.device
<add> attn_weights = attn_weights / torch.full(
<add> [], value.size(-1) ** 0.5, dtype=attn_weights.dtype, device=attn_weights.device
<ide> )
<ide>
<ide> # Layer-wise attention scaling
<ide> def _attn(self, query, key, value, attention_mask=None, head_mask=None):
<ide> mask_value = torch.finfo(attn_weights.dtype).min
<ide> # Need to be a tensor, otherwise we get error: `RuntimeError: expected scalar type float but found double`.
<ide> # Need to be on the same device, otherwise `RuntimeError: ..., x and y to be on the same device`
<del> mask_value = torch.tensor(mask_value, dtype=attn_weights.dtype).to(attn_weights.device)
<add> mask_value = torch.full([], mask_value, dtype=attn_weights.dtype).to(attn_weights.device)
<ide> attn_weights = torch.where(causal_mask, attn_weights, mask_value)
<ide>
<ide> if attention_mask is not None:
<ide><path>src/transformers/models/gpt2/modeling_gpt2.py
<ide> def _attn(self, query, key, value, attention_mask=None, head_mask=None):
<ide> attn_weights = torch.matmul(query, key.transpose(-1, -2))
<ide>
<ide> if self.scale_attn_weights:
<del> attn_weights = attn_weights / torch.tensor(
<del> value.size(-1) ** 0.5, dtype=attn_weights.dtype, device=attn_weights.device
<add> attn_weights = attn_weights / torch.full(
<add> [], value.size(-1) ** 0.5, dtype=attn_weights.dtype, device=attn_weights.device
<ide> )
<ide>
<ide> # Layer-wise attention scaling
<ide> def _attn(self, query, key, value, attention_mask=None, head_mask=None):
<ide> mask_value = torch.finfo(attn_weights.dtype).min
<ide> # Need to be a tensor, otherwise we get error: `RuntimeError: expected scalar type float but found double`.
<ide> # Need to be on the same device, otherwise `RuntimeError: ..., x and y to be on the same device`
<del> mask_value = torch.tensor(mask_value, dtype=attn_weights.dtype).to(attn_weights.device)
<add> mask_value = torch.full([], mask_value, dtype=attn_weights.dtype).to(attn_weights.device)
<ide> attn_weights = torch.where(causal_mask, attn_weights, mask_value)
<ide>
<ide> if attention_mask is not None: | 2 |
Text | Text | reset state if comment submit fails | 240d7c82ccdcda6bfe26e5f853851281e5585da1 | <ide><path>docs/docs/tutorial.it-IT.md
<ide> var CommentBox = React.createClass({
<ide> this.setState({data: data});
<ide> }.bind(this),
<ide> error: function(xhr, status, err) {
<add> this.setState({data: comments});
<ide> console.error(this.props.url, status, err.toString());
<ide> }.bind(this)
<ide> });
<ide><path>docs/docs/tutorial.ja-JP.md
<ide> var CommentBox = React.createClass({
<ide> this.setState({data: data});
<ide> }.bind(this),
<ide> error: function(xhr, status, err) {
<add> this.setState({data: comments});
<ide> console.error(this.props.url, status, err.toString());
<ide> }.bind(this)
<ide> });
<ide><path>docs/docs/tutorial.ko-KR.md
<ide> var CommentBox = React.createClass({
<ide> this.setState({data: data});
<ide> }.bind(this),
<ide> error: function(xhr, status, err) {
<add> this.setState({data: comments});
<ide> console.error(this.props.url, status, err.toString());
<ide> }.bind(this)
<ide> });
<ide><path>docs/docs/tutorial.md
<ide> var CommentBox = React.createClass({
<ide> this.setState({data: data});
<ide> }.bind(this),
<ide> error: function(xhr, status, err) {
<add> this.setState({data: comments});
<ide> console.error(this.props.url, status, err.toString());
<ide> }.bind(this)
<ide> });
<ide><path>docs/docs/tutorial.zh-CN.md
<ide> var CommentBox = React.createClass({
<ide> this.setState({data: data});
<ide> }.bind(this),
<ide> error: function(xhr, status, err) {
<add> this.setState({data: comments});
<ide> console.error(this.props.url, status, err.toString());
<ide> }.bind(this)
<ide> }); | 5 |
Ruby | Ruby | fix example in active model attribute methods | 1c02b988641c201308e6b3de6457128878e47bd5 | <ide><path>activemodel/lib/active_model/attribute_methods.rb
<ide> class MissingAttributeError < NoMethodError
<ide> # attribute_method_affix prefix: 'reset_', suffix: '_to_default!'
<ide> # attribute_method_suffix '_contrived?'
<ide> # attribute_method_prefix 'clear_'
<del> # define_attribute_methods :name
<add> # define_attribute_methods [:name]
<ide> #
<ide> # attr_accessor :name
<ide> # | 1 |
Javascript | Javascript | add commonjs build of ember | 27dac7bffd707ec25bba9a8b98cdeb937f518b10 | <ide><path>Brocfile.js
<ide> var deprecatedDebugFile = replace(compiledSource, {
<ide> { match: /var runningNonEmberDebugJS = false;/, replacement: 'var runningNonEmberDebugJS = true;'}
<ide> ]
<ide> });
<add>
<ide> deprecatedDebugFile = concat(deprecatedDebugFile, {
<ide> inputFiles: [ 'ember.debug.js' ],
<ide> outputFile: '/ember.js'
<ide> function buildRuntimeTree() {
<ide> });
<ide> }
<ide>
<add>function buildCJSTree() {
<add> var compiledSource = concatES6(devSourceTrees, {
<add> es3Safe: env !== 'development',
<add> derequire: env !== 'development',
<add> includeLoader: true,
<add> bootstrapModule: 'ember',
<add> vendorTrees: vendorTrees,
<add> inputFiles: ['**/*.js'],
<add> destFile: '/ember.debug.cjs.js'
<add> });
<add>
<add> var exportsTree = writeFile('export-ember', ';module.exports = Ember;\n');
<add>
<add> return concat(mergeTrees([compiledSource, exportsTree]), {
<add> wrapInEval: false,
<add> inputFiles: ['ember.debug.cjs.js', 'export-ember'],
<add> outputFile: '/ember.debug.cjs.js'
<add> });
<add>}
<add>
<ide> // Generates prod build. defeatureify increases the overall runtime speed of ember.js by
<ide> // ~10%. See defeatureify.
<ide> var prodCompiledSource = concatES6(prodSourceTrees, {
<ide> if (env !== 'development') {
<ide> distTrees.push(minCompiledSource);
<ide> }
<ide> distTrees.push(buildRuntimeTree());
<add> distTrees.push(buildCJSTree());
<ide> }
<ide>
<ide> // merge distTrees and sub out version placeholders for distribution
<ide><path>bin/run-node-tests.js
<add>#!/usr/bin/env node
<add>
<add>require('qunitjs');
<add>
<add>// adds test reporting
<add>var qe = require('qunit-extras');
<add>qe.runInContext(global);
<add>
<add>var glob = require('glob');
<add>var root = 'tests/';
<add>
<add>function addFiles(files) {
<add> glob.sync(root + files)
<add> .map(function(name) {
<add> return "../" + name.substring(0, name.length - 3);
<add> })
<add> .forEach(require);
<add>}
<add>
<add>addFiles('/**/*-test.js');
<add>
<add>QUnit.load();
<ide><path>tests/node/app-boot-test.js
<ide> var distPath = path.join(__dirname, '../../dist');
<ide> QUnit.module("App boot");
<ide>
<ide> QUnit.test("App is created without throwing an exception", function() {
<del> var Ember = require(path.join(distPath, 'ember.debug'));
<add> var Ember = require(path.join(distPath, 'ember.debug.cjs'));
<ide>
<ide> var App = Ember.Application.create({
<ide> }); | 3 |
Ruby | Ruby | use appropriate type to `header` option | c4a11171da2e56a46d7c2e1ee3ba82cca9a72a5f | <ide><path>railties/lib/rails/commands/dbconsole/dbconsole_command.rb
<ide> class DbconsoleCommand < Base # :nodoc:
<ide> class_option :mode, enum: %w( html list line column ), type: :string,
<ide> desc: "Automatically put the sqlite3 database in the specified mode (html, list, line, column)."
<ide>
<del> class_option :header, type: :string
<add> class_option :header, type: :boolean
<ide>
<ide> class_option :environment, aliases: "-e", type: :string,
<ide> desc: "Specifies the environment to run this console under (test/development/production)." | 1 |
Text | Text | add treeview shortcuts | 8faf1ed5d5730dd095e536b424c71d8ad2add7c6 | <ide><path>README.md
<ide> explore features.
<ide>
<ide> Most default OS X keybindings also work.
<ide>
<add>## TreeView Keyboard shortcuts
<add>With the treeview focused:
<add>
<add>`a` : Add a new file or directory. Directories end with '/'.
<add>
<add>`m` : Rename a file or directory
<add>
<ide> ## Init Script
<ide>
<ide> Atom will require `~/.atom/user.coffee` whenever a window is opened or reloaded if it is present in your | 1 |
Javascript | Javascript | fix typo in property name (histroy --> history) | fa79eaa816aa27c6d1b3c084b8372f9c17c8d5a3 | <ide><path>test/ng/browserSpecs.js
<ide> describe('browser', function() {
<ide> // `history.state` in contexts where `$sniffer.history` is false.
<ide>
<ide> var historyStateAccessed = false;
<del> var mockSniffer = {histroy: false};
<add> var mockSniffer = {history: false};
<ide> var mockWindow = new MockWindow();
<ide>
<ide> var _state = mockWindow.history.state; | 1 |
Javascript | Javascript | use test text instead of err message | 181fcb9b32fca3cf1b62bd7a9c08d76691c29d22 | <ide><path>client/src/client/frame-runner.js
<ide> document.addEventListener('DOMContentLoaded', function() {
<ide> const { message, stack } = err;
<ide> // we catch the error here to prevent the error from bubbling up
<ide> // and collapsing the pipe
<del> let errMessage = message.slice(0) || '';
<del> const assertIndex = errMessage.indexOf(': expected');
<del> if (assertIndex !== -1) {
<del> errMessage = errMessage.slice(0, assertIndex);
<del> }
<del> errMessage = errMessage.replace(/<code>(.*?)<\/code>/g, '$1');
<del> newTest.err = errMessage + '\n' + stack;
<add> newTest.err = message + '\n' + stack;
<ide> newTest.stack = stack;
<del> newTest.message = errMessage;
<add> newTest.message = text.replace(/<code>(.*?)<\/code>/g, '$1');
<add> if (!(err instanceof chai.AssertionError)) {
<add> console.error(err);
<add> }
<ide> // RxJS catch expects an observable as a return
<ide> return of(newTest);
<ide> }) | 1 |
Mixed | Ruby | drop microseconds in job argument assertions | 7f038621dfd7eba316b601b010cbf442b63ea17e | <ide><path>activejob/CHANGELOG.md
<add>* Make job argument assertions with `Time`, `ActiveSupport::TimeWithZone`, and `DateTime` work by dropping microseconds. Microsecond precision is lost during serialization.
<add>
<add> *Gannon McGibbon*
<add>
<add>
<ide> ## Rails 6.0.0.beta3 (March 11, 2019) ##
<ide>
<ide> * No changes.
<ide><path>activejob/lib/active_job/test_helper.rb
<ide> def flush_enqueued_jobs(only: nil, except: nil, queue: nil)
<ide> def prepare_args_for_assertion(args)
<ide> args.dup.tap do |arguments|
<ide> arguments[:at] = arguments[:at].to_f if arguments[:at]
<add> arguments[:args] = round_time_arguments(arguments[:args]) if arguments[:args]
<add> end
<add> end
<add>
<add> def round_time_arguments(argument)
<add> case argument
<add> when Time, ActiveSupport::TimeWithZone, DateTime
<add> argument.change(usec: 0)
<add> when Hash
<add> argument.transform_values { |value| round_time_arguments(value) }
<add> when Array
<add> argument.map { |element| round_time_arguments(element) }
<add> else
<add> argument
<ide> end
<ide> end
<ide>
<ide><path>activejob/test/cases/test_helper_test.rb
<ide> def test_assert_enqueued_with_selective_args_fails
<ide> end
<ide> end
<ide>
<add> def test_assert_enqueued_with_time
<add> now = Time.now
<add> args = [{ argument1: [now] }]
<add>
<add> assert_enqueued_with(job: MultipleKwargsJob, args: args) do
<add> MultipleKwargsJob.perform_later(argument1: [now])
<add> end
<add> end
<add>
<add> def test_assert_enqueued_with_date_time
<add> now = DateTime.now
<add> args = [{ argument1: [now] }]
<add>
<add> assert_enqueued_with(job: MultipleKwargsJob, args: args) do
<add> MultipleKwargsJob.perform_later(argument1: [now])
<add> end
<add> end
<add>
<add> def test_assert_enqueued_with_time_with_zone
<add> now = Time.now.in_time_zone("Tokyo")
<add> args = [{ argument1: [now] }]
<add>
<add> assert_enqueued_with(job: MultipleKwargsJob, args: args) do
<add> MultipleKwargsJob.perform_later(argument1: [now])
<add> end
<add> end
<add>
<ide> def test_assert_enqueued_with_with_no_block_args
<ide> assert_raise ArgumentError do
<ide> NestedJob.set(wait_until: Date.tomorrow.noon).perform_later
<ide> def test_assert_performed_with_selective_args_fails
<ide> end
<ide> end
<ide>
<add> def test_assert_performed_with_time
<add> now = Time.now
<add> args = [{ argument1: { now: now } }]
<add>
<add> assert_enqueued_with(job: MultipleKwargsJob, args: args) do
<add> MultipleKwargsJob.perform_later(argument1: { now: now })
<add> end
<add> end
<add>
<add> def test_assert_performed_with_date_time
<add> now = DateTime.now
<add> args = [{ argument1: { now: now } }]
<add>
<add> assert_enqueued_with(job: MultipleKwargsJob, args: args) do
<add> MultipleKwargsJob.perform_later(argument1: { now: now })
<add> end
<add> end
<add>
<add> def test_assert_performed_with_time_with_zone
<add> now = Time.now.in_time_zone("Tokyo")
<add> args = [{ argument1: { now: now } }]
<add>
<add> assert_enqueued_with(job: MultipleKwargsJob, args: args) do
<add> MultipleKwargsJob.perform_later(argument1: { now: now })
<add> end
<add> end
<add>
<ide> def test_assert_performed_with_with_global_id_args
<ide> ricardo = Person.new(9)
<ide> assert_performed_with(job: HelloJob, args: [ricardo]) do | 3 |
PHP | PHP | remove "password" validation key | c532e14680c01fcdc6e9531046cc4bafe9073254 | <ide><path>lang/en/validation.php
<ide> 'not_in' => 'The selected :attribute is invalid.',
<ide> 'not_regex' => 'The :attribute format is invalid.',
<ide> 'numeric' => 'The :attribute must be a number.',
<del> 'password' => 'The password is incorrect.',
<ide> 'present' => 'The :attribute field must be present.',
<ide> 'prohibited' => 'The :attribute field is prohibited.',
<ide> 'prohibited_if' => 'The :attribute field is prohibited when :other is :value.', | 1 |
Text | Text | add quotes in test description | 1a3c038119e1fc306fb752df4b5e8af2b135fa3e | <ide><path>curriculum/challenges/english/06-quality-assurance/quality-assurance-projects/sudoku-solver.md
<ide> async (getUserInput) => {
<ide> };
<ide> ```
<ide>
<del>If the object submitted to `/api/check` is missing `puzzle`, `coordinate` or `value`, the returned value will be `{ error: Required field(s) missing }`
<add>If the object submitted to `/api/check` is missing `puzzle`, `coordinate` or `value`, the returned value will be `{ error: 'Required field(s) missing' }`
<ide>
<ide> ```js
<ide> async (getUserInput) => { | 1 |
Ruby | Ruby | use extlib accessor for new callbacks | 67f9b39bd05678881e200ddeed02b2bce9744ac8 | <ide><path>activesupport/lib/active_support/new_callbacks.rb
<ide> def _run__#{klass.split("::").last}__#{kind}__#{key}__callbacks
<ide> def define_callbacks(*symbols)
<ide> terminator = symbols.pop if symbols.last.is_a?(String)
<ide> symbols.each do |symbol|
<del> self.class_inheritable_accessor("_#{symbol}_terminator")
<add> self.extlib_inheritable_accessor("_#{symbol}_terminator")
<ide> self.send("_#{symbol}_terminator=", terminator)
<ide> self.class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
<del> class_inheritable_accessor :_#{symbol}_callbacks
<add> extlib_inheritable_accessor :_#{symbol}_callbacks
<ide> self._#{symbol}_callbacks = CallbackChain.new(:#{symbol})
<ide>
<ide> def self.#{symbol}_callback(*filters, &blk) | 1 |
Javascript | Javascript | allow leading period in multiline input | 451254ed25a3b9860d7b45dade6ed05b629d6bbd | <ide><path>lib/repl.js
<ide> function REPLServer(prompt,
<ide> var rest = matches && matches[2];
<ide> if (self.parseREPLKeyword(keyword, rest) === true) {
<ide> return;
<del> } else {
<add> } else if (!self.bufferedCommand) {
<ide> self.outputStream.write('Invalid REPL keyword\n');
<ide> skipCatchall = true;
<ide> }
<ide><path>test/parallel/test-repl.js
<ide> function error_test() {
<ide> expect: prompt_multiline },
<ide> { client: client_unix, send: '+ ".2"}`',
<ide> expect: `'io.js 1.0.2'\n${prompt_unix}` },
<add> // Dot prefix in multiline commands aren't treated as commands
<add> { client: client_unix, send: '("a"',
<add> expect: prompt_multiline },
<add> { client: client_unix, send: '.charAt(0))',
<add> expect: `'a'\n${prompt_unix}` },
<ide> // Floating point numbers are not interpreted as REPL commands.
<ide> { client: client_unix, send: '.1234',
<ide> expect: '0.1234' }, | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.