content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
PHP
PHP
add tests for radio options and string disabled
49299f7f43262c257d3b39d6d2ff5f2abca456f3
<ide><path>tests/TestCase/View/Widget/RadioTest.php <ide> public function testRenderDisabled() { <ide> ]; <ide> $this->assertTags($result, $expected); <ide> <add> $data['disabled'] = 'a string'; <add> $result = $radio->render($data); <add> $this->assertTags($result, $expected); <add> <ide> $data['disabled'] = ['1']; <ide> $result = $radio->render($data); <ide> $expected = [
1
PHP
PHP
add unsigned support to mysql
9e4c94b0a87f406f42047f6ff49f1a64bf737de2
<ide><path>Cake/Database/Schema/MysqlSchema.php <ide> <?php <ide> /** <del> * PHP Version 5.4 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide> <ide> /** <ide> * Schema generation/reflection features for MySQL <del> * <ide> */ <ide> class MysqlSchema extends BaseSchema { <ide> <ide> /** <ide> * {@inheritdoc} <del> * <ide> */ <ide> public function listTablesSql($config) { <ide> return ['SHOW TABLES FROM ' . $this->_driver->quoteIdentifier($config['database']), []]; <ide> } <ide> <ide> /** <ide> * {@inheritdoc} <del> * <ide> */ <ide> public function describeTableSql($name, $config) { <ide> return ['SHOW FULL COLUMNS FROM ' . $this->_driver->quoteIdentifier($name), []]; <ide> } <ide> <ide> /** <ide> * {@inheritdoc} <del> * <ide> */ <ide> public function describeIndexSql($table, $config) { <ide> return ['SHOW INDEXES FROM ' . $this->_driver->quoteIdentifier($table), []]; <ide> public function describeIndexSql($table, $config) { <ide> * @throws Cake\Database\Exception When column type cannot be parsed. <ide> */ <ide> protected function _convertColumn($column) { <del> preg_match('/([a-z]+)(?:\(([0-9,]+)\))?/i', $column, $matches); <add> preg_match('/([a-z]+)(?:\(([0-9,]+)\))?\s*([a-z]+)?/i', $column, $matches); <ide> if (empty($matches)) { <ide> throw new Exception(__d('cake_dev', 'Unable to parse column type from "%s"', $column)); <ide> } <ide> protected function _convertColumn($column) { <ide> if (($col === 'tinyint' && $length === 1) || $col === 'boolean') { <ide> return ['type' => 'boolean', 'length' => null]; <ide> } <add> <add> $unsigned = (isset($matches[3]) && strtolower($matches[3]) === 'unsigned'); <ide> if (strpos($col, 'bigint') !== false || $col === 'bigint') { <del> return ['type' => 'biginteger', 'length' => $length]; <add> return ['type' => 'biginteger', 'length' => $length, 'unsigned' => $unsigned]; <ide> } <ide> if (strpos($col, 'int') !== false) { <del> return ['type' => 'integer', 'length' => $length]; <add> return ['type' => 'integer', 'length' => $length, 'unsigned' => $unsigned]; <ide> } <ide> if ($col === 'char' && $length === 36) { <ide> return ['type' => 'uuid', 'length' => null]; <ide> protected function _convertColumn($column) { <ide> return ['type' => 'binary', 'length' => $length]; <ide> } <ide> if (strpos($col, 'float') !== false || strpos($col, 'double') !== false) { <del> return ['type' => 'float', 'length' => $length, 'precision' => $precision]; <add> return [ <add> 'type' => 'float', <add> 'length' => $length, <add> 'precision' => $precision, <add> 'unsigned' => $unsigned <add> ]; <ide> } <ide> if (strpos($col, 'decimal') !== false) { <del> return ['type' => 'decimal', 'length' => $length, 'precision' => $precision]; <add> return [ <add> 'type' => 'decimal', <add> 'length' => $length, <add> 'precision' => $precision, <add> 'unsigned' => $unsigned <add> ]; <ide> } <ide> return ['type' => 'text', 'length' => null]; <ide> } <ide> public function columnSql(Table $table, $name) { <ide> if (in_array($data['type'], $hasLength, true) && isset($data['length'])) { <ide> $out .= '(' . (int)$data['length'] . ')'; <ide> } <add> <ide> $hasPrecision = ['float', 'decimal']; <ide> if ( <ide> in_array($data['type'], $hasPrecision, true) && <ide> (isset($data['length']) || isset($data['precision'])) <ide> ) { <ide> $out .= '(' . (int)$data['length'] . ',' . (int)$data['precision'] . ')'; <ide> } <add> <add> $hasUnsigned = ['float', 'decimal', 'integer', 'biginteger']; <add> if ( <add> in_array($data['type'], $hasUnsigned, true) && <add> isset($data['unsigned']) && $data['unsigned'] === true <add> ) { <add> $out .= ' UNSIGNED'; <add> } <add> <ide> if (isset($data['null']) && $data['null'] === false) { <ide> $out .= ' NOT NULL'; <ide> } <ide><path>Cake/Test/TestCase/Database/Schema/MysqlSchemaTest.php <ide> <?php <ide> /** <del> * PHP Version 5.4 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide> public static function convertColumnProvider() { <ide> ], <ide> [ <ide> 'TINYINT(2)', <del> ['type' => 'integer', 'length' => 2] <add> ['type' => 'integer', 'length' => 2, 'unsigned' => false] <ide> ], <ide> [ <ide> 'INTEGER(11)', <del> ['type' => 'integer', 'length' => 11] <add> ['type' => 'integer', 'length' => 11, 'unsigned' => false] <add> ], <add> [ <add> 'INTEGER(11) UNSIGNED', <add> ['type' => 'integer', 'length' => 11, 'unsigned' => true] <ide> ], <ide> [ <ide> 'BIGINT', <del> ['type' => 'biginteger', 'length' => null] <add> ['type' => 'biginteger', 'length' => null, 'unsigned' => false] <add> ], <add> [ <add> 'BIGINT UNSIGNED', <add> ['type' => 'biginteger', 'length' => null, 'unsigned' => true] <ide> ], <ide> [ <ide> 'VARCHAR(255)', <ide> public static function convertColumnProvider() { <ide> ], <ide> [ <ide> 'FLOAT', <del> ['type' => 'float', 'length' => null, 'precision' => null] <add> ['type' => 'float', 'length' => null, 'precision' => null, 'unsigned' => false] <ide> ], <ide> [ <ide> 'DOUBLE', <del> ['type' => 'float', 'length' => null, 'precision' => null] <add> ['type' => 'float', 'length' => null, 'precision' => null, 'unsigned' => false] <add> ], <add> [ <add> 'DOUBLE UNSIGNED', <add> ['type' => 'float', 'length' => null, 'precision' => null, 'unsigned' => true] <add> ], <add> [ <add> 'DECIMAL(11,2) UNSIGNED', <add> ['type' => 'decimal', 'length' => 11, 'precision' => 2, 'unsigned' => true] <ide> ], <ide> [ <ide> 'DECIMAL(11,2)', <del> ['type' => 'decimal', 'length' => 11, 'precision' => 2] <add> ['type' => 'decimal', 'length' => 11, 'precision' => 2, 'unsigned' => false] <ide> ], <ide> [ <ide> 'FLOAT(11,2)', <del> ['type' => 'float', 'length' => 11, 'precision' => 2] <add> ['type' => 'float', 'length' => 11, 'precision' => 2, 'unsigned' => false] <add> ], <add> [ <add> 'FLOAT(11,2) UNSIGNED', <add> ['type' => 'float', 'length' => 11, 'precision' => 2, 'unsigned' => true] <ide> ], <ide> [ <ide> 'DOUBLE(10,4)', <del> ['type' => 'float', 'length' => 10, 'precision' => 4] <add> ['type' => 'float', 'length' => 10, 'precision' => 4, 'unsigned' => false] <add> ], <add> [ <add> 'DOUBLE(10,4) UNSIGNED', <add> ['type' => 'float', 'length' => 10, 'precision' => 4, 'unsigned' => true] <ide> ], <ide> ]; <ide> } <ide> public function testDescribeTable() { <ide> 'id' => [ <ide> 'type' => 'biginteger', <ide> 'null' => false, <add> 'unsigned' => false, <ide> 'default' => null, <ide> 'length' => 20, <ide> 'precision' => null, <del> 'fixed' => null, <ide> 'comment' => null, <ide> ], <ide> 'title' => [ <ide> public function testDescribeTable() { <ide> 'default' => null, <ide> 'length' => null, <ide> 'precision' => null, <del> 'fixed' => null, <ide> 'comment' => null, <ide> ], <ide> 'author_id' => [ <ide> 'type' => 'integer', <ide> 'null' => false, <add> 'unsigned' => false, <ide> 'default' => null, <ide> 'length' => 11, <ide> 'precision' => null, <del> 'fixed' => null, <ide> 'comment' => null, <ide> ], <ide> 'published' => [ <ide> public function testDescribeTable() { <ide> 'default' => 0, <ide> 'length' => null, <ide> 'precision' => null, <del> 'fixed' => null, <ide> 'comment' => null, <ide> ], <ide> 'allow_comments' => [ <ide> public function testDescribeTable() { <ide> 'default' => 0, <ide> 'length' => null, <ide> 'precision' => null, <del> 'fixed' => null, <ide> 'comment' => null, <ide> ], <ide> 'created' => [ <ide> public function testDescribeTable() { <ide> 'default' => null, <ide> 'length' => null, <ide> 'precision' => null, <del> 'fixed' => null, <ide> 'comment' => null, <ide> ], <ide> ]; <ide> public static function columnSqlProvider() { <ide> ['type' => 'integer', 'length' => 11], <ide> '`post_id` INTEGER(11)' <ide> ], <add> [ <add> 'post_id', <add> ['type' => 'integer', 'length' => 11, 'unsigned' => true], <add> '`post_id` INTEGER(11) UNSIGNED' <add> ], <ide> [ <ide> 'post_id', <ide> ['type' => 'biginteger', 'length' => 20], <ide> '`post_id` BIGINT' <ide> ], <add> [ <add> 'post_id', <add> ['type' => 'biginteger', 'length' => 20, 'unsigned' => true], <add> '`post_id` BIGINT UNSIGNED' <add> ], <ide> // Decimal <ide> [ <ide> 'value', <ide> public static function columnSqlProvider() { <ide> ], <ide> [ <ide> 'value', <del> ['type' => 'decimal', 'length' => 11], <del> '`value` DECIMAL(11,0)' <add> ['type' => 'decimal', 'length' => 11, 'unsigned' => true], <add> '`value` DECIMAL(11,0) UNSIGNED' <ide> ], <ide> [ <ide> 'value', <ide> public static function columnSqlProvider() { <ide> // Float <ide> [ <ide> 'value', <del> ['type' => 'float'], <add> ['type' => 'float', 'unsigned'], <ide> '`value` FLOAT' <ide> ], <add> [ <add> 'value', <add> ['type' => 'float', 'unsigned' => true], <add> '`value` FLOAT UNSIGNED' <add> ], <ide> [ <ide> 'value', <ide> ['type' => 'float', 'length' => 11, 'precision' => 3],
2
Text
Text
improve the workflow to test release binaries
7ceb624dcec8cea3086f2ef78e53f5d1f554057f
<ide><path>doc/contributing/releases.md <ide> the build before moving forward. Use the following list as a baseline: <ide> must be in the expected updated version) <ide> * npm version (check it matches what we expect) <ide> * Run the test suite against the built binaries (optional) <add> * Remember to use the proposal branch <add> * Run `make build-addons` before running the tests <add> * Remove `config.gypi` file <ide> <ide> ```console <ide> ./tools/test.py --shell ~/Downloads/node-v18.5.0-linux-x64/bin/node <ide> ``` <ide> <del><sup>There may be test issues if the branch used to test does not match the Node.js binary.</sup> <del> <ide> ### 11. Tag and sign the release commit <ide> <ide> Once you have produced builds that you're happy with, create a new tag. By
1
Mixed
Javascript
fix unallocated deprecation code
193926ecabe144d622e38aad89ba442df3e2114a
<ide><path>doc/api/deprecations.md <ide> Type: Runtime <ide> <ide> `REPLServer.parseREPLKeyword()` was removed from userland visibility. <ide> <del><a id="DEP00XX"></a> <del>### DEP00XX: tls.parseCertString() <add><a id="DEP0076"></a> <add>### DEP0076: tls.parseCertString() <ide> <ide> Type: Runtime <ide> <ide><path>lib/tls.js <ide> exports.parseCertString = internalUtil.deprecate( <ide> internalTLS.parseCertString, <ide> 'tls.parseCertString() is deprecated. ' + <ide> 'Please use querystring.parse() instead.', <del> 'DEP00XX'); <add> 'DEP0076'); <ide> <ide> // Public API <ide> exports.createSecureContext = require('_tls_common').createSecureContext;
2
Javascript
Javascript
remove unused frustum bounding box
bdf738fb9048c279b7599889c60800e92e0f2b78
<ide><path>examples/jsm/csm/FrustumBoundingBox.js <del>/** <del> * @author vHawk / https://github.com/vHawk/ <del> */ <del> <del>export default class FrustumBoundingBox { <del> <del> constructor() { <del> <del> this.min = { <del> x: 0, <del> y: 0, <del> z: 0 <del> }; <del> this.max = { <del> x: 0, <del> y: 0, <del> z: 0 <del> }; <del> <del> } <del> <del> fromFrustum( frustum ) { <del> <del> const vertices = []; <del> <del> for ( let i = 0; i < 4; i ++ ) { <del> <del> vertices.push( frustum.vertices.near[ i ] ); <del> vertices.push( frustum.vertices.far[ i ] ); <del> <del> } <del> <del> this.min = { <del> x: vertices[ 0 ].x, <del> y: vertices[ 0 ].y, <del> z: vertices[ 0 ].z <del> }; <del> this.max = { <del> x: vertices[ 0 ].x, <del> y: vertices[ 0 ].y, <del> z: vertices[ 0 ].z <del> }; <del> <del> for ( let i = 1; i < 8; i ++ ) { <del> <del> this.min.x = Math.min( this.min.x, vertices[ i ].x ); <del> this.min.y = Math.min( this.min.y, vertices[ i ].y ); <del> this.min.z = Math.min( this.min.z, vertices[ i ].z ); <del> this.max.x = Math.max( this.max.x, vertices[ i ].x ); <del> this.max.y = Math.max( this.max.y, vertices[ i ].y ); <del> this.max.z = Math.max( this.max.z, vertices[ i ].z ); <del> <del> } <del> <del> return this; <del> <del> } <del> <del> getSize() { <del> <del> this.size = { <del> x: this.max.x - this.min.x, <del> y: this.max.y - this.min.y, <del> z: this.max.z - this.min.z <del> }; <del> <del> return this.size; <del> <del> } <del> <del> getCenter( margin ) { <del> <del> this.center = { <del> x: ( this.max.x + this.min.x ) / 2, <del> y: ( this.max.y + this.min.y ) / 2, <del> z: this.max.z + margin <del> }; <del> <del> return this.center; <del> <del> } <del> <del>}
1
Javascript
Javascript
fix lint warnings
753bfcf7c7f39fcee26ea23fc71554c2e6129f87
<ide><path>extensions/firefox/bootstrap.js <add>/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ <add>/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */ <add> <add>'use strict'; <add> <ide> let Cc = Components.classes; <ide> let Ci = Components.interfaces; <ide> let Cm = Components.manager; <ide> let Cu = Components.utils; <ide> <del>Cu.import("resource://gre/modules/Services.jsm"); <add>Cu.import('resource://gre/modules/Services.jsm'); <ide> <ide> function log(str) { <del> dump(str + "\n"); <del>}; <add> dump(str + '\n'); <add>} <ide> <ide> function startup(aData, aReason) { <del> let manifestPath = "chrome.manifest"; <del> let file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsILocalFile); <add> let manifestPath = 'chrome.manifest'; <add> let file = Cc['@mozilla.org/file/local;1'].createInstance(Ci.nsILocalFile); <ide> try { <ide> file.initWithPath(aData.installPath.path); <ide> file.append(manifestPath); <ide> Cm.QueryInterface(Ci.nsIComponentRegistrar).autoRegister(file); <del> } catch(e) { <add> } catch (e) { <ide> log(e); <ide> } <del>}; <add>} <ide> <ide> function shutdown(aData, aReason) { <del>}; <add>} <ide> <ide> function install(aData, aReason) { <del> let url = "chrome://pdf.js/content/web/viewer.html?file=%s"; <del> Services.prefs.setCharPref("extensions.pdf.js.url", url); <del>}; <add> let url = 'chrome://pdf.js/content/web/viewer.html?file=%s'; <add> Services.prefs.setCharPref('extensions.pdf.js.url', url); <add>} <ide> <ide><path>extensions/firefox/components/pdfContentHandler.js <add>/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ <add>/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */ <add> <add>'use strict'; <add> <ide> const Cc = Components.classes; <ide> const Ci = Components.interfaces; <ide> const Cr = Components.results; <ide> const Cu = Components.utils; <ide> <del>const PDF_CONTENT_TYPE = "application/pdf"; <add>const PDF_CONTENT_TYPE = 'application/pdf'; <ide> <del>Cu.import("resource://gre/modules/XPCOMUtils.jsm"); <del>Cu.import("resource://gre/modules/Services.jsm"); <add>Cu.import('resource://gre/modules/XPCOMUtils.jsm'); <add>Cu.import('resource://gre/modules/Services.jsm'); <ide> <ide> // TODO <ide> // Add some download progress event <ide> <ide> function log(aMsg) { <del> let msg = "pdfContentHandler.js: " + (aMsg.join ? aMsg.join("") : aMsg); <del> Cc["@mozilla.org/consoleservice;1"].getService(Ci.nsIConsoleService) <add> let msg = 'pdfContentHandler.js: ' + (aMsg.join ? aMsg.join('') : aMsg); <add> Cc['@mozilla.org/consoleservice;1'].getService(Ci.nsIConsoleService) <ide> .logStringMessage(msg); <del> dump(msg + "\n"); <del>}; <add> dump(msg + '\n'); <add>} <ide> <ide> function loadDocument(aWindow, aDocumentUrl) { <del> let xhr = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"] <add> let xhr = Cc['@mozilla.org/xmlextras/xmlhttprequest;1'] <ide> .createInstance(Ci.nsIXMLHttpRequest); <del> xhr.open("GET", aDocumentUrl); <del> xhr.mozResponseType = xhr.responseType = "arraybuffer"; <add> xhr.open('GET', aDocumentUrl); <add> xhr.mozResponseType = xhr.responseType = 'arraybuffer'; <ide> xhr.onreadystatechange = function() { <ide> if (xhr.readyState == 4 && xhr.status == 200) { <ide> let data = (xhr.mozResponseArrayBuffer || xhr.mozResponse || <ide> xhr.responseArrayBuffer || xhr.response); <ide> try { <ide> var view = new Uint8Array(data); <ide> <del> // I think accessing aWindow.wrappedJSObject returns a <add> // I think accessing aWindow.wrappedJSObject returns a <ide> // XPCSafeJSObjectWrapper and so it is safe but mrbkap can confirm that <ide> let window = aWindow.wrappedJSObject; <ide> var arrayBuffer = new window.ArrayBuffer(data.byteLength); <ide> var view2 = new window.Uint8Array(arrayBuffer); <ide> view2.set(view); <ide> <del> let evt = window.document.createEvent("CustomEvent"); <del> evt.initCustomEvent("pdfloaded", false, false, arrayBuffer); <add> let evt = window.document.createEvent('CustomEvent'); <add> evt.initCustomEvent('pdfloaded', false, false, arrayBuffer); <ide> window.document.dispatchEvent(evt); <del> } catch(e) { <del> log("Error - " + e); <add> } catch (e) { <add> log('Error - ' + e); <ide> } <ide> } <ide> }; <ide> xhr.send(null); <del>}; <add>} <ide> <ide> let WebProgressListener = { <ide> init: function(aWindow, aUrl) { <ide> let WebProgressListener = { <ide> .getInterface(Ci.nsIWebProgress); <ide> try { <ide> webProgress.removeProgressListener(this); <del> } catch(e) {} <add> } catch (e) {} <ide> webProgress.addProgressListener(this, flags); <ide> }, <ide> <del> onStateChange: function onStateChange(aWebProgress, aRequest, aStateFlags, aStatus) { <add> onStateChange: function onStateChange(aWebProgress, aRequest, aStateFlags, <add> aStatus) { <ide> const complete = Ci.nsIWebProgressListener.STATE_IS_WINDOW + <ide> Ci.nsIWebProgressListener.STATE_STOP; <ide> if ((aStateFlags & complete) == complete && this._locationHasChanged) { <ide> let WebProgressListener = { <ide> } <ide> }, <ide> <del> onProgressChange: function onProgressChange(aWebProgress, aRequest, aCurSelf, aMaxSelf, aCurTotal, aMaxTotal) { <add> onProgressChange: function onProgressChange(aWebProgress, aRequest, aCurSelf, <add> aMaxSelf, aCurTotal, aMaxTotal) { <ide> }, <ide> <del> onLocationChange: function onLocationChange(aWebProgress, aRequest, aLocationURI) { <add> onLocationChange: function onLocationChange(aWebProgress, aRequest, <add> aLocationURI) { <ide> this._locationHasChanged = true; <ide> }, <ide> <del> onStatusChange: function onStatusChange(aWebProgress, aRequest, aStatus, aMessage) { <add> onStatusChange: function onStatusChange(aWebProgress, aRequest, aStatus, <add> aMessage) { <ide> }, <ide> <ide> onSecurityChange: function onSecurityChange(aWebProgress, aRequest, aState) { <ide> pdfContentHandler.prototype = { <ide> WebProgressListener.init(window, uri.spec); <ide> <ide> try { <del> let url = Services.prefs.getCharPref("extensions.pdf.js.url"); <del> url = url.replace("%s", uri.spec); <add> let url = Services.prefs.getCharPref('extensions.pdf.js.url'); <add> url = url.replace('%s', uri.spec); <ide> window.location = url; <del> } catch(e) { <del> log("Error - " + e); <add> } catch (e) { <add> log('Error - ' + e); <ide> } <ide> }, <ide> <del> classID: Components.ID("{2278dfd0-b75c-11e0-8257-1ba3d93c9f1a}"), <del> QueryInterface: XPCOMUtils.generateQI([Ci.nsIContentHandler]), <add> classID: Components.ID('{2278dfd0-b75c-11e0-8257-1ba3d93c9f1a}'), <add> QueryInterface: XPCOMUtils.generateQI([Ci.nsIContentHandler]) <ide> }; <ide> <ide> var NSGetFactory = XPCOMUtils.generateNSGetFactory([pdfContentHandler]); <ide><path>pdf.js <ide> var Catalog = (function catalogCatalog() { <ide> })(); <ide> <ide> var PDFDoc = (function pdfDoc() { <del> function constructor(arg, callback) { <add> function constructor(arg, callback) { <ide> // Stream argument <ide> if (typeof arg.isStream !== 'undefined') { <ide> init.call(this, arg); <ide> var PDFDoc = (function pdfDoc() { <ide> } <ide> else { <ide> error('Unknown argument type'); <del> } <add> } <ide> } <ide> <del> function init(stream){ <add> function init(stream) { <ide> assertWellFormed(stream.length > 0, 'stream must have data'); <ide> this.stream = stream; <ide> this.setup(); <ide> var PDFDoc = (function pdfDoc() { <ide> stream.pos += index; <ide> return true; /* found */ <ide> } <del> <add> <ide> constructor.prototype = { <ide> get linearization() { <ide> var length = this.stream.length;
3
PHP
PHP
fix behavior in postgres
7eac855e7ff3ec1dae0e2d998d1f0af39bac0b32
<ide><path>src/TestSuite/Fixture/SchemaLoader.php <ide> public function loadFiles( <ide> $cleaner->dropTables($connectionName); <ide> } <ide> <add> /** @var \Cake\Database\Connection $connection */ <ide> $connection = ConnectionManager::get($connectionName); <ide> foreach ($files as $file) { <ide> if (!file_exists($file)) { <ide> throw new InvalidArgumentException("Unable to load schema file `$file`."); <ide> } <del> <ide> $sql = file_get_contents($file); <del> $connection->execute($sql)->closeCursor(); <add> <add> // Use the underlying PDO connection so we can avoid prepared statements <add> // which don't support multiple queries in postgres. <add> $driver = $connection->getDriver(); <add> $driver->getConnection()->exec($sql); <ide> } <ide> <ide> if ($truncateTables) {
1
Ruby
Ruby
build changed dependencies first
0031e1947df198f16b86d9c1bf2b39ad15b1178e
<ide><path>Library/Contributions/cmd/brew-test-bot.rb <ide> def run <ide> end <ide> <ide> class Test <del> attr_reader :log_root, :category, :name, :formulae, :steps <add> attr_reader :log_root, :category, :name, :steps <ide> <ide> def initialize argument, tap=nil <ide> @hash = nil <ide> def formula formula <ide> reqs |= formula_object.devel.requirements.to_a <ide> end <ide> <del> <ide> begin <ide> deps.each {|f| CompilerSelector.new(f.to_formula).compiler } <ide> CompilerSelector.new(formula_object).compiler <ide> def formula formula <ide> end <ide> <ide> test "brew", "fetch", "--retry", *unchanged_dependencies unless unchanged_dependencies.empty? <del> test "brew", "fetch", "--retry", "--build-from-source", *changed_dependences unless changed_dependences.empty? <add> test "brew", "fetch", "--retry", "--build-bottle", *changed_dependences unless changed_dependences.empty? <ide> formula_fetch_options = [] <ide> formula_fetch_options << "--build-bottle" unless ARGV.include? "--no-bottle" <ide> formula_fetch_options << "--force" if ARGV.include? "--cleanup" <ide> def formula formula <ide> test "brew", "uninstall", "--devel", "--force", formula <ide> end <ide> end <del> test "brew", "uninstall", "--force", *dependencies unless dependencies.empty? <add> test "brew", "uninstall", "--force", *unchanged_dependencies unless unchanged_dependencies.empty? <ide> end <ide> <ide> def homebrew <ide> def check_results <ide> status == :passed <ide> end <ide> <add> def formulae <add> changed_formulae_dependents = {} <add> dependencies = [] <add> non_dependencies = [] <add> <add> @formulae.each do |formula| <add> formula_dependencies = `brew deps #{formula}`.split("\n") <add> unchanged_dependencies = formula_dependencies - @formulae <add> changed_dependences = formula_dependencies - unchanged_dependencies <add> changed_dependences.each do |changed_formula| <add> changed_formulae_dependents[changed_formula] ||= 0 <add> changed_formulae_dependents[changed_formula] += 1 <add> end <add> end <add> <add> changed_formulae = changed_formulae_dependents.sort do |a1,a2| <add> a2[1].to_i <=> a1[1].to_i <add> end <add> changed_formulae.map!(&:first) <add> unchanged_formulae = @formulae - changed_formulae <add> changed_formulae + unchanged_formulae <add> end <add> <ide> def run <ide> cleanup_before <ide> download
1
Go
Go
restore netns on teardown
afa41b16eacee43f75e83c088712e4b7a24b48e2
<ide><path>libnetwork/osl/sandbox_linux_test.go <ide> import ( <ide> "net" <ide> "os" <ide> "path/filepath" <del> "runtime" <ide> "strings" <ide> "syscall" <ide> "testing" <ide> func TestDisableIPv6DAD(t *testing.T) { <ide> if err != nil { <ide> t.Fatalf("Failed to create a new sandbox: %v", err) <ide> } <del> runtime.LockOSThread() <ide> defer destroyTest(t, s) <ide> <ide> n, ok := s.(*networkNamespace) <ide> func TestSetInterfaceIP(t *testing.T) { <ide> if err != nil { <ide> t.Fatalf("Failed to create a new sandbox: %v", err) <ide> } <del> runtime.LockOSThread() <ide> defer destroyTest(t, s) <ide> <ide> n, ok := s.(*networkNamespace) <ide> func TestLiveRestore(t *testing.T) { <ide> if err != nil { <ide> t.Fatalf("Failed to create a new sandbox: %v", err) <ide> } <del> runtime.LockOSThread() <ide> defer destroyTest(t, s) <ide> <ide> n, ok := s.(*networkNamespace) <ide> func TestSandboxCreateTwice(t *testing.T) { <ide> if err != nil { <ide> t.Fatalf("Failed to create a new sandbox: %v", err) <ide> } <del> runtime.LockOSThread() <ide> <ide> // Create another sandbox with the same key to see if we handle it <ide> // gracefully. <ide> s, err := NewSandbox(key, true, false) <ide> if err != nil { <ide> t.Fatalf("Failed to create a new sandbox: %v", err) <ide> } <del> runtime.LockOSThread() <ide> <ide> err = s.Destroy() <ide> if err != nil { <ide> func TestAddRemoveInterface(t *testing.T) { <ide> if err != nil { <ide> t.Fatalf("Failed to create a new sandbox: %v", err) <ide> } <del> runtime.LockOSThread() <ide> <ide> if s.Key() != key { <ide> t.Fatalf("s.Key() returned %s. Expected %s", s.Key(), key) <ide><path>libnetwork/testutils/context_unix.go <ide> package testutils <ide> <ide> import ( <ide> "runtime" <del> "syscall" <ide> "testing" <ide> <ide> "github.com/docker/docker/libnetwork/ns" <add> "github.com/vishvananda/netns" <ide> ) <ide> <ide> // SetupTestOSContext joins a new network namespace, and returns its associated <ide> import ( <ide> // <ide> // defer SetupTestOSContext(t)() <ide> func SetupTestOSContext(t *testing.T) func() { <del> runtime.LockOSThread() <del> if err := syscall.Unshare(syscall.CLONE_NEWNET); err != nil { <del> t.Fatalf("Failed to enter netns: %v", err) <add> origNS, err := netns.Get() <add> if err != nil { <add> t.Fatalf("Failed to open initial netns: %v", err) <add> } <add> restore := func() { <add> if err := netns.Set(origNS); err != nil { <add> t.Logf("Warning: failed to restore thread netns (%v)", err) <add> } else { <add> runtime.UnlockOSThread() <add> } <add> <add> if err := origNS.Close(); err != nil { <add> t.Logf("Warning: netns closing failed (%v)", err) <add> } <ide> } <ide> <del> fd, err := syscall.Open("/proc/self/ns/net", syscall.O_RDONLY, 0) <add> runtime.LockOSThread() <add> newNS, err := netns.New() <ide> if err != nil { <del> t.Fatal("Failed to open netns file") <add> // netns.New() is not atomic: it could have encountered an error <add> // after unsharing the current thread's network namespace. <add> restore() <add> t.Fatalf("Failed to enter netns: %v", err) <ide> } <ide> <ide> // Since we are switching to a new test namespace make <ide> // sure to re-initialize initNs context <ide> ns.Init() <ide> <del> runtime.LockOSThread() <del> <ide> return func() { <del> if err := syscall.Close(fd); err != nil { <add> if err := newNS.Close(); err != nil { <ide> t.Logf("Warning: netns closing failed (%v)", err) <ide> } <del> runtime.UnlockOSThread() <add> restore() <add> ns.Init() <ide> } <ide> }
2
PHP
PHP
fix typos in namespaces
10605040813ead7499c742e009f044a758a0fa95
<ide><path>src/Database/Query.php <ide> protected function _makeJoin($table, $conditions, $type) <ide> * @param array $types associative array of type names used to bind values to query <ide> * @param bool $overwrite whether to reset conditions with passed list or not <ide> * @see \Cake\Database\Type <del> * @see \Cake\Database\QueryExpression <add> * @see \Cake\Database\Expression\QueryExpression <ide> * @return $this <ide> */ <ide> public function where($conditions = null, $types = [], $overwrite = false) <ide> public function order($fields, $overwrite = false) <ide> * This method allows you to set complex expressions <ide> * as order conditions unlike order() <ide> * <del> * @param string|\Cake\Database\QueryExpression $field The field to order on. <add> * @param string|\Cake\Database\Expression\QueryExpression $field The field to order on. <ide> * @param bool $overwrite Whether or not to reset the order clauses. <ide> * @return $this <ide> */ <ide> public function orderAsc($field, $overwrite = false) <ide> * This method allows you to set complex expressions <ide> * as order conditions unlike order() <ide> * <del> * @param string|\Cake\Database\QueryExpression $field The field to order on. <add> * @param string|\Cake\Database\Expression\QueryExpression $field The field to order on. <ide> * @param bool $overwrite Whether or not to reset the order clauses. <ide> * @return $this <ide> */ <ide> public function type() <ide> * if required. <ide> * <ide> * You can optionally pass a single raw SQL string or an array or expressions in <del> * any format accepted by \Cake\Database\QueryExpression: <add> * any format accepted by \Cake\Database\Expression\QueryExpression: <ide> * <ide> * ``` <ide> * <ide><path>src/Database/Type.php <ide> public static function build($name) <ide> * Returns a Type object capable of converting a type identified by $name <ide> * <ide> * @param string $name The type identifier you want to set. <del> * @param \Cake\Databse\Type $instance The type instance you want to set. <add> * @param \Cake\Database\Type $instance The type instance you want to set. <ide> * @return void <ide> */ <ide> public static function set($name, Type $instance)
2
PHP
PHP
initialize $fixtures to null
0c9622514c34b9e93aa33291f6e786df4fcd8629
<ide><path>src/TestSuite/TestCase.php <ide> abstract class TestCase extends BaseTestCase <ide> */ <ide> public $fixtureManager; <ide> <add> /** <add> * Fixtures used by this test case. <add> * <add> * @var array|string <add> */ <add> public $fixtures = null; <add> <add> <ide> /** <ide> * By default, all fixtures attached to this class will be truncated and reloaded after each test. <ide> * Set this to false to handle manually
1
Go
Go
implement env within docker builder
e45aef0c82044be6a427502d4bbb0979074c2ba1
<ide><path>builder.go <ide> func (builder *Builder) Build(dockerfile io.Reader, stdout io.Writer) (*Image, e <ide> image, base *Image <ide> config *Config <ide> maintainer string <add> env map[string]string = make(map[string]string) <ide> tmpContainers map[string]struct{} = make(map[string]struct{}) <ide> tmpImages map[string]struct{} = make(map[string]struct{}) <ide> ) <ide> func (builder *Builder) Build(dockerfile io.Reader, stdout io.Writer) (*Image, e <ide> return nil, err <ide> } <ide> <add> for key, value := range env { <add> config.Env = append(config.Env, fmt.Sprintf("%s=%s", key, value)) <add> } <add> <ide> if cache, err := builder.getCachedImage(image, config); err != nil { <ide> return nil, err <ide> } else if cache != nil { <ide> func (builder *Builder) Build(dockerfile io.Reader, stdout io.Writer) (*Image, e <ide> break <ide> } <ide> <add> Debugf("Env -----> %v ------ %v\n", config.Env, env) <add> <ide> // Create the container and start it <ide> c, err := builder.Create(config) <ide> if err != nil { <ide> return nil, err <ide> } <add> <add> if os.Getenv("DEBUG") != "" { <add> out, _ := c.StdoutPipe() <add> err2, _ := c.StderrPipe() <add> go io.Copy(os.Stdout, out) <add> go io.Copy(os.Stdout, err2) <add> } <add> <ide> if err := c.Start(); err != nil { <ide> return nil, err <ide> } <ide> func (builder *Builder) Build(dockerfile io.Reader, stdout io.Writer) (*Image, e <ide> // use the base as the new image <ide> image = base <ide> <add> break <add> case "env": <add> tmp := strings.SplitN(arguments, " ", 2) <add> if len(tmp) != 2 { <add> return nil, fmt.Errorf("Invalid ENV format") <add> } <add> key := strings.Trim(tmp[0], " ") <add> value := strings.Trim(tmp[1], " ") <add> fmt.Fprintf(stdout, "ENV %s %s\n", key, value) <add> env[key] = value <add> if image != nil { <add> fmt.Fprintf(stdout, "===> %s\n", image.ShortId()) <add> } else { <add> fmt.Fprintf(stdout, "===> <nil>\n") <add> } <ide> break <ide> case "cmd": <ide> fmt.Fprintf(stdout, "CMD %s\n", arguments)
1
Javascript
Javascript
remove circular dependencies in react core
2ee66262db9fb91b0d0e9d64cefeb223074f8e05
<ide><path>src/core/ReactComponent.js <ide> var getReactRootElementInContainer = require('getReactRootElementInContainer'); <ide> var ReactCurrentOwner = require('ReactCurrentOwner'); <ide> var ReactDOMIDOperations = require('ReactDOMIDOperations'); <del>var ReactID = require('ReactID'); <ide> var ReactMarkupChecksum = require('ReactMarkupChecksum'); <add>var ReactMount = require('ReactMount'); <ide> var ReactOwner = require('ReactOwner'); <ide> var ReactReconcileTransaction = require('ReactReconcileTransaction'); <ide> var ReactUpdates = require('ReactUpdates'); <ide> var ReactComponent = { <ide> this.isMounted(), <ide> 'getDOMNode(): A component must be mounted to have a DOM node.' <ide> ); <del> return ReactID.getNode(this._rootNodeID); <add> return ReactMount.getNode(this._rootNodeID); <ide> }, <ide> <ide> /** <ide> var ReactComponent = { <ide> if (props.ref != null) { <ide> ReactOwner.removeComponentAsRefFrom(this, props.ref, props[OWNER]); <ide> } <del> ReactID.purgeID(this._rootNodeID); <add> ReactMount.purgeID(this._rootNodeID); <ide> this._rootNodeID = null; <ide> this._lifeCycleState = ComponentLifeCycle.UNMOUNTED; <ide> }, <ide><path>src/core/ReactDOMIDOperations.js <ide> var CSSPropertyOperations = require('CSSPropertyOperations'); <ide> var DOMChildrenOperations = require('DOMChildrenOperations'); <ide> var DOMPropertyOperations = require('DOMPropertyOperations'); <del>var ReactID = require('ReactID'); <add>var ReactMount = require('ReactMount'); <ide> <ide> var getTextContentAccessor = require('getTextContentAccessor'); <ide> var invariant = require('invariant'); <ide> var ReactDOMIDOperations = { <ide> * @internal <ide> */ <ide> updatePropertyByID: function(id, name, value) { <del> var node = ReactID.getNode(id); <add> var node = ReactMount.getNode(id); <ide> invariant( <ide> !INVALID_PROPERTY_ERRORS.hasOwnProperty(name), <ide> 'updatePropertyByID(...): %s', <ide> var ReactDOMIDOperations = { <ide> * @internal <ide> */ <ide> deletePropertyByID: function(id, name, value) { <del> var node = ReactID.getNode(id); <add> var node = ReactMount.getNode(id); <ide> invariant( <ide> !INVALID_PROPERTY_ERRORS.hasOwnProperty(name), <ide> 'updatePropertyByID(...): %s', <ide> var ReactDOMIDOperations = { <ide> * @internal <ide> */ <ide> updateStylesByID: function(id, styles) { <del> var node = ReactID.getNode(id); <add> var node = ReactMount.getNode(id); <ide> CSSPropertyOperations.setValueForStyles(node, styles); <ide> }, <ide> <ide> var ReactDOMIDOperations = { <ide> * @internal <ide> */ <ide> updateInnerHTMLByID: function(id, html) { <del> var node = ReactID.getNode(id); <add> var node = ReactMount.getNode(id); <ide> // HACK: IE8- normalize whitespace in innerHTML, removing leading spaces. <ide> // @see quirksmode.org/bugreports/archives/2004/11/innerhtml_and_t.html <ide> node.innerHTML = (html && html.__html || '').replace(/^ /g, '&nbsp;'); <ide> var ReactDOMIDOperations = { <ide> * @internal <ide> */ <ide> updateTextContentByID: function(id, content) { <del> var node = ReactID.getNode(id); <add> var node = ReactMount.getNode(id); <ide> node[textContentAccessor] = content; <ide> }, <ide> <ide> var ReactDOMIDOperations = { <ide> * @see {Danger.dangerouslyReplaceNodeWithMarkup} <ide> */ <ide> dangerouslyReplaceNodeWithMarkupByID: function(id, markup) { <del> var node = ReactID.getNode(id); <add> var node = ReactMount.getNode(id); <ide> DOMChildrenOperations.dangerouslyReplaceNodeWithMarkup(node, markup); <ide> }, <ide> <ide> var ReactDOMIDOperations = { <ide> * Detect if any elements were removed instead of blindly purging. <ide> */ <ide> manageChildrenByParentID: function(parentID, domOperations) { <del> var parent = ReactID.getNode(parentID); <add> var parent = ReactMount.getNode(parentID); <ide> DOMChildrenOperations.manageChildren(parent, domOperations); <ide> } <ide> <ide><path>src/core/ReactDefaultInjection.js <ide> var ReactDOMInput = require('ReactDOMInput'); <ide> var ReactDOMOption = require('ReactDOMOption'); <ide> var ReactDOMSelect = require('ReactDOMSelect'); <ide> var ReactDOMTextarea = require('ReactDOMTextarea'); <add>var ReactEventEmitter = require('ReactEventEmitter'); <add>var ReactEventTopLevelCallback = require('ReactEventTopLevelCallback'); <ide> <ide> var DefaultDOMPropertyConfig = require('DefaultDOMPropertyConfig'); <ide> var DOMProperty = require('DOMProperty'); <ide> var SimpleEventPlugin = require('SimpleEventPlugin'); <ide> var MobileSafariClickEventPlugin = require('MobileSafariClickEventPlugin'); <ide> <ide> function inject() { <add> ReactEventEmitter.TopLevelCallbackCreator = ReactEventTopLevelCallback; <ide> /** <ide> * Inject module for resolving DOM hierarchy and plugin ordering. <ide> */ <ide><path>src/core/ReactEventEmitter.js <ide> var ReactEventEmitter = { <ide> * reason, and only in some cases). <ide> * <ide> * @param {boolean} touchNotMouse Listen to touch events instead of mouse. <del> * @param {object} TopLevelCallbackCreator <ide> */ <del> ensureListening: function(touchNotMouse, TopLevelCallbackCreator) { <add> ensureListening: function(touchNotMouse) { <ide> invariant( <ide> ExecutionEnvironment.canUseDOM, <ide> 'ensureListening(...): Cannot toggle event listening in a Worker ' + <ide> 'thread. This is likely a bug in the framework. Please report ' + <ide> 'immediately.' <ide> ); <add> invariant( <add> ReactEventEmitter.TopLevelCallbackCreator, <add> 'ensureListening(...): Cannot be called without a top level callback ' + <add> 'creator being injected.' <add> ); <ide> if (!_isListening) { <del> ReactEventEmitter.TopLevelCallbackCreator = TopLevelCallbackCreator; <ide> listenAtTopLevel(touchNotMouse); <ide> _isListening = true; <ide> } <ide><path>src/core/ReactEventTopLevelCallback.js <ide> <ide> var ExecutionEnvironment = require('ExecutionEnvironment'); <ide> var ReactEventEmitter = require('ReactEventEmitter'); <del>var ReactID = require('ReactID'); <del>var ReactInstanceHandles = require('ReactInstanceHandles'); <add>var ReactMount = require('ReactMount'); <ide> <ide> var getEventTarget = require('getEventTarget'); <ide> <ide> var _topLevelListenersEnabled = true; <ide> <ide> /** <ide> * Top-level callback creator used to implement event handling using delegation. <del> * This is used via dependency injection in `ReactEventEmitter.ensureListening`. <add> * This is used via dependency injection. <ide> */ <ide> var ReactEventTopLevelCallback = { <ide> <ide> var ReactEventTopLevelCallback = { <ide> nativeEvent.srcElement !== nativeEvent.target) { <ide> nativeEvent.target = nativeEvent.srcElement; <ide> } <del> var topLevelTarget = ReactInstanceHandles.getFirstReactDOM( <add> var topLevelTarget = ReactMount.getFirstReactDOM( <ide> getEventTarget(nativeEvent) <ide> ) || ExecutionEnvironment.global; <del> var topLevelTargetID = ReactID.getID(topLevelTarget) || ''; <add> var topLevelTargetID = ReactMount.getID(topLevelTarget) || ''; <ide> ReactEventEmitter.handleTopLevel( <ide> topLevelType, <ide> topLevelTarget, <ide><path>src/core/ReactID.js <del>/** <del> * Copyright 2013 Facebook, Inc. <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> * @providesModule ReactID <del> * @typechecks static-only <del> */ <del> <del>"use strict"; <del> <del>var invariant = require('invariant'); <del>var ReactMount = require('ReactMount'); <del>var ATTR_NAME = 'data-reactid'; <del>var nodeCache = {}; <del> <del>/** <del> * Accessing node[ATTR_NAME] or calling getAttribute(ATTR_NAME) on a form <del> * element can return its control whose name or ID equals ATTR_NAME. All <del> * DOM nodes support `getAttributeNode` but this can also get called on <del> * other objects so just return '' if we're given something other than a <del> * DOM node (such as window). <del> * <del> * @param {?DOMElement|DOMWindow|DOMDocument|DOMTextNode} node DOM node. <del> * @return {string} ID of the supplied `domNode`. <del> */ <del>function getID(node) { <del> var id = internalGetID(node); <del> if (id) { <del> if (nodeCache.hasOwnProperty(id)) { <del> var cached = nodeCache[id]; <del> if (cached !== node) { <del> invariant( <del> !isValid(cached, id), <del> 'ReactID: Two valid but unequal nodes with the same `%s`: %s', <del> ATTR_NAME, id <del> ); <del> <del> nodeCache[id] = node; <del> } <del> } else { <del> nodeCache[id] = node; <del> } <del> } <del> <del> return id; <del>} <del> <del>function internalGetID(node) { <del> // If node is something like a window, document, or text node, none of <del> // which support attributes or a .getAttribute method, gracefully return <del> // the empty string, as if the attribute were missing. <del> return node && node.getAttribute && node.getAttribute(ATTR_NAME) || ''; <del>} <del> <del>/** <del> * Sets the React-specific ID of the given node. <del> * <del> * @param {DOMElement} node The DOM node whose ID will be set. <del> * @param {string} id The value of the ID attribute. <del> */ <del>function setID(node, id) { <del> var oldID = internalGetID(node); <del> if (oldID !== id) { <del> delete nodeCache[oldID]; <del> } <del> node.setAttribute(ATTR_NAME, id); <del> nodeCache[id] = node; <del>} <del> <del>/** <del> * Finds the node with the supplied React-generated DOM ID. <del> * <del> * @param {string} id A React-generated DOM ID. <del> * @return {DOMElement} DOM node with the suppled `id`. <del> * @internal <del> */ <del>function getNode(id) { <del> if (!nodeCache.hasOwnProperty(id) || !isValid(nodeCache[id], id)) { <del> nodeCache[id] = ReactMount.findReactNodeByID(id); <del> } <del> return nodeCache[id]; <del>} <del> <del>/** <del> * A node is "valid" if it is contained by a currently mounted container. <del> * <del> * This means that the node does not have to be contained by a document in <del> * order to be considered valid. <del> * <del> * @param {?DOMElement} node The candidate DOM node. <del> * @param {string} id The expected ID of the node. <del> * @return {boolean} Whether the node is contained by a mounted container. <del> */ <del>function isValid(node, id) { <del> if (node) { <del> invariant( <del> internalGetID(node) === id, <del> 'ReactID: Unexpected modification of `%s`', <del> ATTR_NAME <del> ); <del> <del> var container = ReactMount.findReactContainerForID(id); <del> if (container && contains(container, node)) { <del> return true; <del> } <del> } <del> <del> return false; <del>} <del> <del>function contains(ancestor, descendant) { <del> if (ancestor.contains) { <del> // Supported natively in virtually all browsers, but not in jsdom. <del> return ancestor.contains(descendant); <del> } <del> <del> if (descendant === ancestor) { <del> return true; <del> } <del> <del> if (descendant.nodeType === 3) { <del> // If descendant is a text node, start from descendant.parentNode <del> // instead, so that we can assume all ancestors worth considering are <del> // element nodes with nodeType === 1. <del> descendant = descendant.parentNode; <del> } <del> <del> while (descendant && descendant.nodeType === 1) { <del> if (descendant === ancestor) { <del> return true; <del> } <del> descendant = descendant.parentNode; <del> } <del> <del> return false; <del>} <del> <del>/** <del> * Causes the cache to forget about one React-specific ID. <del> * <del> * @param {string} id The ID to forget. <del> */ <del>function purgeID(id) { <del> delete nodeCache[id]; <del>} <del> <del>exports.ATTR_NAME = ATTR_NAME; <del>exports.getID = getID; <del>exports.rawGetID = internalGetID; <del>exports.setID = setID; <del>exports.getNode = getNode; <del>exports.purgeID = purgeID; <ide><path>src/core/ReactInstanceHandles.js <ide> <ide> "use strict"; <ide> <del>var ReactID = require('ReactID'); <del> <ide> var invariant = require('invariant'); <ide> <ide> var SEPARATOR = '.'; <ide> var ReactInstanceHandles = { <ide> ); <ide> }, <ide> <del> /** <del> * True if the supplied `node` is rendered by React. <del> * <del> * @param {*} node DOM Element to check. <del> * @return {boolean} True if the DOM Element appears to be rendered by React. <del> * @internal <del> */ <del> isRenderedByReact: function(node) { <del> if (node.nodeType !== 1) { <del> // Not a DOMElement, therefore not a React component <del> return false; <del> } <del> var id = ReactID.getID(node); <del> return id ? id.charAt(0) === SEPARATOR : false; <del> }, <del> <del> /** <del> * Traverses up the ancestors of the supplied node to find a node that is a <del> * DOM representation of a React component. <del> * <del> * @param {*} node <del> * @return {?DOMEventTarget} <del> * @internal <del> */ <del> getFirstReactDOM: function(node) { <del> var current = node; <del> while (current && current.parentNode !== current) { <del> if (ReactInstanceHandles.isRenderedByReact(current)) { <del> return current; <del> } <del> current = current.parentNode; <del> } <del> return null; <del> }, <del> <del> /** <del> * Finds a node with the supplied `id` inside of the supplied `ancestorNode`. <del> * Exploits the ID naming scheme to perform the search quickly. <del> * <del> * @param {DOMEventTarget} ancestorNode Search from this root. <del> * @pararm {string} id ID of the DOM representation of the component. <del> * @return {DOMEventTarget} DOM node with the supplied `id`. <del> * @internal <del> */ <del> findComponentRoot: function(ancestorNode, id) { <del> var firstChildren = [ancestorNode.firstChild]; <del> var childIndex = 0; <del> <del> while (childIndex < firstChildren.length) { <del> var child = firstChildren[childIndex++]; <del> while (child) { <del> var childID = ReactID.getID(child); <del> if (childID) { <del> if (id === childID) { <del> return child; <del> } else if (isAncestorIDOf(childID, id)) { <del> // If we find a child whose ID is an ancestor of the given ID, <del> // then we can be sure that we only want to search the subtree <del> // rooted at this child, so we can throw out the rest of the <del> // search state. <del> firstChildren.length = childIndex = 0; <del> firstChildren.push(child.firstChild); <del> break; <del> } else { <del> // TODO This should not be necessary if the ID hierarchy is <del> // correct, but is occasionally necessary if the DOM has been <del> // modified in unexpected ways. <del> firstChildren.push(child.firstChild); <del> } <del> } else { <del> // If this child had no ID, then there's a chance that it was <del> // injected automatically by the browser, as when a `<table>` <del> // element sprouts an extra `<tbody>` child as a side effect of <del> // `.innerHTML` parsing. Optimistically continue down this <del> // branch, but not before examining the other siblings. <del> firstChildren.push(child.firstChild); <del> } <del> child = child.nextSibling; <del> } <del> } <del> <del> if (__DEV__) { <del> console.error( <del> 'Error while invoking `findComponentRoot` with the following ' + <del> 'ancestor node:', <del> ancestorNode <del> ); <del> } <del> invariant( <del> false, <del> 'findComponentRoot(..., %s): Unable to find element. This probably ' + <del> 'means the DOM was unexpectedly mutated (e.g. by the browser).', <del> id, <del> ReactID.getID(ancestorNode) <del> ); <del> }, <del> <ide> /** <ide> * Gets the DOM ID of the React component that is the root of the tree that <ide> * contains the React component with the supplied DOM ID. <ide> var ReactInstanceHandles = { <ide> * Exposed for unit testing. <ide> * @private <ide> */ <del> _getNextDescendantID: getNextDescendantID <add> _getNextDescendantID: getNextDescendantID, <add> <add> isAncestorIDOf: isAncestorIDOf, <add> <add> SEPARATOR: SEPARATOR <ide> <ide> }; <ide> <ide><path>src/core/ReactMount.js <ide> var invariant = require('invariant'); <ide> var getReactRootElementInContainer = require('getReactRootElementInContainer'); <ide> var ReactEventEmitter = require('ReactEventEmitter'); <ide> var ReactInstanceHandles = require('ReactInstanceHandles'); <del>var ReactEventTopLevelCallback = require('ReactEventTopLevelCallback'); <del>var ReactID = require('ReactID'); <add> <add>var SEPARATOR = ReactInstanceHandles.SEPARATOR; <add> <add>var ATTR_NAME = 'data-reactid'; <add>var nodeCache = {}; <ide> <ide> var $ = require('$'); <ide> <ide> if (__DEV__) { <ide> */ <ide> function getReactRootID(container) { <ide> var rootElement = getReactRootElementInContainer(container); <del> return rootElement && ReactID.getID(rootElement); <add> return rootElement && ReactMount.getID(rootElement); <add>} <add> <add>/** <add> * Accessing node[ATTR_NAME] or calling getAttribute(ATTR_NAME) on a form <add> * element can return its control whose name or ID equals ATTR_NAME. All <add> * DOM nodes support `getAttributeNode` but this can also get called on <add> * other objects so just return '' if we're given something other than a <add> * DOM node (such as window). <add> * <add> * @param {?DOMElement|DOMWindow|DOMDocument|DOMTextNode} node DOM node. <add> * @return {string} ID of the supplied `domNode`. <add> */ <add>function getID(node) { <add> var id = internalGetID(node); <add> if (id) { <add> if (nodeCache.hasOwnProperty(id)) { <add> var cached = nodeCache[id]; <add> if (cached !== node) { <add> invariant( <add> !isValid(cached, id), <add> 'ReactMount: Two valid but unequal nodes with the same `%s`: %s', <add> ATTR_NAME, id <add> ); <add> <add> nodeCache[id] = node; <add> } <add> } else { <add> nodeCache[id] = node; <add> } <add> } <add> <add> return id; <add>} <add> <add>function internalGetID(node) { <add> // If node is something like a window, document, or text node, none of <add> // which support attributes or a .getAttribute method, gracefully return <add> // the empty string, as if the attribute were missing. <add> return node && node.getAttribute && node.getAttribute(ATTR_NAME) || ''; <add>} <add> <add>/** <add> * Sets the React-specific ID of the given node. <add> * <add> * @param {DOMElement} node The DOM node whose ID will be set. <add> * @param {string} id The value of the ID attribute. <add> */ <add>function setID(node, id) { <add> var oldID = internalGetID(node); <add> if (oldID !== id) { <add> delete nodeCache[oldID]; <add> } <add> node.setAttribute(ATTR_NAME, id); <add> nodeCache[id] = node; <add>} <add> <add>/** <add> * Finds the node with the supplied React-generated DOM ID. <add> * <add> * @param {string} id A React-generated DOM ID. <add> * @return {DOMElement} DOM node with the suppled `id`. <add> * @internal <add> */ <add>function getNode(id) { <add> if (!nodeCache.hasOwnProperty(id) || !isValid(nodeCache[id], id)) { <add> nodeCache[id] = ReactMount.findReactNodeByID(id); <add> } <add> return nodeCache[id]; <add>} <add> <add>/** <add> * A node is "valid" if it is contained by a currently mounted container. <add> * <add> * This means that the node does not have to be contained by a document in <add> * order to be considered valid. <add> * <add> * @param {?DOMElement} node The candidate DOM node. <add> * @param {string} id The expected ID of the node. <add> * @return {boolean} Whether the node is contained by a mounted container. <add> */ <add>function isValid(node, id) { <add> if (node) { <add> invariant( <add> internalGetID(node) === id, <add> 'ReactMount: Unexpected modification of `%s`', <add> ATTR_NAME <add> ); <add> <add> var container = ReactMount.findReactContainerForID(id); <add> if (container && contains(container, node)) { <add> return true; <add> } <add> } <add> <add> return false; <add>} <add> <add>function contains(ancestor, descendant) { <add> if (ancestor.contains) { <add> // Supported natively in virtually all browsers, but not in jsdom. <add> return ancestor.contains(descendant); <add> } <add> <add> if (descendant === ancestor) { <add> return true; <add> } <add> <add> if (descendant.nodeType === 3) { <add> // If descendant is a text node, start from descendant.parentNode <add> // instead, so that we can assume all ancestors worth considering are <add> // element nodes with nodeType === 1. <add> descendant = descendant.parentNode; <add> } <add> <add> while (descendant && descendant.nodeType === 1) { <add> if (descendant === ancestor) { <add> return true; <add> } <add> descendant = descendant.parentNode; <add> } <add> <add> return false; <add>} <add> <add>/** <add> * Causes the cache to forget about one React-specific ID. <add> * <add> * @param {string} id The ID to forget. <add> */ <add>function purgeID(id) { <add> delete nodeCache[id]; <ide> } <ide> <ide> /** <ide> var ReactMount = { <ide> * Ensures that the top-level event delegation listener is set up. This will <ide> * be invoked some time before the first time any React component is rendered. <ide> * <del> * @param {object} TopLevelCallbackCreator <ide> * @private <ide> */ <del> prepareTopLevelEvents: function(TopLevelCallbackCreator) { <del> ReactEventEmitter.ensureListening( <del> ReactMount.useTouchEvents, <del> TopLevelCallbackCreator <del> ); <add> prepareTopLevelEvents: function() { <add> ReactEventEmitter.ensureListening(ReactMount.useTouchEvents); <ide> }, <ide> <ide> /** <ide> var ReactMount = { <ide> * @return {string} reactRoot ID prefix <ide> */ <ide> _registerComponent: function(nextComponent, container) { <del> ReactMount.prepareTopLevelEvents(ReactEventTopLevelCallback); <add> ReactMount.prepareTopLevelEvents(); <ide> <ide> var reactRootID = ReactMount.registerContainer(container); <ide> instanceByReactRootID[reactRootID] = nextComponent; <ide> var ReactMount = { <ide> <ide> var reactRootElement = getReactRootElementInContainer(container); <ide> var containerHasReactMarkup = <del> reactRootElement && <del> ReactInstanceHandles.isRenderedByReact(reactRootElement); <add> reactRootElement && ReactMount.isRenderedByReact(reactRootElement); <ide> <ide> var shouldReuseMarkup = containerHasReactMarkup && !registeredComponent; <ide> <ide> var ReactMount = { <ide> var rootElement = rootElementsByReactRootID[reactRootID]; <ide> if (rootElement && rootElement.parentNode !== container) { <ide> invariant( <del> // Call rawGetID here because getID calls isValid which calls <add> // Call internalGetID here because getID calls isValid which calls <ide> // findReactContainerForID (this function). <del> ReactID.rawGetID(rootElement) === reactRootID, <add> internalGetID(rootElement) === reactRootID, <ide> 'ReactMount: Root element ID differed from reactRootID.' <ide> ); <ide> <ide> var containerChild = container.firstChild; <ide> if (containerChild && <del> reactRootID === ReactID.rawGetID(containerChild)) { <add> reactRootID === internalGetID(containerChild)) { <ide> // If the container has a new child with the same ID as the old <ide> // root element, then rootElementsByReactRootID[reactRootID] is <ide> // just stale and needs to be updated. The case that deserves a <ide> var ReactMount = { <ide> */ <ide> findReactNodeByID: function(id) { <ide> var reactRoot = ReactMount.findReactContainerForID(id); <del> return ReactInstanceHandles.findComponentRoot(reactRoot, id); <del> } <add> return ReactMount.findComponentRoot(reactRoot, id); <add> }, <add> <add> /** <add> * True if the supplied `node` is rendered by React. <add> * <add> * @param {*} node DOM Element to check. <add> * @return {boolean} True if the DOM Element appears to be rendered by React. <add> * @internal <add> */ <add> isRenderedByReact: function(node) { <add> if (node.nodeType !== 1) { <add> // Not a DOMElement, therefore not a React component <add> return false; <add> } <add> var id = ReactMount.getID(node); <add> return id ? id.charAt(0) === SEPARATOR : false; <add> }, <add> <add> /** <add> * Traverses up the ancestors of the supplied node to find a node that is a <add> * DOM representation of a React component. <add> * <add> * @param {*} node <add> * @return {?DOMEventTarget} <add> * @internal <add> */ <add> getFirstReactDOM: function(node) { <add> var current = node; <add> while (current && current.parentNode !== current) { <add> if (ReactMount.isRenderedByReact(current)) { <add> return current; <add> } <add> current = current.parentNode; <add> } <add> return null; <add> }, <add> <add> /** <add> * Finds a node with the supplied `id` inside of the supplied `ancestorNode`. <add> * Exploits the ID naming scheme to perform the search quickly. <add> * <add> * @param {DOMEventTarget} ancestorNode Search from this root. <add> * @pararm {string} id ID of the DOM representation of the component. <add> * @return {DOMEventTarget} DOM node with the supplied `id`. <add> * @internal <add> */ <add> findComponentRoot: function(ancestorNode, id) { <add> var firstChildren = [ancestorNode.firstChild]; <add> var childIndex = 0; <add> <add> while (childIndex < firstChildren.length) { <add> var child = firstChildren[childIndex++]; <add> while (child) { <add> var childID = ReactMount.getID(child); <add> if (childID) { <add> if (id === childID) { <add> return child; <add> } else if (ReactInstanceHandles.isAncestorIDOf(childID, id)) { <add> // If we find a child whose ID is an ancestor of the given ID, <add> // then we can be sure that we only want to search the subtree <add> // rooted at this child, so we can throw out the rest of the <add> // search state. <add> firstChildren.length = childIndex = 0; <add> firstChildren.push(child.firstChild); <add> break; <add> } else { <add> // TODO This should not be necessary if the ID hierarchy is <add> // correct, but is occasionally necessary if the DOM has been <add> // modified in unexpected ways. <add> firstChildren.push(child.firstChild); <add> } <add> } else { <add> // If this child had no ID, then there's a chance that it was <add> // injected automatically by the browser, as when a `<table>` <add> // element sprouts an extra `<tbody>` child as a side effect of <add> // `.innerHTML` parsing. Optimistically continue down this <add> // branch, but not before examining the other siblings. <add> firstChildren.push(child.firstChild); <add> } <add> child = child.nextSibling; <add> } <add> } <add> <add> if (__DEV__) { <add> console.error( <add> 'Error while invoking `findComponentRoot` with the following ' + <add> 'ancestor node:', <add> ancestorNode <add> ); <add> } <add> invariant( <add> false, <add> 'findComponentRoot(..., %s): Unable to find element. This probably ' + <add> 'means the DOM was unexpectedly mutated (e.g. by the browser).', <add> id, <add> ReactMount.getID(ancestorNode) <add> ); <add> }, <add> <add> <add> /** <add> * React ID utilities. <add> */ <add> <add> ATTR_NAME: ATTR_NAME, <add> <add> getID: getID, <add> <add> setID: setID, <add> <add> getNode: getNode, <add> <add> purgeID: purgeID, <add> <add> injection: {} <ide> }; <ide> <ide> module.exports = ReactMount; <ide><path>src/core/ReactNativeComponent.js <ide> var DOMPropertyOperations = require('DOMPropertyOperations'); <ide> var ReactComponent = require('ReactComponent'); <ide> var ReactEventEmitter = require('ReactEventEmitter'); <ide> var ReactMultiChild = require('ReactMultiChild'); <del>var ReactID = require('ReactID'); <add>var ReactMount = require('ReactMount'); <ide> <ide> var escapeTextForBrowser = require('escapeTextForBrowser'); <ide> var flattenChildren = require('flattenChildren'); <ide> ReactNativeComponent.Mixin = { <ide> } <ide> <ide> var escapedID = escapeTextForBrowser(this._rootNodeID); <del> return ret + ' ' + ReactID.ATTR_NAME + '="' + escapedID + '">'; <add> return ret + ' ' + ReactMount.ATTR_NAME + '="' + escapedID + '">'; <ide> }, <ide> <ide> /** <ide><path>src/core/ReactTextComponent.js <ide> "use strict"; <ide> <ide> var ReactComponent = require('ReactComponent'); <del>var ReactID = require('ReactID'); <add>var ReactMount = require('ReactMount'); <ide> <ide> var escapeTextForBrowser = require('escapeTextForBrowser'); <ide> var mixInto = require('mixInto'); <ide> mixInto(ReactTextComponent, { <ide> mountComponent: function(rootID) { <ide> ReactComponent.Mixin.mountComponent.call(this, rootID); <ide> return ( <del> '<span ' + ReactID.ATTR_NAME + '="' + rootID + '">' + <add> '<span ' + ReactMount.ATTR_NAME + '="' + rootID + '">' + <ide> escapeTextForBrowser(this.props.text) + <ide> '</span>' <ide> ); <ide><path>src/core/__tests__/ReactCompositeComponent-test.js <ide> var React; <ide> var ReactCurrentOwner; <ide> var ReactPropTypes; <ide> var ReactTestUtils; <del>var ReactID; <add>var ReactMount; <ide> var ReactDoNotBindDeprecated; <ide> <ide> var cx; <ide> describe('ReactCompositeComponent', function() { <ide> ReactDoNotBindDeprecated = require('ReactDoNotBindDeprecated'); <ide> ReactPropTypes = require('ReactPropTypes'); <ide> ReactTestUtils = require('ReactTestUtils'); <del> ReactID = require('ReactID'); <add> ReactMount = require('ReactMount'); <ide> <ide> MorphingComponent = React.createClass({ <ide> getInitialState: function() { <ide> describe('ReactCompositeComponent', function() { <ide> // rerender <ide> instance.setProps({renderAnchor: true, anchorClassOn: false}); <ide> var anchorID = instance.getAnchorID(); <del> var actualDOMAnchorNode = ReactID.getNode(anchorID); <add> var actualDOMAnchorNode = ReactMount.getNode(anchorID); <ide> expect(actualDOMAnchorNode.className).toBe(''); <ide> }); <ide> <ide><path>src/core/__tests__/ReactDOM-test.js <ide> var React = require('React'); <ide> var ReactDOM = require('ReactDOM'); <ide> var ReactTestUtils = require('ReactTestUtils'); <ide> var React = require('React'); <del>var ReactID = require('ReactID'); <add>var ReactMount = require('ReactMount'); <ide> <ide> describe('ref swapping', function() { <ide> // TODO: uncomment this test once we can run in phantom, which <ide> describe('ref swapping', function() { <ide> var argDiv = ReactTestUtils.renderIntoDocument( <ide> ReactDOM.div(null, 'child') <ide> ); <del> var argNode = ReactID.getNode(argDiv._rootNodeID); <add> var argNode = ReactMount.getNode(argDiv._rootNodeID); <ide> expect(argNode.innerHTML).toBe('child'); <ide> }); <ide> <ide> it("should overwrite props.children with children argument", function() { <ide> var conflictDiv = ReactTestUtils.renderIntoDocument( <ide> ReactDOM.div({children: 'fakechild'}, 'child') <ide> ); <del> var conflictNode = ReactID.getNode(conflictDiv._rootNodeID); <add> var conflictNode = ReactMount.getNode(conflictDiv._rootNodeID); <ide> expect(conflictNode.innerHTML).toBe('child'); <ide> }); <ide> <ide> describe('ref swapping', function() { <ide> theBird: <div class="bird" /> <ide> } <ide> }); <del> var root = ReactID.getNode(myDiv._rootNodeID); <add> var root = ReactMount.getNode(myDiv._rootNodeID); <ide> var dog = root.childNodes[0]; <ide> expect(dog.className).toBe('bigdog'); <ide> }); <ide><path>src/core/__tests__/ReactDOMIDOperations-test.js <ide> describe('ReactDOMIDOperations', function() { <ide> var DOMPropertyOperations = require('DOMPropertyOperations'); <ide> var ReactDOMIDOperations = require('ReactDOMIDOperations'); <del> var ReactID = require('ReactID'); <add> var ReactMount = require('ReactMount'); <ide> var keyOf = require('keyOf'); <ide> <ide> it('should disallow updating special properties', function() { <del> spyOn(ReactID, "getNode"); <add> spyOn(ReactMount, "getNode"); <ide> spyOn(DOMPropertyOperations, "setValueForProperty"); <ide> <ide> expect(function() { <ide> describe('ReactDOMIDOperations', function() { <ide> }).toThrow(); <ide> <ide> expect( <del> ReactID.getNode.argsForCall[0][0] <add> ReactMount.getNode.argsForCall[0][0] <ide> ).toBe('testID'); <ide> <ide> expect( <ide> describe('ReactDOMIDOperations', function() { <ide> <ide> it('should update innerHTML and special-case whitespace', function() { <ide> var stubNode = document.createElement('div'); <del> spyOn(ReactID, "getNode").andReturn(stubNode); <add> spyOn(ReactMount, "getNode").andReturn(stubNode); <ide> <ide> ReactDOMIDOperations.updateInnerHTMLByID( <ide> 'testID', <ide> {__html: ' testContent'} <ide> ); <ide> <ide> expect( <del> ReactID.getNode.argsForCall[0][0] <add> ReactMount.getNode.argsForCall[0][0] <ide> ).toBe('testID'); <ide> <ide> expect(stubNode.innerHTML).toBe('&nbsp;testContent'); <ide><path>src/core/__tests__/ReactEventEmitter-test.js <ide> require('mock-modules') <ide> .dontMock('BrowserScroll') <ide> .dontMock('CallbackRegistry') <ide> .dontMock('EventPluginHub') <del> .dontMock('ReactID') <add> .dontMock('ReactMount') <ide> .dontMock('ReactEventEmitter') <ide> .dontMock('ReactInstanceHandles') <ide> .dontMock('EventPluginHub') <ide> var keyOf = require('keyOf'); <ide> var mocks = require('mocks'); <ide> <ide> var EventPluginHub; <del>var ReactID = require('ReactID'); <del>var getID = ReactID.getID; <del>var setID = ReactID.setID; <add>var ReactMount = require('ReactMount'); <add>var getID = ReactMount.getID; <add>var setID = ReactMount.setID; <ide> var ReactEventEmitter; <ide> var ReactEventTopLevelCallback; <ide> var ReactTestUtils; <ide> describe('ReactEventEmitter', function() { <ide> require('mock-modules').dumpCache(); <ide> EventPluginHub = require('EventPluginHub'); <ide> TapEventPlugin = require('TapEventPlugin'); <del> ReactID = require('ReactID'); <del> getID = ReactID.getID; <del> setID = ReactID.setID; <add> ReactMount = require('ReactMount'); <add> getID = ReactMount.getID; <add> setID = ReactMount.setID; <ide> ReactEventEmitter = require('ReactEventEmitter'); <ide> ReactTestUtils = require('ReactTestUtils'); <ide> ReactEventTopLevelCallback = require('ReactEventTopLevelCallback'); <ide><path>src/core/__tests__/ReactIdentity-test.js <ide> var React; <ide> var ReactTestUtils; <ide> var reactComponentExpect; <del>var ReactID; <add>var ReactMount; <ide> <ide> describe('ReactIdentity', function() { <ide> <ide> describe('ReactIdentity', function() { <ide> React = require('React'); <ide> ReactTestUtils = require('ReactTestUtils'); <ide> reactComponentExpect = require('reactComponentExpect'); <del> ReactID = require('ReactID'); <add> ReactMount = require('ReactMount'); <ide> }); <ide> <ide> var idExp = /^\.r\[.+?\](.*)$/; <ide> function checkId(child, expectedId) { <del> var actual = idExp.exec(ReactID.getID(child)); <add> var actual = idExp.exec(ReactMount.getID(child)); <ide> var expected = idExp.exec(expectedId); <ide> expect(actual).toBeTruthy(); <ide> expect(expected).toBeTruthy(); <ide> describe('ReactIdentity', function() { <ide> <ide> React.renderComponent(wrapped, document.createElement('div')); <ide> <del> var beforeID = ReactID.getID(wrapped.getDOMNode().firstChild); <add> var beforeID = ReactMount.getID(wrapped.getDOMNode().firstChild); <ide> <ide> wrapped.swap(); <ide> <del> var afterID = ReactID.getID(wrapped.getDOMNode().firstChild); <add> var afterID = ReactMount.getID(wrapped.getDOMNode().firstChild); <ide> <ide> expect(beforeID).not.toEqual(afterID); <ide> <ide><path>src/core/__tests__/ReactInstanceHandles-test.js <ide> <ide> var React = require('React'); <ide> var ReactTestUtils = require('ReactTestUtils'); <del>var ReactID = require('ReactID'); <add>var ReactMount = require('ReactMount'); <ide> <ide> /** <ide> * Ensure that all callbacks are invoked, passing this unique argument. <ide> describe('ReactInstanceHandles', function() { <ide> describe('isRenderedByReact', function() { <ide> it('should not crash on text nodes', function() { <ide> expect(function() { <del> ReactInstanceHandles.isRenderedByReact(document.createTextNode('yolo')); <add> ReactMount.isRenderedByReact(document.createTextNode('yolo')); <ide> }).not.toThrow(); <ide> }); <ide> }); <ide> describe('ReactInstanceHandles', function() { <ide> parentNode.appendChild(childNodeA); <ide> parentNode.appendChild(childNodeB); <ide> <del> ReactID.setID(parentNode, '.react[0]'); <del> ReactID.setID(childNodeA, '.react[0].0'); <del> ReactID.setID(childNodeB, '.react[0].0:1'); <add> ReactMount.setID(parentNode, '.react[0]'); <add> ReactMount.setID(childNodeA, '.react[0].0'); <add> ReactMount.setID(childNodeB, '.react[0].0:1'); <ide> <ide> expect( <del> ReactInstanceHandles.findComponentRoot( <add> ReactMount.findComponentRoot( <ide> parentNode, <del> ReactID.getID(childNodeB) <add> ReactMount.getID(childNodeB) <ide> ) <ide> ).toBe(childNodeB); <ide> }); <ide> describe('ReactInstanceHandles', function() { <ide> parentNode.appendChild(childNodeA); <ide> parentNode.appendChild(childNodeB); <ide> <del> ReactID.setID(parentNode, '.react[0]'); <add> ReactMount.setID(parentNode, '.react[0]'); <ide> // No ID on `childNodeA`. <del> ReactID.setID(childNodeB, '.react[0].0:1'); <add> ReactMount.setID(childNodeB, '.react[0].0:1'); <ide> <ide> expect( <del> ReactInstanceHandles.findComponentRoot( <add> ReactMount.findComponentRoot( <ide> parentNode, <del> ReactID.getID(childNodeB) <add> ReactMount.getID(childNodeB) <ide> ) <ide> ).toBe(childNodeB); <ide> }); <ide> describe('ReactInstanceHandles', function() { <ide> parentNode.appendChild(childNodeA); <ide> childNodeA.appendChild(childNodeB); <ide> <del> ReactID.setID(parentNode, '.react[0]'); <add> ReactMount.setID(parentNode, '.react[0]'); <ide> // No ID on `childNodeA`, it was "rendered by the browser". <del> ReactID.setID(childNodeB, '.react[0].1:0'); <add> ReactMount.setID(childNodeB, '.react[0].1:0'); <ide> <del> expect(ReactInstanceHandles.findComponentRoot( <add> expect(ReactMount.findComponentRoot( <ide> parentNode, <del> ReactID.getID(childNodeB) <add> ReactMount.getID(childNodeB) <ide> )).toBe(childNodeB); <ide> <ide> spyOn(console, 'error'); <ide> expect(console.error.argsForCall.length).toBe(0); <ide> <ide> expect(function() { <del> ReactInstanceHandles.findComponentRoot( <add> ReactMount.findComponentRoot( <ide> parentNode, <del> ReactID.getID(childNodeB) + ":junk" <add> ReactMount.getID(childNodeB) + ":junk" <ide> ); <ide> }).toThrow( <ide> 'Invariant Violation: findComponentRoot(..., .react[0].1:0:junk): ' + <ide><path>src/core/__tests__/ReactMultiChildReconcile-test.js <ide> require('mock-modules'); <ide> <ide> var React = require('React'); <ide> var ReactTestUtils = require('ReactTestUtils'); <del>var ReactID = require('ReactID'); <add>var ReactMount = require('ReactMount'); <ide> <ide> var objMapKeyVal = require('objMapKeyVal'); <ide> <ide> function verifyDomOrderingAccurate(parentInstance, statusDisplays) { <ide> var i; <ide> var orderedDomIds = []; <ide> for (i=0; i < statusDisplayNodes.length; i++) { <del> orderedDomIds.push(ReactID.getID(statusDisplayNodes[i])); <add> orderedDomIds.push(ReactMount.getID(statusDisplayNodes[i])); <ide> } <ide> <ide> var orderedLogicalIds = []; <ide><path>src/core/__tests__/ReactNativeComponent-test.js <ide> describe('ReactNativeComponent', function() { <ide> it("should clean up listeners", function() { <ide> var React = require('React'); <ide> var ReactEventEmitter = require('ReactEventEmitter'); <del> var ReactID = require('ReactID'); <add> var ReactMount = require('ReactMount'); <ide> <ide> var container = document.createElement('div'); <ide> document.documentElement.appendChild(container); <ide> describe('ReactNativeComponent', function() { <ide> React.renderComponent(instance, container); <ide> <ide> var rootNode = instance.getDOMNode(); <del> var rootNodeID = ReactID.getID(rootNode); <add> var rootNodeID = ReactMount.getID(rootNode); <ide> expect( <ide> ReactEventEmitter.getListener(rootNodeID, 'onClick') <ide> ).toBe(callback); <ide><path>src/environment/__tests__/ReactServerRendering-test.js <ide> require('mock-modules') <ide> .dontMock('ExecutionEnvironment') <ide> .dontMock('React') <del> .dontMock('ReactID') <add> .dontMock('ReactMount') <ide> .dontMock('ReactServerRendering') <ide> .dontMock('ReactTestUtils') <ide> .dontMock('ReactMarkupChecksum'); <ide> <ide> var mocks = require('mocks'); <ide> <ide> var React; <del>var ReactID; <add>var ReactMount; <ide> var ReactTestUtils; <ide> var ReactServerRendering; <ide> var ReactMarkupChecksum; <ide> describe('ReactServerRendering', function() { <ide> beforeEach(function() { <ide> require('mock-modules').dumpCache(); <ide> React = require('React'); <del> ReactID = require('ReactID'); <add> ReactMount = require('ReactMount'); <ide> ReactTestUtils = require('ReactTestUtils'); <ide> ExecutionEnvironment = require('ExecutionEnvironment'); <ide> ExecutionEnvironment.canUseDOM = false; <ide> describe('ReactServerRendering', function() { <ide> } <ide> ); <ide> expect(response).toMatch( <del> '<span ' + ReactID.ATTR_NAME + '="[^"]+" ' + <add> '<span ' + ReactMount.ATTR_NAME + '="[^"]+" ' + <ide> ReactMarkupChecksum.CHECKSUM_ATTR_NAME + '="[^"]+">hello world</span>' <ide> ); <ide> }); <ide> describe('ReactServerRendering', function() { <ide> } <ide> ); <ide> expect(response).toMatch( <del> '<div ' + ReactID.ATTR_NAME + '="[^"]+" ' + <add> '<div ' + ReactMount.ATTR_NAME + '="[^"]+" ' + <ide> ReactMarkupChecksum.CHECKSUM_ATTR_NAME + '="[^"]+">' + <del> '<span ' + ReactID.ATTR_NAME + '="[^"]+">' + <del> '<span ' + ReactID.ATTR_NAME + '="[^"]+">My name is </span>' + <del> '<span ' + ReactID.ATTR_NAME + '="[^"]+">child</span>' + <add> '<span ' + ReactMount.ATTR_NAME + '="[^"]+">' + <add> '<span ' + ReactMount.ATTR_NAME + '="[^"]+">My name is </span>' + <add> '<span ' + ReactMount.ATTR_NAME + '="[^"]+">child</span>' + <ide> '</span>' + <ide> '</div>' <ide> ); <ide> describe('ReactServerRendering', function() { <ide> ); <ide> <ide> expect(response).toMatch( <del> '<span ' + ReactID.ATTR_NAME + '="[^"]+" ' + <add> '<span ' + ReactMount.ATTR_NAME + '="[^"]+" ' + <ide> ReactMarkupChecksum.CHECKSUM_ATTR_NAME + '="[^"]+">' + <del> '<span ' + ReactID.ATTR_NAME + '="[^"]+">Component name: </span>' + <del> '<span ' + ReactID.ATTR_NAME + '="[^"]+">TestComponent</span>' + <add> '<span ' + ReactMount.ATTR_NAME + '="[^"]+">Component name: </span>' + <add> '<span ' + ReactMount.ATTR_NAME + '="[^"]+">TestComponent</span>' + <ide> '</span>' <ide> ); <ide> expect(lifecycle).toEqual( <ide><path>src/eventPlugins/EnterLeaveEventPlugin.js <ide> var EventConstants = require('EventConstants'); <ide> var EventPropagators = require('EventPropagators'); <ide> var ExecutionEnvironment = require('ExecutionEnvironment'); <del>var ReactInstanceHandles = require('ReactInstanceHandles'); <ide> var SyntheticMouseEvent = require('SyntheticMouseEvent'); <ide> <del>var ReactID = require('ReactID'); <add>var ReactMount = require('ReactMount'); <ide> var keyOf = require('keyOf'); <ide> <ide> var topLevelTypes = EventConstants.topLevelTypes; <del>var getFirstReactDOM = ReactInstanceHandles.getFirstReactDOM; <add>var getFirstReactDOM = ReactMount.getFirstReactDOM; <ide> <ide> var eventTypes = { <ide> mouseEnter: {registrationName: keyOf({onMouseEnter: null})}, <ide> var EnterLeaveEventPlugin = { <ide> return null; <ide> } <ide> <del> var fromID = from ? ReactID.getID(from) : ''; <del> var toID = to ? ReactID.getID(to) : ''; <add> var fromID = from ? ReactMount.getID(from) : ''; <add> var toID = to ? ReactMount.getID(to) : ''; <ide> <ide> var leave = SyntheticMouseEvent.getPooled( <ide> eventTypes.mouseLeave, <ide><path>src/test/ReactTestUtils.js <ide> var React = require('React'); <ide> var ReactComponent = require('ReactComponent'); <ide> var ReactEventEmitter = require('ReactEventEmitter'); <ide> var ReactTextComponent = require('ReactTextComponent'); <del>var ReactID = require('ReactID'); <add>var ReactMount = require('ReactMount'); <ide> <ide> var mergeInto = require('mergeInto'); <ide> <ide> var ReactTestUtils = { <ide> ReactEventEmitter.TopLevelCallbackCreator.createTopLevelCallback( <ide> topLevelType <ide> ); <del> var node = ReactID.getNode(reactRootID); <add> var node = ReactMount.getNode(reactRootID); <ide> fakeNativeEvent.target = node; <ide> /* jsdom is returning nodes without id's - fixing that issue here. */ <del> ReactID.setID(node, reactRootID); <add> ReactMount.setID(node, reactRootID); <ide> virtualHandler(fakeNativeEvent); <ide> }, <ide>
21
Text
Text
add v3.24.3, v3.25.2, and v3.25.3 to changelog.md
56c3520b0e52e5bc7f357b5865c34a23eefd98e7
<ide><path>CHANGELOG.md <ide> - [#19298](https://github.com/emberjs/ember.js/pull/19298) [BUGFIX] Route serialize did not extract param off proxy <ide> - [#19326](https://github.com/emberjs/ember.js/pull/19326) [BUGFIX] Lazily setup the router in non-application tests for <LinkTo> component <ide> <add> <add>### v3.25.3 (March 7, 2021) <add> <add>- [#19448](https://github.com/emberjs/ember.js/pull/19448) Ensure query params are preserved through an intermediate loading state transition <add>- [#19450](https://github.com/emberjs/ember.js/pull/19450) Ensure `routerService.currentRoute.name` and `routerService.currentRouteName` match during loading states <add> <add> <add>### v3.25.2 (March 7, 2021) <add> <add>- [#19389](https://github.com/emberjs/ember.js/pull/19389) Removes template ids <add>- [#19395](https://github.com/emberjs/ember.js/pull/19395) [BUGFIX] Ensure `<LinkTo>` can return a valid `href` most of the time <add>- [#19396](https://github.com/emberjs/ember.js/pull/19396) [BUGFIX] Revert deprecation of htmlSafe and isHTMLSafe <add>- [#19397](https://github.com/emberjs/ember.js/pull/19397) [BUGFIX] Force building Ember bundles when `targets.node` is defined <add>- [#19399](https://github.com/emberjs/ember.js/pull/19399) [DOC] Update ArrayProxy Documentation <add>- [#19412](https://github.com/emberjs/ember.js/pull/19412) / [#19416](https://github.com/emberjs/ember.js/pull/19416) [BUGFIX] Update Glimmer VM to 0.77 (fix dynamic helpers/modifiers) <add> <add> <ide> ### v3.25.1 (February 10, 2021) <ide> <ide> - [#19326](https://github.com/emberjs/ember.js/pull/19326) / [#19387](https://github.com/emberjs/ember.js/pull/19387) [BUGFIX] Fix usage of `<LinkTo />` prior to routing (e.g. component rendering tests) <ide> - [#19338](https://github.com/emberjs/ember.js/pull/19338) [BUGFIX] Add missing `deprecate` options (`for` + `since`) <ide> - [#19342](https://github.com/emberjs/ember.js/pull/19342) [BUGFIX] Fix misleading LinkTo error message <ide> <add> <add>### v3.24.3 (March 7, 2021) <add> <add>- [#19448](https://github.com/emberjs/ember.js/pull/19448) Ensure query params are preserved through an intermediate loading state transition <add>- [#19450](https://github.com/emberjs/ember.js/pull/19450) Ensure `routerService.currentRoute.name` and `routerService.currentRouteName` match during loading states <add>- [#19395](https://github.com/emberjs/ember.js/pull/19395) [BUGFIX] Ensure `<LinkTo>` can return a valid `href` most of the time <add>- [#19397](https://github.com/emberjs/ember.js/pull/19397) [BUGFIX] Force building Ember bundles when `targets.node` is defined <add> <add> <ide> ### v3.24.2 (February 10, 2021) <ide> <ide> - [#19326](https://github.com/emberjs/ember.js/pull/19326) / [#19387](https://github.com/emberjs/ember.js/pull/19387) [BUGFIX] Fix usage of `<LinkTo />` prior to routing (e.g. component rendering tests)
1
Text
Text
add note about aur to arch build instructions
3c8bcd7ea9a35c357c7342dd73ea079e95750d58
<ide><path>docs/build-instructions/linux.md <ide> Ubuntu LTS 12.04 64-bit is the recommended platform. <ide> <ide> ### Arch <ide> <del>* `sudo pacman -S gconf base-devel git nodejs npm libgnome-keyring python2` <del>* `export PYTHON=/usr/bin/python2` before building Atom. <add>* To automatically build Atom from source, install the atom-editor package from the [Arch User Repository (AUR)](https://wiki.archlinux.org/index.php/Arch_User_Repository) <add>* Alternatively run <add> * `sudo pacman -S gconf base-devel git nodejs npm libgnome-keyring python2` <add> * `export PYTHON=/usr/bin/python2` before building Atom. <ide> <ide> ### Slackware <ide>
1
Go
Go
restore network settings at startup
f1087c5fcf070f151601f643418f3963facfea84
<ide><path>daemon/daemon.go <ide> func (daemon *Daemon) restore() error { <ide> registeredContainers = append(registeredContainers, container) <ide> } <ide> <add> // Restore networking of registered containers. <add> // This must be performed prior to any IP allocation, otherwise we might <add> // end up giving away an already allocated address. <add> for _, container := range registeredContainers { <add> if err := container.RestoreNetwork(); err != nil { <add> log.Errorf("Failed to restore network for %v: %v", container.Name, err) <add> continue <add> } <add> } <add> <ide> // check the restart policy on the containers and restart any container with <ide> // the restart policy of "always" <ide> if daemon.config.AutoRestart {
1
Ruby
Ruby
push parent up to the superclass
217aedf1bf4255696c4f95976ee5056054dc9231
<ide><path>activerecord/lib/active_record/associations/join_dependency/join_association.rb <ide> class JoinAssociation < JoinPart # :nodoc: <ide> # The reflection of the association represented <ide> attr_reader :reflection <ide> <del> # A JoinBase instance representing the active record we are joining onto. <del> # (So in Author.has_many :posts, the Author would be that base record.) <del> attr_reader :parent <del> <ide> # What type of join will be generated, either Arel::InnerJoin (default) or Arel::OuterJoin <ide> attr_accessor :join_type <ide> <ide> class JoinAssociation < JoinPart # :nodoc: <ide> delegate :options, :through_reflection, :source_reflection, :chain, :to => :reflection <ide> <ide> def initialize(reflection, index, parent, join_type, alias_tracker) <del> super(reflection.klass) <add> super(reflection.klass, parent) <ide> <ide> @reflection = reflection <ide> @alias_tracker = alias_tracker <del> @parent = parent <ide> @join_type = join_type <ide> @aliased_prefix = "t#{ index }" <ide> @tables = construct_tables.reverse <ide><path>activerecord/lib/active_record/associations/join_dependency/join_base.rb <ide> module ActiveRecord <ide> module Associations <ide> class JoinDependency # :nodoc: <ide> class JoinBase < JoinPart # :nodoc: <add> def initialize(klass) <add> super(klass, nil) <add> end <add> <ide> def ==(other) <ide> other.class == self.class && <ide> other.base_klass == base_klass <ide><path>activerecord/lib/active_record/associations/join_dependency/join_part.rb <ide> class JoinDependency # :nodoc: <ide> class JoinPart # :nodoc: <ide> include Enumerable <ide> <add> # A JoinBase instance representing the active record we are joining onto. <add> # (So in Author.has_many :posts, the Author would be that base record.) <add> attr_reader :parent <add> <ide> # The Active Record class which this join part is associated 'about'; for a JoinBase <ide> # this is the actual base model, for a JoinAssociation this is the target model of the <ide> # association. <ide> attr_reader :base_klass, :children <ide> <ide> delegate :table_name, :column_names, :primary_key, :arel_engine, :to => :base_klass <ide> <del> def initialize(base_klass) <add> def initialize(base_klass, parent) <ide> @base_klass = base_klass <add> @parent = parent <ide> @cached_record = {} <ide> @column_names_with_alias = nil <ide> @children = []
3
PHP
PHP
fix digestauthenticate with simulated http methods
8b9dfc43e813f57c937a4418a27c248a26288514
<ide><path>src/Auth/DigestAuthenticate.php <ide> public function getUser(Request $request) { <ide> $password = $user[$field]; <ide> unset($user[$field]); <ide> <del> $hash = $this->generateResponseHash($digest, $password, $request->env('REQUEST_METHOD')); <add> $hash = $this->generateResponseHash($digest, $password, $request->env('ORIGINAL_REQUEST_METHOD')); <ide> if ($digest['response'] === $hash) { <ide> return $user; <ide> } <ide><path>src/Network/Request.php <ide> protected function _setConfig($config) { <ide> <ide> /** <ide> * Sets the REQUEST_METHOD environment variable based on the simulated _method <del> * HTTP override value. <add> * HTTP override value. The 'ORIGINAL_REQUEST_METHOD' is also preserved, if you <add> * want the read the non-simulated HTTP method the client used. <ide> * <ide> * @param array $data Array of post data. <ide> * @return array <ide> */ <ide> protected function _processPost($data) { <add> $method = $this->env('REQUEST_METHOD'); <ide> if ( <del> in_array($this->env('REQUEST_METHOD'), array('PUT', 'DELETE', 'PATCH')) && <add> in_array($method, array('PUT', 'DELETE', 'PATCH')) && <ide> strpos($this->env('CONTENT_TYPE'), 'application/x-www-form-urlencoded') === 0 <ide> ) { <ide> $data = $this->input(); <ide> protected function _processPost($data) { <ide> if ($this->env('HTTP_X_HTTP_METHOD_OVERRIDE')) { <ide> $data['_method'] = $this->env('HTTP_X_HTTP_METHOD_OVERRIDE'); <ide> } <add> $this->_environment['ORIGINAL_REQUEST_METHOD'] = $method; <ide> if (isset($data['_method'])) { <ide> $this->_environment['REQUEST_METHOD'] = $data['_method']; <ide> unset($data['_method']); <ide><path>tests/TestCase/Auth/DigestAuthenticateTest.php <ide> public function testAuthenticateSuccess() { <ide> $this->assertEquals($expected, $result); <ide> } <ide> <add>/** <add> * test authenticate success <add> * <add> * @return void <add> */ <add> public function testAuthenticateSuccessSimulatedRequestMethod() { <add> $request = new Request([ <add> 'url' => 'posts/index', <add> 'post' => ['_method' => 'PUT'], <add> 'environment' => ['REQUEST_METHOD' => 'GET'] <add> ]); <add> $request->addParams(array('pass' => array())); <add> <add> $digest = <<<DIGEST <add>Digest username="mariano", <add>realm="localhost", <add>nonce="123", <add>uri="/dir/index.html", <add>qop=auth, <add>nc=1, <add>cnonce="123", <add>response="06b257a54befa2ddfb9bfa134224aa29", <add>opaque="123abc" <add>DIGEST; <add> $request->env('PHP_AUTH_DIGEST', $digest); <add> <add> $result = $this->auth->authenticate($request, $this->response); <add> $expected = array( <add> 'id' => 1, <add> 'username' => 'mariano', <add> 'created' => new Time('2007-03-17 01:16:23'), <add> 'updated' => new Time('2007-03-17 01:18:31') <add> ); <add> $this->assertEquals($expected, $result); <add> } <add> <ide> /** <ide> * test scope failure. <ide> * <ide><path>tests/TestCase/Network/RequestTest.php <ide> public function testMethodOverrides() { <ide> <ide> $request = new Request(['environment' => ['HTTP_X_HTTP_METHOD_OVERRIDE' => 'PUT']]); <ide> $this->assertEquals('PUT', $request->env('REQUEST_METHOD')); <add> <add> $request = new Request([ <add> 'environment' => ['REQUEST_METHOD' => 'POST'], <add> 'post' => ['_method' => 'PUT'] <add> ]); <add> $this->assertEquals('PUT', $request->env('REQUEST_METHOD')); <add> $this->assertEquals('POST', $request->env('ORIGINAL_REQUEST_METHOD')); <ide> } <ide> <ide> /**
4
Mixed
Go
provide a knob dm.xfs_nospace_max_retries
4f0017b9ad7dfa2e9dcdee69d000b98595893e60
<ide><path>daemon/graphdriver/devmapper/deviceset.go <ide> type DeviceSet struct { <ide> uidMaps []idtools.IDMap <ide> gidMaps []idtools.IDMap <ide> minFreeSpacePercent uint32 //min free space percentage in thinpool <add> xfsNospaceRetries string // max retries when xfs receives ENOSPC <ide> } <ide> <ide> // DiskUsage contains information about disk usage and is used when reporting Status of a device. <ide> func (devices *DeviceSet) Shutdown(home string) error { <ide> return nil <ide> } <ide> <add>// Recent XFS changes allow changing behavior of filesystem in case of errors. <add>// When thin pool gets full and XFS gets ENOSPC error, currently it tries <add>// IO infinitely and sometimes it can block the container process <add>// and process can't be killWith 0 value, XFS will not retry upon error <add>// and instead will shutdown filesystem. <add> <add>func (devices *DeviceSet) xfsSetNospaceRetries(info *devInfo) error { <add> dmDevicePath, err := os.Readlink(info.DevName()) <add> if err != nil { <add> return fmt.Errorf("devmapper: readlink failed for device %v:%v", info.DevName(), err) <add> } <add> <add> dmDeviceName := path.Base(dmDevicePath) <add> filePath := "/sys/fs/xfs/" + dmDeviceName + "/error/metadata/ENOSPC/max_retries" <add> maxRetriesFile, err := os.OpenFile(filePath, os.O_WRONLY, 0) <add> if err != nil { <add> // Older kernels don't have this feature/file <add> if os.IsNotExist(err) { <add> return nil <add> } <add> return fmt.Errorf("devmapper: Failed to open file %v:%v", filePath, err) <add> } <add> defer maxRetriesFile.Close() <add> <add> // Set max retries to 0 <add> _, err = maxRetriesFile.WriteString(devices.xfsNospaceRetries) <add> if err != nil { <add> return fmt.Errorf("devmapper: Failed to write string %v to file %v:%v", devices.xfsNospaceRetries, filePath, err) <add> } <add> return nil <add>} <add> <ide> // MountDevice mounts the device if not already mounted. <ide> func (devices *DeviceSet) MountDevice(hash, path, mountLabel string) error { <ide> info, err := devices.lookupDeviceWithLock(hash) <ide> func (devices *DeviceSet) MountDevice(hash, path, mountLabel string) error { <ide> return fmt.Errorf("devmapper: Error mounting '%s' on '%s': %s", info.DevName(), path, err) <ide> } <ide> <add> if fstype == "xfs" && devices.xfsNospaceRetries != "" { <add> if err := devices.xfsSetNospaceRetries(info); err != nil { <add> return err <add> } <add> } <add> <ide> return nil <ide> } <ide> <ide> func NewDeviceSet(root string, doInit bool, options []string, uidMaps, gidMaps [ <ide> } <ide> <ide> devices.minFreeSpacePercent = uint32(minFreeSpacePercent) <add> case "dm.xfs_nospace_max_retries": <add> _, err := strconv.ParseUint(val, 10, 64) <add> if err != nil { <add> return nil, err <add> } <add> devices.xfsNospaceRetries = val <ide> default: <ide> return nil, fmt.Errorf("devmapper: Unknown option %s\n", key) <ide> } <ide><path>docs/reference/commandline/dockerd.md <ide> options for `zfs` start with `zfs` and options for `btrfs` start with `btrfs`. <ide> $ dockerd --storage-opt dm.min_free_space=10% <ide> ``` <ide> <add>* `dm.xfs_nospace_max_retries` <add> <add> Specifies the maximum number of retries XFS should attempt to complete <add> IO when ENOSPC (no space) error is returned by underlying storage device. <add> <add> By default XFS retries infinitely for IO to finish and this can result <add> in unkillable process. To change this behavior one can set <add> xfs_nospace_max_retries to say 0 and XFS will not retry IO after getting <add> ENOSPC and will shutdown filesystem. <add> <add> Example use: <add> <add> ```bash <add> $ dockerd --storage-opt dm.xfs_nospace_max_retries=0 <add> ``` <add> <ide> #### ZFS options <ide> <ide> * `zfs.fsname`
2
Go
Go
protect the health status with mutex
7db30ab0cdf072956d2ceda833b7de22fe17655c
<ide><path>container/health.go <ide> type Health struct { <ide> <ide> // String returns a human-readable description of the health-check state <ide> func (s *Health) String() string { <del> // This happens when the monitor has yet to be setup. <del> if s.Status == "" { <del> return types.Unhealthy <del> } <add> status := s.Status() <ide> <del> switch s.Status { <add> switch status { <ide> case types.Starting: <ide> return "health: starting" <ide> default: // Healthy and Unhealthy are clear on their own <del> return s.Status <add> return s.Health.Status <ide> } <ide> } <ide> <add>// Status returns the current health status. <add>// <add>// Note that this takes a lock and the value may change after being read. <add>func (s *Health) Status() string { <add> s.mu.Lock() <add> defer s.mu.Unlock() <add> <add> // This happens when the monitor has yet to be setup. <add> if s.Health.Status == "" { <add> return types.Unhealthy <add> } <add> <add> return s.Health.Status <add>} <add> <add>// SetStatus writes the current status to the underlying health structure, <add>// obeying the locking semantics. <add>// <add>// Status may be set directly if another lock is used. <add>func (s *Health) SetStatus(new string) { <add> s.mu.Lock() <add> defer s.mu.Unlock() <add> <add> s.Health.Status = new <add>} <add> <ide> // OpenMonitorChannel creates and returns a new monitor channel. If there <ide> // already is one, it returns nil. <ide> func (s *Health) OpenMonitorChannel() chan struct{} { <ide> func (s *Health) CloseMonitorChannel() { <ide> close(s.stop) <ide> s.stop = nil <ide> // unhealthy when the monitor has stopped for compatibility reasons <del> s.Status = types.Unhealthy <add> s.Health.Status = types.Unhealthy <ide> logrus.Debug("CloseMonitorChannel done") <ide> } <ide> } <ide><path>daemon/health.go <ide> func handleProbeResult(d *Daemon, c *container.Container, result *types.Healthch <ide> } <ide> <ide> h := c.State.Health <del> oldStatus := h.Status <add> oldStatus := h.Status() <ide> <ide> if len(h.Log) >= maxLogEntries { <ide> h.Log = append(h.Log[len(h.Log)+1-maxLogEntries:], result) <ide> func handleProbeResult(d *Daemon, c *container.Container, result *types.Healthch <ide> <ide> if result.ExitCode == exitStatusHealthy { <ide> h.FailingStreak = 0 <del> h.Status = types.Healthy <add> h.SetStatus(types.Healthy) <ide> } else { // Failure (including invalid exit code) <ide> shouldIncrementStreak := true <ide> <ide> // If the container is starting (i.e. we never had a successful health check) <ide> // then we check if we are within the start period of the container in which <ide> // case we do not increment the failure streak. <del> if h.Status == types.Starting { <add> if h.Status() == types.Starting { <ide> startPeriod := timeoutWithDefault(c.Config.Healthcheck.StartPeriod, defaultStartPeriod) <ide> timeSinceStart := result.Start.Sub(c.State.StartedAt) <ide> <ide> func handleProbeResult(d *Daemon, c *container.Container, result *types.Healthch <ide> h.FailingStreak++ <ide> <ide> if h.FailingStreak >= retries { <del> h.Status = types.Unhealthy <add> h.SetStatus(types.Unhealthy) <ide> } <ide> } <ide> // Else we're starting or healthy. Stay in that state. <ide> func handleProbeResult(d *Daemon, c *container.Container, result *types.Healthch <ide> logrus.Errorf("Error replicating health state for container %s: %v", c.ID, err) <ide> } <ide> <del> if oldStatus != h.Status { <del> d.LogContainerEvent(c, "health_status: "+h.Status) <add> current := h.Status() <add> if oldStatus != current { <add> d.LogContainerEvent(c, "health_status: "+current) <ide> } <ide> } <ide> <ide> func (d *Daemon) initHealthMonitor(c *container.Container) { <ide> d.stopHealthchecks(c) <ide> <ide> if h := c.State.Health; h != nil { <del> h.Status = types.Starting <add> h.SetStatus(types.Starting) <ide> h.FailingStreak = 0 <ide> } else { <ide> h := &container.Health{} <del> h.Status = types.Starting <add> h.SetStatus(types.Starting) <ide> c.State.Health = h <ide> } <ide> <ide><path>daemon/health_test.go <ide> import ( <ide> func reset(c *container.Container) { <ide> c.State = &container.State{} <ide> c.State.Health = &container.Health{} <del> c.State.Health.Status = types.Starting <add> c.State.Health.SetStatus(types.Starting) <ide> } <ide> <ide> func TestNoneHealthcheck(t *testing.T) { <ide> func TestHealthStates(t *testing.T) { <ide> <ide> handleResult(c.State.StartedAt.Add(20*time.Second), 1) <ide> handleResult(c.State.StartedAt.Add(40*time.Second), 1) <del> if c.State.Health.Status != types.Starting { <del> t.Errorf("Expecting starting, but got %#v\n", c.State.Health.Status) <add> if status := c.State.Health.Status(); status != types.Starting { <add> t.Errorf("Expecting starting, but got %#v\n", status) <ide> } <ide> if c.State.Health.FailingStreak != 2 { <ide> t.Errorf("Expecting FailingStreak=2, but got %d\n", c.State.Health.FailingStreak) <ide> func TestHealthStates(t *testing.T) { <ide> c.Config.Healthcheck.StartPeriod = 30 * time.Second <ide> <ide> handleResult(c.State.StartedAt.Add(20*time.Second), 1) <del> if c.State.Health.Status != types.Starting { <del> t.Errorf("Expecting starting, but got %#v\n", c.State.Health.Status) <add> if status := c.State.Health.Status(); status != types.Starting { <add> t.Errorf("Expecting starting, but got %#v\n", status) <ide> } <ide> if c.State.Health.FailingStreak != 0 { <ide> t.Errorf("Expecting FailingStreak=0, but got %d\n", c.State.Health.FailingStreak) <ide> } <ide> handleResult(c.State.StartedAt.Add(50*time.Second), 1) <del> if c.State.Health.Status != types.Starting { <del> t.Errorf("Expecting starting, but got %#v\n", c.State.Health.Status) <add> if status := c.State.Health.Status(); status != types.Starting { <add> t.Errorf("Expecting starting, but got %#v\n", status) <ide> } <ide> if c.State.Health.FailingStreak != 1 { <ide> t.Errorf("Expecting FailingStreak=1, but got %d\n", c.State.Health.FailingStreak) <ide><path>daemon/inspect.go <ide> func (daemon *Daemon) getInspectData(container *container.Container) (*types.Con <ide> var containerHealth *types.Health <ide> if container.State.Health != nil { <ide> containerHealth = &types.Health{ <del> Status: container.State.Health.Status, <add> Status: container.State.Health.Status(), <ide> FailingStreak: container.State.Health.FailingStreak, <ide> Log: append([]*types.HealthcheckResult{}, container.State.Health.Log...), <ide> }
4
Ruby
Ruby
add methods to strongparameters
3f2ac413b7c455ca951944da510683f52cb964da
<ide><path>actionpack/lib/action_controller/metal/strong_parameters.rb <ide> class Parameters <ide> cattr_accessor :permit_all_parameters, instance_accessor: false <ide> cattr_accessor :action_on_unpermitted_parameters, instance_accessor: false <ide> <del> delegate :keys, :key?, :has_key?, :empty?, :include?, :inspect, <add> delegate :keys, :key?, :has_key?, :values, :has_value?, :value?, :empty?, :include?, :inspect, <ide> :as_json, to: :@parameters <ide> <ide> # By default, never raise an UnpermittedParameters exception if these <ide><path>actionpack/test/controller/required_params_test.rb <ide> class ParametersRequireTest < ActiveSupport::TestCase <ide> end <ide> end <ide> <del> test "Deprecated method are deprecated" do <add> test "value params" do <add> params = ActionController::Parameters.new(foo: "bar", dog: "cinco") <add> assert_equal ["bar", "cinco"], params.values <add> assert params.has_value?("cinco") <add> assert params.value?("cinco") <add> end <add> <add> test "Deprecated methods are deprecated" do <ide> assert_deprecated do <ide> ActionController::Parameters.new(foo: "bar").merge!({bar: "foo"}) <ide> end
2
Ruby
Ruby
improve help text formatting
6b8724431fb73b75f003064cb4b70c20e9e665e0
<ide><path>Library/Homebrew/cli_parser.rb <ide> def initialize(&block) <ide> @constraints = [] <ide> @conflicts = [] <ide> @processed_options = [] <del> @desc_line_length = 48 <add> @desc_line_length = 43 <ide> instance_eval(&block) <ide> post_initialize <ide> end <ide> <ide> def post_initialize <del> @parser.on_tail("-h", "--help", "Show this message") do <add> @parser.on_tail("-h", "--help", "Show this message.") do <ide> puts generate_help_text <ide> exit 0 <ide> end <ide> def global_option?(name) <ide> <ide> def generate_help_text <ide> @parser.to_s.sub(/^/, "#{Tty.bold}Usage: brew#{Tty.reset} ") <del> .gsub(/`(.*?)`/, "#{Tty.bold}\\1#{Tty.reset}") <add> .gsub(/`(.*?)`/m, "#{Tty.bold}\\1#{Tty.reset}") <ide> .gsub(%r{<([^\s]+?://[^\s]+?)>}) { |url| Formatter.url(url) } <del> .gsub(/<(.*?)>/, "#{Tty.underline}\\1#{Tty.reset}") <add> .gsub(/<(.*?)>/m, "#{Tty.underline}\\1#{Tty.reset}") <add> .gsub(/\*(.*?)\*/m, "#{Tty.underline}\\1#{Tty.reset}") <ide> end <ide> <ide> private <ide><path>Library/Homebrew/help.rb <ide> def command_help(path) <ide> .gsub(/`(.*?)`/, "#{Tty.bold}\\1#{Tty.reset}") <ide> .gsub(%r{<([^\s]+?://[^\s]+?)>}) { |url| Formatter.url(url) } <ide> .gsub(/<(.*?)>/, "#{Tty.underline}\\1#{Tty.reset}") <add> .gsub(/\*(.*?)\*/, "#{Tty.underline}\\1#{Tty.reset}") <ide> .gsub("@hide_from_man_page", "") <ide> end.join.strip <ide> end <ide><path>Library/Homebrew/test/cli_parser_spec.rb <ide> <ide> it "raises exception on depends_on constraint violation" do <ide> expect { parser.parse(["--flag2=flag2"]) }.to raise_error(Homebrew::CLI::OptionConstraintError) <add> expect { parser.parse(["--flag4=flag4"]) }.to raise_error(Homebrew::CLI::OptionConstraintError) <ide> end <ide> <ide> it "raises exception for conflict violation" do <ide> <ide> it "raises exception on depends_on constraint violation" do <ide> expect { parser.parse(["--switch-c"]) }.to raise_error(Homebrew::CLI::OptionConstraintError) <add> expect { parser.parse(["--switch-d"]) }.to raise_error(Homebrew::CLI::OptionConstraintError) <ide> end <ide> <ide> it "raises exception for conflict violation" do
3
PHP
PHP
set connection while retrieving models
7392014bee4601a054f070f95451037d99df4ce7
<ide><path>src/Illuminate/Database/Eloquent/Builder.php <ide> public function orWhere($column, $operator = null, $value = null) <ide> */ <ide> public function hydrate(array $items) <ide> { <del> $instance = $this->model->newInstance(); <add> $instance = $this->model->newInstance()->setConnection( <add> $this->query->getConnection()->getName() <add> ); <ide> <ide> return $instance->newCollection(array_map(function ($item) use ($instance) { <ide> return $instance->newFromBuilder($item); <ide> public function get($columns = ['*']) <ide> public function getModels($columns = ['*']) <ide> { <ide> return $this->model->hydrate( <del> $this->query->get($columns)->all(), <del> $this->model->getConnectionName() <add> $this->query->get($columns)->all() <ide> )->all(); <ide> } <ide> <ide><path>tests/Database/DatabaseEloquentBuilderTest.php <ide> public function testGetModelsProperlyHydratesModels() <ide> $records[] = ['name' => 'taylor', 'age' => 26]; <ide> $records[] = ['name' => 'dayle', 'age' => 28]; <ide> $builder->getQuery()->shouldReceive('get')->once()->with(['foo'])->andReturn(new BaseCollection($records)); <del> $model = m::mock('Illuminate\Database\Eloquent\Model[getTable,getConnectionName,hydrate]'); <add> $model = m::mock('Illuminate\Database\Eloquent\Model[getTable,hydrate]'); <ide> $model->shouldReceive('getTable')->once()->andReturn('foo_table'); <ide> $builder->setModel($model); <del> $model->shouldReceive('getConnectionName')->once()->andReturn('foo_connection'); <del> $model->shouldReceive('hydrate')->once()->with($records, 'foo_connection')->andReturn(new Collection(['hydrated'])); <add> $model->shouldReceive('hydrate')->once()->with($records)->andReturn(new Collection(['hydrated'])); <ide> $models = $builder->getModels(['foo']); <ide> <ide> $this->assertEquals($models, ['hydrated']); <ide><path>tests/Database/DatabaseEloquentIntegrationTest.php <ide> public function testBelongsToManyCustomPivot() <ide> $this->assertEquals('Jule Doe', $johnWithFriends->friends->find(4)->pivot->friend->name); <ide> } <ide> <add> public function testIsAfterRetrievingTheSameModel() <add> { <add> $saved = EloquentTestUser::create(['id' => 1, 'email' => '[email protected]']); <add> $retrieved = EloquentTestUser::find(1); <add> <add> $this->assertTrue($saved->is($retrieved)); <add> } <add> <ide> /** <ide> * Helpers... <ide> */
3
Java
Java
fix typo and use of componentry
65d2e9bb547e15df4b9eda1dcf36ec17f8f3a60a
<ide><path>spring-context/src/main/java/org/springframework/scheduling/annotation/EnableAsync.java <ide> * setting of the <em>thread name prefix</em> of the {@code Executor}; this is because <ide> * the {@code <task:executor>} element does not expose such an attribute. This <ide> * demonstrates how the JavaConfig-based approach allows for maximum configurability <del> * through direct access to actual componentry. <add> * through direct access to actual component. <ide> * <ide> * <p>The {@link #mode} attribute controls how advice is applied: If the mode is <ide> * {@link AdviceMode#PROXY} (the default), then the other attributes control the behavior <ide><path>spring-context/src/main/java/org/springframework/scheduling/annotation/EnableScheduling.java <ide> * instead of a custom <em>{@code Trigger}</em> implementation; this is because the <ide> * {@code task:} namespace {@code scheduled} cannot easily expose such support. This is <ide> * but one demonstration how the code-based approach allows for maximum configurability <del> * through direct access to actual componentry. <add> * through direct access to actual component. <ide> * <ide> * <p><b>Note: {@code @EnableScheduling} applies to its local application context only, <ide> * allowing for selective scheduling of beans at different levels.</b> Please redeclare <ide><path>spring-web/src/main/java/org/springframework/http/server/RequestPath.java <ide> /* <del> * Copyright 2002-2020 the original author or authors. <add> * Copyright 2002-2021 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> /** <ide> * Specialization of {@link PathContainer} that sub-divides the path into a <ide> * {@link #contextPath()} and the remaining {@link #pathWithinApplication()}. <del> * The lattery is typically used for request mapping within the application <add> * The latter is typically used for request mapping within the application <ide> * while the former is useful when preparing external links that point back to <ide> * the application. <ide> * <ide><path>spring-web/src/main/java/org/springframework/web/SpringServletContainerInitializer.java <ide> public class SpringServletContainerInitializer implements ServletContainerInitia <ide> * method will be invoked on each instance, delegating the {@code ServletContext} such <ide> * that each instance may register and configure servlets such as Spring's <ide> * {@code DispatcherServlet}, listeners such as Spring's {@code ContextLoaderListener}, <del> * or any other Servlet API componentry such as filters. <add> * or any other Servlet API component such as filters. <ide> * @param webAppInitializerClasses all implementations of <ide> * {@link WebApplicationInitializer} found on the application classpath <ide> * @param servletContext the servlet context to be initialized
4
Java
Java
leave query un-encoded in mockmvc request builder
0b8554f94a73b1620d8c34d1a68b3eb8e56d482a
<ide><path>spring-test/src/main/java/org/springframework/test/web/servlet/request/MockHttpServletRequestBuilder.java <ide> public final MockHttpServletRequest buildRequest(ServletContext servletContext) <ide> <ide> try { <ide> if (this.uriComponents.getQuery() != null) { <del> String query = UriUtils.decode(this.uriComponents.getQuery(), "UTF-8"); <del> request.setQueryString(query); <add> request.setQueryString(this.uriComponents.getQuery()); <ide> } <ide> <ide> for (Entry<String, List<String>> entry : this.uriComponents.getQueryParams().entrySet()) { <ide><path>spring-test/src/test/java/org/springframework/test/web/servlet/request/MockHttpServletRequestBuilderTests.java <ide> public void requestParameterFromQueryList() { <ide> <ide> MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); <ide> <del> assertEquals("foo[0]=bar&foo[1]=baz", request.getQueryString()); <add> assertEquals("foo%5B0%5D=bar&foo%5B1%5D=baz", request.getQueryString()); <ide> assertEquals("bar", request.getParameter("foo[0]")); <ide> assertEquals("baz", request.getParameter("foo[1]")); <ide> } <ide> public void requestParameterFromQueryWithEncoding() { <ide> <ide> MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); <ide> <del> assertEquals("foo=bar=baz", request.getQueryString()); <add> assertEquals("foo=bar%3Dbaz", request.getQueryString()); <ide> assertEquals("bar=baz", request.getParameter("foo")); <ide> } <ide>
2
Javascript
Javascript
simplify implementation of angular.string.todate()
42855e436327eb75050f98e2c1791b5448a49e9d
<ide><path>src/apis.js <ide> var angularString = { <ide> } <ide> return chars.join(''); <ide> }, <add> <add> /** <add> * Tries to convert input to date and if successful returns the date, otherwise returns the input. <add> * @param {string} string <add> * @return {(Date|string)} <add> */ <ide> 'toDate':function(string){ <del> var match; <del> if (typeof string == 'string' && <del> (match = string.match(/^(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)Z$/))){ <del> var date = new Date(0); <del> date.setUTCFullYear(match[1], match[2] - 1, match[3]); <del> date.setUTCHours(match[4], match[5], match[6], 0); <del> return date; <del> } <del> return string; <add> var date = new Date(string); <add> return isNaN(date.getTime()) ? string : date; <ide> } <ide> }; <ide>
1
Javascript
Javascript
fix some lint issues
36b58b235eeca4e9580162a697d8a96c41263ebc
<ide><path>src/widgets.js <ide> function valueAccessor(scope, element) { <ide> format = formatter.format; <ide> parse = formatter.parse; <ide> if (requiredExpr) { <del> scope.$watch(requiredExpr, function(newValue) {required = newValue; validate();}); <add> scope.$watch(requiredExpr, function(newValue) { <add> required = newValue; <add> validate(); <add> }); <ide> } else { <ide> required = requiredExpr === ''; <ide> } <del> <ide> <ide> element.data('$validate', validate); <ide> return { <ide><path>test/widgetsSpec.js <ide> describe("widget", function(){ <ide> expect(element.hasClass('ng-validation-error')).toBeFalsy(); <ide> expect(element.attr('ng-validation-error')).toBeFalsy(); <ide> <add> scope.$set('price', ''); <ide> scope.$set('ineedz', true); <ide> scope.$eval(); <del> expect(element.hasClass('ng-validation-error')).toBeFalsy(); <del> expect(element.attr('ng-validation-error')).toBeFalsy(); <del> <del> element.val(''); <del> element.trigger('keyup'); <ide> expect(element.hasClass('ng-validation-error')).toBeTruthy(); <ide> expect(element.attr('ng-validation-error')).toEqual('Required'); <add> <add> element.val('abc'); <add> element.trigger('keyup'); <add> expect(element.hasClass('ng-validation-error')).toBeFalsy(); <add> expect(element.attr('ng-validation-error')).toBeFalsy(); <ide> }); <ide> <ide> it("should process ng-required2", function() {
2
Text
Text
move changelog entry in railties to the top
149b86d97bd14b26cdf1d408567a414418710bcf
<ide><path>activerecord/CHANGELOG.md <ide> ## Rails 4.0.0 (unreleased) ## <ide> <del>* Support for PostgreSQL's ltree data type. <add>* Support for PostgreSQL's `ltree` data type. <ide> <ide> *Rob Worley* <ide> <ide> This is a soft-deprecation for `update_attributes`, although it will still work without any <ide> deprecation message in 4.0 is recommended to start using `update` since `update_attributes` will be <ide> deprecated and removed in future versions of Rails. <del> <add> <ide> *Amparo Luna + Guillermo Iguaran* <ide> <ide> * `after_commit` and `after_rollback` now validate the `:on` option and raise an `ArgumentError` <ide><path>activesupport/CHANGELOG.md <ide> ## Rails 4.0.0 (unreleased) ## <ide> <del>* Change String#to_date to use Date.parse. This gives more consistant error <add>* Change `String#to_date` to use `Date.parse`. This gives more consistent error <ide> messages and allows the use of partial dates. <ide> <ide> "gibberish".to_date => Argument Error: invalid date <ide> "3rd Feb".to_date => Sun, 03 Feb 2013 <ide> <ide> *Kelly Stannard* <ide> <del>* It's now possible to compare Date, DateTime, Time and TimeWithZone with Infinity <del> This allows to create date/time ranges with one infinite bound. <add>* It's now possible to compare `Date`, `DateTime`, `Time` and `TimeWithZone` <add> with `Infinity`. This allows to create date/time ranges with one infinite bound. <ide> Example: <ide> <ide> range = Range.new(Date.today, Float::INFINITY) <ide><path>railties/CHANGELOG.md <ide> ## Rails 4.0.0 (unreleased) ## <ide> <del>* Add `-B` alias for `--skip-bundle` option in the rails new generators. <add>* Environment name can be a start substring of the default environment names <add> (production, development, test). For example: tes, pro, prod, dev, devel. <add> Fix #8628. <ide> <del> *Jiri Pospisil* <add> *Mykola Kyryk* <ide> <del>* Environment name can be a start substring of the default environment names <del> (production, development, test). <del> For example: tes, pro, prod, dev, devel. <del> Fix #8628 <add>* Add `-B` alias for `--skip-bundle` option in the rails new generators. <ide> <del> *Mykola Kyryk* <add> *Jiri Pospisil* <ide> <ide> * Quote column names in generates fixture files. This prevents <ide> conflicts with reserved YAML keywords such as 'yes' and 'no' <del> Fix #8612 <add> Fix #8612. <ide> <ide> *Yves Senn* <ide>
3
Ruby
Ruby
convert edit test to spec
3ef51dba055700ecca9a4f10e1fe0e714b7f9889
<add><path>Library/Homebrew/cask/spec/cask/cli/edit_spec.rb <del><path>Library/Homebrew/cask/test/cask/cli/edit_test.rb <del>require "test_helper" <add>require "spec_helper" <ide> <ide> # monkeypatch for testing <ide> module Hbc <ide> def self.editor_commands <ide> end <ide> <ide> describe Hbc::CLI::Edit do <del> before do <add> before(:each) do <ide> Hbc::CLI::Edit.reset! <ide> end <ide> <ide> it "opens the editor for the specified Cask" do <del> Hbc::CLI::Edit.run("alfred") <del> Hbc::CLI::Edit.editor_commands.must_equal [ <del> [Hbc.path("alfred")], <add> Hbc::CLI::Edit.run("local-caffeine") <add> expect(Hbc::CLI::Edit.editor_commands).to eq [ <add> [Hbc.path("local-caffeine")], <ide> ] <ide> end <ide> <ide> it "throws away additional arguments and uses the first" do <del> Hbc::CLI::Edit.run("adium", "alfred") <del> Hbc::CLI::Edit.editor_commands.must_equal [ <del> [Hbc.path("adium")], <add> Hbc::CLI::Edit.run("local-caffeine", "local-transmission") <add> expect(Hbc::CLI::Edit.editor_commands).to eq [ <add> [Hbc.path("local-caffeine")], <ide> ] <ide> end <ide> <ide> it "raises an exception when the Cask doesnt exist" do <del> lambda { <add> expect { <ide> Hbc::CLI::Edit.run("notacask") <del> }.must_raise Hbc::CaskUnavailableError <add> }.to raise_error(Hbc::CaskUnavailableError) <ide> end <ide> <ide> describe "when no Cask is specified" do <ide> it "raises an exception" do <del> lambda { <add> expect { <ide> Hbc::CLI::Edit.run <del> }.must_raise Hbc::CaskUnspecifiedError <add> }.to raise_error(Hbc::CaskUnspecifiedError) <ide> end <ide> end <ide> <ide> describe "when no Cask is specified, but an invalid option" do <ide> it "raises an exception" do <del> lambda { <add> expect { <ide> Hbc::CLI::Edit.run("--notavalidoption") <del> }.must_raise Hbc::CaskUnspecifiedError <add> }.to raise_error(Hbc::CaskUnspecifiedError) <ide> end <ide> end <ide> end
1
Python
Python
add test for non native bytetypes
a4bb3bc1dc2e5c7114e77e4a92df04d57ee02c9b
<ide><path>numpy/core/tests/test_ufunc.py <ide> def test_inplace_fancy_indexing(self): <ide> np.add.at(a, [0,1], 3) <ide> assert_array_equal(orig, np.arange(4)) <ide> <add> dt = np.dtype(np.intp).newbyteorder() <add> index = np.array([1,2,3], dt) <add> dt = np.dtype(np.float_).newbyteorder() <add> values = np.array([1,2,3,4], dt) <add> np.add.at(values, index, 3) <add> <ide> if __name__ == "__main__": <ide> run_module_suite()
1
Go
Go
fix typo mistake
fa9e54fbf112c44de05a66330fc22303b1681d05
<ide><path>daemon/execdriver/termconsole.go <ide> func (s *StdConsole) AttachPipes(command *exec.Cmd, pipes *Pipes) error { <ide> <ide> // Resize implements Resize method of Terminal interface <ide> func (s *StdConsole) Resize(h, w int) error { <del> // we do not need to reside a non tty <add> // we do not need to resize a non tty <ide> return nil <ide> } <ide>
1
Text
Text
remove docs for unimplemented api
dd83b5f2ac3a9684044b4aa5ad0b3832ea63694b
<ide><path>doc/api/perf_hooks.md <ide> the Performance Timeline or any of the timestamp properties provided by the <ide> `PerformanceNodeTiming` class. If the named `endMark` does not exist, an <ide> error will be thrown. <ide> <del>### performance.nodeFrame <del><!-- YAML <del>added: v8.5.0 <del>--> <del> <del>* {PerformanceFrame} <del> <del>An instance of the `PerformanceFrame` class that provides performance metrics <del>for the event loop. <del> <ide> ### performance.nodeTiming <ide> <!-- YAML <ide> added: v8.5.0 <ide> The value may be one of: <ide> * `perf_hooks.constants.NODE_PERFORMANCE_GC_INCREMENTAL` <ide> * `perf_hooks.constants.NODE_PERFORMANCE_GC_WEAKCB` <ide> <del>## Class: PerformanceNodeFrame extends PerformanceEntry <del><!-- YAML <del>added: v8.5.0 <del>--> <del> <del>Provides timing details for the Node.js event loop. <del> <del>### performanceNodeFrame.frameCheck <del> <del>The high resolution timestamp when `uv_check_t` processing occurred on the <del>current loop. <del> <del>### performanceNodeFrame.frameCount <del> <del>The total number of event loop iterations (iterated when `uv_idle_t` <del>processing occurrs). <del> <del>### performanceNodeFrame.frameIdle <del> <del>The high resolution timestamp when `uv_idle_t` processing occurred on the <del>current loop. <del> <del>### performanceNodeFrame.framesPerSecond <del> <del>The number of event loop iterations per second. <del> <del>### performanceNodeFrame.framePrepare <del> <del>The high resolution timestamp when `uv_prepare_t` processing occurred on the <del>current loop. <del> <ide> ## Class: PerformanceNodeTiming extends PerformanceEntry <ide> <!-- YAML <ide> added: v8.5.0
1
Python
Python
add roles to create_user test
a1a32f7c7c2df41e6150f2594a3a41bfecb76fb0
<ide><path>tests/www/views/test_views_base.py <ide> def test_create_user(app, admin_client, non_exist_username): <ide> 'last_name': 'fake_last_name', <ide> 'username': non_exist_username, <ide> 'email': '[email protected]', <add> 'roles': [1], <ide> 'password': 'test', <ide> 'conf_password': 'test', <ide> },
1
Text
Text
fix all github issues and prs query params
4d60346fc4691881ccf448c7b0e8076c882ee52f
<ide><path>docs/_posts/2017-09-08-dom-attributes-in-react-16.md <ide> It uses React 16 RC, and you can [help us by testing the RC in your project!](ht <ide> <ide> ## Thanks <ide> <del>This effort was largely driven by [Nathan Hunzaker](https://github.com/nhunzaker) who has been a [prolific outside contributor to React](https://github.com/facebook/react/pulls?q=is%3Apr+author%3Anhunzaker+is%3Aclosed). <add>This effort was largely driven by [Nathan Hunzaker](https://github.com/nhunzaker) who has been a [prolific outside contributor to React](https://github.com/facebook/react/pulls?q=is:pr+author:nhunzaker+is:closed). <ide> <ide> You can find his work on this issue in several PRs over the course of last year: [#6459](https://github.com/facebook/react/pull/6459), [#7311](https://github.com/facebook/react/pull/7311), [#10229](https://github.com/facebook/react/pull/10229), [#10397](https://github.com/facebook/react/pull/10397), [#10385](https://github.com/facebook/react/pull/10385), and [#10470](https://github.com/facebook/react/pull/10470). <ide> <ide><path>docs/contributing/codebase-overview.md <ide> It is important to understand that the stack reconciler always processes the com <ide> <ide> The "fiber" reconciler is a new effort aiming to resolve the problems inherent in the stack reconciler and fix a few long-standing issues. <ide> <del>It is a complete rewrite of the reconciler and is currently [in active development](https://github.com/facebook/react/pulls?utf8=%E2%9C%93&q=is%3Apr%20is%3Aopen%20fiber). <add>It is a complete rewrite of the reconciler and is currently [in active development](https://github.com/facebook/react/pulls?utf8=✓&q=is:pr+is:open+fiber). <ide> <ide> Its main goals are: <ide> <ide><path>docs/contributing/design-principles.md <ide> For example, if React didn't provide support for local state or lifecycle hooks, <ide> <ide> This is why sometimes we add features to React itself. If we notice that many components implement a certain feature in incompatible or inefficient ways, we might prefer to bake it into React. We don't do it lightly. When we do it, it's because we are confident that raising the abstraction level benefits the whole ecosystem. State, lifecycle hooks, cross-browser event normalization are good examples of this. <ide> <del>We always discuss such improvement proposals with the community. You can find some of those discussions by the [“big picture”](https://github.com/facebook/react/issues?q=is%3Aopen+is%3Aissue+label%3A%22big+picture%22) label on the React issue tracker. <add>We always discuss such improvement proposals with the community. You can find some of those discussions by the ["big picture"](https://github.com/facebook/react/issues?q=is:open+is:issue+label:"big+picture") label on the React issue tracker. <ide> <ide> ### Escape Hatches <ide> <ide><path>docs/contributing/how-to-contribute.md <ide> If you send a pull request, please do it against the `master` branch. We maintai <ide> <ide> React follows [semantic versioning](http://semver.org/). We release patch versions for bugfixes, minor versions for new features, and major versions for any breaking changes. When we make breaking changes, we also introduce deprecation warnings in a minor version so that our users learn about the upcoming changes and migrate their code in advance. <ide> <del>We tag every pull request with a label marking whether the change should go in the next [patch](https://github.com/facebook/react/pulls?q=is%3Aopen+is%3Apr+label%3Asemver-patch), [minor](https://github.com/facebook/react/pulls?q=is%3Aopen+is%3Apr+label%3Asemver-minor), or a [major](https://github.com/facebook/react/pulls?q=is%3Aopen+is%3Apr+label%3Asemver-major) version. We release new patch versions every few weeks, minor versions every few months, and major versions one or two times a year. <add>We tag every pull request with a label marking whether the change should go in the next [patch](https://github.com/facebook/react/pulls?q=is:open+is:pr+label:semver-patch), [minor](https://github.com/facebook/react/pulls?q=is:open+is:pr+label:semver-minor), or a [major](https://github.com/facebook/react/pulls?q=is:open+is:pr+label:semver-major) version. We release new patch versions every few weeks, minor versions every few months, and major versions one or two times a year. <ide> <ide> Every significant change is documented in the [changelog file](https://github.com/facebook/react/blob/master/CHANGELOG.md). <ide> <ide> Working on your first Pull Request? You can learn how from this free video serie <ide> <ide> **[How to Contribute to an Open Source Project on GitHub](https://egghead.io/series/how-to-contribute-to-an-open-source-project-on-github)** <ide> <del>To help you get your feet wet and get you familiar with our contribution process, we have a list of **[beginner friendly issues](https://github.com/facebook/react/issues?q=is:open+is:issue+label:%22Difficulty:+beginner%22)** that contain bugs which are fairly easy to fix. This is a great place to get started. <add>To help you get your feet wet and get you familiar with our contribution process, we have a list of **[beginner friendly issues](https://github.com/facebook/react/issues?q=is:open+is:issue+label:"Difficulty:+beginner")** that contain bugs which are fairly easy to fix. This is a great place to get started. <ide> <ide> If you decide to fix an issue, please be sure to check the comment thread in case somebody is already working on a fix. If nobody is working on it at the moment, please leave a comment stating that you intend to work on it so other people don't accidentally duplicate your effort. <ide>
4
Ruby
Ruby
remove unneeded yaml_as declaration
452dba72f5bac3118a3405408665ae372ebbe6a1
<ide><path>activesupport/lib/active_support/core_ext/big_decimal/conversions.rb <ide> class BigDecimal <ide> YAML_TAG = 'tag:yaml.org,2002:float' <ide> YAML_MAPPING = { 'Infinity' => '.Inf', '-Infinity' => '-.Inf', 'NaN' => '.NaN' } <ide> <del> yaml_as YAML_TAG <del> <ide> # This emits the number without any scientific notation. <ide> # This is better than self.to_f.to_s since it doesn't lose precision. <ide> #
1
Text
Text
update chinese translation of es6
83957bb15080b7324beceb05cad08930c5aa4d1d
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/compare-scopes-of-the-var-and-let-keywords.chinese.md <ide> id: 587d7b87367417b2b2512b40 <ide> title: Compare Scopes of the var and let Keywords <ide> challengeType: 1 <del>videoUrl: '' <del>localeTitle: 比较var的范围并让关键字 <add>forumTopicId: 301195 <add>localeTitle: 比较 var 和 let 关键字的作用域 <ide> --- <ide> <ide> ## Description <del><section id="description">使用<code>var</code>关键字声明变量时,它将全局声明,如果在函数内声明,则声明为本地。 <code>let</code>关键字的行为类似,但具有一些额外的功能。在块,语句或表达式中使用<code>let</code>关键字声明变量时,其范围仅限于该块,语句或表达式。例如: <blockquote> var numArray = []; <br> for(var i = 0; i &lt;3; i ++){ <br> numArray.push(ⅰ); <br> } <br>的console.log(numArray); <br> //返回[0,1,2] <br>的console.log(ⅰ); <br> //返回3 </blockquote>使用<code>var</code>关键字, <code>i</code>被全局声明。因此,当执行<code>i++</code>时,它会更新全局变量。此代码类似于以下内容: <blockquote> var numArray = []; <br> var i; <br> for(i = 0; i &lt;3; i ++){ <br> numArray.push(ⅰ); <br> } <br>的console.log(numArray); <br> //返回[0,1,2] <br>的console.log(ⅰ); <br> //返回3 </blockquote>如果您要创建一个函数并将其存储以供以后在使用<code>i</code>变量的for循环中使用,则此行为将导致问题。这是因为存储的函数将始终引用更新的全局<code>i</code>变量的值。 <blockquote> var printNumTwo; <br> for(var i = 0; i &lt;3; i ++){ <br> if(i === 2){ <br> printNumTwo = function(){ <br>return i; <br> }; <br> } <br> } <br>的console.log(printNumTwo()); <br> //返回3 </blockquote>正如你所看到的, <code>printNumTwo()</code>打印3,而不是2.这是因为分配给该值<code>i</code>进行了更新和<code>printNumTwo()</code>返回全球<code>i</code> ,而不是价值<code>i</code>的作用是在创建for循环的时候了。 <code>let</code>关键字不遵循此行为: <blockquote> &#39;use strict&#39;; <br>让printNumTwo; <br> for(let i = 0; i &lt;3; i ++){ <br> if(i === 2){ <br> printNumTwo = function(){ <br>return i;<br> }; <br> } <br> } <br>的console.log(printNumTwo()); <br> //返回2 <br>的console.log(ⅰ); <br> //返回“i没有定义” </blockquote> <code>i</code>没有定义,因为它没有在全局范围内声明。它仅在for循环语句中声明。 <code>printNumTwo()</code>返回正确的值,因为循环语句中的<code>let</code>关键字创建了具有唯一值(0,1和2)的三个不同的<code>i</code>变量。 </section> <add><section id='description'> <add>当你使用<code>var</code>关键字来声明一个变量的时候,这个变量会被声明成全局变量,或是函数内的局部变量。 <add><code>let</code>关键字的作用类似,但会有一些额外的特性。如果你在代码块、语句或表达式中使用关键字<code>let</code>声明变量,这个变量的作用域就被限制在当前的代码块,语句或表达式之中。 <add>举个例子: <add> <add>```js <add>var numArray = []; <add>for (var i = 0; i < 3; i++) { <add> numArray.push(i); <add>} <add>console.log(numArray); <add>// 返回 [0, 1, 2] <add>console.log(i); <add>// 返回 3 <add>``` <add> <add>当使用<code>var</code>关键字的时候,<code>i</code>会被声明成全局变量。当<code>i++</code>执行的时候,它会改变全局变量的值。这段代码可以看做下面这样: <add> <add>```js <add>var numArray = []; <add>var i; <add>for (i = 0; i < 3; i++) { <add> numArray.push(i); <add>} <add>console.log(numArray); <add>// 返回 [0, 1, 2] <add>console.log(i); <add>// 返回 3 <add>``` <add> <add>如果你在<code>for</code>循环中创建了使用<code>i</code>变量的函数,那么在后续调用函数的时候,上面提到的这种行为就会出现问题。这是因为函数存储的值会因为全局变量<code>i</code>的变化而不断的改变。 <add> <add>```js <add>var printNumTwo; <add>for (var i = 0; i < 3; i++) { <add> if (i === 2) { <add> printNumTwo = function() { <add> return i; <add> }; <add> } <add>} <add>console.log(printNumTwo()); <add>// 返回 3 <add>``` <add> <add>可以看到,<code>printNumTwo()</code>打印了 3 而不是 2。这是因为<code>i</code>发生了改变,并且函数<code>printNumTwo()</code>返回的是全局变量<code>i</code>的值,而不是<code>for</code>循环中创建函数时<code>i</code>的值。<code>let</code>关键字就不会有这种现象: <add> <add>```js <add>'use strict'; <add>let printNumTwo; <add>for (let i = 0; i < 3; i++) { <add> if (i === 2) { <add> printNumTwo = function() { <add> return i; <add> }; <add> } <add>} <add>console.log(printNumTwo()); <add>// 返回 2 <add>console.log(i); <add>// 返回 "i 未定义" <add>``` <add> <add><code>i</code>在全局作用域中没有声明,所以它没有被定义,它的声明只会发生在<code>for</code>循环内。在循环执行的时候,<code>let</code>关键字创建了三个不同的<code>i</code>变量,他们的值分别为 0、1 和 2,所以<code>printNumTwo()</code>返回了正确的值。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">修复代码,以便<code>i</code>在if语句中声明的是一个单独的变量,而不是<code>i</code>在函数的第一行声明的变量。确保不要在代码中的任何位置使用<code>var</code>关键字。本练习旨在说明<code>var</code>和<code>let</code>关键字如何将范围分配给声明的变量之间的区别。在编写与本练习中使用的函数类似的函数时,通常最好使用不同的变量名来避免混淆。 </section> <add><section id='instructions'> <add>修改这段代码,使得在<code>if</code>语句中声明的<code>i</code>变量与在函数的第一行声明的<code>i</code>变量是彼此独立的。请注意不要在你的代码的任何地方使用<code>var</code>关键字。 <add>这个练习说明了使用<code>var</code>与<code>let</code>关键字声明变量时,作用域之间的不同。当编写类似这个练习中的函数的时候,通常来说最好还是使用不同的变量名来避免误会。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: <code>var</code>在代码中不存在。 <add> - text: <code>var</code>不应该在代码中存在。 <ide> testString: getUserInput => assert(!getUserInput('index').match(/var/g)); <del> - text: 在if语句中声明的变量<code>i</code>应该等于“块范围”。 <add> - text: "在<code>if</code>语句中声明的<code>i</code>变量的值是 'block scope'。" <ide> testString: getUserInput => assert(getUserInput('index').match(/(i\s*=\s*).*\s*.*\s*.*\1('|")block\s*scope\2/g)); <del> - text: <code>checkScope()</code>应该返回“函数范围” <add> - text: "<code>checkScope()</code>应当返回 'function scope'" <ide> testString: assert(checkScope() === "function scope"); <ide> <ide> ``` <ide> tests: <ide> <ide> ```js <ide> function checkScope() { <del>"use strict"; <del> var i = "function scope"; <add> 'use strict'; <add> var i = 'function scope'; <ide> if (true) { <del> i = "block scope"; <del> console.log("Block scope i is: ", i); <add> i = 'block scope'; <add> console.log('Block scope i is: ', i); <ide> } <del> console.log("Function scope i is: ", i); <add> console.log('Function scope i is: ', i); <ide> return i; <ide> } <del> <ide> ``` <ide> <ide> </div> <ide> function checkScope() { <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add>function checkScope() { <add> 'use strict'; <add> let i = 'function scope'; <add> if (true) { <add> let i = 'block scope'; <add> console.log('Block scope i is: ', i); <add> } <add> <add> console.log('Function scope i is: ', i); <add> return i; <add>} <ide> ``` <add> <ide> </section> <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/complete-a-promise-with-resolve-and-reject.chinese.md <add>--- <add>id: 5cdafbc32913098997531680 <add>title: Complete a Promise with resolve and reject <add>challengeType: 1 <add>forumTopicId: 301196 <add>localeTitle: 通过 resolve 和 reject 完成 Promise <add>--- <add> <add>## Description <add><section id='description'> <add>promise 有三个状态:<code>pending</code>、<code>fulfilled</code> 和 <code>rejected</code>。上一个挑战里创建的 promise 一直阻塞在 <code>pending</code> 状态里,因为没有调用 promise 的完成方法。promise 提供的 <code>resolve</code> 和 <code>reject</code> 参数就是用来结束 promise 的。promise 成功时调用 <code>resolve</code>,promise 执行失败时调用 <code>reject</code>,这两个方法接收一个参数,如下所示。 <add> <add>```js <add>const myPromise = new Promise((resolve, reject) => { <add> if(condition here) { <add> resolve("Promise was fulfilled"); <add> } else { <add> reject("Promise was rejected"); <add> } <add>}); <add>``` <add> <add>上面的例子使用字符串做为函数的参数,也可以是任意类型,通常会是对象,里面可能是将要放到页面或其它地方的数据。 <add></section> <add> <add>## Instructions <add><section id='instructions'> <add>使 promise 可以处理成功和失败情况。如果 <code>responseFromServer</code> 是 <code>true</code>,调用 <code>resolve</code> 方法使 promise 成功。给 <code>resolve</code> 传递值为 <code>We got the data</code> 的字符串。如果 <code>responseFromServer</code> 是 <code>false</code>, 使用 <code>reject</code> 方法并传入值为 <code>Data not received</code> 的字符串。 <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: 当 <code>if</code> 条件是 <code>true</code> 时应该执行 <code>resolve</code>。 <add> testString: assert(removeJSComments(code).match(/if\s*\(\s*responseFromServer\s*\)\s*{\s*resolve\s*\(\s*('|"|`)We got the data\1\s*\)(\s*|\s*;\s*)}/g)); <add> - text: 当 <code>if</code> 条件是 <code>false</code> 时应该执行 <code>reject</code>。 <add> testString: assert(removeJSComments(code).match(/}\s*else\s*{\s*reject\s*\(\s*('|"|`)Data not received\1\s*\)(\s*|\s*;\s*)}/g)); <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add><div id='js-seed'> <add> <add>```js <add>const makeServerRequest = new Promise((resolve, reject) => { <add> // responseFromServer represents a response from a server <add> let responseFromServer; <add> <add> if(responseFromServer) { <add> // change this line <add> } else { <add> // change this line <add> } <add>}); <add>``` <add> <add></div> <add> <add>### After Test <add><div id='js-teardown'> <add> <add>```js <add>const removeJSComments = str => str.replace(/\/\*[\s\S]*?\*\/|\/\/.*$/gm, ''); <add>``` <add> <add></div> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>const makeServerRequest = new Promise((resolve, reject) => { <add> // responseFromServer represents a response from a server <add> let responseFromServer; <add> <add> if(responseFromServer) { <add> resolve("We got the data"); <add> } else { <add> reject("Data not received"); <add> } <add>}); <add>``` <add> <add></section> <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/create-a-javascript-promise.chinese.md <add>--- <add>id: 5cdafbb0291309899753167f <add>title: Create a JavaScript Promise <add>challengeType: 1 <add>forumTopicId: 301197 <add>localeTitle: 创建一个 JavaScript Promise <add>--- <add> <add>## Description <add><section id='description'> <add>Promise 是异步编程的一种解决方案 - 它在未来的某时会生成一个值。任务完成,分执行成功和执行失败两种情况。<code>Promise</code> 是构造器函数,需要通过 <code>new</code> 关键字来创建。构造器参数是一个函数,该函数有两个参数 - <code>resolve</code> 和 <code>reject</code>。通过它们来判断 promise 的执行结果。用法如下: <add> <add>```js <add>const myPromise = new Promise((resolve, reject) => { <add> <add>}); <add>``` <add> <add></section> <add> <add>## Instructions <add><section id='instructions'> <add>创建一个名为 <code>makeServerRequest</code> 的 promise。给构造器函数传入 <code>resolve</code> 和 <code>reject</code> 两个参数。 <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: 应该给名为 <code>makeServerRequest</code> 的变量指定一个 promise。 <add> testString: assert(makeServerRequest instanceof Promise); <add> - text: promise 应该接收一个函数做为参数,该函数应该包含 <code>resolve</code> 和 <code>reject</code> 两个参数。 <add> testString: assert(code.match(/Promise\(\s*(function\s*\(\s*resolve\s*,\s*reject\s*\)\s*{|\(\s*resolve\s*,\s*reject\s*\)\s*=>\s*{)[^}]*}/g)); <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add><div id='js-seed'> <add> <add>```js <add> <add>``` <add> <add></div> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>const makeServerRequest = new Promise((resolve, reject) => { <add> <add>}); <add>``` <add> <add></section> <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/create-a-module-script.chinese.md <add>--- <add>id: 5cddbfd622f1a59093ec611d <add>title: Create a Module Script <add>challengeType: 6 <add>forumTopicId: 301198 <add>localeTitle: 创建一个模块脚本 <add>--- <add> <add>## Description <add><section id='description'> <add>起初,JavaScript 几乎只在 HTML web 扮演一个很小的角色。今天,一切不同了,很多网站几乎全是用 JavaScript 所写。为了让 JavaScript 更模块化、更整洁以及更易于维护,ES6 引入了在多个 JavaScript 文件之间共享代码的机制。它可以导出文件的一部分供其它文件使用,然后在需要它的地方按需导入。为了使用这一功能, 需要在 HTML 文档里创建一个类型为 <code>module</code> 的脚本。例子如下: <add> <add>```html <add><script type="module" src="filename.js"></script> <add>``` <add> <add>使用了 <code>module</code> 类型的脚本后可以再接下来的挑战里使用 <code>import</code> 和 <code>export</code> 特性。 <add></section> <add> <add>## Instructions <add><section id='instructions'> <add>给 HTML 文档添加 <code>module</code> 类型的脚本,指定源文件为 <code>index.js</code>。 <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: 应该创建一个 <code>script</code> 标签。 <add> testString: assert(code.match(/<\s*script[^>]*>\s*<\/\s*script\s*>/g)); <add> - text: <code>script</code> 标签的类型应该为 <code>module</code>。 <add> testString: assert(code.match(/<\s*script\s+[^t]*type\s*=\s*('|")module\1[^>]*>\s*<\/\s*script\s*>/g)); <add> - text: <code>script</code> 标签的 <code>src</code> 属性应该为 <code>index.js</code>。 <add> testString: assert(code.match(/<\s*script\s+[^s]*src\s*=\s*('|")index\.js\1[^>]*>\s*<\/\s*script\s*>/g)); <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add><div id='html-seed'> <add> <add>```html <add><html> <add> <body> <add> <!-- add your code below --> <add> <add> <!-- add your code above --> <add> </body> <add></html> <add>``` <add> <add></div> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```html <add><html> <add> <body> <add> <!-- add your code below --> <add> <script type="module" src="index.js"></script> <add> <!-- add your code above --> <add> </body> <add></html> <add>``` <add> <add></section> <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/create-an-export-fallback-with-export-default.chinese.md <ide> id: 587d7b8c367417b2b2512b58 <ide> title: Create an Export Fallback with export default <ide> challengeType: 1 <del>videoUrl: '' <del>localeTitle: 使用导出默认值创建导出回退 <add>forumTopicId: 301199 <add>localeTitle: 用 export default 创建一个默认导出 <ide> --- <ide> <ide> ## Description <del><section id="description">在<code>export</code>课程中,您了解了称为<dfn>命名导出</dfn>的语法。这使您可以使多个函数和变量可用于其他文件。您需要知道另一种<code>export</code>语法,称为<dfn>导出默认值</dfn> 。通常,如果只从文件导出一个值,您将使用此语法。它还用于为文件或模块创建回退值。以下是<code>export default</code>的快速示例: <blockquote> export default function add(x,y){ <br> &nbsp;&nbsp;return x + y; <br> } </blockquote>注意:由于<code>export default</code>用于声明模块或文件的回退值,因此每个模块或文件中只能有一个值作为默认导出。此外,您不能将<code>export default</code>用于<code>var</code> , <code>let</code>或<code>const</code> </section> <add><section id='description'> <add>在<code>export</code>的课程中,学习了<dfn>命名导出</dfn>语法。这可以在其他文件中引用一些函数或者变量。 <add>还需要了解另外一种被称为<dfn>默认导出</dfn>的<code>export</code>的语法。在文件中只有一个值需要导出的时候,通常会使用这种语法。它也常常用于给文件或者模块创建返回值。 <add>下面是一个简单的<code>export default</code>例子: <add> <add>```js <add>// named function <add>export default function add(x, y) { <add> return x + y; <add>} <add> <add>// anonymous function <add>export default function(x, y) { <add> return x + y; <add>} <add>``` <add> <add>注意:当使用<code>export default</code>去声明一个文件或者模块的返回值时,在每个文件或者模块中应当只默认导出一个值。特别地,能将<code>export deafult</code>与<code>var</code>,<code>let</code>与<code>const</code>一起使用。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">以下函数应该是模块的回退值。请添加必要的代码。 </section> <add><section id='instructions'> <add>下面的函数应该在这个模块中返回一个值。请添加需要的代码: <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 适当使用<code>export</code>回落。 <add> - text: 正确的使用<code>export</code>进行返回。 <ide> testString: assert(code.match(/export\s+default\s+function(\s+subtract\s*|\s*)\(\s*x,\s*y\s*\)\s*{/g)); <del> <ide> ``` <ide> <ide> </section> <ide> <ide> ## Challenge Seed <ide> <section id='challengeSeed'> <del> <ide> <div id='js-seed'> <ide> <ide> ```js <del>"use strict"; <del>function subtract(x,y) {return x - y;} <del> <add>function subtract(x, y) { <add> return x - y; <add>} <ide> ``` <ide> <ide> </div> <del> <del>### Before Test <del><div id='js-setup'> <del> <del>```js <del>window.exports = function(){}; <del> <del>``` <del> <del></div> <del> <del> <ide> </section> <ide> <ide> ## Solution <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add>export default function subtract(x, y) { <add> return x - y; <add>} <ide> ``` <add> <ide> </section> <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/create-strings-using-template-literals.chinese.md <ide> id: 587d7b8a367417b2b2512b4e <ide> title: Create Strings using Template Literals <ide> challengeType: 1 <del>videoUrl: '' <del>localeTitle: 使用模板文字创建字符串 <add>forumTopicId: 301200 <add>localeTitle: 使用模板字面量创建字符串 <ide> --- <ide> <ide> ## Description <del><section id="description"> ES6的一个新功能是<dfn>模板文字</dfn> 。这是一种特殊类型的字符串,可以更轻松地创建复杂字符串。模板文字允许您创建多行字符串并使用字符串插值功能来创建字符串。考虑以下代码: <blockquote> const person = { <br>name: "Zodiac Hasbro", <br>age: 56<br> }; <br><br> //具有多行和字符串插值的模板文字<br> const greeting =`您好,我的名字是${person.name}! <br>我是${person.age}岁。` <br><br>的console.log(greeting); //打印<br> //你好,我的名字是Zodiac Hasbro! <br> //我今年56岁<br></blockquote>那里发生了很多事情。首先,例如使用反引号( <code>`</code> ),而不是引号( <code>&#39;</code>或<code>&quot;</code> ),换行字符串。其次,请注意,该字符串是多线,无论是在代码和输出。这节省了插入<code>\n</code>串内。上面使用的<code>${variable}</code>语法是占位符。基本上,您不必再使用<code>+</code>运算符连接。要将变量添加到字符串,只需将变量放在模板字符串中并用<code>${</code>包装它<code>}</code>同样,您可以在您的字符串表达式的其他文字,例如<code>${a + b}</code>这个新创建的字符串的方式为您提供了更大的灵活性,以创建强大的字符串。 </section> <add><section id='description'> <add>模板字符串是 ES6 的另外一项新的功能。这是一种可以轻松构建复杂字符串的方法。 <add>模板字符串可以使用多行字符串和字符串插值功能。 <add>请看以下代码: <add> <add>```js <add>const person = { <add> name: "Zodiac Hasbro", <add> age: 56 <add>}; <add> <add>// Template literal with multi-line and string interpolation <add>const greeting = `Hello, my name is ${person.name}! <add>I am ${person.age} years old.`; <add> <add>console.log(greeting); // prints <add>// Hello, my name is Zodiac Hasbro! <add>// I am 56 years old. <add> <add>``` <add> <add>这段代码有许多的不同: <add>首先,上面的例子使用了反引号(<code>`</code>)而不是引号(<code>'</code> 或者 <code>"</code>)定义字符串。 <add>其次,注意字符串是多行的,不管是代码还是输出。这是因为在字符串内插入了 <code>\n</code>。 <add>上面使用的<code>${variable}</code>语法是一个占位符。这样一来,你将不再需要使用<code>+</code>运算符来连接字符串。当需要在字符串里增加变量的时候,你只需要在变量的外面括上<code>${</code>和<code>}</code>,并将其放在字符串里就可以了。 <add>这个新的方式使你可以更灵活的创建复杂的字符串。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">使用带有反引号的模板文字语法来显示<code>result</code>对象的<code>failure</code>数组的每个条目。每个条目都应该包含在一个带有class属性<code>text-warning</code>的<code>li</code>元素中,并列在<code>resultDisplayArray</code> 。 </section> <add><section id='instructions'> <add>使用模板字符串的反引号的语法来展示<code>result</code>对象的<code>failure</code>数组内的每个条目。每个条目应该括在带有<code>text-warning</code>类属性的<code>li</code>标签中,并赋值给<code>resultDisplayArray</code>。 <add>使用遍历方法(可以是任意形式的循环)输出指定值。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: <code>resultDisplayArray</code>是一个包含<code>result failure</code>消息的数组。 <del> testString: 'assert(typeof makeList(result.failure) === "object" && resultDisplayArray.length === 3, "<code>resultDisplayArray</code> is a list containing <code>result failure</code> messages.");' <del> - text: <code>resultDisplayArray</code>是所需的输出。 <del> testString: 'assert(makeList(result.failure).every((v, i) => v === `<li class="text-warning">${result.failure[i]}</li>` || v === `<li class="text-warning">${result.failure[i]}</li>`), "<code>resultDisplayArray</code> is the desired output.");' <del> - text: 使用了模板字符串 <del> testString: 'getUserInput => assert(getUserInput("index").match(/`.*`/g), "Template strings were not used");' <del> <add> - text: <code>resultDisplayArray</code> 是一个包含了 <code>result failure</code> 内的消息的数组。 <add> testString: assert(typeof makeList(result.failure) === 'object' && resultDisplayArray.length === 3); <add> - text: <code>resultDisplayArray</code> 要有正确的输出。 <add> testString: assert(makeList(result.failure).every((v, i) => v === `<li class="text-warning">${result.failure[i]}</li>` || v === `<li class='text-warning'>${result.failure[i]}</li>`)); <add> - text: 应使用模板字符串。 <add> testString: getUserInput => assert(getUserInput('index').match(/(`.*\${.*}.*`)/)); <add> - text: 应该遍历。 <add> testString: getUserInput => assert(getUserInput('index').match(/for|map|reduce|forEach|while/)); <ide> ``` <ide> <ide> </section> <ide> function makeList(arr) { <ide> * `<li class="text-warning">linebreak</li>` ] <ide> **/ <ide> const resultDisplayArray = makeList(result.failure); <del> <ide> ``` <ide> <ide> </div> <ide> const resultDisplayArray = makeList(result.failure); <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add>const result = { <add> success: ["max-length", "no-amd", "prefer-arrow-functions"], <add> failure: ["no-var", "var-on-top", "linebreak"], <add> skipped: ["id-blacklist", "no-dup-keys"] <add>}; <add>function makeList(arr) { <add> "use strict"; <add> <add> const resultDisplayArray = arr.map(val => `<li class="text-warning">${val}</li>`); <add> <add> return resultDisplayArray; <add>} <add>/** <add> * makeList(result.failure) should return: <add> * [ `<li class="text-warning">no-var</li>`, <add> * `<li class="text-warning">var-on-top</li>`, <add> * `<li class="text-warning">linebreak</li>` ] <add> **/ <add>const resultDisplayArray = makeList(result.failure); <ide> ``` <add> <ide> </section> <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/declare-a-read-only-variable-with-the-const-keyword.chinese.md <ide> id: 587d7b87367417b2b2512b41 <ide> title: Declare a Read-Only Variable with the const Keyword <ide> challengeType: 1 <del>videoUrl: '' <del>localeTitle: 使用const关键字声明只读变量 <add>forumTopicId: 301201 <add>localeTitle: 用 const 关键字声明只读变量 <ide> --- <ide> <ide> ## Description <del><section id="description"> <code>let</code>不是声明变量的唯一新方法。在ES6中,您还可以使用<code>const</code>关键字声明变量。 <code>const</code>拥有所有的真棒功能, <code>let</code>具有,与额外的奖励,使用声明的变量<code>const</code>是只读的。它们是一个常量值,这意味着一旦变量被赋值为<code>const</code> ,就无法重新赋值。 <blockquote> "use strict" <br> const FAV_PET ="Cats"; <br> FAV_PET = "Dogs"; //返回错误</blockquote>如您所见,尝试重新分配使用<code>const</code>声明的变量将引发错误。您应该始终使用<code>const</code>关键字命名您不想重新分配的变量。当您意外尝试重新分配一个旨在保持不变的变量时,这会有所帮助。命名常量时的常见做法是使用全部大写字母,单词用下划线分隔。 </section> <add><section id='description'> <add><code>let</code>并不是唯一的新的声明变量的方式。在 ES6里面,你还可以使用<code>const</code>关键字来声明变量。 <add><code>const</code>拥有<code>let</code>的所有优点,所不同的是,通过<code>const</code>声明的变量是只读的。这意味着通过<code>const</code>声明的变量只能被赋值一次,而不能被再次赋值。 <add> <add>```js <add>"use strict"; <add>const FAV_PET = "Cats"; <add>FAV_PET = "Dogs"; // returns error <add>``` <add> <add>可以看见,尝试给通过<code>const</code>声明的变量再次赋值会报错。你应该使用<code>const</code>关键字来对所有不打算再次赋值的变量进行声明。这有助于你避免给一个常量进行额外的再次赋值。一个最佳实践是对所有常量的命名采用全大写字母,并在单词之间使用下划线进行分隔。 <add> <add> <strong>注意:</strong> 一般开发者会以大写做为常量标识符,小写字母或者驼峰命名做为变量(对象或数组)标识符。接下来的挑战里会涉及到小写变量标识符的数组。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">更改代码,以便使用<code>let</code>或<code>const</code>声明所有变量。如果希望变量更改,请使用<code>let</code> ;如果希望变量保持不变,请使用<code>const</code> 。此外,重命名用<code>const</code>声明的变量以符合常规做法,这意味着常量应该全部大写。 </section> <add><section id='instructions'> <add>改变以下代码,使得所有的变量都使用<code>let</code>或<code>const</code>关键词来声明。当变量将会改变的时候使用<code>let</code>关键字,当变量要保持常量的时候使用<code>const</code>关键字。同时,对使用<code>const</code>声明的变量按照最佳实践重命名,变量名中的字母应该都是大写的。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: <code>var</code>在您的代码中不存在。 <add> - text: <code>var</code>在代码中不存在。 <ide> testString: getUserInput => assert(!getUserInput('index').match(/var/g)); <del> - text: <code>SENTENCE</code>应该是用<code>const</code>声明的常量变量。 <add> - text: <code>SENTENCE</code>应该是使用<code>const</code>声明的常量。 <ide> testString: getUserInput => assert(getUserInput('index').match(/(const SENTENCE)/g)); <del> - text: <code>i</code>应该以<code>let</code>来宣布。 <add> - text: <code>i</code>应该是使用<code>let</code>声明的变量。 <ide> testString: getUserInput => assert(getUserInput('index').match(/(let i)/g)); <del> - text: 应更改<code>console.log</code>以打印<code>SENTENCE</code>变量。 <add> - text: <code>console.log</code>应该修改为用于打印<code>SENTENCE</code>变量。 <ide> testString: getUserInput => assert(getUserInput('index').match(/console\.log\(\s*SENTENCE\s*\)\s*;?/g)); <ide> <ide> ``` <ide> function printManyTimes(str) { <ide> // change code below this line <ide> <ide> var sentence = str + " is cool!"; <del> for(var i = 0; i < str.length; i+=2) { <add> for (var i = 0; i < str.length; i+=2) { <ide> console.log(sentence); <ide> } <ide> <ide> // change code above this line <ide> <ide> } <ide> printManyTimes("freeCodeCamp"); <del> <ide> ``` <ide> <ide> </div> <ide> printManyTimes("freeCodeCamp"); <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add>function printManyTimes(str) { <add> "use strict"; <add> <add> // change code below this line <add> <add> const SENTENCE = str + " is cool!"; <add> for (let i = 0; i < str.length; i+=2) { <add> console.log(SENTENCE); <add> } <add> <add> // change code above this line <add> <add>} <add>printManyTimes("freeCodeCamp"); <ide> ``` <add> <ide> </section> <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/explore-differences-between-the-var-and-let-keywords.chinese.md <ide> id: 587d7b87367417b2b2512b3f <ide> title: Explore Differences Between the var and let Keywords <ide> challengeType: 1 <del>videoUrl: '' <del>localeTitle: 探索var和let关键字之间的差异 <add>forumTopicId: 301202 <add>localeTitle: 探索 var 和 let 关键字之间的差异 <ide> --- <ide> <del><section id="description">使用<code>var</code>关键字声明变量的最大问题之一是您可以在没有错误的情况下覆盖变量声明。 <del><blockquote>var camper = 'James';<br>var camper = 'David';<br>console.log(camper);<br>// 输出 'David'</blockquote> <del>正如您在上面的代码中看到的那样, <code>camper</code>变量最初被声明为<code>James</code> ,然后被重写为<code>David</code> 。在小型应用程序中,您可能不会遇到此类问题,但是当您的代码变大时,您可能会意外覆盖您不打算覆盖的变量。因为这种行为不会引发错误,所以搜索和修复错误变得更加困难。 <br>在ES6中引入了一个名为<code>let</code>的新关键字,用<code>var</code>关键字解决了这个潜在的问题。如果要在上面代码的变量声明中用<code>let</code>替换<code>var</code> ,结果将是一个错误。 <del><blockquote>let camper = 'James';<br>let camper = 'David'; // 抛出一个错误</blockquote> <del>您可以在浏览器的控制台中看到此错误。因此与<code>var</code>不同,使用<code>let</code> ,具有相同名称的变量只能声明一次。注意<code>&quot;use strict&quot;</code> 。这启用了严格模式,可以捕获常见的编码错误和“不安全”操作。例如: <del><blockquote>"use strict";<br>x = 3.14; // 抛出一个错误,因为 x 未定义</blockquote> <add>## Description <add><section id='description'> <add>使用<code>var</code>关键字来声明变量,会出现重复声明导致变量被覆盖却不会报错的问题: <add> <add>```js <add>var camper = 'James'; <add>var camper = 'David'; <add>console.log(camper); <add>// logs 'David' <add>``` <add> <add>在上面的代码中,<code>camper</code>的初始值为<code>'James'</code>,然后又被覆盖成了<code>'David'</code>。 <add>在小型的应用中,你可能不会遇到这样的问题,但是当你的代码规模变得更加庞大的时候,就可能会在不经意间覆盖了之前定义的变量。 <add>这样的行为不会报错,导致了 debug 非常困难。<br> <add>在 ES6 中引入了新的关键字<code>let</code>来解决<code>var</code>关键字带来的潜在问题。 <add>如果你在上面的代码中,使用了<code>let</code>关键字来代替<code>var</code>关键字,结果会是一个报错。 <add> <add>```js <add>let camper = 'James'; <add>let camper = 'David'; // throws an error <add>``` <add> <add>你可以在浏览器的控制台里看见这个错误。 <add>与<code>var</code>不同的是,当使用<code>let</code>的时候,同一名字的变量只能被声明一次。 <add>请注意<code>"use strict"</code>。这代表着开启了严格模式,用于检测常见的代码错误以及"不安全"的行为,例如: <add> <add>```js <add>"use strict"; <add>x = 3.14; // throws an error because x is not declared <add>``` <add> <ide> </section> <ide> <ide> ## Instructions <del><section id="instructions">更新代码,使其仅使用<code>let</code>关键字。 </section> <add><section id='instructions'> <add>请更新这段代码,并且在其中只使用<code>let</code>关键字 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: <code>var</code>在代码中不存在。 <add> - text: 在代码中不应存在<code>var</code>。 <ide> testString: getUserInput => assert(!getUserInput('index').match(/var/g)); <del> - text: <code>catName</code>应该是<code>Oliver</code> 。 <add> - text: "<code>catName</code>变量的值应该为<code>'Oliver'</code>。" <ide> testString: assert(catName === "Oliver"); <del> - text: <code>quote</code>应该是<code>&quot;Oliver says Meow!&quot;</code> <add> - text: "<code>quote</code>变量的值应该为<code>'Oliver says Meow!'</code>" <ide> testString: assert(quote === "Oliver says Meow!"); <ide> <ide> ``` <ide> function catTalk() { <ide> <ide> } <ide> catTalk(); <del> <ide> ``` <ide> <ide> </div> <ide> catTalk(); <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add>let catName; <add>let quote; <add>function catTalk() { <add> 'use strict'; <add> <add> catName = 'Oliver'; <add> quote = catName + ' says Meow!'; <add>} <add>catTalk(); <ide> ``` <add> <ide> </section> <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/handle-a-fulfilled-promise-with-then.chinese.md <add>--- <add>id: 5cdafbd72913098997531681 <add>title: Handle a Fulfilled Promise with then <add>challengeType: 1 <add>forumTopicId: 301203 <add>localeTitle: 在 then 中处理 Promise 完成的情况 <add>--- <add> <add>## Description <add><section id='description'> <add>当程序需要花费未知的时间才能完成时 Promise 很有用(比如,一些异步操作),一般是网络请求。网络请求会花费一些时间,当结束时需要根据服务器的响应执行一些操作。这可以用 <code>then</code> 方法来实现,当 promise 完成 <code>resolve</code> 时会触发 <code>then</code> 方法。例子如下: <add> <add>```js <add>myPromise.then(result => { <add> // do something with the result. <add>}); <add>``` <add> <add><code>result</code> 即传入 <code>resolve</code> 方法的参数。 <add></section> <add> <add>## Instructions <add><section id='instructions'> <add>给 promise 添加 <code>then</code> 方法。用 <code>result</code> 做为回调函数的参数并将 <code>result</code> 打印在控制台。 <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: 应该给 promise 方法调用 <code>then</code> 方法。 <add> testString: assert(codeWithoutSpaces.match(/(makeServerRequest|\))\.then\(/g)); <add> - text: <code>then</code> 方法应该有一个回调函数,回调函数参数为 <code>result</code>。 <add> testString: assert(resultIsParameter); <add> - text: 应该打印 <code>result</code> 到控制台。 <add> testString: assert(resultIsParameter && codeWithoutSpaces.match(/\.then\(.*?result.*?console.log\(result\).*?\)/)); <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add><div id='js-seed'> <add> <add>```js <add>const makeServerRequest = new Promise((resolve, reject) => { <add> // responseFromServer is set to true to represent a successful response from a server <add> let responseFromServer = true; <add> <add> if(responseFromServer) { <add> resolve("We got the data"); <add> } else { <add> reject("Data not received"); <add> } <add>}); <add>``` <add> <add></div> <add> <add>### After Test <add><div id='js-teardown'> <add> <add>```js <add>const codeWithoutSpaces = code.replace(/\s/g, ''); <add>const resultIsParameter = /\.then\((function\(result\){|result|\(result\)=>)/.test(codeWithoutSpaces); <add>``` <add> <add></div> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>const makeServerRequest = new Promise((resolve, reject) => { <add> // responseFromServer is set to true to represent a successful response from a server <add> let responseFromServer = true; <add> <add> if(responseFromServer) { <add> resolve("We got the data"); <add> } else { <add> reject("Data not received"); <add> } <add>}); <add> <add>makeServerRequest.then(result => { <add> console.log(result); <add>}); <add>``` <add> <add></section> <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/handle-a-rejected-promise-with-catch.chinese.md <add>--- <add>id: 5cdafbe72913098997531682 <add>title: Handle a Rejected Promise with catch <add>challengeType: 1 <add>forumTopicId: 301204 <add>localeTitle: 在 catch 中处理 Promise 失败的情况 <add>--- <add> <add>## Description <add><section id='description'> <add>当 promise 失败时会调用 <code>catch</code> 方法。当 promise 的 <code>reject</code> 方法执行时会直接调用。用法如下: <add> <add>```js <add>myPromise.catch(error => { <add> // do something with the error. <add>}); <add>``` <add> <add><code>error</code> 是传入 <code>reject</code> 方法的参数。 <add> <add><strong>注意:</strong> <code>then</code> 和 <code>catch</code> 方法可以在 promise 后面链式调用。 <add></section> <add> <add>## Instructions <add><section id='instructions'> <add>给 promise 添加 <code>catch</code> 方法。用 <code>error</code> 做为回调函数的参数并把 <code>error</code> 打印到控制台。 <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: 应该在 promise 上调用 <code>catch</code> 方法。 <add> testString: assert(codeWithoutSpaces.match(/(makeServerRequest|\))\.catch\(/g)); <add> - text: <code>catch</code> 方法应该有一个回调函数,函数参数为<code>error</code>。 <add> testString: assert(errorIsParameter); <add> - text: 应该打印<code>error</code>到控制台。 <add> testString: assert(errorIsParameter && codeWithoutSpaces.match(/\.catch\(.*?error.*?console.log\(error\).*?\)/)); <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add><div id='js-seed'> <add> <add>```js <add>const makeServerRequest = new Promise((resolve, reject) => { <add> // responseFromServer is set to false to represent an unsuccessful response from a server <add> let responseFromServer = false; <add> <add> if(responseFromServer) { <add> resolve("We got the data"); <add> } else { <add> reject("Data not received"); <add> } <add>}); <add> <add>makeServerRequest.then(result => { <add> console.log(result); <add>}); <add>``` <add> <add></div> <add> <add>### After Test <add><div id='js-teardown'> <add> <add>```js <add>const codeWithoutSpaces = code.replace(/\s/g, ''); <add>const errorIsParameter = /\.catch\((function\(error\){|error|\(error\)=>)/.test(codeWithoutSpaces); <add>``` <add> <add></div> <add> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>const makeServerRequest = new Promise((resolve, reject) => { <add> // responseFromServer is set to false to represent an unsuccessful response from a server <add> let responseFromServer = false; <add> <add> if(responseFromServer) { <add> resolve("We got the data"); <add> } else { <add> reject("Data not received"); <add> } <add>}); <add> <add>makeServerRequest.then(result => { <add> console.log(result); <add>}); <add> <add>makeServerRequest.catch(error => { <add> console.log(error); <add>}); <add>``` <add> <add></section> <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/import-a-default-export.chinese.md <ide> id: 587d7b8d367417b2b2512b59 <ide> title: Import a Default Export <ide> challengeType: 1 <del>videoUrl: '' <del>localeTitle: 导入默认导出 <add>forumTopicId: 301205 <add>localeTitle: 导入一个默认的导出 <ide> --- <ide> <ide> ## Description <del><section id="description">在上一次挑战中,您了解了<code>export default</code>及其用途。请务必注意,要导入默认导出,您需要使用不同的<code>import</code>语法。在下面的示例中,我们有一个函数<code>add</code> ,它是文件的默认导出<code>&quot;math_functions&quot;</code> 。以下是如何导入它: <blockquote>从“math_functions”导入添加; <br>添加(5,4); //将返回9 </blockquote>语法在一个关键位置有所不同 - 导入的值<code>add</code>不会被花括号<code>{}</code>包围。与导出值不同,导入默认导出的主要方法是在<code>import</code>后简单地写入值的名称。 </section> <add><section id='description'> <add>在上一个挑战里,学习了<code>export default</code>的用法。还需要一种<code>import</code>的语法来导入默认的导出。 <add>在下面的例子里有一个<code>add</code>函数, 它在<code>"math_functions"</code>文件里默认被导出。来看看来如何导入它: <add> <add>```js <add>import add from "./math_functions.js"; <add>``` <add> <add>这个语法只有一处不同的地方 —— 被导入的<code>add</code>值,并没有被花括号<code>{}</code>所包围。与导出值的方法不同,导入默认导出的写法仅仅只是简单的将变量名写在<code>import</code>之后。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">在下面的代码中,请从文件<code>&quot;math_functions&quot;</code>导入默认导出, <code>subtract</code> ,该文件位于与此文件相同的目录中。 </section> <add><section id='instructions'> <add>在下面的代码中,请导入在同目录下的<code>"math_functions"</code>文件中默认导出的<code>subtract</code>值。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 正确导入<code>export default</code>方法。 <add> - text: 正确导入<code>export default</code>方法导出的值。 <ide> testString: assert(code.match(/import\s+subtract\s+from\s+('|")\.\/math_functions\.js\1/g)); <del> <ide> ``` <ide> <ide> </section> <ide> <ide> ## Challenge Seed <ide> <section id='challengeSeed'> <del> <ide> <div id='js-seed'> <ide> <ide> ```js <del>"use strict"; <del>subtract(7,4); <del> <del>``` <del> <del></div> <del> <del>### Before Test <del><div id='js-setup'> <del> <del>```js <del>window.require = function(str) { <del>if (str === 'math_functions') { <del>return function(a, b) { <del>return a - b; <del>}}}; <add> <add>// add code above this line <ide> <add>subtract(7,4); <ide> ``` <ide> <ide> </div> <del> <del> <ide> </section> <ide> <ide> ## Solution <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add>import subtract from "./math_functions.js"; <add>// add code above this line <add> <add>subtract(7,4); <ide> ``` <add> <ide> </section> <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/mutate-an-array-declared-with-const.chinese.md <ide> id: 587d7b87367417b2b2512b42 <ide> title: Mutate an Array Declared with const <ide> challengeType: 1 <del>videoUrl: '' <del>localeTitle: 改变用const声明的数组 <add>forumTopicId: 301206 <add>localeTitle: 改变一个用 const 声明的数组 <ide> --- <ide> <ide> ## Description <del><section id="description"> <code>const</code>声明在现代JavaScript中有许多用例。一些开发人员更喜欢默认使用<code>const</code>分配所有变量,除非他们知道需要重新分配值。只有在这种情况下,他们才会使用<code>let</code> 。但是,重要的是要理解使用<code>const</code>分配给变量的对象(包括数组和函数)仍然是可变的。使用<code>const</code>声明仅阻止重新分配变量标识符。 <blockquote> “严格使用”; <br> const s = [5,6,7]; <br> s = [1,2,3]; //抛出错误,尝试分配const <br> s [2] = 45; //就像使用var或let声明的数组一样工作<br>的console.log(一个或多个); //返回[5,6,45] </blockquote>如您所见,您可以改变对象<code>[5, 6, 7]</code>本身,变量<code>s</code>仍将指向更改的数组<code>[5, 6, 45]</code> 。与所有数组一样, <code>s</code>中的数组元素是可变的,但由于使用了<code>const</code> ,因此不能使用变量标识符<code>s</code>使用赋值运算符指向不同的数组。 </section> <add><section id='description'> <add>在现代的 JavaScript 里,<code>const</code>声明有很多用法。 <add>一些开发者倾向默认使用<code>const</code>来声明所有变量,但如果它们打算在后续的代码中修改某个值,那在声明的时候就会用<code>let</code>。 <add>然而,你要注意,对象(包括数组和函数)在使用<code>const</code>声明的时候依然是可变的。使用<code>const</code>来声明只会保证它的标识不会被重新赋值。 <add> <add>```js <add>"use strict"; <add>const s = [5, 6, 7]; <add>s = [1, 2, 3]; // throws error, trying to assign a const <add>s[2] = 45; // works just as it would with an array declared with var or let <add>console.log(s); // returns [5, 6, 45] <add>``` <add> <add>从以上代码看出,你可以改变<code>[5, 6, 7]</code>自身,所以<code>s</code>变量指向了改变后的数组<code>[5, 6, 45]</code>。和所有数组一样,数组<code>s</code>中的数组元素是可以被改变的,但是因为使用了<code>const</code>关键字,你不能使用赋值操作符将变量标识<code>s</code>指向另外一个数组。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">数组声明为<code>const s = [5, 7, 2]</code> 。使用各种元素分配将数组更改为<code>[2, 5, 7]</code> 。 </section> <add><section id='instructions'> <add>这里有一个使用<code>const s = [5, 7, 2]</code>声明的数组。使用对各元素赋值的方法将数组改成<code>[2, 5, 7]</code>。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> localeTitle: 改变用const声明的数组 <ide> tests: <ide> - text: 不要替换<code>const</code>关键字。 <ide> testString: getUserInput => assert(getUserInput('index').match(/const/g)); <del> - text: <code>s</code>应该是一个常量变量(使用<code>const</code> )。 <add> - text: <code>s</code>应该为常量 (通过使用<code>const</code>)。 <ide> testString: getUserInput => assert(getUserInput('index').match(/const\s+s/g)); <del> - text: 不要更改原始数组声明。 <add> - text: 不要改变原数组的声明。 <ide> testString: getUserInput => assert(getUserInput('index').match(/const\s+s\s*=\s*\[\s*5\s*,\s*7\s*,\s*2\s*\]\s*;?/g)); <del> - text: '<code>s</code>应该等于<code>[2, 5, 7]</code> 。' <add> - text: <code>s</code>应该等于<code>[2, 5, 7]</code>。 <ide> testString: assert.deepEqual(s, [2, 5, 7]); <ide> <ide> ``` <ide> tests: <ide> ```js <ide> const s = [5, 7, 2]; <ide> function editInPlace() { <del> "use strict"; <add> 'use strict'; <ide> // change code below this line <ide> <ide> // s = [2, 5, 7]; <- this is invalid <ide> <ide> // change code above this line <ide> } <ide> editInPlace(); <del> <ide> ``` <ide> <ide> </div> <ide> editInPlace(); <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add>const s = [5, 7, 2]; <add>function editInPlace() { <add> 'use strict'; <add> // change code below this line <add> <add> // s = [2, 5, 7]; <- this is invalid <add> s[0] = 2; <add> s[1] = 5; <add> s[2] = 7; <add> // change code above this line <add>} <add>editInPlace(); <ide> ``` <add> <ide> </section> <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/prevent-object-mutation.chinese.md <ide> id: 598f48a36c8c40764b4e52b3 <ide> title: Prevent Object Mutation <ide> challengeType: 1 <del>videoUrl: '' <del>localeTitle: 防止对象突变 <add>forumTopicId: 301207 <add>localeTitle: 防止对象改变 <ide> --- <ide> <ide> ## Description <del><section id="description">正如之前的挑战所示, <code>const</code>声明本身并不能真正保护您的数据免受突变。为确保您的数据不会发生变化,JavaScript提供了一个<code>Object.freeze</code>函数来防止数据突变。对象冻结后,您将无法再从中添加,更新或删除属性。任何更改对象的尝试都将被拒绝而不会出现错误。 <blockquote>让obj = { <br>名称:“FreeCodeCamp” <br>点评:“真棒” <br> }; <br> Object.freeze(OBJ); <br> obj.review =“坏”; //将被忽略。不允许变异<br> obj.newProp =“测试”; //将被忽略。不允许变异<br>的console.log(OBJ); <br> // {name:“FreeCodeCamp”,评论:“很棒”} </blockquote></section> <add><section id='description'> <add>通过之前的挑战可以看出,<code>const</code>声明并不会真的保护你的数据不被改变。为了确保数据不被改变,JavaScript 提供了一个函数<code>Object.freeze</code>来防止数据改变。 <add>当一个对象被冻结的时候,你不能再对它的属性再进行增、删、改的操作。任何试图改变对象的操作都会被阻止,却不会报错。 <add> <add>```js <add>let obj = { <add> name:"FreeCodeCamp", <add> review:"Awesome" <add>}; <add>Object.freeze(obj); <add>obj.review = "bad"; // will be ignored. Mutation not allowed <add>obj.newProp = "Test"; // will be ignored. Mutation not allowed <add>console.log(obj); <add>// { name: "FreeCodeCamp", review:"Awesome"} <add>``` <add> <add></section> <ide> <ide> ## Instructions <del><section id="instructions">在这个挑战中,您将使用<code>Object.freeze</code>来防止数学常量发生变化。您需要冻结<code>MATH_CONSTANTS</code>对象,以便没有人能够更改<code>PI</code>的值,添加或删除属性。 </section> <add><section id='instructions'> <add>在这个挑战中,你将使用<code>Object.freeze</code>来防止数学常量被改变。你需要冻结<code>MATH_CONSTANTS</code>对象,使得没有人可以改变<code>PI</code>的值,抑或增加或删除属性。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> localeTitle: 防止对象突变 <ide> tests: <ide> - text: 不要替换<code>const</code>关键字。 <ide> testString: getUserInput => assert(getUserInput('index').match(/const/g)); <del> - text: <code>MATH_CONSTANTS</code>应该是一个常量变量(使用<code>const</code> )。 <add> - text: <code>MATH_CONSTANTS</code>应该为一个常量 (使用<code>const</code>)。 <ide> testString: getUserInput => assert(getUserInput('index').match(/const\s+MATH_CONSTANTS/g)); <del> - text: 请勿更改原始<code>MATH_CONSTANTS</code> 。 <add> - text: 不要改变原始的<code>MATH_CONSTANTS</code>。 <ide> testString: getUserInput => assert(getUserInput('index').match(/const\s+MATH_CONSTANTS\s+=\s+{\s+PI:\s+3.14\s+};/g)); <del> - text: <code>PI</code>等于<code>3.14</code> 。 <add> - text: <code>PI</code>等于<code>3.14</code>。 <ide> testString: assert(PI === 3.14); <ide> <ide> ``` <ide> tests: <ide> <ide> ```js <ide> function freezeObj() { <del> "use strict"; <add> 'use strict'; <ide> const MATH_CONSTANTS = { <ide> PI: 3.14 <ide> }; <ide> function freezeObj() { <ide> // change code above this line <ide> try { <ide> MATH_CONSTANTS.PI = 99; <del> } catch( ex ) { <add> } catch(ex) { <ide> console.log(ex); <ide> } <ide> return MATH_CONSTANTS.PI; <ide> } <ide> const PI = freezeObj(); <del> <ide> ``` <ide> <ide> </div> <ide> const PI = freezeObj(); <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add>function freezeObj() { <add> 'use strict'; <add> const MATH_CONSTANTS = { <add> PI: 3.14 <add> }; <add> // change code below this line <add> Object.freeze(MATH_CONSTANTS); <add> <add> // change code above this line <add> try { <add> MATH_CONSTANTS.PI = 99; <add> } catch(ex) { <add> console.log(ex); <add> } <add> return MATH_CONSTANTS.PI; <add>} <add>const PI = freezeObj(); <ide> ``` <add> <ide> </section> <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/reuse-javascript-code-using-import.chinese.md <add>--- <add>id: 587d7b8c367417b2b2512b55 <add>title: Reuse Javascript Code Using import <add>challengeType: 1 <add>forumTopicId: 301208 <add>localeTitle: 通过 import 复用 JavaScript 代码 <add>--- <add> <add>## Description <add><section id='description'> <add><code>import</code> 可以导入文件或模块的一部分。在之前的课程里,例子从 <code>math_functions.js</code> 文件里导出了 <code>add</code>,下面看一下如何在其它的文件导入它: <add> <add>```js <add>import { add } from './math_functions.js'; <add>``` <add> <add>在这里,<code>import</code> 会在 <code>math_functions.js</code> 里找到 <code>add</code>,只导入这个函数,忽略剩余的部分。<code>./</code> 告诉程序在当前文件的相同目录寻找 <code>math_functions.js</code> 文件。用这种方式导入时,相对路径(<code>./</code>)和文件扩展名(<code>.js</code>)都是必需的。 <add> <add>可以在导入语句里导入多个项目,如下: <add> <add>```js <add>import { add, subtract } from './math_functions.js'; <add>``` <add> <add></section> <add> <add>## Instructions <add><section id='instructions'> <add>添加 <code>import</code> 语句,使当前文件可以使用你在之前课程里导出的 <code>uppercaseString</code> 和 <code>lowercaseString</code> 函数,函数在当前路径下的 <code>string_functions.js</code> 文件里。 <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: 应该导入 <code>uppercaseString</code>、 <add> testString: assert(code.match(/import\s*{\s*(uppercaseString[^}]*|[^,]*,\s*uppercaseString\s*)}\s+from\s+('|")\.\/string_functions\.js\2/g)); <add> - text: 应该导入 <code>lowercaseString</code>、 <add> testString: assert(code.match(/import\s*{\s*(lowercaseString[^}]*|[^,]*,\s*lowercaseString\s*)}\s+from\s+('|")\.\/string_functions\.js\2/g)); <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add><div id='js-seed'> <add> <add>```js <add> <add>// add code above this line <add> <add>uppercaseString("hello"); <add>lowercaseString("WORLD!"); <add>``` <add> <add></div> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>import { uppercaseString, lowercaseString } from './string_functions.js'; <add>// add code above this line <add> <add>uppercaseString("hello"); <add>lowercaseString("WORLD!"); <add>``` <add> <add></section> <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/set-default-parameters-for-your-functions.chinese.md <ide> id: 587d7b88367417b2b2512b46 <ide> title: Set Default Parameters for Your Functions <ide> challengeType: 1 <del>videoUrl: '' <add>forumTopicId: 301209 <ide> localeTitle: 设置函数的默认参数 <ide> --- <ide> <ide> ## Description <del><section id="description">为了帮助我们创建更灵活的函数,ES6引入了函数的<dfn>默认参数</dfn> 。看看这段代码: <blockquote> function greeting(name =“Anonymous”){ <br>返回“你好”+名字; <br> } <br>的console.log(问候语( “约翰”)); // 你好约翰<br>的console.log(问候()); //你好匿名</blockquote>默认参数在未指定参数时启动(未定义)。正如您在上面的示例中所看到的,当您未为参数提供值时,参数<code>name</code>将接收其默认值<code>&quot;Anonymous&quot;</code> 。您可以根据需要为任意数量的参数添加默认值。 </section> <add><section id='description'> <add>ES6 里允许给函数传入<dfn>默认参数</dfn>,来构建更加灵活的函数。 <add>请看以下代码: <add> <add>```js <add>const greeting = (name = "Anonymous") => "Hello " + name; <add> <add>console.log(greeting("John")); // Hello John <add>console.log(greeting()); // Hello Anonymous <add>``` <add> <add>默认参数会在参数没有被指定(值为 undefined )的时候起作用。在上面的例子中,参数<code>name</code>会在没有得到新的值的时候,默认使用值 "Anonymous"。你还可以给多个参数赋予默认值。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">修改函数<code>increment</code>加入默认参数,这样它会加1 <code>number</code> ,如果<code>value</code>未指定。 </section> <add><section id='instructions'> <add>给函数<code>increment</code>加上默认参数,使得在<code>value</code>没有被赋值的时候,默认给<code>number</code>加1。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: '<code>increment(5, 2)</code>应为<code>7</code> 。' <add> - text: <code>increment(5, 2)</code>的结果应该为<code>7</code>。 <ide> testString: assert(increment(5, 2) === 7); <del> - text: <code>increment(5)</code>的结果应为<code>6</code> 。 <add> - text: <code>increment(5)</code>的结果应该为<code>6</code>。 <ide> testString: assert(increment(5) === 6); <del> - text: 默认参数<code>1</code>用于<code>value</code> 。 <add> - text: 参数<code>value</code>的默认值应该为<code>1</code>。 <ide> testString: assert(code.match(/value\s*=\s*1/g)); <ide> <ide> ``` <ide> tests: <ide> <div id='js-seed'> <ide> <ide> ```js <del>const increment = (function() { <del> "use strict"; <del> return function increment(number, value) { <del> return number + value; <del> }; <del>})(); <add>const increment = (number, value) => number + value; <add> <ide> console.log(increment(5, 2)); // returns 7 <ide> console.log(increment(5)); // returns 6 <del> <ide> ``` <ide> <ide> </div> <ide> console.log(increment(5)); // returns 6 <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add>const increment = (number, value = 1) => number + value; <ide> ``` <add> <ide> </section> <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/understand-the-differences-between-import-and-require.chinese.md <del>--- <del>id: 587d7b8c367417b2b2512b55 <del>title: Understand the Differences Between import and require <del>challengeType: 1 <del>videoUrl: '' <del>localeTitle: 理解import和require之间的差异 <del>--- <del> <del>## Description <del><section id="description">过去,函数<code>require()</code>将用于导入外部文件和模块中的函数和代码。虽然方便,但这会带来一个问题:某些文件和模块相当大,您可能只需要来自这些外部资源的某些代码。 ES6为我们提供了一个非常方便的工具,称为<dfn>import</dfn> 。有了它,我们可以选择加载到给定文件中的模块或文件的哪些部分,从而节省时间和内存。请考虑以下示例。想象一下<code>math_array_functions</code>有大约20个函数,但我在当前文件中只需要一个<code>countItems</code> 。旧的<code>require()</code>方法会迫使我引入所有20个函数。使用这种新的<code>import</code>语法,我可以引入所需的功能,如下所示: <blockquote>从“math_array_functions”导入{countItems} </blockquote>上面代码的描述: <blockquote>从“file_path_goes_here”导入{function} <br> //我们也可以用同样的方式导入变量! </blockquote>有几种方法可以编写<code>import</code>语句,但上面是一个非常常见的用例。 <strong>注意</strong> <br>花括号内的函数周围的空格是最佳实践 - 它使得读取<code>import</code>语句更容易。 <strong>注意</strong> <br>本节中的课程处理非浏览器功能。 <code>import</code>以及我们在其余课程中介绍的语句将无法直接在浏览器上运行。但是,我们可以使用各种工具来创建代码,使其在浏览器中工作。 <strong>注意</strong> <br>在大多数情况下,文件路径在它之前需要<code>./</code> ;否则,node将首先尝试将其作为依赖项加载到<code>node_modules</code>目录中。 </section> <del> <del>## Instructions <del><section id="instructions">添加适当的<code>import</code>语句,允许当前文件使用<code>capitalizeString</code>函数。此函数所在的文件称为<code>&quot;string_functions&quot;</code> ,它与当前文件位于同一目录中。 </section> <del> <del>## Tests <del><section id='tests'> <del> <del>```yml <del>tests: <del> - text: 有效的<code>import</code>声明 <del> testString: 'getUserInput => assert(getUserInput("index").match(/import\s+\{\s*capitalizeString\s*\}\s+from\s+("|")string_functions\1/g), "valid <code>import</code> statement");' <del> <del>``` <del> <del></section> <del> <del>## Challenge Seed <del><section id='challengeSeed'> <del> <del><div id='js-seed'> <del> <del>```js <del>"use strict"; <del>capitalizeString("hello!"); <del> <del>``` <del> <del></div> <del> <del>### Before Test <del><div id='js-setup'> <del> <del>```js <del>window.require = function (str) { <del>if (str === 'string_functions') { <del>return { <del>capitalizeString: str => str.toUpperCase() <del>}}}; <del> <del>``` <del> <del></div> <del> <del> <del></section> <del> <del>## Solution <del><section id='solution'> <del> <del>```js <del>// solution required <del>``` <del></section> <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use--to-import-everything-from-a-file.chinese.md <ide> id: 587d7b8c367417b2b2512b57 <ide> title: Use * to Import Everything from a File <ide> challengeType: 1 <del>videoUrl: '' <del>localeTitle: 使用*从文件导入所有内容 <add>forumTopicId: 301210 <add>localeTitle: 用 * 从文件中导入所有内容 <ide> --- <ide> <ide> ## Description <del><section id="description">假设您有一个文件要将其所有内容导入当前文件。这可以使用<dfn>import *</dfn>语法完成。这是一个示例,其中名为<code>&quot;math_functions&quot;</code>的文件的内容被导入到同一目录中的文件中: <blockquote>从“math_functions”导入*作为myMathModule; <br> myMathModule.add(2,3); <br> myMathModule.subtract(5,3); </blockquote>并打破代码: <blockquote>从“file_path_goes_here”导入* as object_with_name_of_your_choice <br> object_with_name_of_your_choice.imported_function </blockquote>您可以使用<code>import * as</code>后面的任何名称<code>import * as</code>语句的一部分。为了使用此方法,它需要一个接收导入值的对象。从这里,您将使用点表示法来调用导入的值。 </section> <add><section id='description'> <add>我们还可以用<code>import</code>语法从文件中导入所有的内容。下面是一个从同目录下的<code>"math_functions"</code>文件中导入所有内容的例子: <add> <add>```js <add>import * as myMathModule from "./math_functions.js"; <add>``` <add> <add>上面的 <code>import</code> 语句会创建一个叫做 <code>myMathModule</code> 的对象。这只是一个变量名,可以随便命名。对象包含 <code>math_functions.js</code> 文件里的所有导出,可以像访问对象的属性那样访问里面的函数。下面是使用导入的 <code>add</code> 和 <code>subtract</code> 函数的例子: <add> <add>```js <add>myMathModule.add(2,3); <add>myMathModule.subtract(5,3); <add>``` <add> <add></section> <ide> <ide> ## Instructions <del><section id="instructions">下面的代码需要在导入的同一目录中找到的文件<code>&quot;capitalize_strings&quot;</code>的内容。使用提供的对象将相应的<code>import *</code>语句添加到文件的顶部。 </section> <add><section id='instructions'> <add>下面的代码需要从同目录下的<code>"string_functions"</code>文件中导入所有内容。使用提供的对象,在当前文件的顶部添加正确的<code>import *</code>语句 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> localeTitle: 使用*从文件导入所有内容 <ide> tests: <ide> - text: 正确使用<code>import * as</code>语法。 <ide> testString: assert(code.match(/import\s*\*\s*as\s+stringFunctions\s+from\s*('|")\.\/string_functions\.js\1/g)); <del> <ide> ``` <ide> <ide> </section> <ide> <ide> ## Challenge Seed <ide> <section id='challengeSeed'> <del> <ide> <div id='js-seed'> <ide> <ide> ```js <del>"use strict"; <del> <del>``` <ide> <del></div> <del> <del>### Before Test <del><div id='js-setup'> <del> <del>```js <del>window.require = function(str) { <del>if (str === 'capitalize_strings') { <del>return { <del>capitalize: str => str.toUpperCase(), <del>lowercase: str => str.toLowerCase() <del>}}}; <add>// add code above this line <ide> <add>stringFunctions.uppercaseString("hello"); <add>stringFunctions.lowercaseString("WORLD!"); <ide> ``` <ide> <ide> </div> <del> <del> <ide> </section> <ide> <ide> ## Solution <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add>import * as stringFunctions from "./string_functions.js"; <add>// add code above this line <add> <add>stringFunctions.uppercaseString("hello"); <add>stringFunctions.lowercaseString("WORLD!"); <ide> ``` <add> <ide> </section> <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-arrow-functions-to-write-concise-anonymous-functions.chinese.md <ide> id: 587d7b87367417b2b2512b43 <ide> title: Use Arrow Functions to Write Concise Anonymous Functions <ide> challengeType: 1 <del>videoUrl: '' <del>localeTitle: 使用箭头函数编写简明的匿名函数 <add>forumTopicId: 301211 <add>localeTitle: 使用箭头函数编写简洁的匿名函数 <ide> --- <ide> <ide> ## Description <del><section id="description">在JavaScript中,我们通常不需要命名我们的函数,特别是在将函数作为参数传递给另一个函数时。相反,我们创建内联函数。我们不需要命名这些函数,因为我们不会在其他任何地方重用它们。为此,我们经常使用以下语法: <blockquote> const myFunc = function(){ <br> const myVar =“value”; <br>返回myVar; <br> } </blockquote> ES6为我们提供了语法糖,而不必以这种方式编写匿名函数。相反,您可以使用<strong>箭头函数语法</strong> : <blockquote> const myFunc =()=&gt; { <br> const myVar =“value”; <br>返回myVar; <br> } </blockquote>当没有函数体,并且只有返回值时,箭头函数语法允许您省略关键字<code>return</code>以及代码周围的括号。这有助于将较小的函数简化为单行语句: <blockquote> const myFunc =()=&gt;“value” </blockquote>默认情况下,此代码仍将返回<code>value</code> 。 </section> <add><section id='description'> <add>在 JavaScript 里,我们会经常遇到不需要给函数命名的情况,尤其是在需要将一个函数作为参数传给另外一个函数的时候。这时,我们会创建匿名函数。因为这些函数不会在其他地方复用,所以我们不需要给它们命名。 <add>这种情况下,我们通常会使用以下语法: <add> <add>```js <add>const myFunc = function() { <add> const myVar = "value"; <add> return myVar; <add>} <add>``` <add> <add>ES6 提供了其他写匿名函数的方式的语法糖。你可以使用箭头函数: <add> <add>```js <add>const myFunc = () => { <add> const myVar = "value"; <add> return myVar; <add>} <add>``` <add> <add>当不需要函数体,只返回一个值的时候,箭头函数允许你省略<code>return</code>关键字和外面的大括号。这样就可以将一个简单的函数简化成一个单行语句。 <add> <add>```js <add>const myFunc = () => "value"; <add>``` <add> <add>这段代码仍然会返回<code>value</code>。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">重写分配给变量<code>magic</code>的函数,该函数返回一个新的<code>Date()</code>以使用箭头函数语法。还要确保使用关键字<code>var</code>定义任何内容。 </section> <add><section id='instructions'> <add>使用箭头函数的语法重写<code>magic</code>函数,使其返回一个新的<code>Date()</code>。同时不要用<code>var</code>关键字来定义任何变量。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 用户确实替换了<code>var</code>关键字。 <add> - text: 替换掉<code>var</code>关键字。 <ide> testString: getUserInput => assert(!getUserInput('index').match(/var/g)); <del> - text: <code>magic</code>应该是一个常量变量(通过使用<code>const</code> )。 <add> - text: <code>magic</code>应该为一个常量 (使用<code>const</code>)。 <ide> testString: getUserInput => assert(getUserInput('index').match(/const\s+magic/g)); <del> - text: <code>magic</code>是一种<code>function</code> 。 <add> - text: <code>magic</code>是一个<code>function</code>。 <ide> testString: assert(typeof magic === 'function'); <ide> - text: <code>magic()</code>返回正确的日期。 <ide> testString: assert(magic().setHours(0,0,0,0) === new Date().setHours(0,0,0,0)); <del> - text: <code>function</code>关键字未使用。 <add> - text: 不要使用<code>function</code>关键字。 <ide> testString: getUserInput => assert(!getUserInput('index').match(/function/g)); <ide> <ide> ``` <ide> var magic = function() { <ide> "use strict"; <ide> return new Date(); <ide> }; <del> <ide> ``` <ide> <ide> </div> <ide> var magic = function() { <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add>const magic = () => { <add> "use strict"; <add> return new Date(); <add>}; <ide> ``` <add> <ide> </section> <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-class-syntax-to-define-a-constructor-function.chinese.md <ide> id: 587d7b8b367417b2b2512b53 <ide> title: Use class Syntax to Define a Constructor Function <ide> challengeType: 1 <del>videoUrl: '' <del>localeTitle: 使用类语法定义构造函数 <add>forumTopicId: 301212 <add>localeTitle: 使用 class 语法定义构造函数 <ide> --- <ide> <ide> ## Description <del><section id="description"> ES6使用关键字<dfn>class</dfn>提供了一种帮助创建对象的新语法。需要注意的是, <code>class</code>语法只是一种语法,而不是面向对象范例的完整的基于类的实现,不像Java,Python或Ruby等语言。在ES5中,我们通常定义一个构造函数function,并使用<code>new</code>关键字实例化一个对象。 <blockquote> var SpaceShuttle = function(targetPlanet){ <br> this.targetPlanet = targetPlanet; <br> } <br> var zeus = new SpaceShuttle(&#39;Jupiter&#39;); </blockquote>类语法只是替换构造函数创建: <blockquote> class SpaceShuttle { <br>构造(targetPlanet){ <br> this.targetPlanet = targetPlanet; <br> } <br> } <br> const zeus = new SpaceShuttle(&#39;Jupiter&#39;); </blockquote>请注意, <code>class</code>关键字声明了一个新函数,并添加了一个构造函数,该函数将在调用<code>new</code>调用 - 以创建新对象。 </section> <add><section id='description'> <add>ES6 提供了一个新的创建对象的语法,使用关键字<code>class</code>。 <add>值得注意的是,<code>class</code>只是一个语法糖,它并不像 Java、Python 或者 Ruby 这一类的语言一样,严格履行了面向对象的开发规范。 <add>在 ES5 里面,我们通常会定义一个构造函数,然后使用 <code>new</code> 关键字来实例化一个对象: <add> <add>```js <add>var SpaceShuttle = function(targetPlanet){ <add> this.targetPlanet = targetPlanet; <add>} <add>var zeus = new SpaceShuttle('Jupiter'); <add>``` <add> <add><code>class</code>的语法只是简单地替换了构造函数的写法: <add> <add>```js <add>class SpaceShuttle { <add> constructor(targetPlanet) { <add> this.targetPlanet = targetPlanet; <add> } <add>} <add>const zeus = new SpaceShuttle('Jupiter'); <add>``` <add> <add>应该注意 <code>class</code> 关键字声明了一个函数,里面添加了一个构造器(constructor)。当调用 <code>new</code> 来创建一个新对象时构造器会被调用。 <add> <add><strong>注意:</strong><br><ul> <add><li> 首字母大写驼峰命名法是 ES6 class 名的惯例,就像上面的 <code>SpaceShuttle</code>。</li> <add><li> 构造函数是一个特殊的函数,在用 class 创建时来创建和初始化对象。在 JavaScript 算法和数据结构证书的面向对象章节里会更深入介绍。</li></ul> <add></section> <ide> <ide> ## Instructions <del><section id="instructions">使用<code>class</code>关键字并编写适当的构造函数来创建<code>Vegetable</code>类。使用<code>Vegetable</code>可以创建具有属性<code>name</code>的蔬菜对象,以传递给构造函数。 </section> <add><section id='instructions'> <add>使用<code>class</code>关键字,并写出正确的构造函数,来创建<code>Vegetable</code>这个类: <add><code>Vegetable</code>这个类可以创建 vegetable 对象,这个对象拥有一个在构造函数中赋值的<code>name</code>属性。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: <code>Vegetable</code>应该是一个<code>class</code>具有限定<code>constructor</code>方法。 <add> - text: <code>Vegetable</code> 应该是一个 <code>class</code>,并在其中定义了<code>constructor</code>方法。 <ide> testString: assert(typeof Vegetable === 'function' && typeof Vegetable.constructor === 'function'); <del> - text: <code>class</code>关键字。 <add> - text: 使用了<code>class</code>关键字。 <ide> testString: assert(code.match(/class/g)); <del> - text: <code>Vegetable</code>可以实例化。 <add> - text: <code>Vegetable</code>可以被实例化。 <ide> testString: assert(() => {const a = new Vegetable("apple"); return typeof a === 'object';}); <del> - text: <code>carrot.name</code>应该返回<code>carrot</code> 。 <add> - text: <code>carrot.name</code> 应该返回 <code>carrot</code>. <ide> testString: assert(carrot.name=='carrot'); <ide> <ide> ``` <ide> tests: <ide> <div id='js-seed'> <ide> <ide> ```js <del>function makeClass() { <del> "use strict"; <del> /* Alter code below this line */ <add>/* Alter code below this line */ <add> <add>/* Alter code above this line */ <ide> <del> /* Alter code above this line */ <del> return Vegetable; <del>} <del>const Vegetable = makeClass(); <ide> const carrot = new Vegetable('carrot'); <ide> console.log(carrot.name); // => should be 'carrot' <del> <ide> ``` <ide> <ide> </div> <ide> console.log(carrot.name); // => should be 'carrot' <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add>class Vegetable { <add> constructor(name) { <add> this.name = name; <add> } <add>} <add>const carrot = new Vegetable('carrot'); <ide> ``` <add> <ide> </section> <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-to-assign-variables-from-arrays.chinese.md <ide> id: 587d7b89367417b2b2512b4b <ide> title: Use Destructuring Assignment to Assign Variables from Arrays <ide> challengeType: 1 <del>videoUrl: '' <del>localeTitle: 使用解构分配从数组中分配变量 <add>forumTopicId: 301213 <add>localeTitle: 使用解构赋值从数组中分配变量 <ide> --- <ide> <ide> ## Description <del><section id="description"> ES6使解构数组像解构对象一样简单。扩展运算符和数组解构之间的一个关键区别是扩展运算符将数组的所有内容解包为逗号分隔列表。因此,您无法选择或选择要分配给变量的元素。对阵列进行解构可以让我们做到这一点: <blockquote> const [a,b] = [1,2,3,4,5,6]; <br> console.log(a,b); // 1,2 </blockquote>变量<code>a</code>被赋予数组的第一个值,而<code>b</code>被赋予数组的第二个值。我们还可以通过使用逗号来访问所需索引,从而在数组中的任何索引处访问该值: <blockquote> const [a,b ,,, c] = [1,2,3,4,5,6]; <br> console.log(a,b,c); // 1,2,5 </blockquote></section> <add><section id='description'> <add>在 ES6 里面,解构数组可以如同解构对象一样简单。 <add>与数组解构不同,数组的扩展运算会将数组里的所有内容分解成一个由逗号分隔的列表。所以,你不能选择哪个元素来给变量赋值。 <add>而对数组进行解构却可以让我们做到这一点: <add> <add>```js <add>const [a, b] = [1, 2, 3, 4, 5, 6]; <add>console.log(a, b); // 1, 2 <add>``` <add> <add>变量<code>a</code>以及<code>b</code>分别被数组的第一、第二个元素赋值。 <add>我们甚至能在数组解构中使用逗号分隔符,来获取任意一个想要的值: <add> <add>```js <add>const [a, b,,, c] = [1, 2, 3, 4, 5, 6]; <add>console.log(a, b, c); // 1, 2, 5 <add>``` <add> <add></section> <ide> <ide> ## Instructions <del><section id="instructions">使用解构赋值来交换<code>a</code>和<code>b</code>的值,以便<code>a</code>接收存储在<code>b</code>的值,并且<code>b</code>接收存储在<code>a</code>的值。 </section> <add><section id='instructions'> <add>使用数组解构来交换变量<code>a</code>与<code>b</code>的值。使<code>a</code>、<code>b</code>能分别获得对方的值。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 交换后<code>a</code>值应为6。 <add> - text: 在交换后,<code>a</code>的值应该为6。 <ide> testString: assert(a === 6); <del> - text: 交换后<code>b</code>值应为8。 <add> - text: 在交换后,<code>b</code>的值应该为8。 <ide> testString: assert(b === 8); <del> - text: 使用数组解构来交换a和b。 <add> - text: 使用数组解构来交换<code>a</code>和<code>b</code>。 <ide> testString: assert(/\[\s*(\w)\s*,\s*(\w)\s*\]\s*=\s*\[\s*\2\s*,\s*\1\s*\]/g.test(code)); <ide> <ide> ``` <ide> tests: <ide> <ide> ```js <ide> let a = 8, b = 6; <del>(() => { <del> "use strict"; <del> // change code below this line <add>// change code below this line <ide> <del> // change code above this line <del>})(); <add>// change code above this line <ide> console.log(a); // should be 6 <ide> console.log(b); // should be 8 <del> <ide> ``` <ide> <ide> </div> <ide> console.log(b); // should be 8 <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add>let a = 8, b = 6; <add>[a, b] = [b, a]; <ide> ``` <add> <ide> </section> <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-to-assign-variables-from-nested-objects.chinese.md <ide> id: 587d7b89367417b2b2512b4a <ide> title: Use Destructuring Assignment to Assign Variables from Nested Objects <ide> challengeType: 1 <del>videoUrl: '' <del>localeTitle: 使用解构分配从嵌套对象分配变量 <add>forumTopicId: 301214 <add>localeTitle: 使用解构赋值从嵌套对象中分配变量 <ide> --- <ide> <ide> ## Description <del><section id="description">我们可以类似地将<em>嵌套</em>对象解构为变量。请考虑以下代码: <blockquote> const a = { <br>开始:{x:5,y:6}, <br>结束:{x:6,y:-9} <br> }; <br> const {start:{x:startX,y:startY}} = a; <br> console.log(startX,startY); // 5,6 </blockquote>在上面的示例中,变量<code>start</code>被赋予<code>a.start</code>的值,该值也是一个对象。 </section> <add><section id='description'> <add>同样,我们可以将 <em>嵌套的对象</em>解构到变量中。 <add> <add>请看以下代码: <add> <add>```js <add>const user = { <add> johnDoe: { <add> age: 34, <add> email: '[email protected]' <add> } <add>}; <add>``` <add> <add>这是解构对象的属性并赋值给相同名字的变量: <add> <add>```js <add>const { johnDoe: { age, email }} = user; <add>``` <add> <add>这是将对象的属性值指定给一个不同的名字: <add> <add>```js <add>const { johnDoe: { age: userAge, email: userEmail }} = user; <add>``` <add> <add></section> <ide> <ide> ## Instructions <del><section id="instructions">用解构赋值来获得<code>max</code>的<code>forecast.tomorrow</code>并将其分配给<code>maxOfTomorrow</code> 。 </section> <add><section id='instructions'> <add>将两个赋值语句替换成等价的解构赋值。<code>lowToday</code> 和 <code>highToday</code> 应该为 <code>LOCAL_FORECAST</code> 中 <code>today.low</code> 和 <code>today.high</code> 的值。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: <code>maxOfTomorrow</code>等于<code>84.6</code> <del> testString: 'assert(getMaxOfTmrw(LOCAL_FORECAST) === 84.6, "<code>maxOfTomorrow</code> equals <code>84.6</code>");' <del> - text: 使用嵌套解构 <del> testString: 'getUserInput => assert(getUserInput("index").match(/\{\s*tomorrow\s*:\s*\{\s*max\s*:\s*maxOfTomorrow\s*\}\s*\}\s*=\s*forecast/g),"nested destructuring was used");' <del> <add> - text: 不能使用 ES5 的赋值语句。 <add> testString: assert(!code.match(/lowToday = LOCAL_FORECAST\.today\.low/g) && !code.match(/highToday = LOCAL_FORECAST\.today.high/g)) <add> - text: 应该使用解构创建 <code>lowToday</code> 变量。 <add> testString: assert(code.match(/(var|const|let)\s*{\s*today\s*:\s*{\s*(low\s*:\s*lowToday[^}]*|[^,]*,\s*low\s*:\s*lowToday\s*)}\s*}\s*=\s*LOCAL_FORECAST(;|\s+|\/\/)/g)); <add> - text: 应该使用解构创建 <code>highToday</code> 变量。 <add> testString: assert(code.match(/(var|const|let)\s*{\s*today\s*:\s*{\s*(high\s*:\s*highToday[^}]*|[^,]*,\s*high\s*:\s*highToday\s*)}\s*}\s*=\s*LOCAL_FORECAST(;|\s+|\/\/)/g)); <ide> ``` <ide> <ide> </section> <ide> <ide> ## Challenge Seed <ide> <section id='challengeSeed'> <del> <ide> <div id='js-seed'> <ide> <ide> ```js <ide> const LOCAL_FORECAST = { <del> today: { min: 72, max: 83 }, <del> tomorrow: { min: 73.3, max: 84.6 } <add> yesterday: { low: 61, high: 75 }, <add> today: { low: 64, high: 77 }, <add> tomorrow: { low: 68, high: 80 } <ide> }; <ide> <del>function getMaxOfTmrw(forecast) { <del> "use strict"; <del> // change code below this line <del> const maxOfTomorrow = undefined; // change this line <del> // change code above this line <del> return maxOfTomorrow; <del>} <add>// change code below this line <add> <add>const lowToday = LOCAL_FORECAST.today.low; <add>const highToday = LOCAL_FORECAST.today.high; <ide> <del>console.log(getMaxOfTmrw(LOCAL_FORECAST)); // should be 84.6 <add>// change code above this line <ide> <add>console.log(lowToday); // should be 64 <add>console.log(highToday); // should be 77 <ide> ``` <ide> <ide> </div> <del> <del> <del> <ide> </section> <ide> <ide> ## Solution <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add>const LOCAL_FORECAST = { <add> yesterday: { low: 61, high: 75 }, <add> today: { low: 64, high: 77 }, <add> tomorrow: { low: 68, high: 80 } <add>}; <add> <add>// change code below this line <add> <add>const { today: { low: lowToday, high: highToday }} = LOCAL_FORECAST; <add> <add>// change code above this line <add> <add>console.log(highToday); // should be 77 <add>console.log(highTomorrow); // should be 80 <ide> ``` <add> <ide> </section> <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-to-assign-variables-from-objects.chinese.md <ide> id: 587d7b89367417b2b2512b49 <ide> title: Use Destructuring Assignment to Assign Variables from Objects <ide> challengeType: 1 <del>videoUrl: '' <del>localeTitle: 使用解构分配从对象分配变量 <add>forumTopicId: 301215 <add>localeTitle: 使用解构赋值从对象中分配变量 <ide> --- <ide> <ide> ## Description <del><section id="description">我们之前看到扩展运算符如何有效地扩展或解包数组的内容。我们也可以用对象做类似的事情。 <dfn>解构赋值</dfn>是一种特殊的语法,用于将直接从对象获取的值整齐地分配给变量。请考虑以下ES5代码: <blockquote> var voxel = {x:3.6,y:7.4,z:6.54}; <br> var x = voxel.x; // x = 3.6 <br> var y = voxel.y; // y = 7.4 <br> var z = voxel.z; // z = 6.54 </blockquote>这是与ES6解构语法相同的赋值语句: <blockquote> const {x,y,z} =体素; // x = 3.6,y = 7.4,z = 6.54 </blockquote>相反,如果你想将<code>voxel.x</code>的值存储到<code>a</code> ,将<code>voxel.y</code>到<code>b</code> ,将<code>voxel.z</code>到<code>c</code> ,那么你也有这种自由。 <blockquote> const {x:a,y:b,z:c} =体素// a = 3.6,b = 7.4,c = 6.54 </blockquote>您可以将其读作“获取字段<code>x</code>并将值复制到<code>a</code>中”,依此类推。 </section> <add><section id='description'> <add>可以在解构的属性后添加冒号和新的变量名来给解构的值赋予一个新的变量名。 <add> <add>还是以上个例子的对象来举例: <add> <add>```js <add>const user = { name: 'John Doe', age: 34 }; <add>``` <add> <add>这是指定新的变量名的例子: <add> <add>```js <add>const { name: userName, age: userAge } = user; <add>// userName = 'John Doe', userAge = 34 <add>``` <add> <add>获取到了 <code>user.name</code> 的值并赋值给名为 <code>userName</code> 的变量。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">使用解构从输入对象<code>AVG_TEMPERATURES</code>获得明天的平均温度,并在<code>tomorrow</code>将关键值赋值给<code>tempOfTomorrow</code> 。 </section> <add><section id='instructions'> <add>使用解构赋值语句替换两个赋值语句。确保 <code>HIGH_TEMPERATURES</code> 的 <code>today</code> 和 <code>tomorrow</code> 属性赋值给 <code>highToday</code> 和 <code>highTomorrow</code>。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: <code>getTempOfTmrw(AVG_TEMPERATURES)</code>应为<code>79</code> <del> testString: 'assert(getTempOfTmrw(AVG_TEMPERATURES) === 79, "<code>getTempOfTmrw(AVG_TEMPERATURES)</code> should be <code>79</code>");' <del> - text: 使用了重新分配的解构 <del> testString: 'getUserInput => assert(getUserInput("index").match(/\{\s*tomorrow\s*:\s*tempOfTomorrow\s*}\s*=\s*avgTemperatures/g),"destructuring with reassignment was used");' <del> <add> - text: 应该移除 ES5 赋值语句。 <add> testString: assert(!code.match(/highToday = HIGH_TEMPERATURES\.today/g) && !code.match(/highTomorrow = HIGH_TEMPERATURES\.tomorrow/g)) <add> - text: 应该使用解构赋值语句创建 <code>highToday</code> 变量。 <add> testString: assert(code.match(/(var|const|let)\s*{\s*(today:\s*highToday[^}]*|[^,]*,\s*today\s*:\s*highToday\s*)}\s*=\s*HIGH_TEMPERATURES(;|\s+|\/\/)/g)); <add> - text: 应该使用解构赋值语句创建 <code>highTomorrow</code> 变量。 <add> testString: assert(code.match(/(var|const|let)\s*{\s*(tomorrow:\s*highTomorrow[^}]*|[^,]*,\s*tomorrow\s*:\s*highTomorrow\s*)}\s*=\s*HIGH_TEMPERATURES(;|\s+|\/\/)/g)); <ide> ``` <ide> <ide> </section> <ide> <ide> ## Challenge Seed <ide> <section id='challengeSeed'> <del> <ide> <div id='js-seed'> <ide> <ide> ```js <del>const AVG_TEMPERATURES = { <del> today: 77.5, <del> tomorrow: 79 <add>const HIGH_TEMPERATURES = { <add> yesterday: 75, <add> today: 77, <add> tomorrow: 80 <ide> }; <ide> <del>function getTempOfTmrw(avgTemperatures) { <del> "use strict"; <del> // change code below this line <del> const tempOfTomorrow = undefined; // change this line <del> // change code above this line <del> return tempOfTomorrow; <del>} <add>// change code below this line <add> <add>const highToday = HIGH_TEMPERATURES.today; <add>const highTomorrow = HIGH_TEMPERATURES.tomorrow; <ide> <del>console.log(getTempOfTmrw(AVG_TEMPERATURES)); // should be 79 <add>// change code above this line <ide> <add>console.log(yesterday) // should be not defined <add>console.log(highToday); // should be 77 <add>console.log(highTomorrow); // should be 80 <ide> ``` <ide> <ide> </div> <del> <del> <del> <ide> </section> <ide> <ide> ## Solution <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add>const HIGH_TEMPERATURES = { <add> yesterday: 75, <add> today: 77, <add> tomorrow: 80 <add>}; <add> <add>// change code below this line <add> <add>const { today: highToday, tomorrow: highTomorrow } = HIGH_TEMPERATURES; <add> <add>// change code above this line <add> <add>console.log(highToday); // should be 77 <add>console.log(highTomorrow); // should be 80 <ide> ``` <add> <ide> </section> <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-to-extract-values-from-objects.chinese.md <add>--- <add>id: 5cfa550e84205a357704ccb6 <add>title: Use Destructuring Assignment to Extract Values from Objects <add>challengeType: 1 <add>forumTopicId: 301216 <add>localeTitle: 使用解构赋值来获取对象的值 <add>--- <add> <add>## Description <add><section id='description'> <add><dfn>解构赋值</dfn> 是 ES6 引入的新语法,用来从数组和对象中提取值,并优雅的对变量进行赋值。 <add> <add>有如下 ES5 代码: <add> <add>```js <add>const user = { name: 'John Doe', age: 34 }; <add> <add>const name = user.name; // name = 'John Doe' <add>const age = user.age; // age = 34 <add>``` <add> <add>下面是使用 ES6 解构赋值的等价语句: <add> <add>```js <add>const { name, age } = user; <add>// name = 'John Doe', age = 34 <add>``` <add> <add>在这里,<code>name</code> 和 <code>age</code> 被自动创建并赋予 <code>user</code> 对象相应属性的值。一目了然。 <add> <add>解构赋值的参数数量可以任意。 <add></section> <add> <add>## Instructions <add><section id='instructions'> <add>把两个赋值语句替换成等价的解构赋值。<code>today</code> 和 <code>tomorrow</code> 的值应该还为 <code>HIGH_TEMPERATURES</code> 对象的 <code>today</code> 和 <code>tomorrow</code> 属性的值。 <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: 应该移除 ES5 赋值语句。 <add> testString: assert(!code.match(/today = HIGH_TEMPERATURES\.today/g) && !code.match(/tomorrow = HIGH_TEMPERATURES\.tomorrow/g)) <add> - text: 应该解构创建 <code>today</code> 变量。 <add> testString: assert(code.match(/(var|let|const)\s*{\s*(today[^}]*|[^,]*,\s*today)\s*}\s*=\s*HIGH_TEMPERATURES(;|\s+|\/\/)/g)); <add> - text: 应该解构创建 <code>tomorrow</code> 变量。 <add> testString: assert(code.match(/(var|let|const)\s*{\s*(tomorrow[^}]*|[^,]*,\s*tomorrow)\s*}\s*=\s*HIGH_TEMPERATURES(;|\s+|\/\/)/g)); <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add><div id='js-seed'> <add> <add>```js <add>const HIGH_TEMPERATURES = { <add> yesterday: 75, <add> today: 77, <add> tomorrow: 80 <add>}; <add> <add>// change code below this line <add> <add>const today = HIGH_TEMPERATURES.today; <add>const tomorrow = HIGH_TEMPERATURES.tomorrow; <add> <add>// change code above this line <add> <add>console.log(yesterday) // should be not defined <add>console.log(today); // should be 77 <add>console.log(tomorrow); // should be 80 <add>``` <add> <add></div> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>const HIGH_TEMPERATURES = { <add> yesterday: 75, <add> today: 77, <add> tomorrow: 80 <add>}; <add> <add>// change code below this line <add> <add>const { today, tomorrow } = HIGH_TEMPERATURES; <add> <add>// change code above this line <add> <add>console.log(yesterday) // should be not defined <add>console.log(today); // should be 77 <add>console.log(tomorrow); // should be 80 <add>``` <add> <add></section> <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-to-pass-an-object-as-a-functions-parameters.chinese.md <ide> id: 587d7b8a367417b2b2512b4d <ide> title: Use Destructuring Assignment to Pass an Object as a Function's Parameters <ide> challengeType: 1 <del>videoUrl: '' <del>localeTitle: 使用解构分配将对象作为函数的参数传递 <add>forumTopicId: 301217 <add>localeTitle: 使用解构赋值将对象作为函数的参数传递 <ide> --- <ide> <ide> ## Description <del><section id="description">在某些情况下,您可以在函数参数本身中对对象进行解构。考虑以下代码: <blockquote> const profileUpdate =(profileData)=&gt; { <br> const {name,age,nationality,location} = profileData; <br> //用这些变量做点什么<br> } </blockquote>这有效地破坏了发送到函数中的对象。这也可以就地完成: <blockquote> const profileUpdate =({name,age,nationality,location})=&gt; { <br> / *用这些字段做某事* / <br> } </blockquote>这将删除一些额外的行,使我们的代码看起来整洁。这具有额外的好处,即不必操纵函数中的整个对象;只有所需的字段才会复制到函数内部。 </section> <add><section id='description'> <add>在某些情况下,你可以在函数的参数里直接解构对象。 <add>请看以下代码: <add> <add>```js <add>const profileUpdate = (profileData) => { <add> const { name, age, nationality, location } = profileData; <add> // do something with these variables <add>} <add>``` <add> <add>上面的操作解构了传给函数的对象。这样的操作也可以直接在参数里完成: <add> <add>```js <add>const profileUpdate = ({ name, age, nationality, location }) => { <add> /* do something with these fields */ <add>} <add>``` <add> <add>这样的操作去除了多余的代码,使代码更加整洁。 <add>这样做还有个额外的好处:函数不需要再去操作整个对象,而仅仅是操作复制到函数作用域内部的参数。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">在函数<code>half</code>的参数内使用解构赋值,仅在函数内发送<code>max</code>和<code>min</code> 。 </section> <add><section id='instructions'> <add>对<code>half</code>的参数进行解构赋值,使得仅仅将<code>max</code>与<code>min</code>的值传进函数。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: <code>stats</code>应该是一个<code>object</code> 。 <del> testString: 'assert(typeof stats === "object", "<code>stats</code> should be an <code>object</code>.");' <del> - text: <code>half(stats)</code>应为<code>28.015</code> <del> testString: 'assert(half(stats) === 28.015, "<code>half(stats)</code> should be <code>28.015</code>");' <del> - text: 使用了解构。 <del> testString: 'getUserInput => assert(getUserInput("index").match(/\(\s*\{\s*\w+\s*,\s*\w+\s*\}\s*\)/g), "Destructuring was used.");' <add> - text: <code>stats</code>的类型应该是一个<code>object</code>。 <add> testString: assert(typeof stats === 'object'); <add> - text: <code>half(stats)</code>应该等于<code>28.015</code> <add> testString: assert(half(stats) === 28.015); <add> - text: 应该使用解构赋值。 <add> testString: assert(code.replace(/\s/g, '').match(/half=\({\w+,\w+}\)/)); <add> - text: 应该使用解构参数。 <add> testString: assert(!code.match(/stats\.max|stats\.min/)); <ide> <ide> ``` <ide> <ide> const stats = { <ide> min: -0.75, <ide> average: 35.85 <ide> }; <del>const half = (function() { <del> "use strict"; // do not change this line <ide> <del> // change code below this line <del> return function half(stats) { <del> // use function argument destructuring <del> return (stats.max + stats.min) / 2.0; <del> }; <del> // change code above this line <add>// change code below this line <add>const half = (stats) => (stats.max + stats.min) / 2.0; // use function argument destructuring <add>// change code above this line <ide> <del>})(); <ide> console.log(stats); // should be object <ide> console.log(half(stats)); // should be 28.015 <del> <ide> ``` <ide> <ide> </div> <ide> console.log(half(stats)); // should be 28.015 <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add>const stats = { <add> max: 56.78, <add> standard_deviation: 4.34, <add> median: 34.54, <add> mode: 23.87, <add> min: -0.75, <add> average: 35.85 <add>}; <add> <add>const half = ( {max, min} ) => (max + min) / 2.0; <ide> ``` <add> <ide> </section> <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-with-the-rest-operator-to-reassign-array-elements.chinese.md <del>--- <del>id: 587d7b8a367417b2b2512b4c <del>title: Use Destructuring Assignment with the Rest Operator to Reassign Array Elements <del>challengeType: 1 <del>videoUrl: '' <del>localeTitle: 使用与Rest运算符的Destructuring Assignment重新分配数组元素 <del>--- <del> <del>## Description <del><section id="description">在某些涉及数组解构的情况下,我们可能希望将其余元素收集到一个单独的数组中。结果类似于<code>Array.prototype.slice()</code> ,如下所示: <blockquote> const [a,b,... arr] = [1,2,3,4,5,7]; <br> console.log(a,b); // 1,2 <br>的console.log(ARR); // [3,4,5,7] </blockquote>变量<code>a</code>和<code>b</code>从数组中获取第一个和第二个值。之后,由于rest操作符的存在, <code>arr</code>以数组的形式获取其余的值。 rest元素仅作为列表中的最后一个变量正常工作。在中,您不能使用rest运算符来捕获一个子数组,该子数组会遗漏原始数组的最后一个元素。 </section> <del> <del>## Instructions <del><section id="instructions">使用与rest运算符的解构赋值来执行有效的<code>Array.prototype.slice()</code>以便<code>arr</code>是原始数组<code>source</code>的子数组,省略前两个元素。 </section> <del> <del>## Tests <del><section id='tests'> <del> <del>```yml <del>tests: <del> - text: '<code>arr</code>应为<code>[3,4,5,6,7,8,9,10]</code>' <del> testString: 'assert(arr.every((v, i) => v === i + 3) && arr.length === 8,"<code>arr</code> should be <code>[3,4,5,6,7,8,9,10]</code>");' <del> - text: 应该使用解构。 <del> testString: 'getUserInput => assert(getUserInput("index").match(/\[\s*\w*\s*,\s*\w*\s*,\s*...\w+\s*\]/g),"Destructuring should be used.");' <del> - text: 不应使用<code>Array.slice()</code> 。 <del> testString: 'getUserInput => assert(!getUserInput("index").match(/slice/g), "<code>Array.slice()</code> should not be used.");' <del> <del>``` <del> <del></section> <del> <del>## Challenge Seed <del><section id='challengeSeed'> <del> <del><div id='js-seed'> <del> <del>```js <del>const source = [1,2,3,4,5,6,7,8,9,10]; <del>function removeFirstTwo(list) { <del> "use strict"; <del> // change code below this line <del> arr = list; // change this <del> // change code above this line <del> return arr; <del>} <del>const arr = removeFirstTwo(source); <del>console.log(arr); // should be [3,4,5,6,7,8,9,10] <del>console.log(source); // should be [1,2,3,4,5,6,7,8,9,10]; <del> <del>``` <del> <del></div> <del> <del> <del> <del></section> <del> <del>## Solution <del><section id='solution'> <del> <del>```js <del>// solution required <del>``` <del></section> <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-with-the-rest-parameter-to-reassign-array-elements.chinese.md <add>--- <add>id: 587d7b8a367417b2b2512b4c <add>title: Use Destructuring Assignment with the Rest Parameter to Reassign Array Elements <add>challengeType: 1 <add>forumTopicId: 301218 <add>localeTitle: 使用解构赋值配合 rest 操作符来重新分配数组元素 <add>--- <add> <add>## Description <add><section id='description'> <add>在解构数组的某些情况下,我们可能希望将剩下的元素放进另一个数组里面。 <add>以下代码的结果与使用<code>Array.prototype.slice()</code>相同: <add> <add>```js <add>const [a, b, ...arr] = [1, 2, 3, 4, 5, 7]; <add>console.log(a, b); // 1, 2 <add>console.log(arr); // [3, 4, 5, 7] <add>``` <add> <add>变量<code>a</code>与<code>b</code>分别获取了数组的前两个元素的值。之后,因为<code>rest</code>操作符的存在,<code>arr</code>获取了原数组剩余的元素的值,并构成了一个新的数组。 <add><code>rest</code>操作只能对数组列表最后的元素起作用。这意味着你不能使用<code>rest</code>操作符来截取原数组中间元素的子数组。 <add></section> <add> <add>## Instructions <add><section id='instructions'> <add>使用解构赋值以及<code>rest</code>操作符来进行一个<code>Array.prototype.slice</code>相同的操作。使得<code>arr</code>是原数组<code>source</code>除开前两个元素的子数组。 <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: <code>arr</code>应该为<code>[3,4,5,6,7,8,9,10]</code> <add> testString: assert(arr.every((v, i) => v === i + 3) && arr.length === 8); <add> - text: 没有使用<code>Array.slice()</code>。 <add> testString: getUserInput => assert(!getUserInput('index').match(/slice/g)); <add> - text: 使用了解构赋值。 <add> testString: assert(code.replace(/\s/g, '').match(/\[(([_$a-z]\w*)?,){1,}\.\.\.arr\]=list/i)); <add> <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add> <add><div id='js-seed'> <add> <add>```js <add>const source = [1,2,3,4,5,6,7,8,9,10]; <add>function removeFirstTwo(list) { <add> "use strict"; <add> // change code below this line <add> const arr = list; // change this <add> // change code above this line <add> return arr; <add>} <add>const arr = removeFirstTwo(source); <add>console.log(arr); // should be [3,4,5,6,7,8,9,10] <add>console.log(source); // should be [1,2,3,4,5,6,7,8,9,10]; <add>``` <add> <add></div> <add> <add> <add> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>const source = [1,2,3,4,5,6,7,8,9,10]; <add>function removeFirstTwo(list) { <add> "use strict"; <add> // change code below this line <add> const [, , ...arr] = list; <add> // change code above this line <add> return arr; <add>} <add>const arr = removeFirstTwo(source); <add>``` <add> <add></section> <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-export-to-reuse-a-code-block.chinese.md <del>--- <del>id: 587d7b8c367417b2b2512b56 <del>title: Use export to Reuse a Code Block <del>challengeType: 1 <del>videoUrl: '' <del>localeTitle: 使用export重用代码块 <del>--- <del> <del>## Description <del><section id="description">在之前的挑战中,您了解了<code>import</code>以及如何利用它从大型文件导入少量代码。但是,为了使其工作,我们必须使用<code>import</code>一个语句,称为<dfn>导出</dfn> 。当我们想要一些代码 - 一个函数或一个变量 - 可以在另一个文件中使用时,我们必须将其导出才能将其导入另一个文件。与<code>import</code>一样, <code>export</code>是非浏览器功能。以下是我们称为<dfn>命名导出的内容</dfn> 。有了这个,我们可以使用您在上一课中学到的<code>import</code>语法将我们导出的任何代码导入到另一个文件中。这是一个例子: <blockquote> const capitalizeString =(string)=&gt; { <br> return string.charAt(0).toUpperCase()+ string.slice(1); <br> } <br> export {capitalizeString} //如何导出函数。 <br> export const foo =“bar”; //如何导出变量</blockquote>或者,如果您想将所有<code>export</code>语句压缩成一行,则可以采用以下方法: <blockquote> const capitalizeString =(string)=&gt; { <br> return string.charAt(0).toUpperCase()+ string.slice(1); <br> } <br> const foo =“bar”; <br> export {capitalizeString,foo} </blockquote>两种方法都是完全可以接受的。 </section> <del> <del>## Instructions <del><section id="instructions">下面是我想让其他文件使用的两个变量。利用我演示<code>export</code>的第一种方式,导出两个变量。 </section> <del> <del>## Tests <del><section id='tests'> <del> <del>```yml <del>tests: <del> - text: <code>foo</code>被导出了。 <del> testString: 'getUserInput => assert(getUserInput("index").match(/export\s+const\s+foo\s*=\s*"bar"/g), "<code>foo</code> is exported.");' <del> - text: <code>bar</code>出口。 <del> testString: 'getUserInput => assert(getUserInput("index").match(/export\s+const\s+bar\s*=\s*"foo"/g), "<code>bar</code> is exported.");' <del> <del>``` <del> <del></section> <del> <del>## Challenge Seed <del><section id='challengeSeed'> <del> <del><div id='js-seed'> <del> <del>```js <del>"use strict"; <del>const foo = "bar"; <del>const bar = "foo"; <del> <del>``` <del> <del></div> <del> <del>### Before Test <del><div id='js-setup'> <del> <del>```js <del>window.exports = function(){}; <del> <del>``` <del> <del></div> <del> <del> <del></section> <del> <del>## Solution <del><section id='solution'> <del> <del>```js <del>// solution required <del>``` <del></section> <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-export-to-share-a-code-block.chinese.md <add>--- <add>id: 587d7b8c367417b2b2512b56 <add>title: Use export to Share a Code Block <add>challengeType: 1 <add>forumTopicId: 301219 <add>localeTitle: 用 export 来重用代码块 <add>--- <add> <add>## Description <add><section id='description'> <add>假设有一个文件 <code>math_functions.js</code>,该文件包含了数学运算相关的一些函数。其中一个存储在变量 <code>add</code> 里,该函数接受两个数字做为参数返回它们的和。如果想在其它不同的 JavaScript 文件里使用这个函数,就需要 <code>export</code> 它。 <add> <add>```js <add>export const add = (x, y) => { <add> return x + y; <add>} <add>``` <add> <add>上面是导出单个函数常用方法,还可以这样导出: <add> <add>```js <add>const add = (x, y) => { <add> return x + y; <add>} <add> <add>export { add }; <add>``` <add> <add>导出变量和函数后,就可以在其它文件里导入使用从而避免了代码冗余。重复第一个例子的代码可以导出多个对象或函数,在第二个例子里面的导出语句中添加更多值也可以导出多项,例子如下: <add> <add>```js <add>export { add, subtract }; <add>``` <add> <add></section> <add> <add>## Instructions <add><section id='instructions'> <add>下面有两个变量需要在别的文件中可以使用。利用刚才展示的第一种方式,导出两个变量。 <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: 应该导出<code>uppercaseString</code>变量。 <add> testString: assert(code.match(/(export\s+const\s+uppercaseString|export\s*{\s*(uppercaseString[^}]*|[^,]*,\s*uppercaseString\s*)})/g)); <add> - text: 应该导出<code>lowercaseString</code>变量。 <add> testString: assert(code.match(/(export\s+const\s+lowercaseString|export\s*{\s*(lowercaseString[^}]*|[^,]*,\s*lowercaseString\s*)})/g)); <add> <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add><div id='js-seed'> <add> <add>```js <add>const uppercaseString = (string) => { <add> return string.toUpperCase(); <add>} <add> <add>const lowercaseString = (string) => { <add> return string.toLowerCase() <add>} <add>``` <add> <add></div> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>export const uppercaseString = (string) => { <add> return string.toUpperCase(); <add>} <add> <add>export const lowercaseString = (string) => { <add> return string.toLowerCase() <add>} <add>``` <add> <add></section> <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-getters-and-setters-to-control-access-to-an-object.chinese.md <ide> id: 587d7b8c367417b2b2512b54 <ide> title: Use getters and setters to Control Access to an Object <ide> challengeType: 1 <del>videoUrl: '' <del>localeTitle: 使用getter和setter来控制对象的访问 <add>forumTopicId: 301220 <add>localeTitle: 使用 getter 和 setter 来控制对象的访问 <ide> --- <ide> <ide> ## Description <del><section id="description">您可以从对象获取值,并在对象中设置属性的值。这些通常被称为<dfn>getter</dfn>和<dfn>setter</dfn> 。 Getter函数旨在简单地将对象的私有变量的值返回(获取)给用户,而无需用户直接访问私有变量。 Setter函数用于根据传递给setter函数的值修改(设置)对象私有变量的值。此更改可能涉及计算,甚至完全覆盖先前的值。 <blockquote> class Book { <br>构造函数(作者){ <br> this._author = author; <br> } <br> // getter <br> get writer(){ <br> return this._author; <br> } <br> // setter <br> set writer(updatedAuthor){ <br> this._author = updatedAuthor; <br> } <br> } <br> const lol = new Book(&#39;anonymous&#39;); <br>的console.log(lol.writer); //匿名<br> lol.writer =&#39;wut&#39;; <br>的console.log(lol.writer); //哇</blockquote>注意我们用来调用getter和setter的语法 - 就好像它们甚至不是函数一样。 Getter和setter很重要,因为它们隐藏了内部实现细节。 </section> <add><section id='description'> <add>你可以从对象中获得一个值,也可以给对象的属性赋值。 <add>这些通常行为被称为 <dfn>getters</dfn> 以及 <dfn>setters</dfn>。 <add>Getter 函数的作用是可以让对象返回一个私有变量,而不需要直接去访问私有变量。 <add>Setter 函数的作用是可以基于传进的参数来修改对象中私有变量。这些修改可以是计算,或者是直接替换之前的值。 <add> <add>```js <add>class Book { <add> constructor(author) { <add> this._author = author; <add> } <add> // getter <add> get writer() { <add> return this._author; <add> } <add> // setter <add> set writer(updatedAuthor) { <add> this._author = updatedAuthor; <add> } <add>} <add>const lol = new Book('anonymous'); <add>console.log(lol.writer); // anonymous <add>lol.writer = 'wut'; <add>console.log(lol.writer); // wut <add>``` <add> <add>注意我们调用 getter 和 setter 的语法,它们看起来并不像一个函数调用。 <add>Getter 和 Setter 非常重要,因为它们隐藏了内部的实现细节。 <add> <add><strong>注意:</strong> 通常会在私有变量前添加下划线(<code>_</code>)。这里并没有真正意义上让变量私有。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">使用<code>class</code>关键字创建Thermostat类。构造函数接受华氏温度。现在在类中创建<code>getter</code>和<code>setter</code> ,以获得摄氏温度。请记住, <code>C = 5/9 * (F - 32)</code>和<code>F = C * 9.0 / 5 + 32</code> ,其中F是华氏温标的温度值,C是摄氏温度相同温度的值注意当你实现这一点,你将在一个等级中跟踪班级内的温度 - 华氏温度或摄氏温度。这是getter或setter的强大功能 - 您正在为另一个用户创建一个API,无论您追踪哪个用户,都可以获得正确的结果。换句话说,您正在从使用者那里抽象出实现细节。 </section> <add><section id='instructions'> <add>使用<code>class</code>关键字来创建<code>Thermostat</code>类,它的构造函数应该可以接收 fahrenheit(华氏温度)作为参数。 <add>在类中创建 temperature 的 <code>getter</code>和<code>setter</code>,将温度转换成摄氏温度。 <add>温度转换的公式是<code>C = 5/9 * (F - 32)</code>以及<code>F = C * 9.0 / 5 + 32</code>,F 代表华氏温度,C 代表摄氏温度。 <add><strong>注意:</strong> 当你实现这个作业的时候,你应当在类中使用一个温度标准,无论是华氏温度还是摄氏温度。 <add>是时候展现 getter 和 setter 的威力了——无论你的 API 内部使用的是哪种温度标准,用户都能得到正确的结果。 <add>或者说,你从用户需求中抽象出了实现细节。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: <code>Thermostat</code>应该是一个<code>class</code>具有限定<code>constructor</code>方法。 <del> testString: 'assert(typeof Thermostat === "function" && typeof Thermostat.constructor === "function","<code>Thermostat</code> should be a <code>class</code> with a defined <code>constructor</code> method.");' <del> - text: <code>class</code>关键字。 <del> testString: 'getUserInput => assert(getUserInput("index").match(/class/g),"<code>class</code> keyword was used.");' <del> - text: <code>Thermostat</code>可以实例化。 <del> testString: 'assert(() => {const t = new Thermostat(32); return typeof t === "object" && t.temperature === 0;}, "<code>Thermostat</code> can be instantiated.");' <add> - text: <code>Thermostat</code>应该是一个<code>class</code>,并且在其中定义了<code>constructor</code>方法。 <add> testString: assert(typeof Thermostat === 'function' && typeof Thermostat.constructor === 'function'); <add> - text: 应该使用 <code>class</code> 关键字。 <add> testString: assert(code.match(/class/g)); <add> - text: <code>Thermostat</code>应该可以被实例化。 <add> testString: assert((() => {const t = new Thermostat(32);return typeof t === 'object' && t.temperature === 0;})()); <add> - text: 应该定义一个 <code>getter</code>。 <add> testString: assert((() => {const desc = Object.getOwnPropertyDescriptor(Thermostat.prototype, 'temperature');return !!desc && typeof desc.get === 'function';})()); <add> - text: 应该定义一个 <code>setter</code>。 <add> testString: assert((() => {const desc = Object.getOwnPropertyDescriptor(Thermostat.prototype, 'temperature');return !!desc && typeof desc.set === 'function';})()); <add> - text: 调用 <code>setter</code> 应该设置 temperature。 <add> testString: assert((() => {const t = new Thermostat(32); t.temperature = 26;return t.temperature !== 0;})()); <ide> <ide> ``` <ide> <ide> tests: <ide> <div id='js-seed'> <ide> <ide> ```js <del>function makeClass() { <del> "use strict"; <del> /* Alter code below this line */ <add>/* Alter code below this line */ <add> <add>/* Alter code above this line */ <ide> <del> /* Alter code above this line */ <del> return Thermostat; <del>} <del>const Thermostat = makeClass(); <ide> const thermos = new Thermostat(76); // setting in Fahrenheit scale <ide> let temp = thermos.temperature; // 24.44 in C <ide> thermos.temperature = 26; <ide> temp = thermos.temperature; // 26 in C <del> <ide> ``` <ide> <ide> </div> <ide> temp = thermos.temperature; // 26 in C <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add> <add>/* Alter code below this line */ <add>class Thermostat { <add> constructor(fahrenheit) { <add> this._tempInCelsius = 5/9 * (fahrenheit - 32); <add> } <add> get temperature(){ <add> return this._tempInCelsius; <add> } <add> set temperature(newTemp){ <add> this._tempInCelsius = newTemp; <add> } <add>} <add>/* Alter code above this line */ <add> <add>const thermos = new Thermostat(76); // setting in Fahrenheit scale <add>let temp = thermos.temperature; // 24.44 in C <add>thermos.temperature = 26; <add>temp = thermos.temperature; // 26 in C <ide> ``` <add> <ide> </section> <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-the-rest-operator-with-function-parameters.chinese.md <del>--- <del>id: 587d7b88367417b2b2512b47 <del>title: Use the Rest Operator with Function Parameters <del>challengeType: 1 <del>videoUrl: '' <del>localeTitle: 将Rest运算符与函数参数一起使用 <del>--- <del> <del>## Description <del><section id="description">为了帮助我们创建更灵活的函数,ES6引入了函数参数的<dfn>rest运算符</dfn> 。使用rest运算符,您可以创建带有可变数量参数的函数。这些参数存储在一个数组中,以后可以从函数内部访问。看看这段代码: <blockquote> function howMany(... args){ <br>返回“你已经通过”+ args.length +“arguments。”; <br> } <br> console.log(howMany(0,1,2)); //你已经传递了3个参数<br> console.log(howMany(“string”,null,[1,2,3],{})); //你已经传递了4个参数。 </blockquote>其余运算符无需检查<code>args</code>数组,并允许我们在<code>args</code>数组上应用<code>map()</code> , <code>filter()</code>和<code>reduce()</code> 。 </section> <del> <del>## Instructions <del><section id="instructions">修改函数<code>sum</code> ,使其使用rest运算符,并以相同的方式使用任意数量的参数。 </section> <del> <del>## Tests <del><section id='tests'> <del> <del>```yml <del>tests: <del> - text: '<code>sum(0,1,2)</code>的结果应为3' <del> testString: 'assert(sum(0,1,2) === 3, "The result of <code>sum(0,1,2)</code> should be 3");' <del> - text: '<code>sum(1,2,3,4)</code>的结果应为10' <del> testString: 'assert(sum(1,2,3,4) === 10, "The result of <code>sum(1,2,3,4)</code> should be 10");' <del> - text: <code>sum(5)</code>的结果应为5 <del> testString: 'assert(sum(5) === 5, "The result of <code>sum(5)</code> should be 5");' <del> - text: <code>sum()</code>的结果应为0 <del> testString: 'assert(sum() === 0, "The result of <code>sum()</code> should be 0");' <del> - text: <code>sum</code>函数在<code>args</code>参数上使用<code>...</code> spread运算符。 <del> testString: 'getUserInput => assert(getUserInput("index").match(/function\s+sum\s*\(\s*...args\s*\)\s*{/g), "The <code>sum</code> function uses the <code>...</code> spread operator on the <code>args</code> parameter.");' <del> <del>``` <del> <del></section> <del> <del>## Challenge Seed <del><section id='challengeSeed'> <del> <del><div id='js-seed'> <del> <del>```js <del>const sum = (function() { <del> "use strict"; <del> return function sum(x, y, z) { <del> const args = [ x, y, z ]; <del> return args.reduce((a, b) => a + b, 0); <del> }; <del>})(); <del>console.log(sum(1, 2, 3)); // 6 <del> <del>``` <del> <del></div> <del> <del> <del> <del></section> <del> <del>## Solution <del><section id='solution'> <del> <del>```js <del>// solution required <del>``` <del></section> <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-the-rest-parameter-with-function-parameters.chinese.md <add>--- <add>id: 587d7b88367417b2b2512b47 <add>title: Use the Rest Parameter with Function Parameters <add>challengeType: 1 <add>forumTopicId: 301221 <add>localeTitle: 将 rest 操作符与函数参数一起使用 <add>--- <add> <add>## Description <add><section id='description'> <add>ES6 推出了用于函数参数的<dfn> rest 操作符</dfn>帮助我们创建更加灵活的函数。在<code>rest</code>操作符的帮助下,你可以创建有一个变量来接受多个参数的函数。这些参数被储存在一个可以在函数内部读取的数组中。 <add>请看以下代码: <add> <add>```js <add>function howMany(...args) { <add> return "You have passed " + args.length + " arguments."; <add>} <add>console.log(howMany(0, 1, 2)); // You have passed 3 arguments. <add>console.log(howMany("string", null, [1, 2, 3], { })); // You have passed 4 arguments. <add>``` <add> <add><code>rest</code>操作符可以避免查看<code>args</code>数组的需求,并且允许我们在参数数组上使用<code>map()</code>、<code>fiter()</code> 和 <code>reduce()</code>。 <add></section> <add> <add>## Instructions <add><section id='instructions'> <add>修改<code>sum</code>函数,来让它使用<code>rest</code>操作符,并且它可以在有任何数量的参数时以相同的形式工作。 <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: <code>sum(0,1,2)</code>的返回结果应该为3。 <add> testString: assert(sum(0,1,2) === 3); <add> - text: <code>sum(1,2,3,4)</code>的返回结果应该为10。 <add> testString: assert(sum(1,2,3,4) === 10); <add> - text: <code>sum(5)</code>的返回结果应该为5。 <add> testString: assert(sum(5) === 5); <add> - text: <code>sum()</code>的返回结果应该为 0。 <add> testString: assert(sum() === 0); <add> - text: 对<code>sum</code>函数的<code>args</code>参数使用了<code>...</code>展开操作符。 <add> testString: assert(code.replace(/\s/g,'').match(/sum=\(\.\.\.args\)=>/)); <add> <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add> <add><div id='js-seed'> <add> <add>```js <add>const sum = (x, y, z) => { <add> const args = [x, y, z]; <add> return args.reduce((a, b) => a + b, 0); <add>} <add>console.log(sum(1, 2, 3)); // 6 <add>``` <add> <add></div> <add> <add> <add> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>const sum = (...args) => { <add> return args.reduce((a, b) => a + b, 0); <add>} <add>``` <add> <add></section> <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/use-the-spread-operator-to-evaluate-arrays-in-place.chinese.md <ide> id: 587d7b89367417b2b2512b48 <ide> title: Use the Spread Operator to Evaluate Arrays In-Place <ide> challengeType: 1 <del>videoUrl: '' <del>localeTitle: 使用Spread运算符来就地评估数组 <add>forumTopicId: 301222 <add>localeTitle: 使用 spread 运算符展开数组项 <ide> --- <ide> <ide> ## Description <del><section id="description"> ES6引入了<dfn>扩展运算符</dfn> ,它允许我们在需要多个参数或元素的位置扩展数组和其他表达式。下面的ES5代码使用<code>apply()</code>来计算数组中的最大值: <blockquote> var arr = [6,89,3,45]; <br> var maximus = Math.max.apply(null,arr); //返回89 </blockquote>我们必须使用<code>Math.max.apply(null, arr)</code>因为<code>Math.max(arr)</code>返回<code>NaN</code> 。 <code>Math.max()</code>期望以逗号分隔的参数,但不是数组。扩展运算符使这种语法更易于阅读和维护。 <blockquote> const arr = [6,89,3,45]; <br> const maximus = Math.max(... arr); //返回89 </blockquote> <code>...arr</code>返回一个解压缩的数组。换句话说,它<em>传播</em>阵列。但是,扩展运算符只能在就地工作,就像在函数的参数或数组文字中一样。以下代码不起作用: <blockquote> const spreaded = ... arr; //将抛出语法错误</blockquote></section> <add><section id='description'> <add>ES6 允许我们使用 <dfn>展开操作符</dfn> 来展开数组,以及需要多个参数或元素的表达式。 <add>下面的 ES5 代码使用了<code>apply()</code>来计算数组的最大值: <add> <add>```js <add>var arr = [6, 89, 3, 45]; <add>var maximus = Math.max.apply(null, arr); // returns 89 <add>``` <add> <add>我们必须使用<code>Math.max.apply(null,arr)</code>,是因为直接调用<code>Math.max(arr)</code>会返回<code>NaN</code>。<code>Math.max()</code>函数需要传入的是一系列由逗号分隔的参数,而不是一个数组。 <add>展开操作符可以提升代码的可读性,这对后续的代码维护是有积极作用的。 <add> <add>```js <add>const arr = [6, 89, 3, 45]; <add>const maximus = Math.max(...arr); // returns 89 <add>``` <add> <add><code>...arr</code>返回了一个“打开”的数组。或者说它 <em>展开</em> 了数组。 <add>然而,展开操作符只能够在函数的参数中,或者数组之中使用。下面的代码将会报错: <add> <add>```js <add>const spreaded = ...arr; // will throw a syntax error <add>``` <add> <add></section> <ide> <ide> ## Instructions <del><section id="instructions">使用spread运算符将<code>arr1</code>所有内容复制到另一个数组<code>arr2</code> 。 </section> <add><section id='instructions'> <add>使用展开操作符将<code>arr1</code>中的内容都赋值到<code>arr2</code>中去。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: <code>arr2</code>是<code>arr1</code>正确副本。 <add> - text: <code>arr2</code>的值是由<code>arr1</code>拷贝而来的。 <ide> testString: assert(arr2.every((v, i) => v === arr1[i])); <del> - text: <code>...</code>传播运算符用于复制<code>arr1</code> 。 <add> - text: 用<code>...</code>展开操作符来赋值<code>arr1</code>。 <ide> testString: assert(code.match(/Array\(\s*\.\.\.arr1\s*\)|\[\s*\.\.\.arr1\s*\]/)); <del> - text: 更改<code>arr1</code>时, <code>arr2</code>保持不变。 <add> - text: 当<code>arr1</code>改变的时候,<code>arr2</code>不会改变。 <ide> testString: assert((arr1, arr2) => {arr1.push('JUN'); return arr2.length < arr1.length}); <ide> <ide> ``` <ide> tests: <ide> ```js <ide> const arr1 = ['JAN', 'FEB', 'MAR', 'APR', 'MAY']; <ide> let arr2; <del>(function() { <del> "use strict"; <del> arr2 = []; // change this line <del>})(); <del>console.log(arr2); <ide> <add>arr2 = []; // change this line <add> <add>console.log(arr2); <ide> ``` <ide> <ide> </div> <ide> console.log(arr2); <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add>const arr1 = ['JAN', 'FEB', 'MAR', 'APR', 'MAY']; <add>let arr2; <add> <add>arr2 = [...arr1]; <ide> ``` <add> <ide> </section> <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/write-arrow-functions-with-parameters.chinese.md <ide> id: 587d7b88367417b2b2512b44 <ide> title: Write Arrow Functions with Parameters <ide> challengeType: 1 <del>videoUrl: '' <del>localeTitle: 用参数写箭头函数 <add>forumTopicId: 301223 <add>localeTitle: 编写带参数的箭头函数 <ide> --- <ide> <ide> ## Description <del><section id="description">就像普通函数一样,您可以将参数传递给箭头函数。 <blockquote> //将输入值加倍并返回<br> const doubler =(item)=&gt; item * 2; </blockquote>您也可以将多个参数传递给箭头函数。 </section> <add><section id='description'> <add>和一般的函数一样,你也可以给箭头函数传递参数。 <add> <add>```js <add>// 给传入的数值乘以 2 并返回结果 <add>const doubler = (item) => item * 2; <add>``` <add> <add>如果箭头函数只有一个参数,则可以省略包含该参数的括号。 <add> <add>```js <add>// the same function, without the argument parentheses <add>const doubler = item => item * 2; <add>``` <add> <add>可以将多个参数传递到箭头函数中。 <add> <add>```js <add>// multiplies the first input value by the second and returns it <add>const multiplier = (item, multi) => item * multi; <add>``` <add> <add></section> <ide> <ide> ## Instructions <del><section id="instructions">重写<code>myConcat</code>函数,该函数将<code>arr2</code>内容追加到<code>arr1</code>以便该函数使用箭头函数语法。 </section> <add><section id='instructions'> <add>使用箭头函数的语法重写<code>myConcat</code>函数,使其可以将<code>arr2</code>的内容填充在<code>arr1</code>里。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 用户确实替换了<code>var</code>关键字。 <add> - text: 替换掉所有的<code>var</code>关键字。 <ide> testString: getUserInput => assert(!getUserInput('index').match(/var/g)); <del> - text: <code>myConcat</code>应该是一个常量变量(使用<code>const</code> )。 <add> - text: <code>myConcat</code>应该是一个常量 (使用<code>const</code>)。 <ide> testString: getUserInput => assert(getUserInput('index').match(/const\s+myConcat/g)); <del> - text: <code>myConcat</code>应该是一个函数 <add> - text: <code>myConcat</code>应该是一个函数。 <ide> testString: assert(typeof myConcat === 'function'); <del> - text: <code>myConcat()</code>返回正确的<code>array</code> <add> - text: <code>myConcat()</code> 应该返回 <code>[1, 2, 3, 4, 5]</code>。 <ide> testString: assert(() => { const a = myConcat([1], [2]); return a[0] == 1 && a[1] == 2; }); <del> - text: <code>function</code>关键字未使用。 <add> - text: 不要使用<code>function</code>关键字。 <ide> testString: getUserInput => assert(!getUserInput('index').match(/function/g)); <ide> <ide> ``` <ide> var myConcat = function(arr1, arr2) { <ide> }; <ide> // test your code <ide> console.log(myConcat([1, 2], [3, 4, 5])); <del> <ide> ``` <ide> <ide> </div> <ide> console.log(myConcat([1, 2], [3, 4, 5])); <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add>const myConcat = (arr1, arr2) => { <add> "use strict"; <add> return arr1.concat(arr2); <add>}; <add>// test your code <add>console.log(myConcat([1, 2], [3, 4, 5])); <ide> ``` <add> <ide> </section> <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/write-concise-declarative-functions-with-es6.chinese.md <ide> id: 587d7b8b367417b2b2512b50 <ide> title: Write Concise Declarative Functions with ES6 <ide> challengeType: 1 <del>videoUrl: '' <del>localeTitle: 用ES6编写简明的声明函数 <add>forumTopicId: 301224 <add>localeTitle: 用 ES6 编写简洁的函数声明 <ide> --- <ide> <ide> ## Description <del><section id="description">在ES5中定义对象内的函数时,我们必须使用关键字<code>function</code> ,如下所示: <blockquote> const person = { <br>名称:“泰勒”, <br> sayHello:function(){ <br>回来`你好!我的名字是$ {this.name} .`; <br> } <br> }; </blockquote>使用ES6,您可以在定义对象中的函数时完全删除<code>function</code>关键字和冒号。以下是此语法的示例: <blockquote> const person = { <br>名称:“泰勒”, <br>问好() { <br>回来`你好!我的名字是$ {this.name} .`; <br> } <br> }; </blockquote></section> <add><section id='description'> <add>在 ES5 中,当我们需要在对象中定义一个函数的时候,我们必须如下面这般使用<code>function</code>关键字: <add> <add>```js <add>const person = { <add> name: "Taylor", <add> sayHello: function() { <add> return `Hello! My name is ${this.name}.`; <add> } <add>}; <add>``` <add> <add>在 ES6 语法的对象中定义函数的时候,你可以完全删除<code>function</code>关键字和冒号。请看以下例子: <add> <add>```js <add>const person = { <add> name: "Taylor", <add> sayHello() { <add> return `Hello! My name is ${this.name}.`; <add> } <add>}; <add>``` <add> <add></section> <ide> <ide> ## Instructions <del><section id="instructions">重构对象<code>bicycle</code>内的函数<code>setGear</code>以使用上述简写语法。 </section> <add><section id='instructions'> <add>使用以上这种简短的语法,重构在<code>bicycle</code>对象中的<code>setGear</code>函数。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 未使用传统函数表达式。 <add> - text: 不应使用<code>function</code>关键字定义方法。 <ide> testString: getUserInput => assert(!removeJSComments(code).match(/function/)); <del> - text: <code>setGear</code>是一个声明函数。 <add> - text: <code>setGear</code>应是一个函数。 <ide> testString: assert(typeof bicycle.setGear === 'function' && code.match(/setGear\s*\(.+\)\s*\{/)); <del> - text: <code>bicycle.setGear(48)</code>应该返回48。 <add> - text: 执行<code>bicycle.setGear(48)</code>应可以让<code>gear</code>的值变为 48。 <ide> testString: assert((new bicycle.setGear(48)).gear === 48); <ide> <ide> ``` <ide> tests: <ide> const bicycle = { <ide> gear: 2, <ide> setGear: function(newGear) { <del> "use strict"; <ide> this.gear = newGear; <ide> } <ide> }; <ide> // change code above this line <ide> bicycle.setGear(3); <ide> console.log(bicycle.gear); <del> <ide> ``` <ide> <ide> </div> <ide> <add>### After Test <add><div id='js-teardown'> <ide> <add>```js <add>const removeJSComments = str => str.replace(/\/\*[\s\S]*?\*\/|\/\/.*$/gm, ''); <add>``` <add> <add></div> <ide> <ide> </section> <ide> <ide> ## Solution <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add>const bicycle = { <add> gear: 2, <add> setGear(newGear) { <add> this.gear = newGear; <add> } <add>}; <add>bicycle.setGear(3); <ide> ``` <add> <ide> </section> <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/write-concise-object-literal-declarations-using-object-property-shorthand.chinese.md <add>--- <add>id: 587d7b8a367417b2b2512b4f <add>title: Write Concise Object Literal Declarations Using Object Property Shorthand <add>challengeType: 1 <add>forumTopicId: 301225 <add>localeTitle: 使用简单字段编写简洁的对象字面量声明 <add>--- <add> <add>## Description <add><section id='description'> <add>ES6 添加了一些很棒的功能,以便于更方便地定义对象。 <add>请看以下代码: <add> <add>```js <add>const getMousePosition = (x, y) => ({ <add> x: x, <add> y: y <add>}); <add>``` <add> <add><code>getMousePosition</code>是一个返回了拥有2个属性的对象的简单函数。 <add>ES6 提供了一个语法糖,消除了类似<code>x: x</code>这种冗余的写法.你可以仅仅只写一次<code>x</code>,解释器会自动将其转换成<code>x: x</code>。 <add>下面是使用这种语法重写的同样的函数: <add> <add>```js <add>const getMousePosition = (x, y) => ({ x, y }); <add>``` <add> <add></section> <add> <add>## Instructions <add><section id='instructions'> <add>请使用简单属性对象的语法来创建并返回一个<code>Person</code>对象。 <add></section> <add> <add>## Tests <add><section id='tests'> <add> <add>```yml <add>tests: <add> - text: '输出是<code>{name: "Zodiac Hasbro", age: 56, gender: "male"}</code>。' <add> testString: assert.deepEqual({name:"Zodiac Hasbro",age:56,gender:"male"}, createPerson("Zodiac Hasbro", 56, "male")); <add> - text: '不要使用<code>key:value</code>。' <add> testString: getUserInput => assert(!getUserInput('index').match(/:/g)); <add> <add>``` <add> <add></section> <add> <add>## Challenge Seed <add><section id='challengeSeed'> <add> <add><div id='js-seed'> <add> <add>```js <add>const createPerson = (name, age, gender) => { <add> "use strict"; <add> // change code below this line <add> return { <add> name: name, <add> age: age, <add> gender: gender <add> }; <add> // change code above this line <add>}; <add>console.log(createPerson("Zodiac Hasbro", 56, "male")); // returns a proper object <add>``` <add> <add></div> <add> <add> <add> <add></section> <add> <add>## Solution <add><section id='solution'> <add> <add>```js <add>const createPerson = (name, age, gender) => { <add> "use strict"; <add> return { <add> name, <add> age, <add> gender <add> }; <add>}; <add>``` <add> <add></section> <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/es6/write-higher-order-arrow-functions.chinese.md <del>--- <del>id: 587d7b88367417b2b2512b45 <del>title: Write Higher Order Arrow Functions <del>challengeType: 1 <del>videoUrl: '' <del>localeTitle: 编写高阶箭头函数 <del>--- <del> <del>## Description <del><section id="description">是时候我们看到处理数据时箭头功能有多强大了。 Arrow函数与高阶函数(例如<code>map()</code> , <code>filter()</code>和<code>reduce()</code>非常兼容,它们将其他函数作为处理数据集合的参数。阅读以下代码: <blockquote> FBPosts.filter(function(post){ <br> return post.thumbnail!== null &amp;&amp; post.shares&gt; 100 &amp;&amp; post.likes&gt; 500; <br> }) </blockquote>我们用<code>filter()</code>写了这个,至少使它有点可读。现在将它与以下使用箭头函数语法的代码进行比较: <blockquote> FBPosts.filter((post)=&gt; post.thumbnail!== null &amp;&amp; post.shares&gt; 100 &amp;&amp; post.likes&gt; 500) </blockquote>此代码更简洁,使用更少的代码行完成相同的任务。 </section> <del> <del>## Instructions <del><section id="instructions">使用箭头函数语法计算数组<code>realNumberArray</code>中只有正整数(十进制数不是整数)的<code>realNumberArray</code> ,并将新数组存储在变量<code>squaredIntegers</code> 。 </section> <del> <del>## Tests <del><section id='tests'> <del> <del>```yml <del>tests: <del> - text: <code>squaredIntegers</code>应该是一个常量变量(通过使用<code>const</code> )。 <del> testString: 'getUserInput => assert(getUserInput("index").match(/const\s+squaredIntegers/g), "<code>squaredIntegers</code> should be a constant variable (by using <code>const</code>).");' <del> - text: <code>squaredIntegers</code>应该是一个<code>array</code> <del> testString: 'assert(Array.isArray(squaredIntegers), "<code>squaredIntegers</code> should be an <code>array</code>");' <del> - text: '<code>squaredIntegers</code>应该是<code>[16, 1764, 36]</code> <code>squaredIntegers</code> <code>[16, 1764, 36]</code>' <del> testString: 'assert.deepStrictEqual(squaredIntegers, [16, 1764, 36], "<code>squaredIntegers</code> should be <code>[16, 1764, 36]</code>");' <del> - text: <code>function</code>关键字未使用。 <del> testString: 'getUserInput => assert(!getUserInput("index").match(/function/g), "<code>function</code> keyword was not used.");' <del> - text: 不应该使用循环 <del> testString: 'getUserInput => assert(!getUserInput("index").match(/(for)|(while)/g), "loop should not be used");' <del> - text: 应使用<code>map</code> , <code>filter</code>或<code>reduce</code> <del> testString: 'getUserInput => assert(getUserInput("index").match(/map|filter|reduce/g), "<code>map</code>, <code>filter</code>, or <code>reduce</code> should be used");' <del> <del>``` <del> <del></section> <del> <del>## Challenge Seed <del><section id='challengeSeed'> <del> <del><div id='js-seed'> <del> <del>```js <del>const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2]; <del>const squareList = (arr) => { <del> "use strict"; <del> // change code below this line <del> const squaredIntegers = arr; <del> // change code above this line <del> return squaredIntegers; <del>}; <del>// test your code <del>const squaredIntegers = squareList(realNumberArray); <del>console.log(squaredIntegers); <del> <del>``` <del> <del></div> <del> <del> <del> <del></section> <del> <del>## Solution <del><section id='solution'> <del> <del>```js <del>// solution required <del>``` <del></section>
36
PHP
PHP
add some fluent methods to routes
1c095f839d3b983784b360a4899a743a0a472243
<ide><path>src/Illuminate/Foundation/Support/Providers/RouteServiceProvider.php <ide> public function boot(Router $router) <ide> $this->loadCachedRoutes(); <ide> } else { <ide> $this->loadRoutes(); <add> <add> // We still want name look-ups to be fast, even if names were specified fluently <add> // on the route itself. This will update the name look-up table just in case. <add> $this->app->booted(function () use ($router) { <add> $router->getRoutes()->refreshNameLookup(); <add> }); <ide> } <ide> } <ide> <ide><path>src/Illuminate/Routing/Route.php <ide> protected function extractOptionalParameters() <ide> } <ide> <ide> /** <del> * Get the middlewares attached to the route. <add> * Set or get the middlewares attached to the route. <add> * <add> * @param array|string|null $middleware <ide> * <ide> * @return array <ide> */ <del> public function middleware() <add> public function middleware($middleware = null) <ide> { <del> return (array) Arr::get($this->action, 'middleware', []); <add> if (is_null($middleware)) { <add> return (array) Arr::get($this->action, 'middleware', []); <add> } <add> <add> if (is_string($middleware)) { <add> $middleware = [$middleware]; <add> } <add> <add> $this->action['middleware'] = array_merge($this->action['middleware'], $middleware); <add> <add> return $this; <ide> } <ide> <ide> /** <ide> public function getName() <ide> return isset($this->action['as']) ? $this->action['as'] : null; <ide> } <ide> <add> /** <add> * Add or change the route name. <add> * <add> * @param $name <add> * <add> * @return $this <add> */ <add> public function name($name) <add> { <add> $this->action['as'] = $name; <add> <add> return $this; <add> } <add> <ide> /** <ide> * Get the action name for the route. <ide> * <ide><path>src/Illuminate/Routing/RouteCollection.php <ide> protected function addLookups($route) <ide> } <ide> } <ide> <add> /** <add> * Refresh the name look-up table, in case any names have been defined fluently. <add> * <add> * @return void <add> */ <add> public function refreshNameLookup() <add> { <add> $this->nameList = []; <add> <add> foreach ($this->allRoutes as $route) { <add> if ($route->getName()) { <add> $this->nameList[$route->getName()] = $route; <add> } <add> } <add> } <add> <ide> /** <ide> * Add a route to the controller action dictionary. <ide> *
3
Text
Text
fix a spelling mistake in the docs
35c82f422d5db64baec6739490900f7f8fa7d7fd
<ide><path>docs/reference/commandline/logs.md <ide> The `docker logs` command batch-retrieves logs present at the time of execution. <ide> > **Note**: this command is only functional for containers that are started with <ide> > the `json-file` or `journald` logging driver. <ide> <del>For more information about selecting and configuring login-drivers, refer to <add>For more information about selecting and configuring logging drivers, refer to <ide> [Configure logging drivers](https://docs.docker.com/engine/admin/logging/overview/). <ide> <ide> The `docker logs --follow` command will continue streaming the new output from <ide><path>docs/reference/commandline/service_logs.md <ide> The `docker service logs` command batch-retrieves logs present at the time of ex <ide> > **Note**: this command is only functional for services that are started with <ide> > the `json-file` or `journald` logging driver. <ide> <del>For more information about selecting and configuring login-drivers, refer to <add>For more information about selecting and configuring logging drivers, refer to <ide> [Configure logging drivers](https://docs.docker.com/engine/admin/logging/overview/). <ide> <ide> The `docker service logs --follow` command will continue streaming the new output from
2
Javascript
Javascript
use process.nexttick() instead of setimmediate()
8dd635eb41ff05162b4851026a5a68a3360e5bbf
<ide><path>lib/internal/js_stream_socket.js <ide> class JSStreamSocket extends Socket { <ide> <ide> const handle = this._handle; <ide> <del> setImmediate(() => { <add> process.nextTick(() => { <ide> // Ensure that write is dispatched asynchronously. <ide> this.stream.end(() => { <ide> this.finishShutdown(handle, 0);
1
Javascript
Javascript
add comment for animationcurve-less node
09d75ad29ad2461f0bbc3d99993a93ed7733ab8f
<ide><path>examples/js/loaders/FBXLoader.js <ide> if ( curveNode.attr === 'R' ) { <ide> <ide> var curves = curveNode.curves; <add> <add> // Seems like some FBX files have AnimationCurveNode <add> // which doesn't have any connected AnimationCurve. <add> // Setting animation parameter for them here. <add> <add> if ( curves.x === null ) { <add> <add> curves.x = { <add> version: null, <add> times: [ 0.0 ], <add> values: [ 0.0 ] <add> }; <add> <add> } <add> <add> if ( curves.y === null ) { <add> <add> curves.y = { <add> version: null, <add> times: [ 0.0 ], <add> values: [ 0.0 ] <add> }; <add> <add> } <add> <add> if ( curves.z === null ) { <add> <add> curves.z = { <add> version: null, <add> times: [ 0.0 ], <add> values: [ 0.0 ] <add> }; <add> <add> } <add> <ide> curves.x.values = curves.x.values.map( degreeToRadian ); <ide> curves.y.values = curves.y.values.map( degreeToRadian ); <ide> curves.z.values = curves.z.values.map( degreeToRadian );
1
Ruby
Ruby
add a failure message to be_detected_from matcher
557105640b5154e3fe1299aa31abdc106aa71df5
<ide><path>Library/Homebrew/test/version_spec.rb <ide> <ide> describe "::detect" do <ide> matcher :be_detected_from do |url, specs = {}| <del> match do |version| <del> Version.detect(url, specs) == version <add> detected = Version.detect(url, specs) <add> <add> match do |expected| <add> detected == expected <add> end <add> <add> failure_message do |expected| <add> format = <<-EOS <add> expected: %s <add> detected: %s <add> EOS <add> format % [expected, detected] <ide> end <ide> end <ide>
1
Javascript
Javascript
fix bug in ie where clone removes whitespace nodes
8e40e7070d44d11332adc1426b7076c2be570b2b
<ide><path>src/Angular.js <ide> if (msie) { <ide> }; <ide> } <ide> <add>function quickClone(element) { <add> return jqLite(element[0].cloneNode(true)); <add>} <add> <ide> function isVisible(element) { <ide> var rect = element[0].getBoundingClientRect(), <ide> width = (rect.width || (rect.right||0 - rect.left||0)), <ide><path>src/directives.js <ide> angularWidget("@ng:repeat", function(expression, element){ <ide> if (keyIdent) childScope[keyIdent] = key; <ide> } else { <ide> // grow children <del> childScope = template(element.clone(), createScope(currentScope)); <add> childScope = template(quickClone(element), createScope(currentScope)); <ide> childScope[valueIdent] = collection[key]; <ide> if (keyIdent) childScope[keyIdent] = key; <ide> lastElement.after(childScope.$element); <ide><path>src/widgets.js <ide> var ngSwitch = angularWidget('ng:switch', function (element){ <ide> childScope = createScope(scope); <ide> foreach(cases, function(switchCase){ <ide> if (switchCase.when(childScope, value)) { <del> var caseElement = switchCase.element.clone(); <add> var caseElement = quickClone(switchCase.element); <ide> element.append(caseElement); <ide> childScope.$tryEval(switchCase.change, element); <ide> switchCase.template(caseElement, childScope);
3
Text
Text
add ronnyvotel@ to maintainers list
4648f6dc2dbe137f1f52c5ee203dc2572225c84a
<ide><path>research/object_detection/README.md <ide> https://scholar.googleusercontent.com/scholar.bib?q=info:l291WsrB-hQJ:scholar.go <ide> <ide> * Jonathan Huang, github: [jch1](https://github.com/jch1) <ide> * Vivek Rathod, github: [tombstone](https://github.com/tombstone) <add>* Ronny Votel, github: [ronnyvotel](https://github.com/ronnyvotel) <ide> * Derek Chow, github: [derekjchow](https://github.com/derekjchow) <ide> * Chen Sun, github: [jesu9](https://github.com/jesu9) <ide> * Menglong Zhu, github: [dreamdragon](https://github.com/dreamdragon)
1
Mixed
Java
add support for extrapolation
6d978c3c8b1e3929e59439db0c0a34dd094253cf
<ide><path>Libraries/Animated/src/AnimatedImplementation.js <ide> class AnimatedInterpolation extends AnimatedWithChildren { <ide> } <ide> <ide> __getNativeConfig(): any { <del> NativeAnimatedHelper.validateInterpolation(this._config); <add> if (__DEV__) { <add> NativeAnimatedHelper.validateInterpolation(this._config); <add> } <add> <ide> return { <del> ...this._config, <add> inputRange: this._config.inputRange, <ide> // Only the `outputRange` can contain strings so we don't need to tranform `inputRange` here <ide> outputRange: this.__transformDataType(this._config.outputRange), <add> extrapolateLeft: this._config.extrapolateLeft || this._config.extrapolate || 'extend', <add> extrapolateRight: this._config.extrapolateRight || this._config.extrapolate || 'extend', <ide> type: 'interpolation', <ide> }; <ide> } <ide><path>Libraries/Animated/src/NativeAnimatedHelper.js <ide> function validateInterpolation(config: Object): void { <ide> var SUPPORTED_INTERPOLATION_PARAMS = { <ide> inputRange: true, <ide> outputRange: true, <add> extrapolate: true, <add> extrapolateRight: true, <add> extrapolateLeft: true, <ide> }; <ide> for (var key in config) { <ide> if (!SUPPORTED_INTERPOLATION_PARAMS.hasOwnProperty(key)) { <ide><path>ReactAndroid/src/main/java/com/facebook/react/animated/InterpolationAnimatedNode.java <ide> package com.facebook.react.animated; <ide> <add>import com.facebook.react.bridge.JSApplicationIllegalArgumentException; <ide> import com.facebook.react.bridge.ReadableArray; <ide> import com.facebook.react.bridge.ReadableMap; <ide> <ide> */ <ide> /*package*/ class InterpolationAnimatedNode extends ValueAnimatedNode { <ide> <add> public static final String EXTRAPOLATE_TYPE_IDENTITY = "identity"; <add> public static final String EXTRAPOLATE_TYPE_CLAMP = "clamp"; <add> public static final String EXTRAPOLATE_TYPE_EXTEND = "extend"; <add> <ide> private static double[] fromDoubleArray(ReadableArray ary) { <ide> double[] res = new double[ary.size()]; <ide> for (int i = 0; i < res.length; i++) { <ide> private static double interpolate( <ide> double inputMin, <ide> double inputMax, <ide> double outputMin, <del> double outputMax) { <add> double outputMax, <add> String extrapolateLeft, <add> String extrapolateRight) { <add> double result = value; <add> <add> // Extrapolate <add> if (result < inputMin) { <add> switch (extrapolateLeft) { <add> case EXTRAPOLATE_TYPE_IDENTITY: <add> return result; <add> case EXTRAPOLATE_TYPE_CLAMP: <add> result = inputMin; <add> break; <add> case EXTRAPOLATE_TYPE_EXTEND: <add> break; <add> default: <add> throw new JSApplicationIllegalArgumentException( <add> "Invalid extrapolation type " + extrapolateLeft + "for left extrapolation"); <add> } <add> } <add> <add> if (result > inputMax) { <add> switch (extrapolateRight) { <add> case EXTRAPOLATE_TYPE_IDENTITY: <add> return result; <add> case EXTRAPOLATE_TYPE_CLAMP: <add> result = inputMax; <add> break; <add> case EXTRAPOLATE_TYPE_EXTEND: <add> break; <add> default: <add> throw new JSApplicationIllegalArgumentException( <add> "Invalid extrapolation type " + extrapolateRight + "for right extrapolation"); <add> } <add> } <add> <ide> return outputMin + (outputMax - outputMin) * <del> (value - inputMin) / (inputMax - inputMin); <add> (result - inputMin) / (inputMax - inputMin); <ide> } <ide> <del> /*package*/ static double interpolate(double value, double[] inputRange, double[] outputRange) { <add> /*package*/ static double interpolate( <add> double value, <add> double[] inputRange, <add> double[] outputRange, <add> String extrapolateLeft, <add> String extrapolateRight <add> ) { <ide> int rangeIndex = findRangeIndex(value, inputRange); <ide> return interpolate( <ide> value, <ide> inputRange[rangeIndex], <ide> inputRange[rangeIndex + 1], <ide> outputRange[rangeIndex], <del> outputRange[rangeIndex + 1]); <add> outputRange[rangeIndex + 1], <add> extrapolateLeft, <add> extrapolateRight); <ide> } <ide> <ide> private static int findRangeIndex(double value, double[] ranges) { <ide> private static int findRangeIndex(double value, double[] ranges) { <ide> <ide> private final double mInputRange[]; <ide> private final double mOutputRange[]; <add> private final String mExtrapolateLeft; <add> private final String mExtrapolateRight; <ide> private @Nullable ValueAnimatedNode mParent; <ide> <ide> public InterpolationAnimatedNode(ReadableMap config) { <ide> mInputRange = fromDoubleArray(config.getArray("inputRange")); <ide> mOutputRange = fromDoubleArray(config.getArray("outputRange")); <add> mExtrapolateLeft = config.getString("extrapolateLeft"); <add> mExtrapolateRight = config.getString("extrapolateRight"); <ide> } <ide> <ide> @Override <ide> public void update() { <ide> throw new IllegalStateException("Trying to update interpolation node that has not been " + <ide> "attached to the parent"); <ide> } <del> mValue = interpolate(mParent.mValue, mInputRange, mOutputRange); <add> mValue = interpolate(mParent.mValue, mInputRange, mOutputRange, mExtrapolateLeft, mExtrapolateRight); <ide> } <ide> } <ide><path>ReactAndroid/src/test/java/com/facebook/react/animated/NativeAnimatedInterpolationTest.java <ide> @RunWith(RobolectricTestRunner.class) <ide> public class NativeAnimatedInterpolationTest { <ide> <add> private double simpleInterpolation(double value, double[] input, double[] output) { <add> return InterpolationAnimatedNode.interpolate( <add> value, <add> input, <add> output, <add> InterpolationAnimatedNode.EXTRAPOLATE_TYPE_EXTEND, <add> InterpolationAnimatedNode.EXTRAPOLATE_TYPE_EXTEND <add> ); <add> } <add> <ide> @Test <ide> public void testSimpleOneToOneMapping() { <ide> double[] input = new double[] {0d, 1d}; <ide> double[] output = new double[] {0d, 1d}; <del> assertThat(InterpolationAnimatedNode.interpolate(0, input, output)).isEqualTo(0); <del> assertThat(InterpolationAnimatedNode.interpolate(0.5, input, output)).isEqualTo(0.5); <del> assertThat(InterpolationAnimatedNode.interpolate(0.8, input, output)).isEqualTo(0.8); <del> assertThat(InterpolationAnimatedNode.interpolate(1, input, output)).isEqualTo(1); <add> assertThat(simpleInterpolation(0, input, output)).isEqualTo(0); <add> assertThat(simpleInterpolation(0.5, input, output)).isEqualTo(0.5); <add> assertThat(simpleInterpolation(0.8, input, output)).isEqualTo(0.8); <add> assertThat(simpleInterpolation(1, input, output)).isEqualTo(1); <ide> } <ide> <ide> @Test <ide> public void testWiderOutputRange() { <ide> double[] input = new double[] {0d, 1d}; <ide> double[] output = new double[] {100d, 200d}; <del> assertThat(InterpolationAnimatedNode.interpolate(0, input, output)).isEqualTo(100); <del> assertThat(InterpolationAnimatedNode.interpolate(0.5, input, output)).isEqualTo(150); <del> assertThat(InterpolationAnimatedNode.interpolate(0.8, input, output)).isEqualTo(180); <del> assertThat(InterpolationAnimatedNode.interpolate(1, input, output)).isEqualTo(200); <add> assertThat(simpleInterpolation(0, input, output)).isEqualTo(100); <add> assertThat(simpleInterpolation(0.5, input, output)).isEqualTo(150); <add> assertThat(simpleInterpolation(0.8, input, output)).isEqualTo(180); <add> assertThat(simpleInterpolation(1, input, output)).isEqualTo(200); <ide> } <ide> <ide> @Test <ide> public void testWiderInputRange() { <ide> double[] input = new double[] {2000d, 3000d}; <ide> double[] output = new double[] {1d, 2d}; <del> assertThat(InterpolationAnimatedNode.interpolate(2000, input, output)).isEqualTo(1); <del> assertThat(InterpolationAnimatedNode.interpolate(2250, input, output)).isEqualTo(1.25); <del> assertThat(InterpolationAnimatedNode.interpolate(2800, input, output)).isEqualTo(1.8); <del> assertThat(InterpolationAnimatedNode.interpolate(3000, input, output)).isEqualTo(2); <add> assertThat(simpleInterpolation(2000, input, output)).isEqualTo(1); <add> assertThat(simpleInterpolation(2250, input, output)).isEqualTo(1.25); <add> assertThat(simpleInterpolation(2800, input, output)).isEqualTo(1.8); <add> assertThat(simpleInterpolation(3000, input, output)).isEqualTo(2); <ide> } <ide> <ide> @Test <ide> public void testManySegments() { <ide> double[] input = new double[] {-1d, 1d, 5d}; <ide> double[] output = new double[] {0, 10d, 20d}; <del> assertThat(InterpolationAnimatedNode.interpolate(-1, input, output)).isEqualTo(0); <del> assertThat(InterpolationAnimatedNode.interpolate(0, input, output)).isEqualTo(5); <del> assertThat(InterpolationAnimatedNode.interpolate(1, input, output)).isEqualTo(10); <del> assertThat(InterpolationAnimatedNode.interpolate(2, input, output)).isEqualTo(12.5); <del> assertThat(InterpolationAnimatedNode.interpolate(5, input, output)).isEqualTo(20); <add> assertThat(simpleInterpolation(-1, input, output)).isEqualTo(0); <add> assertThat(simpleInterpolation(0, input, output)).isEqualTo(5); <add> assertThat(simpleInterpolation(1, input, output)).isEqualTo(10); <add> assertThat(simpleInterpolation(2, input, output)).isEqualTo(12.5); <add> assertThat(simpleInterpolation(5, input, output)).isEqualTo(20); <ide> } <ide> <ide> @Test <del> public void testExtrapolate() { <add> public void testExtendExtrapolate() { <ide> double[] input = new double[] {10d, 20d}; <ide> double[] output = new double[] {0d, 1d}; <del> assertThat(InterpolationAnimatedNode.interpolate(30d, input, output)).isEqualTo(2); <del> assertThat(InterpolationAnimatedNode.interpolate(5d, input, output)).isEqualTo(-0.5); <add> assertThat(simpleInterpolation(30d, input, output)).isEqualTo(2); <add> assertThat(simpleInterpolation(5d, input, output)).isEqualTo(-0.5); <ide> } <ide> <add> @Test <add> public void testClampExtrapolate() { <add> double[] input = new double[] {10d, 20d}; <add> double[] output = new double[] {0d, 1d}; <add> assertThat(InterpolationAnimatedNode.interpolate( <add> 30d, <add> input, <add> output, <add> InterpolationAnimatedNode.EXTRAPOLATE_TYPE_CLAMP, <add> InterpolationAnimatedNode.EXTRAPOLATE_TYPE_CLAMP <add> )).isEqualTo(1); <add> assertThat(InterpolationAnimatedNode.interpolate( <add> 5d, <add> input, <add> output, <add> InterpolationAnimatedNode.EXTRAPOLATE_TYPE_CLAMP, <add> InterpolationAnimatedNode.EXTRAPOLATE_TYPE_CLAMP <add> )).isEqualTo(0); <add> } <add> <add> @Test <add> public void testIdentityExtrapolate() { <add> double[] input = new double[] {10d, 20d}; <add> double[] output = new double[] {0d, 1d}; <add> assertThat(InterpolationAnimatedNode.interpolate( <add> 30d, <add> input, <add> output, <add> InterpolationAnimatedNode.EXTRAPOLATE_TYPE_IDENTITY, <add> InterpolationAnimatedNode.EXTRAPOLATE_TYPE_IDENTITY <add> )).isEqualTo(30); <add> assertThat(InterpolationAnimatedNode.interpolate( <add> 5d, <add> input, <add> output, <add> InterpolationAnimatedNode.EXTRAPOLATE_TYPE_IDENTITY, <add> InterpolationAnimatedNode.EXTRAPOLATE_TYPE_IDENTITY <add> )).isEqualTo(5); <add> } <ide> } <ide><path>ReactAndroid/src/test/java/com/facebook/react/animated/NativeAnimatedNodeTraversalTest.java <ide> public void testInterpolationNode() { <ide> "inputRange", <ide> JavaOnlyArray.of(10d, 20d), <ide> "outputRange", <del> JavaOnlyArray.of(0d, 1d))); <add> JavaOnlyArray.of(0d, 1d), <add> "extrapolateLeft", <add> "extend", <add> "extrapolateRight", <add> "extend")); <ide> <ide> mNativeAnimatedNodesManager.createAnimatedNode( <ide> 3,
5
PHP
PHP
add a unit test for stringtype
33c03f446456bea4f3e4c13eaaadf61c22463644
<ide><path>tests/TestCase/Database/Type/StringTypeTest.php <add><?php <add>/** <add> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <add> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <add> * <add> * Licensed under The MIT License <add> * For full copyright and license information, please see the LICENSE.txt <add> * Redistributions of files must retain the above copyright notice. <add> * <add> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <add> * @link http://cakephp.org CakePHP(tm) Project <add> * @since 3.1.7 <add> * @license http://www.opensource.org/licenses/mit-license.php MIT License <add> */ <add>namespace Cake\Test\TestCase\Database\Type; <add> <add>use Cake\Database\Type; <add>use Cake\Database\Type\IntegerType; <add>use Cake\TestSuite\TestCase; <add>use \PDO; <add> <add>/** <add> * Test for the String type. <add> */ <add>class StringTypeTest extends TestCase <add>{ <add> <add> /** <add> * Setup <add> * <add> * @return void <add> */ <add> public function setUp() <add> { <add> parent::setUp(); <add> $this->type = Type::build('string'); <add> $this->driver = $this->getMock('Cake\Database\Driver'); <add> } <add> <add> /** <add> * Test toPHP <add> * <add> * @return void <add> */ <add> public function testToPHP() <add> { <add> $this->assertNull($this->type->toPHP(null, $this->driver)); <add> $this->assertSame('word', $this->type->toPHP('word', $this->driver)); <add> $this->assertSame('2.123', $this->type->toPHP(2.123, $this->driver)); <add> } <add> <add> /** <add> * Test converting to database format <add> * <add> * @return void <add> */ <add> public function testToDatabase() <add> { <add> $obj = $this->getMock('StdClass', ['__toString']); <add> $obj->method('__toString')->will($this->returnValue('toString called')); <add> <add> $this->assertNull($this->type->toDatabase(null, $this->driver)); <add> $this->assertSame('word', $this->type->toDatabase('word', $this->driver)); <add> $this->assertSame('2.123', $this->type->toDatabase(2.123, $this->driver)); <add> $this->assertSame('toString called', $this->type->toDatabase($obj, $this->driver)); <add> } <add> <add> /** <add> * Tests that passing an invalid value will throw an exception <add> * <add> * @expectedException InvalidArgumentException <add> * @return void <add> */ <add> public function testToDatabseInvalidArray() <add> { <add> $this->type->toDatabase([1, 2, 3], $this->driver); <add> } <add> <add> /** <add> * Test marshalling <add> * <add> * @return void <add> */ <add> public function testMarshal() <add> { <add> $this->assertNull($this->type->marshal(null)); <add> $this->assertSame('word', $this->type->marshal('word')); <add> $this->assertSame('2.123', $this->type->marshal(2.123)); <add> $this->assertSame('', $this->type->marshal([1, 2, 3])); <add> } <add> <add> /** <add> * Test that the PDO binding type is correct. <add> * <add> * @return void <add> */ <add> public function testToStatement() <add> { <add> $this->assertEquals(PDO::PARAM_STR, $this->type->toStatement('', $this->driver)); <add> } <add>}
1
Javascript
Javascript
add videojs to window directly. fix #448
b1b0ac0377b3fefe9c09c9d09bd83421c14672c7
<ide><path>src/js/core.js <ide> var vjs = function(id, options, ready){ <ide> <ide> // Extended name, also available externally, window.videojs <ide> var videojs = vjs; <add>window.videojs = window.vjs = vjs; <ide> <ide> // CDN Version. Used to target right flash swf. <ide> vjs.CDN_VERSION = 'GENERATED_CDN_VSN';
1
PHP
PHP
add routes() hook
5ab8de4468c00ada8a1323da88be1acb8811a421
<ide><path>src/Http/BaseApplication.php <ide> public function bootstrap() <ide> require_once $this->configDir . '/bootstrap.php'; <ide> } <ide> <add> /** <add> * Define the routes for an application. <add> * <add> * By default this will load `config/routes.php` for ease of use and backwards compatibility. <add> * <add> * @param \Cake\Routing\RouteBuilder $routes A route builder to add routes into. <add> * @return void <add> */ <add> public function routes($routes) <add> { <add> require $this->configDir . '/routes.php'; <add> } <add> <ide> /** <ide> * Invoke the application. <ide> * <ide><path>src/Routing/Middleware/RoutingMiddleware.php <ide> */ <ide> namespace Cake\Routing\Middleware; <ide> <add>use Cake\Http\BaseApplication; <ide> use Cake\Http\MiddlewareQueue; <ide> use Cake\Http\Runner; <ide> use Cake\Routing\Exception\RedirectException; <add>use Cake\Routing\RouteBuilder; <ide> use Cake\Routing\Router; <ide> use Psr\Http\Message\ResponseInterface; <ide> use Psr\Http\Message\ServerRequestInterface; <ide> */ <ide> class RoutingMiddleware <ide> { <add> /** <add> * Constructor <add> * <add> * @param \Cake\Http\BaseApplication $app The application instance that routes are defined on. <add> */ <add> public function __construct(BaseApplication $app = null) <add> { <add> $this->app = $app; <add> } <add> <add> /** <add> * Trigger the application's routes() hook if the application exists. <add> * <add> * If the middleware is created without an Application, routes will be <add> * loaded via the automatic route loading that pre-dates the routes() hook. <add> * <add> * @return void <add> */ <add> protected function loadRoutes() <add> { <add> if ($this->app) { <add> $builder = Router::getRouteBuilder('/'); <add> $this->app->routes($builder); <add> // Prevent routes from being loaded again <add> Router::$initialized = true; <add> } <add> } <add> <ide> /** <ide> * Apply routing and update the request. <ide> * <del> * Any route/path specific middleware will be wrapped around $next and then the new middleware stack <del> * will be invoked. <add> * Any route/path specific middleware will be wrapped around $next and then the new middleware stack will be <add> * invoked. <ide> * <ide> * @param \Psr\Http\Message\ServerRequestInterface $request The request. <ide> * @param \Psr\Http\Message\ResponseInterface $response The response. <ide> class RoutingMiddleware <ide> */ <ide> public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $next) <ide> { <add> $this->loadRoutes(); <ide> try { <ide> Router::setRequestContext($request); <ide> $params = (array)$request->getAttribute('params', []); <ide><path>src/Routing/Router.php <ide> public static function getRouteCollection() <ide> /** <ide> * Loads route configuration <ide> * <add> * @deprecated 3.5.0 Routes will be loaded via the Application::routes() hook in 4.0.0 <ide> * @return void <ide> */ <ide> protected static function _loadRoutes() <ide><path>tests/TestCase/Routing/Middleware/RoutingMiddlewareTest.php <ide> use Cake\Routing\Middleware\RoutingMiddleware; <ide> use Cake\Routing\Router; <ide> use Cake\TestSuite\TestCase; <add>use TestApp\Application; <ide> use Zend\Diactoros\Response; <ide> use Zend\Diactoros\ServerRequestFactory; <ide> <ide> public function testRouterSetParams() <ide> $middleware($request, $response, $next); <ide> } <ide> <add> /** <add> * Test middleware invoking hook method <add> * <add> * @return void <add> */ <add> public function testRoutesHookInvokedOnApp() <add> { <add> Router::reload(); <add> $this->assertFalse(Router::$initialized, 'Router precondition failed'); <add> <add> $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/app/articles']); <add> $response = new Response(); <add> $next = function ($req, $res) { <add> $expected = [ <add> 'controller' => 'Articles', <add> 'action' => 'index', <add> 'plugin' => null, <add> 'pass' => [], <add> '_matchedRoute' => '/app/articles' <add> ]; <add> $this->assertEquals($expected, $req->getAttribute('params')); <add> $this->assertTrue(Router::$initialized, 'Router state should indicate routes loaded'); <add> $this->assertCount(1, Router::routes()); <add> }; <add> $app = new Application(CONFIG); <add> $middleware = new RoutingMiddleware($app); <add> $middleware($request, $response, $next); <add> } <add> <ide> /** <ide> * Test that routing is not applied if a controller exists already <ide> * <ide><path>tests/test_app/TestApp/Application.php <ide> public function middleware($middleware) <ide> <ide> return $middleware; <ide> } <add> <add> /** <add> * Routes hook, used for testing with RoutingMiddleware. <add> * <add> * @param \Cake\Routing\RouteBuilder $routes <add> * @return void <add> */ <add> public function routes($routes) <add> { <add> $routes->scope('/app', function ($routes) { <add> $routes->connect('/articles', ['controller' => 'Articles']); <add> }); <add> } <ide> }
5
Ruby
Ruby
move batch finders to relation
dc3cc6c608b93209b23bbebd2ade04835abd6f6c
<ide><path>activerecord/lib/active_record.rb <ide> module ActiveRecord <ide> autoload :Calculations <ide> autoload :PredicateBuilder <ide> autoload :SpawnMethods <add> autoload :Batches <ide> end <ide> <ide> autoload :Base <del> autoload :Batches <ide> autoload :Callbacks <ide> autoload :DynamicFinderMatch <ide> autoload :DynamicScopeMatch <ide><path>activerecord/lib/active_record/base.rb <ide> def colorize_logging(*args) <ide> alias :colorize_logging= :colorize_logging <ide> <ide> delegate :find, :first, :last, :all, :destroy, :destroy_all, :exists?, :delete, :delete_all, :update, :update_all, :to => :scoped <add> delegate :find_each, :find_in_batches, :to => :scoped <ide> delegate :select, :group, :order, :limit, :joins, :where, :preload, :eager_load, :includes, :from, :lock, :readonly, :having, :to => :scoped <ide> delegate :count, :average, :minimum, :maximum, :sum, :calculate, :to => :scoped <ide> <ide> def object_from_yaml(string) <ide> # #save_with_autosave_associations to be wrapped inside a transaction. <ide> include AutosaveAssociation, NestedAttributes <ide> <del> include Aggregations, Transactions, Reflection, Batches, Serialization <add> include Aggregations, Transactions, Reflection, Serialization <ide> <ide> end <ide> end <ide><path>activerecord/lib/active_record/batches.rb <del>module ActiveRecord <del> module Batches # :nodoc: <del> extend ActiveSupport::Concern <del> <del> # When processing large numbers of records, it's often a good idea to do <del> # so in batches to prevent memory ballooning. <del> module ClassMethods <del> # Yields each record that was found by the find +options+. The find is <del> # performed by find_in_batches with a batch size of 1000 (or as <del> # specified by the <tt>:batch_size</tt> option). <del> # <del> # Example: <del> # <del> # Person.find_each(:conditions => "age > 21") do |person| <del> # person.party_all_night! <del> # end <del> # <del> # Note: This method is only intended to use for batch processing of <del> # large amounts of records that wouldn't fit in memory all at once. If <del> # you just need to loop over less than 1000 records, it's probably <del> # better just to use the regular find methods. <del> def find_each(options = {}) <del> find_in_batches(options) do |records| <del> records.each { |record| yield record } <del> end <del> <del> self <del> end <del> <del> # Yields each batch of records that was found by the find +options+ as <del> # an array. The size of each batch is set by the <tt>:batch_size</tt> <del> # option; the default is 1000. <del> # <del> # You can control the starting point for the batch processing by <del> # supplying the <tt>:start</tt> option. This is especially useful if you <del> # want multiple workers dealing with the same processing queue. You can <del> # make worker 1 handle all the records between id 0 and 10,000 and <del> # worker 2 handle from 10,000 and beyond (by setting the <tt>:start</tt> <del> # option on that worker). <del> # <del> # It's not possible to set the order. That is automatically set to <del> # ascending on the primary key ("id ASC") to make the batch ordering <del> # work. This also mean that this method only works with integer-based <del> # primary keys. You can't set the limit either, that's used to control <del> # the the batch sizes. <del> # <del> # Example: <del> # <del> # Person.find_in_batches(:conditions => "age > 21") do |group| <del> # sleep(50) # Make sure it doesn't get too crowded in there! <del> # group.each { |person| person.party_all_night! } <del> # end <del> def find_in_batches(options = {}) <del> raise "You can't specify an order, it's forced to be #{batch_order}" if options[:order] <del> raise "You can't specify a limit, it's forced to be the batch_size" if options[:limit] <del> <del> start = options.delete(:start).to_i <del> batch_size = options.delete(:batch_size) || 1000 <del> <del> with_scope(:find => options.merge(:order => batch_order, :limit => batch_size)) do <del> records = find(:all, :conditions => [ "#{table_name}.#{primary_key} >= ?", start ]) <del> <del> while records.any? <del> yield records <del> <del> break if records.size < batch_size <del> records = find(:all, :conditions => [ "#{table_name}.#{primary_key} > ?", records.last.id ]) <del> end <del> end <del> end <del> <del> <del> private <del> def batch_order <del> "#{table_name}.#{primary_key} ASC" <del> end <del> end <del> end <del>end <ide>\ No newline at end of file <ide><path>activerecord/lib/active_record/relation.rb <ide> class Relation <ide> MULTI_VALUE_METHODS = [:select, :group, :order, :joins, :where, :having] <ide> SINGLE_VALUE_METHODS = [:limit, :offset, :lock, :readonly, :create_with, :from] <ide> <del> include FinderMethods, Calculations, SpawnMethods, QueryMethods <add> include FinderMethods, Calculations, SpawnMethods, QueryMethods, Batches <ide> <ide> delegate :length, :collect, :map, :each, :all?, :include?, :to => :to_a <ide> delegate :insert, :to => :arel <ide><path>activerecord/lib/active_record/relation/batches.rb <add>module ActiveRecord <add> module Batches # :nodoc: <add> # Yields each record that was found by the find +options+. The find is <add> # performed by find_in_batches with a batch size of 1000 (or as <add> # specified by the <tt>:batch_size</tt> option). <add> # <add> # Example: <add> # <add> # Person.where("age > 21").find_each do |person| <add> # person.party_all_night! <add> # end <add> # <add> # Note: This method is only intended to use for batch processing of <add> # large amounts of records that wouldn't fit in memory all at once. If <add> # you just need to loop over less than 1000 records, it's probably <add> # better just to use the regular find methods. <add> def find_each(options = {}) <add> find_in_batches(options) do |records| <add> records.each { |record| yield record } <add> end <add> <add> self <add> end <add> <add> # Yields each batch of records that was found by the find +options+ as <add> # an array. The size of each batch is set by the <tt>:batch_size</tt> <add> # option; the default is 1000. <add> # <add> # You can control the starting point for the batch processing by <add> # supplying the <tt>:start</tt> option. This is especially useful if you <add> # want multiple workers dealing with the same processing queue. You can <add> # make worker 1 handle all the records between id 0 and 10,000 and <add> # worker 2 handle from 10,000 and beyond (by setting the <tt>:start</tt> <add> # option on that worker). <add> # <add> # It's not possible to set the order. That is automatically set to <add> # ascending on the primary key ("id ASC") to make the batch ordering <add> # work. This also mean that this method only works with integer-based <add> # primary keys. You can't set the limit either, that's used to control <add> # the the batch sizes. <add> # <add> # Example: <add> # <add> # Person.where("age > 21").find_in_batches do |group| <add> # sleep(50) # Make sure it doesn't get too crowded in there! <add> # group.each { |person| person.party_all_night! } <add> # end <add> def find_in_batches(options = {}) <add> relation = self <add> <add> if (finder_options = options.except(:start, :batch_size)).present? <add> raise "You can't specify an order, it's forced to be #{batch_order}" if options[:order].present? <add> raise "You can't specify a limit, it's forced to be the batch_size" if options[:limit].present? <add> <add> relation = apply_finder_options(finder_options) <add> end <add> <add> start = options.delete(:start).to_i <add> batch_size = options.delete(:batch_size) || 1000 <add> <add> relation = relation.except(:order).order(batch_order).limit(batch_size) <add> records = relation.where(primary_key.gteq(start)).all <add> <add> while records.any? <add> yield records <add> <add> break if records.size < batch_size <add> records = relation.where(primary_key.gt(records.last.id)).all <add> end <add> end <add> <add> private <add> <add> def batch_order <add> "#{@klass.table_name}.#{@klass.primary_key} ASC" <add> end <add> end <add>end <ide>\ No newline at end of file
5
Python
Python
pass initkwargs stored on view to instance
f1ca71ce217a0477bc1f54dfd551b5da23386e41
<ide><path>rest_framework/utils/breadcrumbs.py <ide> def breadcrumbs_recursive(url, breadcrumbs_list, prefix, seen): <ide> # Check if this is a REST framework view, <ide> # and if so add it to the breadcrumbs <ide> cls = getattr(view, 'cls', None) <add> initkwargs = getattr(view, 'initkwargs', {}) <ide> if cls is not None and issubclass(cls, APIView): <ide> # Don't list the same view twice in a row. <ide> # Probably an optional trailing slash. <ide> if not seen or seen[-1] != view: <del> c = cls() <add> c = cls(**initkwargs) <ide> c.suffix = getattr(view, 'suffix', None) <ide> name = c.get_view_name() <ide> insert_url = preserve_builtin_query_params(prefix + url, request)
1
Go
Go
rename some tests to be more descriptive
a9c5a40087348ac47d94f2cc71a8d76e946a1b98
<ide><path>pkg/system/chtimes_linux_test.go <ide> import ( <ide> "time" <ide> ) <ide> <del>// TestChtimesLinux tests Chtimes access time on a tempfile on Linux <del>func TestChtimesLinux(t *testing.T) { <add>// TestChtimesATime tests Chtimes access time on a tempfile. <add>func TestChtimesATime(t *testing.T) { <ide> file := filepath.Join(t.TempDir(), "exist") <ide> if err := os.WriteFile(file, []byte("hello"), 0o644); err != nil { <ide> t.Fatal(err) <ide><path>pkg/system/chtimes_test.go <ide> import ( <ide> "time" <ide> ) <ide> <del>// TestChtimes tests Chtimes on a tempfile. Test only mTime, because aTime is OS dependent <del>func TestChtimes(t *testing.T) { <add>// TestChtimesModTime tests Chtimes on a tempfile. Test only mTime, because <add>// aTime is OS dependent. <add>func TestChtimesModTime(t *testing.T) { <ide> file := filepath.Join(t.TempDir(), "exist") <ide> if err := os.WriteFile(file, []byte("hello"), 0o644); err != nil { <ide> t.Fatal(err) <ide><path>pkg/system/chtimes_windows_test.go <ide> import ( <ide> "time" <ide> ) <ide> <del>// TestChtimesWindows tests Chtimes access time on a tempfile on Windows <del>func TestChtimesWindows(t *testing.T) { <add>// TestChtimesATimeWindows tests Chtimes access time on a tempfile on Windows. <add>func TestChtimesATimeWindows(t *testing.T) { <ide> file := filepath.Join(t.TempDir(), "exist") <ide> if err := os.WriteFile(file, []byte("hello"), 0o644); err != nil { <ide> t.Fatal(err)
3
Ruby
Ruby
add test case to relation select
ccbba229386bdc629be5f5f4ef765ab5e29e7da7
<ide><path>activerecord/test/cases/relation/select_test.rb <add># frozen_string_literal: true <add> <add>require "cases/helper" <add>require "models/post" <add> <add>module ActiveRecord <add> class SelectTest < ActiveRecord::TestCase <add> fixtures :posts <add> <add> def test_select_with_nil_agrument <add> expected = Post.select(:title).to_sql <add> assert_equal expected, Post.select(nil).select(:title).to_sql <add> end <add> end <add>end
1
PHP
PHP
allow only keys directly on safe
5e4ded83bacc64e5604b6f71496734071c53b221
<ide><path>src/Illuminate/Foundation/Http/FormRequest.php <ide> protected function failedAuthorization() <ide> /** <ide> * Get a validated input container for the validated input. <ide> * <del> * @return \Illuminate\Support\ValidatedInput <add> * @param array|null $keys <add> * @return \Illuminate\Support\ValidatedInput|array <ide> */ <del> public function safe() <add> public function safe(array $keys = null) <ide> { <del> return $this->validator->safe(); <add> return is_array($keys) <add> ? $this->validator->safe()->only($keys) <add> : $this->validator->safe(); <ide> } <ide> <ide> /** <ide><path>src/Illuminate/Validation/Validator.php <ide> public function validateWithBag(string $errorBag) <ide> /** <ide> * Get a validated input container for the validated input. <ide> * <del> * @return \Illuminate\Support\ValidatedInput <add> * @param array|null $keys <add> * @return \Illuminate\Support\ValidatedInput|array <ide> */ <del> public function safe() <add> public function safe(array $keys = null) <ide> { <del> return new ValidatedInput($this->validated()); <add> return is_array($keys) <add> ? (new ValidatedInput($this->validated()))->only($keys) <add> : new ValidatedInput($this->validated()); <ide> } <ide> <ide> /**
2
Ruby
Ruby
remove superfluous tests directive
888a2927b65889465ce7a1a71e87d37640a2b41b
<ide><path>actionpack/test/template/prototype_helper_test.rb <ide> class Author::Nested < Author; end <ide> <ide> <ide> class PrototypeHelperBaseTest < ActionView::TestCase <del> tests ActionView::Helpers::PrototypeHelper <del> <ide> attr_accessor :template_format <ide> <ide> def setup
1
Text
Text
change "monsterstats" element to "#monsterstats"
374b69ab23b0e502bbef124244f0116b21d81d70
<ide><path>curriculum/challenges/english/15-javascript-algorithms-and-data-structures-22/learn-basic-javascript-by-building-a-role-playing-game/62a23d1c5f1c93161f3582ae.md <ide> Similar to your `#stats` element, your `#monsterStats` element needs two `span` <ide> <ide> # --hints-- <ide> <del>Your `monsterStats` element should have two `span` elements. <add>Your `#monsterStats` element should have two `span` elements. <ide> <ide> ```js <ide> const spans = document.querySelectorAll(`#monsterStats > span`);
1
Mixed
Text
remove em dashes
b6cd2155c3442a8c56aa6f6ffa0dc9b6a308a7b1
<ide><path>CHANGELOG.md <ide> <ide> Select a Node.js version below to view the changelog history: <ide> <del>* [Node.js 13](doc/changelogs/CHANGELOG_V13.md) - **Current** <del>* [Node.js 12](doc/changelogs/CHANGELOG_V12.md) - **Long Term Support** <del>* [Node.js 11](doc/changelogs/CHANGELOG_V11.md) - End-of-Life <del>* [Node.js 10](doc/changelogs/CHANGELOG_V10.md) — Long Term Support <del>* [Node.js 9](doc/changelogs/CHANGELOG_V9.md) — End-of-Life <del>* [Node.js 8](doc/changelogs/CHANGELOG_V8.md) — End-of-Life <del>* [Node.js 7](doc/changelogs/CHANGELOG_V7.md) — End-of-Life <del>* [Node.js 6](doc/changelogs/CHANGELOG_V6.md) — End-of-Life <del>* [Node.js 5](doc/changelogs/CHANGELOG_V5.md) — End-of-Life <del>* [Node.js 4](doc/changelogs/CHANGELOG_V4.md) — End-of-Life <del>* [io.js](doc/changelogs/CHANGELOG_IOJS.md) — End-of-Life <del>* [Node.js 0.12](doc/changelogs/CHANGELOG_V012.md) — End-of-Life <del>* [Node.js 0.10](doc/changelogs/CHANGELOG_V010.md) — End-of-Life <add>* [Node.js 13](doc/changelogs/CHANGELOG_V13.md) **Current** <add>* [Node.js 12](doc/changelogs/CHANGELOG_V12.md) **Long Term Support** <add>* [Node.js 11](doc/changelogs/CHANGELOG_V11.md) End-of-Life <add>* [Node.js 10](doc/changelogs/CHANGELOG_V10.md) Long Term Support <add>* [Node.js 9](doc/changelogs/CHANGELOG_V9.md) End-of-Life <add>* [Node.js 8](doc/changelogs/CHANGELOG_V8.md) End-of-Life <add>* [Node.js 7](doc/changelogs/CHANGELOG_V7.md) End-of-Life <add>* [Node.js 6](doc/changelogs/CHANGELOG_V6.md) End-of-Life <add>* [Node.js 5](doc/changelogs/CHANGELOG_V5.md) End-of-Life <add>* [Node.js 4](doc/changelogs/CHANGELOG_V4.md) End-of-Life <add>* [io.js](doc/changelogs/CHANGELOG_IOJS.md) End-of-Life <add>* [Node.js 0.12](doc/changelogs/CHANGELOG_V012.md) End-of-Life <add>* [Node.js 0.10](doc/changelogs/CHANGELOG_V010.md) End-of-Life <ide> * [Archive](doc/changelogs/CHANGELOG_ARCHIVE.md) <ide> <ide> Please use the following table to find the changelog for a specific Node.js <ide><path>doc/api/addons.md <ide> require('./build/Release/addon'); <ide> Once the source code has been written, it must be compiled into the binary <ide> `addon.node` file. To do so, create a file called `binding.gyp` in the <ide> top-level of the project describing the build configuration of the module <del>using a JSON-like format. This file is used by [node-gyp][] — a tool written <add>using a JSON-like format. This file is used by [node-gyp][], a tool written <ide> specifically to compile Node.js Addons. <ide> <ide> ```json <ide><path>doc/api/errors.md <ide> program. For a comprehensive list, see the [`errno`(3) man page][]. <ide> `ulimit -n 2048` in the same shell that will run the Node.js process. <ide> <ide> * `ENOENT` (No such file or directory): Commonly raised by [`fs`][] operations <del> to indicate that a component of the specified pathname does not exist — no <add> to indicate that a component of the specified pathname does not exist. No <ide> entity (file or directory) could be found by the given path. <ide> <ide> * `ENOTDIR` (Not a directory): A component of the given pathname existed, but <ide> was not a directory as expected. Commonly raised by [`fs.readdir`][]. <ide> <ide> * `ENOTEMPTY` (Directory not empty): A directory with entries was the target <del> of an operation that requires an empty directory — usually [`fs.unlink`][]. <add> of an operation that requires an empty directory, usually [`fs.unlink`][]. <ide> <ide> * `ENOTFOUND` (DNS lookup failed): Indicates a DNS failure of either <ide> `EAI_NODATA` or `EAI_NONAME`. This is not a standard POSIX error. <ide> program. For a comprehensive list, see the [`errno`(3) man page][]. <ide> <ide> * `ETIMEDOUT` (Operation timed out): A connect or send request failed because <ide> the connected party did not properly respond after a period of time. Usually <del> encountered by [`http`][] or [`net`][] — often a sign that a `socket.end()` <add> encountered by [`http`][] or [`net`][]. Often a sign that a `socket.end()` <ide> was not properly called. <ide> <ide> ## Class: `TypeError` <ide><path>doc/api/http.md <ide> To use the HTTP server and client one must `require('http')`. <ide> The HTTP interfaces in Node.js are designed to support many features <ide> of the protocol which have been traditionally difficult to use. <ide> In particular, large, possibly chunk-encoded, messages. The interface is <del>careful to never buffer entire requests or responses — the <add>careful to never buffer entire requests or responses, so the <ide> user is able to stream data. <ide> <ide> HTTP message headers are represented by an object like this: <ide> added: v0.1.29 <ide> <ide> Sends a chunk of the body. By calling this method <ide> many times, a request body can be sent to a <del>server — in that case it is suggested to use the <add>server. In that case, it is suggested to use the <ide> `['Transfer-Encoding', 'chunked']` header line when <ide> creating the request. <ide> <ide> added: v0.1.17 <ide> <ide> * Extends: {Stream} <ide> <del>This object is created internally by an HTTP server — not by the user. It is <add>This object is created internally by an HTTP server, not by the user. It is <ide> passed as the second parameter to the [`'request'`][] event. <ide> <ide> ### Event: `'close'` <ide><path>doc/api/http2.md <ide> added: v8.4.0 <ide> <ide> * Extends: {Stream} <ide> <del>This object is created internally by an HTTP server — not by the user. It is <add>This object is created internally by an HTTP server, not by the user. It is <ide> passed as the second parameter to the [`'request'`][] event. <ide> <ide> #### Event: `'close'` <ide><path>doc/api/modules.md <ide> added: v0.3.7 <ide> * {Object} <ide> <ide> Provides general utility methods when interacting with instances of <del>`Module` — the `module` variable often seen in file modules. Accessed <add>`Module`, the `module` variable often seen in file modules. Accessed <ide> via `require('module')`. <ide> <ide> ### `module.builtinModules` <ide><path>doc/api/net.md <ide> added: v0.1.90 <ide> * Returns: {boolean} <ide> <ide> Sends data on the socket. The second parameter specifies the encoding in the <del>case of a string — it defaults to UTF8 encoding. <add>case of a string. It defaults to UTF8 encoding. <ide> <ide> Returns `true` if the entire data was flushed successfully to the kernel <ide> buffer. Returns `false` if all or part of the data was queued in user memory. <ide><path>doc/api/path.md <ide> path.parse('/home/user/dir/file.txt'); <ide> │ root │ │ name │ ext │ <ide> " / home/user/dir / file .txt " <ide> └──────┴──────────────┴──────┴─────┘ <del>(all spaces in the "" line should be ignored — they are purely for formatting) <add>(All spaces in the "" line should be ignored. They are purely for formatting.) <ide> ``` <ide> <ide> On Windows: <ide> path.parse('C:\\path\\dir\\file.txt'); <ide> │ root │ │ name │ ext │ <ide> " C:\ path\dir \ file .txt " <ide> └──────┴──────────────┴──────┴─────┘ <del>(all spaces in the "" line should be ignored — they are purely for formatting) <add>(All spaces in the "" line should be ignored. They are purely for formatting.) <ide> ``` <ide> <ide> A [`TypeError`][] is thrown if `path` is not a string. <ide><path>doc/api/process.md <ide> rejection handler. <ide> <ide> There is no notion of a top level for a `Promise` chain at which rejections can <ide> always be handled. Being inherently asynchronous in nature, a `Promise` <del>rejection can be handled at a future point in time — possibly much later than <add>rejection can be handled at a future point in time, possibly much later than <ide> the event loop turn it takes for the `'unhandledRejection'` event to be emitted. <ide> <ide> Another way of stating this is that, unlike in synchronous code where there is <ide><path>doc/api/url.md <ide> WHATWG URL's `origin` property includes `protocol` and `host`, but not <ide> ├─────────────┴─────────────────────┴────────────────────────┴──────────┴────────────────┴───────┤ <ide> │ href │ <ide> └────────────────────────────────────────────────────────────────────────────────────────────────┘ <del>(all spaces in the "" line should be ignored — they are purely for formatting) <add>(All spaces in the "" line should be ignored. They are purely for formatting.) <ide> ``` <ide> <ide> Parsing the URL string using the WHATWG API: <ide><path>doc/guides/backporting-to-release-lines.md <ide> replace that with the staging branch for the targeted release line. <ide> 9. Open a pull request: <ide> 1. Be sure to target the `v10.x-staging` branch in the pull request. <ide> 1. Include the backport target in the pull request title in the following <del> format — `[v10.x backport] <commit title>`. <add> format: `[v10.x backport] <commit title>`. <ide> Example: `[v10.x backport] process: improve performance of nextTick` <ide> 1. Check the checkbox labeled "Allow edits from maintainers". <ide> 1. In the description add a reference to the original PR. <ide><path>doc/guides/contributing/issues.md <ide> around it. Some contributors may have differing opinions about the issue, <ide> including whether the behavior being seen is a bug or a feature. This discussion <ide> is part of the process and should be kept focused, helpful, and professional. <ide> <del>Short, clipped responses—that provide neither additional context nor supporting <del>detail—are not helpful or professional. To many, such responses are simply <add>Short, clipped responses that provide neither additional context nor supporting <add>detail are not helpful or professional. To many, such responses are simply <ide> annoying and unfriendly. <ide> <ide> Contributors are encouraged to help one another make forward progress as much <ide><path>doc/guides/doc-style-guide.md <ide> * Outside of the wrapping element if the wrapping element contains only a <ide> fragment of a clause. <ide> * Documents must start with a level-one heading. <del>* Prefer affixing links to inlining links — prefer `[a link][]` to <del> `[a link](http://example.com)`. <add>* Prefer affixing links (`[a link][]`) to inlining links <add> (`[a link](http://example.com)`). <ide> * When documenting APIs, update the YAML comment associated with the API as <ide> appropriate. This is especially true when introducing or deprecating an API. <del>* Use [Em dashes][] ("—" or `Option+Shift+"-"` on macOS) surrounded by spaces, <del> as per [The New York Times Manual of Style and Usage][]. <ide> * For code blocks: <ide> * Use language aware fences. ("```js") <ide> * Code need not be complete. Treat code blocks as an illustration or aid to <ide> <ide> See also API documentation structure overview in [doctools README][]. <ide> <del>[Em dashes]: https://en.wikipedia.org/wiki/Dash#Em_dash <ide> [Javascript type]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Data_structures_and_types <ide> [serial commas]: https://en.wikipedia.org/wiki/Serial_comma <del>[The New York Times Manual of Style and Usage]: https://en.wikipedia.org/wiki/The_New_York_Times_Manual_of_Style_and_Usage <ide> [plugin]: https://editorconfig.org/#download <ide> [doctools README]: ../tools/doc/README.md <ide><path>doc/guides/maintaining-icu.md <ide> following the steps above in the prior section of this document ought to be <ide> repeatable without concern for overriding a patch. <ide> <ide> 2. **Verifiability.** Given the number of files modified in an ICU PR, <del>a floating patch could easily be missed — or dropped altogether next time <add>a floating patch could easily be missed or dropped altogether next time <ide> something is landed. <ide> <ide> 3. **Compatibility.** There are a number of ways that ICU can be loaded into <ide><path>tools/doc/versions.js <ide> module.exports = { <ide> } <ide> } <ide> const ltsRE = /Long Term Support/i; <del> const versionRE = /\* \[Node\.js ([0-9.]+)\][^-—]+[-—]\s*(.*)\r?\n/g; <add> const versionRE = /\* \[Node\.js ([0-9.]+)\]\S+ (.*)\r?\n/g; <ide> _versions = []; <ide> let match; <ide> while ((match = versionRE.exec(changelog)) != null) {
15
Ruby
Ruby
update license checks to new style
e215b3df75bbc355e0e1872258055ab270db4844
<ide><path>Library/Homebrew/dev-cmd/audit.rb <ide> def audit <ide> # Check style in a single batch run up front for performance <ide> style_results = Style.check_style_json(style_files, options) if style_files <ide> # load licenses <del> spdx_data = SPDX.spdx_data <add> spdx_license_data = SPDX.license_data <add> spdx_exception_data = SPDX.exception_data <ide> new_formula_problem_lines = [] <ide> audit_formulae.sort.each do |f| <ide> only = only_cops ? ["style"] : args.only <ide> options = { <del> new_formula: new_formula, <del> strict: strict, <del> online: online, <del> git: git, <del> only: only, <del> except: args.except, <del> spdx_data: spdx_data, <add> new_formula: new_formula, <add> strict: strict, <add> online: online, <add> git: git, <add> only: only, <add> except: args.except, <add> spdx_license_data: spdx_license_data, <add> spdx_exception_data: spdx_exception_data, <ide> } <ide> options[:style_offenses] = style_results.file_offenses(f.path) if style_results <ide> options[:display_cop_names] = args.display_cop_names? <ide> def initialize(formula, options = {}) <ide> @new_formula_problems = [] <ide> @text = FormulaText.new(formula.path) <ide> @specs = %w[stable devel head].map { |s| formula.send(s) }.compact <del> @spdx_data = options[:spdx_data] <add> @spdx_license_data = options[:spdx_license_data] <add> @spdx_exception_data = options[:spdx_exception_data] <ide> end <ide> <ide> def audit_style <ide> def audit_formula_name <ide> <ide> def audit_license <ide> if formula.license.present? <del> non_standard_licenses = formula.license.map do |license| <del> next if license == :public_domain <del> next if @spdx_data["licenses"].any? { |spdx| spdx["licenseId"] == license } <del> <del> license <del> end.compact <add> licenses, exceptions = SPDX.parse_license_expression formula.license <ide> <add> non_standard_licenses = licenses.reject { |license| SPDX.valid_license? license } <ide> if non_standard_licenses.present? <del> problem "Formula #{formula.name} contains non-standard SPDX licenses: #{non_standard_licenses}." <add> problem <<~EOS <add> Formula #{formula.name} contains non-standard SPDX licenses: #{non_standard_licenses}. <add> For a list of valid licenses check: #{Formatter.url("https://spdx.org/licenses/")} <add> EOS <ide> end <ide> <ide> if @strict <del> deprecated_licenses = formula.license.map do |license| <del> next if license == :public_domain <del> next if @spdx_data["licenses"].any? do |spdx| <del> spdx["licenseId"] == license && !spdx["isDeprecatedLicenseId"] <del> end <del> <del> license <del> end.compact <del> <add> deprecated_licenses = licenses.select do |license| <add> SPDX.deprecated_license? license <add> end <ide> if deprecated_licenses.present? <del> problem "Formula #{formula.name} contains deprecated SPDX licenses: #{deprecated_licenses}." <add> problem <<~EOS <add> Formula #{formula.name} contains deprecated SPDX licenses: #{deprecated_licenses}. <add> You may need to add `-only` or `-or-later` for GNU licenses (e.g. `GPL`, `LGPL`, `AGPL`, `GFDL`). <add> For a list of valid licenses check: #{Formatter.url("https://spdx.org/licenses/")} <add> EOS <ide> end <ide> end <ide> <add> invalid_exceptions = exceptions.reject { |exception| SPDX.valid_license_exception? exception } <add> if invalid_exceptions.present? <add> problem <<~EOS <add> Formula #{formula.name} contains invalid or deprecated SPDX license exceptions: #{invalid_exceptions}. <add> For a list of valid license exceptions check: <add> #{Formatter.url("https://spdx.org/licenses/exceptions-index.html/")} <add> EOS <add> end <add> <ide> return unless @online <ide> <ide> user, repo = get_repo_data(%r{https?://github\.com/([^/]+)/([^/]+)/?.*}) <ide> return if user.blank? <ide> <ide> github_license = GitHub.get_repo_license(user, repo) <del> return if github_license && (formula.license + ["NOASSERTION"]).include?(github_license) <del> return if PERMITTED_LICENSE_MISMATCHES[github_license]&.any? { |license| formula.license.include? license } <add> return if github_license && (licenses + ["NOASSERTION"]).include?(github_license) <add> return if PERMITTED_LICENSE_MISMATCHES[github_license]&.any? { |license| licenses.include? license } <ide> return if PERMITTED_FORMULA_LICENSE_MISMATCHES[formula.name] == formula.version <ide> <del> problem "Formula license #{formula.license} does not match GitHub license #{Array(github_license)}." <add> problem "Formula license #{licenses} does not match GitHub license #{Array(github_license)}." <ide> <ide> elsif @new_formula && @core_tap <ide> problem "Formulae in homebrew/core must specify a license." <ide><path>Library/Homebrew/test/dev-cmd/audit_spec.rb <ide> require "dev-cmd/audit" <ide> require "formulary" <ide> require "cmd/shared_examples/args_parse" <add>require "utils/spdx" <ide> <ide> describe "Homebrew.audit_args" do <ide> it_behaves_like "parseable arguments" <ide> class Foo < Formula <ide> end <ide> <ide> describe "#audit_license" do <del> let(:spdx_data) { <del> JSON.parse Pathname(File.join(File.dirname(__FILE__), "../../data/spdx.json")).read <del> } <add> let(:spdx_license_data) { SPDX.license_data } <add> let(:spdx_exception_data) { SPDX.exception_data } <ide> <del> let(:custom_spdx_id) { "zzz" } <ide> let(:deprecated_spdx_id) { "GPL-1.0" } <del> let(:standard_mismatch_spdx_id) { "0BSD" } <del> let(:license_array) { ["0BSD", "GPL-3.0"] } <del> let(:license_array_mismatch) { ["0BSD", "MIT"] } <del> let(:license_array_nonstandard) { ["0BSD", "zzz", "MIT"] } <del> let(:license_array_deprecated) { ["0BSD", "GPL-1.0", "MIT"] } <add> let(:license_all_custom_id) { 'all_of: ["MIT", "zzz"]' } <add> let(:deprecated_spdx_exception) { "Nokia-Qt-exception-1.1" } <add> let(:license_any) { 'any_of: ["0BSD", "GPL-3.0-only"]' } <add> let(:license_any_with_plus) { 'any_of: ["0BSD+", "GPL-3.0-only"]' } <add> let(:license_nested_conditions) { 'any_of: ["0BSD", { all_of: ["GPL-3.0-only", "MIT"] }]' } <add> let(:license_any_mismatch) { 'any_of: ["0BSD", "MIT"]' } <add> let(:license_any_nonstandard) { 'any_of: ["0BSD", "zzz", "MIT"]' } <add> let(:license_any_deprecated) { 'any_of: ["0BSD", "GPL-1.0", "MIT"]' } <ide> <ide> it "does not check if the formula is not a new formula" do <del> fa = formula_auditor "foo", <<~RUBY, spdx_data: spdx_data, new_formula: false <add> fa = formula_auditor "foo", <<~RUBY, new_formula: false <ide> class Foo < Formula <ide> url "https://brew.sh/foo-1.0.tgz" <ide> end <ide> class Foo < Formula <ide> end <ide> <ide> it "detects no license info" do <del> fa = formula_auditor "foo", <<~RUBY, spdx_data: spdx_data, new_formula: true, core_tap: true <add> fa = formula_auditor "foo", <<~RUBY, spdx_license_data: spdx_license_data, new_formula: true, core_tap: true <ide> class Foo < Formula <ide> url "https://brew.sh/foo-1.0.tgz" <ide> end <ide> class Foo < Formula <ide> end <ide> <ide> it "detects if license is not a standard spdx-id" do <del> fa = formula_auditor "foo", <<~RUBY, spdx_data: spdx_data, new_formula: true <add> fa = formula_auditor "foo", <<~RUBY, spdx_license_data: spdx_license_data, new_formula: true <ide> class Foo < Formula <ide> url "https://brew.sh/foo-1.0.tgz" <del> license "#{custom_spdx_id}" <add> license "zzz" <ide> end <ide> RUBY <ide> <ide> fa.audit_license <del> expect(fa.problems.first).to match "Formula foo contains non-standard SPDX licenses: [\"zzz\"]." <add> expect(fa.problems.first).to match <<~EOS <add> Formula foo contains non-standard SPDX licenses: ["zzz"]. <add> For a list of valid licenses check: https://spdx.org/licenses/ <add> EOS <ide> end <ide> <ide> it "detects if license is a deprecated spdx-id" do <del> fa = formula_auditor "foo", <<~RUBY, spdx_data: spdx_data, new_formula: true, strict: true <add> fa = formula_auditor "foo", <<~RUBY, spdx_license_data: spdx_license_data, new_formula: true, strict: true <ide> class Foo < Formula <ide> url "https://brew.sh/foo-1.0.tgz" <ide> license "#{deprecated_spdx_id}" <ide> end <ide> RUBY <ide> <ide> fa.audit_license <del> expect(fa.problems.first).to match "Formula foo contains deprecated SPDX licenses: [\"GPL-1.0\"]." <add> expect(fa.problems.first).to match <<~EOS <add> Formula foo contains deprecated SPDX licenses: ["GPL-1.0"]. <add> You may need to add `-only` or `-or-later` for GNU licenses (e.g. `GPL`, `LGPL`, `AGPL`, `GFDL`). <add> For a list of valid licenses check: https://spdx.org/licenses/ <add> EOS <add> end <add> <add> it "detects if license with AND contains a non-standard spdx-id" do <add> fa = formula_auditor "foo", <<~RUBY, spdx_license_data: spdx_license_data, new_formula: true <add> class Foo < Formula <add> url "https://brew.sh/foo-1.0.tgz" <add> license #{license_all_custom_id} <add> end <add> RUBY <add> <add> fa.audit_license <add> expect(fa.problems.first).to match <<~EOS <add> Formula foo contains non-standard SPDX licenses: ["zzz"]. <add> For a list of valid licenses check: https://spdx.org/licenses/ <add> EOS <ide> end <ide> <ide> it "detects if license array contains a non-standard spdx-id" do <del> fa = formula_auditor "foo", <<~RUBY, spdx_data: spdx_data, new_formula: true <add> fa = formula_auditor "foo", <<~RUBY, spdx_license_data: spdx_license_data, new_formula: true <ide> class Foo < Formula <ide> url "https://brew.sh/foo-1.0.tgz" <del> license #{license_array_nonstandard} <add> license #{license_any_nonstandard} <ide> end <ide> RUBY <ide> <ide> fa.audit_license <del> expect(fa.problems.first).to match "Formula foo contains non-standard SPDX licenses: [\"zzz\"]." <add> expect(fa.problems.first).to match <<~EOS <add> Formula foo contains non-standard SPDX licenses: ["zzz"]. <add> For a list of valid licenses check: https://spdx.org/licenses/ <add> EOS <ide> end <ide> <ide> it "detects if license array contains a deprecated spdx-id" do <del> fa = formula_auditor "foo", <<~RUBY, spdx_data: spdx_data, new_formula: true, strict: true <add> fa = formula_auditor "foo", <<~RUBY, spdx_license_data: spdx_license_data, new_formula: true, strict: true <ide> class Foo < Formula <ide> url "https://brew.sh/foo-1.0.tgz" <del> license #{license_array_deprecated} <add> license #{license_any_deprecated} <ide> end <ide> RUBY <ide> <ide> fa.audit_license <del> expect(fa.problems.first).to match "Formula foo contains deprecated SPDX licenses: [\"GPL-1.0\"]." <add> expect(fa.problems.first).to match <<~EOS <add> Formula foo contains deprecated SPDX licenses: ["GPL-1.0"]. <add> You may need to add `-only` or `-or-later` for GNU licenses (e.g. `GPL`, `LGPL`, `AGPL`, `GFDL`). <add> For a list of valid licenses check: https://spdx.org/licenses/ <add> EOS <ide> end <ide> <ide> it "verifies that a license info is a standard spdx id" do <del> fa = formula_auditor "foo", <<~RUBY, spdx_data: spdx_data, new_formula: true <add> fa = formula_auditor "foo", <<~RUBY, spdx_license_data: spdx_license_data, new_formula: true <ide> class Foo < Formula <ide> url "https://brew.sh/foo-1.0.tgz" <ide> license "0BSD" <ide> class Foo < Formula <ide> expect(fa.problems).to be_empty <ide> end <ide> <add> it "verifies that a license info with plus is a standard spdx id" do <add> fa = formula_auditor "foo", <<~RUBY, spdx_license_data: spdx_license_data, new_formula: true <add> class Foo < Formula <add> url "https://brew.sh/foo-1.0.tgz" <add> license "0BSD+" <add> end <add> RUBY <add> <add> fa.audit_license <add> expect(fa.problems).to be_empty <add> end <add> <add> it "allows :public_domain license" do <add> fa = formula_auditor "foo", <<~RUBY, spdx_license_data: spdx_license_data, new_formula: true <add> class Foo < Formula <add> url "https://brew.sh/foo-1.0.tgz" <add> license :public_domain <add> end <add> RUBY <add> <add> fa.audit_license <add> expect(fa.problems).to be_empty <add> end <add> <add> it "verifies that a license info with multiple licenses are standard spdx ids" do <add> fa = formula_auditor "foo", <<~RUBY, spdx_license_data: spdx_license_data, new_formula: true <add> class Foo < Formula <add> url "https://brew.sh/foo-1.0.tgz" <add> license any_of: ["0BSD", "MIT"] <add> end <add> RUBY <add> <add> fa.audit_license <add> expect(fa.problems).to be_empty <add> end <add> <add> it "verifies that a license info with exceptions are standard spdx ids" do <add> formula_text = <<~RUBY <add> class Foo < Formula <add> url "https://brew.sh/foo-1.0.tgz" <add> license "Apache-2.0" => { with: "LLVM-exception" } <add> end <add> RUBY <add> fa = formula_auditor "foo", formula_text, new_formula: true, <add> spdx_license_data: spdx_license_data, spdx_exception_data: spdx_exception_data <add> <add> fa.audit_license <add> expect(fa.problems).to be_empty <add> end <add> <ide> it "verifies that a license array contains only standard spdx id" do <del> fa = formula_auditor "foo", <<~RUBY, spdx_data: spdx_data, new_formula: true <add> fa = formula_auditor "foo", <<~RUBY, spdx_license_data: spdx_license_data, new_formula: true <add> class Foo < Formula <add> url "https://brew.sh/foo-1.0.tgz" <add> license #{license_any} <add> end <add> RUBY <add> <add> fa.audit_license <add> expect(fa.problems).to be_empty <add> end <add> <add> it "verifies that a license array contains only standard spdx id with plus" do <add> fa = formula_auditor "foo", <<~RUBY, spdx_license_data: spdx_license_data, new_formula: true <ide> class Foo < Formula <ide> url "https://brew.sh/foo-1.0.tgz" <del> license #{license_array} <add> license #{license_any_with_plus} <add> end <add> RUBY <add> <add> fa.audit_license <add> expect(fa.problems).to be_empty <add> end <add> <add> it "verifies that a license array with AND contains only standard spdx ids" do <add> fa = formula_auditor "foo", <<~RUBY, spdx_license_data: spdx_license_data, new_formula: true <add> class Foo < Formula <add> url "https://brew.sh/foo-1.0.tgz" <add> license #{license_nested_conditions} <ide> end <ide> RUBY <ide> <ide> class Foo < Formula <ide> <ide> it "checks online and verifies that a standard license id is the same "\ <ide> "as what is indicated on its Github repo" do <del> fa = formula_auditor "cask", <<~RUBY, spdx_data: spdx_data, online: true, core_tap: true, new_formula: true <add> formula_text = <<~RUBY <ide> class Cask < Formula <ide> url "https://github.com/cask/cask/archive/v0.8.4.tar.gz" <ide> head "https://github.com/cask/cask.git" <ide> license "GPL-3.0" <ide> end <ide> RUBY <add> fa = formula_auditor "cask", formula_text, spdx_license_data: spdx_license_data, <add> online: true, core_tap: true, new_formula: true <add> <add> fa.audit_license <add> expect(fa.problems).to be_empty <add> end <add> <add> it "checks online and verifies that a standard license id with AND is the same "\ <add> "as what is indicated on its Github repo" do <add> formula_text = <<~RUBY <add> class Cask < Formula <add> url "https://github.com/cask/cask/archive/v0.8.4.tar.gz" <add> head "https://github.com/cask/cask.git" <add> license all_of: ["GPL-3.0-or-later", "MIT"] <add> end <add> RUBY <add> fa = formula_auditor "cask", formula_text, spdx_license_data: spdx_license_data, <add> online: true, core_tap: true, new_formula: true <add> <add> fa.audit_license <add> expect(fa.problems).to be_empty <add> end <add> <add> it "checks online and verifies that a standard license id with WITH is the same "\ <add> "as what is indicated on its Github repo" do <add> formula_text = <<~RUBY <add> class Cask < Formula <add> url "https://github.com/cask/cask/archive/v0.8.4.tar.gz" <add> head "https://github.com/cask/cask.git" <add> license "GPL-3.0-or-later" => { with: "LLVM-exception" } <add> end <add> RUBY <add> fa = formula_auditor "cask", formula_text, online: true, core_tap: true, new_formula: true, <add> spdx_license_data: spdx_license_data, spdx_exception_data: spdx_exception_data <ide> <ide> fa.audit_license <ide> expect(fa.problems).to be_empty <ide> end <ide> <add> it "verifies that a license exception has standard spdx ids" do <add> formula_text = <<~RUBY <add> class Cask < Formula <add> url "https://github.com/cask/cask/archive/v0.8.4.tar.gz" <add> head "https://github.com/cask/cask.git" <add> license "GPL-3.0-or-later" => { with: "zzz" } <add> end <add> RUBY <add> fa = formula_auditor "cask", formula_text, core_tap: true, new_formula: true, <add> spdx_license_data: spdx_license_data, spdx_exception_data: spdx_exception_data <add> <add> fa.audit_license <add> expect(fa.problems.first).to match <<~EOS <add> Formula cask contains invalid or deprecated SPDX license exceptions: ["zzz"]. <add> For a list of valid license exceptions check: <add> https://spdx.org/licenses/exceptions-index.html/ <add> EOS <add> end <add> <add> it "verifies that a license exception has non-deprecated spdx ids" do <add> formula_text = <<~RUBY <add> class Cask < Formula <add> url "https://github.com/cask/cask/archive/v0.8.4.tar.gz" <add> head "https://github.com/cask/cask.git" <add> license "GPL-3.0-or-later" => { with: "#{deprecated_spdx_exception}" } <add> end <add> RUBY <add> fa = formula_auditor "cask", formula_text, core_tap: true, new_formula: true, <add> spdx_license_data: spdx_license_data, spdx_exception_data: spdx_exception_data <add> <add> fa.audit_license <add> expect(fa.problems.first).to match <<~EOS <add> Formula cask contains invalid or deprecated SPDX license exceptions: ["#{deprecated_spdx_exception}"]. <add> For a list of valid license exceptions check: <add> https://spdx.org/licenses/exceptions-index.html/ <add> EOS <add> end <add> <ide> it "checks online and verifies that a standard license id is in the same exempted license group" \ <ide> "as what is indicated on its GitHub repo" do <del> fa = formula_auditor "cask", <<~RUBY, spdx_data: spdx_data, online: true, new_formula: true <add> fa = formula_auditor "cask", <<~RUBY, spdx_license_data: spdx_license_data, online: true, new_formula: true <ide> class Cask < Formula <ide> url "https://github.com/cask/cask/archive/v0.8.4.tar.gz" <ide> head "https://github.com/cask/cask.git" <ide> class Cask < Formula <ide> <ide> it "checks online and verifies that a standard license array is in the same exempted license group" \ <ide> "as what is indicated on its GitHub repo" do <del> fa = formula_auditor "cask", <<~RUBY, spdx_data: spdx_data, online: true, new_formula: true <add> fa = formula_auditor "cask", <<~RUBY, spdx_license_data: spdx_license_data, online: true, new_formula: true <ide> class Cask < Formula <ide> url "https://github.com/cask/cask/archive/v0.8.4.tar.gz" <ide> head "https://github.com/cask/cask.git" <del> license ["GPL-3.0-or-later", "MIT"] <add> license any_of: ["GPL-3.0-or-later", "MIT"] <ide> end <ide> RUBY <ide> <ide> class Cask < Formula <ide> <ide> it "checks online and detects that a formula-specified license is not "\ <ide> "the same as what is indicated on its Github repository" do <del> fa = formula_auditor "cask", <<~RUBY, online: true, spdx_data: spdx_data, core_tap: true, new_formula: true <add> formula_text = <<~RUBY <ide> class Cask < Formula <ide> url "https://github.com/cask/cask/archive/v0.8.4.tar.gz" <ide> head "https://github.com/cask/cask.git" <del> license "#{standard_mismatch_spdx_id}" <add> license "0BSD" <ide> end <ide> RUBY <add> fa = formula_auditor "cask", formula_text, spdx_license_data: spdx_license_data, <add> online: true, core_tap: true, new_formula: true <ide> <ide> fa.audit_license <del> expect(fa.problems.first).to match "Formula license #{Array(standard_mismatch_spdx_id)} "\ <del> "does not match GitHub license [\"GPL-3.0\"]." <add> expect(fa.problems.first).to match "Formula license [\"0BSD\"] does not match GitHub license [\"GPL-3.0\"]." <ide> end <ide> <ide> it "checks online and detects that an array of license does not contain "\ <ide> "what is indicated on its Github repository" do <del> fa = formula_auditor "cask", <<~RUBY, online: true, spdx_data: spdx_data, core_tap: true, new_formula: true <add> formula_text = <<~RUBY <ide> class Cask < Formula <ide> url "https://github.com/cask/cask/archive/v0.8.4.tar.gz" <ide> head "https://github.com/cask/cask.git" <del> license #{license_array_mismatch} <add> license #{license_any_mismatch} <ide> end <ide> RUBY <add> fa = formula_auditor "cask", formula_text, spdx_license_data: spdx_license_data, <add> online: true, core_tap: true, new_formula: true <ide> <ide> fa.audit_license <del> expect(fa.problems.first).to match "Formula license #{license_array_mismatch} "\ <add> expect(fa.problems.first).to match "Formula license [\"0BSD\", \"MIT\"] "\ <ide> "does not match GitHub license [\"GPL-3.0\"]." <ide> end <ide> <ide> it "checks online and verifies that an array of license contains "\ <ide> "what is indicated on its Github repository" do <del> fa = formula_auditor "cask", <<~RUBY, online: true, spdx_data: spdx_data, core_tap: true, new_formula: true <add> formula_text = <<~RUBY <ide> class Cask < Formula <ide> url "https://github.com/cask/cask/archive/v0.8.4.tar.gz" <ide> head "https://github.com/cask/cask.git" <del> license #{license_array} <add> license #{license_any} <ide> end <ide> RUBY <add> fa = formula_auditor "cask", formula_text, spdx_license_data: spdx_license_data, <add> online: true, core_tap: true, new_formula: true <ide> <ide> fa.audit_license <ide> expect(fa.problems).to be_empty
2
Go
Go
remove unused function in server_unit_test.go
641a7ec9ad61a42b255d203b7791198431761104
<ide><path>api/server/server_unit_test.go <ide> package server <ide> <ide> import ( <del> "bytes" <ide> "encoding/json" <ide> "fmt" <ide> "io" <ide> import ( <ide> "testing" <ide> <ide> "github.com/docker/docker/api" <del> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/engine" <ide> "github.com/docker/docker/pkg/version" <ide> ) <ide> func readEnv(src io.Reader, t *testing.T) *engine.Env { <ide> return v <ide> } <ide> <del>func toJson(data interface{}, t *testing.T) io.Reader { <del> var buf bytes.Buffer <del> if err := json.NewEncoder(&buf).Encode(data); err != nil { <del> t.Fatal(err) <del> } <del> return &buf <del>} <del> <ide> func assertContentType(recorder *httptest.ResponseRecorder, contentType string, t *testing.T) { <ide> if recorder.HeaderMap.Get("Content-Type") != contentType { <ide> t.Fatalf("%#v\n", recorder) <ide> } <ide> } <del> <del>// XXX: Duplicated from integration/utils_test.go, but maybe that's OK as that <del>// should die as soon as we converted all integration tests? <del>// assertHttpNotError expect the given response to not have an error. <del>// Otherwise the it causes the test to fail. <del>func assertHttpNotError(r *httptest.ResponseRecorder, t *testing.T) { <del> // Non-error http status are [200, 400) <del> if r.Code < http.StatusOK || r.Code >= http.StatusBadRequest { <del> t.Fatal(fmt.Errorf("Unexpected http error: %v", r.Code)) <del> } <del>} <del> <del>func createEnvFromGetImagesJSONStruct(data getImagesJSONStruct) types.Image { <del> return types.Image{ <del> RepoTags: data.RepoTags, <del> ID: data.Id, <del> Created: int(data.Created), <del> Size: int(data.Size), <del> VirtualSize: int(data.VirtualSize), <del> } <del>} <del> <del>type getImagesJSONStruct struct { <del> RepoTags []string <del> Id string <del> Created int64 <del> Size int64 <del> VirtualSize int64 <del>} <del> <del>var sampleImage getImagesJSONStruct = getImagesJSONStruct{ <del> RepoTags: []string{"test-name:test-tag"}, <del> Id: "ID", <del> Created: 999, <del> Size: 777, <del> VirtualSize: 666, <del>}
1
Javascript
Javascript
add support to parse `do`
742ba1e308d785eda289c1741587709845bb2291
<ide><path>moment.js <ide> parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z <ide> parseTokenT = /T/i, // T (ISO separator) <ide> parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123 <add> parseTokenOrdinal = /\d{1,2}/, <ide> <ide> //strict parsing regexes <ide> parseTokenOneDigit = /\d/, // 0 - 9 <ide> case 'e': <ide> case 'E': <ide> return parseTokenOneOrTwoDigits; <add> case 'Do': <add> return parseTokenOrdinal; <ide> default : <ide> a = new RegExp(regexpEscape(unescapeFormat(token.replace('\\', '')), "i")); <ide> return a; <ide> datePartArray[DATE] = toInt(input); <ide> } <ide> break; <add> case 'Do' : <add> if (input != null) { <add> datePartArray[DATE] = toInt(parseInt(input, 10)); <add> } <add> break; <ide> // DAY OF YEAR <ide> case 'DDD' : // fall through to DDDD <ide> case 'DDDD' :
1
Mixed
Ruby
keep index names when using with sqlite3
d01f913f8d21230b387c70d13b5646a838ba2915
<ide><path>activerecord/CHANGELOG.md <ide> ## Rails 4.0.0 (unreleased) ## <ide> <add>* Keep index names when using `alter_table` with sqlite3. <add> Fix #3489 <add> <add> *Yves Senn* <add> <ide> * Add ability for postgresql adapter to disable user triggers in disable_referential_integrity. <ide> Fix #5523 <ide> <ide><path>activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb <ide> def copy_table(from, to, options = {}) #:nodoc: <ide> end <ide> yield @definition if block_given? <ide> end <del> <ide> copy_table_indexes(from, to, options[:rename] || {}) <ide> copy_table_contents(from, to, <ide> @definition.columns.map {|column| column.name}, <ide> def copy_table_indexes(from, to, rename = {}) #:nodoc: <ide> <ide> unless columns.empty? <ide> # index name can't be the same <del> opts = { :name => name.gsub(/_(#{from})_/, "_#{to}_") } <add> opts = { name: name.gsub(/(^|_)(#{from})_/, "\\1#{to}_") } <ide> opts[:unique] = true if index.unique <ide> add_index(to, columns, opts) <ide> end <ide><path>activerecord/test/cases/migration/rename_column_test.rb <ide> def test_change_column_with_new_default <ide> refute TestModel.new.administrator? <ide> end <ide> <add> def test_change_column_with_custom_index_name <add> add_column "test_models", "category", :string <add> add_index :test_models, :category, name: 'test_models_categories_idx' <add> <add> assert_equal ['test_models_categories_idx'], connection.indexes('test_models').map(&:name) <add> change_column "test_models", "category", :string, null: false, default: 'article' <add> <add> assert_equal ['test_models_categories_idx'], connection.indexes('test_models').map(&:name) <add> end <add> <ide> def test_change_column_default <ide> add_column "test_models", "first_name", :string <ide> connection.change_column_default "test_models", "first_name", "Tester"
3
Javascript
Javascript
use === in _http_server and _tls_wrap
20fa6e7d07c8c593548330b478c1869adaaf1456
<ide><path>lib/_http_server.js <ide> function connectionListener(socket) { <ide> } <ide> <ide> if (req.headers.expect !== undefined && <del> (req.httpVersionMajor == 1 && req.httpVersionMinor == 1)) { <add> (req.httpVersionMajor === 1 && req.httpVersionMinor === 1)) { <ide> if (continueExpression.test(req.headers.expect)) { <ide> res._expect_continue = true; <ide> <ide><path>lib/_tls_wrap.js <ide> TLSSocket.prototype.renegotiate = function(options, callback) { <ide> }; <ide> <ide> TLSSocket.prototype.setMaxSendFragment = function setMaxSendFragment(size) { <del> return this._handle.setMaxSendFragment(size) == 1; <add> return this._handle.setMaxSendFragment(size) === 1; <ide> }; <ide> <ide> TLSSocket.prototype.getTLSTicket = function getTLSTicket() {
2
Mixed
PHP
fix some typos and links
7027bc6b2138b44e48e5704c857e81f6aaab5ec5
<ide><path>src/Database/README.md <ide> SELECT CONCAT(title, :c0) ...; <ide> <ide> ### Other SQL Clauses <ide> <del>Read of all other SQL clases that the builder is capable of generating in the [official API docs](http://api.cakephp.org/3.0/class-Cake.Database.Query.html) <add>Read of all other SQL clauses that the builder is capable of generating in the [official API docs](http://api.cakephp.org/3.2/class-Cake.Database.Query.html) <ide> <ide> ### Getting Results out of a Query <ide> <ide> $results = $query->execute()->fetchAll('assoc'); <ide> <ide> ## Official API <ide> <del>You can read the official [official API docs](http://api.cakephp.org/3.0/namespace-Cake.Database.html) to learn more of what this library <add>You can read the official [official API docs](http://api.cakephp.org/3.2/namespace-Cake.Database.html) to learn more of what this library <ide> has to offer. <ide><path>src/Datasource/README.md <ide> $conn = ConnectionManager::config('other', $connectionInstance); <ide> <ide> ## Documentation <ide> <del>Please make sure you check the [official API documentation](http://api.cakephp.org/3.0/namespace-Cake.Datasource.html) <add>Please make sure you check the [official API documentation](http://api.cakephp.org/3.2/namespace-Cake.Datasource.html) <ide><path>src/Network/Response.php <ide> public function cookie($options = null) <ide> * cors($request, ['http://www.cakephp.org', '*.google.com', 'https://myproject.github.io']); <ide> * ``` <ide> * <del> * *Note* The `$allowedDomains`, `$allowedMethods`, `$allowedHeaders` parameters are deprectated. <add> * *Note* The `$allowedDomains`, `$allowedMethods`, `$allowedHeaders` parameters are deprecated. <ide> * Instead the builder object should be used. <ide> * <ide> * @param \Cake\Network\Request $request Request object <ide><path>src/ORM/LazyEagerLoader.php <ide> public function loadInto($entities, array $contain, Table $source) <ide> * Builds a query for loading the passed list of entity objects along with the <ide> * associations specified in $contain. <ide> * <del> * @param \Cake\Collection\CollectionInterface $objects The original entitites <add> * @param \Cake\Collection\CollectionInterface $objects The original entities <ide> * @param array $contain The associations to be loaded <ide> * @param \Cake\ORM\Table $source The table to use for fetching the top level entities <ide> * @return \Cake\ORM\Query <ide><path>src/Utility/Hash.php <ide> public static function numeric(array $data) <ide> * Counts the dimensions of an array. <ide> * Only considers the dimension of the first element in the array. <ide> * <del> * If you have an un-even or heterogenous array, consider using Hash::maxDimensions() <add> * If you have an un-even or heterogeneous array, consider using Hash::maxDimensions() <ide> * to get the dimensions of the array. <ide> * <ide> * @param array $data Array to count dimensions on <ide><path>src/Validation/Validator.php <ide> public function notEmpty($field, $message = null, $when = false) <ide> * @param string $field The field you want to apply the rule to. <ide> * @param string $message The error message when the rule fails. <ide> * @param string|callable $when Either 'create' or 'update' or a callable that returns <del> * true when the valdiation rule should be applied. <add> * true when the validation rule should be applied. <ide> * @see \Cake\Validation\Validation::notBlank() <ide> * @return $this <ide> */ <ide> public function notBlank($field, $message = null, $when = null) <ide> * @param string $field The field you want to apply the rule to. <ide> * @param string $message The error message when the rule fails. <ide> * @param string|callable $when Either 'create' or 'update' or a callable that returns <del> * true when the valdiation rule should be applied. <add> * true when the validation rule should be applied. <ide> * @see \Cake\Validation\Validation::alphaNumeric() <ide> * @return $this <ide> */ <ide> public function alphaNumeric($field, $message = null, $when = null) <ide> * @param array $range The inclusive minimum and maximum length you want permitted. <ide> * @param string $message The error message when the rule fails. <ide> * @param string|callable $when Either 'create' or 'update' or a callable that returns <del> * true when the valdiation rule should be applied. <add> * true when the validation rule should be applied. <ide> * @see \Cake\Validation\Validation::alphaNumeric() <ide> * @return $this <ide> */ <ide> public function lengthBetween($field, array $range, $message = null, $when = nul <ide> * You can also supply an array of accepted card types. e.g `['mastercard', 'visa', 'amex']` <ide> * @param string $message The error message when the rule fails. <ide> * @param string|callable $when Either 'create' or 'update' or a callable that returns <del> * true when the valdiation rule should be applied. <add> * true when the validation rule should be applied. <ide> * @see \Cake\Validation\Validation::cc() <ide> * @return $this <ide> */ <ide> public function creditCard($field, $type = 'all', $message = null, $when = null) <ide> * @param int|float $value The value user data must be greater than. <ide> * @param string $message The error message when the rule fails. <ide> * @param string|callable $when Either 'create' or 'update' or a callable that returns <del> * true when the valdiation rule should be applied. <add> * true when the validation rule should be applied. <ide> * @see \Cake\Validation\Validation::comparison() <ide> * @return $this <ide> */ <ide> public function greaterThan($field, $value, $message = null, $when = null) <ide> * @param int|float $value The value user data must be greater than or equal to. <ide> * @param string $message The error message when the rule fails. <ide> * @param string|callable $when Either 'create' or 'update' or a callable that returns <del> * true when the valdiation rule should be applied. <add> * true when the validation rule should be applied. <ide> * @see \Cake\Validation\Validation::comparison() <ide> * @return $this <ide> */ <ide> public function greaterThanOrEqual($field, $value, $message = null, $when = null <ide> * @param int|float $value The value user data must be less than. <ide> * @param string $message The error message when the rule fails. <ide> * @param string|callable $when Either 'create' or 'update' or a callable that returns <del> * true when the valdiation rule should be applied. <add> * true when the validation rule should be applied. <ide> * @see \Cake\Validation\Validation::comparison() <ide> * @return $this <ide> */ <ide> public function lessThan($field, $value, $message = null, $when = null) <ide> * @param int|float $value The value user data must be less than or equal to. <ide> * @param string $message The error message when the rule fails. <ide> * @param string|callable $when Either 'create' or 'update' or a callable that returns <del> * true when the valdiation rule should be applied. <add> * true when the validation rule should be applied. <ide> * @see \Cake\Validation\Validation::comparison() <ide> * @return $this <ide> */ <ide> public function lessThanOrEqual($field, $value, $message = null, $when = null) <ide> * @param int|float $value The value user data must be equal to. <ide> * @param string $message The error message when the rule fails. <ide> * @param string|callable $when Either 'create' or 'update' or a callable that returns <del> * true when the valdiation rule should be applied. <add> * true when the validation rule should be applied. <ide> * @see \Cake\Validation\Validation::comparison() <ide> * @return $this <ide> */ <ide> public function equals($field, $value, $message = null, $when = null) <ide> * @param int|float $value The value user data must be not be equal to. <ide> * @param string $message The error message when the rule fails. <ide> * @param string|callable $when Either 'create' or 'update' or a callable that returns <del> * true when the valdiation rule should be applied. <add> * true when the validation rule should be applied. <ide> * @see \Cake\Validation\Validation::comparison() <ide> * @return $this <ide> */ <ide> public function notEquals($field, $value, $message = null, $when = null) <ide> * @param mixed $secondField The field you want to compare against. <ide> * @param string $message The error message when the rule fails. <ide> * @param string|callable $when Either 'create' or 'update' or a callable that returns <del> * true when the valdiation rule should be applied. <add> * true when the validation rule should be applied. <ide> * @see \Cake\Validation\Validation::compareWith() <ide> * @return $this <ide> */ <ide> public function sameAs($field, $secondField, $message = null, $when = null) <ide> * @param int $limit The minimum number of non-alphanumeric fields required. <ide> * @param string $message The error message when the rule fails. <ide> * @param string|callable $when Either 'create' or 'update' or a callable that returns <del> * true when the valdiation rule should be applied. <add> * true when the validation rule should be applied. <ide> * @see \Cake\Validation\Validation::containsNonAlphaNumeric() <ide> * @return $this <ide> */ <ide> public function containsNonAlphaNumeric($field, $limit = 1, $message = null, $wh <ide> * @param array $formats A list of accepted date formats. <ide> * @param string $message The error message when the rule fails. <ide> * @param string|callable $when Either 'create' or 'update' or a callable that returns <del> * true when the valdiation rule should be applied. <add> * true when the validation rule should be applied. <ide> * @see \Cake\Validation\Validation::date() <ide> * @return $this <ide> */ <ide> public function date($field, $formats = ['ymd'], $message = null, $when = null) <ide> * @param array $formats A list of accepted date formats. <ide> * @param string $message The error message when the rule fails. <ide> * @param string|callable $when Either 'create' or 'update' or a callable that returns <del> * true when the valdiation rule should be applied. <add> * true when the validation rule should be applied. <ide> * @see \Cake\Validation\Validation::datetime() <ide> * @return $this <ide> */ <ide> public function dateTime($field, $formats = ['ymd'], $message = null, $when = nu <ide> * @param string $field The field you want to apply the rule to. <ide> * @param string $message The error message when the rule fails. <ide> * @param string|callable $when Either 'create' or 'update' or a callable that returns <del> * true when the valdiation rule should be applied. <add> * true when the validation rule should be applied. <ide> * @see \Cake\Validation\Validation::time() <ide> * @return $this <ide> */ <ide> public function time($field, $message = null, $when = null) <ide> * @param string $field The field you want to apply the rule to. <ide> * @param string $message The error message when the rule fails. <ide> * @param string|callable $when Either 'create' or 'update' or a callable that returns <del> * true when the valdiation rule should be applied. <add> * true when the validation rule should be applied. <ide> * @see \Cake\Validation\Validation::boolean() <ide> * @return $this <ide> */ <ide> public function boolean($field, $message = null, $when = null) <ide> * @param int $places The number of decimal places to require. <ide> * @param string $message The error message when the rule fails. <ide> * @param string|callable $when Either 'create' or 'update' or a callable that returns <del> * true when the valdiation rule should be applied. <add> * true when the validation rule should be applied. <ide> * @see \Cake\Validation\Validation::decimal() <ide> * @return $this <ide> */ <ide> public function decimal($field, $places = null, $message = null, $when = null) <ide> * @param bool $checkMX Whether or not to check the MX records. <ide> * @param string $message The error message when the rule fails. <ide> * @param string|callable $when Either 'create' or 'update' or a callable that returns <del> * true when the valdiation rule should be applied. <add> * true when the validation rule should be applied. <ide> * @see \Cake\Validation\Validation::email() <ide> * @return $this <ide> */ <ide> public function email($field, $checkMX = false, $message = null, $when = null) <ide> * @param string $field The field you want to apply the rule to. <ide> * @param string $message The error message when the rule fails. <ide> * @param string|callable $when Either 'create' or 'update' or a callable that returns <del> * true when the valdiation rule should be applied. <add> * true when the validation rule should be applied. <ide> * @see \Cake\Validation\Validation::ip() <ide> * @return $this <ide> */ <ide> public function ip($field, $message = null, $when = null) <ide> * @param string $field The field you want to apply the rule to. <ide> * @param string $message The error message when the rule fails. <ide> * @param string|callable $when Either 'create' or 'update' or a callable that returns <del> * true when the valdiation rule should be applied. <add> * true when the validation rule should be applied. <ide> * @see \Cake\Validation\Validation::ip() <ide> * @return $this <ide> */ <ide> public function ipv4($field, $message = null, $when = null) <ide> * @param string $field The field you want to apply the rule to. <ide> * @param string $message The error message when the rule fails. <ide> * @param string|callable $when Either 'create' or 'update' or a callable that returns <del> * true when the valdiation rule should be applied. <add> * true when the validation rule should be applied. <ide> * @see \Cake\Validation\Validation::ip() <ide> * @return $this <ide> */ <ide> public function ipv6($field, $message = null, $when = null) <ide> * @param int $min The minimum length required. <ide> * @param string $message The error message when the rule fails. <ide> * @param string|callable $when Either 'create' or 'update' or a callable that returns <del> * true when the valdiation rule should be applied. <add> * true when the validation rule should be applied. <ide> * @see \Cake\Validation\Validation::minLength() <ide> * @return $this <ide> */ <ide> public function minLength($field, $min, $message = null, $when = null) <ide> * @param int $max The maximum length allowed. <ide> * @param string $message The error message when the rule fails. <ide> * @param string|callable $when Either 'create' or 'update' or a callable that returns <del> * true when the valdiation rule should be applied. <add> * true when the validation rule should be applied. <ide> * @see \Cake\Validation\Validation::maxLength() <ide> * @return $this <ide> */ <ide> public function maxLength($field, $max, $message = null, $when = null) <ide> * @param string $field The field you want to apply the rule to. <ide> * @param string $message The error message when the rule fails. <ide> * @param string|callable $when Either 'create' or 'update' or a callable that returns <del> * true when the valdiation rule should be applied. <add> * true when the validation rule should be applied. <ide> * @see \Cake\Validation\Validation::numeric() <ide> * @return $this <ide> */ <ide> public function numeric($field, $message = null, $when = null) <ide> * @param string $field The field you want to apply the rule to. <ide> * @param string $message The error message when the rule fails. <ide> * @param string|callable $when Either 'create' or 'update' or a callable that returns <del> * true when the valdiation rule should be applied. <add> * true when the validation rule should be applied. <ide> * @see \Cake\Validation\Validation::naturalNumber() <ide> * @return $this <ide> */ <ide> public function naturalNumber($field, $message = null, $when = null) <ide> * @param string $field The field you want to apply the rule to. <ide> * @param string $message The error message when the rule fails. <ide> * @param string|callable $when Either 'create' or 'update' or a callable that returns <del> * true when the valdiation rule should be applied. <add> * true when the validation rule should be applied. <ide> * @see \Cake\Validation\Validation::naturalNumber() <ide> * @return $this <ide> */ <ide> public function nonNegativeInteger($field, $message = null, $when = null) <ide> * @param array $range The inclusive upper and lower bounds of the valid range. <ide> * @param string $message The error message when the rule fails. <ide> * @param string|callable $when Either 'create' or 'update' or a callable that returns <del> * true when the valdiation rule should be applied. <add> * true when the validation rule should be applied. <ide> * @see \Cake\Validation\Validation::range() <ide> * @return $this <ide> */ <ide> public function range($field, array $range, $message = null, $when = null) <ide> * @param string $field The field you want to apply the rule to. <ide> * @param string $message The error message when the rule fails. <ide> * @param string|callable $when Either 'create' or 'update' or a callable that returns <del> * true when the valdiation rule should be applied. <add> * true when the validation rule should be applied. <ide> * @see \Cake\Validation\Validation::url() <ide> * @return $this <ide> */ <ide> public function url($field, $message = null, $when = null) <ide> * @param string $field The field you want to apply the rule to. <ide> * @param string $message The error message when the rule fails. <ide> * @param string|callable $when Either 'create' or 'update' or a callable that returns <del> * true when the valdiation rule should be applied. <add> * true when the validation rule should be applied. <ide> * @see \Cake\Validation\Validation::url() <ide> * @return $this <ide> */ <ide> public function urlWithProtocol($field, $message = null, $when = null) <ide> * @param array $list The list of valid options. <ide> * @param string $message The error message when the rule fails. <ide> * @param string|callable $when Either 'create' or 'update' or a callable that returns <del> * true when the valdiation rule should be applied. <add> * true when the validation rule should be applied. <ide> * @see \Cake\Validation\Validation::inList() <ide> * @return $this <ide> */ <ide> public function inList($field, array $list, $message = null, $when = null) <ide> * @param string $field The field you want to apply the rule to. <ide> * @param string $message The error message when the rule fails. <ide> * @param string|callable $when Either 'create' or 'update' or a callable that returns <del> * true when the valdiation rule should be applied. <add> * true when the validation rule should be applied. <ide> * @see \Cake\Validation\Validation::uuid() <ide> * @return $this <ide> */ <ide> public function uuid($field, $message = null, $when = null) <ide> * @param array $options An array of options. <ide> * @param string $message The error message when the rule fails. <ide> * @param string|callable $when Either 'create' or 'update' or a callable that returns <del> * true when the valdiation rule should be applied. <add> * true when the validation rule should be applied. <ide> * @see \Cake\Validation\Validation::uploadedFile() <ide> * @return $this <ide> */ <ide> public function uploadedFile($field, array $options, $message = null, $when = nu <ide> * @param string $field The field you want to apply the rule to. <ide> * @param string $message The error message when the rule fails. <ide> * @param string|callable $when Either 'create' or 'update' or a callable that returns <del> * true when the valdiation rule should be applied. <add> * true when the validation rule should be applied. <ide> * @see \Cake\Validation\Validation::uuid() <ide> * @return $this <ide> */ <ide> public function latLong($field, $message = null, $when = null) <ide> * @param string $field The field you want to apply the rule to. <ide> * @param string $message The error message when the rule fails. <ide> * @param string|callable $when Either 'create' or 'update' or a callable that returns <del> * true when the valdiation rule should be applied. <add> * true when the validation rule should be applied. <ide> * @see \Cake\Validation\Validation::latitude() <ide> * @return $this <ide> */ <ide> public function latitude($field, $message = null, $when = null) <ide> * @param string $field The field you want to apply the rule to. <ide> * @param string $message The error message when the rule fails. <ide> * @param string|callable $when Either 'create' or 'update' or a callable that returns <del> * true when the valdiation rule should be applied. <add> * true when the validation rule should be applied. <ide> * @see \Cake\Validation\Validation::longitude() <ide> * @return $this <ide> */ <ide> public function longitude($field, $message = null, $when = null) <ide> * @param string $field The field you want to apply the rule to. <ide> * @param string $message The error message when the rule fails. <ide> * @param string|callable $when Either 'create' or 'update' or a callable that returns <del> * true when the valdiation rule should be applied. <add> * true when the validation rule should be applied. <ide> * @see \Cake\Validation\Validation::ascii() <ide> * @return $this <ide> */ <ide> public function ascii($field, $message = null, $when = null) <ide> * @param string $field The field you want to apply the rule to. <ide> * @param string $message The error message when the rule fails. <ide> * @param string|callable $when Either 'create' or 'update' or a callable that returns <del> * true when the valdiation rule should be applied. <add> * true when the validation rule should be applied. <ide> * @see \Cake\Validation\Validation::utf8() <ide> * @return $this <ide> */ <ide> public function utf8($field, $message = null, $when = null) <ide> * @param string $field The field you want to apply the rule to. <ide> * @param string $message The error message when the rule fails. <ide> * @param string|callable $when Either 'create' or 'update' or a callable that returns <del> * true when the valdiation rule should be applied. <add> * true when the validation rule should be applied. <ide> * @see \Cake\Validation\Validation::utf8() <ide> * @return $this <ide> */ <ide> public function utf8Extended($field, $message = null, $when = null) <ide> * @param string $field The field you want to apply the rule to. <ide> * @param string $message The error message when the rule fails. <ide> * @param string|callable $when Either 'create' or 'update' or a callable that returns <del> * true when the valdiation rule should be applied. <add> * true when the validation rule should be applied. <ide> * @see \Cake\Validation\Validation::isInteger() <ide> * @return $this <ide> */
6
Go
Go
remove unused id
a44f547343299d609d6840306851102a0c78b70e
<ide><path>registry/session.go <ide> import ( <ide> "github.com/docker/docker/errdefs" <ide> "github.com/docker/docker/pkg/ioutils" <ide> "github.com/docker/docker/pkg/jsonmessage" <del> "github.com/docker/docker/pkg/stringid" <ide> "github.com/pkg/errors" <ide> "github.com/sirupsen/logrus" <ide> ) <ide> import ( <ide> type session struct { <ide> indexEndpoint *v1Endpoint <ide> client *http.Client <del> id string <ide> } <ide> <ide> type authTransport struct { <ide> func newSession(client *http.Client, endpoint *v1Endpoint) *session { <ide> return &session{ <ide> client: client, <ide> indexEndpoint: endpoint, <del> id: stringid.GenerateRandomID(), <ide> } <ide> } <ide>
1
PHP
PHP
startswith etc
df945ea3a74cd2d79885b21cf5af994c61088a41
<ide><path>tests/Support/SupportStrTest.php <ide> public function testStartsWith() <ide> $this->assertTrue(Str::startsWith('jason', 'jas')); <ide> $this->assertTrue(Str::startsWith('jason', 'jason')); <ide> $this->assertTrue(Str::startsWith('jason', ['jas'])); <add> $this->assertTrue(Str::startsWith('jason', ['day', 'jas'])); <ide> $this->assertFalse(Str::startsWith('jason', 'day')); <ide> $this->assertFalse(Str::startsWith('jason', ['day'])); <ide> $this->assertFalse(Str::startsWith('jason', '')); <ide> public function testEndsWith() <ide> $this->assertTrue(Str::endsWith('jason', 'on')); <ide> $this->assertTrue(Str::endsWith('jason', 'jason')); <ide> $this->assertTrue(Str::endsWith('jason', ['on'])); <add> $this->assertTrue(Str::endsWith('jason', ['no', 'on'])); <ide> $this->assertFalse(Str::endsWith('jason', 'no')); <ide> $this->assertFalse(Str::endsWith('jason', ['no'])); <ide> $this->assertFalse(Str::endsWith('jason', '')); <ide> public function testEndsWith() <ide> public function testStrContains() <ide> { <ide> $this->assertTrue(Str::contains('taylor', 'ylo')); <add> $this->assertTrue(Str::contains('taylor', 'taylor')); <ide> $this->assertTrue(Str::contains('taylor', ['ylo'])); <add> $this->assertTrue(Str::contains('taylor', ['xxx', 'ylo'])); <ide> $this->assertFalse(Str::contains('taylor', 'xxx')); <ide> $this->assertFalse(Str::contains('taylor', ['xxx'])); <ide> $this->assertFalse(Str::contains('taylor', ''));
1
Ruby
Ruby
warn people about tapped, deprecated taps
67cbb129ffa5b6519be668fe0e61508b1b2d721c
<ide><path>Library/Homebrew/diagnostic.rb <ide> def check_coretap_git_branch <ide> EOS <ide> end <ide> <add> def check_deprecated_official_taps <add> tapped_deprecated_taps = <add> Tap.select(&:official?).map(&:repo) & DEPRECATED_OFFICIAL_TAPS <add> return if tapped_deprecated_taps.empty? <add> <add> <<~EOS <add> You have the following deprecated, official taps tapped: <add> Homebrew/homebrew-#{tapped_deprecated_taps.join("\n ")} <add> Untap them with `brew untap`. <add> EOS <add> end <add> <ide> def __check_linked_brew(f) <ide> f.installed_prefixes.each do |prefix| <ide> prefix.find do |src|
1
PHP
PHP
support aliases on withcount
dd29bbcb9cdeba47286d22666692d00dd9a3a35d
<ide><path>src/Illuminate/Database/Eloquent/Builder.php <ide> public function withCount($relations) <ide> $relations = is_array($relations) ? $relations : func_get_args(); <ide> <ide> foreach ($this->parseWithRelations($relations) as $name => $constraints) { <del> // If relation string matches "relation as newname" extract first part as the relation <del> // name and remember the last part as output name. <del> $nameParts = explode(' ', $name); <del> $resultName = ''; <del> if (count($nameParts) == 3 && Str::lower($nameParts[1]) == 'as') { <del> $name = $nameParts[0]; <del> $resultName = $nameParts[2]; <add> // First we will determine if the name has been aliased using an "as" clause on the name <add> // and if it has we will extract the actual relationship name and the desired name of <add> // the resulting column. This allows multiple counts on the same relationship name. <add> $segments = explode(' ', $name); <add> <add> if (count($segments) == 3 && Str::lower($segments[1]) == 'as') { <add> list($name, $alias) = [$segments[0], $segments[2]]; <ide> } <ide> <add> $relation = $this->getHasRelationQuery($name); <add> <ide> // Here we will get the relationship count query and prepare to add it to the main query <ide> // as a sub-select. First, we'll get the "has" query and use that to get the relation <ide> // count query. We will normalize the relation name then append _count as the name. <del> $relation = $this->getHasRelationQuery($name); <del> <ide> $query = $relation->getRelationCountQuery( <ide> $relation->getRelated()->newQuery(), $this <ide> ); <ide> public function withCount($relations) <ide> <ide> $query->mergeModelDefinedRelationConstraints($relation->getQuery()); <ide> <del> $this->selectSub($query->toBase(), snake_case(! empty($resultName) ? $resultName : $name).'_count'); <add> // Finally we will add the proper result column alias to the query and run the subselect <add> // statement against the query builder. Then we will return the builder instance back <add> // to the developer for further constraint chaining that needs to take place on it. <add> $column = snake_case(isset($alias) ? $alias : $name).'_count'; <add> <add> $this->selectSub($query->toBase(), $column); <ide> } <ide> <ide> return $this;
1
Javascript
Javascript
improve readfile performance
eb2d4161f56efa7d82a6364734c674757f1f3ea4
<ide><path>lib/fs.js <ide> function readFileAfterStat(err, stats) { <ide> <ide> const size = context.size = isFileType(stats, S_IFREG) ? stats[8] : 0; <ide> <del> if (size === 0) { <del> context.buffers = []; <del> context.read(); <del> return; <del> } <del> <ide> if (size > kMaxLength) { <ide> err = new ERR_FS_FILE_TOO_LARGE(size); <ide> return context.close(err); <ide> } <ide> <ide> try { <del> context.buffer = Buffer.allocUnsafeSlow(size); <add> if (size === 0) { <add> context.buffers = []; <add> } else { <add> context.buffer = Buffer.allocUnsafeSlow(size); <add> } <ide> } catch (err) { <ide> return context.close(err); <ide> } <ide><path>lib/internal/fs/read_file_context.js <ide> const { Buffer } = require('buffer'); <ide> <ide> const { FSReqCallback, close, read } = internalBinding('fs'); <ide> <del>const kReadFileBufferLength = 8 * 1024; <add>// Use 64kb in case the file type is not a regular file and thus do not know the <add>// actual file size. Increasing the value further results in more frequent over <add>// allocation for small files and consumes CPU time and memory that should be <add>// used else wise. <add>// Use up to 512kb per read otherwise to partition reading big files to prevent <add>// blocking other threads in case the available threads are all in use. <add>const kReadFileUnknownBufferLength = 64 * 1024; <add>const kReadFileBufferLength = 512 * 1024; <ide> <ide> function readFileAfterRead(err, bytesRead) { <ide> const context = this.context; <ide> <ide> if (err) <ide> return context.close(err); <ide> <del> if (bytesRead === 0) <del> return context.close(); <del> <ide> context.pos += bytesRead; <ide> <del> if (context.size !== 0) { <del> if (context.pos === context.size) <del> context.close(); <del> else <del> context.read(); <add> if (context.pos === context.size || bytesRead === 0) { <add> context.close(); <ide> } else { <del> // Unknown size, just read until we don't get bytes. <del> context.buffers.push(context.buffer.slice(0, bytesRead)); <add> if (context.size === 0) { <add> // Unknown size, just read until we don't get bytes. <add> const buffer = bytesRead === kReadFileUnknownBufferLength ? <add> context.buffer : context.buffer.slice(0, bytesRead); <add> context.buffers.push(buffer); <add> } <ide> context.read(); <ide> } <ide> } <ide> class ReadFileContext { <ide> constructor(callback, encoding) { <ide> this.fd = undefined; <ide> this.isUserFd = undefined; <del> this.size = undefined; <add> this.size = 0; <ide> this.callback = callback; <ide> this.buffers = null; <ide> this.buffer = null; <ide> class ReadFileContext { <ide> let length; <ide> <ide> if (this.size === 0) { <del> buffer = this.buffer = Buffer.allocUnsafeSlow(kReadFileBufferLength); <add> buffer = Buffer.allocUnsafeSlow(kReadFileUnknownBufferLength); <ide> offset = 0; <del> length = kReadFileBufferLength; <add> length = kReadFileUnknownBufferLength; <add> this.buffer = buffer; <ide> } else { <ide> buffer = this.buffer; <ide> offset = this.pos;
2
Java
Java
register runtime hints for @sql scripts
e57b5f1dfcff0b993408f5e8b26e551b345f0a5c
<ide><path>spring-test/src/main/java/org/springframework/test/context/jdbc/SqlScriptsTestExecutionListener.java <ide> package org.springframework.test.context.jdbc; <ide> <ide> import java.lang.reflect.Method; <add>import java.util.Arrays; <ide> import java.util.List; <ide> import java.util.Set; <add>import java.util.stream.Stream; <ide> <ide> import javax.sql.DataSource; <ide> <ide> import org.apache.commons.logging.Log; <ide> import org.apache.commons.logging.LogFactory; <ide> <add>import org.springframework.aot.hint.RuntimeHints; <ide> import org.springframework.context.ApplicationContext; <ide> import org.springframework.core.annotation.AnnotatedElementUtils; <ide> import org.springframework.core.io.ByteArrayResource; <ide> import org.springframework.lang.Nullable; <ide> import org.springframework.test.context.TestContext; <ide> import org.springframework.test.context.TestContextAnnotationUtils; <add>import org.springframework.test.context.aot.AotTestExecutionListener; <ide> import org.springframework.test.context.jdbc.Sql.ExecutionPhase; <ide> import org.springframework.test.context.jdbc.SqlConfig.ErrorMode; <ide> import org.springframework.test.context.jdbc.SqlConfig.TransactionMode; <ide> import org.springframework.util.ClassUtils; <ide> import org.springframework.util.ObjectUtils; <ide> import org.springframework.util.ReflectionUtils; <del>import org.springframework.util.ResourceUtils; <add>import org.springframework.util.ReflectionUtils.MethodFilter; <ide> import org.springframework.util.StringUtils; <ide> <add>import static org.springframework.util.ResourceUtils.CLASSPATH_URL_PREFIX; <add> <ide> /** <ide> * {@code TestExecutionListener} that provides support for executing SQL <ide> * {@link Sql#scripts scripts} and inlined {@link Sql#statements statements} <ide> * @since 4.1 <ide> * @see Sql <ide> * @see SqlConfig <add> * @see SqlMergeMode <ide> * @see SqlGroup <ide> * @see org.springframework.test.context.transaction.TestContextTransactionUtils <ide> * @see org.springframework.test.context.transaction.TransactionalTestExecutionListener <ide> * @see org.springframework.jdbc.datasource.init.ResourceDatabasePopulator <ide> * @see org.springframework.jdbc.datasource.init.ScriptUtils <ide> */ <del>public class SqlScriptsTestExecutionListener extends AbstractTestExecutionListener { <add>public class SqlScriptsTestExecutionListener extends AbstractTestExecutionListener implements AotTestExecutionListener { <ide> <ide> private static final String SLASH = "/"; <ide> <ide> private static final Log logger = LogFactory.getLog(SqlScriptsTestExecutionListener.class); <ide> <add> private static final MethodFilter sqlMethodFilter = ReflectionUtils.USER_DECLARED_METHODS <add> .and(method -> AnnotatedElementUtils.hasAnnotation(method, Sql.class)); <add> <ide> <ide> /** <ide> * Returns {@code 5000}. <ide> public void afterTestMethod(TestContext testContext) { <ide> executeSqlScripts(testContext, ExecutionPhase.AFTER_TEST_METHOD); <ide> } <ide> <add> /** <add> * Process the supplied test class and its methods and register run-time <add> * hints for any SQL scripts configured or detected as classpath resources <add> * via {@link Sql @Sql}. <add> * @since 6.0 <add> */ <add> @Override <add> public void processAheadOfTime(Class<?> testClass, RuntimeHints runtimeHints, ClassLoader classLoader) { <add> getSqlAnnotationsFor(testClass).forEach(sql -> <add> registerClasspathResources(runtimeHints, getScripts(sql, testClass, null, true))); <add> getSqlMethods(testClass).forEach(testMethod -> <add> getSqlAnnotationsFor(testMethod).forEach(sql -> <add> registerClasspathResources(runtimeHints, getScripts(sql, testClass, testMethod, false)))); <add> } <add> <ide> /** <ide> * Execute SQL scripts configured via {@link Sql @Sql} for the supplied <ide> * {@link TestContext} and {@link ExecutionPhase}. <ide> private void executeSqlScripts( <ide> mergedSqlConfig, executionPhase, testContext)); <ide> } <ide> <del> String[] scripts = getScripts(sql, testContext, classLevel); <del> scripts = TestContextResourceUtils.convertToClasspathResourcePaths(testContext.getTestClass(), scripts); <add> String[] scripts = getScripts(sql, testContext.getTestClass(), testContext.getTestMethod(), classLevel); <ide> List<Resource> scriptResources = TestContextResourceUtils.convertToResourceList( <ide> testContext.getApplicationContext(), scripts); <ide> for (String stmt : sql.statements()) { <ide> private DataSource getDataSourceFromTransactionManager(PlatformTransactionManage <ide> return null; <ide> } <ide> <del> private String[] getScripts(Sql sql, TestContext testContext, boolean classLevel) { <add> private String[] getScripts(Sql sql, Class<?> testClass, Method testMethod, boolean classLevel) { <ide> String[] scripts = sql.scripts(); <ide> if (ObjectUtils.isEmpty(scripts) && ObjectUtils.isEmpty(sql.statements())) { <del> scripts = new String[] {detectDefaultScript(testContext, classLevel)}; <add> scripts = new String[] {detectDefaultScript(testClass, testMethod, classLevel)}; <ide> } <del> return scripts; <add> return TestContextResourceUtils.convertToClasspathResourcePaths(testClass, scripts); <ide> } <ide> <ide> /** <ide> * Detect a default SQL script by implementing the algorithm defined in <ide> * {@link Sql#scripts}. <ide> */ <del> private String detectDefaultScript(TestContext testContext, boolean classLevel) { <del> Class<?> clazz = testContext.getTestClass(); <del> Method method = testContext.getTestMethod(); <add> private String detectDefaultScript(Class<?> testClass, Method testMethod, boolean classLevel) { <ide> String elementType = (classLevel ? "class" : "method"); <del> String elementName = (classLevel ? clazz.getName() : method.toString()); <add> String elementName = (classLevel ? testClass.getName() : testMethod.toString()); <ide> <del> String resourcePath = ClassUtils.convertClassNameToResourcePath(clazz.getName()); <add> String resourcePath = ClassUtils.convertClassNameToResourcePath(testClass.getName()); <ide> if (!classLevel) { <del> resourcePath += "." + method.getName(); <add> resourcePath += "." + testMethod.getName(); <ide> } <ide> resourcePath += ".sql"; <ide> <del> String prefixedResourcePath = ResourceUtils.CLASSPATH_URL_PREFIX + SLASH + resourcePath; <add> String prefixedResourcePath = CLASSPATH_URL_PREFIX + SLASH + resourcePath; <ide> ClassPathResource classPathResource = new ClassPathResource(resourcePath); <ide> <ide> if (classPathResource.exists()) { <ide> private String detectDefaultScript(TestContext testContext, boolean classLevel) <ide> } <ide> } <ide> <add> private Stream<Method> getSqlMethods(Class<?> testClass) { <add> return Arrays.stream(ReflectionUtils.getUniqueDeclaredMethods(testClass, sqlMethodFilter)); <add> } <add> <add> private void registerClasspathResources(RuntimeHints runtimeHints, String... locations) { <add> Arrays.stream(locations) <add> .filter(location -> location.startsWith(CLASSPATH_URL_PREFIX)) <add> .map(this::cleanClasspathResource) <add> .forEach(runtimeHints.resources()::registerPattern); <add> } <add> <add> private String cleanClasspathResource(String location) { <add> location = location.substring(CLASSPATH_URL_PREFIX.length()); <add> if (!location.startsWith(SLASH)) { <add> location = SLASH + location; <add> } <add> return location; <add> } <add> <ide> } <ide><path>spring-test/src/test/java/org/springframework/test/context/aot/TestContextAotGeneratorTests.java <ide> private static void assertRuntimeHints(RuntimeHints runtimeHints) { <ide> // @WebAppConfiguration(value = ...) <ide> assertThat(resource().forResource("/META-INF/web-resources/resources/Spring.js")).accepts(runtimeHints); <ide> assertThat(resource().forResource("/META-INF/web-resources/WEB-INF/views/home.jsp")).accepts(runtimeHints); <add> <add> // @Sql(scripts = ...) <add> assertThat(resource().forResource("/org/springframework/test/context/jdbc/schema.sql")) <add> .accepts(runtimeHints); <add> assertThat(resource().forResource("/org/springframework/test/context/aot/samples/jdbc/SqlScriptsSpringJupiterTests.test.sql")) <add> .accepts(runtimeHints); <ide> } <ide> <ide> private static void assertReflectionRegistered(RuntimeHints runtimeHints, String type, MemberCategory memberCategory) {
2
Ruby
Ruby
use method compilation for association methods
6e57d5c5840716b63851f02a6a806ba968065bca
<ide><path>activerecord/lib/active_record/associations/builder/association.rb <ide> def define_accessors <ide> end <ide> <ide> def define_readers <del> name = self.name <del> mixin.redefine_method(name) do |*params| <del> association(name).reader(*params) <del> end <add> mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1 <add> def #{name}(*args) <add> association(:#{name}).reader(*args) <add> end <add> CODE <ide> end <ide> <ide> def define_writers <del> name = self.name <del> mixin.redefine_method("#{name}=") do |value| <del> association(name).writer(value) <del> end <add> mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1 <add> def #{name}=(value) <add> association(:#{name}).writer(value) <add> end <add> CODE <ide> end <ide> <ide> def configure_dependency <ide> def configure_dependency <ide> ) <ide> end <ide> <del> name = self.name <del> mixin.redefine_method("#{macro}_dependent_for_#{name}") do <del> association(name).handle_dependency <del> end <add> mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1 <add> def #{macro}_dependent_for_#{name} <add> association(:#{name}).handle_dependency <add> end <add> CODE <ide> <ide> model.before_destroy "#{macro}_dependent_for_#{name}" <ide> end <ide><path>activerecord/lib/active_record/associations/builder/belongs_to.rb <ide> def build <ide> <ide> def add_counter_cache_callbacks(reflection) <ide> cache_column = reflection.counter_cache_column <del> name = self.name <ide> <del> method_name = "belongs_to_counter_cache_after_create_for_#{name}" <del> mixin.redefine_method(method_name) do <del> record = send(name) <del> record.class.increment_counter(cache_column, record.id) unless record.nil? <del> end <del> model.after_create(method_name) <add> mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1 <add> def belongs_to_counter_cache_after_create_for_#{name} <add> record = #{name} <add> record.class.increment_counter(:#{cache_column}, record.id) unless record.nil? <add> end <ide> <del> method_name = "belongs_to_counter_cache_before_destroy_for_#{name}" <del> mixin.redefine_method(method_name) do <del> unless marked_for_destruction? <del> record = send(name) <del> record.class.decrement_counter(cache_column, record.id) unless record.nil? <add> def belongs_to_counter_cache_before_destroy_for_#{name} <add> unless marked_for_destruction? <add> record = #{name} <add> record.class.decrement_counter(:#{cache_column}, record.id) unless record.nil? <add> end <ide> end <del> end <del> model.before_destroy(method_name) <add> CODE <ide> <del> model.send(:module_eval, <del> "#{reflection.class_name}.send(:attr_readonly,\"#{cache_column}\".intern) if defined?(#{reflection.class_name}) && #{reflection.class_name}.respond_to?(:attr_readonly)", __FILE__, __LINE__ <del> ) <add> model.after_create "belongs_to_counter_cache_after_create_for_#{name}" <add> model.before_destroy "belongs_to_counter_cache_before_destroy_for_#{name}" <add> <add> klass = reflection.class_name.safe_constantize <add> klass.attr_readonly cache_column if klass && klass.respond_to?(:attr_readonly) <ide> end <ide> <ide> def add_touch_callbacks(reflection) <del> name = self.name <del> method_name = "belongs_to_touch_after_save_or_destroy_for_#{name}" <del> touch = options[:touch] <del> <del> mixin.redefine_method(method_name) do <del> record = send(name) <add> mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1 <add> def belongs_to_touch_after_save_or_destroy_for_#{name} <add> record = #{name} <ide> <del> unless record.nil? <del> if touch == true <del> record.touch <del> else <del> record.touch(touch) <add> unless record.nil? <add> record.touch #{options[:touch].inspect if options[:touch] != true} <ide> end <ide> end <del> end <add> CODE <ide> <del> model.after_save(method_name) <del> model.after_touch(method_name) <del> model.after_destroy(method_name) <add> model.after_save "belongs_to_touch_after_save_or_destroy_for_#{name}" <add> model.after_touch "belongs_to_touch_after_save_or_destroy_for_#{name}" <add> model.after_destroy "belongs_to_touch_after_save_or_destroy_for_#{name}" <ide> end <ide> <ide> def valid_dependent_options <ide><path>activerecord/lib/active_record/associations/builder/collection_association.rb <ide> def define_callback(callback_name) <ide> def define_readers <ide> super <ide> <del> name = self.name <del> mixin.redefine_method("#{name.to_s.singularize}_ids") do <del> association(name).ids_reader <del> end <add> mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1 <add> def #{name.to_s.singularize}_ids <add> association(:#{name}).ids_reader <add> end <add> CODE <ide> end <ide> <ide> def define_writers <ide> super <ide> <del> name = self.name <del> mixin.redefine_method("#{name.to_s.singularize}_ids=") do |ids| <del> association(name).ids_writer(ids) <del> end <add> mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1 <add> def #{name.to_s.singularize}_ids=(ids) <add> association(:#{name}).ids_writer(ids) <add> end <add> CODE <ide> end <ide> end <ide> end <ide><path>activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb <ide> def define_destroy_hook <ide> model.send(:include, Module.new { <ide> class_eval <<-RUBY, __FILE__, __LINE__ + 1 <ide> def destroy_associations <del> association(#{name.to_sym.inspect}).delete_all <add> association(:#{name}).delete_all <ide> super <ide> end <ide> RUBY <ide><path>activerecord/lib/active_record/associations/builder/singular_association.rb <ide> def define_accessors <ide> end <ide> <ide> def define_constructors <del> name = self.name <add> mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1 <add> def build_#{name}(*args, &block) <add> association(:#{name}).build(*args, &block) <add> end <ide> <del> mixin.redefine_method("build_#{name}") do |*params, &block| <del> association(name).build(*params, &block) <del> end <add> def create_#{name}(*args, &block) <add> association(:#{name}).create(*args, &block) <add> end <ide> <del> mixin.redefine_method("create_#{name}") do |*params, &block| <del> association(name).create(*params, &block) <del> end <del> <del> mixin.redefine_method("create_#{name}!") do |*params, &block| <del> association(name).create!(*params, &block) <del> end <add> def create_#{name}!(*args, &block) <add> association(:#{name}).create!(*args, &block) <add> end <add> CODE <ide> end <ide> end <ide> end <ide><path>activerecord/test/cases/associations/belongs_to_associations_test.rb <ide> def test_dependent_delete_and_destroy_with_belongs_to <ide> <ide> def test_invalid_belongs_to_dependent_option_nullify_raises_exception <ide> assert_raise ArgumentError do <del> Author.belongs_to :special_author_address, :dependent => :nullify <add> Class.new(Author).belongs_to :special_author_address, :dependent => :nullify <ide> end <ide> end <ide> <ide> def test_invalid_belongs_to_dependent_option_restrict_raises_exception <ide> assert_raise ArgumentError do <del> Author.belongs_to :special_author_address, :dependent => :restrict <add> Class.new(Author).belongs_to :special_author_address, :dependent => :restrict <ide> end <ide> end <ide> <ide><path>activerecord/test/cases/associations/join_model_test.rb <ide> def test_has_many_through_has_many_find_by_id <ide> end <ide> <ide> def test_has_many_through_polymorphic_has_one <del> assert_equal Tagging.find(1,2).sort_by { |t| t.id }, authors(:david).tagging <add> assert_equal Tagging.find(1,2).sort_by { |t| t.id }, authors(:david).taggings_2 <ide> end <ide> <ide> def test_has_many_through_polymorphic_has_many <ide><path>activerecord/test/cases/multiple_db_test.rb <ide> require "cases/helper" <ide> require 'models/entrant' <ide> require 'models/bird' <del> <del># So we can test whether Course.connection survives a reload. <del>require_dependency 'models/course' <add>require 'models/course' <ide> <ide> class MultipleDbTest < ActiveRecord::TestCase <ide> self.use_transactional_fixtures = false <ide><path>activerecord/test/cases/timestamp_test.rb <ide> def test_destroying_a_record_with_a_belongs_to_that_specifies_touching_the_paren <ide> end <ide> <ide> def test_saving_a_record_with_a_belongs_to_that_specifies_touching_a_specific_attribute_the_parent_should_update_that_attribute <del> Pet.belongs_to :owner, :touch => :happy_at <add> klass = Class.new(ActiveRecord::Base) do <add> def self.name; 'Pet'; end <add> belongs_to :owner, :touch => :happy_at <add> end <ide> <del> pet = Pet.first <add> pet = klass.first <ide> owner = pet.owner <ide> previously_owner_happy_at = owner.happy_at <ide> <ide> pet.name = "Fluffy the Third" <ide> pet.save <ide> <ide> assert_not_equal previously_owner_happy_at, pet.owner.happy_at <del> ensure <del> Pet.belongs_to :owner, :touch => true <ide> end <ide> <ide> def test_touching_a_record_with_a_belongs_to_that_uses_a_counter_cache_should_update_the_parent <del> Pet.belongs_to :owner, :counter_cache => :use_count, :touch => true <add> klass = Class.new(ActiveRecord::Base) do <add> def self.name; 'Pet'; end <add> belongs_to :owner, :counter_cache => :use_count, :touch => true <add> end <ide> <del> pet = Pet.first <add> pet = klass.first <ide> owner = pet.owner <ide> owner.update_columns(happy_at: 3.days.ago) <ide> previously_owner_updated_at = owner.updated_at <ide> def test_touching_a_record_with_a_belongs_to_that_uses_a_counter_cache_should_up <ide> pet.save <ide> <ide> assert_not_equal previously_owner_updated_at, pet.owner.updated_at <del> ensure <del> Pet.belongs_to :owner, :touch => true <ide> end <ide> <ide> def test_touching_a_record_touches_parent_record_and_grandparent_record <del> Toy.belongs_to :pet, :touch => true <del> Pet.belongs_to :owner, :touch => true <add> klass = Class.new(ActiveRecord::Base) do <add> def self.name; 'Toy'; end <add> belongs_to :pet, :touch => true <add> end <ide> <del> toy = Toy.first <add> toy = klass.first <ide> pet = toy.pet <ide> owner = pet.owner <ide> time = 3.days.ago <ide> def test_touching_a_record_touches_parent_record_and_grandparent_record <ide> owner.reload <ide> <ide> assert_not_equal time, owner.updated_at <del> ensure <del> Toy.belongs_to :pet <ide> end <ide> <ide> def test_timestamp_attributes_for_create <ide><path>activerecord/test/models/author.rb <ide> def testing_proxy_target <ide> has_many :author_favorites <ide> has_many :favorite_authors, -> { order('name') }, :through => :author_favorites <ide> <del> has_many :tagging, :through => :posts <ide> has_many :taggings, :through => :posts <add> has_many :taggings_2, :through => :posts, :source => :tagging <ide> has_many :tags, :through => :posts <ide> has_many :post_categories, :through => :posts, :source => :categories <ide> has_many :tagging_tags, :through => :taggings, :source => :tag <ide><path>activerecord/test/models/member.rb <ide> class Member < ActiveRecord::Base <ide> <ide> has_one :club_category, :through => :club, :source => :category <ide> <del> has_many :current_memberships <del> has_one :club_through_many, :through => :current_memberships, :source => :club <del> <ide> has_many :current_memberships, -> { where :favourite => true } <ide> has_many :clubs, :through => :current_memberships <add> <add> has_one :club_through_many, :through => :current_memberships, :source => :club <ide> end <ide> <ide> class SelfMember < ActiveRecord::Base <ide><path>activerecord/test/support/connection.rb <ide> require 'active_support/logger' <del>require_dependency 'models/college' <del>require_dependency 'models/course' <add>require 'models/college' <add>require 'models/course' <ide> <ide> module ARTest <ide> def self.connection_name
12
Text
Text
fix bug in validators documentation
614bd87b601c84f7687c94de616daacad8a3734a
<ide><path>docs/api-guide/validators.md <ide> A validator may be any callable that raises a `serializers.ValidationError` on f <ide> def even_number(value): <ide> if value % 2 != 0: <ide> raise serializers.ValidationError('This field must be an even number.') <add> return value <ide> <ide> #### Field-level validation <ide>
1
Text
Text
rectify layout errors
85afde04e5f69e94efef33388cf87a74132bb5eb
<ide><path>guide/english/css/comments-in-css/index.md <ide> Here are a few exmples to get you started of CSS comments you can use in your da <ide> ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ <ide> ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ <ide> <add> <ide> /**************************************************************************** <ide> 1.0 - Reset */ <ide> <ide> Here are a few exmples to get you started of CSS comments you can use in your da <ide> /**************************************************************************** <ide> 6.0 - Body */ <ide> <del> /************************************************************************ <del> 5.1 - Sliders */ <add>/************************************************************************ <add>5.1 - Sliders */ <ide> <del> /************************************************************************ <del> 5.2 - Imagery */ <add>/************************************************************************ <add>5.2 - Imagery */ <ide> <ide> /**************************************************************************** <ide> 7.0 - Footer */ <del> <del>h2 { <del> font-size: 1.2em; <del> font-family: "Ubuntu", serif; <del> text-transform: uppercase; <del>} <ide> ``` <ide> <ide> Tip: Many code editors will comment a highlighted portion of text by typing `CMD + /` (Mac) or `CTRL + /` (Windows).
1
Mixed
Javascript
add options to http.createserver()
a899576c977aef32d85074ac09d511e4590e28d7
<ide><path>doc/api/http.md <ide> A collection of all the standard HTTP response status codes, and the <ide> short description of each. For example, `http.STATUS_CODES[404] === 'Not <ide> Found'`. <ide> <del>## http.createServer([requestListener]) <add>## http.createServer([options][, requestListener]) <ide> <!-- YAML <ide> added: v0.1.13 <del>--> <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/15752 <add> description: The `options` argument is supported now. <add>--> <add>- `options` {Object} <add> * `IncomingMessage` {http.IncomingMessage} Specifies the IncomingMessage class <add> to be used. Useful for extending the original `IncomingMessage`. Defaults <add> to: `IncomingMessage` <add> * `ServerResponse` {http.ServerResponse} Specifies the ServerResponse class to <add> be used. Useful for extending the original `ServerResponse`. Defaults to: <add> `ServerResponse` <ide> - `requestListener` {Function} <ide> <ide> * Returns: {http.Server} <ide><path>doc/api/https.md <ide> See [`http.Server#keepAliveTimeout`][]. <ide> <!-- YAML <ide> added: v0.3.4 <ide> --> <del>- `options` {Object} Accepts `options` from [`tls.createServer()`][] and [`tls.createSecureContext()`][]. <add>- `options` {Object} Accepts `options` from [`tls.createServer()`][], <add> [`tls.createSecureContext()`][] and [`http.createServer()`][]. <ide> - `requestListener` {Function} A listener to be added to the `request` event. <ide> <ide> Example: <ide> const req = https.request(options, (res) => { <ide> [`http.Server#setTimeout()`]: http.html#http_server_settimeout_msecs_callback <ide> [`http.Server#timeout`]: http.html#http_server_timeout <ide> [`http.Server`]: http.html#http_class_http_server <add>[`http.createServer()`]: http.html#httpcreateserveroptions-requestlistener <ide> [`http.close()`]: http.html#http_server_close_callback <ide> [`http.get()`]: http.html#http_http_get_options_callback <ide> [`http.request()`]: http.html#http_http_request_options_callback <ide><path>lib/_http_common.js <ide> const { <ide> <ide> const debug = require('util').debuglog('http'); <ide> <add>const kIncomingMessage = Symbol('IncomingMessage'); <ide> const kOnHeaders = HTTPParser.kOnHeaders | 0; <ide> const kOnHeadersComplete = HTTPParser.kOnHeadersComplete | 0; <ide> const kOnBody = HTTPParser.kOnBody | 0; <ide> function parserOnHeadersComplete(versionMajor, versionMinor, headers, method, <ide> parser._url = ''; <ide> } <ide> <del> parser.incoming = new IncomingMessage(parser.socket); <add> // Parser is also used by http client <add> var ParserIncomingMessage = parser.socket && parser.socket.server ? <add> parser.socket.server[kIncomingMessage] : IncomingMessage; <add> <add> parser.incoming = new ParserIncomingMessage(parser.socket); <ide> parser.incoming.httpVersionMajor = versionMajor; <ide> parser.incoming.httpVersionMinor = versionMinor; <ide> parser.incoming.httpVersion = `${versionMajor}.${versionMinor}`; <ide> module.exports = { <ide> freeParser, <ide> httpSocketSetup, <ide> methods, <del> parsers <add> parsers, <add> kIncomingMessage <ide> }; <ide><path>lib/_http_server.js <ide> const { <ide> continueExpression, <ide> chunkExpression, <ide> httpSocketSetup, <add> kIncomingMessage, <ide> _checkInvalidHeaderChar: checkInvalidHeaderChar <ide> } = require('_http_common'); <ide> const { OutgoingMessage } = require('_http_outgoing'); <ide> const { <ide> defaultTriggerAsyncIdScope, <ide> getOrSetAsyncId <ide> } = require('internal/async_hooks'); <add>const { IncomingMessage } = require('_http_incoming'); <ide> const errors = require('internal/errors'); <ide> const Buffer = require('buffer').Buffer; <ide> <add>const kServerResponse = Symbol('ServerResponse'); <add> <ide> const STATUS_CODES = { <ide> 100: 'Continue', <ide> 101: 'Switching Protocols', <ide> function writeHead(statusCode, reason, obj) { <ide> // Docs-only deprecated: DEP0063 <ide> ServerResponse.prototype.writeHeader = ServerResponse.prototype.writeHead; <ide> <add>function Server(options, requestListener) { <add> if (!(this instanceof Server)) return new Server(options, requestListener); <add> <add> if (typeof options === 'function') { <add> requestListener = options; <add> options = {}; <add> } else if (options == null || typeof options === 'object') { <add> options = util._extend({}, options); <add> } <add> <add> this[kIncomingMessage] = options.IncomingMessage || IncomingMessage; <add> this[kServerResponse] = options.ServerResponse || ServerResponse; <ide> <del>function Server(requestListener) { <del> if (!(this instanceof Server)) return new Server(requestListener); <ide> net.Server.call(this, { allowHalfOpen: true }); <ide> <ide> if (requestListener) { <ide> function parserOnIncoming(server, socket, state, req, keepAlive) { <ide> } <ide> } <ide> <del> var res = new ServerResponse(req); <add> var res = new server[kServerResponse](req); <ide> res._onPendingData = updateOutgoingData.bind(undefined, socket, state); <ide> <ide> res.shouldKeepAlive = keepAlive; <ide> module.exports = { <ide> STATUS_CODES, <ide> Server, <ide> ServerResponse, <del> _connectionListener: connectionListener <add> _connectionListener: connectionListener, <add> kServerResponse <ide> }; <ide><path>lib/https.js <ide> const { inherits } = util; <ide> const debug = util.debuglog('https'); <ide> const { urlToOptions, searchParamsSymbol } = require('internal/url'); <ide> const errors = require('internal/errors'); <add>const { IncomingMessage, ServerResponse } = require('http'); <add>const { kIncomingMessage } = require('_http_common'); <add>const { kServerResponse } = require('_http_server'); <ide> <ide> function Server(opts, requestListener) { <ide> if (!(this instanceof Server)) return new Server(opts, requestListener); <ide> function Server(opts, requestListener) { <ide> opts.ALPNProtocols = ['http/1.1']; <ide> } <ide> <add> this[kIncomingMessage] = opts.IncomingMessage || IncomingMessage; <add> this[kServerResponse] = opts.ServerResponse || ServerResponse; <add> <ide> tls.Server.call(this, opts, _connectionListener); <ide> <ide> this.httpAllowHalfOpen = false; <ide><path>test/parallel/test-http-server-options-incoming-message.js <add>'use strict'; <add> <add>/** <add> * This test covers http.Server({ IncomingMessage }) option: <add> * With IncomingMessage option the server should use <add> * the new class for creating req Object instead of the default <add> * http.IncomingMessage. <add> */ <add>const common = require('../common'); <add>const assert = require('assert'); <add>const http = require('http'); <add> <add>class MyIncomingMessage extends http.IncomingMessage { <add> getUserAgent() { <add> return this.headers['user-agent'] || 'unknown'; <add> } <add>} <add> <add>const server = http.Server({ <add> IncomingMessage: MyIncomingMessage <add>}, common.mustCall(function(req, res) { <add> assert.strictEqual(req.getUserAgent(), 'node-test'); <add> res.statusCode = 200; <add> res.end(); <add>})); <add>server.listen(); <add> <add>server.on('listening', function makeRequest() { <add> http.get({ <add> port: this.address().port, <add> headers: { <add> 'User-Agent': 'node-test' <add> } <add> }, (res) => { <add> assert.strictEqual(res.statusCode, 200); <add> res.on('end', () => { <add> server.close(); <add> }); <add> res.resume(); <add> }); <add>}); <ide><path>test/parallel/test-http-server-options-server-response.js <add>'use strict'; <add> <add>/** <add> * This test covers http.Server({ ServerResponse }) option: <add> * With ServerResponse option the server should use <add> * the new class for creating res Object instead of the default <add> * http.ServerResponse. <add> */ <add>const common = require('../common'); <add>const assert = require('assert'); <add>const http = require('http'); <add> <add>class MyServerResponse extends http.ServerResponse { <add> status(code) { <add> return this.writeHead(code, { 'Content-Type': 'text/plain' }); <add> } <add>} <add> <add>const server = http.Server({ <add> ServerResponse: MyServerResponse <add>}, common.mustCall(function(req, res) { <add> res.status(200); <add> res.end(); <add>})); <add>server.listen(); <add> <add>server.on('listening', function makeRequest() { <add> http.get({ port: this.address().port }, (res) => { <add> assert.strictEqual(res.statusCode, 200); <add> res.on('end', () => { <add> server.close(); <add> }); <add> res.resume(); <add> }); <add>}); <ide><path>test/parallel/test-https-server-options-incoming-message.js <add>'use strict'; <add> <add>/** <add> * This test covers http.Server({ IncomingMessage }) option: <add> * With IncomingMessage option the server should use <add> * the new class for creating req Object instead of the default <add> * http.IncomingMessage. <add> */ <add>const common = require('../common'); <add>const fixtures = require('../common/fixtures'); <add> <add>if (!common.hasCrypto) <add> common.skip('missing crypto'); <add> <add>const assert = require('assert'); <add>const http = require('http'); <add>const https = require('https'); <add> <add>class MyIncomingMessage extends http.IncomingMessage { <add> getUserAgent() { <add> return this.headers['user-agent'] || 'unknown'; <add> } <add>} <add> <add>const server = https.createServer({ <add> key: fixtures.readKey('agent1-key.pem'), <add> cert: fixtures.readKey('agent1-cert.pem'), <add> ca: fixtures.readKey('ca1-cert.pem'), <add> IncomingMessage: MyIncomingMessage <add>}, common.mustCall(function(req, res) { <add> assert.strictEqual(req.getUserAgent(), 'node-test'); <add> res.statusCode = 200; <add> res.end(); <add>})); <add>server.listen(); <add> <add>server.on('listening', function makeRequest() { <add> https.get({ <add> port: this.address().port, <add> rejectUnauthorized: false, <add> headers: { <add> 'User-Agent': 'node-test' <add> } <add> }, (res) => { <add> assert.strictEqual(res.statusCode, 200); <add> res.on('end', () => { <add> server.close(); <add> }); <add> res.resume(); <add> }); <add>}); <ide><path>test/parallel/test-https-server-options-server-response.js <add>'use strict'; <add> <add>/** <add> * This test covers http.Server({ ServerResponse }) option: <add> * With ServerResponse option the server should use <add> * the new class for creating res Object instead of the default <add> * http.ServerResponse. <add> */ <add>const common = require('../common'); <add>const fixtures = require('../common/fixtures'); <add> <add>if (!common.hasCrypto) <add> common.skip('missing crypto'); <add> <add>const assert = require('assert'); <add>const http = require('http'); <add>const https = require('https'); <add> <add>class MyServerResponse extends http.ServerResponse { <add> status(code) { <add> return this.writeHead(code, { 'Content-Type': 'text/plain' }); <add> } <add>} <add> <add>const server = https.createServer({ <add> key: fixtures.readKey('agent1-key.pem'), <add> cert: fixtures.readKey('agent1-cert.pem'), <add> ca: fixtures.readKey('ca1-cert.pem'), <add> ServerResponse: MyServerResponse <add>}, common.mustCall(function(req, res) { <add> res.status(200); <add> res.end(); <add>})); <add>server.listen(); <add> <add>server.on('listening', function makeRequest() { <add> https.get({ <add> port: this.address().port, <add> rejectUnauthorized: false <add> }, (res) => { <add> assert.strictEqual(res.statusCode, 200); <add> res.on('end', () => { <add> server.close(); <add> }); <add> res.resume(); <add> }); <add>});
9
PHP
PHP
add method for marking password confirmed
fb3f45aa0142764c5c29b97e8bcf8328091986e9
<ide><path>src/Illuminate/Session/Store.php <ide> public function setPreviousUrl($url) <ide> $this->put('_previous.url', $url); <ide> } <ide> <add> /** <add> * Specify that the user has confirmed their password. <add> * <add> * @return void <add> */ <add> public function passwordConfirmed() <add> { <add> $this->put('auth.password_confirmed_at', time()); <add> } <add> <ide> /** <ide> * Get the underlying session handler implementation. <ide> *
1
Ruby
Ruby
avoid referencing rubygems
ec0d4efd7985df6c03c47db845292b919d24eaf0
<ide><path>activesupport/test/isolation_test.rb <ide> class ParentIsolationTest < ActiveSupport::TestCase <ide> File.open(File.join(File.dirname(__FILE__), "fixtures", "isolation_test"), "w") {} <ide> <ide> ENV["CHILD"] = "1" <del> OUTPUT = `#{Gem.ruby} -I#{File.dirname(__FILE__)} "#{File.expand_path(__FILE__)}" -v` <add> OUTPUT = `ruby -I#{File.dirname(__FILE__)} "#{File.expand_path(__FILE__)}" -v` <ide> ENV.delete("CHILD") <ide> <ide> def setup
1
Python
Python
remove unused imports
6d709f42cd3305c8e6cb629ce2d16d0174e2ce80
<ide><path>libcloud/drivers/dreamhost.py <ide> """ <ide> DreamHost Driver <ide> """ <del>import uuid <ide> <del>from libcloud.interface import INodeDriver <ide> from libcloud.base import ConnectionKey, Response, NodeDriver, Node <del>from libcloud.base import NodeSize, NodeImage, NodeLocation <add>from libcloud.base import NodeSize, NodeImage <ide> from libcloud.types import Provider, NodeState, InvalidCredsException <ide> <ide> # JSON is included in the standard library starting with Python 2.6. For 2.5
1
Javascript
Javascript
move cjs type check behind flag
2825e1183d87354507e2e847f0891116d48b1a38
<ide><path>lib/internal/modules/cjs/loader.js <ide> Module.prototype._compile = function(content, filename) { <ide> <ide> // Native extension for .js <ide> Module._extensions['.js'] = function(module, filename) { <del> if (filename.endsWith('.js')) { <add> if (experimentalModules && filename.endsWith('.js')) { <ide> const pkg = readPackageScope(filename); <ide> if (pkg && pkg.type === 'module') { <ide> throw new ERR_REQUIRE_ESM(filename); <ide><path>test/es-module/test-esm-type-flag-errors.js <add>// Flags: --experimental-modules <ide> 'use strict'; <ide> const common = require('../common'); <ide> const assert = require('assert');
2
Javascript
Javascript
set input .type before .value always
07c0bc6166013fc56edd8310bd97267549e5c708
<ide><path>src/renderers/dom/client/wrappers/ReactDOMInput.js <ide> var ReactDOMInput = { <ide> var value = LinkedValueUtils.getValue(props); <ide> var checked = LinkedValueUtils.getChecked(props); <ide> <del> var nativeProps = assign({}, props, { <add> var nativeProps = assign({ <add> // Make sure we set .type before any other properties (setting .value <add> // before .type means .value is lost in IE11 and below) <add> type: undefined, <add> }, props, { <ide> defaultChecked: undefined, <ide> defaultValue: undefined, <ide> value: value != null ? value : inst._wrapperState.initialValue, <ide><path>src/renderers/dom/client/wrappers/__tests__/ReactDOMInput-test.js <ide> describe('ReactDOMInput', function() { <ide> ReactTestUtils.renderIntoDocument(<input type="text" value={null} />); <ide> expect(console.error.argsForCall.length).toBe(1); <ide> }); <add> <add> it('sets type before value always', function() { <add> var log = []; <add> var originalCreateElement = document.createElement; <add> spyOn(document, 'createElement').andCallFake(function(type) { <add> var el = originalCreateElement.apply(this, arguments); <add> if (type === 'input') { <add> Object.defineProperty(el, 'value', { <add> get: function() {}, <add> set: function() { <add> log.push('set value'); <add> }, <add> }); <add> spyOn(el, 'setAttribute').andCallFake(function(name, value) { <add> log.push('set ' + name); <add> }); <add> } <add> return el; <add> }); <add> <add> ReactTestUtils.renderIntoDocument(<input value="hi" type="radio" />); <add> // Setting value before type does bad things. Make sure we set type first. <add> expect(log).toEqual([ <add> 'set data-reactroot', <add> 'set type', <add> 'set value', <add> ]); <add> }); <ide> });
2
Ruby
Ruby
add test for keg#mach_o_files hardlink behavior
62d7079684cdb568600e22531c62888622a71ff1
<ide><path>Library/Homebrew/test/test_keg.rb <ide> def test_removes_broken_symlinks_that_conflict_with_directories <ide> keg.unlink <ide> keg.uninstall <ide> end <add> <add> def test_mach_o_files_skips_hardlinks <add> a = HOMEBREW_CELLAR.join("a", "1.0") <add> a.join("lib").mkpath <add> FileUtils.cp dylib_path("i386"), a.join("lib", "i386.dylib") <add> FileUtils.ln a.join("lib", "i386.dylib"), a.join("lib", "i386_link.dylib") <add> <add> keg = Keg.new(a) <add> keg.link <add> <add> assert_equal 1, keg.mach_o_files.size <add> ensure <add> keg.unlink <add> keg.uninstall <add> end <ide> end <ide><path>Library/Homebrew/test/test_mach.rb <ide> require "testing_env" <ide> <ide> class MachOPathnameTests < Homebrew::TestCase <del> def dylib_path(name) <del> Pathname.new("#{TEST_DIRECTORY}/mach/#{name}.dylib") <del> end <del> <del> def bundle_path(name) <del> Pathname.new("#{TEST_DIRECTORY}/mach/#{name}.bundle") <del> end <del> <ide> def test_fat_dylib <ide> pn = dylib_path("fat") <ide> assert_predicate pn, :universal? <ide><path>Library/Homebrew/test/testing_env.rb <ide> def refute_eql(exp, act, msg = nil) <ide> } <ide> refute exp.eql?(act), msg <ide> end <add> <add> def dylib_path(name) <add> Pathname.new("#{TEST_DIRECTORY}/mach/#{name}.dylib") <add> end <add> <add> def bundle_path(name) <add> Pathname.new("#{TEST_DIRECTORY}/mach/#{name}.bundle") <add> end <ide> end <ide> end
3
Java
Java
fix issue with suffix pattern match
9cc4bd892a6bb3aca9fea4b2423369181cebea9a
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMapping.java <ide> public class RequestMappingHandlerMapping extends RequestMappingInfoHandlerMappi <ide> <ide> private boolean useSuffixPatternMatch = true; <ide> <add> private boolean useRegisteredSuffixPatternMatch = false; <add> <ide> private boolean useTrailingSlashMatch = true; <ide> <ide> private ContentNegotiationManager contentNegotiationManager = new ContentNegotiationManager(); <ide> <del> private final List<String> contentNegotiationFileExtensions = new ArrayList<String>(); <add> private final List<String> fileExtensions = new ArrayList<String>(); <ide> <ide> /** <ide> * Whether to use suffix pattern match (".*") when matching patterns to <ide> * requests. If enabled a method mapped to "/users" also matches to "/users.*". <ide> * <p>The default value is {@code true}. <add> * <p>Also see {@link #setUseRegisteredSuffixPatternMatch(boolean)} for <add> * more fine-grained control over specific suffices to allow. <ide> */ <ide> public void setUseSuffixPatternMatch(boolean useSuffixPatternMatch) { <ide> this.useSuffixPatternMatch = useSuffixPatternMatch; <ide> } <ide> <add> /** <add> * Whether to use suffix pattern match for registered file extensions only <add> * when matching patterns to requests. <add> * <add> * <p>If enabled, a controller method mapped to "/users" also matches to <add> * "/users.json" assuming ".json" is a file extension registered with the <add> * provided {@link #setContentNegotiationManager(ContentNegotiationManager) <add> * contentNegotiationManager}. This can be useful for allowing only specific <add> * URL extensions to be used as well as in cases where a "." in the URL path <add> * can lead to ambiguous interpretation of path variable content, (e.g. given <add> * "/users/{user}" and incoming URLs such as "/users/john.j.joe" and <add> * "/users/john.j.joe.json"). <add> * <add> * <p>If enabled, this flag also enables <add> * {@link #setUseSuffixPatternMatch(boolean) useSuffixPatternMatch}. The <add> * default value is {@code false}. <add> */ <add> public void setUseRegisteredSuffixPatternMatch(boolean useRegsiteredSuffixPatternMatch) { <add> this.useRegisteredSuffixPatternMatch = useRegsiteredSuffixPatternMatch; <add> this.useSuffixPatternMatch = useRegsiteredSuffixPatternMatch ? true : this.useSuffixPatternMatch; <add> } <add> <ide> /** <ide> * Whether to match to URLs irrespective of the presence of a trailing slash. <ide> * If enabled a method mapped to "/users" also matches to "/users/". <ide> public void setUseTrailingSlashMatch(boolean useTrailingSlashMatch) { <ide> public void setContentNegotiationManager(ContentNegotiationManager contentNegotiationManager) { <ide> Assert.notNull(contentNegotiationManager); <ide> this.contentNegotiationManager = contentNegotiationManager; <del> this.contentNegotiationFileExtensions.addAll(contentNegotiationManager.getAllFileExtensions()); <ide> } <ide> <ide> /** <ide> public void setContentNegotiationManager(ContentNegotiationManager contentNegoti <ide> public boolean useSuffixPatternMatch() { <ide> return this.useSuffixPatternMatch; <ide> } <add> <add> /** <add> * Whether to use registered suffixes for pattern matching. <add> */ <add> public boolean useRegisteredSuffixPatternMatch() { <add> return useRegisteredSuffixPatternMatch; <add> } <add> <ide> /** <ide> * Whether to match to URLs irrespective of the presence of a trailing slash. <ide> */ <ide> public ContentNegotiationManager getContentNegotiationManager() { <ide> } <ide> <ide> /** <del> * Return the known file extensions for content negotiation. <add> * Return the file extensions to use for suffix pattern matching. <ide> */ <del> public List<String> getContentNegotiationFileExtensions() { <del> return this.contentNegotiationFileExtensions; <add> public List<String> getFileExtensions() { <add> return fileExtensions; <add> } <add> <add> @Override <add> public void afterPropertiesSet() { <add> super.afterPropertiesSet(); <add> if (this.useRegisteredSuffixPatternMatch) { <add> this.fileExtensions.addAll(contentNegotiationManager.getAllFileExtensions()); <add> } <ide> } <ide> <ide> /** <ide> protected RequestCondition<?> getCustomMethodCondition(Method method) { <ide> private RequestMappingInfo createRequestMappingInfo(RequestMapping annotation, RequestCondition<?> customCondition) { <ide> return new RequestMappingInfo( <ide> new PatternsRequestCondition(annotation.value(), getUrlPathHelper(), getPathMatcher(), <del> this.useSuffixPatternMatch, this.useTrailingSlashMatch, this.contentNegotiationFileExtensions), <add> this.useSuffixPatternMatch, this.useTrailingSlashMatch, this.fileExtensions), <ide> new RequestMethodsRequestCondition(annotation.method()), <ide> new ParamsRequestCondition(annotation.params()), <ide> new HeadersRequestCondition(annotation.headers()), <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMappingTests.java <add>/* <add> * Copyright 2002-2012 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>package org.springframework.web.servlet.mvc.method.annotation; <add> <add>import static org.junit.Assert.*; <add> <add>import java.util.Arrays; <add>import java.util.Collections; <add>import java.util.Map; <add> <add>import org.junit.Before; <add>import org.junit.Test; <add>import org.springframework.http.MediaType; <add>import org.springframework.web.accept.ContentNegotiationManager; <add>import org.springframework.web.accept.PathExtensionContentNegotiationStrategy; <add>import org.springframework.web.context.support.StaticWebApplicationContext; <add>import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; <add> <add>/** <add> * Tests for {@link RequestMappingHandlerMapping}. <add> * <add> * @author Rossen Stoyanchev <add> */ <add>public class RequestMappingHandlerMappingTests { <add> <add> private RequestMappingHandlerMapping handlerMapping; <add> <add> @Before <add> public void setup() { <add> this.handlerMapping = new RequestMappingHandlerMapping(); <add> this.handlerMapping.setApplicationContext(new StaticWebApplicationContext()); <add> } <add> <add> @Test <add> public void useRegsiteredSuffixPatternMatch() { <add> assertTrue(this.handlerMapping.useSuffixPatternMatch()); <add> assertFalse(this.handlerMapping.useRegisteredSuffixPatternMatch()); <add> <add> Map<String, MediaType> fileExtensions = Collections.singletonMap("json", MediaType.APPLICATION_JSON); <add> PathExtensionContentNegotiationStrategy strategy = new PathExtensionContentNegotiationStrategy(fileExtensions); <add> ContentNegotiationManager manager = new ContentNegotiationManager(strategy); <add> <add> this.handlerMapping.setContentNegotiationManager(manager); <add> this.handlerMapping.setUseRegisteredSuffixPatternMatch(true); <add> this.handlerMapping.afterPropertiesSet(); <add> <add> assertTrue(this.handlerMapping.useSuffixPatternMatch()); <add> assertTrue(this.handlerMapping.useRegisteredSuffixPatternMatch()); <add> assertEquals(Arrays.asList("json"), this.handlerMapping.getFileExtensions()); <add> } <add> <add> @Test <add> public void useSuffixPatternMatch() { <add> assertTrue(this.handlerMapping.useSuffixPatternMatch()); <add> <add> this.handlerMapping.setUseSuffixPatternMatch(false); <add> assertFalse(this.handlerMapping.useSuffixPatternMatch()); <add> <add> this.handlerMapping.setUseRegisteredSuffixPatternMatch(false); <add> assertFalse("'false' registeredSuffixPatternMatch shouldn't impact suffixPatternMatch", <add> this.handlerMapping.useSuffixPatternMatch()); <add> <add> this.handlerMapping.setUseRegisteredSuffixPatternMatch(true); <add> assertTrue("'true' registeredSuffixPatternMatch should enable suffixPatternMatch", <add> this.handlerMapping.useSuffixPatternMatch()); <add> } <add> <add>}
2
Text
Text
use lowercase for zlib
005363ad372cf6f98572f0d0da3caf9b74448fde
<ide><path>doc/api/index.md <ide> * [V8](v8.html) <ide> * [VM](vm.html) <ide> * [Worker Threads](worker_threads.html) <del>* [ZLIB](zlib.html) <add>* [Zlib](zlib.html) <ide> <ide> <div class="line"></div> <ide>
1
PHP
PHP
add relation not found exception
f8ead240b1c9af58365ee885807cf950ca5f66d5
<ide><path>src/Illuminate/Database/Eloquent/Builder.php <ide> <ide> namespace Illuminate\Database\Eloquent; <ide> <add>use BadMethodCallException; <ide> use Closure; <ide> use Illuminate\Support\Arr; <ide> use Illuminate\Support\Str; <ide> public function getRelation($name) <ide> // not have to remove these where clauses manually which gets really hacky <ide> // and is error prone while we remove the developer's own where clauses. <ide> $relation = Relation::noConstraints(function () use ($name) { <del> return $this->getModel()->$name(); <add> try { <add> return $this->getModel()->$name(); <add> } catch (BadMethodCallException $e) { <add> throw new RelationNotFoundException("Call to undefined relationship {$name} on Model {$this->getModel()}"); <add> } <ide> }); <ide> <ide> $nested = $this->nestedRelations($name); <ide><path>src/Illuminate/Database/Eloquent/RelationNotFoundException.php <add><?php <add> <add>namespace Illuminate\Database\Eloquent; <add> <add>use RuntimeException; <add> <add>class RelationNotFoundException extends RuntimeException <add>{ <add> // <add>} <ide>\ No newline at end of file <ide><path>tests/Database/DatabaseEloquentBuilderTest.php <ide> public function testGetRelationProperlySetsNestedRelationshipsWithSimilarNames() <ide> $relation = $builder->getRelation('ordersGroups'); <ide> } <ide> <add> /** <add> * @expectedException Illuminate\Database\Eloquent\RelationNotFoundException <add> */ <add> public function testGetRelationThrowsException() <add> { <add> $builder = $this->getBuilder(); <add> $builder->setModel($this->getMockModel()); <add> <add> $builder->getRelation( 'invalid' ); <add> } <add> <ide> public function testEagerLoadParsingSetsProperRelationships() <ide> { <ide> $builder = $this->getBuilder();
3
Text
Text
fix dependencyparser.predict docs (resolves )
6cfa1e1f47e8963519ff974eebe17ed414a4c2c5
<ide><path>website/docs/api/dependencyparser.md <ide> Apply the pipeline's model to a batch of docs, without modifying them. <ide> > scores = parser.predict([doc1, doc2]) <ide> > ``` <ide> <del>| Name | Type | Description | <del>| ----------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | <del>| `docs` | iterable | The documents to predict. | <del>| **RETURNS** | tuple | A `(scores, tensors)` tuple where `scores` is the model's prediction for each document and `tensors` is the token representations used to predict the scores. Each tensor is an array with one row for each token in the document. | <add>| Name | Type | Description | <add>| ----------- | ------------------- | ---------------------------------------------- | <add>| `docs` | iterable | The documents to predict. | <add>| **RETURNS** | `syntax.StateClass` | A helper class for the parse state (internal). | <ide> <ide> ## DependencyParser.set_annotations {#set_annotations tag="method"} <ide>
1
Javascript
Javascript
replace common.fixturesdir w/common.fixtures
4716a9d3494037beadef3400a8b3a8f3f5e2af91
<ide><path>test/parallel/test-module-require-depth.js <ide> // Flags: --expose_internals <ide> 'use strict'; <del>const common = require('../common'); <add>require('../common'); <add>const fixtures = require('../common/fixtures'); <ide> const assert = require('assert'); <ide> const internalModule = require('internal/module'); <ide> <ide> // Module one loads two too so the expected depth for two is, well, two. <ide> assert.strictEqual(internalModule.requireDepth, 0); <del>const one = require(`${common.fixturesDir}/module-require-depth/one`); <del>const two = require(`${common.fixturesDir}/module-require-depth/two`); <add>const one = require(fixtures.path('module-require-depth', 'one')); <add>const two = require(fixtures.path('module-require-depth', 'two')); <ide> assert.deepStrictEqual(one, { requireDepth: 1 }); <ide> assert.deepStrictEqual(two, { requireDepth: 2 }); <ide> assert.strictEqual(internalModule.requireDepth, 0);
1
Ruby
Ruby
add support for ordering on expressions
85882d1b26b033afb2643865afe6410673949d32
<ide><path>lib/arel.rb <ide> require 'arel/expressions' <ide> require 'arel/predications' <ide> require 'arel/math' <add>require 'arel/order_predications' <ide> require 'arel/table' <ide> require 'arel/attributes' <ide> require 'arel/compatibility/wheres' <ide><path>lib/arel/attributes/attribute.rb <ide> module Attributes <ide> class Attribute < Struct.new :relation, :name <ide> include Arel::Expressions <ide> include Arel::Predications <add> include Arel::OrderPredications <ide> include Arel::Math <ide> <ide> ### <ide><path>lib/arel/expression.rb <ide> module Arel <ide> module Expression <add> include Arel::OrderPredications <ide> end <ide> end <ide><path>lib/arel/nodes/sql_literal.rb <ide> module Nodes <ide> class SqlLiteral < String <ide> include Arel::Expressions <ide> include Arel::Predications <add> include Arel::OrderPredications <ide> end <ide> end <ide> end <ide><path>lib/arel/order_predications.rb <add>module Arel <add> module OrderPredications <add> <add> def asc <add> Nodes::Ordering.new self, :asc <add> end <add> <add> def desc <add> Nodes::Ordering.new self, :desc <add> end <add> <add> end <add>end <ide><path>lib/arel/predications.rb <ide> module Arel <ide> module Predications <add> <ide> def as other <ide> Nodes::As.new self, Nodes::SqlLiteral.new(other) <ide> end <ide> def lteq_all others <ide> grouping_all :lteq, others <ide> end <ide> <del> def asc <del> Nodes::Ordering.new self, :asc <del> end <del> <del> def desc <del> Nodes::Ordering.new self, :desc <del> end <del> <ide> private <ide> <ide> def grouping_any method_id, others <ide><path>test/test_select_manager.rb <ide> def test_join_sources <ide> manager = Arel::SelectManager.new Table.engine <ide> manager.order(table[:id]).must_equal manager <ide> end <add> <add> it 'has order attributes' do <add> table = Table.new :users <add> manager = Arel::SelectManager.new Table.engine <add> manager.project SqlLiteral.new '*' <add> manager.from table <add> manager.order table[:id].desc <add> manager.to_sql.must_be_like %{ <add> SELECT * FROM "users" ORDER BY "users"."id" DESC <add> } <add> end <add> <add> it 'has order attributes for expressions' do <add> table = Table.new :users <add> manager = Arel::SelectManager.new Table.engine <add> manager.project SqlLiteral.new '*' <add> manager.from table <add> manager.order table[:id].count.desc <add> manager.to_sql.must_be_like %{ <add> SELECT * FROM "users" ORDER BY COUNT("users"."id") DESC <add> } <add> end <add> <ide> end <ide> <ide> describe 'on' do
7
Java
Java
improve handlermethod#bridgedmethod initialization
caf88ff2cc311b345f5fc0a5ced54d24bd9d553f
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/handler/HandlerMethod.java <ide> /* <del> * Copyright 2002-2019 the original author or authors. <add> * Copyright 2002-2021 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import org.springframework.util.Assert; <ide> import org.springframework.util.ClassUtils; <ide> import org.springframework.util.ObjectUtils; <add>import org.springframework.util.ReflectionUtils; <ide> import org.springframework.util.StringUtils; <ide> <ide> /** <ide> public HandlerMethod(Object bean, Method method) { <ide> this.beanType = ClassUtils.getUserClass(bean); <ide> this.method = method; <ide> this.bridgedMethod = BridgeMethodResolver.findBridgedMethod(method); <add> ReflectionUtils.makeAccessible(this.bridgedMethod); <ide> this.parameters = initMethodParameters(); <ide> } <ide> <ide> public HandlerMethod(Object bean, String methodName, Class<?>... parameterTypes) <ide> this.beanType = ClassUtils.getUserClass(bean); <ide> this.method = bean.getClass().getMethod(methodName, parameterTypes); <ide> this.bridgedMethod = BridgeMethodResolver.findBridgedMethod(this.method); <add> ReflectionUtils.makeAccessible(this.bridgedMethod); <ide> this.parameters = initMethodParameters(); <ide> } <ide> <ide> public HandlerMethod(String beanName, BeanFactory beanFactory, Method method) { <ide> this.beanType = ClassUtils.getUserClass(beanType); <ide> this.method = method; <ide> this.bridgedMethod = BridgeMethodResolver.findBridgedMethod(method); <add> ReflectionUtils.makeAccessible(this.bridgedMethod); <ide> this.parameters = initMethodParameters(); <ide> } <ide> <ide><path>spring-messaging/src/main/java/org/springframework/messaging/handler/invocation/InvocableHandlerMethod.java <ide> /* <del> * Copyright 2002-2019 the original author or authors. <add> * Copyright 2002-2021 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import org.springframework.messaging.Message; <ide> import org.springframework.messaging.handler.HandlerMethod; <ide> import org.springframework.util.ObjectUtils; <del>import org.springframework.util.ReflectionUtils; <ide> <ide> /** <ide> * Extension of {@link HandlerMethod} that invokes the underlying method with <ide> protected Object[] getMethodArgumentValues(Message<?> message, Object... provide <ide> */ <ide> @Nullable <ide> protected Object doInvoke(Object... args) throws Exception { <del> ReflectionUtils.makeAccessible(getBridgedMethod()); <ide> try { <ide> return getBridgedMethod().invoke(getBean(), args); <ide> } <ide><path>spring-messaging/src/main/java/org/springframework/messaging/handler/invocation/reactive/InvocableHandlerMethod.java <ide> /* <del> * Copyright 2002-2019 the original author or authors. <add> * Copyright 2002-2021 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import org.springframework.messaging.handler.HandlerMethod; <ide> import org.springframework.messaging.handler.invocation.MethodArgumentResolutionException; <ide> import org.springframework.util.ObjectUtils; <del>import org.springframework.util.ReflectionUtils; <ide> <ide> /** <ide> * Extension of {@link HandlerMethod} that invokes the underlying method with <ide> public Mono<Object> invoke(Message<?> message, Object... providedArgs) { <ide> boolean isSuspendingFunction = false; <ide> try { <ide> Method method = getBridgedMethod(); <del> ReflectionUtils.makeAccessible(method); <ide> if (KotlinDetector.isSuspendingFunction(method)) { <ide> isSuspendingFunction = true; <ide> value = CoroutinesUtils.invokeSuspendingFunction(method, getBean(), args); <ide><path>spring-web/src/main/java/org/springframework/web/method/HandlerMethod.java <ide> import org.springframework.util.Assert; <ide> import org.springframework.util.ClassUtils; <ide> import org.springframework.util.ObjectUtils; <add>import org.springframework.util.ReflectionUtils; <ide> import org.springframework.util.StringUtils; <ide> import org.springframework.web.bind.annotation.ResponseStatus; <ide> <ide> protected HandlerMethod(Object bean, Method method, @Nullable MessageSource mess <ide> this.beanType = ClassUtils.getUserClass(bean); <ide> this.method = method; <ide> this.bridgedMethod = BridgeMethodResolver.findBridgedMethod(method); <add> ReflectionUtils.makeAccessible(this.bridgedMethod); <ide> this.parameters = initMethodParameters(); <ide> evaluateResponseStatus(); <ide> this.description = initDescription(this.beanType, this.method); <ide> public HandlerMethod(Object bean, String methodName, Class<?>... parameterTypes) <ide> this.beanType = ClassUtils.getUserClass(bean); <ide> this.method = bean.getClass().getMethod(methodName, parameterTypes); <ide> this.bridgedMethod = BridgeMethodResolver.findBridgedMethod(this.method); <add> ReflectionUtils.makeAccessible(this.bridgedMethod); <ide> this.parameters = initMethodParameters(); <ide> evaluateResponseStatus(); <ide> this.description = initDescription(this.beanType, this.method); <ide> public HandlerMethod( <ide> this.beanType = ClassUtils.getUserClass(beanType); <ide> this.method = method; <ide> this.bridgedMethod = BridgeMethodResolver.findBridgedMethod(method); <add> ReflectionUtils.makeAccessible(this.bridgedMethod); <ide> this.parameters = initMethodParameters(); <ide> evaluateResponseStatus(); <ide> this.description = initDescription(this.beanType, this.method); <ide><path>spring-web/src/main/java/org/springframework/web/method/support/InvocableHandlerMethod.java <ide> import org.springframework.core.ParameterNameDiscoverer; <ide> import org.springframework.lang.Nullable; <ide> import org.springframework.util.ObjectUtils; <del>import org.springframework.util.ReflectionUtils; <ide> import org.springframework.web.bind.WebDataBinder; <ide> import org.springframework.web.bind.support.SessionStatus; <ide> import org.springframework.web.bind.support.WebDataBinderFactory; <ide> protected Object[] getMethodArgumentValues(NativeWebRequest request, @Nullable M <ide> @Nullable <ide> protected Object doInvoke(Object... args) throws Exception { <ide> Method method = getBridgedMethod(); <del> ReflectionUtils.makeAccessible(method); <ide> try { <ide> if (KotlinDetector.isSuspendingFunction(method)) { <ide> return CoroutinesUtils.invokeSuspendingFunction(method, getBean(), args); <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/method/InvocableHandlerMethod.java <ide> /* <del> * Copyright 2002-2020 the original author or authors. <add> * Copyright 2002-2021 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import org.springframework.http.server.reactive.ServerHttpResponse; <ide> import org.springframework.lang.Nullable; <ide> import org.springframework.util.ObjectUtils; <del>import org.springframework.util.ReflectionUtils; <ide> import org.springframework.web.method.HandlerMethod; <ide> import org.springframework.web.reactive.BindingContext; <ide> import org.springframework.web.reactive.HandlerResult; <ide> public Mono<HandlerResult> invoke( <ide> return getMethodArgumentValues(exchange, bindingContext, providedArgs).flatMap(args -> { <ide> Object value; <ide> try { <del> ReflectionUtils.makeAccessible(getBridgedMethod()); <ide> Method method = getBridgedMethod(); <ide> if (KotlinDetector.isSuspendingFunction(method)) { <ide> value = CoroutinesUtils.invokeSuspendingFunction(method, getBean(), args);
6
Javascript
Javascript
fix some iframe edge cases
9c961c0a279e31015b8df987bd86e6fec7548614
<ide><path>packages/react-dom/src/client/ReactDOMSelection.js <ide> export function getModernOffsetsFromPoints( <ide> */ <ide> export function setOffsets(node, offsets) { <ide> const doc = node.ownerDocument || document; <del> const win = doc ? doc.defaultView : window; <add> const win = (doc && doc.defaultView) || window; <ide> const selection = win.getSelection(); <ide> const length = node.textContent.length; <ide> let start = Math.min(offsets.start, length);
1
Ruby
Ruby
fix post-bottling dylib id relocation
c7de544fe8b7671a02399b895abfdeb8823f982c
<ide><path>Library/Homebrew/extend/os/mac/keg_relocate.rb <ide> def relocate_dynamic_linkage(relocation) <ide> mach_o_files.each do |file| <ide> file.ensure_writable do <ide> if file.dylib? <del> id = relocated_name_for(dylib_id_for(file), relocation) <del> change_dylib_id(id, file) if id <add> id = relocated_name_for(file.dylib_id, relocation) <add> change_dylib_id(id, file) <ide> end <ide> <ide> each_install_name_for(file) do |old_name|
1
Ruby
Ruby
remove unused "developer" fixtures from tests
3502e6ed7c7a720e6b4d358d9ff7b3242e52a36f
<ide><path>activerecord/test/cases/callbacks_test.rb <ide> class ChildDeveloper < ParentDeveloper <ide> <ide> end <ide> <del>class RecursiveCallbackDeveloper < ActiveRecord::Base <del> self.table_name = 'developers' <del> <del> before_save :on_before_save <del> after_save :on_after_save <del> <del> attr_reader :on_before_save_called, :on_after_save_called <del> <del> def on_before_save <del> @on_before_save_called ||= 0 <del> @on_before_save_called += 1 <del> save unless @on_before_save_called > 1 <del> end <del> <del> def on_after_save <del> @on_after_save_called ||= 0 <del> @on_after_save_called += 1 <del> save unless @on_after_save_called > 1 <del> end <del>end <del> <ide> class ImmutableDeveloper < ActiveRecord::Base <ide> self.table_name = 'developers' <ide> <ide> class ImmutableDeveloper < ActiveRecord::Base <ide> before_save :cancel <ide> before_destroy :cancel <ide> <del> def cancelled? <del> @cancelled == true <del> end <del> <ide> private <ide> def cancel <del> @cancelled = true <ide> false <ide> end <ide> end <ide> <del>class ImmutableMethodDeveloper < ActiveRecord::Base <del> self.table_name = 'developers' <del> <del> validates_inclusion_of :salary, :in => 50000..200000 <del> <del> def cancelled? <del> @cancelled == true <del> end <del> <del> before_save do <del> @cancelled = true <del> false <del> end <del> <del> before_destroy do <del> @cancelled = true <del> false <del> end <del>end <del> <ide> class OnCallbacksDeveloper < ActiveRecord::Base <ide> self.table_name = 'developers' <ide>
1
Text
Text
fix example for animation
c91f95a092051c44bb9e241f7551f47cfdce8e36
<ide><path>docs/docs/09.1-animation.md <ide> React provides a `ReactTransitionGroup` addon component as a low-level API for a <ide> <ide> `ReactCSSTransitionGroup` is the interface to `ReactTransitions`. This is a simple element that wraps all of the components you are interested in animating. Here's an example where we fade list items in and out. <ide> <del>```javascript{22-24} <add>```javascript{30-32} <ide> /** @jsx React.DOM */ <ide> <ide> var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup; <ide> var TodoList = React.createClass({ <ide> }, <ide> handleRemove: function(i) { <ide> var newItems = this.state.items; <del> newItems.splice(i, 1) <add> newItems.splice(i, 1); <ide> this.setState({items: newItems}); <ide> }, <ide> render: function() { <ide> var TodoList = React.createClass({ <ide> }.bind(this)); <ide> return ( <ide> <div> <del> <div><button onClick={this.handleAdd} /></div> <add> <button onClick={this.handleAdd}>Add Item</button> <ide> <ReactCSSTransitionGroup transitionName="example"> <ide> {items} <ide> </ReactCSSTransitionGroup>
1
Text
Text
add relay blog post
531add88c4862e3cbe62d11d4b87e04d8292dd3b
<ide><path>docs/_posts/2015-02-20-introducing-relay-and-graphql.md <add>--- <add>title: "Introducing Relay and GraphQL" <add>layout: post <add>author: Greg Hurrell <add>--- <add> <add>## Data fetching for React applications <add> <add>There's more to building an application than creating a user interface. Data fetching is still a tricky problem, especially as applications become more complicated. At [React.js Conf](http://conf.reactjs.com/) we announced two projects we've created at Facebook to make data fetching simple for developers, even as a product grows to include dozens of contributors and the application becomes as complex as Facebook itself. <add> <add><iframe width="560" height="315" src="https://www.youtube.com/embed/9sc8Pyc51uU" frameborder="0" allowfullscreen></iframe> <add> <add>The two projects &mdash; Relay and GraphQL &mdash; have been in use in production at Facebook for some time, and we're excited to be bringing them to the world as open source in the future. In the meantime, we wanted to share some additional information about the projects here. <add> <add><script async class="speakerdeck-embed" data-id="7af7c2f33bf9451a892dcd91de55b7c2" data-ratio="1.29456384323641" src="//speakerdeck.com/assets/embed.js"></script> <add> <add>## What is Relay? <add> <add>Relay is a new framework from Facebook that provides data-fetching functionality for React applications. It was announced at React.js Conf (January 2015). <add> <add>Each component specifies its own data dependencies declaratively using a query language called GraphQL. The data is made available to the component via properties on `this.props`. <add> <add>Developers compose these React components naturally, and Relay takes care of composing the data queries into efficient batches, providing each component with exactly the data that it requested (and no more), updating those components when the data changes, and maintaining a client-side store (cache) of all data. <add> <add>## What is GraphQL? <add> <add>GraphQL is a data querying language designed to describe the complex, nested data dependencies of modern applications. It's been in production use in Facebook's native apps for several years. <add> <add>On the server, we configure the GraphQL system to map queries to underlying data-fetching code. This configuration layer allows GraphQL to work with arbitrary underlying storage mechanisms. Relay uses GraphQL as its query language, but it is not tied to a specific implementation of GraphQL. <add> <add>## The value proposition <add> <add>Relay was born out of our experiences building large applications at Facebook. Our overarching goal is to enable developers to create correct, high-performance applications in a straightforward and obvious way. The design enables even large teams to make changes with a high degree of isolation and confidence. Fetching data is hard, dealing with ever-changing data is hard, and performance is hard. Relay aims to reduce these problems to simple ones, moving the tricky bits into the framework and freeing you to concentrate on building your application. <add> <add>By co-locating the queries with the view code, the developer can reason about what a component is doing by looking at it in isolation; it's not necessary to consider the context where the component was rendered in order to understand it. Components can be moved anywhere in a render hierarchy without having to apply a cascade of modifications to parent components or to the server code which prepares the data payload. <add> <add>Co-location leads developers to fall into the "pit of success", because they get exactly the data they asked for and the data they asked for is explicitly defined right next to where it is used. This means that performance becomes the default (it becomes much harder to accidentally over-fetch), and components are more robust (under-fetching is also less likely for the same reason, so components won't try to render missing data and blow up at runtime). <add> <add>Relay provides a predictable environment for developers by maintaining an invariant: a component won't be rendered until all the data it requested is available. Additionally, queries are defined statically (ie. we can extract queries from a component tree before rendering) and the GraphQL schema provides an authoritative description of what queries are valid, so we can validate queries early and fail fast when the developer makes a mistake. <add> <add>Only the fields of an object that a component explicitly asks for will be accessible to that component, even if other fields are known and cached in the store (because another component requested them). This makes it impossible for implicit data dependency bugs to exist latently in the system. <add> <add>By handling all data-fetching via a single abstraction, we're able to handle a bunch of things that would otherwise have to be dealt with repeatedly and pervasively across the application: <add> <add>- **Performance:** All queries flow through the framework code, where things that would otherwise be inefficient, repeated query patterns get automatically collapsed and batched into efficient, minimal queries. Likewise, the framework knows which data have been previously requested, or for which requests are currently "in flight", so queries can be automatically de-duplicated and the minimal queries can be produced. <add>- **Subscriptions:** All data flows into a single store, and all reads from the store are via the framework. This means the framework knows which components care about which data and which should be re-rendered when data changes; components never have to set up individual subscriptions. <add>- **Common patterns:** We can make common patterns easy. Pagination is the example that [Jing](https://twitter.com/jingc) gave at the conference: if you have 10 records initially, getting the next page just means declaring you want 15 records in total, and the framework automatically constructs the minimal query to grab the delta between what you have and what you need, requests it, and re-renders your view when the data become available. <add>- **Simplified server implementation:** Rather than having a proliferation of end-points (per action, per route), a single GraphQL endpoint can serve as a facade for any number of underlying resources. <add>- **Uniform mutations:** There is one consistent pattern for performing mutations (writes), and it is conceptually baked into the data querying model itself. You can think of a mutation as a query with side-effects: you provide some parameters that describe the change to be made (eg. attaching a comment to a record) and a query that specifies the data you'll need to update your view of the world after the mutation completes (eg. the comment count on the record), and the data flows through the system using the normal flow. We can do an immediate "optimistic" update on the client (ie. update the view under the assumption that the write will succeed), and finally commit it, retry it or roll it back in the event of an error when the server payload comes back. <add> <add>## How does it relate to Flux? <add> <add>In some ways Relay is inspired by Flux, but the mental model is much simpler. Instead of multiple stores, there is one central store that caches all GraphQL data. Instead of explicit subscriptions, the framework itself can track which data each component requests, and which components should be updated whenever the data change. Instead of actions, modifications take the form of mutations. <add> <add>At Facebook, we have apps built entirely using Flux, entirely using Relay, or with both. One pattern we see emerging is letting Relay manage the bulk of the data flow for an application, but using Flux stores on the side to handle a subset of application state. <add> <add>## Open source plans <add> <add>We're working very hard right now on getting both GraphQL (a spec, and a reference implementation) and Relay ready for public release (no specific dates yet, but we are super excited about getting these out there). <add> <add>In the meantime, we'll be providing more and more information in the form of blog posts (and in [other channels](https://gist.github.com/wincent/598fa75e22bdfa44cf47)). As we get closer to the open source release, you can expect more concrete details, syntax and API descriptions and more. <add> <add>Watch this space!
1
Python
Python
update help to > set flask_app=hello.py
a72583652329da810fc2a04e8541a0e2efd47ee1
<ide><path>flask/cli.py <ide> def shell_command(): <ide> Example usage: <ide> <ide> \b <del> %(prefix)s%(cmd)s FLASK_APP=hello <add> %(prefix)s%(cmd)s FLASK_APP=hello.py <ide> %(prefix)s%(cmd)s FLASK_DEBUG=1 <ide> %(prefix)sflask run <ide> """ % {
1
Python
Python
handle errors while multiprocessing
b120fb35113d95be25af9a6091a4a511d78254b5
<ide><path>spacy/errors.py <ide> class Errors: <ide> E202 = ("Unsupported alignment mode '{mode}'. Supported modes: {modes}.") <ide> <ide> # New errors added in v3.x <add> E871 = ("Error encountered in nlp.pipe with multiprocessing:\n\n{error}") <ide> E872 = ("Unable to copy tokenizer from base model due to different " <ide> 'tokenizer settings: current tokenizer config "{curr_config}" ' <ide> 'vs. base model "{base_config}"') <ide><path>spacy/language.py <ide> import multiprocessing as mp <ide> from itertools import chain, cycle <ide> from timeit import default_timer as timer <add>import traceback <ide> <ide> from .tokens.underscore import Underscore <ide> from .vocab import Vocab, create_vocab <ide> def _multiprocessing_pipe( <ide> <ide> # Cycle channels not to break the order of docs. <ide> # The received object is a batch of byte-encoded docs, so flatten them with chain.from_iterable. <del> byte_docs = chain.from_iterable(recv.recv() for recv in cycle(bytedocs_recv_ch)) <del> docs = (Doc(self.vocab).from_bytes(byte_doc) for byte_doc in byte_docs) <add> byte_tuples = chain.from_iterable(recv.recv() for recv in cycle(bytedocs_recv_ch)) <ide> try: <del> for i, (_, doc) in enumerate(zip(raw_texts, docs), 1): <del> yield doc <add> for i, (_, (byte_doc, byte_error)) in enumerate(zip(raw_texts, byte_tuples), 1): <add> if byte_doc is not None: <add> doc = Doc(self.vocab).from_bytes(byte_doc) <add> yield doc <add> elif byte_error is not None: <add> error = srsly.msgpack_loads(byte_error) <add> self.default_error_handler(None, None, None, ValueError(Errors.E871.format(error=error))) <ide> if i % batch_size == 0: <ide> # tell `sender` that one batch was consumed. <ide> sender.step() <ide> def _apply_pipes( <ide> """ <ide> Underscore.load_state(underscore_state) <ide> while True: <del> texts = receiver.get() <del> docs = (make_doc(text) for text in texts) <del> for pipe in pipes: <del> docs = pipe(docs) <del> # Connection does not accept unpickable objects, so send list. <del> sender.send([doc.to_bytes() for doc in docs]) <add> try: <add> texts = receiver.get() <add> docs = (make_doc(text) for text in texts) <add> for pipe in pipes: <add> docs = pipe(docs) <add> # Connection does not accept unpickable objects, so send list. <add> byte_docs = [(doc.to_bytes(), None) for doc in docs] <add> padding = [(None, None)] * (len(texts) - len(byte_docs)) <add> sender.send(byte_docs + padding) <add> except Exception: <add> error_msg = [(None, srsly.msgpack_dumps(traceback.format_exc()))] <add> padding = [(None, None)] * (len(texts) - 1) <add> sender.send(error_msg + padding) <ide> <ide> <ide> class _Sender: <ide><path>spacy/tests/test_language.py <ide> from spacy.training import Example <ide> from spacy.lang.en import English <ide> from spacy.lang.de import German <del>from spacy.util import registry, ignore_error, raise_error <add>from spacy.util import registry, ignore_error, raise_error, logger <ide> import spacy <ide> from thinc.api import NumpyOps, get_current_ops <ide> <ide> from .util import add_vecs_to_vocab, assert_docs_equal <ide> <ide> <add>def evil_component(doc): <add> if "2" in doc.text: <add> raise ValueError("no dice") <add> return doc <add> <add> <add>def perhaps_set_sentences(doc): <add> if not doc.text.startswith("4"): <add> doc[-1].is_sent_start = True <add> return doc <add> <add> <add>def assert_sents_error(doc): <add> if not doc.has_annotation("SENT_START"): <add> raise ValueError("no sents") <add> return doc <add> <add> <add>def warn_error(proc_name, proc, docs, e): <add> logger = logging.getLogger("spacy") <add> logger.warning(f"Trouble with component {proc_name}.") <add> <add> <ide> @pytest.fixture <ide> def nlp(): <ide> nlp = Language(Vocab()) <ide> def pipe(doc): <ide> nlp.evaluate([Example.from_dict(doc, annots)]) <ide> <ide> <del>@Language.component("test_language_vector_modification_pipe") <ide> def vector_modification_pipe(doc): <ide> doc.vector += 1 <ide> return doc <ide> <ide> <del>@Language.component("test_language_userdata_pipe") <ide> def userdata_pipe(doc): <ide> doc.user_data["foo"] = "bar" <ide> return doc <ide> <ide> <del>@Language.component("test_language_ner_pipe") <ide> def ner_pipe(doc): <ide> span = Span(doc, 0, 1, label="FIRST") <ide> doc.ents += (span,) <ide> def sample_vectors(): <ide> <ide> @pytest.fixture <ide> def nlp2(nlp, sample_vectors): <add> Language.component("test_language_vector_modification_pipe", func=vector_modification_pipe) <add> Language.component("test_language_userdata_pipe", func=userdata_pipe) <add> Language.component("test_language_ner_pipe", func=ner_pipe) <ide> add_vecs_to_vocab(nlp.vocab, sample_vectors) <ide> nlp.add_pipe("test_language_vector_modification_pipe") <ide> nlp.add_pipe("test_language_ner_pipe") <ide> def test_language_pipe_stream(nlp2, n_process, texts): <ide> assert_docs_equal(doc, expected_doc) <ide> <ide> <del>def test_language_pipe_error_handler(): <add>@pytest.mark.parametrize("n_process", [1, 2]) <add>def test_language_pipe_error_handler(n_process): <ide> """Test that the error handling of nlp.pipe works well""" <del> nlp = English() <del> nlp.add_pipe("merge_subtokens") <del> nlp.initialize() <del> texts = ["Curious to see what will happen to this text.", "And this one."] <del> # the pipeline fails because there's no parser <del> with pytest.raises(ValueError): <add> ops = get_current_ops() <add> if isinstance(ops, NumpyOps) or n_process < 2: <add> nlp = English() <add> nlp.add_pipe("merge_subtokens") <add> nlp.initialize() <add> texts = ["Curious to see what will happen to this text.", "And this one."] <add> # the pipeline fails because there's no parser <add> with pytest.raises(ValueError): <add> nlp(texts[0]) <add> with pytest.raises(ValueError): <add> list(nlp.pipe(texts, n_process=n_process)) <add> nlp.set_error_handler(raise_error) <add> with pytest.raises(ValueError): <add> list(nlp.pipe(texts, n_process=n_process)) <add> # set explicitely to ignoring <add> nlp.set_error_handler(ignore_error) <add> docs = list(nlp.pipe(texts, n_process=n_process)) <add> assert len(docs) == 0 <ide> nlp(texts[0]) <del> with pytest.raises(ValueError): <del> list(nlp.pipe(texts)) <del> nlp.set_error_handler(raise_error) <del> with pytest.raises(ValueError): <del> list(nlp.pipe(texts)) <del> # set explicitely to ignoring <del> nlp.set_error_handler(ignore_error) <del> docs = list(nlp.pipe(texts)) <del> assert len(docs) == 0 <del> nlp(texts[0]) <ide> <ide> <del>def test_language_pipe_error_handler_custom(en_vocab): <add>@pytest.mark.parametrize("n_process", [1, 2]) <add>def test_language_pipe_error_handler_custom(en_vocab, n_process): <ide> """Test the error handling of a custom component that has no pipe method""" <add> Language.component("my_evil_component", func=evil_component) <add> ops = get_current_ops() <add> if isinstance(ops, NumpyOps) or n_process < 2: <add> nlp = English() <add> nlp.add_pipe("my_evil_component") <add> texts = ["TEXT 111", "TEXT 222", "TEXT 333", "TEXT 342", "TEXT 666"] <add> with pytest.raises(ValueError): <add> # the evil custom component throws an error <add> list(nlp.pipe(texts)) <add> <add> nlp.set_error_handler(warn_error) <add> logger = logging.getLogger("spacy") <add> with mock.patch.object(logger, "warning") as mock_warning: <add> # the errors by the evil custom component raise a warning for each <add> # bad doc <add> docs = list(nlp.pipe(texts, n_process=n_process)) <add> # HACK/TODO? the warnings in child processes don't seem to be <add> # detected by the mock logger <add> if n_process == 1: <add> mock_warning.assert_called() <add> assert mock_warning.call_count == 2 <add> assert len(docs) + mock_warning.call_count == len(texts) <add> assert [doc.text for doc in docs] == ["TEXT 111", "TEXT 333", "TEXT 666"] <ide> <del> @Language.component("my_evil_component") <del> def evil_component(doc): <del> if "2" in doc.text: <del> raise ValueError("no dice") <del> return doc <del> <del> def warn_error(proc_name, proc, docs, e): <del> from spacy.util import logger <ide> <del> logger.warning(f"Trouble with component {proc_name}.") <add>@pytest.mark.parametrize("n_process", [1, 2]) <add>def test_language_pipe_error_handler_pipe(en_vocab, n_process): <add> """Test the error handling of a component's pipe method""" <add> Language.component("my_perhaps_sentences", func=perhaps_set_sentences) <add> Language.component("assert_sents_error", func=assert_sents_error) <add> ops = get_current_ops() <add> if isinstance(ops, NumpyOps) or n_process < 2: <add> texts = [f"{str(i)} is enough. Done" for i in range(100)] <add> nlp = English() <add> nlp.add_pipe("my_perhaps_sentences") <add> nlp.add_pipe("assert_sents_error") <add> nlp.initialize() <add> with pytest.raises(ValueError): <add> # assert_sents_error requires sentence boundaries, will throw an error otherwise <add> docs = list(nlp.pipe(texts, n_process=n_process, batch_size=10)) <add> nlp.set_error_handler(ignore_error) <add> docs = list(nlp.pipe(texts, n_process=n_process, batch_size=10)) <add> # we lose/ignore the failing 4,40-49 docs <add> assert len(docs) == 89 <ide> <del> nlp = English() <del> nlp.add_pipe("my_evil_component") <del> nlp.initialize() <del> texts = ["TEXT 111", "TEXT 222", "TEXT 333", "TEXT 342", "TEXT 666"] <del> with pytest.raises(ValueError): <del> # the evil custom component throws an error <del> list(nlp.pipe(texts)) <ide> <del> nlp.set_error_handler(warn_error) <del> logger = logging.getLogger("spacy") <del> with mock.patch.object(logger, "warning") as mock_warning: <del> # the errors by the evil custom component raise a warning for each bad batch <del> docs = list(nlp.pipe(texts)) <del> mock_warning.assert_called() <del> assert mock_warning.call_count == 2 <del> assert len(docs) + mock_warning.call_count == len(texts) <del> assert [doc.text for doc in docs] == ["TEXT 111", "TEXT 333", "TEXT 666"] <add>@pytest.mark.parametrize("n_process", [1, 2]) <add>def test_language_pipe_error_handler_make_doc_actual(n_process): <add> """Test the error handling for make_doc""" <add> # TODO: fix so that the following test is the actual behavior <ide> <add> ops = get_current_ops() <add> if isinstance(ops, NumpyOps) or n_process < 2: <add> nlp = English() <add> nlp.max_length = 10 <add> texts = ["12345678901234567890", "12345"] * 10 <add> with pytest.raises(ValueError): <add> list(nlp.pipe(texts, n_process=n_process)) <add> nlp.default_error_handler = ignore_error <add> if n_process == 1: <add> with pytest.raises(ValueError): <add> list(nlp.pipe(texts, n_process=n_process)) <add> else: <add> docs = list(nlp.pipe(texts, n_process=n_process)) <add> assert len(docs) == 0 <ide> <del>def test_language_pipe_error_handler_pipe(en_vocab): <del> """Test the error handling of a component's pipe method""" <ide> <del> @Language.component("my_sentences") <del> def perhaps_set_sentences(doc): <del> if not doc.text.startswith("4"): <del> doc[-1].is_sent_start = True <del> return doc <add>@pytest.mark.xfail <add>@pytest.mark.parametrize("n_process", [1, 2]) <add>def test_language_pipe_error_handler_make_doc_preferred(n_process): <add> """Test the error handling for make_doc""" <ide> <del> texts = [f"{str(i)} is enough. Done" for i in range(100)] <del> nlp = English() <del> nlp.add_pipe("my_sentences") <del> entity_linker = nlp.add_pipe("entity_linker", config={"entity_vector_length": 3}) <del> entity_linker.kb.add_entity(entity="Q1", freq=12, entity_vector=[1, 2, 3]) <del> nlp.initialize() <del> with pytest.raises(ValueError): <del> # the entity linker requires sentence boundaries, will throw an error otherwise <del> docs = list(nlp.pipe(texts, batch_size=10)) <del> nlp.set_error_handler(ignore_error) <del> docs = list(nlp.pipe(texts, batch_size=10)) <del> # we lose/ignore the failing 0-9 and 40-49 batches <del> assert len(docs) == 80 <add> ops = get_current_ops() <add> if isinstance(ops, NumpyOps) or n_process < 2: <add> nlp = English() <add> nlp.max_length = 10 <add> texts = ["12345678901234567890", "12345"] * 10 <add> with pytest.raises(ValueError): <add> list(nlp.pipe(texts, n_process=n_process)) <add> nlp.default_error_handler = ignore_error <add> docs = list(nlp.pipe(texts, n_process=n_process)) <add> assert len(docs) == 0 <ide> <ide> <ide> def test_language_from_config_before_after_init():
3
Go
Go
move validation into parsenetworkoptions()
4e39cdd9bbbf6600a435200c8f19d57bf6fd31fa
<ide><path>libnetwork/drivers/ipvlan/ipvlan_network.go <ide> func (d *driver) CreateNetwork(nid string, option map[string]interface{}, nInfo <ide> } <ide> config.processIPAM(ipV4Data, ipV6Data) <ide> <del> // verify the ipvlan mode from -o ipvlan_mode option <del> switch config.IpvlanMode { <del> case "", modeL2: <del> // default to ipvlan L2 mode if -o ipvlan_mode is empty <del> config.IpvlanMode = modeL2 <del> case modeL3: <del> config.IpvlanMode = modeL3 <del> case modeL3S: <del> config.IpvlanMode = modeL3S <del> default: <del> return fmt.Errorf("requested ipvlan mode '%s' is not valid, 'l2' mode is the ipvlan driver default", config.IpvlanMode) <del> } <del> // verify the ipvlan flag from -o ipvlan_flag option <del> switch config.IpvlanFlag { <del> case "", flagBridge: <del> // default to bridge if -o ipvlan_flag is empty <del> config.IpvlanFlag = flagBridge <del> case flagPrivate: <del> config.IpvlanFlag = flagPrivate <del> case flagVepa: <del> config.IpvlanFlag = flagVepa <del> default: <del> return fmt.Errorf("requested ipvlan flag '%s' is not valid, 'bridge' is the ipvlan driver default", config.IpvlanFlag) <del> } <del> // loopback is not a valid parent link <del> if config.Parent == "lo" { <del> return fmt.Errorf("loopback interface is not a valid %s parent link", ipvlanType) <del> } <ide> // if parent interface not specified, create a dummy type link to use named dummy+net_id <ide> if config.Parent == "" { <ide> config.Parent = getDummyName(stringid.TruncateID(config.ID)) <ide> func parseNetworkOptions(id string, option options.Generic) (*configuration, err <ide> config.Internal = true <ide> } <ide> } <add> <add> // verify the ipvlan mode from -o ipvlan_mode option <add> switch config.IpvlanMode { <add> case "": <add> // default to ipvlan L2 mode if -o ipvlan_mode is empty <add> config.IpvlanMode = modeL2 <add> case modeL2, modeL3, modeL3S: <add> // valid option <add> default: <add> return nil, fmt.Errorf("requested ipvlan mode '%s' is not valid, 'l2' mode is the ipvlan driver default", config.IpvlanMode) <add> } <add> <add> // verify the ipvlan flag from -o ipvlan_flag option <add> switch config.IpvlanFlag { <add> case "": <add> // default to bridge if -o ipvlan_flag is empty <add> config.IpvlanFlag = flagBridge <add> case flagBridge, flagPrivate, flagVepa: <add> // valid option <add> default: <add> return nil, fmt.Errorf("requested ipvlan flag '%s' is not valid, 'bridge' is the ipvlan driver default", config.IpvlanFlag) <add> } <add> <add> // loopback is not a valid parent link <add> if config.Parent == "lo" { <add> return nil, fmt.Errorf("loopback interface is not a valid ipvlan parent link") <add> } <add> <ide> config.ID = id <ide> return config, nil <ide> }
1
Go
Go
reset the encryption keys on swarm leave
6e965c03ad0f6c3eda701c1de203b143beb94aa7
<ide><path>libnetwork/agent.go <ide> func (c *controller) agentClose() { <ide> c.agent.epTblCancel() <ide> <ide> c.agent.networkDB.Close() <add> <add> c.Lock() <ide> c.agent = nil <add> c.Unlock() <ide> } <ide> <ide> func (n *network) isClusterEligible() bool { <ide><path>libnetwork/controller.go <ide> func (c *controller) clusterAgentInit() { <ide> c.Lock() <ide> c.clusterConfigAvailable = false <ide> c.agentInitDone = make(chan struct{}) <add> c.keys = nil <ide> c.Unlock() <ide> <ide> if err := c.ingressSandbox.Delete(); err != nil { <ide> log.Warnf("Could not delete ingress sandbox while leaving: %v", err) <ide> } <ide> <add> c.Lock() <ide> c.ingressSandbox = nil <add> c.Unlock() <ide> <ide> n, err := c.NetworkByName("ingress") <ide> if err != nil {
2
Javascript
Javascript
add detox tests for switch
4dea677b4fd8ea8841bbe34c99e307557773cd04
<add><path>RNTester/e2e/__tests__/Button-test.js <del><path>RNTester/e2e/__tests__/sanity-test.js <ide> * <ide> * This source code is licensed under the MIT license found in the <ide> * LICENSE file in the root directory of this source tree. <add> * <add> * @emails oncall+react_native <add> * @format <ide> */ <ide> <del>/* global device, element, by, expect */ <add>/* global element, by, expect */ <ide> <del>describe('Sanity', () => { <del> beforeEach(async () => { <del> await device.reloadReactNative(); <del> await element(by.label('<Button> Simple React Native button component.')).tap(); <add>describe('Button', () => { <add> beforeAll(async () => { <add> await element(by.id('explorer_search')).replaceText('<Button>'); <add> await element( <add> by.label('<Button> Simple React Native button component.'), <add> ).tap(); <ide> }); <ide> <del> afterEach(async () => { <add> afterAll(async () => { <ide> //TODO - remove app state persistency, till then, we must go back to main screen, <ide> await element(by.label('Back')).tap(); <ide> }); <ide> describe('Sanity', () => { <ide> <ide> it('Disabled button should not interact', async () => { <ide> await element(by.label('I Am Disabled')).tap(); <del> await expect(element(by.text('Disabled has been pressed!'))).toBeNotVisible(); <add> await expect( <add> element(by.text('Disabled has been pressed!')), <add> ).toBeNotVisible(); <ide> }); <ide> }); <ide><path>RNTester/e2e/__tests__/Switch-test.js <add>/** <add> * Copyright (c) Facebook, Inc. and its affiliates. <add> * <add> * This source code is licensed under the MIT license found in the <add> * LICENSE file in the root directory of this source tree. <add> * <add> * @emails oncall+react_native <add> * @format <add> */ <add> <add>/* global element, by, expect */ <add> <add>const jestExpect = require('expect'); <add> <add>describe('Switch', () => { <add> beforeAll(async () => { <add> await element(by.id('explorer_search')).replaceText('<Switch>'); <add> await element(by.label('<Switch> Native boolean input')).tap(); <add> }); <add> <add> afterAll(async () => { <add> await element(by.label('Back')).tap(); <add> }); <add> <add> it('Switch that starts on should switch', async () => { <add> const testID = 'on-off-initial-off'; <add> const indicatorID = 'on-off-initial-off-indicator'; <add> <add> await expect(element(by.id(testID))).toHaveValue('0'); <add> await expect(element(by.id(indicatorID))).toHaveText('Off'); <add> await element(by.id(testID)).tap(); <add> await expect(element(by.id(testID))).toHaveValue('1'); <add> await expect(element(by.id(indicatorID))).toHaveText('On'); <add> }); <add> <add> it('Switch that starts off should switch', async () => { <add> const testID = 'on-off-initial-on'; <add> const indicatorID = 'on-off-initial-on-indicator'; <add> <add> await expect(element(by.id(testID))).toHaveValue('1'); <add> await expect(element(by.id(indicatorID))).toHaveText('On'); <add> await element(by.id(testID)).tap(); <add> await expect(element(by.id(testID))).toHaveValue('0'); <add> await expect(element(by.id(indicatorID))).toHaveText('Off'); <add> }); <add> <add> it('disabled switch should not toggle', async () => { <add> const onTestID = 'disabled-initial-on'; <add> const offTestID = 'disabled-initial-off'; <add> const onIndicatorID = 'disabled-initial-on-indicator'; <add> const offIndicatorID = 'disabled-initial-off-indicator'; <add> <add> await expect(element(by.id(onTestID))).toHaveValue('1'); <add> await expect(element(by.id(onIndicatorID))).toHaveText('On'); <add> <add> try { <add> await element(by.id(onTestID)).tap(); <add> throw new Error('Does not match'); <add> } catch (err) { <add> jestExpect(err.message.message).toEqual( <add> jestExpect.stringContaining( <add> 'Cannot perform action due to constraint(s) failure', <add> ), <add> ); <add> } <add> await expect(element(by.id(onTestID))).toHaveValue('1'); <add> await expect(element(by.id(onIndicatorID))).toHaveText('On'); <add> <add> await expect(element(by.id(offTestID))).toHaveValue('0'); <add> await expect(element(by.id(offIndicatorID))).toHaveText('Off'); <add> try { <add> await element(by.id(offTestID)).tap(); <add> throw new Error('Does not match'); <add> } catch (err) { <add> jestExpect(err.message.message).toEqual( <add> jestExpect.stringContaining( <add> 'Cannot perform action due to constraint(s) failure', <add> ), <add> ); <add> } <add> await expect(element(by.id(offTestID))).toHaveValue('0'); <add> await expect(element(by.id(offIndicatorID))).toHaveText('Off'); <add> }); <add>}); <ide><path>RNTester/js/SwitchExample.js <ide> 'use strict'; <ide> <ide> const React = require('react'); <del>const ReactNative = require('react-native'); <del>const {Switch, Text, View} = ReactNative; <add>const {Switch, Text, View} = require('react-native'); <ide> <del>class BasicSwitchExample extends React.Component<{}, $FlowFixMeState> { <add>type OnOffIndicatorProps = $ReadOnly<{|on: boolean, testID: string|}>; <add>function OnOffIndicator({on, testID}: OnOffIndicatorProps) { <add> return <Text testID={testID}>{on ? 'On' : 'Off'}</Text>; <add>} <add> <add>type ExampleRowProps = $ReadOnly<{|children: React.Node|}>; <add>function ExampleRow({children}: ExampleRowProps) { <add> return ( <add> <View <add> style={{ <add> flexDirection: 'row', <add> justifyContent: 'space-between', <add> alignItems: 'center', <add> marginBottom: 10, <add> }}> <add> {children} <add> </View> <add> ); <add>} <add> <add>type SimpleSwitchExampleState = $ReadOnly<{| <add> trueSwitchIsOn: boolean, <add> falseSwitchIsOn: boolean, <add>|}>; <add> <add>class BasicSwitchExample extends React.Component< <add> {||}, <add> SimpleSwitchExampleState, <add>> { <ide> state = { <ide> trueSwitchIsOn: true, <ide> falseSwitchIsOn: false, <ide> class BasicSwitchExample extends React.Component<{}, $FlowFixMeState> { <ide> render() { <ide> return ( <ide> <View> <del> <Switch <del> onValueChange={value => this.setState({falseSwitchIsOn: value})} <del> style={{marginBottom: 10}} <del> value={this.state.falseSwitchIsOn} <del> /> <del> <Switch <del> onValueChange={value => this.setState({trueSwitchIsOn: value})} <del> value={this.state.trueSwitchIsOn} <del> /> <add> <ExampleRow> <add> <Switch <add> testID="on-off-initial-off" <add> onValueChange={value => this.setState({falseSwitchIsOn: value})} <add> value={this.state.falseSwitchIsOn} <add> /> <add> <OnOffIndicator <add> on={this.state.falseSwitchIsOn} <add> testID="on-off-initial-off-indicator" <add> /> <add> </ExampleRow> <add> <ExampleRow> <add> <Switch <add> testID="on-off-initial-on" <add> onValueChange={value => this.setState({trueSwitchIsOn: value})} <add> value={this.state.trueSwitchIsOn} <add> /> <add> <OnOffIndicator <add> on={this.state.trueSwitchIsOn} <add> testID="on-off-initial-on-indicator" <add> /> <add> </ExampleRow> <ide> </View> <ide> ); <ide> } <ide> } <ide> <del>class DisabledSwitchExample extends React.Component<{}> { <add>class DisabledSwitchExample extends React.Component< <add> {||}, <add> SimpleSwitchExampleState, <add>> { <add> state = { <add> trueSwitchIsOn: true, <add> falseSwitchIsOn: false, <add> }; <add> <ide> render() { <ide> return ( <ide> <View> <del> <Switch disabled={true} style={{marginBottom: 10}} value={true} /> <del> <Switch disabled={true} value={false} /> <add> <ExampleRow> <add> <Switch <add> testID="disabled-initial-off" <add> disabled={true} <add> onValueChange={value => this.setState({falseSwitchIsOn: value})} <add> value={this.state.falseSwitchIsOn} <add> /> <add> <add> <OnOffIndicator <add> on={this.state.falseSwitchIsOn} <add> testID="disabled-initial-off-indicator" <add> /> <add> </ExampleRow> <add> <add> <ExampleRow> <add> <Switch <add> testID="disabled-initial-on" <add> disabled={true} <add> onValueChange={value => this.setState({trueSwitchIsOn: value})} <add> value={this.state.trueSwitchIsOn} <add> /> <add> <add> <OnOffIndicator <add> on={this.state.trueSwitchIsOn} <add> testID="disabled-initial-on-indicator" <add> /> <add> </ExampleRow> <ide> </View> <ide> ); <ide> }
3
Go
Go
move udevwait from defer to inline
5206d45e70512f5fc06006047fb67b2f478b304d
<ide><path>pkg/devicemapper/devmapper.go <ide> func RemoveDevice(name string) error { <ide> if err := task.setCookie(cookie, 0); err != nil { <ide> return fmt.Errorf("devicemapper: Can not set cookie: %s", err) <ide> } <del> defer UdevWait(cookie) <ide> <ide> dmSawBusy = false // reset before the task is run <ide> if err = task.run(); err != nil { <ide> func RemoveDevice(name string) error { <ide> return fmt.Errorf("devicemapper: Error running RemoveDevice %s", err) <ide> } <ide> <del> return nil <add> return UdevWait(cookie) <ide> } <ide> <ide> // RemoveDeviceDeferred is a useful helper for cleaning up a device, but deferred. <ide> func RemoveDeviceDeferred(name string) error { <ide> return fmt.Errorf("devicemapper: Can not set cookie: %s", err) <ide> } <ide> <add> if err = task.run(); err != nil { <add> return fmt.Errorf("devicemapper: Error running RemoveDeviceDeferred %s", err) <add> } <add> <ide> // libdevmapper and udev relies on System V semaphore for synchronization, <ide> // semaphores created in `task.setCookie` will be cleaned up in `UdevWait`. <ide> // So these two function call must come in pairs, otherwise semaphores will <ide> func RemoveDeviceDeferred(name string) error { <ide> // this call will not wait for the deferred removal's final executing, since no <ide> // udev event will be generated, and the semaphore's value will not be incremented <ide> // by udev, what UdevWait is just cleaning up the semaphore. <del> defer UdevWait(cookie) <del> <del> if err = task.run(); err != nil { <del> return fmt.Errorf("devicemapper: Error running RemoveDeviceDeferred %s", err) <del> } <ide> <del> return nil <add> return UdevWait(cookie) <ide> } <ide> <ide> // CancelDeferredRemove cancels a deferred remove for a device. <ide> func CreatePool(poolName string, dataFile, metadataFile *os.File, poolBlockSize <ide> if err := task.setCookie(cookie, flags); err != nil { <ide> return fmt.Errorf("devicemapper: Can't set cookie %s", err) <ide> } <del> defer UdevWait(cookie) <ide> <ide> if err := task.run(); err != nil { <ide> return fmt.Errorf("devicemapper: Error running deviceCreate (CreatePool) %s", err) <ide> } <ide> <del> return nil <add> return UdevWait(cookie) <ide> } <ide> <ide> // ReloadPool is the programmatic example of "dmsetup reload". <ide> func ResumeDevice(name string) error { <ide> if err := task.setCookie(cookie, 0); err != nil { <ide> return fmt.Errorf("devicemapper: Can't set cookie %s", err) <ide> } <del> defer UdevWait(cookie) <ide> <ide> if err := task.run(); err != nil { <ide> return fmt.Errorf("devicemapper: Error running deviceResume %s", err) <ide> } <ide> <del> return nil <add> return UdevWait(cookie) <ide> } <ide> <ide> // CreateDevice creates a device with the specified poolName with the specified device id. <ide> func activateDevice(poolName string, name string, deviceID int, size uint64, ext <ide> return fmt.Errorf("devicemapper: Can't set cookie %s", err) <ide> } <ide> <del> defer UdevWait(cookie) <del> <ide> if err := task.run(); err != nil { <ide> return fmt.Errorf("devicemapper: Error running deviceCreate (ActivateDevice) %s", err) <ide> } <ide> <del> return nil <add> return UdevWait(cookie) <ide> } <ide> <ide> // CreateSnapDeviceRaw creates a snapshot device. Caller needs to suspend and resume the origin device if it is active.
1
Ruby
Ruby
remove more dependencies from the view
2f683fd870d0e4c5aff38510ef03c7e5144a1ea4
<ide><path>actionpack/lib/action_view/base.rb <ide> def initialize(lookup_context = nil, assigns_for_first_render = {}, controller = <ide> lookup_context : ActionView::LookupContext.new(lookup_context) <ide> @_lookup_context.formats = formats if formats <ide> <del> @_renderer = ActionView::Renderer.new(@_lookup_context, self) <add> @view_renderer = ActionView::Renderer.new(@_lookup_context, self) <ide> end <ide> <ide> def controller_path <ide> @controller_path ||= controller && controller.controller_path <ide> end <ide> <del> def controller_prefixes <del> @controller_prefixes ||= controller && controller._prefixes <del> end <del> <ide> ActiveSupport.run_load_hooks(:action_view, self) <ide> end <ide> end <ide><path>actionpack/lib/action_view/renderer/partial_renderer.rb <ide> module ActionView <ide> class PartialRenderer < AbstractRenderer #:nodoc: <ide> PARTIAL_NAMES = Hash.new {|h,k| h[k] = {} } <ide> <add> # TODO Controller should not come from the view <ide> def initialize(view, *) <ide> super <del> @partial_names = PARTIAL_NAMES[@view.controller.class.name] <add> @controller = @view.controller <add> @partial_names = PARTIAL_NAMES[@controller.class.name] <ide> end <ide> <ide> def setup(options, block) <ide> def render_partial <ide> locals[as] = object <ide> <ide> content = @template.render(view, locals) do |*name| <del> view._block_layout_for(*name, &block) <add> view._layout_for(*name, &block) <ide> end <ide> <ide> content = layout.render(view, locals){ content } if layout <ide> def render_partial <ide> <ide> private <ide> <add> def controller_prefixes <add> @controller_prefixes ||= @controller && @controller._prefixes <add> end <add> <ide> def collection <ide> if @options.key?(:collection) <ide> collection = @options[:collection] <ide> def find_partial <ide> end <ide> <ide> def find_template(path=@path, [email protected]) <del> prefixes = path.include?(?/) ? [] : @view.controller_prefixes <add> prefixes = path.include?(?/) ? [] : controller_prefixes <ide> @lookup_context.find_template(path, prefixes, true, locals) <ide> end <ide> <ide> def partial_path(object = @object) <ide> object = object.to_model if object.respond_to?(:to_model) <ide> <ide> object.class.model_name.partial_path.dup.tap do |partial| <del> path = @view.controller_prefixes.first <add> path = controller_prefixes.first <ide> partial.insert(0, "#{File.dirname(path)}/") if partial.include?(?/) && path.include?(?/) <ide> end <ide> end <ide><path>actionpack/lib/action_view/renderer/renderer.rb <ide> class Renderer <ide> attr_accessor :lookup_context <ide> <ide> # TODO: render_context should not be an initialization parameter <add> # TODO: controller should be received on initialization <ide> def initialize(lookup_context, render_context) <ide> @render_context = render_context <ide> @lookup_context = lookup_context <ide><path>actionpack/lib/action_view/rendering.rb <ide> module ActionView <ide> # = Action View Rendering <ide> module Rendering <ide> # This is temporary until we remove the renderer dependency from AV. <del> delegate :render, :render_body, :to => :@_renderer <add> delegate :render, :render_body, :to => :@view_renderer <ide> <ide> # Returns the contents that are yielded to a layout, given a name or a block. <ide> # <ide> module Rendering <ide> # Hello David <ide> # </html> <ide> # <del> def _layout_for(*args) <del> name = args.first <del> name = :layout unless name.is_a?(Symbol) <del> @_view_flow.get(name).html_safe <del> end <del> <del> # Handle layout for calls from partials that supports blocks. <del> def _block_layout_for(*args, &block) <add> def _layout_for(*args, &block) <ide> name = args.first <ide> <del> if !name.is_a?(Symbol) && block <add> if name.is_a?(Symbol) <add> @_view_flow.get(name).html_safe <add> elsif block <ide> capture(*args, &block) <ide> else <del> _layout_for(*args) <add> @_view_flow.get(:layout).html_safe <ide> end <ide> end <ide> end <ide><path>actionpack/test/template/log_subscriber_test.rb <ide> class AVLogSubscriberTest < ActiveSupport::TestCase <ide> def setup <ide> super <ide> @old_logger = ActionController::Base.logger <del> @view = ActionView::Base.new(ActionController::Base.view_paths, {}) <add> @controller = Object.new <add> @controller.stubs(:_prefixes).returns(%w(test)) <add> @view = ActionView::Base.new(ActionController::Base.view_paths, {}, @controller) <ide> Rails.stubs(:root).returns(File.expand_path(FIXTURE_LOAD_PATH)) <ide> ActionView::LogSubscriber.attach_to :action_view <ide> end <ide> def test_render_partial_template <ide> end <ide> <ide> def test_render_partial_with_implicit_path <del> @view.stubs(:controller_prefixes).returns(%w(test)) <ide> @view.render(Customer.new("david"), :greeting => "hi") <ide> wait <ide> <ide> def test_render_collection_template <ide> end <ide> <ide> def test_render_collection_with_implicit_path <del> @view.stubs(:controller_prefixes).returns(%w(test)) <ide> @view.render([ Customer.new("david"), Customer.new("mary") ], :greeting => "hi") <ide> wait <ide> <ide> def test_render_collection_with_implicit_path <ide> end <ide> <ide> def test_render_collection_template_without_path <del> @view.stubs(:controller_prefixes).returns(%w(test)) <ide> @view.render([ GoodCustomer.new("david"), Customer.new("mary") ], :greeting => "hi") <ide> wait <ide>
5
Python
Python
update t5 tf
8669598abd7af877bd33890d62ae70ec1623f145
<ide><path>transformers/tests/modeling_tf_t5_test.py <ide> def prepare_config_and_inputs(self): <ide> token_labels = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) <ide> <ide> config = T5Config( <del> vocab_size_or_config_json_file=self.vocab_size, <add> vocab_size=self.vocab_size, <ide> n_positions=self.n_positions, <ide> d_model=self.hidden_size, <ide> d_ff=self.d_ff,
1
Go
Go
add a test for mount.getmounts
a7e181c8576e0413da888bea95fb7155173714ea
<ide><path>pkg/mount/mount_test.go <ide> func TestMountReadonly(t *testing.T) { <ide> t.Fatal("Should not be able to open a ro file as rw") <ide> } <ide> } <add> <add>func TestGetMounts(t *testing.T) { <add> mounts, err := GetMounts() <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> root := false <add> for _, entry := range mounts { <add> if entry.Mountpoint == "/" { <add> root = true <add> } <add> } <add> <add> if !root { <add> t.Fatal("/ should be mounted at least") <add> } <add>}
1
Javascript
Javascript
remove unused global types from type-parser
6ac3c44012cf0a52c3d586c4fcf473d98fce69ef
<ide><path>tools/doc/type-parser.js <ide> const jsPrimitives = { <ide> <ide> const jsGlobalObjectsUrl = `${jsDocPrefix}Reference/Global_Objects/`; <ide> const jsGlobalTypes = [ <del> 'Array', 'ArrayBuffer', 'AsyncFunction', 'DataView', 'Date', 'Error', <del> 'EvalError', 'Float32Array', 'Float64Array', 'Function', 'Generator', <del> 'GeneratorFunction', 'Int16Array', 'Int32Array', 'Int8Array', 'Map', 'Object', <del> 'Promise', 'Proxy', 'RangeError', 'ReferenceError', 'RegExp', 'Set', <add> 'Array', 'ArrayBuffer', 'DataView', 'Date', 'Error', 'EvalError', 'Function', <add> 'Object', 'Promise', 'RangeError', 'ReferenceError', 'RegExp', <ide> 'SharedArrayBuffer', 'SyntaxError', 'TypeError', 'TypedArray', 'URIError', <del> 'Uint16Array', 'Uint32Array', 'Uint8Array', 'Uint8ClampedArray', 'WeakMap', <del> 'WeakSet' <add> 'Uint8Array', <ide> ]; <ide> <ide> const customTypesMap = {
1
Java
Java
fix typo in javadoc
961c6419733926d6dfa2ca75af1edf7a886b2f66
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/DispatcherHandler.java <ide> /* <del> * Copyright 2002-2017 the original author or authors. <add> * Copyright 2002-2018 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * <li>{@link HandlerResultHandler} -- process handler return values <ide> * </ul> <ide> * <del> * <p>{@code DispatcherHandler} s also designed to be a Spring bean itself and <add> * <p>{@code DispatcherHandler} is also designed to be a Spring bean itself and <ide> * implements {@link ApplicationContextAware} for access to the context it runs <ide> * in. If {@code DispatcherHandler} is declared with the bean name "webHandler" <ide> * it is discovered by {@link WebHttpHandlerBuilder#applicationContext} which
1