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 | firstornew logic | 0b94f5c6df65b31d0cd238b8ebe17554a0131290 | <ide><path>src/Illuminate/Database/Eloquent/Relations/MorphOneOrMany.php
<ide> public function firstOrNew(array $attributes)
<ide> {
<ide> if (is_null($instance = $this->where($attributes)->first()))
<ide> {
<del> $instance = $this->related->newInstance();
<add> $instance = $this->related->newInstance($attributes);
<ide>
<ide> // When saving a polymorphic relationship, we need to set not only the foreign
<ide> // key, but also the foreign key type, which is typically the class name of
<ide><path>tests/Database/DatabaseEloquentMorphTest.php
<ide> public function testFirstOrNewMethodReturnsNewModelWithMorphKeysSet()
<ide> $relation = $this->getOneRelation();
<ide> $relation->getQuery()->shouldReceive('where')->once()->with(array('foo'))->andReturn($relation->getQuery());
<ide> $relation->getQuery()->shouldReceive('first')->once()->with()->andReturn(null);
<del> $relation->getRelated()->shouldReceive('newInstance')->once()->with()->andReturn($model = m::mock('Illuminate\Database\Eloquent\Model'));
<add> $relation->getRelated()->shouldReceive('newInstance')->once()->with(array('foo'))->andReturn($model = m::mock('Illuminate\Database\Eloquent\Model'));
<ide> $model->shouldReceive('setAttribute')->once()->with('morph_id', 1);
<ide> $model->shouldReceive('setAttribute')->once()->with('morph_type', get_class($relation->getParent()));
<ide> $model->shouldReceive('save')->never();
<ide> public function testUpdateOrCreateMethodCreatesNewMorphModel()
<ide> $relation = $this->getOneRelation();
<ide> $relation->getQuery()->shouldReceive('where')->once()->with(array('foo'))->andReturn($relation->getQuery());
<ide> $relation->getQuery()->shouldReceive('first')->once()->with()->andReturn(null);
<del> $relation->getRelated()->shouldReceive('newInstance')->once()->with()->andReturn($model = m::mock('Illuminate\Database\Eloquent\Model'));
<add> $relation->getRelated()->shouldReceive('newInstance')->once()->with(array('foo'))->andReturn($model = m::mock('Illuminate\Database\Eloquent\Model'));
<ide> $model->shouldReceive('setAttribute')->once()->with('morph_id', 1);
<ide> $model->shouldReceive('setAttribute')->once()->with('morph_type', get_class($relation->getParent()));
<ide> $model->shouldReceive('save')->once()->andReturn(true); | 2 |
Python | Python | fix a bug in the estimate remaining time part | d58005cfd4e8bb945043ad8f8e45b120e0aa67d1 | <ide><path>celery/beat.py
<ide> def tick(self):
<ide> result = self.apply_async(entry)
<ide> self.logger.debug("Scheduler: %s sent. id->%s" % (
<ide> entry.name, result.task_id))
<del> else:
<del> if remaining:
<del> remaining_times.append(remaining)
<add> if remaining:
<add> remaining_times.append(remaining)
<ide>
<ide> return min(remaining_times or [self.interval])
<ide>
<ide><path>celery/task/base.py
<ide> def __init__(self):
<ide>
<ide> def remaining_estimate(self, last_run_at):
<ide> rem = (last_run_at + self.run_every) - datetime.now()
<del> if not rem.days:
<add> if rem.days == -1:
<ide> return 0
<ide> return rem.seconds + (rem.microseconds / 10e5)
<ide>
<ide><path>celery/task/builtins.py
<ide> class DeleteExpiredTaskMetaTask(PeriodicTask):
<ide>
<ide> """
<ide> name = "celery.delete_expired_task_meta"
<del> run_every = timedelta(days=1)
<add> run_every = timedelta(minutes=1)
<ide>
<ide> def run(self, **kwargs):
<ide> """The method run by ``celeryd``.""" | 3 |
Python | Python | use recwarn everywhere | d393597c507ea62df534ba2ffb8a4e77cf3f1548 | <ide><path>tests/conftest.py
<ide> def inner(name):
<ide> return inner
<ide>
<ide>
<del>@pytest.fixture
<del>def catch_deprecation_warnings():
<del> import warnings
<del> warnings.simplefilter('default', category=DeprecationWarning)
<del> return lambda: warnings.catch_warnings(record=True)
<add>@pytest.yield_fixture(autouse=True)
<add>def catch_deprecation_warnings(recwarn):
<add> yield
<add> assert not recwarn.list
<ide><path>tests/test_basic.py
<ide> def test_static_files():
<ide> rv.close()
<ide>
<ide>
<del>def test_static_path_deprecated():
<del> with pytest.deprecated_call():
<del> app = flask.Flask(__name__, static_path='/foo')
<add>def test_static_path_deprecated(recwarn):
<add> app = flask.Flask(__name__, static_path='/foo')
<add> recwarn.pop(DeprecationWarning)
<add>
<ide> app.testing = True
<ide> rv = app.test_client().get('/foo/index.html')
<ide> assert rv.status_code == 200
<ide><path>tests/test_deprecations.py
<ide>
<ide> class TestRequestDeprecation(object):
<ide>
<del> def test_request_json(self, catch_deprecation_warnings):
<add> def test_request_json(self, recwarn):
<ide> """Request.json is deprecated"""
<ide> app = flask.Flask(__name__)
<ide> app.testing = True
<ide> def index():
<ide> print(flask.request.json)
<ide> return 'OK'
<ide>
<del> with catch_deprecation_warnings() as captured:
<del> c = app.test_client()
<del> c.post('/', data='{"spam": 42}', content_type='application/json')
<add> c = app.test_client()
<add> c.post('/', data='{"spam": 42}', content_type='application/json')
<add> recwarn.pop(DeprecationWarning)
<ide>
<del> assert len(captured) == 1
<del>
<del> def test_request_module(self, catch_deprecation_warnings):
<add> def test_request_module(self, recwarn):
<ide> """Request.module is deprecated"""
<ide> app = flask.Flask(__name__)
<ide> app.testing = True
<ide> def index():
<ide> assert flask.request.module is None
<ide> return 'OK'
<ide>
<del> with catch_deprecation_warnings() as captured:
<del> c = app.test_client()
<del> c.get('/')
<del>
<del> assert len(captured) == 1
<add> c = app.test_client()
<add> c.get('/')
<add> recwarn.pop(DeprecationWarning)
<ide><path>tests/test_ext.py
<ide> from flask._compat import PY2
<ide>
<ide>
<add>@pytest.fixture(autouse=True)
<add>def disable_extwarnings(request, recwarn):
<add> from flask.exthook import ExtDeprecationWarning
<add>
<add> def inner():
<add> assert set(w.category for w in recwarn.list) \
<add> <= set([ExtDeprecationWarning])
<add> recwarn.clear()
<add>
<add> request.addfinalizer(inner)
<add>
<add>
<ide> @pytest.fixture(autouse=True)
<ide> def importhook_setup(monkeypatch, request):
<ide> # we clear this out for various reasons. The most important one is
<ide><path>tests/test_helpers.py
<ide> def test_send_file_regular(self):
<ide> assert rv.data == f.read()
<ide> rv.close()
<ide>
<del> def test_send_file_xsendfile(self):
<add> def test_send_file_xsendfile(self, catch_deprecation_warnings):
<ide> app = flask.Flask(__name__)
<ide> app.use_x_sendfile = True
<ide> with app.test_request_context():
<ide> def test_send_file_xsendfile(self):
<ide> assert rv.mimetype == 'text/html'
<ide> rv.close()
<ide>
<del> def test_send_file_object(self, catch_deprecation_warnings):
<add> def test_send_file_object(self, recwarn):
<ide> app = flask.Flask(__name__)
<del> with catch_deprecation_warnings() as captured:
<del> with app.test_request_context():
<del> f = open(os.path.join(app.root_path, 'static/index.html'), mode='rb')
<del> rv = flask.send_file(f)
<del> rv.direct_passthrough = False
<del> with app.open_resource('static/index.html') as f:
<del> assert rv.data == f.read()
<del> assert rv.mimetype == 'text/html'
<del> rv.close()
<del> # mimetypes + etag
<del> assert len(captured) == 2
<add>
<add> with app.test_request_context():
<add> f = open(os.path.join(app.root_path, 'static/index.html'), mode='rb')
<add> rv = flask.send_file(f)
<add> rv.direct_passthrough = False
<add> with app.open_resource('static/index.html') as f:
<add> assert rv.data == f.read()
<add> assert rv.mimetype == 'text/html'
<add> rv.close()
<add>
<add> # mimetypes + etag
<add> assert len(recwarn.list) == 2
<add> recwarn.clear()
<ide>
<ide> app.use_x_sendfile = True
<del> with catch_deprecation_warnings() as captured:
<del> with app.test_request_context():
<del> f = open(os.path.join(app.root_path, 'static/index.html'))
<del> rv = flask.send_file(f)
<del> assert rv.mimetype == 'text/html'
<del> assert 'x-sendfile' in rv.headers
<del> assert rv.headers['x-sendfile'] == \
<del> os.path.join(app.root_path, 'static/index.html')
<del> rv.close()
<del> # mimetypes + etag
<del> assert len(captured) == 2
<add>
<add> with app.test_request_context():
<add> f = open(os.path.join(app.root_path, 'static/index.html'))
<add> rv = flask.send_file(f)
<add> assert rv.mimetype == 'text/html'
<add> assert 'x-sendfile' in rv.headers
<add> assert rv.headers['x-sendfile'] == \
<add> os.path.join(app.root_path, 'static/index.html')
<add> rv.close()
<add>
<add> # mimetypes + etag
<add> recwarn.pop()
<add> recwarn.pop()
<ide>
<ide> app.use_x_sendfile = False
<ide> with app.test_request_context():
<del> with catch_deprecation_warnings() as captured:
<del> f = StringIO('Test')
<del> rv = flask.send_file(f)
<del> rv.direct_passthrough = False
<del> assert rv.data == b'Test'
<del> assert rv.mimetype == 'application/octet-stream'
<del> rv.close()
<add> f = StringIO('Test')
<add> rv = flask.send_file(f)
<add> rv.direct_passthrough = False
<add> assert rv.data == b'Test'
<add> assert rv.mimetype == 'application/octet-stream'
<add> rv.close()
<add>
<ide> # etags
<del> assert len(captured) == 1
<del> with catch_deprecation_warnings() as captured:
<del> class PyStringIO(object):
<del> def __init__(self, *args, **kwargs):
<del> self._io = StringIO(*args, **kwargs)
<del> def __getattr__(self, name):
<del> return getattr(self._io, name)
<del> f = PyStringIO('Test')
<del> f.name = 'test.txt'
<del> rv = flask.send_file(f)
<del> rv.direct_passthrough = False
<del> assert rv.data == b'Test'
<del> assert rv.mimetype == 'text/plain'
<del> rv.close()
<add> recwarn.pop()
<add>
<add> class PyStringIO(object):
<add> def __init__(self, *args, **kwargs):
<add> self._io = StringIO(*args, **kwargs)
<add> def __getattr__(self, name):
<add> return getattr(self._io, name)
<add> f = PyStringIO('Test')
<add> f.name = 'test.txt'
<add> rv = flask.send_file(f)
<add> rv.direct_passthrough = False
<add> assert rv.data == b'Test'
<add> assert rv.mimetype == 'text/plain'
<add> rv.close()
<add>
<ide> # attachment_filename and etags
<del> assert len(captured) == 3
<del> with catch_deprecation_warnings() as captured:
<del> f = StringIO('Test')
<del> rv = flask.send_file(f, mimetype='text/plain')
<del> rv.direct_passthrough = False
<del> assert rv.data == b'Test'
<del> assert rv.mimetype == 'text/plain'
<del> rv.close()
<add> recwarn.pop()
<add> recwarn.pop()
<add> recwarn.pop()
<add>
<add> f = StringIO('Test')
<add> rv = flask.send_file(f, mimetype='text/plain')
<add> rv.direct_passthrough = False
<add> assert rv.data == b'Test'
<add> assert rv.mimetype == 'text/plain'
<add> rv.close()
<add>
<ide> # etags
<del> assert len(captured) == 1
<add> recwarn.pop()
<ide>
<ide> app.use_x_sendfile = True
<del> with catch_deprecation_warnings() as captured:
<del> with app.test_request_context():
<del> f = StringIO('Test')
<del> rv = flask.send_file(f)
<del> assert 'x-sendfile' not in rv.headers
<del> rv.close()
<del> # etags
<del> assert len(captured) == 1
<del>
<del> def test_attachment(self, catch_deprecation_warnings):
<del> app = flask.Flask(__name__)
<del> with catch_deprecation_warnings() as captured:
<del> with app.test_request_context():
<del> f = open(os.path.join(app.root_path, 'static/index.html'))
<del> rv = flask.send_file(f, as_attachment=True)
<del> value, options = parse_options_header(rv.headers['Content-Disposition'])
<del> assert value == 'attachment'
<del> rv.close()
<del> # mimetypes + etag
<del> assert len(captured) == 2
<add>
<add> with app.test_request_context():
<add> f = StringIO('Test')
<add> rv = flask.send_file(f)
<add> assert 'x-sendfile' not in rv.headers
<add> rv.close()
<add>
<add> # etags
<add> recwarn.pop()
<add>
<add> def test_attachment(self, recwarn):
<add> app = flask.Flask(__name__)
<add> with app.test_request_context():
<add> f = open(os.path.join(app.root_path, 'static/index.html'))
<add> rv = flask.send_file(f, as_attachment=True)
<add> value, options = parse_options_header(rv.headers['Content-Disposition'])
<add> assert value == 'attachment'
<add> rv.close()
<add>
<add> # mimetypes + etag
<add> assert len(recwarn.list) == 2
<add> recwarn.clear()
<ide>
<ide> with app.test_request_context():
<ide> assert options['filename'] == 'index.html' | 5 |
Javascript | Javascript | remove unneeded guard | 0e660ce09f5cc5648358866871aef843cfdad509 | <ide><path>lib/internal/crypto/cfrg.js
<ide> async function cfrgImportKey(
<ide> case 'raw': {
<ide> verifyAcceptableCfrgKeyUse(name, 'public', usagesSet);
<ide> keyObject = createCFRGRawKey(name, keyData, true);
<del> if (keyObject === undefined)
<del> throw lazyDOMException('Unable to import CFRG key', 'OperationError');
<ide> break;
<ide> }
<ide> }
<ide><path>lib/internal/crypto/keys.js
<ide> for (const m of [[kKeyEncodingPKCS1, 'pkcs1'], [kKeyEncodingPKCS8, 'pkcs8'],
<ide> encodingNames[m[0]] = m[1];
<ide>
<ide> // Creating the KeyObject class is a little complicated due to inheritance
<del>// and that fact that KeyObjects should be transferrable between threads,
<add>// and the fact that KeyObjects should be transferrable between threads,
<ide> // which requires the KeyObject base class to be implemented in C++.
<ide> // The creation requires a callback to make sure that the NativeKeyObject
<ide> // base class cannot exist without the other KeyObject implementations. | 2 |
PHP | PHP | remove unused parameter | f13bb7f0a3db39c9c9cf8618cb70c0c309a54090 | <ide><path>src/Illuminate/Foundation/helpers.php
<ide> function response($content = '', $status = 200, array $headers = [])
<ide> * @param string $name
<ide> * @param array $parameters
<ide> * @param bool $absolute
<del> * @param \Illuminate\Routing\Route $route
<ide> * @return string
<ide> */
<del> function route($name, $parameters = [], $absolute = true, $route = null)
<add> function route($name, $parameters = [], $absolute = true)
<ide> {
<del> return app('url')->route($name, $parameters, $absolute, $route);
<add> return app('url')->route($name, $parameters, $absolute);
<ide> }
<ide> }
<ide> | 1 |
Ruby | Ruby | remove unused argument | c91f1482a178cc82fe37101a04a97cb697ca5d7d | <ide><path>railties/test/application/rake/dbs_test.rb
<ide> def set_database_url
<ide> FileUtils.rm_rf("#{app_path}/config/database.yml")
<ide> end
<ide>
<del> def db_create_and_drop(expected_database, environment_loaded: true)
<add> def db_create_and_drop(expected_database)
<ide> Dir.chdir(app_path) do
<ide> output = rails("db:create")
<ide> assert_match(/Created database/, output) | 1 |
Javascript | Javascript | add tests for issue-2991 | a02d172de4b697538f7b158817355b58957d2eed | <ide><path>test/configCases/records/issue-2991/test.js
<add>try {
<add> require("foo");
<add>} catch(e){}
<add>
<add>it("should write relative paths to records", function() {
<add> var fs = require("fs");
<add> var path = require("path");
<add> var content = fs.readFileSync(path.join(__dirname, "records.json"), "utf-8");
<add> content.should.eql(`{
<add> "modules": {
<add> "byIdentifier": {
<add> "../../../../external \\"fs\\"": 0,
<add> "../../../../external \\"path\\"": 1,
<add> "../../../../ignored ../test/configCases/records/issue-2991 foo": 2,
<add> "test.js": 3
<add> },
<add> "usedIds": {
<add> "0": 0,
<add> "1": 1,
<add> "2": 2,
<add> "3": 3
<add> }
<add> },
<add> "chunks": {
<add> "byName": {
<add> "main": 0
<add> },
<add> "byBlocks": {},
<add> "usedIds": {
<add> "0": 0
<add> }
<add> }
<add>}`);
<add>});
<ide><path>test/configCases/records/issue-2991/webpack.config.js
<add>var path = require("path");
<add>
<add>module.exports = {
<add> entry: "./test",
<add> recordsPath: path.resolve(__dirname, "../../../js/config/records/issue-2991/records.json"),
<add> target: "node",
<add> node: {
<add> __dirname: false
<add> },
<add> plugins: [
<add> {
<add> apply(compiler) {
<add> compiler.plugin("normal-module-factory", (nmf) => {
<add> var oldResolve = nmf.resolvers.normal.resolve;
<add> nmf.resolvers.normal.resolve = function(_, __, resource, callback) {
<add> if(resource === "foo") {
<add> callback(null, false, false);
<add> return;
<add> }
<add> return oldResolve.apply(this, arguments);
<add> };
<add> });
<add> }
<add> }
<add> ]
<add>}; | 2 |
PHP | PHP | remove inline assignments | efe7e3f78b752f172d5585d28bc8c90e12dad6f0 | <ide><path>lib/Cake/Console/ConsoleInput.php
<ide> public function read() {
<ide> */
<ide> public function dataAvailable($timeout = 0) {
<ide> $readFds = array($this->_input);
<del> $readyFds = stream_select($readFds, $w = null, $e = null, $timeout);
<add> $readyFds = stream_select($readFds, $w, $e, $timeout);
<ide> return ($readyFds > 0);
<ide> }
<ide> | 1 |
Javascript | Javascript | fix helper export, add test | a5e5ad6917ee2f091f826aa5996be1c4d0c10db7 | <ide><path>packages/ember-htmlbars/lib/main.js
<ide> Ember.HTMLBars = {
<ide> DOMHelper
<ide> };
<ide>
<del>if (Ember.FEATURES.isEnabled('ember-htmlbars-helpers')) {
<add>if (Ember.FEATURES.isEnabled('ember-htmlbars-helper')) {
<ide> Helper.helper = makeHelper;
<ide> Ember.Helper = Helper;
<ide> }
<ide><path>packages/ember/tests/global-api-test.js
<ide> function confirmExport(property) {
<ide>
<ide> confirmExport('Ember.DefaultResolver');
<ide> confirmExport('Ember.generateController');
<add>if (Ember.FEATURES.isEnabled('ember-htmlbars-helper')) {
<add> confirmExport('Ember.Helper');
<add> confirmExport('Ember.Helper.helper');
<add>} | 2 |
Javascript | Javascript | move version into packcontainer | 82452939f587fa0b34db17901dfcc3ef2b7b93c9 | <ide><path>lib/cache/PackFileCacheStrategy.js
<ide> const {
<ide>
<ide> const MAX_INLINE_SIZE = 20000;
<ide>
<del>class DataWithBuildSnapshot {
<add>class PackContainer {
<ide> constructor(
<ide> data,
<add> version,
<ide> buildSnapshot,
<ide> buildDependencies,
<ide> resolveResults,
<ide> resolveBuildDependenciesSnapshot
<ide> ) {
<ide> this.data = data;
<add> this.version = version;
<ide> this.buildSnapshot = buildSnapshot;
<ide> this.buildDependencies = buildDependencies;
<ide> this.resolveResults = resolveResults;
<ide> this.resolveBuildDependenciesSnapshot = resolveBuildDependenciesSnapshot;
<ide> }
<ide>
<ide> serialize({ write }) {
<add> write(this.version);
<ide> write(this.buildSnapshot);
<ide> write(this.buildDependencies);
<ide> write(this.resolveResults);
<ide> class DataWithBuildSnapshot {
<ide> }
<ide>
<ide> deserialize({ read }) {
<add> this.version = read();
<ide> this.buildSnapshot = read();
<ide> this.buildDependencies = read();
<ide> this.resolveResults = read();
<ide> class DataWithBuildSnapshot {
<ide> }
<ide>
<ide> makeSerializable(
<del> DataWithBuildSnapshot,
<add> PackContainer,
<ide> "webpack/lib/cache/PackFileCacheStrategy",
<del> "DataWithBuildSnapshot_v1"
<add> "PackContainer"
<ide> );
<ide>
<ide> class Pack {
<del> constructor(version, logger) {
<del> this.version = version;
<add> constructor(logger) {
<ide> this.etags = new Map();
<ide> /** @type {Map<string, any | (() => Promise<PackEntry>)>} */
<ide> this.content = new Map();
<ide> class Pack {
<ide>
<ide> serialize({ write }) {
<ide> this._updateLastAccess();
<del> write(this.version);
<ide> write(this.etags);
<ide> write(this.unserializable);
<ide> write(this.lastAccess);
<ide> class Pack {
<ide>
<ide> deserialize({ read, logger }) {
<ide> this.logger = logger;
<del> this.version = read();
<ide> this.etags = read();
<ide> this.unserializable = read();
<ide> this.lastAccess = read();
<ide> class PackFileCacheStrategy {
<ide> let newBuildDependencies;
<ide> let resolveBuildDependenciesSnapshot;
<ide> let resolveResults;
<del> logger.time("restore pack");
<add> logger.time("restore pack container");
<ide> return this.fileSerializer
<ide> .deserialize({ filename: `${cacheLocation}.pack`, logger })
<ide> .catch(err => {
<ide> class PackFileCacheStrategy {
<ide> }
<ide> return undefined;
<ide> })
<del> .then(cacheEntry => {
<del> logger.timeEnd("restore pack");
<del> if (cacheEntry instanceof DataWithBuildSnapshot) {
<del> logger.time("check build dependencies");
<del> return Promise.all([
<del> new Promise((resolve, reject) => {
<del> this.fileSystemInfo.checkSnapshotValid(
<del> cacheEntry.buildSnapshot,
<del> (err, valid) => {
<del> if (err) return reject(err);
<del> if (!valid) {
<add> .then(packContainer => {
<add> logger.timeEnd("restore pack container");
<add> if (!packContainer) return undefined;
<add> if (!(packContainer instanceof PackContainer)) {
<add> logger.warn(
<add> `Restored pack from ${cacheLocation}.pack, but contained content is unexpected.`,
<add> packContainer
<add> );
<add> return undefined;
<add> }
<add> if (packContainer.version !== version) {
<add> logger.log(
<add> `Restored pack from ${cacheLocation}.pack, but version doesn't match.`
<add> );
<add> return undefined;
<add> }
<add> logger.time("check build dependencies");
<add> return Promise.all([
<add> new Promise((resolve, reject) => {
<add> this.fileSystemInfo.checkSnapshotValid(
<add> packContainer.buildSnapshot,
<add> (err, valid) => {
<add> if (err) return reject(err);
<add> if (!valid) {
<add> logger.log(
<add> `Restored pack from ${cacheLocation}.pack, but build dependencies have changed.`
<add> );
<add> return resolve(false);
<add> }
<add> buildSnapshot = packContainer.buildSnapshot;
<add> return resolve(true);
<add> }
<add> );
<add> }),
<add> new Promise((resolve, reject) => {
<add> this.fileSystemInfo.checkSnapshotValid(
<add> packContainer.resolveBuildDependenciesSnapshot,
<add> (err, valid) => {
<add> if (err) return reject(err);
<add> if (valid) {
<add> resolveBuildDependenciesSnapshot =
<add> packContainer.resolveBuildDependenciesSnapshot;
<add> buildDependencies = packContainer.buildDependencies;
<add> resolveResults = packContainer.resolveResults;
<add> return resolve(true);
<add> }
<add> logger.debug(
<add> "resolving of build dependencies is invalid, will re-resolve build dependencies"
<add> );
<add> this.fileSystemInfo.checkResolveResultsValid(
<add> packContainer.resolveResults,
<add> (err, valid) => {
<add> if (err) return reject(err);
<add> if (valid) {
<add> newBuildDependencies = packContainer.buildDependencies;
<add> resolveResults = packContainer.resolveResults;
<add> return resolve(true);
<add> }
<ide> logger.log(
<del> `Restored pack from ${cacheLocation}.pack, but build dependencies have changed.`
<add> `Restored pack from ${cacheLocation}.pack, but build dependencies resolve to different locations.`
<ide> );
<ide> return resolve(false);
<ide> }
<del> buildSnapshot = cacheEntry.buildSnapshot;
<del> return resolve(true);
<del> }
<del> );
<del> }),
<del> new Promise((resolve, reject) => {
<del> this.fileSystemInfo.checkSnapshotValid(
<del> cacheEntry.resolveBuildDependenciesSnapshot,
<del> (err, valid) => {
<del> if (err) return reject(err);
<del> if (valid) {
<del> resolveBuildDependenciesSnapshot =
<del> cacheEntry.resolveBuildDependenciesSnapshot;
<del> buildDependencies = cacheEntry.buildDependencies;
<del> resolveResults = cacheEntry.resolveResults;
<del> return resolve(true);
<del> }
<del> logger.debug(
<del> "resolving of build dependencies is invalid, will re-resolve build dependencies"
<del> );
<del> this.fileSystemInfo.checkResolveResultsValid(
<del> cacheEntry.resolveResults,
<del> (err, valid) => {
<del> if (err) return reject(err);
<del> if (valid) {
<del> newBuildDependencies = cacheEntry.buildDependencies;
<del> resolveResults = cacheEntry.resolveResults;
<del> return resolve(true);
<del> }
<del> logger.log(
<del> `Restored pack from ${cacheLocation}.pack, but build dependencies resolve to different locations.`
<del> );
<del> return resolve(false);
<del> }
<del> );
<del> }
<del> );
<del> })
<del> ])
<del> .catch(err => {
<del> logger.timeEnd("check build dependencies");
<del> throw err;
<del> })
<del> .then(([buildSnapshotValid, resolveValid]) => {
<del> logger.timeEnd("check build dependencies");
<del> if (buildSnapshotValid && resolveValid) {
<del> logger.time("restore pack content");
<del> return cacheEntry.data().then(d => {
<del> logger.timeEnd("restore pack content");
<del> return d;
<del> });
<add> );
<ide> }
<del> return undefined;
<del> });
<del> }
<del> return cacheEntry;
<del> })
<del> .then(cacheEntry => {
<del> if (cacheEntry) {
<del> if (!(cacheEntry instanceof Pack)) {
<del> logger.warn(
<del> `Restored from ${cacheLocation}.pack, but is not a Pack.`
<del> );
<del> return new Pack(version, logger);
<del> }
<del> if (cacheEntry.version !== version) {
<del> logger.log(
<del> `Restored pack from ${cacheLocation}.pack, but version doesn't match.`
<ide> );
<del> return new Pack(version, logger);
<del> }
<add> })
<add> ])
<add> .catch(err => {
<add> logger.timeEnd("check build dependencies");
<add> throw err;
<add> })
<add> .then(([buildSnapshotValid, resolveValid]) => {
<add> logger.timeEnd("check build dependencies");
<add> if (buildSnapshotValid && resolveValid) {
<add> logger.time("restore pack");
<add> return packContainer.data().then(d => {
<add> logger.timeEnd("restore pack");
<add> return d;
<add> });
<add> }
<add> return undefined;
<add> });
<add> })
<add> .then(pack => {
<add> if (pack) {
<ide> this.buildSnapshot = buildSnapshot;
<ide> if (buildDependencies) this.buildDependencies = buildDependencies;
<ide> if (newBuildDependencies)
<ide> this.newBuildDependencies.addAll(newBuildDependencies);
<ide> this.resolveResults = resolveResults;
<ide> this.resolveBuildDependenciesSnapshot = resolveBuildDependenciesSnapshot;
<del> return cacheEntry;
<add> return pack;
<ide> }
<del> return new Pack(version, logger);
<add> return new Pack(logger);
<ide> });
<ide> }
<ide>
<ide> class PackFileCacheStrategy {
<ide> return promise.then(() => {
<ide> this.logger.time(`store pack`);
<ide> pack.collectGarbage(1000 * 60 * 60 * 24 * 2);
<del> const content = this.buildSnapshot
<del> ? new DataWithBuildSnapshot(
<del> () => pack,
<del> this.buildSnapshot,
<del> this.buildDependencies,
<del> this.resolveResults,
<del> this.resolveBuildDependenciesSnapshot
<del> )
<del> : pack;
<add> const content = new PackContainer(
<add> () => pack,
<add> this.version,
<add> this.buildSnapshot,
<add> this.buildDependencies,
<add> this.resolveResults,
<add> this.resolveBuildDependenciesSnapshot
<add> );
<ide> // You might think this breaks all access to the existing pack
<ide> // which are still referenced, but serializing the pack memorizes
<ide> // all data in the pack and makes it no longer need the backing file
<ide><path>test/BuildDependencies.test.js
<ide> describe("BuildDependencies", () => {
<ide> beforeEach(done => {
<ide> rimraf(outputDirectory, done);
<ide> });
<add>
<add> beforeEach(done => {
<add> rimraf(inputDirectory, done);
<add> });
<ide> beforeEach(done => {
<ide> fs.mkdir(inputDirectory, { recursive: true }, done);
<ide> });
<del> it("should capture loader dependencies", async () => {
<add> it("should capture loader and config dependencies", async () => {
<ide> fs.writeFileSync(
<ide> path.resolve(inputDirectory, "loader-dependency.js"),
<ide> "module.exports = 1;" | 2 |
PHP | PHP | enable the query log for tests. dry up code | 0735f1d658f2bf3b2f6672bf8f964890e14ed44d | <ide><path>src/Illuminate/Container/Container.php
<ide> protected function getDependencyForCallParameter(ReflectionParameter $parameter,
<ide> */
<ide> protected function callClass($target, array $parameters = array(), $defaultMethod = null)
<ide> {
<add> $segments = explode('@', $target);
<add>
<ide> // If the listener has an @ sign, we will assume it is being used to delimit
<ide> // the class name from the handle method name. This allows for handlers
<ide> // to run multiple handler methods in a single class for convenience.
<del> $segments = explode('@', $target);
<del>
<ide> $method = count($segments) == 2 ? $segments[1] : $defaultMethod;
<ide>
<ide> if (is_null($method))
<ide> {
<ide> throw new \InvalidArgumentException("Method not provided.");
<ide> }
<ide>
<del> // We will make a callable of the listener instance and a method that should
<del> // be called on that instance, then we will pass in the arguments that we
<del> // received in this method into this listener class instance's methods.
<del> $callable = array($this->make($segments[0]), $method);
<del>
<del> $dependencies = $this->getMethodDependencies($callable, $parameters);
<del>
<del> return call_user_func_array($callable, $dependencies);
<add> return $this->call([$this->make($segments[0]), $method], $parameters);
<ide> }
<ide>
<ide> /**
<ide><path>tests/Database/DatabaseConnectionTest.php
<ide> protected function getMockConnection($methods = array(), $pdo = null)
<ide> {
<ide> $pdo = $pdo ?: new DatabaseConnectionTestMockPDO;
<ide> $defaults = array('getDefaultQueryGrammar', 'getDefaultPostProcessor', 'getDefaultSchemaGrammar');
<del> return $this->getMock('Illuminate\Database\Connection', array_merge($defaults, $methods), array($pdo));
<add> $connection = $this->getMock('Illuminate\Database\Connection', array_merge($defaults, $methods), array($pdo));
<add> $connection->enableQueryLog();
<add> return $connection;
<ide> }
<ide>
<ide> } | 2 |
Text | Text | add reacteurope 2018 conference | 803b493314ad65be26ef9bb3a621eb65ce8b11e2 | <ide><path>docs/community/conferences.md
<ide> April 13 in Amsterdam, The Netherlands
<ide>
<ide> [Website](https://react.amsterdam) - [Twitter](https://twitter.com/reactamsterdam) - [Facebook](https://www.facebook.com/reactamsterdam)
<ide>
<add>### ReactEurope 2018
<add>May 17-18 in Paris, France
<add>
<add>[Website](https://www.react-europe.org) - [Twitter](https://twitter.com/ReactEurope) - [Facebook](https://www.facebook.com/ReactEurope)
<add>
<ide> ## Past Conferences
<ide>
<ide> ### React.js Conf 2015 | 1 |
Go | Go | fix cache miss when builtin build args are used | 721e1736ae31914902d2c2196aed5f92e1a0982d | <ide><path>builder/dockerfile/dispatchers.go
<ide> func run(req dispatchRequest) error {
<ide> // that starts with "foo=abc" to be considered part of a build-time env var.
<ide> saveCmd := config.Cmd
<ide> if len(cmdBuildEnv) > 0 {
<del> sort.Strings(cmdBuildEnv)
<del> tmpEnv := append([]string{fmt.Sprintf("|%d", len(cmdBuildEnv))}, cmdBuildEnv...)
<del> saveCmd = strslice.StrSlice(append(tmpEnv, saveCmd...))
<add> saveCmd = prependEnvOnCmd(req.builder.buildArgs, cmdBuildEnv, saveCmd)
<ide> }
<ide>
<ide> req.runConfig.Cmd = saveCmd
<ide> func run(req dispatchRequest) error {
<ide> // properly match it.
<ide> req.runConfig.Env = env
<ide>
<del> // remove builtinAllowedBuildArgs (see: builder.go) from the saveCmd
<del> // these args are transparent so resulting image should be the same regardless of the value
<del> if len(cmdBuildEnv) > 0 {
<del> saveCmd = config.Cmd
<del> var tmpBuildEnv []string
<del> for _, env := range cmdBuildEnv {
<del> key := strings.SplitN(env, "=", 2)[0]
<del> if !req.builder.buildArgs.IsUnreferencedBuiltin(key) {
<del> tmpBuildEnv = append(tmpBuildEnv, env)
<del> }
<del> }
<del> sort.Strings(tmpBuildEnv)
<del> tmpEnv := append([]string{fmt.Sprintf("|%d", len(tmpBuildEnv))}, tmpBuildEnv...)
<del> saveCmd = strslice.StrSlice(append(tmpEnv, saveCmd...))
<del> }
<ide> req.runConfig.Cmd = saveCmd
<ide> return req.builder.commitContainer(cID, copyRunConfig(req.runConfig, withCmd(cmd)))
<ide> }
<ide>
<add>func prependEnvOnCmd(buildArgs *buildArgs, buildArgVars []string, cmd strslice.StrSlice) strslice.StrSlice {
<add> var tmpBuildEnv []string
<add> for _, env := range buildArgVars {
<add> key := strings.SplitN(env, "=", 2)[0]
<add> if !buildArgs.IsUnreferencedBuiltin(key) {
<add> tmpBuildEnv = append(tmpBuildEnv, env)
<add> }
<add> }
<add>
<add> sort.Strings(tmpBuildEnv)
<add> tmpEnv := append([]string{fmt.Sprintf("|%d", len(tmpBuildEnv))}, tmpBuildEnv...)
<add> return strslice.StrSlice(append(tmpEnv, cmd...))
<add>}
<add>
<ide> // CMD foo
<ide> //
<ide> // Set the default command to run in the container (which may be empty).
<ide><path>integration-cli/docker_cli_build_test.go
<ide> func (s *DockerSuite) TestBuildTimeArgHistoryExclusions(c *check.C) {
<ide> ARG %s
<ide> ARG %s
<ide> RUN echo "Testing Build Args!"`, envKey, explicitProxyKey)
<del> buildImage(imgName,
<del> cli.WithFlags("--build-arg", "https_proxy=https://proxy.example.com",
<del> "--build-arg", fmt.Sprintf("%s=%s", envKey, envVal),
<del> "--build-arg", fmt.Sprintf("%s=%s", explicitProxyKey, explicitProxyVal),
<del> "--build-arg", proxy),
<del> build.WithDockerfile(dockerfile),
<del> ).Assert(c, icmd.Success)
<ide>
<del> out, _ := dockerCmd(c, "history", "--no-trunc", imgName)
<add> buildImage := func(imgName string) string {
<add> cli.BuildCmd(c, imgName,
<add> cli.WithFlags("--build-arg", "https_proxy=https://proxy.example.com",
<add> "--build-arg", fmt.Sprintf("%s=%s", envKey, envVal),
<add> "--build-arg", fmt.Sprintf("%s=%s", explicitProxyKey, explicitProxyVal),
<add> "--build-arg", proxy),
<add> build.WithDockerfile(dockerfile),
<add> )
<add> return getIDByName(c, imgName)
<add> }
<add>
<add> origID := buildImage(imgName)
<add> result := cli.DockerCmd(c, "history", "--no-trunc", imgName)
<add> out := result.Stdout()
<add>
<ide> if strings.Contains(out, proxy) {
<ide> c.Fatalf("failed to exclude proxy settings from history!")
<ide> }
<ide> func (s *DockerSuite) TestBuildTimeArgHistoryExclusions(c *check.C) {
<ide> if !strings.Contains(out, fmt.Sprintf("%s=%s", envKey, envVal)) {
<ide> c.Fatalf("missing build arguments from output")
<ide> }
<add>
<add> cacheID := buildImage(imgName + "-two")
<add> c.Assert(origID, checker.Equals, cacheID)
<ide> }
<ide>
<ide> func (s *DockerSuite) TestBuildBuildTimeArgCacheHit(c *check.C) { | 2 |
Javascript | Javascript | simplify icon param for electron packager | 1d0b39bf512f8d528e026a7560777f1fe660cef9 | <ide><path>script/lib/package-application.js
<ide> module.exports = function () {
<ide> electronVersion: CONFIG.appMetadata.electronVersion,
<ide> extendInfo: path.join(CONFIG.repositoryRootPath, 'resources', 'mac', 'atom-Info.plist'),
<ide> helperBundleId: 'com.github.atom.helper',
<del> icon: getIcon(),
<add> icon: path.join(CONFIG.repositoryRootPath, 'resources', 'app-icons', CONFIG.channel, 'atom'),
<ide> name: appName,
<ide> out: CONFIG.buildOutputPath,
<ide> overwrite: true,
<ide> function getAppName () {
<ide> }
<ide> }
<ide>
<del>function getIcon () {
<del> switch (process.platform) {
<del> case 'darwin':
<del> return path.join(CONFIG.repositoryRootPath, 'resources', 'app-icons', CONFIG.channel, 'atom.icns')
<del> case 'linux':
<del> // Don't pass an icon, as the dock/window list icon is set via the icon
<del> // option in the BrowserWindow constructor in atom-window.coffee.
<del> return null
<del> default:
<del> return path.join(CONFIG.repositoryRootPath, 'resources', 'app-icons', CONFIG.channel, 'atom.ico')
<del> }
<del>}
<del>
<ide> function runPackager (options) {
<ide> return electronPackager(options)
<ide> .then(packageOutputDirPaths => { | 1 |
Python | Python | fix parser sourcing in ner converter | e6b7600adf70e5586b19d938d3a4ba7b12244f44 | <ide><path>spacy/training/converters/conll_ner_to_docs.py
<ide> def segment_sents_and_docs(doc, n_sents, doc_delimiter, model=None, msg=None):
<ide> nlp = load_model(model)
<ide> if "parser" in nlp.pipe_names:
<ide> msg.info(f"Segmenting sentences with parser from model '{model}'.")
<add> for name, proc in nlp.pipeline:
<add> if "parser" in getattr(proc, "listening_components", []):
<add> nlp.replace_listeners(name, "parser", ["model.tok2vec"])
<ide> sentencizer = nlp.get_pipe("parser")
<ide> if not sentencizer:
<ide> msg.info( | 1 |
Javascript | Javascript | fix a couple of document typos in enumerable | b7faf658b4fe136d522ddf2138bf09be6021fe72 | <ide><path>packages/ember-runtime/lib/mixins/enumerable.js
<ide> function iter(key, value) {
<ide> To make your own custom class enumerable, you need two items:
<ide>
<ide> 1. You must have a length property. This property should change whenever
<del> the number of items in your enumerable object changes. If you using this
<add> the number of items in your enumerable object changes. If you use this
<ide> with an `Ember.Object` subclass, you should be sure to change the length
<ide> property using `set().`
<ide>
<ide> 2. You must implement `nextObject().` See documentation.
<ide>
<del> Once you have these two methods implement, apply the `Ember.Enumerable` mixin
<add> Once you have these two methods implemented, apply the `Ember.Enumerable` mixin
<ide> to your class and you will be able to enumerate the contents of your object
<ide> like any other collection.
<ide> | 1 |
Text | Text | add mdn link for map function | 2e11dcb1ea4ef09993ab46e50b95327e30f2b2b5 | <ide><path>guide/english/javascript/es6/map-function/index.md
<del>---
<del>title: Map Function
<del>---
<del>
<del>## The Map Function
<del>
<del>The `map()` function is used for creating a new array from an existing one, applying a function to each one of the elements of the first array.
<del>
<del>The original syntax of the map function is:
<del>```javascript
<del> let new_arr = arr.map(function callback(currentValue, index, array) {
<del> // Do some stuff with currentValue (index and array are optionals)
<del> })
<del>```
<del>* `new_arr` - the new array that is returned
<del>* `ar`r - the array to run the map function on
<del>* `currentValue` - the current value being processed
<del>* `index` - the current index of the value being processed
<del>* `array` - the original array
<del>
<del>### Example (ES6):
<del>
<del>```javascript
<del>const myArray_1 = [1, 2, 3, 4];
<del>const myArray_2 = myArray_1.map(el => el * 2);
<del>```
<del>`myArray_2` will contain the elements: `[2, 4, 6, 8]`
<del>
<del>`map()` is a method of the `Array` object, so to pass that function to an iterable object it is necessary to make the object an Array.
<add>---
<add>title: Map Function
<add>---
<add>
<add>## The Map Function
<add>
<add>The `map()` function is used for creating a new array from an existing one, applying a function to each one of the elements of the first array.
<add>
<add>The original syntax of the map function is:
<add>```javascript
<add> let new_arr = arr.map(function callback(currentValue, index, array) {
<add> // Do some stuff with currentValue (index and array are optionals)
<add> })
<add>```
<add>* `new_arr` - the new array that is returned
<add>* `ar`r - the array to run the map function on
<add>* `currentValue` - the current value being processed
<add>* `index` - the current index of the value being processed
<add>* `array` - the original array
<add>
<add>### Example (ES6):
<add>
<add>```javascript
<add>const myArray_1 = [1, 2, 3, 4];
<add>const myArray_2 = myArray_1.map(el => el * 2);
<add>```
<add>`myArray_2` will contain the elements: `[2, 4, 6, 8]`
<add>
<add>`map()` is a method of the `Array` object, so to pass that function to an iterable object it is necessary to make the object an Array.
<add>
<add>### Resources:
<add>
<add> [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) | 1 |
Ruby | Ruby | fix inconsistent alignment in gemfile generator | d32a90b9b77d3f7d8098ee6ddb5bf62cb8da0ed7 | <ide><path>railties/lib/rails/generators/app_base.rb
<ide> def rails_gemfile_entry
<ide> gem 'rails', '#{Rails::VERSION::STRING}'
<ide>
<ide> # Bundle edge Rails instead:
<del> # gem 'rails', :git => 'git://github.com/rails/rails.git'
<add> # gem 'rails', :git => 'git://github.com/rails/rails.git'
<ide> GEMFILE
<ide> end
<ide> end
<ide>
<ide> def gem_for_database
<ide> # %w( mysql oracle postgresql sqlite3 frontbase ibm_db sqlserver jdbcmysql jdbcsqlite3 jdbcpostgresql )
<ide> case options[:database]
<del> when "oracle" then "ruby-oci8"
<del> when "postgresql" then "pg"
<del> when "frontbase" then "ruby-frontbase"
<del> when "mysql" then "mysql2"
<del> when "sqlserver" then "activerecord-sqlserver-adapter"
<add> when "oracle" then "ruby-oci8"
<add> when "postgresql" then "pg"
<add> when "frontbase" then "ruby-frontbase"
<add> when "mysql" then "mysql2"
<add> when "sqlserver" then "activerecord-sqlserver-adapter"
<ide> when "jdbcmysql" then "activerecord-jdbcmysql-adapter"
<ide> when "jdbcsqlite3" then "activerecord-jdbcsqlite3-adapter"
<ide> when "jdbcpostgresql" then "activerecord-jdbcpostgresql-adapter" | 1 |
Java | Java | fix attempt to the firehose test | e3ca9e519c82b2607a1e692f2f8aa6b614835ebe | <ide><path>src/main/java/io/reactivex/internal/subscribers/EmptySubscriber.java
<ide> * A subscriber that ignores all events (onError is forwarded to RxJavaPlugins though).
<ide> */
<ide> public enum EmptySubscriber implements Subscriber<Object> {
<del> INSTANCE;
<add> /** Empty instance that reports error to the plugins. */
<add> INSTANCE(true),
<add> /** Empty instance that doesn't report to the plugins to avoid flooding the test output. */
<add> INSTANCE_NOERROR(false);
<add>
<add> final boolean reportError;
<add>
<add> EmptySubscriber(boolean reportError) {
<add> this.reportError = reportError;
<add> }
<ide>
<ide> @Override
<ide> public void onSubscribe(Subscription s) {
<ide> public void onNext(Object t) {
<ide>
<ide> @Override
<ide> public void onError(Throwable t) {
<del> RxJavaPlugins.onError(t);
<add> if (reportError) {
<add> RxJavaPlugins.onError(t);
<add> }
<ide> }
<ide>
<ide> @Override
<ide><path>src/main/java/io/reactivex/subscribers/TestSubscriber.java
<ide> public void cancel() {
<ide> * Constructs a non-forwarding TestSubscriber with an initial request value of Long.MAX_VALUE.
<ide> */
<ide> public TestSubscriber() {
<del> this(EmptySubscriber.INSTANCE, Long.MAX_VALUE);
<add> this(EmptySubscriber.INSTANCE_NOERROR, Long.MAX_VALUE);
<ide> }
<ide>
<ide> /**
<ide> public TestSubscriber() {
<ide> * @param initialRequest the initial request value if not null
<ide> */
<ide> public TestSubscriber(Long initialRequest) {
<del> this(EmptySubscriber.INSTANCE, initialRequest);
<add> this(EmptySubscriber.INSTANCE_NOERROR, initialRequest);
<ide> }
<ide>
<ide> /**
<ide><path>src/test/java/io/reactivex/BackpressureTests.java
<ide> public void request(long n) {
<ide> }
<ide> if (compareAndSet(false, true)) {
<ide> int i = 0;
<add> final Subscriber<? super Integer> a = s;
<add> final AtomicInteger c = counter;
<add>
<ide> while (!cancelled) {
<del> s.onNext(i++);
<del> counter.incrementAndGet();
<add> a.onNext(i++);
<add> c.incrementAndGet();
<ide> }
<ide> System.out.println("unsubscribed after: " + i);
<ide> }
<ide> public void testFirehoseFailsAsExpected() {
<ide>
<ide> ts.assertError(MissingBackpressureException.class);
<ide> }
<add>
<add> @Test
<add> public void testFirehoseFailsAsExpectedLoop() {
<add> for (int i = 0; i < 1000; i++) {
<add> testFirehoseFailsAsExpected();
<add> }
<add> }
<ide>
<ide> @Test(timeout = 10000)
<ide> public void testOnBackpressureDrop() { | 3 |
Text | Text | change lead maintainer date | 573da9002b246a24f4dcba691568fdf00ed5ad9d | <ide><path>docs/Maintainer-Guidelines.md
<ide> Individual Homebrew repositories should not have formal lead maintainers (althou
<ide>
<ide> Maintainers should feel even more free to pleasantly disagree with the work and decisions of the lead maintainer: with greater authority comes greater responsibility to handle and moderate technical disagreements.
<ide>
<del>Homebrew's last lead maintainer will be Mike McQuaid. On February 1st, Mike will step down as lead maintainer of Homebrew and his responsibilities will be passed on to the project leadership committee and/or a new, technical steering committee and/or something else.
<add>Homebrew's last lead maintainer will be Mike McQuaid. On February 4th (to coincide with Homebrew maintainers' conference), Mike will step down as lead maintainer of Homebrew and his responsibilities will be passed on to the project leadership committee and/or a new, technical steering committee and/or something else.
<ide>
<ide> Some food for thought and discussion before those dates:
<ide> | 1 |
Javascript | Javascript | install apm using ci | c7b55e5ceae15343be28e4ddca954c2277ea1970 | <ide><path>script/lib/install-apm.js
<ide> const CONFIG = require('../config');
<ide>
<ide> module.exports = function(ci) {
<ide> console.log('Installing apm');
<del> // npm ci leaves apm with a bunch of unmet dependencies
<ide> childProcess.execFileSync(
<ide> CONFIG.getNpmBinPath(),
<del> ['--global-style', '--loglevel=error', 'install'],
<add> ['--global-style', '--loglevel=error', ci ? 'ci' : 'install'],
<ide> { env: process.env, cwd: CONFIG.apmRootPath }
<ide> );
<ide> }; | 1 |
Ruby | Ruby | preserve file attributes like mtime | 4a8632e54d02b8c71ab581f18287a682e1640bcc | <ide><path>Library/Homebrew/cmd/unpack.rb
<ide> def unpack
<ide> ENV["VERBOSE"] = "1" # show messages about tar
<ide> f.brew do
<ide> f.patch if ARGV.flag?("--patch")
<del> cp_r getwd, stage_dir
<add> cp_r getwd, stage_dir, :preserve => true
<ide> end
<ide> ENV["VERBOSE"] = nil
<ide> | 1 |
PHP | PHP | remove more code | 4dab08861a622b9c6948cfc10751d9cc2282218d | <ide><path>src/Console/ConsoleErrorHandler.php
<ide>
<ide> use Cake\Error\BaseErrorHandler;
<ide> use Cake\Error\FatalErrorException;
<del>use Cake\Error\PHP7ErrorException;
<ide> use Exception;
<ide> use Throwable;
<ide>
<ide><path>src/Error/BaseErrorHandler.php
<ide> protected function _logError($level, array $data): bool
<ide> protected function _logException(Throwable $exception): bool
<ide> {
<ide> $config = $this->_options;
<del> $unwrapped = $exception instanceof PHP7ErrorException ?
<del> $exception->getError() :
<del> $exception;
<del>
<ide> if (empty($config['log'])) {
<ide> return false;
<ide> }
<ide>
<ide> if (!empty($config['skipLog'])) {
<ide> foreach ((array)$config['skipLog'] as $class) {
<del> if ($unwrapped instanceof $class) {
<add> if ($error instanceof $class) {
<ide> return false;
<ide> }
<ide> }
<ide> protected function _requestContext($request): string
<ide> */
<ide> protected function _getMessage(Throwable $exception): string
<ide> {
<del> $exception = $exception instanceof PHP7ErrorException ?
<del> $exception->getError() :
<del> $exception;
<ide> $config = $this->_options;
<ide> $message = sprintf(
<ide> '[%s] %s in %s on line %s',
<ide><path>src/Log/LogEngineRegistry.php
<ide> protected function _create($class, $alias, $settings)
<ide> * Remove a single logger from the registry.
<ide> *
<ide> * @param string $name The logger name.
<del> * @return void
<add> * @return $this
<ide> */
<del> public function unload($name): void
<add> public function unload(string $name
<ide> {
<ide> unset($this->_loaded[$name]);
<add>
<add> return $this;
<ide> }
<ide> }
<ide><path>src/View/HelperRegistry.php
<ide> public function __construct(View $view)
<ide> * @throws \Cake\View\Exception\MissingHelperException When a helper could not be found.
<ide> * App helpers are searched, and then plugin helpers.
<ide> */
<del> public function __isset($helper)
<add> public function __isset(string $helper): bool
<ide> {
<ide> if (isset($this->_loaded[$helper])) {
<ide> return true;
<ide> public function __isset($helper)
<ide> * @param string $name Name of property to read
<ide> * @return mixed
<ide> */
<del> public function __get($name)
<add> public function __get(string $name)
<ide> {
<ide> if (isset($this->_loaded[$name])) {
<ide> return $this->_loaded[$name]; | 4 |
Python | Python | add batch_dot to backend | b0ea92bc127d724f514d25d64d079b2d31e980ea | <ide><path>keras/backend/tensorflow_backend.py
<ide> def dot(x, y):
<ide> return tf.matmul(x, y)
<ide>
<ide>
<add>def batch_dot(x, y, axes=None):
<add> if axes:
<add> adj_x = None if axes[0][0] == x.ndim-1 else True
<add> adj_y = True if axes[1][0] == y.ndim-1 else None
<add> else:
<add> adj_x = None
<add> adj_y = None
<add> return tf.batch_matmul(x, y, adj_x=adj_x, adj_y=adj_y)
<add>
<add>
<ide> def transpose(x):
<ide> return tf.transpose(x)
<ide>
<ide> def random_uniform(shape, low=0.0, high=1.0, dtype=_FLOATX, seed=None):
<ide> def random_binomial(shape, p=0.0, dtype=_FLOATX, seed=None):
<ide> if seed is None:
<ide> seed = np.random.randint(10e6)
<del> return tf.select(tf.random_uniform(shape, dtype=dtype, seed=seed) <= p,
<add> return tf.select(tf.random_uniform(shape, dtype=dtype, seed=seed) <= p,
<ide> tf.ones(shape), tf.zeros(shape))
<ide><path>keras/backend/theano_backend.py
<ide> def dot(x, y):
<ide> return T.dot(x, y)
<ide>
<ide>
<add>def batch_dot(x, y, axes=None):
<add> if axes is None:
<add> # behaves like tf.batch_matmul as default
<add> axes = [(x.ndim-1,), (y.ndim-2,)]
<add> return T.batched_tensordot(x, y, axes=axes)
<add>
<add>
<ide> def transpose(x):
<ide> return T.transpose(x)
<ide>
<ide><path>tests/keras/backend/test_backends.py
<ide> class TestBackend(object):
<ide>
<ide> def test_linear_operations(self):
<ide> check_two_tensor_operation('dot', (4, 2), (2, 4))
<add> check_two_tensor_operation('batch_dot', (4, 2, 3), (4, 5, 3),
<add> axes=((2,), (2,)))
<ide> check_single_tensor_operation('transpose', (4, 2))
<ide>
<ide> def test_shape_operations(self): | 3 |
Python | Python | update doc tests | 6937e311a48db3d06698b8fa4e7f2585b9a90891 | <ide><path>spacy/tests/doc/test_doc_api.py
<ide> def to_str(span):
<ide> def test_doc_api_serialize(en_tokenizer, text):
<ide> tokens = en_tokenizer(text)
<ide> new_tokens = get_doc(tokens.vocab).from_bytes(tokens.to_bytes())
<del> assert tokens.string == new_tokens.string
<add> assert tokens.text == new_tokens.text
<ide> assert [t.text for t in tokens] == [t.text for t in new_tokens]
<ide> assert [t.orth for t in tokens] == [t.orth for t in new_tokens]
<ide> | 1 |
Mixed | Text | add part 2 | 48d9f5807d7ff1cfffc56ac908685fbc49f1ebc4 | <ide><path>docs/tutorials/fundamentals/part-1-overview.md
<ide> import { DetailedExplanation } from '../../components/DetailedExplanation'
<ide>
<ide> Welcome to the Redux Fundamentals tutorial! **This tutorial will introduce you to the core concepts, principles, and patterns for using Redux**. By the time you finish, you should understand the different pieces that make up a Redux app, how data flows when using Redux, and our standard recommended patterns for building Redux apps.
<ide>
<del>In Part 1 of this tutorial, we'll briefly look at a minimal example of a working Redux app to see what the pieces are, and in [Part 2](./part-2-concept-data-flow.md) we'll look at those pieces in more detail and how data flows in a Redux application.
<add>In Part 1 of this tutorial, we'll briefly look at a minimal example of a working Redux app to see what the pieces are, and in [Part 2](./part-2-concepts-data-flow.md) we'll look at those pieces in more detail and how data flows in a Redux application.
<ide>
<ide> Starting in [Part 3](./part-3-actions-reducers.md), we'll use that knowledge to build a small example app that demonstrates how these pieces fit together and talk about how Redux works in practice. After we finish building the working example app "by hand" so that you can see exactly what's happening, we'll talk about some of the standard patterns and abstractions typically used with Redux. Finally, we'll see how these lower-level examples translate into the higher-level patterns that we recommend for actual usage in real applications.
<ide>
<ide> With that in mind, let's review what we've learned so far:
<ide>
<ide> ## What's Next?
<ide>
<del>Now that you know what the basic pieces of a Redux app are, step ahead to [Part 2](./part-2-data-flow),
<add>Now that you know what the basic pieces of a Redux app are, step ahead to [Part 2](./part-2-concepts-data-flow),
<ide> where we'll look at how data flows through a Redux app in more detail.
<ide><path>docs/tutorials/fundamentals/part-2-concepts-data-flow.md
<add>---
<add>id: part-2-concepts-data-flow
<add>title: 'Redux Fundamentals, Part 1: Concepts and Data Flow'
<add>sidebar_label: 'Redux Concepts and Data Flow'
<add>hide_title: true
<add>description: 'The official Fundamentals tutorial for Redux: learn the fundamentals of using Redux'
<add>---
<add>
<add>import { DetailedExplanation } from '../../components/DetailedExplanation'
<add>
<add># Redux Fundamentals, Part 2: Concepts and Data Flow
<add>
<add>:::tip What You'll Learn
<add>
<add>- Key terms and concepts for using Redux
<add>- How data flows through a Redux app
<add>
<add>:::
<add>
<add>## Introduction
<add>
<add>In [Part 1](./part-1-overview.md), we saw a small example of what a working Redux app looks like and
<add>the pieces that make up the app. We also briefly mentioned some of the terms and concepts used with Redux.
<add>
<add>In this section, we'll look at those terms and concepts in more detail, and talk more about how data flows
<add>through a Redux application.
<add>
<add>## Redux Terms and Concepts
<add>
<add>Before we dive into some actual code, let's talk about some of the terms and concepts you'll need to know to use Redux.
<add>
<add>### State Management
<add>
<add>Let's start by looking at a small React counter component. It tracks a number in component state, and increments the number when a button is clicked:
<add>
<add>```jsx
<add>function Counter() {
<add> // State: a counter value
<add> const [counter, setCounter] = useState(0)
<add>
<add> // Action: code that causes an update to the state when something happens
<add> const increment = () => {
<add> setCounter(prevCounter => prevCounter + 1)
<add> }
<add>
<add> // View: the UI definition
<add> return (
<add> <div>
<add> Value: {counter} <button onClick={increment}>Increment</button>
<add> </div>
<add> )
<add>}
<add>```
<add>
<add>It is a self-contained app with the following parts:
<add>
<add>- The **state**, the source of truth that drives our app;
<add>- The **view**, a declarative description of the UI based on the current state
<add>- The **actions**, the events that occur in the app based on user input, and trigger updates in the state
<add>
<add>This is a small example of **"one-way data flow"**:
<add>
<add>- State describes the condition of the app at a specific point in time
<add>- The UI is rendered based on that state
<add>- When something happens (such as a user clicking a button), the state is updated based on what occurred
<add>- The UI re-renders based on the new state
<add>
<add>
<add>
<add>However, the simplicity can break down when we have **multiple components that need to share and use the same state**, especially if those components are located in different parts of the application. Sometimes this can be solved by ["lifting state up"](https://reactjs.org/docs/lifting-state-up.html) to parent components, but that doesn't always help.
<add>
<add>One way to solve this is to extract the shared state from the components, and put it into a centralized location outside the component tree. With this, our component tree becomes a big "view", and any component can access the state or trigger actions, no matter where they are in the tree!
<add>
<add>By defining and separating the concepts involved in state management and enforcing rules that maintain independence between views and states, we give our code more structure and maintainability.
<add>
<add>This is the basic idea behind Redux: a single centralized place to contain the global state in your application, and specific patterns to follow when updating that state to make the code predictable.
<add>
<add>### Immutability
<add>
<add>"Mutable" means "changeable". If something is "immutable", it can never be changed.
<add>
<add>JavaScript objects and arrays are all mutable by default. If I create an object, I can change the contents of its fields. If I create an array, I can change the contents as well:
<add>
<add>```js
<add>const obj = { a: 1, b: 2 }
<add>// still the same object outside, but the contents have changed
<add>obj.b = 3
<add>
<add>const arr = ['a', 'b']
<add>// In the same way, we can change the contents of this array
<add>arr.push('c')
<add>arr[1] = 'd'
<add>```
<add>
<add>This is called _mutating_ the object or array. It's the same object or array reference in memory, but now the contents inside the object have changed.
<add>
<add>**In order to update values immutably, your code must make _copies_ of existing objects/arrays, and then modify the copies**.
<add>
<add>We can do this by hand using JavaScript's array / object spread operators, as well as array methods that return new copies of the array instead of mutating the original array:
<add>
<add>```js
<add>const obj = {
<add> a: {
<add> // To safely update obj.a.c, we have to copy each piece
<add> c: 3
<add> },
<add> b: 2
<add>}
<add>
<add>const obj2 = {
<add> // copy obj
<add> ...obj,
<add> // overwrite a
<add> a: {
<add> // copy obj.a
<add> ...obj.a,
<add> // overwrite c
<add> c: 42
<add> }
<add>}
<add>
<add>const arr = ['a', 'b']
<add>// Create a new copy of arr, with "c" appended to the end
<add>const arr2 = arr.concat('c')
<add>
<add>// or, we can make a copy of the original array:
<add>const arr3 = arr.slice()
<add>// and mutate the copy:
<add>arr3.push('c')
<add>```
<add>
<add>**Redux expects that all state updates are done immutably**. We'll look at where and how this is important a bit later, as well as some easier ways to write immutable update logic.
<add>
<add>:::info Want to Know More?
<add>
<add>For more info on how immutability works in JavaScript, see:
<add>
<add>- [A Visual Guide to References in JavaScript](https://daveceddia.com/javascript-references/)
<add>- [Immutability in React and Redux: The Complete Guide](https://daveceddia.com/react-redux-immutability-guide/)
<add>
<add>:::
<add>
<add>### Terminology
<add>
<add>There's some important Redux terms that you'll need to be familiar with before we continue:
<add>
<add>#### Actions
<add>
<add>An **action** is a plain JavaScript object that has a `type` field. **You can think of an action as an event that describes something that happened in the application**.
<add>
<add>The `type` field should be a string that gives this action a descriptive name, like `"todos/todoAdded"`. We usually write that type string like `"domain/eventName"`, where the first part is the feature or category that this action belongs to, and the second part is the specific thing that happened.
<add>
<add>An action object can have other fields with additional information about what happened. By convention, we put that information in a field called `payload`.
<add>
<add>A typical action object might look like this:
<add>
<add>```js
<add>const addTodoAction = {
<add> type: 'todos/todoAdded',
<add> payload: 'Buy milk'
<add>}
<add>```
<add>
<add>#### Reducers
<add>
<add>A **reducer** is a function that receives the current `state` and an `action` object, decides how to update the state if necessary, and returns the new state: `(state, action) => newState`. **You can think of a reducer as an event listener which handles events based on the received action (event) type.**
<add>
<add>:::info
<add>
<add>"Reducer" functions get their name because they're similar to the kind of callback function you pass to the [`Array.reduce()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) method.
<add>
<add>:::
<add>
<add>Reducers must _always_ follow some specific rules:
<add>
<add>- They should only calculate the new state value based on the `state` and `action` arguments
<add>- They are not allowed to modify the existing `state`. Instead, they must make _immutable updates_, by copying the existing `state` and making changes to the copied values.
<add>- They must not do any asynchronous logic, calculate random values, or cause other "side effects"
<add>
<add>We'll talk more about the rules of reducers later, including why they're important and how to follow them correctly.
<add>
<add>The logic inside reducer functions typically follows the same series of steps:
<add>
<add>- Check to see if the reducer cares about this action
<add> - If so, make a copy of the state, update the copy with new values, and return it
<add>- Otherwise, return the existing state unchanged
<add>
<add>Here's a small example of a reducer, showing the steps that each reducer should follow:
<add>
<add>```js
<add>const initialState = { value: 0 }
<add>
<add>function counterReducer(state = initialState, action) {
<add> // Check to see if the reducer cares about this action
<add> if (action.type === 'counter/incremented') {
<add> // If so, make a copy of `state`
<add> return {
<add> ...state,
<add> // and update the copy with the new value
<add> value: state.value + 1
<add> }
<add> }
<add> // otherwise return the existing state unchanged
<add> return state
<add>}
<add>```
<add>
<add>Reducers can use any kind of logic inside to decide what the new state should be: `if/else`, `switch`, loops, and so on.
<add>
<add><DetailedExplanation title="Detailed Explanation: Why Are They Called 'Reducers?'" >
<add>
<add>The [`Array.reduce()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) method lets you take an array of values, process each item in the array one at a time, and return a single final result. You can think of it as "reducing the array down to one value".
<add>
<add>`Array.reduce()` takes a callback function as an argument, which will be called one time for each item in the array. It takes two arguments:
<add>
<add>- `previousResult`, the value that your callback returned last time
<add>- `currentItem`, the current item in the array
<add>
<add>The first time that the callback runs, there isn't a `previousResult` available, so we need to also pass in an initial value that will be used as the first `previousResult`.
<add>
<add>If we wanted to add together an array of numbers to find out what the total is, we could write a reduce callback that looks like this:
<add>
<add>```js
<add>const numbers = [2, 5, 8]
<add>
<add>const addNumbers = (previousResult, currentItem) => {
<add> console.log({ previousResult, currentItem })
<add> return previousResult + currentItem
<add>}
<add>
<add>const initialValue = 0
<add>
<add>const total = numbers.reduce(addNumbers, initialValue)
<add>// {previousResult: 0, currentItem: 2}
<add>// {previousResult: 2, currentItem: 5}
<add>// {previousResult: 7, currentItem: 8}
<add>
<add>console.log(total)
<add>// 15
<add>```
<add>
<add>Notice that this `addNumber` "reduce callback" function doesn't need to keep track of anything itself. It takes the `previousResult` and `currentItem` arguments, does something with them, and returns a new result value.
<add>
<add>**A Redux reducer function is exactly the same idea as this "reduce callback" function!** It takes a "previous result" (the `state`), and the "current item" (the `action` object), decides a new state value based on those arguments, and returns that new state.
<add>
<add>If we were to create an array of Redux actions, call `reduce()`, and pass in a reducer function, we'd get a final result the same way:
<add>
<add>```js
<add>const actions = [
<add> { type: 'counter/incremented' },
<add> { type: 'counter/incremented' },
<add> { type: 'counter/incremented' }
<add>]
<add>
<add>const initialState = { value: 0 }
<add>
<add>const finalResult = actions.reduce(counterReducer, initialState)
<add>console.log(finalResult)
<add>// {value: 3}
<add>```
<add>
<add>We can say that **Redux reducers reduce a set of actions (over time) into a single state**. The difference is that with `Array.reduce()` it happens all at once, and with Redux, it happens over the lifetime of your running app.
<add>
<add></DetailedExplanation>
<add>
<add>#### Store
<add>
<add>The current Redux application state lives in an object called the **store** .
<add>
<add>The store is created by passing in a reducer, and has a method called `getState` that returns the current state value:
<add>
<add>```js
<add>import { configureStore } from '@reduxjs/toolkit'
<add>
<add>const store = configureStore({ reducer: counterReducer })
<add>
<add>console.log(store.getState())
<add>// {value: 0}
<add>```
<add>
<add>#### Dispatch
<add>
<add>The Redux store has a method called `dispatch`. **The only way to update the state is to call `store.dispatch()` and pass in an action object**. The store will run its reducer function and save the new state value inside, and we can call `getState()` to retrieve the updated value:
<add>
<add>```js
<add>store.dispatch({ type: 'counter/incremented' })
<add>
<add>console.log(store.getState())
<add>// {value: 1}
<add>```
<add>
<add>**You can think of dispatching actions as "triggering an event"** in the application. Something happened, and we want the store to know about it. Reducers act like event listeners, and when they hear an action they are interested in, they update the state in response.
<add>
<add>#### Selectors
<add>
<add>**Selectors** are functions that know how to extract specific pieces of information from a store state value. As an application grows bigger, this can help avoid repeating logic as different parts of the app need to read the same data:
<add>
<add>```js
<add>const selectCounterValue = state => state.value
<add>
<add>const currentValue = selectCounterValue(store.getState())
<add>console.log(currentValue)
<add>// 2
<add>```
<add>
<add>### Redux Application Data Flow
<add>
<add>Earlier, we talked about "one-way data flow", which describes this sequence of steps to update the app:
<add>
<add>- State describes the condition of the app at a specific point in time
<add>- The UI is rendered based on that state
<add>- When something happens (such as a user clicking a button), the state is updated based on what occurred
<add>- The UI re-renders based on the new state
<add>
<add>For Redux specifically, we can break these steps into more detail:
<add>
<add>- Initial setup:
<add> - A Redux store is created using a root reducer function
<add> - The store calls the root reducer once, and saves the return value as its initial `state`
<add> - When the UI is first rendered, UI components access the current state of the Redux store, and use that data to decide what to render. They also subscribe to any future store updates so they can know if the state has changed.
<add>- Updates:
<add> - Something happens in the app, such as a user clicking a button
<add> - The app code dispatches an action to the Redux store, like `dispatch({type: 'counter/incremented'})`
<add> - The store runs the reducer function again with the previous `state` and the current `action`, and saves the return value as the new `state`
<add> - The store notifies all parts of the UI that are subscribed that the store has been updated
<add> - Each UI component that needs data from the store checks to see if the parts of the state they need have changed.
<add> - Each component that sees its data has changed forces a re-render with the new data, so it can update what's shown on the screen
<add>
<add>Here's what that data flow looks like visually:
<add>
<add>
<add>
<add>## What You've Learned
<add>
<add>That counter example was small, but it does show all the working pieces of a real Redux app.
<add>**Everything we'll talk about in the following sections expands on those basic pieces.**
<add>
<add>With that in mind, let's review what we've learned so far:
<add>
<add>:::tip
<add>
<add>- **Redux uses a "one-way data flow" app structure**
<add> - State describes the condition of the app at a point in time, and UI renders based on that state
<add> - When something happens in the app:
<add> - The UI dispatches an action
<add> - The store runs the reducers, and the state is updated based on what occurred
<add> - The store notifies the UI that the state has changed
<add> - The UI re-renders based on the new state
<add>
<add>:::
<add>
<add>## What's Next?
<add>
<add>You should now be familiar with the key concepts and terms that describe the different parts of a Redux app.
<add>
<add>Now, let's see how those pieces work together as we start building a new Redux application in [Part 3](./part-3-state-reducers-actions).
<ide><path>website/sidebars.js
<ide> module.exports = {
<ide> {
<ide> type: 'category',
<ide> label: 'Redux Fundamentals',
<del> items: ['tutorials/fundamentals/part-1-overview']
<add> items: [
<add> 'tutorials/fundamentals/part-1-overview',
<add> 'tutorials/fundamentals/part-2-concepts-data-flow'
<add> ]
<ide> },
<ide> {
<ide> type: 'category', | 3 |
PHP | PHP | fix double line | 40b915fa2bcb7c8f521c09c44bcd6a08c35e677d | <ide><path>tests/TestCase/View/Helper/PaginatorHelperTest.php
<ide> public function testLast()
<ide> $result = $this->Paginator->last(3);
<ide> $this->assertSame('', $result, 'When inside the last links range, no links should be made');
<ide>
<del>
<ide> $result = $this->Paginator->last('lastest', ['url' => ['action' => 'paged']]);
<ide> $expected = [
<ide> 'li' => ['class' => 'last'], | 1 |
PHP | PHP | add windows phone os to mobile browser list | ac408b38e3dda9458795f4df7f01a59db3f78443 | <ide><path>lib/Cake/Network/CakeRequest.php
<ide> class CakeRequest implements ArrayAccess {
<ide> 'Android', 'AvantGo', 'BlackBerry', 'DoCoMo', 'Fennec', 'iPod', 'iPhone',
<ide> 'J2ME', 'MIDP', 'NetFront', 'Nokia', 'Opera Mini', 'Opera Mobi', 'PalmOS', 'PalmSource',
<ide> 'portalmmm', 'Plucker', 'ReqwirelessWeb', 'SonyEricsson', 'Symbian', 'UP\\.Browser',
<del> 'webOS', 'Windows CE', 'Xiino'
<add> 'webOS', 'Windows CE', 'Windows Phone OS', 'Xiino'
<ide> ))
<ide> );
<ide>
<ide><path>lib/Cake/Test/Case/Network/CakeRequestTest.php
<ide> public function testisAjaxFlashAndFriends() {
<ide> $_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0 (Windows NT 5.1; rv:2.0b6pre) Gecko/20100902 Firefox/4.0b6pre Fennec/2.0b1pre';
<ide> $this->assertTrue($request->is('mobile'));
<ide> $this->assertTrue($request->isMobile());
<add>
<add> $_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0 (compatible; MSIE 9.0; Windows Phone OS 7.5; Trident/5.0; IEMobile/9.0; SAMSUNG; OMNIA7)';
<add> $this->assertTrue($request->is('mobile'));
<add> $this->assertTrue($request->isMobile());
<ide> }
<ide>
<ide> /** | 2 |
Javascript | Javascript | set key event handler on control dom element | 465d2afed38e24972f381118eee9916a275a78aa | <ide><path>examples/js/controls/FirstPersonControls.js
<ide> THREE.FirstPersonControls = function ( object, domElement ) {
<ide> this.domElement.removeEventListener( 'mousemove', _onMouseMove, false );
<ide> this.domElement.removeEventListener( 'mouseup', _onMouseUp, false );
<ide>
<del> window.removeEventListener( 'keydown', _onKeyDown, false );
<del> window.removeEventListener( 'keyup', _onKeyUp, false );
<add> this.domElement.removeEventListener( 'keydown', _onKeyDown, false );
<add> this.domElement.removeEventListener( 'keyup', _onKeyUp, false );
<ide>
<ide> };
<ide>
<ide> THREE.FirstPersonControls = function ( object, domElement ) {
<ide> this.domElement.addEventListener( 'mousedown', _onMouseDown, false );
<ide> this.domElement.addEventListener( 'mouseup', _onMouseUp, false );
<ide>
<del> window.addEventListener( 'keydown', _onKeyDown, false );
<del> window.addEventListener( 'keyup', _onKeyUp, false );
<add> this.domElement.addEventListener( 'keydown', _onKeyDown, false );
<add> this.domElement.addEventListener( 'keyup', _onKeyUp, false );
<ide>
<ide> function bind( scope, fn ) {
<ide>
<ide><path>examples/js/controls/FlyControls.js
<ide> THREE.FlyControls = function ( object, domElement ) {
<ide> this.domElement.removeEventListener( 'mousemove', _mousemove, false );
<ide> this.domElement.removeEventListener( 'mouseup', _mouseup, false );
<ide>
<del> window.removeEventListener( 'keydown', _keydown, false );
<del> window.removeEventListener( 'keyup', _keyup, false );
<add> this.domElement.removeEventListener( 'keydown', _keydown, false );
<add> this.domElement.removeEventListener( 'keyup', _keyup, false );
<ide>
<ide> };
<ide>
<ide> THREE.FlyControls = function ( object, domElement ) {
<ide> this.domElement.addEventListener( 'mousedown', _mousedown, false );
<ide> this.domElement.addEventListener( 'mouseup', _mouseup, false );
<ide>
<del> window.addEventListener( 'keydown', _keydown, false );
<del> window.addEventListener( 'keyup', _keyup, false );
<add> this.domElement.addEventListener( 'keydown', _keydown, false );
<add> this.domElement.addEventListener( 'keyup', _keyup, false );
<ide>
<ide> this.updateMovementVector();
<ide> this.updateRotationVector();
<ide><path>examples/js/controls/OrbitControls.js
<ide> THREE.OrbitControls = function ( object, domElement ) {
<ide> document.removeEventListener( 'mousemove', onMouseMove, false );
<ide> document.removeEventListener( 'mouseup', onMouseUp, false );
<ide>
<del> window.removeEventListener( 'keydown', onKeyDown, false );
<add> scope.domElement.removeEventListener( 'keydown', onKeyDown, false );
<ide>
<ide> //scope.dispatchEvent( { type: 'dispose' } ); // should this be added here?
<ide>
<ide> THREE.OrbitControls = function ( object, domElement ) {
<ide> scope.domElement.addEventListener( 'touchend', onTouchEnd, false );
<ide> scope.domElement.addEventListener( 'touchmove', onTouchMove, false );
<ide>
<del> window.addEventListener( 'keydown', onKeyDown, false );
<add> scope.domElement.addEventListener( 'keydown', onKeyDown, false );
<ide>
<ide> // force an update at start
<ide>
<ide><path>examples/js/controls/OrthographicTrackballControls.js
<ide> THREE.OrthographicTrackballControls = function ( object, domElement ) {
<ide>
<ide> if ( _this.enabled === false ) return;
<ide>
<del> window.removeEventListener( 'keydown', keydown );
<add> _this.domElement.removeEventListener( 'keydown', keydown );
<ide>
<ide> _prevState = _state;
<ide>
<ide> THREE.OrthographicTrackballControls = function ( object, domElement ) {
<ide>
<ide> _state = _prevState;
<ide>
<del> window.addEventListener( 'keydown', keydown, false );
<add> _this.domElement.addEventListener( 'keydown', keydown, false );
<ide>
<ide> }
<ide>
<ide> THREE.OrthographicTrackballControls = function ( object, domElement ) {
<ide> document.removeEventListener( 'mousemove', mousemove, false );
<ide> document.removeEventListener( 'mouseup', mouseup, false );
<ide>
<del> window.removeEventListener( 'keydown', keydown, false );
<del> window.removeEventListener( 'keyup', keyup, false );
<add> this.domElement.removeEventListener( 'keydown', keydown, false );
<add> this.domElement.removeEventListener( 'keyup', keyup, false );
<ide>
<ide> };
<ide>
<ide> THREE.OrthographicTrackballControls = function ( object, domElement ) {
<ide> this.domElement.addEventListener( 'touchend', touchend, false );
<ide> this.domElement.addEventListener( 'touchmove', touchmove, false );
<ide>
<del> window.addEventListener( 'keydown', keydown, false );
<del> window.addEventListener( 'keyup', keyup, false );
<add> this.domElement.addEventListener( 'keydown', keydown, false );
<add> this.domElement.addEventListener( 'keyup', keyup, false );
<ide>
<ide> this.handleResize();
<ide>
<ide><path>examples/js/controls/TrackballControls.js
<ide> THREE.TrackballControls = function ( object, domElement ) {
<ide>
<ide> if ( _this.enabled === false ) return;
<ide>
<del> window.removeEventListener( 'keydown', keydown );
<add> _this.domElement.removeEventListener( 'keydown', keydown );
<ide>
<ide> _prevState = _state;
<ide>
<ide> THREE.TrackballControls = function ( object, domElement ) {
<ide>
<ide> _state = _prevState;
<ide>
<del> window.addEventListener( 'keydown', keydown, false );
<add> _this.domElement.addEventListener( 'keydown', keydown, false );
<ide>
<ide> }
<ide>
<ide> THREE.TrackballControls = function ( object, domElement ) {
<ide> document.removeEventListener( 'mousemove', mousemove, false );
<ide> document.removeEventListener( 'mouseup', mouseup, false );
<ide>
<del> window.removeEventListener( 'keydown', keydown, false );
<del> window.removeEventListener( 'keyup', keyup, false );
<add> this.domElement.removeEventListener( 'keydown', keydown, false );
<add> this.domElement.removeEventListener( 'keyup', keyup, false );
<ide>
<ide> };
<ide>
<ide> THREE.TrackballControls = function ( object, domElement ) {
<ide> this.domElement.addEventListener( 'touchend', touchend, false );
<ide> this.domElement.addEventListener( 'touchmove', touchmove, false );
<ide>
<del> window.addEventListener( 'keydown', keydown, false );
<del> window.addEventListener( 'keyup', keyup, false );
<add> this.domElement.addEventListener( 'keydown', keydown, false );
<add> this.domElement.addEventListener( 'keyup', keyup, false );
<ide>
<ide> this.handleResize();
<ide> | 5 |
Ruby | Ruby | remove obsolete autoload | cf7c475ef187e88044cba139cc2e1dbf5f180b15 | <ide><path>activerecord/lib/active_record/associations.rb
<ide> module Associations # :nodoc:
<ide> autoload :HasAndBelongsToManyAssociation, 'active_record/associations/has_and_belongs_to_many_association'
<ide> autoload :HasManyAssociation, 'active_record/associations/has_many_association'
<ide> autoload :HasManyThroughAssociation, 'active_record/associations/has_many_through_association'
<del> autoload :NestedHasManyThroughAssociation, 'active_record/associations/nested_has_many_through_association'
<ide> autoload :HasOneAssociation, 'active_record/associations/has_one_association'
<ide> autoload :HasOneThroughAssociation, 'active_record/associations/has_one_through_association'
<ide> autoload :AliasTracker, 'active_record/associations/alias_tracker' | 1 |
Ruby | Ruby | keep all session tests in the same file | 8a8325766a870df0abcf4662fb71660173737253 | <ide><path>railties/test/application/middleware/flash_test.rb
<del>require 'isolation/abstract_unit'
<del>require 'rack/test'
<del>
<del>module ApplicationTests
<del> class FlashTest < ActiveSupport::TestCase
<del> include ActiveSupport::Testing::Isolation
<del> include Rack::Test::Methods
<del>
<del> def setup
<del> build_app
<del> boot_rails
<del> end
<del>
<del> def teardown
<del> teardown_app
<del> end
<del>
<del> test 'calling reset_session on request does not trigger an error for API apps' do
<del> add_to_config 'config.api_only = true'
<del>
<del> controller :test, <<-RUBY
<del> class TestController < ApplicationController
<del> def dump_flash
<del> request.reset_session
<del> render plain: 'It worked!'
<del> end
<del> end
<del> RUBY
<del>
<del> app_file 'config/routes.rb', <<-RUBY
<del> Rails.application.routes.draw do
<del> get '/dump_flash' => "test#dump_flash"
<del> end
<del> RUBY
<del>
<del> app 'development'
<del>
<del> get '/dump_flash'
<del>
<del> assert_equal 200, last_response.status
<del> assert_equal 'It worked!', last_response.body
<del>
<del> refute Rails.application.middleware.include?(ActionDispatch::Flash)
<del> end
<del> end
<del>end
<ide><path>railties/test/application/middleware/session_test.rb
<ide> def read_raw_cookie
<ide> get '/foo/read_raw_cookie'
<ide> assert_equal 2, verifier.verify(last_response.body)['foo']
<ide> end
<add>
<add> test 'calling reset_session on request does not trigger an error for API apps' do
<add> add_to_config 'config.api_only = true'
<add>
<add> controller :test, <<-RUBY
<add> class TestController < ApplicationController
<add> def dump_flash
<add> request.reset_session
<add> render plain: 'It worked!'
<add> end
<add> end
<add> RUBY
<add>
<add> app_file 'config/routes.rb', <<-RUBY
<add> Rails.application.routes.draw do
<add> get '/dump_flash' => "test#dump_flash"
<add> end
<add> RUBY
<add>
<add> require "#{app_path}/config/environment"
<add>
<add> get '/dump_flash'
<add>
<add> assert_equal 200, last_response.status
<add> assert_equal 'It worked!', last_response.body
<add>
<add> refute Rails.application.middleware.include?(ActionDispatch::Flash)
<add> end
<ide> end
<ide> end | 2 |
PHP | PHP | fix eloquent builder | 32d0f164424ab5b4a2bff2ed927812ae49bd8051 | <ide><path>src/Illuminate/Database/Eloquent/Builder.php
<ide> public function chunkById($count, callable $callback, $column = 'id')
<ide> $lastId = 0;
<ide>
<ide> do {
<del> $results = $this->forPageAfterId($count, $lastId, $column)->get();
<add> $clone = clone $this;
<add>
<add> $results = $clone->forPageAfterId($count, $lastId, $column)->get();
<ide>
<ide> $countResults = $results->count();
<ide> | 1 |
Ruby | Ruby | remove deprecation warnings from tests | f944d528c495fe2ac04caeb1354260eae953f4c7 | <ide><path>activerecord/test/cases/associations/has_many_associations_test.rb
<ide> def test_depends_and_nullify
<ide> end
<ide>
<ide> def test_restrict
<del> # ActiveRecord::Base.dependent_restrict_raises = true, by default
<add> option_before = ActiveRecord::Base.dependent_restrict_raises
<add> ActiveRecord::Base.dependent_restrict_raises = true
<ide>
<ide> firm = RestrictedFirm.create!(:name => 'restrict')
<ide> firm.companies.create(:name => 'child')
<ide> def test_restrict
<ide> assert_raise(ActiveRecord::DeleteRestrictionError) { firm.destroy }
<ide> assert RestrictedFirm.exists?(:name => 'restrict')
<ide> assert firm.companies.exists?(:name => 'child')
<add> ensure
<add> ActiveRecord::Base.dependent_restrict_raises = option_before
<ide> end
<ide>
<ide> def test_restrict_when_dependent_restrict_raises_config_set_to_false
<del> # ActiveRecord::Base.dependent_restrict_raises = true, by default
<del>
<add> option_before = ActiveRecord::Base.dependent_restrict_raises
<ide> ActiveRecord::Base.dependent_restrict_raises = false
<del> # add an error on the model instead of raising ActiveRecord::DeleteRestrictionError
<ide>
<ide> firm = RestrictedFirm.create!(:name => 'restrict')
<ide> firm.companies.create(:name => 'child')
<ide> def test_restrict_when_dependent_restrict_raises_config_set_to_false
<ide> assert RestrictedFirm.exists?(:name => 'restrict')
<ide> assert firm.companies.exists?(:name => 'child')
<ide> ensure
<del> ActiveRecord::Base.dependent_restrict_raises = true
<add> ActiveRecord::Base.dependent_restrict_raises = option_before
<ide> end
<ide>
<ide> def test_included_in_collection
<ide> def test_replace
<ide> end
<ide>
<ide> def test_building_has_many_association_with_restrict_dependency
<add> option_before = ActiveRecord::Base.dependent_restrict_raises
<add> ActiveRecord::Base.dependent_restrict_raises = true
<add>
<ide> klass = Class.new(ActiveRecord::Base)
<del>
<del> assert_deprecated { klass.has_many :companies, :dependent => :restrict }
<add>
<add> assert_deprecated { klass.has_many :companies, :dependent => :restrict }
<ide> assert_not_deprecated { klass.has_many :companies }
<add> ensure
<add> ActiveRecord::Base.dependent_restrict_raises = option_before
<ide> end
<ide> end
<ide><path>activerecord/test/cases/associations/has_one_associations_test.rb
<ide> def test_dependence_with_nil_associate
<ide> end
<ide>
<ide> def test_dependence_with_restrict
<del> # ActiveRecord::Base.dependent_restrict_raises = true, by default
<add> option_before = ActiveRecord::Base.dependent_restrict_raises
<add> ActiveRecord::Base.dependent_restrict_raises = true
<ide>
<ide> firm = RestrictedFirm.create!(:name => 'restrict')
<ide> firm.create_account(:credit_limit => 10)
<ide> def test_dependence_with_restrict
<ide> assert_raise(ActiveRecord::DeleteRestrictionError) { firm.destroy }
<ide> assert RestrictedFirm.exists?(:name => 'restrict')
<ide> assert firm.account.present?
<add> ensure
<add> ActiveRecord::Base.dependent_restrict_raises = option_before
<ide> end
<ide>
<ide> def test_dependence_with_restrict_with_dependent_restrict_raises_config_set_to_false
<del> # ActiveRecord::Base.dependent_restrict_raises = true, by default
<del>
<add> option_before = ActiveRecord::Base.dependent_restrict_raises
<ide> ActiveRecord::Base.dependent_restrict_raises = false
<del> # adds an error on the model instead of raising ActiveRecord::DeleteRestrictionError
<ide>
<ide> firm = RestrictedFirm.create!(:name => 'restrict')
<ide> firm.create_account(:credit_limit => 10)
<ide> def test_dependence_with_restrict_with_dependent_restrict_raises_config_set_to_f
<ide> assert RestrictedFirm.exists?(:name => 'restrict')
<ide> assert firm.account.present?
<ide> ensure
<del> ActiveRecord::Base.dependent_restrict_raises = true
<add> ActiveRecord::Base.dependent_restrict_raises = option_before
<ide> end
<ide>
<ide> def test_successful_build_association
<ide> def test_association_attributes_are_available_to_after_initialize
<ide> end
<ide>
<ide> def test_building_has_one_association_with_dependent_restrict
<add> option_before = ActiveRecord::Base.dependent_restrict_raises
<add> ActiveRecord::Base.dependent_restrict_raises = true
<add>
<ide> klass = Class.new(ActiveRecord::Base)
<del>
<add>
<ide> assert_deprecated { klass.has_one :account, :dependent => :restrict }
<ide> assert_not_deprecated { klass.has_one :account }
<add> ensure
<add> ActiveRecord::Base.dependent_restrict_raises = option_before
<ide> end
<ide> end
<ide><path>activerecord/test/cases/helper.rb
<ide> # Enable Identity Map only when ENV['IM'] is set to "true"
<ide> ActiveRecord::IdentityMap.enabled = (ENV['IM'] == "true")
<ide>
<add># Avoid deprecation warning setting dependent_restric_raises to false. The default is true
<add>ActiveRecord::Base.dependent_restrict_raises = false
<add>
<ide> # Connect to the database
<ide> ARTest.connect
<ide> | 3 |
Ruby | Ruby | use parenthesis so limit works on all dbs | d3b2596884d884b72d50de2b7ced6097df670736 | <ide><path>activerecord/test/cases/base_test.rb
<ide> def test_limit_should_sanitize_sql_injection_for_limit_with_comas
<ide> Topic.limit("1, 7 procedure help()").all
<ide> end
<ide> end
<del>
<del> unless current_adapter?(:MysqlAdapter)
<del> def test_limit_should_allow_sql_literal
<del> assert_equal 1, Topic.limit(Arel.sql('2-1')).all.length
<del> end
<add>
<add> def test_limit_should_allow_sql_literal
<add> assert_equal 1, Topic.limit(Arel.sql('(2 - 1)')).all.length
<ide> end
<del>
<add>
<ide> def test_select_symbol
<ide> topic_ids = Topic.select(:id).map(&:id).sort
<ide> assert_equal Topic.find(:all).map(&:id).sort, topic_ids | 1 |
Mixed | Javascript | remove redundant imports in several examples | dd264f582f547508b5b5af2cf1dc665a9c53f8e5 | <ide><path>examples/auth0/pages/about.js
<del>import React from 'react'
<del>
<ide> import Layout from '../components/layout'
<ide> import { useFetchUser } from '../lib/user'
<ide>
<ide><path>examples/auth0/pages/index.js
<del>import React from 'react'
<del>
<ide> import Layout from '../components/layout'
<ide> import { useFetchUser } from '../lib/user'
<ide>
<ide><path>examples/auth0/pages/profile.js
<del>import React from 'react'
<del>
<ide> // This import is only needed when checking authentication status directly from getInitialProps
<ide> // import auth0 from '../lib/auth0'
<ide> import { useFetchUser } from '../lib/user'
<ide><path>examples/with-apollo-and-redux/components/Clock.js
<del>import React from 'react'
<ide> import { useSelector, shallowEqual } from 'react-redux'
<ide>
<ide> const useClock = () => {
<ide><path>examples/with-apollo-and-redux/components/Counter.js
<del>import React from 'react'
<ide> import { useSelector, useDispatch } from 'react-redux'
<ide>
<ide> const useCounter = () => {
<ide><path>examples/with-apollo-and-redux/components/ErrorMessage.js
<del>import React from 'react'
<ide> import PropTypes from 'prop-types'
<ide>
<ide> const ErrorMessage = ({ message }) => (
<ide><path>examples/with-apollo-and-redux/components/Layout.js
<del>import React from 'react'
<ide> import Nav from './Nav'
<ide> import PropTypes from 'prop-types'
<ide>
<ide><path>examples/with-apollo-and-redux/components/PostUpvoter.js
<del>import React from 'react'
<ide> import { useMutation } from '@apollo/react-hooks'
<ide> import gql from 'graphql-tag'
<ide> import PropTypes from 'prop-types'
<ide><path>examples/with-apollo-and-redux/lib/apollo.js
<del>import React from 'react'
<ide> import Head from 'next/head'
<ide> import { ApolloProvider } from '@apollo/react-hooks'
<ide> import { ApolloClient } from 'apollo-client'
<ide><path>examples/with-apollo-and-redux/lib/redux.js
<del>import React from 'react'
<ide> import { Provider } from 'react-redux'
<ide> import { initializeStore } from '../store'
<ide> import App from 'next/app'
<ide><path>examples/with-apollo-and-redux/pages/index.js
<del>import React from 'react'
<ide> import { useDispatch } from 'react-redux'
<ide> import { withRedux } from '../lib/redux'
<ide> import { compose } from 'redux'
<ide><path>examples/with-apollo-and-redux/pages/redux.js
<del>import React from 'react'
<ide> import { useDispatch } from 'react-redux'
<ide> import { withRedux } from '../lib/redux'
<ide> import useInterval from '../lib/useInterval'
<ide><path>examples/with-apollo/components/PostUpvoter.js
<del>import React from 'react'
<ide> import { useMutation } from '@apollo/react-hooks'
<ide> import gql from 'graphql-tag'
<ide>
<ide><path>examples/with-apollo/lib/apollo.js
<del>import React from 'react'
<ide> import App from 'next/app'
<ide> import Head from 'next/head'
<ide> import { ApolloProvider } from '@apollo/react-hooks'
<ide><path>examples/with-context-api/components/Counter.js
<del>import React, { useReducer, useContext } from 'react'
<add>import { useReducer, useContext, createContext } from 'react'
<ide>
<del>const CounterStateContext = React.createContext()
<del>const CounterDispatchContext = React.createContext()
<add>const CounterStateContext = createContext()
<add>const CounterDispatchContext = createContext()
<ide>
<ide> const reducer = (state, action) => {
<ide> switch (action.type) {
<ide><path>examples/with-context-api/pages/about.js
<del>import React from 'react'
<ide> import Link from 'next/link'
<ide> import { useCount, useDispatchCount } from '../components/Counter'
<ide>
<ide><path>examples/with-context-api/pages/index.js
<del>import React from 'react'
<ide> import Link from 'next/link'
<ide> import { useCount, useDispatchCount } from '../components/Counter'
<ide>
<ide><path>examples/with-docker/pages/index.js
<del>import React from 'react'
<del>
<ide> export default () => {
<ide> return <h1>Hello World!</h1>
<ide> }
<ide><path>examples/with-emotion/pages/_app.js
<del>import * as React from 'react'
<ide> import NextApp from 'next/app'
<ide> import { CacheProvider } from '@emotion/core'
<ide>
<ide><path>examples/with-redux-observable/components/CharacterInfo.js
<del>import React from 'react'
<ide> import { connect } from 'react-redux'
<ide>
<ide> const CharacterInfo = ({
<ide><path>examples/with-redux-observable/pages/_app.js
<del>import React from 'react'
<ide> import { Provider } from 'react-redux'
<ide> import App from 'next/app'
<ide> import withRedux from 'next-redux-wrapper'
<ide><path>examples/with-redux-observable/pages/index.js
<del>import React from 'react'
<add>import { Component } from 'react'
<ide> import Link from 'next/link'
<ide> import { of, Subject } from 'rxjs'
<ide> import { StateObservable } from 'redux-observable'
<ide> import CharacterInfo from '../components/CharacterInfo'
<ide> import { rootEpic } from '../redux/epics'
<ide> import * as actions from '../redux/actions'
<ide>
<del>class Counter extends React.Component {
<add>class Counter extends Component {
<ide> static async getInitialProps({ store, isServer }) {
<ide> const state$ = new StateObservable(new Subject(), store.getState())
<ide> const resultAction = await rootEpic(
<ide><path>examples/with-redux-observable/pages/other.js
<del>import React from 'react'
<ide> import Link from 'next/link'
<ide>
<ide> const OtherPage = () => (
<ide><path>examples/with-redux-persist/components/counter.js
<del>import React, { Component } from 'react'
<add>import { Component } from 'react'
<ide> import { connect } from 'react-redux'
<ide> import { bindActionCreators } from 'redux'
<ide> import { incrementCount, decrementCount, resetCount } from '../store'
<ide><path>examples/with-redux-persist/components/data-list.js
<del>import React, { Component } from 'react'
<add>import { Component } from 'react'
<ide> import { connect } from 'react-redux'
<ide> import { bindActionCreators } from 'redux'
<ide> import { loadExampleData, loadingExampleDataFailure } from '../store'
<ide><path>examples/with-redux-persist/lib/with-redux-store.js
<del>import React from 'react'
<add>import { Component } from 'react'
<ide> import { initializeStore } from '../store'
<ide>
<ide> const isServer = typeof window === 'undefined'
<ide> function getOrCreateStore(initialState) {
<ide> }
<ide>
<ide> export default App => {
<del> return class AppWithRedux extends React.Component {
<add> return class AppWithRedux extends Component {
<ide> static async getInitialProps(appContext) {
<ide> // Get or Create the store with `undefined` as initialState
<ide> // This allows you to set a custom default initialState
<ide><path>examples/with-redux-persist/pages/_app.js
<ide> import App from 'next/app'
<del>import React from 'react'
<ide> import withReduxStore from '../lib/with-redux-store'
<ide> import { Provider } from 'react-redux'
<ide> import { persistStore } from 'redux-persist'
<ide><path>examples/with-redux-persist/pages/index.js
<del>import React from 'react'
<add>import { Component } from 'react'
<ide> import { connect } from 'react-redux'
<ide> import { startClock, serverRenderClock } from '../store'
<ide> import Examples from '../components/examples'
<ide>
<del>class Index extends React.Component {
<add>class Index extends Component {
<ide> static getInitialProps({ reduxStore, req }) {
<ide> const isServer = !!req
<ide> // DISPATCH ACTIONS HERE ONLY WITH `reduxStore.dispatch`
<ide><path>examples/with-redux-saga/components/clock.js
<del>import React from 'react'
<del>
<ide> const pad = n => (n < 10 ? `0${n}` : n)
<ide>
<ide> const format = t => {
<ide><path>examples/with-redux-saga/components/counter.js
<del>import React, { Component } from 'react'
<add>import { Component } from 'react'
<ide> import { connect } from 'react-redux'
<ide>
<ide> import { increment, decrement, reset } from '../actions'
<ide><path>examples/with-redux-saga/pages/_app.js
<ide> import App from 'next/app'
<del>import React from 'react'
<ide> import { Provider } from 'react-redux'
<ide> import withRedux from 'next-redux-wrapper'
<ide> import withReduxSaga from 'next-redux-saga'
<ide><path>examples/with-redux-saga/pages/index.js
<del>import React from 'react'
<add>import { Component } from 'react'
<ide> import { connect } from 'react-redux'
<ide>
<ide> import { loadData, startClock, tickClock } from '../actions'
<ide> import Page from '../components/page'
<ide>
<del>class Index extends React.Component {
<add>class Index extends Component {
<ide> static async getInitialProps(props) {
<ide> const { store, isServer } = props.ctx
<ide> store.dispatch(tickClock(isServer))
<ide><path>examples/with-redux-saga/pages/other.js
<del>import React from 'react'
<add>import { Component } from 'react'
<ide> import { connect } from 'react-redux'
<ide>
<ide> import { startClock, tickClock } from '../actions'
<ide> import Page from '../components/page'
<ide>
<del>class Other extends React.Component {
<add>class Other extends Component {
<ide> static async getInitialProps(props) {
<ide> const { store, isServer } = props.ctx
<ide> store.dispatch(tickClock(isServer))
<ide><path>examples/with-redux-thunk/components/clock.js
<del>import React from 'react'
<del>
<ide> const pad = n => (n < 10 ? `0${n}` : n)
<ide>
<ide> const format = t =>
<ide><path>examples/with-redux-thunk/components/counter.js
<del>import React from 'react'
<ide> import { useSelector, useDispatch } from 'react-redux'
<ide> import { incrementCount, decrementCount, resetCount } from '../actions'
<ide>
<ide><path>examples/with-redux-thunk/components/examples.js
<del>import React from 'react'
<ide> import { useSelector } from 'react-redux'
<ide> import Clock from './clock'
<ide> import Counter from './counter'
<ide><path>examples/with-redux-thunk/lib/with-redux-store.js
<del>import React from 'react'
<add>import { Component } from 'react'
<ide> import initializeStore from '../store'
<ide>
<ide> const __NEXT_REDUX_STORE__ = '__NEXT_REDUX_STORE__'
<ide> function getOrCreateStore(initialState) {
<ide> }
<ide>
<ide> export default App => {
<del> return class AppWithRedux extends React.Component {
<add> return class AppWithRedux extends Component {
<ide> static async getInitialProps(appContext) {
<ide> // Get or Create the store with `undefined` as initialState
<ide> // This allows you to set a custom default initialState
<ide><path>examples/with-redux-thunk/pages/_app.js
<del>import React from 'react'
<ide> import { Provider } from 'react-redux'
<ide> import App from 'next/app'
<ide> import withReduxStore from '../lib/with-redux-store'
<ide><path>examples/with-redux-thunk/pages/index.js
<del>import React, { PureComponent } from 'react'
<add>import { PureComponent } from 'react'
<ide> import { connect } from 'react-redux'
<ide> import Link from 'next/link'
<ide> import { startClock, serverRenderClock } from '../actions'
<ide><path>examples/with-redux-thunk/pages/show-redux-state.js
<del>import React from 'react'
<ide> import { connect } from 'react-redux'
<ide> import Link from 'next/link'
<ide>
<ide><path>examples/with-redux-toolkit/components/clock.js
<del>import React from 'react'
<ide> import { useSelector, shallowEqual } from 'react-redux'
<ide>
<ide> const useClock = () => {
<ide><path>examples/with-redux-toolkit/components/counter.js
<del>import React from 'react'
<ide> import { createAction } from '@reduxjs/toolkit'
<ide> import { useSelector, useDispatch } from 'react-redux'
<ide>
<ide><path>examples/with-redux-toolkit/pages/_app.js
<del>import React from 'react'
<ide> import { Provider } from 'react-redux'
<ide> import { store } from '../store'
<ide>
<ide><path>examples/with-redux-toolkit/pages/index.js
<del>import React from 'react'
<ide> import { createAction } from '@reduxjs/toolkit'
<ide> import { connect } from 'react-redux'
<ide> import useInterval from '../lib/useInterval'
<ide><path>examples/with-styled-components/README.md
<ide> When wrapping a [Link](https://nextjs.org/docs/api-reference/next/link) from `ne
<ide> **components/StyledLink.js**
<ide>
<ide> ```javascript
<del>import React from 'react'
<ide> import Link from 'next/link'
<ide> import styled from 'styled-components'
<ide>
<ide> export default styled(StyledLink)`
<ide> **pages/index.js**
<ide>
<ide> ```javascript
<del>import React from 'react'
<ide> import StyledLink from '../components/StyledLink'
<ide>
<ide> export default () => (
<ide><path>examples/with-styled-components/pages/_app.js
<ide> import App from 'next/app'
<del>import React from 'react'
<ide> import { ThemeProvider } from 'styled-components'
<ide>
<ide> const theme = {
<ide><path>examples/with-styled-components/pages/index.js
<del>import React from 'react'
<ide> import styled from 'styled-components'
<ide>
<ide> const Title = styled.h1` | 47 |
Javascript | Javascript | move hide/unhide logic to offscreen component | cb7075399376f4b913500c4e377d790138b31c74 | <ide><path>packages/react-reconciler/src/ReactFiber.new.js
<ide> import type {WorkTag} from './ReactWorkTags';
<ide> import type {TypeOfMode} from './ReactTypeOfMode';
<ide> import type {ExpirationTimeOpaque} from './ReactFiberExpirationTime.new';
<ide> import type {SuspenseInstance} from './ReactFiberHostConfig';
<add>import type {OffscreenProps} from './ReactFiberOffscreenComponent';
<ide>
<ide> import invariant from 'shared/invariant';
<ide> import {
<ide> export function createFiberFromSuspenseList(
<ide> }
<ide>
<ide> export function createFiberFromOffscreen(
<del> pendingProps: any,
<add> pendingProps: OffscreenProps,
<ide> mode: TypeOfMode,
<ide> expirationTime: ExpirationTimeOpaque,
<ide> key: null | string,
<ide><path>packages/react-reconciler/src/ReactFiberBeginWork.new.js
<ide> import type {
<ide> SuspenseListTailMode,
<ide> } from './ReactFiberSuspenseComponent.new';
<ide> import type {SuspenseContext} from './ReactFiberSuspenseContext.new';
<add>import type {
<add> OffscreenProps,
<add> OffscreenState,
<add>} from './ReactFiberOffscreenComponent';
<ide>
<ide> import checkPropTypes from 'shared/checkPropTypes';
<ide>
<ide> function updateOffscreenComponent(
<ide> workInProgress: Fiber,
<ide> renderExpirationTime: ExpirationTimeOpaque,
<ide> ) {
<del> const nextChildren = workInProgress.pendingProps;
<add> const nextProps: OffscreenProps = workInProgress.pendingProps;
<add> const nextChildren = nextProps.children;
<add>
<add> if (current !== null) {
<add> if (nextProps.mode === 'hidden') {
<add> // TODO: Should currently be unreachable because Offscreen is only used as
<add> // an implementation detail of Suspense. Once this is a public API, it
<add> // will need to create an OffscreenState.
<add> } else {
<add> // Clear the offscreen state.
<add> workInProgress.memoizedState = null;
<add> }
<add> }
<add>
<ide> reconcileChildren(
<ide> current,
<ide> workInProgress,
<ide> function updateSuspenseComponent(
<ide> }
<ide>
<ide> if (showFallback) {
<add> const nextPrimaryChildren = nextProps.children;
<ide> const nextFallbackChildren = nextProps.fallback;
<ide> const fallbackFragment = mountSuspenseFallbackChildren(
<ide> workInProgress,
<add> nextPrimaryChildren,
<ide> nextFallbackChildren,
<ide> renderExpirationTime,
<ide> );
<add> const primaryChildFragment: Fiber = (workInProgress.child: any);
<add> primaryChildFragment.memoizedState = ({baseTime: NoWork}: OffscreenState);
<ide> workInProgress.memoizedState = mountSuspenseState(renderExpirationTime);
<ide> return fallbackFragment;
<ide> } else {
<ide> function updateSuspenseComponent(
<ide> } else {
<ide> // Suspended but we should no longer be in dehydrated mode.
<ide> // Therefore we now have to render the fallback.
<add> const nextPrimaryChildren = nextProps.children;
<ide> const nextFallbackChildren = nextProps.fallback;
<ide> const fallbackChildFragment = mountSuspenseFallbackAfterRetryWithoutHydrating(
<ide> current,
<ide> workInProgress,
<add> nextPrimaryChildren,
<ide> nextFallbackChildren,
<ide> renderExpirationTime,
<ide> );
<del>
<add> const primaryChildFragment: Fiber = (workInProgress.child: any);
<add> primaryChildFragment.memoizedState = ({
<add> baseTime: NoWork,
<add> }: OffscreenState);
<ide> workInProgress.memoizedState = updateSuspenseState(
<ide> current.memoizedState,
<ide> renderExpirationTime,
<ide> function updateSuspenseComponent(
<ide>
<ide> if (showFallback) {
<ide> const nextFallbackChildren = nextProps.fallback;
<add> const nextPrimaryChildren = nextProps.children;
<ide> const fallbackChildFragment = updateSuspenseFallbackChildren(
<ide> current,
<ide> workInProgress,
<add> nextPrimaryChildren,
<ide> nextFallbackChildren,
<ide> renderExpirationTime,
<ide> );
<ide> const primaryChildFragment: Fiber = (workInProgress.child: any);
<add> primaryChildFragment.memoizedState = ({
<add> baseTime: NoWork,
<add> }: OffscreenState);
<ide> primaryChildFragment.childExpirationTime_opaque = getRemainingWorkInPrimaryTree(
<ide> current,
<ide> workInProgress,
<ide> function updateSuspenseComponent(
<ide> if (showFallback) {
<ide> // Timed out.
<ide> const nextFallbackChildren = nextProps.fallback;
<add> const nextPrimaryChildren = nextProps.children;
<ide> const fallbackChildFragment = updateSuspenseFallbackChildren(
<ide> current,
<ide> workInProgress,
<add> nextPrimaryChildren,
<ide> nextFallbackChildren,
<ide> renderExpirationTime,
<ide> );
<ide> const primaryChildFragment: Fiber = (workInProgress.child: any);
<add> primaryChildFragment.memoizedState = ({
<add> baseTime: NoWork,
<add> }: OffscreenState);
<ide> primaryChildFragment.childExpirationTime_opaque = getRemainingWorkInPrimaryTree(
<ide> current,
<ide> workInProgress,
<ide> function mountSuspensePrimaryChildren(
<ide> renderExpirationTime,
<ide> ) {
<ide> const mode = workInProgress.mode;
<add> const primaryChildProps: OffscreenProps = {
<add> mode: 'visible',
<add> children: primaryChildren,
<add> };
<ide> const primaryChildFragment = createFiberFromOffscreen(
<del> primaryChildren,
<add> primaryChildProps,
<ide> mode,
<ide> renderExpirationTime,
<ide> null,
<ide> function mountSuspensePrimaryChildren(
<ide>
<ide> function mountSuspenseFallbackChildren(
<ide> workInProgress,
<add> primaryChildren,
<ide> fallbackChildren,
<ide> renderExpirationTime,
<ide> ) {
<ide> const mode = workInProgress.mode;
<del>
<ide> const progressedPrimaryFragment: Fiber | null = workInProgress.child;
<ide>
<add> const primaryChildProps: OffscreenProps = {
<add> mode: 'hidden',
<add> children: primaryChildren,
<add> };
<add>
<ide> let primaryChildFragment;
<ide> let fallbackChildFragment;
<ide> if ((mode & BlockingMode) === NoMode && progressedPrimaryFragment !== null) {
<ide> // In legacy mode, we commit the primary tree as if it successfully
<ide> // completed, even though it's in an inconsistent state.
<ide> primaryChildFragment = progressedPrimaryFragment;
<ide> primaryChildFragment.childExpirationTime_opaque = NoWork;
<add> primaryChildFragment.pendingProps = primaryChildProps;
<ide>
<ide> if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
<ide> // Reset the durations from the first pass so they aren't included in the
<ide> function mountSuspenseFallbackChildren(
<ide> null,
<ide> );
<ide> } else {
<del> primaryChildFragment = createFiberFromOffscreen(null, mode, NoWork, null);
<add> primaryChildFragment = createFiberFromOffscreen(
<add> primaryChildProps,
<add> mode,
<add> NoWork,
<add> null,
<add> );
<ide> fallbackChildFragment = createFiberFromFragment(
<ide> fallbackChildren,
<ide> mode,
<ide> function mountSuspenseFallbackChildren(
<ide> return fallbackChildFragment;
<ide> }
<ide>
<add>function createWorkInProgressOffscreenFiber(
<add> current: Fiber,
<add> offscreenProps: OffscreenProps,
<add>) {
<add> // The props argument to `createWorkInProgress` is `any` typed, so we use this
<add> // wrapper function to constrain it.
<add> return createWorkInProgress(current, offscreenProps);
<add>}
<add>
<ide> function updateSuspensePrimaryChildren(
<ide> current,
<ide> workInProgress,
<ide> function updateSuspensePrimaryChildren(
<ide> const currentFallbackChildFragment: Fiber | null =
<ide> currentPrimaryChildFragment.sibling;
<ide>
<del> const primaryChildFragment = createWorkInProgress(
<add> const primaryChildFragment = createWorkInProgressOffscreenFiber(
<ide> currentPrimaryChildFragment,
<del> primaryChildren,
<add> {
<add> mode: 'visible',
<add> children: primaryChildren,
<add> },
<ide> );
<ide> if ((workInProgress.mode & BlockingMode) === NoMode) {
<ide> primaryChildFragment.expirationTime_opaque = renderExpirationTime;
<ide> function updateSuspensePrimaryChildren(
<ide> function updateSuspenseFallbackChildren(
<ide> current,
<ide> workInProgress,
<add> primaryChildren,
<ide> fallbackChildren,
<ide> renderExpirationTime,
<ide> ) {
<ide> function updateSuspenseFallbackChildren(
<ide> const currentFallbackChildFragment: Fiber | null =
<ide> currentPrimaryChildFragment.sibling;
<ide>
<add> const primaryChildProps: OffscreenProps = {
<add> mode: 'hidden',
<add> children: primaryChildren,
<add> };
<add>
<ide> let primaryChildFragment;
<ide> if ((mode & BlockingMode) === NoMode) {
<ide> // In legacy mode, we commit the primary tree as if it successfully
<ide> // completed, even though it's in an inconsistent state.
<ide> const progressedPrimaryFragment: Fiber = (workInProgress.child: any);
<ide> primaryChildFragment = progressedPrimaryFragment;
<ide> primaryChildFragment.childExpirationTime_opaque = NoWork;
<add> primaryChildFragment.pendingProps = primaryChildProps;
<ide>
<ide> if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
<ide> // Reset the durations from the first pass so they aren't included in the
<ide> function updateSuspenseFallbackChildren(
<ide> workInProgress.firstEffect = workInProgress.lastEffect = null;
<ide> }
<ide> } else {
<del> primaryChildFragment = createWorkInProgress(
<add> primaryChildFragment = createWorkInProgressOffscreenFiber(
<ide> currentPrimaryChildFragment,
<del> currentPrimaryChildFragment.pendingProps,
<add> primaryChildProps,
<ide> );
<ide> }
<ide> let fallbackChildFragment;
<ide> function retrySuspenseComponentWithoutHydrating(
<ide> function mountSuspenseFallbackAfterRetryWithoutHydrating(
<ide> current,
<ide> workInProgress,
<add> primaryChildren,
<ide> fallbackChildren,
<ide> renderExpirationTime,
<ide> ) {
<ide> const mode = workInProgress.mode;
<ide> const primaryChildFragment = createFiberFromOffscreen(
<del> null,
<add> primaryChildren,
<ide> mode,
<ide> NoWork,
<ide> null,
<ide><path>packages/react-reconciler/src/ReactFiberCommitWork.new.js
<ide> import type {UpdateQueue} from './ReactUpdateQueue.new';
<ide> import type {FunctionComponentUpdateQueue} from './ReactFiberHooks.new';
<ide> import type {Wakeable} from 'shared/ReactTypes';
<ide> import type {ReactPriorityLevel} from './ReactInternalTypes';
<add>import type {OffscreenState} from './ReactFiberOffscreenComponent';
<ide>
<ide> import {unstable_wrap as Schedule_tracing_wrap} from 'scheduler/tracing';
<ide> import {
<ide> import {
<ide> FundamentalComponent,
<ide> ScopeComponent,
<ide> Block,
<add> OffscreenComponent,
<ide> } from './ReactWorkTags';
<ide> import {
<ide> invokeGuardedCallback,
<ide> function commitLifeCycles(
<ide> case IncompleteClassComponent:
<ide> case FundamentalComponent:
<ide> case ScopeComponent:
<add> case OffscreenComponent:
<ide> return;
<ide> }
<ide> invariant(
<ide> function hideOrUnhideAllChildren(finishedWork, isHidden) {
<ide> unhideTextInstance(instance, node.memoizedProps);
<ide> }
<ide> } else if (
<del> node.tag === SuspenseComponent &&
<del> node.memoizedState !== null &&
<del> node.memoizedState.dehydrated === null
<add> node.tag === OffscreenComponent &&
<add> (node.memoizedState: OffscreenState) !== null &&
<add> node !== finishedWork
<ide> ) {
<del> // Found a nested Suspense component that timed out. Skip over the
<del> // primary child fragment, which should remain hidden.
<del> const fallbackChildFragment: Fiber = (node.child: any).sibling;
<del> fallbackChildFragment.return = node;
<del> node = fallbackChildFragment;
<del> continue;
<add> // Found a nested Offscreen component that is hidden. Don't search
<add> // any deeper. This tree should remain hidden.
<ide> } else if (node.child !== null) {
<ide> node.child.return = node;
<ide> node = node.child;
<ide> function commitWork(current: Fiber | null, finishedWork: Fiber): void {
<ide> }
<ide> break;
<ide> }
<add> case OffscreenComponent: {
<add> return;
<add> }
<ide> }
<ide>
<ide> commitContainer(finishedWork);
<ide> function commitWork(current: Fiber | null, finishedWork: Fiber): void {
<ide> }
<ide> break;
<ide> }
<add> case OffscreenComponent: {
<add> const newState: OffscreenState | null = finishedWork.memoizedState;
<add> const isHidden = newState !== null;
<add> hideOrUnhideAllChildren(finishedWork, isHidden);
<add> return;
<add> }
<ide> }
<ide> invariant(
<ide> false,
<ide> function commitWork(current: Fiber | null, finishedWork: Fiber): void {
<ide> function commitSuspenseComponent(finishedWork: Fiber) {
<ide> const newState: SuspenseState | null = finishedWork.memoizedState;
<ide>
<del> let newDidTimeout;
<del> let primaryChildParent = finishedWork;
<del> if (newState === null) {
<del> newDidTimeout = false;
<del> } else {
<del> newDidTimeout = true;
<del> primaryChildParent = finishedWork.child;
<add> if (newState !== null) {
<ide> markCommitTimeOfFallback();
<del> }
<ide>
<del> if (supportsMutation && primaryChildParent !== null) {
<del> hideOrUnhideAllChildren(primaryChildParent, newDidTimeout);
<add> if (supportsMutation) {
<add> // Hide the Offscreen component that contains the primary children. TODO:
<add> // Ideally, this effect would have been scheduled on the Offscreen fiber
<add> // itself. That's how unhiding works: the Offscreen component schedules an
<add> // effect on itself. However, in this case, the component didn't complete,
<add> // so the fiber was never added to the effect list in the normal path. We
<add> // could have appended it to the effect list in the Suspense component's
<add> // second pass, but doing it this way is less complicated. This would be
<add> // simpler if we got rid of the effect list and traversed the tree, like
<add> // we're planning to do.
<add> const primaryChildParent: Fiber = (finishedWork.child: any);
<add> hideOrUnhideAllChildren(primaryChildParent, true);
<add> }
<ide> }
<ide>
<ide> if (enableSuspenseCallback && newState !== null) {
<ide><path>packages/react-reconciler/src/ReactFiberCompleteWork.new.js
<ide> import type {
<ide> SuspenseListRenderState,
<ide> } from './ReactFiberSuspenseComponent.new';
<ide> import type {SuspenseContext} from './ReactFiberSuspenseContext.new';
<add>import type {OffscreenState} from './ReactFiberOffscreenComponent';
<add>
<ide> import {resetWorkInProgressVersions as resetMutableSourceWorkInProgressVersions} from './ReactMutableSource.new';
<ide>
<ide> import {now} from './SchedulerWithReactIntegration.new';
<ide> function completeWork(
<ide> return null;
<ide> }
<ide> break;
<del> case OffscreenComponent:
<add> case OffscreenComponent: {
<add> if (current !== null) {
<add> const nextState: OffscreenState | null = workInProgress.memoizedState;
<add> const prevState: OffscreenState | null = current.memoizedState;
<add>
<add> const prevIsHidden = prevState !== null;
<add> const nextIsHidden = nextState !== null;
<add> if (prevIsHidden !== nextIsHidden) {
<add> workInProgress.effectTag |= Update;
<add> }
<add> }
<ide> return null;
<add> }
<ide> }
<ide> invariant(
<ide> false,
<ide><path>packages/react-reconciler/src/ReactFiberOffscreenComponent.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> * @flow
<add> */
<add>
<add>import type {ReactNodeList} from 'shared/ReactTypes';
<add>import type {ExpirationTimeOpaque} from './ReactFiberExpirationTime.new';
<add>
<add>export type OffscreenProps = {|
<add> // TODO: Pick an API before exposing the Offscreen type. I've chosen an enum
<add> // for now, since we might have multiple variants. For example, hiding the
<add> // content without changing the layout.
<add> //
<add> // Default mode is visible. Kind of a weird default for a component
<add> // called "Offscreen." Possible alt: <Visibility />?
<add> mode?: 'hidden' | 'visible' | null | void,
<add> children?: ReactNodeList,
<add>|};
<add>
<add>// We use the existence of the state object as an indicator that the component
<add>// is hidden.
<add>export type OffscreenState = {|
<add> // TODO: This doesn't do anything, yet. It's always NoWork. But eventually it
<add> // will represent the pending work that must be included in the render in
<add> // order to unhide the component.
<add> baseTime: ExpirationTimeOpaque,
<add>|}; | 5 |
Text | Text | add article for javascript string.codepointat() | 7659d1fdaaa61334bcb9150419c65adc46a883cc | <ide><path>guide/english/javascript/standard-objects/string/string-prototype-codepointat/index.md
<ide> title: String.prototype.codePointAt
<ide> ---
<ide> ## String.prototype.codePointAt
<ide>
<del>This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/javascript/standard-objects/string/string-prototype-codepointat/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<add>The `codePointAt()` method returns a non-negative integer representing the Unicode code point value of a specified character in the given string.
<ide>
<del><a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<add>**Syntax**
<add>```javascript
<add>str.codePointAt(pos) // pos is the position of the character in str from which to return the code point value
<add>```
<ide>
<del><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
<del>
<del>#### More Information:
<del><!-- Please add any articles you think might be helpful to read before writing the article -->
<add>**Example**
<add>```js
<add>var x = "AB12↑↓";
<add>console.log(x.codePointAt(0)); // 65
<add>console.log(x.codePointAt(1)); // 66
<add>console.log(x.codePointAt(2)); // 49
<add>console.log(x.codePointAt(3)); // 50
<add>console.log(x.codePointAt(4)); // 8593
<add>console.log(x.codePointAt(5)); // 8595
<add>console.log(x.codePointAt(6)); // undefined
<add>```
<ide>
<add>*Note*: if there is no character at `pos`, `codePointAt()` returns undefined.
<ide>
<add>#### More Information:
<add>- [String.prototype.codePointAt() on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt)
<add>- [Unicode Lookup](https://unicodelookup.com/) | 1 |
Go | Go | remove links when remove container | 600ad5c1b7b736fba6b103eb99ec87efb050b9ec | <ide><path>daemon/delete.go
<ide> func (daemon *Daemon) cleanupContainer(container *container.Container, forceRemo
<ide> return errors.Wrapf(err, "unable to remove filesystem for %s", container.ID)
<ide> }
<ide>
<del> daemon.linkIndex.delete(container)
<add> linkNames := daemon.linkIndex.delete(container)
<ide> selinuxFreeLxcContexts(container.ProcessLabel)
<ide> daemon.idIndex.Delete(container.ID)
<ide> daemon.containers.Delete(container.ID)
<ide> daemon.containersReplica.Delete(container)
<ide> if e := daemon.removeMountPoints(container, removeVolume); e != nil {
<ide> logrus.Error(e)
<ide> }
<add> for _, name := range linkNames {
<add> daemon.releaseName(name)
<add> }
<ide> container.SetRemoved()
<ide> stateCtr.del(container.ID)
<ide> daemon.LogContainerEvent(container, "destroy")
<ide><path>daemon/links.go
<ide> func (l *linkIndex) parents(child *container.Container) map[string]*container.Co
<ide> }
<ide>
<ide> // delete deletes all link relationships referencing this container
<del>func (l *linkIndex) delete(container *container.Container) {
<add>func (l *linkIndex) delete(container *container.Container) []string {
<ide> l.mu.Lock()
<del> for _, child := range l.idx[container] {
<add>
<add> var aliases []string
<add> for alias, child := range l.idx[container] {
<add> aliases = append(aliases, alias)
<ide> delete(l.childIdx[child], container)
<ide> }
<ide> delete(l.idx, container)
<ide> delete(l.childIdx, container)
<ide> l.mu.Unlock()
<add> return aliases
<ide> }
<ide><path>integration-cli/docker_cli_ps_test.go
<ide> func (s *DockerSuite) TestPsListContainersFilterPorts(c *check.C) {
<ide> c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), id1)
<ide> c.Assert(strings.TrimSpace(out), checker.Equals, id2)
<ide> }
<add>
<add>func (s *DockerSuite) TestPsNotShowLinknamesOfDeletedContainer(c *check.C) {
<add> testRequires(c, DaemonIsLinux)
<add>
<add> dockerCmd(c, "create", "--name=aaa", "busybox", "top")
<add> dockerCmd(c, "create", "--name=bbb", "--link=aaa", "busybox", "top")
<add>
<add> out, _ := dockerCmd(c, "ps", "--no-trunc", "-a", "--format", "{{.Names}}")
<add> lines := strings.Split(strings.TrimSpace(string(out)), "\n")
<add> expected := []string{"bbb", "aaa,bbb/aaa"}
<add> var names []string
<add> names = append(names, lines...)
<add> c.Assert(expected, checker.DeepEquals, names, check.Commentf("Expected array with non-truncated names: %v, got: %v", expected, names))
<add>
<add> dockerCmd(c, "rm", "bbb")
<add>
<add> out, _ = dockerCmd(c, "ps", "--no-trunc", "-a", "--format", "{{.Names}}")
<add> c.Assert(strings.TrimSpace(out), checker.Equals, "aaa")
<add>} | 3 |
PHP | PHP | delete a bad test | 8a4639a8347c2b26ff3a0b43e10c509a997befb5 | <ide><path>tests/TestCase/View/Helper/PaginatorHelperTest.php
<ide> public function testUrlGeneration() {
<ide> $result = $this->Paginator->url();
<ide> $this->assertEquals('/index', $result);
<ide>
<del> $file = fopen('/home/johan/test/log.txt', 'r+');
<del>
<del> fwrite($file, $result);
<del>
<ide> $this->Paginator->request->params['paging']['Article']['page'] = 2;
<ide> $result = $this->Paginator->url();
<ide> $this->assertEquals('/index?page=2', $result); | 1 |
Python | Python | add a bit of flexibility in progbar.update | b9403cb2621a048a885e30f5a9527a14f061a0a6 | <ide><path>keras/utils/generic_utils.py
<ide> def update(self, current, values=[]):
<ide> else:
<ide> info += ' - %ds' % (now - self.start)
<ide> for k in self.unique_values:
<del> info += ' - %s: %.4f' % (k, self.sum_values[k][0] / max(1, self.sum_values[k][1]))
<del>
<add> if type(self.sum_values[k]) is list:
<add> info += ' - %s: %.4f' % (k, self.sum_values[k][0] / max(1, self.sum_values[k][1]))
<add> else:
<add> info += ' - %s: %s' % (k, self.sum_values[k])
<add>
<ide> self.total_width += len(info)
<ide> if prev_total_width > self.total_width:
<ide> info += ((prev_total_width-self.total_width) * " ") | 1 |
Ruby | Ruby | eliminate pathname extensions | bd84b820188daed991756531071137dc7e0876a0 | <ide><path>activesupport/lib/active_support/core_ext/exception.rb
<del>require 'active_support/core_ext/pathname'
<del>
<ide> module ActiveSupport
<ide> FrozenObjectError = RUBY_VERSION < '1.9' ? TypeError : RuntimeError
<ide> end
<ide>
<ide> # TODO: Turn all this into using the BacktraceCleaner.
<ide> class Exception # :nodoc:
<add> # Clean the paths contained in the message.
<add> def self.clean_paths(string)
<add> require 'pathname' unless defined? Pathname
<add> string.gsub(%r{[\w. ]+(/[\w. ]+)+(\.rb)?(\b|$)}) do |path|
<add> Pathname.new(path).cleanpath
<add> end
<add> end
<add>
<ide> def clean_message
<del> Pathname.clean_within message
<add> Exception.clean_paths(message)
<ide> end
<ide>
<ide> TraceSubstitutions = []
<ide> def clean_message
<ide>
<ide> def clean_backtrace
<ide> backtrace.collect do |line|
<del> Pathname.clean_within(TraceSubstitutions.inject(line) do |result, (regexp, sub)|
<add> substituted = TraceSubstitutions.inject(line) do |result, (regexp, sub)|
<ide> result.gsub regexp, sub
<del> end)
<add> end
<add> Exception.clean_paths(substituted)
<ide> end
<ide> end
<ide>
<ide><path>activesupport/lib/active_support/core_ext/pathname.rb
<del>if defined? Pathname
<del> require 'active_support/core_ext/pathname/clean_within'
<del>else
<del> autoload :Pathname, 'active_support/core_ext/pathname/clean_within'
<del>end
<ide><path>activesupport/lib/active_support/core_ext/pathname/clean_within.rb
<del>require 'pathname'
<del>
<del>class Pathname
<del> # Clean the paths contained in the provided string.
<del> def self.clean_within(string)
<del> string.gsub(%r{[\w. ]+(/[\w. ]+)+(\.rb)?(\b|$)}) do |path|
<del> new(path).cleanpath
<del> end
<del> end
<del>end
<ide><path>activesupport/test/core_ext/pathname_test.rb
<del>require 'abstract_unit'
<del>require 'active_support/core_ext/pathname'
<del>
<del>class TestPathname < Test::Unit::TestCase
<del> def test_clean_within
<del> assert_equal "Hi", Pathname.clean_within("Hi")
<del> assert_equal "Hi", Pathname.clean_within("Hi/a/b/../..")
<del> assert_equal "Hello\nWorld", Pathname.clean_within("Hello/a/b/../..\na/b/../../World/c/..")
<del> end
<del>end | 4 |
PHP | PHP | change ternary operator | ae111e6311d5cc40423a32ddc7e7da88b1fef158 | <ide><path>src/ORM/Behavior/TreeBehavior.php
<ide> protected function _recoverTree($counter = 0, $parentId = null, $level = -1)
<ide> list($parent, $left, $right) = [$config['parent'], $config['left'], $config['right']];
<ide> $primaryKey = $this->_getPrimaryKey();
<ide> $aliasedPrimaryKey = $this->_table->aliasField($primaryKey);
<del> $order = $config['recoverOrder'] ? $config['recoverOrder'] : $aliasedPrimaryKey;
<add> $order = $config['recoverOrder'] ?: $aliasedPrimaryKey;
<ide>
<ide> $query = $this->_scope($this->_table->query())
<ide> ->select([$aliasedPrimaryKey]) | 1 |
Text | Text | fix output in inspector heapprofile example | c48467408d6f520b3dda86e34c8f4688acdd52b7 | <ide><path>doc/api/inspector.md
<ide> session.on('HeapProfiler.addHeapSnapshotChunk', (m) => {
<ide> });
<ide>
<ide> session.post('HeapProfiler.takeHeapSnapshot', null, (err, r) => {
<del> console.log('Runtime.takeHeapSnapshot done:', err, r);
<add> console.log('HeapProfiler.takeHeapSnapshot done:', err, r);
<ide> session.disconnect();
<ide> fs.closeSync(fd);
<ide> }); | 1 |
Ruby | Ruby | use gcc instead of apple-gcc42 when needed | 165fdf4617b6ebefebfff47237626ac816a86cf8 | <ide><path>Library/Contributions/cmd/brew-test-bot.rb
<ide> def formula formula
<ide> CompilerSelector.new(formula_object).compiler
<ide> rescue CompilerSelectionError => e
<ide> unless installed_gcc
<del> test "brew install apple-gcc42"
<add> test "brew install gcc"
<ide> installed_gcc = true
<ide> retry
<ide> end
<ide><path>Library/Homebrew/exceptions.rb
<ide> def initialize f
<ide> super f, <<-EOS.undent
<ide> #{f.name} cannot be built with any available compilers.
<ide> To install this formula, you may need to:
<del> brew install apple-gcc42
<add> brew install gcc
<ide> EOS
<ide> end
<ide> end | 2 |
Text | Text | add changelog entry | ad449525dcd0da359c96203be11db2f606c9c812 | <ide><path>actionpack/CHANGELOG.md
<ide>
<ide> ## Rails 3.2.0 (unreleased) ##
<ide>
<add>* Rails initialization with initialize_on_precompile = false should set assets_dir *Santiago Pastorino*
<add>
<ide> * Add font_path helper method *Santiago Pastorino*
<ide>
<ide> * Depends on rack ~> 1.4.0 *Santiago Pastorino* | 1 |
PHP | PHP | adjust whitespace in one more docblock | ab24e0d1f68584e973ece32d41a2302110e97d74 | <ide><path>src/Illuminate/Database/Query/Builder.php
<ide> protected function restoreFieldsForCount()
<ide> /**
<ide> * Chunk the results of the query.
<ide> *
<del> * @param int $count
<del> * @param callable $callback
<add> * @param int $count
<add> * @param callable $callback
<ide> * @return bool
<ide> */
<ide> public function chunk($count, callable $callback) | 1 |
PHP | PHP | remove unnecessary method | 313f8cb48fa678cb01b7688ab5b93facb8e3970e | <ide><path>src/Console/ConsoleErrorHandler.php
<ide> public function __construct(array $options = [])
<ide> public function handleException(Throwable $exception): void
<ide> {
<ide> $this->_displayException($exception);
<del> $this->_logException($exception);
<add> $this->logException($exception);
<ide> $code = $exception->getCode();
<ide> $code = $code && is_int($code) ? $code : 1;
<ide> $this->_stop($code);
<ide><path>src/Error/BaseErrorHandler.php
<ide> use Cake\Core\Configure;
<ide> use Cake\Log\Log;
<ide> use Cake\Routing\Router;
<add>use Psr\Http\Message\ServerRequestInterface;
<ide> use Throwable;
<ide>
<ide> /**
<ide> public function wrapAndHandleException(Throwable $exception): void
<ide> public function handleException(Throwable $exception): void
<ide> {
<ide> $this->_displayException($exception);
<del> $this->_logException($exception);
<add> $this->logException($exception);
<ide> $code = $exception->getCode() ?: 1;
<ide> $this->_stop((int)$code);
<ide> }
<ide> protected function _logError($level, array $data): bool
<ide> }
<ide>
<ide> /**
<del> * Handles exception logging
<add> * Log an error for the exception if applicable.
<ide> *
<del> * @param \Throwable $exception Exception instance.
<add> * @param \Throwable $exception The exception to log a message for.
<add> * @param \Psr\Http\Message\ServerRequestInterface $request The current request.
<ide> * @return bool
<ide> */
<del> protected function _logException(Throwable $exception): bool
<add> public function logException(Throwable $exception, ?ServerRequestInterface $request = null): bool
<ide> {
<ide> $config = $this->_options;
<ide> if (empty($config['log'])) {
<ide> return false;
<ide> }
<ide>
<del> return $this->getLogger()->log($exception, Router::getRequest());
<add> return $this->getLogger()->log($exception, $request ?? Router::getRequest());
<ide> }
<ide>
<ide> /**
<ide><path>src/Error/ErrorHandler.php
<ide> protected function _displayException(Throwable $exception): void
<ide> }
<ide> }
<ide>
<del> /**
<del> * Handles exception logging
<del> *
<del> * @param \Throwable $exception Exception instance.
<del> * @return bool
<del> */
<del> protected function _logException(Throwable $exception): bool
<del> {
<del> return $this->logException($exception);
<del> }
<del>
<del> /**
<del> * Log an error for the exception if applicable.
<del> *
<del> * @param \Throwable $exception The exception to log a message for.
<del> * @param \Psr\Http\Message\ServerRequestInterface $request The current request.
<del> * @return bool
<del> */
<del> public function logException(Throwable $exception, ?ServerRequestInterface $request = null): bool
<del> {
<del> $config = $this->_options;
<del> if (empty($config['log'])) {
<del> return false;
<del> }
<del>
<del> return $this->getLogger()->log($exception, $request ?? Router::getRequest());
<del> }
<del>
<ide> /**
<ide> * Get a renderer instance.
<ide> * | 3 |
Javascript | Javascript | add failing test case for albers artefacts | fbbbfbf239a5c17b569103dc118b3796ba74d5d7 | <ide><path>test/geo/path-test.js
<ide> suite.addBatch({
<ide> "Polygon": {
<ide> "inserts exterior along clip edge if polygon interior surrounds it": function(path) {
<ide> path({type: "Polygon", coordinates: [[[80, -80], [80, 80], [-80, 80], [-80, -80], [80, -80]]]});
<del> var buffer = testContext.buffer();
<del> assert.equal(buffer.filter(function(d) { return d.type === "moveTo"; }).length, 2);
<add> assert.equal(testContext.buffer().filter(function(d) { return d.type === "moveTo"; }).length, 2);
<ide> },
<ide> "inserts exterior along clip edge if polygon exterior surrounds it": function(path) {
<ide> path({type: "Polygon", coordinates: [[[100, -80], [-100, -80], [-100, 80], [100, 80], [100, -80]]]});
<del> var buffer = testContext.buffer();
<del> assert.equal(buffer.filter(function(d) { return d.type === "moveTo"; }).length, 1);
<add> assert.equal(testContext.buffer().filter(function(d) { return d.type === "moveTo"; }).length, 1);
<ide> }
<ide> }
<del> }
<del> },
<del> "path.precision(1)": {
<del> topic: function() {
<del> return d3.geo.path()
<del> .context(testContext)
<del> .projection(d3.geo.stereographic()
<del> .precision(1));
<ide> },
<del>
<del> "correctly resamples points on antemeridian": function(path) {
<del> path({type: "LineString", coordinates: [[0, 90], [90, 0]]});
<del> assert.deepEqual(testContext.buffer(), [
<del> {type: "moveTo", x: 480, y: 100},
<del> {type: "lineTo", x: 509, y: 103},
<del> {type: "lineTo", x: 537, y: 111},
<del> {type: "lineTo", x: 563, y: 125},
<del> {type: "lineTo", x: 586, y: 144},
<del> {type: "lineTo", x: 605, y: 167},
<del> {type: "lineTo", x: 619, y: 193},
<del> {type: "lineTo", x: 627, y: 221},
<del> {type: "lineTo", x: 630, y: 250}
<del> ]);
<add> "stereographic.precision(1)": {
<add> topic: function() {
<add> return d3.geo.path()
<add> .context(testContext)
<add> .projection(d3.geo.stereographic()
<add> .precision(1));
<add> },
<add> "correctly resamples points on antemeridian": function(path) {
<add> path({type: "LineString", coordinates: [[0, 90], [90, 0]]});
<add> assert.deepEqual(testContext.buffer(), [
<add> {type: "moveTo", x: 480, y: 100},
<add> {type: "lineTo", x: 509, y: 103},
<add> {type: "lineTo", x: 537, y: 111},
<add> {type: "lineTo", x: 563, y: 125},
<add> {type: "lineTo", x: 586, y: 144},
<add> {type: "lineTo", x: 605, y: 167},
<add> {type: "lineTo", x: 619, y: 193},
<add> {type: "lineTo", x: 627, y: 221},
<add> {type: "lineTo", x: 630, y: 250}
<add> ]);
<add> }
<add> },
<add> "albers.precision(1)": {
<add> topic: function() {
<add> return d3.geo.path()
<add> .context(testContext)
<add> .projection(d3.geo.albers()
<add> .scale(140)
<add> .rotate([0, 0])
<add> .precision(1));
<add> },
<add> "doesn't introduce artefacts in areas of high distortion": function(path) {
<add> path({type: "LineString", coordinates: [[0, 88], [180, 89]]});
<add> assert.isTrue(testContext.buffer().filter(function(d) { return d.type === "lineTo"; }).length > 1);
<add> }
<ide> }
<ide> }
<ide> }); | 1 |
Text | Text | remove old docs | 270d548d33f813c6121f739ce906385c398d1b1b | <ide><path>packages/next/README.md
<ide> - [With named exports](#with-named-exports)
<ide> - [With Custom Loading Component](#with-custom-loading-component)
<ide> - [With No SSR](#with-no-ssr)
<del> - [With Multiple Modules At Once](#with-multiple-modules-at-once)
<ide> - [Custom `<App>`](#custom-app)
<ide> - [Custom `<Document>`](#custom-document)
<ide> - [Customizing `renderPage`](#customizing-renderpage)
<ide> app.prepare().then(() => {
<ide> </ul>
<ide> </details>
<ide>
<del>Next.js supports TC39 [dynamic import proposal](https://github.com/tc39/proposal-dynamic-import) for JavaScript.
<add>Next.js supports ES2020 [dynamic `import()`](https://github.com/tc39/proposal-dynamic-import) for JavaScript.
<ide> With that, you could import JavaScript modules (inc. React Components) dynamically and work with them.
<ide>
<ide> You can think dynamic imports as another way to split your code into manageable chunks.
<ide> import dynamic from 'next/dynamic'
<ide>
<ide> const DynamicComponentWithCustomLoading = dynamic(
<ide> () => import('../components/hello2'),
<del> {
<del> loading: () => <p>...</p>,
<del> }
<add> { loading: () => <p>...</p> }
<ide> )
<ide>
<ide> function Home() {
<ide> import dynamic from 'next/dynamic'
<ide>
<ide> const DynamicComponentWithNoSSR = dynamic(
<ide> () => import('../components/hello3'),
<del> {
<del> ssr: false,
<del> }
<add> { ssr: false }
<ide> )
<ide>
<ide> function Home() {
<ide> function Home() {
<ide> export default Home
<ide> ```
<ide>
<del>#### With Multiple Modules At Once
<del>
<del>```jsx
<del>import dynamic from 'next/dynamic'
<del>
<del>const HelloBundle = dynamic({
<del> modules: () => {
<del> const components = {
<del> Hello1: () => import('../components/hello1'),
<del> Hello2: () => import('../components/hello2'),
<del> }
<del>
<del> return components
<del> },
<del> render: (props, { Hello1, Hello2 }) => (
<del> <div>
<del> <h1>{props.title}</h1>
<del> <Hello1 />
<del> <Hello2 />
<del> </div>
<del> ),
<del>})
<del>
<del>function DynamicBundle() {
<del> return <HelloBundle title="Dynamic Bundle" />
<del>}
<del>
<del>export default DynamicBundle
<del>```
<del>
<ide> ### Custom `<App>`
<ide>
<ide> <details> | 1 |
Python | Python | fix some doctest failures | 4c696a070a8034acda819ff3d62464b4cc1f0e8a | <ide><path>numpy/core/code_generators/ufunc_docstrings.py
<ide> def add_newdoc(place, name, doc):
<ide> >>> np.cos(np.zeros((3,3)),np.zeros((2,2)))
<ide> Traceback (most recent call last):
<ide> File "<stdin>", line 1, in <module>
<del> ValueError: invalid return array shape
<add> ValueError: operands could not be broadcast together with shapes (3,3) (2,2)
<ide>
<ide> """)
<ide>
<ide> def add_newdoc(place, name, doc):
<ide> - Stacks of matrices are broadcast together as if the matrices
<ide> were elements, respecting the signature ``(n,k),(k,m)->(n,m)``:
<ide>
<del> >>> a = a = np.full([9,5,7,3], True, dtype=bool)
<del> >>> c = np.full([9, 5, 4,3], True, dtype=bool)
<del> >>> np.dot(a, c).shape # doctest: +SKIP
<del> (9, 5, 7, 9, 5, 4)
<del> >>> np.matmul(a, c).shape # doctest: +SKIP
<del> (9, 5, 7, 4)
<del> >>> # n is 5, k is 3, m is 4
<add> >>> a = np.ones([9, 5, 7, 4])
<add> >>> c = np.ones([9, 5, 4, 3])
<add> >>> np.dot(a, c).shape
<add> (9, 5, 7, 9, 5, 3)
<add> >>> np.matmul(a, c).shape
<add> (9, 5, 7, 3)
<add> >>> # n is 7, k is 4, m is 3
<ide>
<ide> The matmul function implements the semantics of the `@` operator introduced
<ide> in Python 3.5 following PEP465.
<ide> def add_newdoc(place, name, doc):
<ide> >>> np.sinh(np.zeros((3,3)),np.zeros((2,2)))
<ide> Traceback (most recent call last):
<ide> File "<stdin>", line 1, in <module>
<del> ValueError: invalid return array shape
<add> ValueError: operands could not be broadcast together with shapes (3,3) (2,2)
<ide>
<ide> """)
<ide>
<ide> def add_newdoc(place, name, doc):
<ide> >>> np.cos(np.zeros((3,3)),np.zeros((2,2)))
<ide> Traceback (most recent call last):
<ide> File "<stdin>", line 1, in <module>
<del> ValueError: invalid return array shape
<add> ValueError: operands could not be broadcast together with shapes (3,3) (2,2)
<ide>
<ide> """)
<ide>
<ide> def add_newdoc(place, name, doc):
<ide> >>> np.tanh(np.zeros((3,3)),np.zeros((2,2)))
<ide> Traceback (most recent call last):
<ide> File "<stdin>", line 1, in <module>
<del> ValueError: invalid return array shape
<add> ValueError: operands could not be broadcast together with shapes (3,3) (2,2)
<ide>
<ide> """)
<ide> | 1 |
PHP | PHP | fix container return docblock | 52485a0c4a1dd4af7066e4de5ed3b2ee9f26d022 | <ide><path>src/Illuminate/Container/Container.php
<ide> protected function getConcrete($abstract)
<ide> * Get the contextual concrete binding for the given abstract.
<ide> *
<ide> * @param string $abstract
<del> * @return string|null
<add> * @return \Closure|string|null
<ide> */
<ide> protected function getContextualConcrete($abstract)
<ide> {
<ide> protected function getContextualConcrete($abstract)
<ide> * Find the concrete binding for the given abstract in the contextual binding array.
<ide> *
<ide> * @param string $abstract
<del> * @return string|null
<add> * @return \Closure|string|null
<ide> */
<ide> protected function findInContextualBindings($abstract)
<ide> { | 1 |
PHP | PHP | remove extra newline | 01ba43ce2669c19e47ab172661561e0e36509e49 | <ide><path>tests/TestCase/Controller/ControllerTest.php
<ide> public function testPaginate()
<ide> $this->assertSame($Controller->request->params['paging']['Posts']['pageCount'], 2);
<ide> $this->assertSame($Controller->request->params['paging']['Posts']['prevPage'], true);
<ide> $this->assertSame($Controller->request->params['paging']['Posts']['nextPage'], false);
<del>
<ide> }
<ide>
<ide> /** | 1 |
Go | Go | add support for 'dangling' filter | 131cbaf5b7b15ffc5e3fc11ed30ce0f67a76c6f8 | <ide><path>api/types/network/network.go
<ide> type ConfigReference struct {
<ide> }
<ide>
<ide> var acceptedFilters = map[string]bool{
<del> "driver": true,
<del> "type": true,
<del> "name": true,
<del> "id": true,
<del> "label": true,
<del> "scope": true,
<add> "driver": true,
<add> "type": true,
<add> "name": true,
<add> "id": true,
<add> "label": true,
<add> "scope": true,
<add> "dangling": true,
<ide> }
<ide>
<ide> // ValidateFilters validates the list of filter args with the available filters.
<ide><path>daemon/network/filter.go
<ide> package network // import "github.com/docker/docker/daemon/network"
<ide> import (
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/api/types/filters"
<add> "github.com/docker/docker/errdefs"
<ide> "github.com/docker/docker/runconfig"
<ide> "github.com/pkg/errors"
<ide> )
<ide> func FilterNetworks(nws []types.NetworkResource, filter filters.Args) ([]types.N
<ide> displayNet = append(displayNet, nw)
<ide> }
<ide>
<add> if values := filter.Get("dangling"); len(values) > 0 {
<add> if len(values) > 1 {
<add> return nil, errdefs.InvalidParameter(errors.New(`got more than one value for filter key "dangling"`))
<add> }
<add>
<add> var danglingOnly bool
<add> switch values[0] {
<add> case "0", "false":
<add> // dangling is false already
<add> case "1", "true":
<add> danglingOnly = true
<add> default:
<add> return nil, errdefs.InvalidParameter(errors.New(`invalid value for filter 'dangling', must be "true" (or "1"), or "false" (or "0")`))
<add> }
<add>
<add> displayNet = filterNetworkByUse(displayNet, danglingOnly)
<add> }
<add>
<ide> if filter.Contains("type") {
<ide> typeNet := []types.NetworkResource{}
<ide> errFilter := filter.WalkValues("type", func(fval string) error {
<ide> func FilterNetworks(nws []types.NetworkResource, filter filters.Args) ([]types.N
<ide> return displayNet, nil
<ide> }
<ide>
<add>func filterNetworkByUse(nws []types.NetworkResource, danglingOnly bool) []types.NetworkResource {
<add> retNws := []types.NetworkResource{}
<add>
<add> filterFunc := func(nw types.NetworkResource) bool {
<add> if danglingOnly {
<add> return !runconfig.IsPreDefinedNetwork(nw.Name) && len(nw.Containers) == 0 && len(nw.Services) == 0
<add> }
<add> return runconfig.IsPreDefinedNetwork(nw.Name) || len(nw.Containers) > 0 || len(nw.Services) > 0
<add> }
<add>
<add> for _, nw := range nws {
<add> if filterFunc(nw) {
<add> retNws = append(retNws, nw)
<add> }
<add> }
<add>
<add> return retNws
<add>}
<add>
<ide> func filterNetworkByType(nws []types.NetworkResource, netType string) ([]types.NetworkResource, error) {
<ide> retNws := []types.NetworkResource{}
<ide> switch netType {
<ide><path>daemon/network/filter_test.go
<ide> func TestFilterNetworks(t *testing.T) {
<ide> Driver: "mykvdriver",
<ide> Scope: "global",
<ide> },
<add> {
<add> Name: "networkwithcontainer",
<add> Driver: "nwc",
<add> Scope: "local",
<add> Containers: map[string]types.EndpointResource{
<add> "customcontainer": {
<add> Name: "customendpoint",
<add> },
<add> },
<add> },
<ide> }
<ide>
<ide> bridgeDriverFilters := filters.NewArgs()
<ide> func TestFilterNetworks(t *testing.T) {
<ide> globalScopeFilters := filters.NewArgs()
<ide> globalScopeFilters.Add("scope", "global")
<ide>
<add> trueDanglingFilters := filters.NewArgs()
<add> trueDanglingFilters.Add("dangling", "true")
<add>
<add> falseDanglingFilters := filters.NewArgs()
<add> falseDanglingFilters.Add("dangling", "false")
<add>
<ide> testCases := []struct {
<ide> filter filters.Args
<ide> resultCount int
<ide> err string
<ide> name string
<add> results []string
<ide> }{
<ide> {
<ide> filter: bridgeDriverFilters,
<ide> func TestFilterNetworks(t *testing.T) {
<ide> },
<ide> {
<ide> filter: customDriverFilters,
<del> resultCount: 3,
<add> resultCount: 4,
<ide> err: "",
<ide> name: "custom driver filters",
<ide> },
<ide> func TestFilterNetworks(t *testing.T) {
<ide> },
<ide> {
<ide> filter: localScopeFilters,
<del> resultCount: 4,
<add> resultCount: 5,
<ide> err: "",
<ide> name: "local scope filters",
<ide> },
<ide> func TestFilterNetworks(t *testing.T) {
<ide> err: "",
<ide> name: "global scope filters",
<ide> },
<add> {
<add> filter: trueDanglingFilters,
<add> resultCount: 3,
<add> err: "",
<add> name: "dangling filter is 'True'",
<add> results: []string{"myoverlay", "mydrivernet", "mykvnet"},
<add> },
<add> {
<add> filter: falseDanglingFilters,
<add> resultCount: 4,
<add> err: "",
<add> name: "dangling filter is 'False'",
<add> results: []string{"host", "bridge", "none", "networkwithcontainer"},
<add> },
<ide> }
<ide>
<ide> for _, testCase := range testCases {
<ide> func TestFilterNetworks(t *testing.T) {
<ide> if len(result) != testCase.resultCount {
<ide> t.Fatalf("expect '%d' networks, got '%d' networks", testCase.resultCount, len(result))
<ide> }
<add>
<add> if len(testCase.results) > 0 {
<add> resultMap := make(map[string]bool)
<add> for _, r := range result {
<add> resultMap[r.Name] = true
<add> }
<add> for _, r := range testCase.results {
<add> if _, ok := resultMap[r]; !ok {
<add> t.Fatalf("expected result: '%s' not found", r)
<add> }
<add> }
<add> }
<ide> }
<ide> })
<ide> } | 3 |
Text | Text | add @iekadou for #700 support. thanks! | 17e0ff0fcde23f4bc6734b75f7fff734ae77c26d | <ide><path>docs/topics/credits.md
<ide> The following people have helped make REST framework great.
<ide> * Ryan Detzel - [ryanrdetzel]
<ide> * Omer Katz - [thedrow]
<ide> * Wiliam Souza - [waa]
<add>* Jonas Braun - [iekadou]
<ide>
<ide> Many thanks to everyone who's contributed to the project.
<ide>
<ide> You can also contact [@_tomchristie][twitter] directly on twitter.
<ide> [ryanrdetzel]: https://github.com/ryanrdetzel
<ide> [thedrow]: https://github.com/thedrow
<ide> [waa]: https://github.com/wiliamsouza
<add>[iekadou]: https://github.com/iekadou | 1 |
Ruby | Ruby | fix output handling | c479c680b8e3fb022d8d5cb93d00a1eff5666af8 | <ide><path>Library/Contributions/cmd/brew-test-bot.rb
<ide> def self.run test, command, puts_output_on_success = false
<ide> step.puts_command
<ide>
<ide> command = "#{step.command} &>#{step.log_file_path}"
<del>
<del> output = nil
<ide> if command.start_with? 'git '
<ide> Dir.chdir step.repository do
<del> output = `#{command}`
<add> `#{command}`
<ide> end
<ide> else
<del> output = `#{command}`
<add> `#{command}`
<ide> end
<del> output = IO.read(step.log_file_path) rescue nil
<ide>
<ide> success = $?.success?
<ide> step.status = success ? :passed : :failed
<ide> step.puts_result
<add>
<add> return unless File.exists?(step.log_file_path)
<add> output = IO.read(step.log_file_path)
<ide> if output and output.any? and (not success or puts_output_on_success)
<ide> puts output
<ide> end | 1 |
Python | Python | remove bert2bert from module declaration | 19e99647806ef597e2b21fd6ec2fed6624bdb696 | <ide><path>transformers/__init__.py
<ide> BertForMaskedLM, BertForNextSentencePrediction,
<ide> BertForSequenceClassification, BertForMultipleChoice,
<ide> BertForTokenClassification, BertForQuestionAnswering,
<del> load_tf_weights_in_bert, BERT_PRETRAINED_MODEL_ARCHIVE_MAP, Bert2Rnd)
<add> load_tf_weights_in_bert, BERT_PRETRAINED_MODEL_ARCHIVE_MAP)
<ide> from .modeling_openai import (OpenAIGPTPreTrainedModel, OpenAIGPTModel,
<ide> OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel,
<ide> load_tf_weights_in_openai_gpt, OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_MAP) | 1 |
Text | Text | update cdn link | d1cccd354639cfc65b5f82ecd5d58666eda2a0a8 | <ide><path>docs/00-Getting-Started.md
<ide> bower install Chart.js --save
<ide>
<ide> Also, Chart.js is available from CDN:
<ide>
<del>https://cdnjs.com/libraries/chart.js
<add>https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js
<ide>
<ide> ###Creating a chart
<ide> | 1 |
Ruby | Ruby | remove unused variables | 36b7bae93cedfa59cba797f7ad3bdcdced700fb7 | <ide><path>Library/Homebrew/cmd/test-bot.rb
<ide> def formula formula_name
<ide> if formula.stable? && !ARGV.include?('--no-bottle')
<ide> bottle_args = ["--rb", canonical_formula_name]
<ide> if @tap
<del> tap_user, tap_repo = @tap.split "/"
<ide> bottle_args << "--root-url=#{BottleSpecification::DEFAULT_DOMAIN}/#{Bintray.repository(@tap)}"
<ide> end
<ide> bottle_args << { :puts_output_on_success => true }
<ide> def check_results
<ide>
<ide> def formulae
<ide> changed_formulae_dependents = {}
<del> dependencies = []
<del> non_dependencies = []
<ide>
<ide> @formulae.each do |formula|
<ide> formula_dependencies = Utils.popen_read("brew", "deps", formula).split("\n") | 1 |
Javascript | Javascript | fix typo in eventpropagators.js | 751d22117213ebf425e1a81cc7b2def10e67ae5f | <ide><path>src/renderers/shared/shared/event/EventPropagators.js
<ide> function accumulateDirectDispatches(events) {
<ide> * are sets of events that have already been annotated with a set of dispatched
<ide> * listener functions/ids. The API is designed this way to discourage these
<ide> * propagation strategies from actually executing the dispatches, since we
<del> * always want to collect the entire set of dispatches before executing event a
<add> * always want to collect the entire set of dispatches before executing even a
<ide> * single one.
<ide> *
<ide> * @constructor EventPropagators | 1 |
Text | Text | add more instructions to releasing_rails | 500d6319ff07d880e24fb1cc577ca0dcd50d63e2 | <ide><path>RELEASING_RAILS.md
<ide> branch.
<ide>
<ide> ## Day of release
<ide>
<add>If making multiple releases. Publish them in order from oldest to newest, to
<add>ensure that the "greatest" version also shows up in NPM and GitHub Releases as
<add>"latest".
<add>
<ide> ### Put the new version in the RAILS_VERSION file.
<ide>
<ide> Include an RC number if appropriate, e.g. `6.0.0.rc1`.
<ide> browser.
<ide> This will stop you from looking silly when you push an RC to rubygems.org and
<ide> then realize it is broken.
<ide>
<add>### Check credentials for RubyGems, npm, and GitHub
<add>
<add>For npm run `npm whoami` to check that you are logged in (`npm login` if not).
<add>
<add>For RubyGems run `gem login`. If there's no output you are logged in.
<add>
<add>For GitHub run `gh auth status` to check that you are logged in (run `gh login` if not).
<add>
<add>npm and RubyGems require MFA. The release task will attempt to use a yubikey if
<add>available, which as we have release several packages at once is strongly
<add>recommended. Check that `ykman oath accounts list` has an entry for both
<add>`npmjs.com` and `rubygems.org`, if not refer to
<add>https://tenderlovemaking.com/2021/10/26/publishing-gems-with-your-yubikey.html
<add>for setup instructions.
<add>
<ide> ### Release to RubyGems and npm.
<ide>
<ide> IMPORTANT: Several gems have JavaScript components that are released as npm
<ide> Run `rake release`. This will populate the gemspecs and npm package.json with
<ide> the current RAILS_VERSION, commit the changes, tag it, and push the gems to
<ide> rubygems.org.
<ide>
<add>### Make GitHub Releases from pushed tags
<add>
<add>We use GitHub Releases to publish the combined release summary for all gems. We
<add>can use a rake task and [GitHub cli](https://cli.github.com/) to do this
<add>(releases can also be created or edited on the web).
<add>
<add>```
<add>bundle exec rake changelog:release_summary > ../6-1-7-release-summary.md
<add>gh release create v6.1.7 -R rails/rails -F ../6-1-7-release-summary.md
<add>```
<add>
<ide> ### Send Rails release announcements
<ide>
<ide> Write a release announcement that includes the version, changes, and links to
<ide> break existing applications.
<ide>
<ide> ### Post the announcement to the Rails blog.
<ide>
<del>If you used Markdown format for your email, you can just paste it into the
<del>blog.
<add>The blog at https://rubyonrails.org/blog is built from
<add>https://github.com/rails/website.
<add>
<add>Create a file named like
<add>`_posts/$(date +'%F')-Rails-<versions>-have-been-released.markdown`
<add>
<add>Add YAML frontmatter
<add>```
<add>---
<add>layout: post
<add>title: 'Rails <VERSIONS> have been released!'
<add>categories: releases
<add>author: <your handle>
<add>published: true
<add>date: <YYYY-MM-DD or `date +%F`>
<add>---
<add>```
<add>
<add>Use the markdown generated by `rake announce` earlier as a base for the post.
<add>Add some context for users as to the purpose of this release (bugfix/security).
<ide>
<del>* https://rubyonrails.org/blog
<add>If this is a part of the latest release series, update `_data/version.yml` so
<add>that the homepage points to the latest version.
<ide>
<ide> ### Post the announcement to the Rails Twitter account.
<ide> | 1 |
Python | Python | fix indent size of docstring's line | eaca5da3e2dc5747fdd7310482396a3738d1b476 | <ide><path>keras/engine/training.py
<ide> def fit(self, x=None,
<ide> batch_size: integer. Number of samples per gradient update.
<ide> epochs: integer, the number of times to iterate
<ide> over the training data arrays.
<del> verbose: 0, 1, or 2. Verbosity mode.
<add> verbose: 0, 1, or 2. Verbosity mode.
<ide> 0 = silent, 1 = verbose, 2 = one log line per epoch.
<ide> callbacks: list of callbacks to be called during training.
<ide> See [callbacks](/callbacks). | 1 |
Python | Python | set version to v2.1.0a12 | 062934aa12179f2e693e022520b1dec7ef1ba45b | <ide><path>spacy/about.py
<ide> # fmt: off
<ide>
<ide> __title__ = "spacy-nightly"
<del>__version__ = "2.1.0a11"
<add>__version__ = "2.1.0a12"
<ide> __summary__ = "Industrial-strength Natural Language Processing (NLP) with Python and Cython"
<ide> __uri__ = "https://spacy.io"
<ide> __author__ = "Explosion AI" | 1 |
Text | Text | change debugging console lesson | d739a0cc5da640fc4a34354cf793481b3599d243 | <ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/debugging/understanding-the-differences-between-the-freecodecamp-and-browser-console.english.md
<ide> forumTopicId: 301193
<ide> <section id='description'>
<ide> You may have noticed that some freeCodeCamp JavaScript challenges include their own console. This console behaves a little differently than the browser console you used in the last challenge.
<ide> The following challenge is meant to highlight the main difference between the freeCodeCamp console and your browser console.
<del>When you run ordinary JavaScript, the browsers console will display your <code>console.log()</code> statements the exact number of times you requested.
<del>The freeCodeCamp console will print your <code>console.log()</code> statements for each test of that challenge, as well as one more time for any function calls that you have in your code.
<del>This lends itself to some interesting behavior and might trip you up in the beginning, because a logged value that you expect to see only once may print out many more times.
<del>If you would like to see only your single output and not have to worry about running through the test cycles, you can use <code>console.clear()</code> and check the browsers console.
<add>When you run ordinary JavaScript, the browser's console will display your <code>console.log()</code> statements the exact number of times it is called.
<add>The freeCodeCamp console will print your <code>console.log()</code> statements a short time after the editor detects a change in the script, as well as during testing.
<add>The freeCodeCamp console is cleared before the tests are run and, to avoid spam, only prints the logs during the first test (see the note below for exceptions).
<add>If you would like to see every log for every test, run the tests, and open the browser console. If you prefer to use the browser console, and want it to mimic the freeCodeCamp console, place <code>console.clear()</code> before any other <code>console</code> calls, to clear the browser console.
<add>
<add>**Note:** `console.log`s inside functions are printed to the freeCodeCamp console whenever those functions are called, this can help debugging functions that are called during testing.
<ide> </section>
<ide>
<ide> ## Instructions
<ide> <section id='instructions'>
<del>First, use <code>console.clear()</code> to clear the browser console. After that, use <code>console.log</code> to log the <code>output</code> variable.
<add>First, use <code>console.log</code> to log the <code>output</code> variable. Then, use <code>console.clear</code> to clear the browser console.
<ide> </section>
<ide>
<ide> ## Tests
<ide> tests:
<ide>
<ide> ```js
<ide> // Open your browser console.
<del>let output = "Get this to log once in the browser console and twice in the freeCodeCamp console";
<del>// Use console.clear() on the next line to clear the browser console.
<del>
<del>
<add>let output = "Get this to log once in the freeCodeCamp console and twice in the browser console";
<ide> // Use console.log() to print the output variable.
<ide>
<add>// Run the tests to see the difference between the two consoles.
<ide>
<del>// Check the two consoles to see the difference. The freeCodeCamp console should have printed the variable twice, once for each test of this challenge. The browser console should only print the variable once because you cleared it first.
<add>// Now, add console.clear() before your console.log() to clear the browser console, and pass the tests.
<ide> ```
<ide>
<ide> </div>
<ide> let output = "Get this to log once in the browser console and twice in the freeC
<ide>
<ide> ```js
<ide> // Open your browser console.
<del>let output = "Get this to log once in the browser console and twice in the freeCodeCamp console";
<del>// Use console.clear() on the next line to clear the browser console.
<del>console.clear();
<del>
<add>let output = "Get this to log once in the freeCodeCamp console and twice in the browser console";
<ide> // Use console.log() to print the output variable.
<add>console.clear();
<ide> console.log(output);
<ide>
<del>// Check the two consoles to see the difference. The freeCodeCamp console should have printed the variable twice, one for each test of this challenge. The browser console should only print the variable once because you cleared it first.
<add>// Run the tests to see the difference between the two consoles.
<add>
<add>// Now, add console.clear() before your console.log() to clear the browser console, and pass the tests.
<ide> ```
<ide>
<ide> </section> | 1 |
Javascript | Javascript | remove special loadstart handling | 73b6316f3bdb8cb7582af85d0c17bcde365fd930 | <ide><path>src/js/tech/tech.js
<ide> Tech.withSourceHandlers = function(_Tech) {
<ide>
<ide> if (sh !== _Tech.nativeSourceHandler) {
<ide> this.currentSource_ = source;
<del>
<del> // Catch if someone replaced the src without calling setSource.
<del> // If they do, set currentSource_ to null and dispose our source handler.
<del> this.off(this.el_, 'loadstart', _Tech.prototype.firstLoadStartListener_);
<del> this.off(this.el_, 'loadstart', _Tech.prototype.successiveLoadStartListener_);
<del> this.one(this.el_, 'loadstart', _Tech.prototype.firstLoadStartListener_);
<ide> }
<ide>
<ide> this.sourceHandler_ = sh.handleSource(source, this, this.options_);
<ide> Tech.withSourceHandlers = function(_Tech) {
<ide> return this;
<ide> };
<ide>
<del> /**
<del> * Called once for the first loadstart of a video.
<del> *
<del> * @listens Tech#loadstart
<del> */
<del> _Tech.prototype.firstLoadStartListener_ = function() {
<del> this.one(this.el_, 'loadstart', _Tech.prototype.successiveLoadStartListener_);
<del> };
<del>
<del> // On successive loadstarts when setSource has not been called again
<del> /**
<del> * Called after the first loadstart for a video occurs.
<del> *
<del> * @listens Tech#loadstart
<del> */
<del> _Tech.prototype.successiveLoadStartListener_ = function() {
<del> this.disposeSourceHandler();
<del> this.one(this.el_, 'loadstart', _Tech.prototype.successiveLoadStartListener_);
<del> };
<del>
<ide> /**
<ide> * Clean up any existing SourceHandlers and listeners when the Tech is disposed.
<ide> *
<ide> Tech.withSourceHandlers = function(_Tech) {
<ide> this.cleanupAutoTextTracks();
<ide>
<ide> if (this.sourceHandler_) {
<del> this.off(this.el_, 'loadstart', _Tech.prototype.firstLoadStartListener_);
<del> this.off(this.el_, 'loadstart', _Tech.prototype.successiveLoadStartListener_);
<ide>
<ide> if (this.sourceHandler_.dispose) {
<ide> this.sourceHandler_.dispose();
<ide><path>test/unit/tech/tech.test.js
<ide> QUnit.test('Tech.isTech returns correct answers for techs and components', funct
<ide> assert.ok(!isTech(isTech), 'A function is not a Tech');
<ide> });
<ide>
<del>QUnit.test('Tech#setSource clears currentSource_ after repeated loadstart', function(assert) {
<del> let disposed = false;
<del> const MyTech = extendFn(Tech);
<del>
<del> Tech.withSourceHandlers(MyTech);
<del> const tech = new MyTech();
<del>
<del> const sourceHandler = {
<del> canPlayType(type) {
<del> return true;
<del> },
<del> canHandleSource(source, options) {
<del> return true;
<del> },
<del> handleSource(source, tech_, options) {
<del> return {
<del> dispose() {
<del> disposed = true;
<del> }
<del> };
<del> }
<del> };
<del>
<del> // Test registering source handlers
<del> MyTech.registerSourceHandler(sourceHandler);
<del>
<del> // First loadstart
<del> tech.setSource('test');
<del> tech.currentSource_ = 'test';
<del> tech.trigger('loadstart');
<del> assert.equal(tech.currentSource_, 'test', 'Current source is test');
<del>
<del> // Second loadstart
<del> tech.trigger('loadstart');
<del> assert.equal(tech.currentSource_, null, 'Current source is null');
<del> assert.equal(disposed, true, 'disposed is true');
<del>
<del> // Third loadstart
<del> tech.currentSource_ = 'test';
<del> tech.trigger('loadstart');
<del> assert.equal(tech.currentSource_, null, 'Current source is still null');
<del>
<del>});
<del>
<ide> QUnit.test('setSource after tech dispose should dispose source handler once', function(assert) {
<ide> const MyTech = extendFn(Tech);
<ide> | 2 |
Javascript | Javascript | use array.prototype.flat where supported | 9df4f1de12728b44a4b0f91748f12421008d9079 | <ide><path>src/core.js
<ide> define( [
<ide> "./var/arr",
<ide> "./var/getProto",
<ide> "./var/slice",
<del> "./var/concat",
<add> "./var/flat",
<ide> "./var/push",
<ide> "./var/indexOf",
<ide> "./var/class2type",
<ide> define( [
<ide> "./var/isWindow",
<ide> "./core/DOMEval",
<ide> "./core/toType"
<del>], function( arr, getProto, slice, concat, push, indexOf,
<add>], function( arr, getProto, slice, flat, push, indexOf,
<ide> class2type, toString, hasOwn, fnToString, ObjectFunctionString,
<ide> support, isWindow, DOMEval, toType ) {
<ide>
<ide> jQuery.extend( {
<ide> }
<ide>
<ide> // Flatten any nested arrays
<del> return concat.apply( [], ret );
<add> return flat( ret );
<ide> },
<ide>
<ide> // A global GUID counter for objects
<ide><path>src/manipulation.js
<ide> define( [
<ide> "./core",
<ide> "./core/isAttached",
<del> "./var/concat",
<add> "./var/flat",
<ide> "./var/isIE",
<ide> "./var/push",
<ide> "./core/access",
<ide> define( [
<ide> "./traversing",
<ide> "./selector",
<ide> "./event"
<del>], function( jQuery, isAttached, concat, isIE, push, access, rtagName,
<add>], function( jQuery, isAttached, flat, isIE, push, access, rtagName,
<ide> rscriptType, wrapMap, getAll, setGlobalEval, buildFragment,
<ide> dataPriv, dataUser, acceptData, DOMEval, nodeName ) {
<ide>
<ide> function cloneCopyEvent( src, dest ) {
<ide> function domManip( collection, args, callback, ignored ) {
<ide>
<ide> // Flatten any nested arrays
<del> args = concat.apply( [], args );
<add> args = flat( args );
<ide>
<ide> var fragment, first, scripts, hasScripts, node, doc,
<ide> i = 0,
<ide><path>src/var/concat.js
<del>define( [
<del> "./arr"
<del>], function( arr ) {
<del> "use strict";
<del>
<del> return arr.concat;
<del>} );
<ide><path>src/var/flat.js
<add>define( [
<add> "./arr"
<add>], function( arr ) {
<add>
<add>"use strict";
<add>
<add>// Support: IE 11+, Edge 18+
<add>// Provide fallback for browsers without Array#flat.
<add>return arr.flat ? function( array ) {
<add> return arr.flat.call( array );
<add>} : function( array ) {
<add> return arr.concat.apply( [], array );
<add>};
<add>
<add>} );
<ide><path>test/unit/core.js
<ide> QUnit.test( "map()", function( assert ) {
<ide> } );
<ide>
<ide> QUnit.test( "jQuery.map", function( assert ) {
<del> assert.expect( 25 );
<add> assert.expect( 28 );
<ide>
<ide> var i, label, result, callback;
<ide>
<ide> QUnit.test( "jQuery.map", function( assert ) {
<ide> return k % 2 ? k : [ k, k, k ];
<ide> } );
<ide> assert.equal( result.join( "" ), "00012223", "Array results flattened (#2616)" );
<add>
<add> result = jQuery.map( [ [ [ 1, 2 ], 3 ], 4 ], function( v, k ) {
<add> return v;
<add> } );
<add> assert.equal( result.length, 3, "Array flatten only one level down" );
<add> assert.ok( Array.isArray( result[ 0 ] ), "Array flatten only one level down" );
<add>
<add> // Support: IE 11+, Edge 18+
<add> // Skip the test in browsers without Array#flat.
<add> if ( Array.prototype.flat ) {
<add> result = jQuery.map( Array( 300000 ), function( v, k ) {
<add> return k;
<add> } );
<add> assert.equal( result.length, 300000, "Able to map 300000 records without any problems (#4320)" );
<add> } else {
<add> assert.ok( "skip", "Array#flat doesn't supported on all browsers" );
<add> }
<ide> } );
<ide>
<ide> QUnit.test( "jQuery.merge()", function( assert ) { | 5 |
Ruby | Ruby | fix quoting of the patch `url` when autocorrecting | a328acc9a109dea01210b0556790728be2023f16 | <ide><path>Library/Homebrew/rubocops/patches.rb
<ide> def patch_problems(patch_url_node)
<ide> gh_patch_param_pattern = %r{https?://github\.com/.+/.+/(?:commit|pull)/[a-fA-F0-9]*.(?:patch|diff)}
<ide> if regex_match_group(patch_url_node, gh_patch_param_pattern) && !patch_url.match?(/\?full_index=\w+$/)
<ide> problem "GitHub patches should use the full_index parameter: #{patch_url}?full_index=1" do |corrector|
<del> corrector.replace(patch_url_node.source_range, "#{patch_url}?full_index=1")
<add> corrector.replace(patch_url_node.source_range, "\"#{patch_url}?full_index=1\"")
<ide> end
<ide> end
<ide> | 1 |
Javascript | Javascript | escape forward slash in email regexp | a88c215f17829c1cfdec36bc1ef40bae10c41dff | <ide><path>src/ng/directive/input.js
<ide> */
<ide>
<ide> var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/;
<del>var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
<add>var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
<ide> var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/;
<ide> var DATE_REGEXP = /^(\d{4})-(\d{2})-(\d{2})$/;
<ide> var DATETIMELOCAL_REGEXP = /^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)$/; | 1 |
Text | Text | add 2.18.2 to the changelog.md | 401ff152f52b14f24f0df1167ff74c5661f76df6 | <ide><path>CHANGELOG.md
<ide> - [#16036](https://github.com/emberjs/ember.js/pull/16036) [CLEANUP] Convert ember-metal accessors tests to new style
<ide> - [#16023](https://github.com/emberjs/ember.js/pull/16023) Make event dispatcher work without jQuery
<ide>
<add>### 2.18.2 (February 14, 2018)
<add>
<add>- [#16245](https://github.com/emberjs/ember.js/pull/16245) [BUGFIX] Ensure errors in deferred component hooks can be recovered.
<add>
<ide> ### 2.18.1 (February 13, 2018)
<ide>
<ide> - [#16174](https://github.com/emberjs/ember.js/pull/16174) [BUGFIX] Enable _some_ recovery of errors thrown during render. | 1 |
Text | Text | add davisjam to collaborators | 7012950e2b8e845b738c82fd6fdf07d35ef13975 | <ide><path>README.md
<ide> For more information about the governance of the Node.js project, see
<ide> **Daniel Bevenius** <daniel.bevenius@gmail.com>
<ide> * [DavidCai1993](https://github.com/DavidCai1993) -
<ide> **David Cai** <davidcai1993@yahoo.com> (he/him)
<add>* [davisjam](https://github.com/davisjam) -
<add>**Jamie Davis** <davisjam@vt.edu> (he/him)
<ide> * [devsnek](https://github.com/devsnek) -
<ide> **Gus Caplan** <me@gus.host> (he/him)
<ide> * [edsadr](https://github.com/edsadr) - | 1 |
Ruby | Ruby | remove unnecessary code | dd1f742854e965261a31e05674cba0cf767c364b | <ide><path>Library/Homebrew/test/testing_env.rb
<ide> def shutup
<ide> require 'extend/ARGV' # needs to be after test/unit to avoid conflict with OptionsParser
<ide> require 'extend/ENV'
<ide> ARGV.extend(HomebrewArgvExtension)
<del>ENV.extend(Stdenv)
<ide>
<ide> begin
<ide> require 'rubygems' | 1 |
PHP | PHP | fix some docblock type | 133c34445cc97314c8ab739d2cfb56f1d084f935 | <ide><path>src/Cache/Engine/MemcachedEngine.php
<ide> class MemcachedEngine extends CacheEngine {
<ide> /**
<ide> * memcached wrapper.
<ide> *
<del> * @var Memcache
<add> * @var Memcached
<ide> */
<ide> protected $_Memcached = null;
<ide>
<ide><path>src/Cache/Engine/RedisEngine.php
<ide> class RedisEngine extends CacheEngine {
<ide> /**
<ide> * Redis wrapper.
<ide> *
<del> * @var Redis
<add> * @var \Redis
<ide> */
<ide> protected $_Redis = null;
<ide>
<ide><path>src/Collection/Iterator/TreePrinter.php
<ide> class TreePrinter extends RecursiveIteratorIterator {
<ide> /**
<ide> * Constructor
<ide> *
<del> * @param RecursiveIterator $items The iterator to flatten.
<add> * @param \RecursiveIterator $items The iterator to flatten.
<ide> * @param string|callable $valuePath The property to extract or a callable to return
<ide> * the display value.
<ide> * @param string|callable $keyPath The property to use as iteration key or a
<ide><path>src/Console/ConsoleErrorHandler.php
<ide> public function __construct($options = []) {
<ide> *
<ide> * @param \Exception $exception Exception instance.
<ide> * @return void
<del> * @throws Exception When renderer class not found
<add> * @throws \Exception When renderer class not found
<ide> * @see http://php.net/manual/en/function.set-exception-handler.php
<ide> */
<ide> public function handleException(\Exception $exception) {
<ide><path>src/Controller/Component/RequestHandlerComponent.php
<ide> use Cake\Event\Event;
<ide> use Cake\Network\Response;
<ide> use Cake\Routing\Router;
<del>use Cake\Utility\Error\XmlException;
<add>use Cake\Utility\Exception\XmlException;
<ide> use Cake\Utility\Inflector;
<ide> use Cake\Utility\Xml;
<ide>
<ide><path>src/Controller/Component/SessionComponent.php
<ide> class SessionComponent extends Component {
<ide> /**
<ide> * The Session object instance
<ide> *
<del> * @var Cake\Network\Session
<add> * @var \Cake\Network\Session
<ide> */
<ide> protected $_session;
<ide>
<ide><path>src/Core/InstanceConfigTrait.php
<ide> protected function _configRead($key) {
<ide> * @param mixed $value Value to write.
<ide> * @param bool $merge Whether to merge or overwrite value.
<ide> * @return void
<del> * @throws Cake\Core\Exception\Exception if attempting to clobber existing config
<add> * @throws \Cake\Core\Exception\Exception if attempting to clobber existing config
<ide> */
<ide> protected function _configWrite($key, $value, $merge = false) {
<ide> if (is_string($key) && $value === null) {
<ide> protected function _configWrite($key, $value, $merge = false) {
<ide> *
<ide> * @param string $key Key to delete.
<ide> * @return void
<del> * @throws Cake\Core\Exception\Exception if attempting to clobber existing config
<add> * @throws \Cake\Core\Exception\Exception if attempting to clobber existing config
<ide> */
<ide> protected function _configDelete($key) {
<ide> if (strpos($key, '.') === false) {
<ide><path>src/Core/ObjectRegistry.php
<ide> abstract protected function _create($class, $alias, $config);
<ide> * Get the loaded object list, or get the object instance at a given name.
<ide> *
<ide> * @param null|string $name The object name to get or null.
<del> * @return array|Helper Either a list of object names, or a loaded object.
<add> * @return array|\Cake\View\Helper Either a list of object names, or a loaded object.
<ide> */
<ide> public function loaded($name = null) {
<ide> if (!empty($name)) {
<ide><path>src/Database/Dialect/PostgresDialectTrait.php
<ide> trait PostgresDialectTrait {
<ide> /**
<ide> * Distinct clause needs no transformation
<ide> *
<del> * @param Query $query The query to be transformed
<del> * @return Query
<add> * @param \Cake\Database\Query $query The query to be transformed
<add> * @return \Cake\Database\Query
<ide> */
<ide> protected function _transformDistinct($query) {
<ide> return $query;
<ide><path>src/Database/Dialect/SqliteDialectTrait.php
<ide> protected function _transformFunctionExpression(FunctionExpression $expression)
<ide> * joined with UNION.
<ide> *
<ide> * @param \Cake\Database\Query $query The query to translate
<del> * @return Query
<add> * @return \Cake\Database\Query
<ide> */
<ide> protected function _insertQueryTranslator($query) {
<ide> $v = $query->clause('values');
<ide><path>src/Database/Expression/Comparison.php
<ide> public function value($value) {
<ide> /**
<ide> * Returns the field name
<ide> *
<del> * @return string|Cake\Database\ExpressionInterface
<add> * @return string|\Cake\Database\ExpressionInterface
<ide> */
<ide> public function getField() {
<ide> return $this->_field;
<ide><path>src/Database/Expression/QueryExpression.php
<ide> class QueryExpression implements ExpressionInterface, Countable {
<ide> *
<ide> * @param array $conditions tree-like array structure containing all the conditions
<ide> * to be added or nested inside this expression object.
<del> * @param array|TypeMap $types associative array of types to be associated with the values
<add> * @param array|\Cake\Database\TypeMap $types associative array of types to be associated with the values
<ide> * passed in $conditions.
<ide> * @param string $conjunction the glue that will join all the string conditions at this
<ide> * level of the expression tree. For example "AND", "OR", "XOR"...
<ide><path>src/Database/Log/LoggedQuery.php
<ide> class LoggedQuery {
<ide> /**
<ide> * Returns the string representation of this logged query
<ide> *
<del> * @return void
<add> * @return string
<ide> */
<ide> public function __toString() {
<ide> return $this->query;
<ide><path>src/Error/BaseErrorHandler.php
<ide> public function handleError($code, $description, $file = null, $line = null, $co
<ide> *
<ide> * @param \Exception $exception Exception instance.
<ide> * @return void
<del> * @throws Exception When renderer class not found
<add> * @throws \Exception When renderer class not found
<ide> * @see http://php.net/manual/en/function.set-exception-handler.php
<ide> */
<ide> public function handleException(\Exception $exception) {
<ide> protected function _logError($level, $data) {
<ide> /**
<ide> * Handles exception logging
<ide> *
<del> * @param Exception $exception Exception instance.
<add> * @param \Exception $exception Exception instance.
<ide> * @return bool
<ide> */
<ide> protected function _logException(\Exception $exception) {
<ide> protected function _logException(\Exception $exception) {
<ide> /**
<ide> * Generates a formatted error message
<ide> *
<del> * @param Exception $exception Exception instance
<add> * @param \Exception $exception Exception instance
<ide> * @return string Formatted message
<ide> */
<ide> protected function _getMessage(\Exception $exception) {
<ide><path>src/Error/ErrorHandler.php
<ide> protected function _clearOutput() {
<ide> /**
<ide> * Method that can be easily stubbed in testing.
<ide> *
<del> * @param string|Cake\Network\Response $response Either the message or response object.
<add> * @param string|\Cake\Network\Response $response Either the message or response object.
<ide> * @return void
<ide> */
<ide> protected function _sendResponse($response) {
<ide><path>src/Event/EventManager.php
<ide> protected function _detachSubscriber(EventListenerInterface $subscriber, $eventK
<ide> * Dispatches a new event to all configured listeners
<ide> *
<ide> * @param string|\Cake\Event\Event $event the event key name or instance of Event
<del> * @return CakeEvent
<del> * @param string|CakeEvent $event the event key name or instance of CakeEvent
<del> * @return CakeEvent
<add> * @return \Cake\Event\Event
<ide> */
<ide> public function dispatch($event) {
<ide> if (is_string($event)) {
<ide><path>src/I18n/Formatter/IcuFormatter.php
<ide> public function format($locale, $message, array $vars) {
<ide> * @param string|array $message The message to be translated
<ide> * @param array $vars The list of values to interpolate in the message
<ide> * @return string The formatted message
<del> * @throws Aura\Intl\Exception\CannotInstantiateFormatter if any error occurred
<add> * @throws \Aura\Intl\Exception\CannotInstantiateFormatter if any error occurred
<ide> * while parsing the message
<del> * @throws Aura\Intl\Exception\CannotFormat If any error related to the passed
<add> * @throws \Aura\Intl\Exception\CannotFormat If any error related to the passed
<ide> * variables is found
<ide> */
<ide> protected function _formatMessage($locale, $message, $vars) {
<ide><path>src/I18n/MessagesFileLoader.php
<ide> public function __construct($name, $locale, $extension = 'po') {
<ide> * Loads the translation file and parses it. Returns an instance of a translations
<ide> * package containing the messages loaded from the file.
<ide> *
<del> * @return Aura\Intl\Package
<add> * @return \Aura\Intl\Package
<ide> * @throws \RuntimeException if no file parser class could be found for the specified
<ide> * file extension.
<ide> */
<ide><path>src/Network/Http/Adapter/Stream.php
<ide> protected function _buildSslContext(Request $request, $options) {
<ide> /**
<ide> * Open the stream and send the request.
<ide> *
<del> * @param \Cake\Network\Request $request The request object.
<add> * @param \Cake\Network\Http\Request $request The request object.
<ide> * @return array Array of populated Response objects
<ide> * @throws \Cake\Core\Exception\Exception
<ide> */
<ide><path>src/Network/Http/Auth/Basic.php
<ide> class Basic {
<ide> /**
<ide> * Add Authorization header to the request.
<ide> *
<del> * @param \Cake\Network\Request $request Request instance.
<add> * @param \Cake\Network\Http\Request $request Request instance.
<ide> * @param array $credentials Credentials.
<ide> * @return void
<ide> * @see http://www.ietf.org/rfc/rfc2617.txt
<ide> public function authentication(Request $request, array $credentials) {
<ide> /**
<ide> * Proxy Authentication
<ide> *
<del> * @param \Cake\Network\Request $request Request instance.
<add> * @param \Cake\Network\Http\Request $request Request instance.
<ide> * @param array $credentials Credentials.
<ide> * @return void
<ide> * @see http://www.ietf.org/rfc/rfc2617.txt
<ide><path>src/Network/Http/Auth/Digest.php
<ide> public function __construct(Client $client, $options = null) {
<ide> /**
<ide> * Add Authorization header to the request.
<ide> *
<del> * @param \Cake\Network\Request $request The request object.
<add> * @param \Cake\Network\Http\Request $request The request object.
<ide> * @param array $credentials Authentication credentials.
<ide> * @return void
<ide> * @see http://www.ietf.org/rfc/rfc2617.txt
<ide> public function authentication(Request $request, array $credentials) {
<ide> * another request without authentication to get authentication
<ide> * challenge.
<ide> *
<del> * @param \Cake\Network\Request $request The request object.
<add> * @param \Cake\Network\Http\Request $request The request object.
<ide> * @param array $credentials Authentication credentials.
<ide> * @return Array modified credentials.
<ide> */
<ide> protected function _getServerInfo(Request $request, $credentials) {
<ide> /**
<ide> * Generate the header Authorization
<ide> *
<del> * @param \Cake\Network\Request $request The request object.
<add> * @param \Cake\Network\Http\Request $request The request object.
<ide> * @param array $credentials Authentication credentials.
<ide> * @return string
<ide> */
<ide><path>src/Network/Http/Auth/Oauth.php
<ide> class Oauth {
<ide> /**
<ide> * Add headers for Oauth authorization.
<ide> *
<del> * @param \Cake\Network\Request $request The request object.
<add> * @param \Cake\Network\Http\Request $request The request object.
<ide> * @param array $credentials Authentication credentials.
<ide> * @return void
<ide> * @throws \Cake\Core\Exception\Exception On invalid signature types.
<ide> public function authentication(Request $request, array $credentials) {
<ide> * You should only ever use PLAINTEXT when dealing with SSL
<ide> * services.
<ide> *
<del> * @param \Cake\Network\Request $request The request object.
<add> * @param \Cake\Network\Http\Request $request The request object.
<ide> * @param array $credentials Authentication credentials.
<ide> * @return string Authorization header.
<ide> */
<ide> protected function _plaintext($request, $credentials) {
<ide> *
<ide> * This method is suitable for plain HTTP or HTTPS.
<ide> *
<del> * @param \Cake\Network\Request $request The request object.
<add> * @param \Cake\Network\Http\Request $request The request object.
<ide> * @param array $credentials Authentication credentials.
<ide> * @return string
<ide> */
<ide> protected function _hmacSha1($request, $credentials) {
<ide> * - The request URL (without querystring) is normalized.
<ide> * - The HTTP method, URL and request parameters are concatenated and returnned.
<ide> *
<del> * @param \Cake\Network\Request $request The request object.
<add> * @param \Cake\Network\Http\Request $request The request object.
<ide> * @param array $oauthValues Oauth values.
<ide> * @return string
<ide> */
<ide> protected function _normalizedUrl($url) {
<ide> * - URL encode keys + values.
<ide> * - Sort keys & values by byte value.
<ide> *
<del> * @param \Cake\Network\Request $request The request object.
<add> * @param \Cake\Network\Http\Request $request The request object.
<ide> * @param array $oauthValues Oauth values.
<ide> * @return string sorted and normalized values
<ide> */
<ide><path>src/Network/Http/CookieCollection.php
<ide> class CookieCollection {
<ide> * Store the cookies that haven't expired. If a cookie has been expired
<ide> * and is currently stored, it will be removed.
<ide> *
<del> * @param \Cake\Network\Response $response The response to read cookies from
<add> * @param \Cake\Network\Http\Response $response The response to read cookies from
<ide> * @param string $url The request URL used for default host/path values.
<ide> * @return void
<ide> */
<ide><path>src/ORM/TableRegistry.php
<ide> public static function exists($alias) {
<ide> *
<ide> * @param string $alias The alias to set.
<ide> * @param \Cake\ORM\Table $object The table to set.
<del> * @return void
<add> * @return \Cake\ORM\Table
<ide> */
<ide> public static function set($alias, Table $object) {
<ide> return static::$_instances[$alias] = $object;
<ide><path>src/Routing/Filter/AssetFilter.php
<ide> class AssetFilter extends DispatcherFilter {
<ide> *
<ide> * @param \Cake\Event\Event $event containing the request and response object
<ide> * @return \Cake\Network\Response if the client is requesting a recognized asset, null otherwise
<del> * @throws NotFoundException When asset not found
<add> * @throws \Cake\Network\Exception\NotFoundException When asset not found
<ide> */
<ide> public function beforeDispatch(Event $event) {
<ide> $request = $event->data['request'];
<ide><path>src/Routing/RouteBuilder.php
<ide> class RouteBuilder {
<ide> /**
<ide> * The route collection routes should be added to.
<ide> *
<del> * @var Cake\Routing\RouteCollection
<add> * @var \Cake\Routing\RouteCollection
<ide> */
<ide> protected $_collection;
<ide>
<ide><path>src/TestSuite/ControllerTestCase.php
<ide> */
<ide> namespace Cake\TestSuite;
<ide>
<del>use Cake\Controller\Error\MissingComponentException;
<del>use Cake\Controller\Error\MissingControllerException;
<add>use Cake\Controller\Exception\MissingComponentException;
<add>use Cake\Routing\Exception\MissingControllerException;
<ide> use Cake\Core\App;
<ide> use Cake\Event\Event;
<ide> use Cake\Network\Request;
<ide> protected function _testAction($url = '', $options = array()) {
<ide> * @param \Cake\Network\Request $request A request object to build the controller with.
<ide> * This parameter is required when mocking prefixed controllers.
<ide> * @return \Cake\Controller\Controller Mocked controller
<del> * @throws \Cake\Controller\Error\MissingControllerException When controllers could not be created.
<del> * @throws \Cake\Controller\Error\MissingComponentException When components could not be created.
<add> * @throws \Cake\Routing\Exception\MissingControllerException When controllers could not be created.
<add> * @throws \Cake\Controller\Exception\MissingComponentException When components could not be created.
<ide> */
<ide> public function generate($controller, array $mocks = array(), Request $request = null) {
<ide> $className = App::className($controller, 'Controller', 'Controller');
<ide><path>src/TestSuite/Fixture/TestFixture.php
<ide> public function __construct() {
<ide> * Initialize the fixture.
<ide> *
<ide> * @return void
<del> * @throws \Cake\ORM\Error\MissingTableException When importing from a table that does not exist.
<add> * @throws \Cake\ORM\Exception\MissingTableClassException When importing from a table that does not exist.
<ide> */
<ide> public function init() {
<ide> if ($this->table === null) {
<ide><path>src/View/Cell.php
<ide> public function __toString() {
<ide> /**
<ide> * Debug info.
<ide> *
<del> * @return void
<add> * @return array
<ide> */
<ide> public function __debugInfo() {
<ide> return [
<ide><path>src/View/CellTrait.php
<ide> public function cell($cell, array $data = [], array $options = []) {
<ide> * @param string $action The action name.
<ide> * @param string $plugin The plugin name.
<ide> * @param array $options The constructor options for the cell.
<del> * @return Cake\View\Cell;
<add> * @return \Cake\View\Cell;
<ide> */
<ide> protected function _createCell($className, $action, $plugin, $options) {
<ide> $instance = new $className($this->request, $this->response, $this->eventManager(), $options);
<ide><path>src/View/ViewVarsTrait.php
<ide> public function getView($viewClass = null) {
<ide> * Constructs the view class instance based on object properties.
<ide> *
<ide> * @param string $viewClass Optional namespaced class name of the View class to instantiate.
<del> * @return Cake\View\View
<add> * @return \Cake\View\View
<ide> */
<ide> public function createView($viewClass = null) {
<ide> if ($viewClass === null) { | 31 |
Javascript | Javascript | add mocha rfc 232 util test | 2efbfac00652c97a89ba7eadc9a15796648790ea | <ide><path>blueprints/util-test/mocha-rfc-232-files/__root__/__testType__/__name__-test.js
<add>import { expect } from 'chai';
<add>import { describe, it } from 'mocha';
<add>import <%= camelizedModuleName %> from '<%= dasherizedPackageName %>/utils/<%= dasherizedModuleName %>';
<add>
<add>describe('<%= friendlyTestName %>', function() {
<add> // Replace this with your real tests.
<add> it('works', function() {
<add> let result = <%= camelizedModuleName %>();
<add> expect(result).to.be.ok;
<add> });
<add>});
<ide><path>node-tests/blueprints/util-test-test.js
<ide> describe('Blueprint: util-test', function() {
<ide> });
<ide> });
<ide> });
<add>
<add> describe('with ember-mocha@0.14.0', function() {
<add> beforeEach(function() {
<add> modifyPackages([
<add> { name: 'ember-cli-qunit', delete: true },
<add> { name: 'ember-mocha', dev: true },
<add> ]);
<add> generateFakePackageManifest('ember-mocha', '0.14.0');
<add> });
<add>
<add> it('util-test foo-bar', function() {
<add> return emberGenerateDestroy(['util-test', 'foo-bar'], _file => {
<add> expect(_file('tests/unit/utils/foo-bar-test.js')).to.equal(
<add> fixture('util-test/mocha-rfc232.js')
<add> );
<add> });
<add> });
<add> });
<ide> });
<ide>
<ide> describe('in app - module uninification', function() {
<ide><path>node-tests/fixtures/util-test/mocha-rfc232.js
<add>import { expect } from 'chai';
<add>import { describe, it } from 'mocha';
<add>import fooBar from 'my-app/utils/foo-bar';
<add>
<add>describe('Unit | Utility | foo-bar', function() {
<add> // Replace this with your real tests.
<add> it('works', function() {
<add> let result = fooBar();
<add> expect(result).to.be.ok;
<add> });
<add>}); | 3 |
Text | Text | remove description duplication in buffer.md | 1dd9662e2ba4934763ea764f2aede977c6c68339 | <ide><path>doc/api/buffer.md
<ide> console.log(buf);
<ide> // Prints: <Buffer 00 00 00 00 00>
<ide> ```
<ide>
<del>Allocates a new `Buffer` of `size` bytes. If `size` is larger than
<add>If `size` is larger than
<ide> [`buffer.constants.MAX_LENGTH`] or smaller than 0, [`ERR_INVALID_OPT_VALUE`] is
<ide> thrown. A zero-length `Buffer` is created if `size` is 0.
<ide> | 1 |
Python | Python | add tests for multiworkermirroredstrategy | 3b77b6168867b8b4eb3cded2ff73f2268f004dc1 | <ide><path>keras/distribute/multi_worker_test.py
<ide> def testSimpleModelIndependentWorkerSync(self, strategy):
<ide>
<ide> verification_callback.verify(self)
<ide>
<add> @tf.__internal__.distribute.combinations.generate(
<add> tf.__internal__.test.combinations.combine(
<add> mode=["eager"],
<add> strategy=[
<add> tf.__internal__.distribute.combinations.multi_worker_mirrored_2x1_cpu, # noqa: E501
<add> tf.__internal__.distribute.combinations.multi_worker_mirrored_2x1_gpu, # noqa: E501
<add> ],
<add> )
<add> )
<add> def test_distribution_reduction_method_auto_default_train_step(
<add> self, strategy
<add> ):
<add> batch_size = 8
<add> epochs = 2
<add> steps = 2
<add> train_ds, _ = multi_worker_testing_utils.mnist_synthetic_dataset(
<add> batch_size, steps
<add> )
<add>
<add> # A model that always outputs `sum(inputs*1) + 1 = 28**2 + 1 = 785`
<add> with strategy.scope():
<add> inputs = keras.Input(shape=(28, 28, 1))
<add> x = keras.layers.Flatten(inputs)
<add> x = keras.layers.Dense(
<add> 1, kernel_initializer="ones", bias_initializer="ones"
<add> )(x)
<add> model = keras.Model(inputs=inputs, outputs=x)
<add> # model.distribute_reduction_method = 'auto'
<add> model.trainable = False
<add> model.compile(
<add> loss=keras.losses.mean_absolute_error,
<add> optimizer=multi_worker_testing_utils.gradient_descent.SGD(
<add> learning_rate=0.001
<add> ),
<add> metrics=["mse"],
<add> )
<add>
<add> # For every output x_i = 785, every target y_i = 1,
<add> # loss_i = |785-1| = 784; and
<add> # loss_total = sum([784, 784, ..., 784]) / (BATCH_SIZE*steps) = 784
<add> orig_loss, _ = model.evaluate(train_ds, steps=steps)
<add> self.assertEqual(784, orig_loss)
<add>
<add> history = model.fit(train_ds, epochs=epochs, steps_per_epoch=steps)
<add> self.assertAllClose(history.history["loss"], [784] * epochs)
<add>
<add> trained_loss, _ = model.evaluate(train_ds, steps=steps)
<add> self.assertEqual(784, trained_loss)
<add>
<add> @tf.__internal__.distribute.combinations.generate(
<add> tf.__internal__.test.combinations.combine(
<add> mode=["eager"],
<add> strategy=[
<add> tf.__internal__.distribute.combinations.multi_worker_mirrored_2x1_cpu, # noqa: E501
<add> tf.__internal__.distribute.combinations.multi_worker_mirrored_2x1_gpu, # noqa: E501
<add> ],
<add> )
<add> )
<add> def test_distribution_reduction_method_auto_custom_train_step(
<add> self, strategy
<add> ):
<add> batch_size = 8
<add> steps = 2
<add> epochs = 2
<add> train_ds, _ = multi_worker_testing_utils.mnist_synthetic_dataset(
<add> batch_size, steps
<add> )
<add>
<add> class MyModel(keras.Model):
<add> @staticmethod
<add> def reduce_loss(loss_value, global_batch_size):
<add> REDUCTION_AXES = range(1, backend.ndim(loss_value))
<add> loss_value = tf.reduce_mean(loss_value, axis=REDUCTION_AXES)
<add> return tf.nn.compute_average_loss(
<add> loss_value, global_batch_size=global_batch_size
<add> )
<add>
<add> def train_step(self, data):
<add> loss_value = 3 * tf.ones_like(data[0])
<add> return {
<add> "loss": MyModel.reduce_loss(
<add> loss_value, global_batch_size=batch_size
<add> )
<add> }
<add>
<add> def test_step(self, data):
<add> loss_value = 5 * tf.ones_like(data[0])
<add> return {
<add> "metric": MyModel.reduce_loss(
<add> loss_value, global_batch_size=batch_size
<add> )
<add> }
<add>
<add> with strategy.scope():
<add> inputs = keras.Input(shape=(28, 28, 1))
<add> x = keras.layers.Flatten(inputs)
<add> x = keras.layers.Dense(
<add> 1, kernel_initializer="ones", bias_initializer="ones"
<add> )(x)
<add> model = MyModel(inputs=inputs, outputs=x)
<add> # model.distribute_reduction_method = 'auto'
<add> model.compile(
<add> loss=keras.losses.mean_absolute_error,
<add> optimizer=multi_worker_testing_utils.gradient_descent.SGD(
<add> learning_rate=0.001
<add> ),
<add> )
<add>
<add> # For two mirrored workers, output x_i = 2, every target y_i = 1,
<add> # train_loss_i = 3 test_loss_i = 5, then:
<add> # train_loss_total = sum([3, 3, ...]) / (BATCH_SIZE * steps) = 3.0
<add> # test_loss_total = sum([5, 5, ...]) / (BATCH_SIZE * steps) = 5.0
<add> history = model.fit(train_ds, epochs=epochs, steps_per_epoch=steps)
<add> self.assertAllClose(history.history["loss"], [3.0] * epochs)
<add>
<add> eval_output = model.evaluate(train_ds, steps=steps)
<add> self.assertAllClose(eval_output, 5.0)
<add>
<ide>
<ide> class KPLMultiWorkerTest(tf.test.TestCase, parameterized.TestCase):
<ide> @tf.__internal__.distribute.combinations.generate( | 1 |
Ruby | Ruby | use formatted number as schema version | 826e49cfbe9589e600e652c31eb62954dcc86061 | <ide><path>activerecord/lib/active_record/schema_dumper.rb
<ide> def initialize(connection, options = {})
<ide> @options = options
<ide> end
<ide>
<add> # turns 20170404131909 into "2017_04_04131909"
<add> def formatted_version
<add> return "" unless @version
<add> stringified = @version.to_s
<add> return stringified unless stringified.length == 14
<add> stringified.insert(4, "_").insert(7, "_").insert(10, "_")
<add> end
<add>
<ide> def header(stream)
<del> define_params = @version ? "version: #{@version}" : ""
<add> define_params = @version ? "version: #{formatted_version}" : ""
<ide>
<ide> stream.puts <<HEADER
<ide> # This file is auto-generated from the current state of the database. Instead | 1 |
Ruby | Ruby | fix deprecation warnings in active support tests | 67e18160e6cd53b2cc605eaeaeae2a0557246e7c | <ide><path>activesupport/test/core_ext/range_ext_test.rb
<ide> def test_cover_on_time_with_zone
<ide> end
<ide>
<ide> def test_include_on_time_with_zone
<del> twz = ActiveSupport::TimeWithZone.new(nil, ActiveSupport::TimeZone["Eastern Time (US & Canada)"], Time.utc(2006, 11, 28, 10, 30))
<del> assert ((twz - 1.hour)..twz).include?(twz)
<del> end
<del>
<del> def test_include_on_time_with_zone_deprecation
<ide> twz = ActiveSupport::TimeWithZone.new(nil, ActiveSupport::TimeZone["Eastern Time (US & Canada)"], Time.utc(2006, 11, 28, 10, 30))
<ide> assert_deprecated do
<ide> ((twz - 1.hour)..twz).include?(twz)
<ide> def test_include_on_time_with_zone_deprecation
<ide>
<ide> def test_case_equals_on_time_with_zone
<ide> twz = ActiveSupport::TimeWithZone.new(nil, ActiveSupport::TimeZone["Eastern Time (US & Canada)"], Time.utc(2006, 11, 28, 10, 30))
<del> assert ((twz - 1.hour)..twz) === twz
<add> if RUBY_VERSION >= "2.6" # https://bugs.ruby-lang.org/issues/14575
<add> assert ((twz - 1.hour)..twz) === twz
<add> else
<add> assert_deprecated do
<add> assert ((twz - 1.hour)..twz) === twz
<add> end
<add> end
<ide> end
<ide>
<ide> def test_date_time_with_each | 1 |
Javascript | Javascript | make the transform defaults to an array | a8a750ab05bdff73ba3af0b98f3f284ff8d1e743 | <ide><path>src/ng/http.js
<ide> function $HttpProvider() {
<ide>
<ide> var $config = this.defaults = {
<ide> // transform incoming response data
<del> transformResponse: function(data) {
<add> transformResponse: [function(data) {
<ide> if (isString(data)) {
<ide> // strip json vulnerability protection prefix
<ide> data = data.replace(PROTECTION_PREFIX, '');
<ide> if (JSON_START.test(data) && JSON_END.test(data))
<ide> data = fromJson(data, true);
<ide> }
<ide> return data;
<del> },
<add> }],
<ide>
<ide> // transform outgoing request data
<del> transformRequest: function(d) {
<add> transformRequest: [function(d) {
<ide> return isObject(d) && !isFile(d) ? toJson(d) : d;
<del> },
<add> }],
<ide>
<ide> // default headers
<ide> headers: { | 1 |
Ruby | Ruby | pass the key to the block in cache.fetch on misses | 81b711256591874b92683e55dc405286eb6df7a6 | <ide><path>activesupport/lib/active_support/cache.rb
<ide> def self.instrument
<ide> # the cache with the given key, then that data is returned.
<ide> #
<ide> # If there is no such data in the cache (a cache miss), then +nil+ will be
<del> # returned. However, if a block has been passed, that block will be run
<del> # in the event of a cache miss. The return value of the block will be
<del> # written to the cache under the given cache key, and that return value
<del> # will be returned.
<add> # returned. However, if a block has been passed, that block will be passed
<add> # the key and executed in the event of a cache miss. The return value of the
<add> # block will be written to the cache under the given cache key, and that
<add> # return value will be returned.
<ide> #
<ide> # cache.write('today', 'Monday')
<ide> # cache.fetch('today') # => "Monday"
<ide> def fetch(name, options = nil)
<ide> entry.value
<ide> else
<ide> result = instrument(:generate, name, options) do |payload|
<del> yield
<add> yield(name)
<ide> end
<ide> write(name, result, options)
<ide> result
<ide><path>activesupport/test/caching_test.rb
<ide> def test_expand_cache_key_of_false
<ide> def test_expand_cache_key_of_true
<ide> assert_equal 'true', ActiveSupport::Cache.expand_cache_key(true)
<ide> end
<del>
<add>
<ide> def test_expand_cache_key_of_array_like_object
<ide> assert_equal 'foo/bar/baz', ActiveSupport::Cache.expand_cache_key(%w{foo bar baz}.to_enum)
<ide> end
<ide> def test_fetch_with_cache_miss
<ide> assert_equal 'baz', @cache.fetch('foo') { 'baz' }
<ide> end
<ide>
<add> def test_fetch_with_cache_miss_passes_key_to_block
<add> @cache.expects(:write).with('foo', 3, @cache.options)
<add> assert_equal 3, @cache.fetch('foo') { |key| key.length }
<add> end
<add>
<ide> def test_fetch_with_forced_cache_miss
<ide> @cache.write('foo', 'bar')
<ide> @cache.expects(:read).never
<ide> def test_key_transformation_with_pathname
<ide> assert_equal "views/index?id=1", @cache_with_pathname.send(:file_path_key, key)
<ide> end
<ide>
<del> # Test that generated cache keys are short enough to have Tempfile stuff added to them and
<add> # Test that generated cache keys are short enough to have Tempfile stuff added to them and
<ide> # remain valid
<ide> def test_filename_max_size
<ide> key = "#{'A' * ActiveSupport::Cache::FileStore::FILENAME_MAX_SIZE}" | 2 |
Text | Text | add wherekeynot to changelog | c60cf5e029bedf83ee19a2e2a6388c0de374e155 | <ide><path>CHANGELOG-5.5.md
<ide> - ⚠️ Call `setConnection()` in `Model::save()` ([#20466](https://github.com/laravel/framework/pull/20466))
<ide> - ⚠️ Touch parent timestamp only if the model is dirty ([#20489](https://github.com/laravel/framework/pull/20489))
<ide> - Added `Model::loadMissing()` method ([#20630](https://github.com/laravel/framework/pull/20630), [4166c12](https://github.com/laravel/framework/commit/4166c12492ce7b1112911299caf4cdb17efc9364))
<add>- Added `whereKeyNot()` method ([#20817](https://github.com/laravel/framework/pull/20817))
<ide>
<ide> ### Encryption
<ide> - Use `openssl_cipher_iv_length()` in `Encrypter` ([#18684](https://github.com/laravel/framework/pull/18684)) | 1 |
Javascript | Javascript | remove unnessecary assignement | 7f648bbcd4096090aaff65d8b46b9678ac310b73 | <ide><path>examples/js/loaders/FBXLoader.js
<ide> }
<ide>
<ide> polygonIndex ++;
<del>
<del> endOfFace = false;
<ide> faceLength = 0;
<ide>
<ide> // reset arrays for the next face | 1 |
Mixed | Ruby | accept nested functions in dangerous query methods | 8fe1bd555f82715508d386b823a9d91628d10aab | <ide><path>activerecord/CHANGELOG.md
<add>* Allow nested functions as safe SQL string
<add>
<add> *Michael Siegfried*
<add>
<ide> * Allow `destroy_association_async_job=` to be configured with a class string instead of a constant.
<ide>
<ide> Defers an autoloading dependency between `ActiveRecord::Base` and `ActiveJob::Base`
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/quoting.rb
<ide> def column_name_with_order_matcher # :nodoc:
<ide> (
<ide> (?:
<ide> # table_name.column_name | function(one or no argument)
<del> ((?:\w+\.)?\w+) | \w+\((?:|\g<2>)\)
<add> ((?:\w+\.)?\w+ | \w+\((?:|\g<2>)\))
<ide> )
<ide> (?:(?:\s+AS)?\s+\w+)?
<ide> )
<ide> def column_name_with_order_matcher # :nodoc:
<ide> (
<ide> (?:
<ide> # table_name.column_name | function(one or no argument)
<del> ((?:\w+\.)?\w+) | \w+\((?:|\g<2>)\)
<add> ((?:\w+\.)?\w+ | \w+\((?:|\g<2>)\))
<ide> )
<ide> (?:\s+ASC|\s+DESC)?
<ide> (?:\s+NULLS\s+(?:FIRST|LAST))?
<ide><path>activerecord/lib/active_record/connection_adapters/mysql/quoting.rb
<ide> def column_name_with_order_matcher
<ide> (
<ide> (?:
<ide> # `table_name`.`column_name` | function(one or no argument)
<del> ((?:\w+\.|`\w+`\.)?(?:\w+|`\w+`)) | \w+\((?:|\g<2>)\)
<add> ((?:\w+\.|`\w+`\.)?(?:\w+|`\w+`) | \w+\((?:|\g<2>)\))
<ide> )
<ide> (?:(?:\s+AS)?\s+(?:\w+|`\w+`))?
<ide> )
<ide> def column_name_with_order_matcher
<ide> (
<ide> (?:
<ide> # `table_name`.`column_name` | function(one or no argument)
<del> ((?:\w+\.|`\w+`\.)?(?:\w+|`\w+`)) | \w+\((?:|\g<2>)\)
<add> ((?:\w+\.|`\w+`\.)?(?:\w+|`\w+`) | \w+\((?:|\g<2>)\))
<ide> )
<ide> (?:\s+COLLATE\s+(?:\w+|"\w+"))?
<ide> (?:\s+ASC|\s+DESC)?
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb
<ide> def column_name_with_order_matcher
<ide> (
<ide> (?:
<ide> # "schema_name"."table_name"."column_name"::type_name | function(one or no argument)::type_name
<del> ((?:\w+\.|"\w+"\.){,2}(?:\w+|"\w+")(?:::\w+)?) | \w+\((?:|\g<2>)\)(?:::\w+)?
<add> ((?:\w+\.|"\w+"\.){,2}(?:\w+|"\w+")(?:::\w+)? | \w+\((?:|\g<2>)\)(?:::\w+)?)
<ide> )
<ide> (?:(?:\s+AS)?\s+(?:\w+|"\w+"))?
<ide> )
<ide> def column_name_with_order_matcher
<ide> (
<ide> (?:
<ide> # "schema_name"."table_name"."column_name"::type_name | function(one or no argument)::type_name
<del> ((?:\w+\.|"\w+"\.){,2}(?:\w+|"\w+")(?:::\w+)?) | \w+\((?:|\g<2>)\)(?:::\w+)?
<add> ((?:\w+\.|"\w+"\.){,2}(?:\w+|"\w+")(?:::\w+)? | \w+\((?:|\g<2>)\)(?:::\w+)?)
<ide> )
<ide> (?:\s+COLLATE\s+"\w+")?
<ide> (?:\s+ASC|\s+DESC)?
<ide><path>activerecord/lib/active_record/connection_adapters/sqlite3/quoting.rb
<ide> def column_name_with_order_matcher
<ide> (
<ide> (?:
<ide> # "table_name"."column_name" | function(one or no argument)
<del> ((?:\w+\.|"\w+"\.)?(?:\w+|"\w+")) | \w+\((?:|\g<2>)\)
<add> ((?:\w+\.|"\w+"\.)?(?:\w+|"\w+") | \w+\((?:|\g<2>)\))
<ide> )
<ide> (?:(?:\s+AS)?\s+(?:\w+|"\w+"))?
<ide> )
<ide> def column_name_with_order_matcher
<ide> (
<ide> (?:
<ide> # "table_name"."column_name" | function(one or no argument)
<del> ((?:\w+\.|"\w+"\.)?(?:\w+|"\w+")) | \w+\((?:|\g<2>)\)
<add> ((?:\w+\.|"\w+"\.)?(?:\w+|"\w+") | \w+\((?:|\g<2>)\))
<ide> )
<ide> (?:\s+COLLATE\s+(?:\w+|"\w+"))?
<ide> (?:\s+ASC|\s+DESC)?
<ide><path>activerecord/test/cases/unsafe_raw_sql_test.rb
<ide> class UnsafeRawSqlTest < ActiveRecord::TestCase
<ide> assert_equal ids_expected, ids
<ide> end
<ide>
<add> test "order: allows nested functions" do
<add> ids_expected = Post.order(Arel.sql("author_id, length(trim(title))")).pluck(:id)
<add>
<add> ids = Post.order("author_id, length(trim(title))").pluck(:id)
<add>
<add> assert_equal ids_expected, ids
<add> end
<add>
<ide> test "order: logs deprecation warning for unrecognized column" do
<ide> e = assert_raises(ActiveRecord::UnknownAttributeReference) do
<ide> Post.order("REPLACE(title, 'misc', 'zzzz')")
<ide> class UnsafeRawSqlTest < ActiveRecord::TestCase
<ide> assert_equal titles_expected, titles
<ide> end
<ide>
<add> test "pluck: allows nested functions" do
<add> title_lengths_expected = Post.pluck(Arel.sql("length(trim(title))"))
<add>
<add> title_lengths = Post.pluck("length(trim(title))")
<add>
<add> assert_equal title_lengths_expected, title_lengths
<add> end
<add>
<ide> test "pluck: disallows invalid column name" do
<ide> assert_raises(ActiveRecord::UnknownAttributeReference) do
<ide> Post.pluck("REPLACE(title, 'misc', 'zzzz')") | 6 |
Ruby | Ruby | add nlopt to migration | 371858f41921f85bf1a98726c91fd9a94e8600a5 | <ide><path>Library/Homebrew/tap_migrations.rb
<ide> 'lmutil' => 'homebrew/binary',
<ide> 'jscoverage' => 'homebrew/boneyard',
<ide> 'jsl' => 'homebrew/binary',
<add> 'nlopt' => 'homebrew/science',
<ide> } | 1 |
Text | Text | fix typo in invalid getstaticpaths value example | 156a77409bed5f18947ece8572a24ae6808199ee | <ide><path>errors/invalid-getstaticpaths-value.md
<ide> In one of the page's `unstable_getStaticPaths` the return value had the incorrec
<ide> Make sure to return the following shape from `unstable_getStaticPaths`:
<ide>
<ide> ```js
<del>export async function unstable_getStaticProps() {
<add>export async function unstable_getStaticPaths() {
<ide> return {
<ide> paths: Array<string | { params: { [key: string]: string } }>
<ide> } | 1 |
Ruby | Ruby | move cache dir creation to fetch | d05478e85b776bf262e6bf2ca7b4b883a25de5ed | <ide><path>Library/Homebrew/formula.rb
<ide> def fetch
<ide> downloader = @downloader
<ide> mirror_list = mirrors
<ide>
<add> # Ensure the cache exists
<add> HOMEBREW_CACHE.mkpath
<add>
<ide> begin
<ide> fetched = downloader.fetch
<ide> rescue CurlDownloadStrategyError => e
<ide> def verify_download_integrity fn, *args
<ide> private
<ide>
<ide> def stage
<del> HOMEBREW_CACHE.mkpath
<ide> fetched, downloader = fetch
<ide> verify_download_integrity fetched if fetched.kind_of? Pathname
<ide> mktemp do | 1 |
Go | Go | add client os and arch to docker version | eceacb8334250b9f241b263f28372d5f35ada71d | <ide><path>api/client/commands.go
<ide> func (cli *DockerCli) CmdVersion(args ...string) error {
<ide> if dockerversion.GITCOMMIT != "" {
<ide> fmt.Fprintf(cli.out, "Git commit (client): %s\n", dockerversion.GITCOMMIT)
<ide> }
<add> fmt.Fprintf(cli.out, "OS/Arch (client): %s/%s\n", runtime.GOOS, runtime.GOARCH)
<ide>
<ide> body, _, err := readBody(cli.call("GET", "/version", nil, false))
<ide> if err != nil { | 1 |
Ruby | Ruby | move everything into one file | 9b50fd81d729080b746b9637ad3a0c59049b96a3 | <ide><path>Library/Homebrew/update_migrator.rb
<del>require "update_migrator/cache_entries_to_double_dashes"
<del>require "update_migrator/cache_entries_to_symlinks"
<del>require "update_migrator/legacy_cache"
<del>require "update_migrator/legacy_keg_symlinks"
<del>require "update_migrator/legacy_repository"
<add>require "hbc/cask_loader"
<add>require "hbc/download"
<ide>
<ide> module UpdateMigrator
<del> module_function
<add> class << self
<add> def formula_resources(formula)
<add> specs = [formula.stable, formula.devel, formula.head].compact
<ide>
<del> def formula_resources(formula)
<del> specs = [formula.stable, formula.devel, formula.head].compact
<add> [*formula.bottle&.resource] + specs.flat_map do |spec|
<add> [
<add> spec,
<add> *spec.resources.values,
<add> *spec.patches.select(&:external?).map(&:resource),
<add> ]
<add> end
<add> end
<add> private :formula_resources
<ide>
<del> [*formula.bottle&.resource] + specs.flat_map do |spec|
<del> [
<del> spec,
<del> *spec.resources.values,
<del> *spec.patches.select(&:external?).map(&:resource),
<del> ]
<add> def parse_extname(url)
<add> uri_path = if URI::DEFAULT_PARSER.make_regexp =~ url
<add> uri = URI(url)
<add> uri.query ? "#{uri.path}?#{uri.query}" : uri.path
<add> else
<add> url
<add> end
<add>
<add> # Given a URL like https://example.com/download.php?file=foo-1.0.tar.gz
<add> # the extension we want is ".tar.gz", not ".php".
<add> Pathname.new(uri_path).ascend do |path|
<add> ext = path.extname[/[^?&]+/]
<add> return ext if ext
<add> end
<add>
<add> nil
<ide> end
<del> end
<add> private :parse_extname
<add>
<add> def migrate_cache_entries_to_double_dashes(initial_version)
<add> return if initial_version && initial_version > "1.7.1"
<add>
<add> return if ENV.key?("HOMEBREW_DISABLE_LOAD_FORMULA")
<ide>
<del> def parse_extname(url)
<del> uri_path = if URI::DEFAULT_PARSER.make_regexp =~ url
<del> uri = URI(url)
<del> uri.query ? "#{uri.path}?#{uri.query}" : uri.path
<del> else
<del> url
<add> ohai "Migrating cache entries..."
<add>
<add> Formula.each do |formula|
<add> formula_resources(formula).each do |resource|
<add> downloader = resource.downloader
<add>
<add> url = downloader.url
<add> name = resource.download_name
<add> version = resource.version
<add>
<add> extname = parse_extname(url)
<add> old_location = downloader.cache/"#{name}-#{version}#{extname}"
<add> new_location = downloader.cache/"#{name}--#{version}#{extname}"
<add>
<add> next unless old_location.file?
<add>
<add> if new_location.exist?
<add> begin
<add> FileUtils.rm_rf old_location
<add> rescue Errno::EACCES
<add> opoo "Could not remove #{old_location}, please do so manually."
<add> end
<add> else
<add> begin
<add> FileUtils.mv old_location, new_location
<add> rescue Errno::EACCES
<add> opoo "Could not move #{old_location} to #{new_location}, please do so manually."
<add> end
<add> end
<add> end
<add> end
<ide> end
<ide>
<del> # Given a URL like https://example.com/download.php?file=foo-1.0.tar.gz
<del> # the extension we want is ".tar.gz", not ".php".
<del> Pathname.new(uri_path).ascend do |path|
<del> ext = path.extname[/[^?&]+/]
<del> return ext if ext
<add> def migrate_cache_entries_to_symlinks(initial_version)
<add> return if initial_version && initial_version > "1.7.2"
<add>
<add> return if ENV.key?("HOMEBREW_DISABLE_LOAD_FORMULA")
<add>
<add> ohai "Migrating cache entries..."
<add>
<add> cache_entries = lambda do |path|
<add> if path.directory?
<add> path.children
<add> .reject(&:symlink?)
<add> .select(&:file?)
<add> .map { |child| child.basename.to_s.sub(/\-\-.*/, "") }
<add> .uniq
<add> else
<add> []
<add> end
<add> end
<add>
<add> load_formula = lambda do |formula|
<add> begin
<add> Formula[formula]
<add> rescue FormulaUnavailableError
<add> nil
<add> end
<add> end
<add>
<add> load_cask = lambda do |cask|
<add> begin
<add> Hbc::CaskLoader.load(cask)
<add> rescue Hbc::CaskUnavailableError
<add> nil
<add> end
<add> end
<add>
<add> formula_downloaders =
<add> cache_entries.call(HOMEBREW_CACHE)
<add> .map(&load_formula)
<add> .compact
<add> .flat_map { |formula| formula_resources(formula) }
<add> .map { |resource| [resource.downloader, resource.download_name, resource.version] }
<add>
<add> cask_downloaders =
<add> cache_entries.call(HOMEBREW_CACHE/"Cask")
<add> .map(&load_cask)
<add> .compact
<add> .map { |cask| [Hbc::Download.new(cask).downloader, cask.token, cask.version] }
<add>
<add> downloaders = formula_downloaders + cask_downloaders
<add>
<add> downloaders.each do |downloader, name, version|
<add> next unless downloader.respond_to?(:symlink_location)
<add>
<add> url = downloader.url
<add> extname = parse_extname(url)
<add> old_location = downloader.cache/"#{name}--#{version}#{extname}"
<add> next unless old_location.file?
<add>
<add> new_symlink_location = downloader.symlink_location
<add> new_location = downloader.cached_location
<add>
<add> if new_location.exist? && new_symlink_location.symlink?
<add> begin
<add> FileUtils.rm_rf old_location unless old_location == new_symlink_location
<add> rescue Errno::EACCES
<add> opoo "Could not remove #{old_location}, please do so manually."
<add> end
<add> else
<add> begin
<add> new_location.dirname.mkpath
<add> if new_location.exist?
<add> FileUtils.rm_rf old_location
<add> else
<add> FileUtils.mv old_location, new_location
<add> end
<add> symlink_target = new_location.relative_path_from(new_symlink_location.dirname)
<add> new_symlink_location.dirname.mkpath
<add> FileUtils.ln_s symlink_target, new_symlink_location, force: true
<add> rescue Errno::EACCES
<add> opoo "Could not move #{old_location} to #{new_location}, please do so manually."
<add> end
<add> end
<add> end
<ide> end
<ide>
<del> nil
<add> def migrate_legacy_cache_if_necessary
<add> legacy_cache = Pathname.new "/Library/Caches/Homebrew"
<add> return if HOMEBREW_CACHE.to_s == legacy_cache.to_s
<add> return unless legacy_cache.directory?
<add> return unless legacy_cache.readable_real?
<add>
<add> migration_attempted_file = legacy_cache/".migration_attempted"
<add> return if migration_attempted_file.exist?
<add>
<add> return unless legacy_cache.writable_real?
<add> FileUtils.touch migration_attempted_file
<add>
<add> # This directory could have been compromised if it's world-writable/
<add> # a symlink/owned by another user so don't copy files in those cases.
<add> world_writable = legacy_cache.stat.mode & 0777 == 0777
<add> return if world_writable
<add> return if legacy_cache.symlink?
<add> return if !legacy_cache.owned? && legacy_cache.lstat.uid.nonzero?
<add>
<add> ohai "Migrating #{legacy_cache} to #{HOMEBREW_CACHE}..."
<add> HOMEBREW_CACHE.mkpath
<add> legacy_cache.cd do
<add> legacy_cache.entries.each do |f|
<add> next if [".", "..", ".migration_attempted"].include? f.to_s
<add> begin
<add> FileUtils.cp_r f, HOMEBREW_CACHE
<add> rescue
<add> @migration_failed ||= true
<add> end
<add> end
<add> end
<add>
<add> if @migration_failed
<add> opoo <<~EOS
<add> Failed to migrate #{legacy_cache} to
<add> #{HOMEBREW_CACHE}. Please do so manually.
<add> EOS
<add> else
<add> ohai "Deleting #{legacy_cache}..."
<add> FileUtils.rm_rf legacy_cache
<add> if legacy_cache.exist?
<add> FileUtils.touch migration_attempted_file
<add> opoo <<~EOS
<add> Failed to delete #{legacy_cache}.
<add> Please do so manually.
<add> EOS
<add> end
<add> end
<add> end
<add>
<add> def migrate_legacy_keg_symlinks_if_necessary
<add> legacy_linked_kegs = HOMEBREW_LIBRARY/"LinkedKegs"
<add> return unless legacy_linked_kegs.directory?
<add>
<add> HOMEBREW_LINKED_KEGS.mkpath unless legacy_linked_kegs.children.empty?
<add> legacy_linked_kegs.children.each do |link|
<add> name = link.basename.to_s
<add> src = begin
<add> link.realpath
<add> rescue Errno::ENOENT
<add> begin
<add> (HOMEBREW_PREFIX/"opt/#{name}").realpath
<add> rescue Errno::ENOENT
<add> begin
<add> Formulary.factory(name).installed_prefix
<add> rescue
<add> next
<add> end
<add> end
<add> end
<add> dst = HOMEBREW_LINKED_KEGS/name
<add> dst.unlink if dst.exist?
<add> FileUtils.ln_sf(src.relative_path_from(dst.parent), dst)
<add> end
<add> FileUtils.rm_rf legacy_linked_kegs
<add>
<add> legacy_pinned_kegs = HOMEBREW_LIBRARY/"PinnedKegs"
<add> return unless legacy_pinned_kegs.directory?
<add>
<add> HOMEBREW_PINNED_KEGS.mkpath unless legacy_pinned_kegs.children.empty?
<add> legacy_pinned_kegs.children.each do |link|
<add> name = link.basename.to_s
<add> src = link.realpath
<add> dst = HOMEBREW_PINNED_KEGS/name
<add> FileUtils.ln_sf(src.relative_path_from(dst.parent), dst)
<add> end
<add> FileUtils.rm_rf legacy_pinned_kegs
<add> end
<add>
<add> def migrate_legacy_repository_if_necessary
<add> return unless HOMEBREW_PREFIX.to_s == "/usr/local"
<add> return unless HOMEBREW_REPOSITORY.to_s == "/usr/local"
<add>
<add> ohai "Migrating HOMEBREW_REPOSITORY (please wait)..."
<add>
<add> unless HOMEBREW_PREFIX.writable_real?
<add> ofail <<~EOS
<add> #{HOMEBREW_PREFIX} is not writable.
<add>
<add> You should change the ownership and permissions of #{HOMEBREW_PREFIX}
<add> temporarily back to your user account so we can complete the Homebrew
<add> repository migration:
<add> sudo chown -R $(whoami) #{HOMEBREW_PREFIX}
<add> EOS
<add> return
<add> end
<add>
<add> new_homebrew_repository = Pathname.new "/usr/local/Homebrew"
<add> new_homebrew_repository.rmdir_if_possible
<add> if new_homebrew_repository.exist?
<add> ofail <<~EOS
<add> #{new_homebrew_repository} already exists.
<add> Please remove it manually or uninstall and reinstall Homebrew into a new
<add> location as the migration cannot be done automatically.
<add> EOS
<add> return
<add> end
<add> new_homebrew_repository.mkpath
<add>
<add> repo_files = HOMEBREW_REPOSITORY.cd do
<add> Utils.popen_read("git ls-files").lines.map(&:chomp)
<add> end
<add>
<add> unless Utils.popen_read("git status --untracked-files=all --porcelain").empty?
<add> HOMEBREW_REPOSITORY.cd do
<add> quiet_system "git", "merge", "--abort"
<add> quiet_system "git", "rebase", "--abort"
<add> quiet_system "git", "reset", "--mixed"
<add> safe_system "git", "-c", "user.email=brew-update@localhost",
<add> "-c", "user.name=brew update",
<add> "stash", "save", "--include-untracked"
<add> end
<add> stashed = true
<add> end
<add>
<add> FileUtils.cp_r "#{HOMEBREW_REPOSITORY}/.git", "#{new_homebrew_repository}/.git"
<add> new_homebrew_repository.cd do
<add> safe_system "git", "checkout", "--force", "."
<add> safe_system "git", "stash", "pop" if stashed
<add> end
<add>
<add> if (HOMEBREW_REPOSITORY/"Library/Locks").exist?
<add> FileUtils.cp_r "#{HOMEBREW_REPOSITORY}/Library/Locks", "#{new_homebrew_repository}/Library/Locks"
<add> end
<add>
<add> if (HOMEBREW_REPOSITORY/"Library/Taps").exist?
<add> FileUtils.cp_r "#{HOMEBREW_REPOSITORY}/Library/Taps", "#{new_homebrew_repository}/Library/Taps"
<add> end
<add>
<add> unremovable_paths = []
<add> extra_remove_paths = [
<add> ".git",
<add> "Library/Locks",
<add> "Library/Taps",
<add> "Library/Homebrew/cask",
<add> "Library/Homebrew/test",
<add> ]
<add> (repo_files + extra_remove_paths).each do |file|
<add> path = Pathname.new "#{HOMEBREW_REPOSITORY}/#{file}"
<add> begin
<add> FileUtils.rm_rf path
<add> rescue Errno::EACCES
<add> unremovable_paths << path
<add> end
<add> quiet_system "rmdir", "-p", path.parent if path.parent.exist?
<add> end
<add>
<add> unless unremovable_paths.empty?
<add> ofail <<~EOS
<add> Could not remove old HOMEBREW_REPOSITORY paths!
<add> Please do this manually with:
<add> sudo rm -rf #{unremovable_paths.join " "}
<add> EOS
<add> end
<add>
<add> (Keg::ALL_TOP_LEVEL_DIRECTORIES + ["Cellar"]).each do |dir|
<add> FileUtils.mkdir_p "#{HOMEBREW_PREFIX}/#{dir}"
<add> end
<add>
<add> src = Pathname.new("#{new_homebrew_repository}/bin/brew")
<add> dst = Pathname.new("#{HOMEBREW_PREFIX}/bin/brew")
<add> begin
<add> FileUtils.ln_s(src.relative_path_from(dst.parent), dst)
<add> rescue Errno::EACCES, Errno::ENOENT
<add> ofail <<~EOS
<add> Could not create symlink at #{dst}!
<add> Please do this manually with:
<add> sudo ln -sf #{src} #{dst}
<add> sudo chown $(whoami) #{dst}
<add> EOS
<add> end
<add>
<add> link_completions_manpages_and_docs(new_homebrew_repository)
<add>
<add> ohai "Migrated HOMEBREW_REPOSITORY to #{new_homebrew_repository}!"
<add> puts <<~EOS
<add> Homebrew no longer needs to have ownership of /usr/local. If you wish you can
<add> return /usr/local to its default ownership with:
<add> sudo chown root:wheel #{HOMEBREW_PREFIX}
<add> EOS
<add> rescue => e
<add> ofail <<~EOS
<add> #{Tty.bold}Failed to migrate HOMEBREW_REPOSITORY to #{new_homebrew_repository}!#{Tty.reset}
<add> The error was:
<add> #{e}
<add> Please try to resolve this error yourself and then run `brew update` again to
<add> complete the migration. If you need help please +1 an existing error or comment
<add> with your new error in issue:
<add> #{Formatter.url("https://github.com/Homebrew/brew/issues/987")}
<add> EOS
<add> $stderr.puts e.backtrace
<add> end
<ide> end
<ide> end
<ide><path>Library/Homebrew/update_migrator/cache_entries_to_double_dashes.rb
<del>module UpdateMigrator
<del> module_function
<del>
<del> def migrate_cache_entries_to_double_dashes(initial_version)
<del> return if initial_version && initial_version > "1.7.1"
<del>
<del> return if ENV.key?("HOMEBREW_DISABLE_LOAD_FORMULA")
<del>
<del> ohai "Migrating cache entries..."
<del>
<del> Formula.each do |formula|
<del> formula_resources(formula).each do |resource|
<del> downloader = resource.downloader
<del>
<del> url = downloader.url
<del> name = resource.download_name
<del> version = resource.version
<del>
<del> extname = parse_extname(url)
<del> old_location = downloader.cache/"#{name}-#{version}#{extname}"
<del> new_location = downloader.cache/"#{name}--#{version}#{extname}"
<del>
<del> next unless old_location.file?
<del>
<del> if new_location.exist?
<del> begin
<del> FileUtils.rm_rf old_location
<del> rescue Errno::EACCES
<del> opoo "Could not remove #{old_location}, please do so manually."
<del> end
<del> else
<del> begin
<del> FileUtils.mv old_location, new_location
<del> rescue Errno::EACCES
<del> opoo "Could not move #{old_location} to #{new_location}, please do so manually."
<del> end
<del> end
<del> end
<del> end
<del> end
<del>end
<ide><path>Library/Homebrew/update_migrator/cache_entries_to_symlinks.rb
<del>require "hbc/cask_loader"
<del>require "hbc/download"
<del>
<del>module UpdateMigrator
<del> module_function
<del>
<del> def migrate_cache_entries_to_symlinks(initial_version)
<del> return if initial_version && initial_version > "1.7.2"
<del>
<del> return if ENV.key?("HOMEBREW_DISABLE_LOAD_FORMULA")
<del>
<del> ohai "Migrating cache entries..."
<del>
<del> cache_entries = lambda do |path|
<del> if path.directory?
<del> path.children
<del> .reject(&:symlink?)
<del> .select(&:file?)
<del> .map { |child| child.basename.to_s.sub(/\-\-.*/, "") }
<del> .uniq
<del> else
<del> []
<del> end
<del> end
<del>
<del> load_formula = lambda do |formula|
<del> begin
<del> Formula[formula]
<del> rescue FormulaUnavailableError
<del> nil
<del> end
<del> end
<del>
<del> load_cask = lambda do |cask|
<del> begin
<del> Hbc::CaskLoader.load(cask)
<del> rescue Hbc::CaskUnavailableError
<del> nil
<del> end
<del> end
<del>
<del> formula_downloaders =
<del> cache_entries.call(HOMEBREW_CACHE)
<del> .map(&load_formula)
<del> .compact
<del> .flat_map { |formula| formula_resources(formula) }
<del> .map { |resource| [resource.downloader, resource.download_name, resource.version] }
<del>
<del> cask_downloaders =
<del> cache_entries.call(HOMEBREW_CACHE/"Cask")
<del> .map(&load_cask)
<del> .compact
<del> .map { |cask| [Hbc::Download.new(cask).downloader, cask.token, cask.version] }
<del>
<del> downloaders = formula_downloaders + cask_downloaders
<del>
<del> downloaders.each do |downloader, name, version|
<del> next unless downloader.respond_to?(:symlink_location)
<del>
<del> url = downloader.url
<del> extname = parse_extname(url)
<del> old_location = downloader.cache/"#{name}--#{version}#{extname}"
<del> next unless old_location.file?
<del>
<del> new_symlink_location = downloader.symlink_location
<del> new_location = downloader.cached_location
<del>
<del> if new_location.exist? && new_symlink_location.symlink?
<del> begin
<del> FileUtils.rm_rf old_location unless old_location == new_symlink_location
<del> rescue Errno::EACCES
<del> opoo "Could not remove #{old_location}, please do so manually."
<del> end
<del> else
<del> begin
<del> new_location.dirname.mkpath
<del> if new_location.exist?
<del> FileUtils.rm_rf old_location
<del> else
<del> FileUtils.mv old_location, new_location
<del> end
<del> symlink_target = new_location.relative_path_from(new_symlink_location.dirname)
<del> new_symlink_location.dirname.mkpath
<del> FileUtils.ln_s symlink_target, new_symlink_location, force: true
<del> rescue Errno::EACCES
<del> opoo "Could not move #{old_location} to #{new_location}, please do so manually."
<del> end
<del> end
<del> end
<del> end
<del>end
<ide><path>Library/Homebrew/update_migrator/legacy_cache.rb
<del>module UpdateMigrator
<del> module_function
<del>
<del> def migrate_legacy_cache_if_necessary
<del> legacy_cache = Pathname.new "/Library/Caches/Homebrew"
<del> return if HOMEBREW_CACHE.to_s == legacy_cache.to_s
<del> return unless legacy_cache.directory?
<del> return unless legacy_cache.readable_real?
<del>
<del> migration_attempted_file = legacy_cache/".migration_attempted"
<del> return if migration_attempted_file.exist?
<del>
<del> return unless legacy_cache.writable_real?
<del> FileUtils.touch migration_attempted_file
<del>
<del> # This directory could have been compromised if it's world-writable/
<del> # a symlink/owned by another user so don't copy files in those cases.
<del> world_writable = legacy_cache.stat.mode & 0777 == 0777
<del> return if world_writable
<del> return if legacy_cache.symlink?
<del> return if !legacy_cache.owned? && legacy_cache.lstat.uid.nonzero?
<del>
<del> ohai "Migrating #{legacy_cache} to #{HOMEBREW_CACHE}..."
<del> HOMEBREW_CACHE.mkpath
<del> legacy_cache.cd do
<del> legacy_cache.entries.each do |f|
<del> next if [".", "..", ".migration_attempted"].include? f.to_s
<del> begin
<del> FileUtils.cp_r f, HOMEBREW_CACHE
<del> rescue
<del> @migration_failed ||= true
<del> end
<del> end
<del> end
<del>
<del> if @migration_failed
<del> opoo <<~EOS
<del> Failed to migrate #{legacy_cache} to
<del> #{HOMEBREW_CACHE}. Please do so manually.
<del> EOS
<del> else
<del> ohai "Deleting #{legacy_cache}..."
<del> FileUtils.rm_rf legacy_cache
<del> if legacy_cache.exist?
<del> FileUtils.touch migration_attempted_file
<del> opoo <<~EOS
<del> Failed to delete #{legacy_cache}.
<del> Please do so manually.
<del> EOS
<del> end
<del> end
<del> end
<del>end
<ide><path>Library/Homebrew/update_migrator/legacy_keg_symlinks.rb
<del>module UpdateMigrator
<del> module_function
<del>
<del> def migrate_legacy_keg_symlinks_if_necessary
<del> legacy_linked_kegs = HOMEBREW_LIBRARY/"LinkedKegs"
<del> return unless legacy_linked_kegs.directory?
<del>
<del> HOMEBREW_LINKED_KEGS.mkpath unless legacy_linked_kegs.children.empty?
<del> legacy_linked_kegs.children.each do |link|
<del> name = link.basename.to_s
<del> src = begin
<del> link.realpath
<del> rescue Errno::ENOENT
<del> begin
<del> (HOMEBREW_PREFIX/"opt/#{name}").realpath
<del> rescue Errno::ENOENT
<del> begin
<del> Formulary.factory(name).installed_prefix
<del> rescue
<del> next
<del> end
<del> end
<del> end
<del> dst = HOMEBREW_LINKED_KEGS/name
<del> dst.unlink if dst.exist?
<del> FileUtils.ln_sf(src.relative_path_from(dst.parent), dst)
<del> end
<del> FileUtils.rm_rf legacy_linked_kegs
<del>
<del> legacy_pinned_kegs = HOMEBREW_LIBRARY/"PinnedKegs"
<del> return unless legacy_pinned_kegs.directory?
<del>
<del> HOMEBREW_PINNED_KEGS.mkpath unless legacy_pinned_kegs.children.empty?
<del> legacy_pinned_kegs.children.each do |link|
<del> name = link.basename.to_s
<del> src = link.realpath
<del> dst = HOMEBREW_PINNED_KEGS/name
<del> FileUtils.ln_sf(src.relative_path_from(dst.parent), dst)
<del> end
<del> FileUtils.rm_rf legacy_pinned_kegs
<del> end
<del>end
<ide><path>Library/Homebrew/update_migrator/legacy_repository.rb
<del>module UpdateMigrator
<del> module_function
<del>
<del> def migrate_legacy_repository_if_necessary
<del> return unless HOMEBREW_PREFIX.to_s == "/usr/local"
<del> return unless HOMEBREW_REPOSITORY.to_s == "/usr/local"
<del>
<del> ohai "Migrating HOMEBREW_REPOSITORY (please wait)..."
<del>
<del> unless HOMEBREW_PREFIX.writable_real?
<del> ofail <<~EOS
<del> #{HOMEBREW_PREFIX} is not writable.
<del>
<del> You should change the ownership and permissions of #{HOMEBREW_PREFIX}
<del> temporarily back to your user account so we can complete the Homebrew
<del> repository migration:
<del> sudo chown -R $(whoami) #{HOMEBREW_PREFIX}
<del> EOS
<del> return
<del> end
<del>
<del> new_homebrew_repository = Pathname.new "/usr/local/Homebrew"
<del> new_homebrew_repository.rmdir_if_possible
<del> if new_homebrew_repository.exist?
<del> ofail <<~EOS
<del> #{new_homebrew_repository} already exists.
<del> Please remove it manually or uninstall and reinstall Homebrew into a new
<del> location as the migration cannot be done automatically.
<del> EOS
<del> return
<del> end
<del> new_homebrew_repository.mkpath
<del>
<del> repo_files = HOMEBREW_REPOSITORY.cd do
<del> Utils.popen_read("git ls-files").lines.map(&:chomp)
<del> end
<del>
<del> unless Utils.popen_read("git status --untracked-files=all --porcelain").empty?
<del> HOMEBREW_REPOSITORY.cd do
<del> quiet_system "git", "merge", "--abort"
<del> quiet_system "git", "rebase", "--abort"
<del> quiet_system "git", "reset", "--mixed"
<del> safe_system "git", "-c", "user.email=brew-update@localhost",
<del> "-c", "user.name=brew update",
<del> "stash", "save", "--include-untracked"
<del> end
<del> stashed = true
<del> end
<del>
<del> FileUtils.cp_r "#{HOMEBREW_REPOSITORY}/.git", "#{new_homebrew_repository}/.git"
<del> new_homebrew_repository.cd do
<del> safe_system "git", "checkout", "--force", "."
<del> safe_system "git", "stash", "pop" if stashed
<del> end
<del>
<del> if (HOMEBREW_REPOSITORY/"Library/Locks").exist?
<del> FileUtils.cp_r "#{HOMEBREW_REPOSITORY}/Library/Locks", "#{new_homebrew_repository}/Library/Locks"
<del> end
<del>
<del> if (HOMEBREW_REPOSITORY/"Library/Taps").exist?
<del> FileUtils.cp_r "#{HOMEBREW_REPOSITORY}/Library/Taps", "#{new_homebrew_repository}/Library/Taps"
<del> end
<del>
<del> unremovable_paths = []
<del> extra_remove_paths = [".git", "Library/Locks", "Library/Taps",
<del> "Library/Homebrew/cask", "Library/Homebrew/test"]
<del> (repo_files + extra_remove_paths).each do |file|
<del> path = Pathname.new "#{HOMEBREW_REPOSITORY}/#{file}"
<del> begin
<del> FileUtils.rm_rf path
<del> rescue Errno::EACCES
<del> unremovable_paths << path
<del> end
<del> quiet_system "rmdir", "-p", path.parent if path.parent.exist?
<del> end
<del>
<del> unless unremovable_paths.empty?
<del> ofail <<~EOS
<del> Could not remove old HOMEBREW_REPOSITORY paths!
<del> Please do this manually with:
<del> sudo rm -rf #{unremovable_paths.join " "}
<del> EOS
<del> end
<del>
<del> (Keg::ALL_TOP_LEVEL_DIRECTORIES + ["Cellar"]).each do |dir|
<del> FileUtils.mkdir_p "#{HOMEBREW_PREFIX}/#{dir}"
<del> end
<del>
<del> src = Pathname.new("#{new_homebrew_repository}/bin/brew")
<del> dst = Pathname.new("#{HOMEBREW_PREFIX}/bin/brew")
<del> begin
<del> FileUtils.ln_s(src.relative_path_from(dst.parent), dst)
<del> rescue Errno::EACCES, Errno::ENOENT
<del> ofail <<~EOS
<del> Could not create symlink at #{dst}!
<del> Please do this manually with:
<del> sudo ln -sf #{src} #{dst}
<del> sudo chown $(whoami) #{dst}
<del> EOS
<del> end
<del>
<del> link_completions_manpages_and_docs(new_homebrew_repository)
<del>
<del> ohai "Migrated HOMEBREW_REPOSITORY to #{new_homebrew_repository}!"
<del> puts <<~EOS
<del> Homebrew no longer needs to have ownership of /usr/local. If you wish you can
<del> return /usr/local to its default ownership with:
<del> sudo chown root:wheel #{HOMEBREW_PREFIX}
<del> EOS
<del> rescue => e
<del> ofail <<~EOS
<del> #{Tty.bold}Failed to migrate HOMEBREW_REPOSITORY to #{new_homebrew_repository}!#{Tty.reset}
<del> The error was:
<del> #{e}
<del> Please try to resolve this error yourself and then run `brew update` again to
<del> complete the migration. If you need help please +1 an existing error or comment
<del> with your new error in issue:
<del> #{Formatter.url("https://github.com/Homebrew/brew/issues/987")}
<del> EOS
<del> $stderr.puts e.backtrace
<del> end
<del>end | 6 |
Javascript | Javascript | add destroyed method back to coreobject | 06b851a09e42c7f73949547b057b732481e09628 | <ide><path>packages/sproutcore-metal/lib/system/core_object.js
<ide> require('sproutcore-metal/system/mixin');
<ide>
<ide> var rewatch = SC.rewatch;
<ide> var classToString = SC.Mixin.prototype.toString;
<add>var set = SC.set, get = SC.get;
<ide>
<ide> function makeCtor() {
<ide>
<ide> Object.PrototypeMixin = SC.Mixin.create({
<ide>
<ide> init: function() {},
<ide>
<add> isDestroyed: false,
<add>
<add> destroy: function() {
<add> set(this, 'isDestroyed', true);
<add> return this;
<add> },
<add>
<ide> bind: function(to, from) {
<ide> if (!(from instanceof SC.Binding)) from = SC.Binding.from(from);
<ide> from.to(to).connect(this); | 1 |
PHP | PHP | fix old code in auth test cases | 86013f1b849045f845a2e9115553401b99f67879 | <ide><path>laravel/tests/cases/auth.test.php
<ide> public function testUserMethodReturnsNullWhenNoUserExistsAndNoRecallerExists()
<ide> public function testUserReturnsUserByID()
<ide> {
<ide> Session::$instance = new Payload($this->getMock('Laravel\\Session\\Drivers\\Driver'));
<del> Session::$instance->session['data'][Auth::user_key] = 1;
<add> // FIXME: Not sure whether hard-coding the key is a good idea.
<add> Session::$instance->session['data']['laravel_auth_drivers_fluent_login'] = 1;
<ide>
<ide> $this->assertEquals('Taylor Otwell', Auth::user()->name);
<ide> }
<ide> public function testUserReturnsUserByID()
<ide> public function testNullReturnedWhenUserIDNotValidInteger()
<ide> {
<ide> Session::$instance = new Payload($this->getMock('Laravel\\Session\\Drivers\\Driver'));
<del> Session::$instance->session['data'][Auth::user_key] = 'asdlkasd';
<add> // FIXME: Not sure whether hard-coding the key is a good idea.
<add> Session::$instance->session['data']['laravel_auth_drivers_fluent_login'] = 'asdlkasd';
<ide>
<ide> $this->assertNull(Auth::user());
<ide> }
<ide> public function testLoginMethodStoresUserKeyInSession()
<ide> $user = new StdClass;
<ide> $user->id = 10;
<ide> Auth::login($user);
<del> $this->assertEquals(10, Session::$instance->session['data'][Auth::user_key]);
<add> // FIXME: Not sure whether hard-coding the key is a good idea.
<add> $user = Session::$instance->session['data']['laravel_auth_drivers_fluent_login'];
<add> $this->assertEquals(10, $user->id);
<ide>
<ide> Auth::login(5);
<del> $this->assertEquals(5, Session::$instance->session['data'][Auth::user_key]);
<add> $user = Session::$instance->session['data']['laravel_auth_drivers_fluent_login'];
<add> $this->assertEquals(5, $user);
<ide> }
<ide>
<ide> /**
<ide> public function testLoginStoresRememberCookieWhenNeeded()
<ide> Config::set('session.domain', 'bar');
<ide> Config::set('session.secure', true);
<ide>
<del> Auth::login(10, true);
<add> Auth::login(10);
<ide> $this->assertTrue(isset(Cookie::$jar[Config::get('auth.cookie')]));
<ide>
<ide> $cookie = Cookie::$jar[Config::get('auth.cookie')]['value'];
<ide> public function testLoginStoresRememberCookieWhenNeeded()
<ide> public function testLogoutMethodLogsOutUser()
<ide> {
<ide> Session::$instance = new Payload($this->getMock('Laravel\\Session\\Drivers\\Driver'));
<del> Session::$instance->session['data'][Auth::user_key] = 10;
<add>
<add> //$data = Session::$instance->session['data']['laravel_auth_drivers_fluent_login'] = 10;
<ide>
<del> Config::set('auth.logout', function($user) { $_SERVER['auth.logout.stub'] = $user; });
<add> // FIXME: Restore some of these!
<add> //Config::set('auth.logout', function($user) { $_SERVER['auth.logout.stub'] = $user; });
<ide>
<del> Auth::$user = 'Taylor';
<add> //Auth::$user = 'Taylor';
<ide> Auth::logout();
<ide>
<del> $this->assertEquals('Taylor', $_SERVER['auth.logout.stub']);
<del> $this->assertNull(Auth::$user);
<del> $this->assertFalse(isset(Session::$instance->session['data'][Auth::user_key]));
<del> $this->assertTrue(Cookie::$jar[Config::get('auth.cookie')]['minutes'] < 0);
<add> //$this->assertEquals('Taylor', $_SERVER['auth.logout.stub']);
<add> $this->assertNull(Auth::user());
<add> // FIXME: Not sure whether hard-coding the key is a good idea.
<add> $this->assertFalse(isset(Session::$instance->session['data']['laravel_auth_drivers_fluent_login']));
<add> $this->assertTrue(Cookie::$jar['laravel_auth_drivers_fluent_remember']['expiration'] < time());
<ide> }
<ide>
<ide> } | 1 |
Python | Python | fix flaky test | 7f3cd093c096c03d9710940dc5cd700c2b7142a6 | <ide><path>tests/integration_tests/test_image_data_tasks.py
<ide> def test_image_classification():
<ide> history = model.fit(X_train, y_train, nb_epoch=10, batch_size=16,
<ide> validation_data=(X_test, y_test),
<ide> show_accuracy=True, verbose=0)
<del> assert(history.history['val_acc'][-1] > 0.9)
<add> assert(history.history['val_acc'][-1] > 0.85)
<ide>
<ide>
<ide> if __name__ == '__main__': | 1 |
Text | Text | add license badge | 4f189ec80ce01a0275d87d24463ef12b16715d9b | <ide><path>README.md
<ide> [](http://npm-stat.com/charts.html?package=axios)
<ide> [](https://gitter.im/mzabriskie/axios)
<ide> [](https://www.codetriage.com/axios/axios)
<add>
<ide>
<ide> Promise based HTTP client for the browser and node.js
<ide> | 1 |
Javascript | Javascript | remove obsolete code | 3732d7786bcb5722b9a4345e1345ff5ad81a7888 | <ide><path>test/parallel/test-repl-tab-complete-no-warn.js
<ide> const testMe = repl.start('', putIn);
<ide> // `Runtime.executionContextCreated` listener
<ide> process.on('warning', common.mustNotCall());
<ide>
<del>putIn.run(['.clear']);
<ide> putIn.run(['async function test() {']);
<ide> for (let i = 0; i < DEFAULT_MAX_LISTENERS; i++) {
<ide> testMe.complete('await Promise.resolve()', () => {}); | 1 |
Python | Python | add circle sort implementation | e1e7922efac2b7fdfab7555baaf784edb345c222 | <ide><path>sorts/circle_sort.py
<add>"""
<add>This is a Python implementation of the circle sort algorithm
<add>
<add>For doctests run following command:
<add>python3 -m doctest -v circle_sort.py
<add>
<add>For manual testing run:
<add>python3 circle_sort.py
<add>"""
<add>
<add>
<add>def circle_sort(collection: list) -> list:
<add> """A pure Python implementation of circle sort algorithm
<add>
<add> :param collection: a mutable collection of comparable items in any order
<add> :return: the same collection in ascending order
<add>
<add> Examples:
<add> >>> circle_sort([0, 5, 3, 2, 2])
<add> [0, 2, 2, 3, 5]
<add> >>> circle_sort([])
<add> []
<add> >>> circle_sort([-2, 5, 0, -45])
<add> [-45, -2, 0, 5]
<add> >>> collections = ([], [0, 5, 3, 2, 2], [-2, 5, 0, -45])
<add> >>> all(sorted(collection) == circle_sort(collection) for collection in collections)
<add> True
<add> """
<add>
<add> if len(collection) < 2:
<add> return collection
<add>
<add> def circle_sort_util(collection: list, low: int, high: int) -> bool:
<add> """
<add> >>> arr = [5,4,3,2,1]
<add> >>> circle_sort_util(lst, 0, 2)
<add> True
<add> >>> arr
<add> [3, 4, 5, 2, 1]
<add> """
<add>
<add> swapped = False
<add>
<add> if low == high:
<add> return swapped
<add>
<add> left = low
<add> right = high
<add>
<add> while left < right:
<add> if collection[left] > collection[right]:
<add> collection[left], collection[right] = (
<add> collection[right],
<add> collection[left],
<add> )
<add> swapped = True
<add>
<add> left += 1
<add> right -= 1
<add>
<add> if left == right:
<add> if collection[left] > collection[right + 1]:
<add> collection[left], collection[right + 1] = (
<add> collection[right + 1],
<add> collection[left],
<add> )
<add>
<add> swapped = True
<add>
<add> mid = low + int((high - low) / 2)
<add> left_swap = circle_sort_util(collection, low, mid)
<add> right_swap = circle_sort_util(collection, mid + 1, high)
<add>
<add> return swapped or left_swap or right_swap
<add>
<add> is_not_sorted = True
<add>
<add> while is_not_sorted is True:
<add> is_not_sorted = circle_sort_util(collection, 0, len(collection) - 1)
<add>
<add> return collection
<add>
<add>
<add>if __name__ == "__main__":
<add> user_input = input("Enter numbers separated by a comma:\n").strip()
<add> unsorted = [int(item) for item in user_input.split(",")]
<add> print(circle_sort(unsorted)) | 1 |
PHP | PHP | avoid duplication in returned results for habtm | fb0053753e2629b3553fbaa1ba04b0eb78585467 | <ide><path>lib/Cake/Model/Model.php
<ide> public function save($data = null, $validate = true, $fieldList = array()) {
<ide> $this->getEventManager()->dispatch($event);
<ide> }
<ide> if (!empty($this->data)) {
<del> $success = Hash::merge($success, $this->data);
<add> $success = array_merge($success, $this->data);
<ide> }
<ide> $this->data = false;
<ide> $this->_clearCache();
<ide><path>lib/Cake/Test/Case/Model/ModelWriteTest.php
<ide> public function testSaveHabtm() {
<ide> $this->assertFalse(empty($result));
<ide> $result = $TestModel->save();
<ide> $this->assertFalse(empty($result));
<add> $this->assertEquals($data['Tag'], $result['Tag']);
<ide>
<ide> $TestModel->unbindModel(array('belongsTo' => array('User'), 'hasMany' => array('Comment')));
<ide> $result = $TestModel->find('first', array('fields' => array('id', 'user_id', 'title', 'body'), 'conditions' => array('Article.id' => 2))); | 2 |
Javascript | Javascript | solve hoisting in vector3 | 979f99d21b688253cab8b6e69f4816febe64fd91 | <ide><path>src/math/Vector3.js
<ide> import { MathUtils } from './MathUtils.js';
<ide> import { Quaternion } from './Quaternion.js';
<ide>
<del>const _vector = new Vector3();
<add>let _vector;
<ide> const _quaternion = new Quaternion();
<ide>
<ide> class Vector3 {
<ide> class Vector3 {
<ide>
<ide> }
<ide>
<del>};
<add>}
<add>
<add>_vector = new Vector3();
<ide>
<ide> export { Vector3 };
<ide><path>src/math/Vector4.js
<ide> class Vector4 {
<ide>
<ide> }
<ide>
<del>};
<add>}
<ide>
<ide> export { Vector4 }; | 2 |
Ruby | Ruby | replace class attribute with set constant | b1dcfa782e64859f9d03b6cf9474506ac5129337 | <ide><path>actionview/lib/action_view/template/types.rb
<ide> module ActionView
<ide> class Template
<ide> class Types
<ide> class Type
<del> cattr_accessor :types
<del> self.types = Set.new([ :html, :text, :js, :css, :xml, :json ])
<add> SET = Set.new([ :html, :text, :js, :css, :xml, :json ])
<ide>
<ide> def self.[](type)
<ide> return type if type.is_a?(self)
<ide>
<del> if type.is_a?(Symbol) || types.member?(type.to_s)
<add> if type.is_a?(Symbol) || SET.member?(type.to_s)
<ide> new(type)
<ide> end
<ide> end | 1 |
Text | Text | fix a3c wrong readme.md | 01a51ee2f3d54288b298fb3375089b9315e85243 | <ide><path>research/a3c_blogpost/README.md
<ide> In order to run this code, you will need the following prerequisites:
<ide>
<ide> * [OpenAI Gym](https://github.com/openai/gym) - `pip install gym`
<ide> * [pyglet](https://bitbucket.org/pyglet/pyglet/wiki/Home) - `pip install pyglet`
<del>* [TensorFlow](https://www.tensorflow.org/install/) - `pip install tensorflow`
<add>* [TensorFlow](https://www.tensorflow.org/install/) - `pip install tensorflow==v1.14.0` | 1 |
Ruby | Ruby | fix incorrect word | 9bbbae06c57da6a25c70e54877c4867310131db9 | <ide><path>activesupport/lib/active_support/log_subscriber/test_helper.rb
<ide> class LogSubscriber
<ide> # up the queue, subscriptions and turning colors in logs off.
<ide> #
<ide> # The messages are available in the @logger instance, which is a logger with limited
<del> # powers (it actually do not send anything to your output), and you can collect them
<add> # powers (it actually does not send anything to your output), and you can collect them
<ide> # doing @logger.logged(level), where level is the level used in logging, like info,
<ide> # debug, warn and so on.
<ide> # | 1 |
Ruby | Ruby | fix rubocop warnings | 51bda9c90efe3c3fbc197b6c1db793575444a711 | <ide><path>Library/Homebrew/dev-cmd/test-bot.rb
<ide> def resolve_test_tap
<ide>
<ide> if git_url = ENV["UPSTREAM_GIT_URL"] || ENV["GIT_URL"]
<ide> # Also can get tap from Jenkins GIT_URL.
<del> url_path = git_url.sub(%r{^https?://github\.com/}, "").chomp("/").sub(%r{\.git$}, "")
<add> url_path = git_url.sub(%r{^https?://github\.com/}, "").chomp("/").sub(/\.git$/, "")
<ide> begin
<ide> return Tap.fetch(url_path) if url_path =~ HOMEBREW_TAP_REGEX
<ide> rescue
<ide> def puts_result
<ide> puts "#{Tty.white}==>#{Tty.red} FAILED#{Tty.reset}" if failed?
<ide> end
<ide>
<del> def has_output?
<add> def output?
<ide> @output && !@output.empty?
<ide> end
<ide>
<ide> def run
<ide> @status = $?.success? ? :passed : :failed
<ide> puts_result
<ide>
<del>
<ide> unless output.empty?
<ide> @output = Homebrew.fix_encoding!(output)
<ide> puts @output if (failed? || @puts_output_on_success) && !verbose
<ide> def run
<ide> class Test
<ide> attr_reader :log_root, :category, :name, :steps
<ide>
<del> def initialize(argument, options={})
<add> def initialize(argument, options = {})
<ide> @hash = nil
<ide> @url = nil
<ide> @formulae = []
<ide> def initialize(argument, options={})
<ide> elsif canonical_formula_name = safe_formula_canonical_name(argument)
<ide> @formulae = [canonical_formula_name]
<ide> else
<del> raise ArgumentError.new("#{argument} is not a pull request URL, commit URL or formula name.")
<add> raise ArgumentError, "#{argument} is not a pull request URL, commit URL or formula name."
<ide> end
<ide>
<ide> @category = __method__
<ide> def diff_formulae(start_revision, end_revision, path, filter)
<ide> @short_url = @url.gsub("https://github.com/", "")
<ide> if @short_url.include? "/commit/"
<ide> # 7 characters should be enough for a commit (not 40).
<del> @short_url.gsub!(/(commit\/\w{7}).*/, '\1')
<add> @short_url.gsub!(%r{(commit/\w{7}).*/, '\1'})
<ide> @name = @short_url
<ide> else
<ide> @name = "#{@short_url}-#{diff_end_sha1}"
<ide> def formula(formula_name)
<ide> dependents -= @formulae
<ide> dependents = dependents.map { |d| Formulary.factory(d) }
<ide>
<del> bottled_dependents = dependents.select { |d| d.bottled? }
<add> bottled_dependents = dependents.select(&:bottled?)
<ide> testable_dependents = dependents.select { |d| d.bottled? && d.test_defined? }
<ide>
<ide> if (deps | reqs).any? { |d| d.name == "mercurial" && d.build? }
<ide> def formula(formula_name)
<ide> bottle_args << "--skip-relocation" if ARGV.include? "--skip-relocation"
<ide> test "brew", "bottle", *bottle_args
<ide> bottle_step = steps.last
<del> if bottle_step.passed? && bottle_step.has_output?
<add> if bottle_step.passed? && bottle_step.output?
<ide> bottle_filename =
<del> bottle_step.output.gsub(/.*(\.\/\S+#{Utils::Bottles::native_regex}).*/m, '\1')
<add> bottle_step.output.gsub(%r{.*(\./\S+#{Utils::Bottles.native_regex}).*/m, '\1'})
<ide> bottle_json_filename = bottle_filename.gsub(/\.(\d+\.)?tar\.gz$/, ".json")
<ide> bottle_merge_args = ["--merge", "--write", "--no-commit", bottle_json_filename]
<ide> bottle_merge_args << "--keep-old" if ARGV.include? "--keep-old"
<ide> def formula(formula_name)
<ide> next if steps.last.failed?
<ide> end
<ide> end
<del> if dependent.installed?
<del> test "brew", "linkage", "--test", dependent.name
<del> if testable_dependents.include? dependent
<del> test "brew", "test", "--verbose", dependent.name
<del> end
<add> next unless dependent.installed?
<add> test "brew", "linkage", "--test", dependent.name
<add> if testable_dependents.include? dependent
<add> test "brew", "test", "--verbose", dependent.name
<ide> end
<ide> end
<ide> test "brew", "uninstall", "--force", formula_name
<ide> def cleanup_after
<ide> end
<ide>
<ide> def test(*args)
<del> options = Hash === args.last ? args.pop : {}
<add> options = args.last.is_a?(Hash) ? args.pop : {}
<ide> options[:repository] = @repository
<ide> step = Step.new self, args, options
<ide> step.run
<ide> def test_ci_upload(tap)
<ide> bintray_repo = bottle_hash["bintray"]["repository"]
<ide> bintray_repo_url = "https://api.bintray.com/packages/homebrew/#{bintray_repo}"
<ide>
<del> bottle_hash["bottle"]["tags"].each do |tag, tag_hash|
<add> bottle_hash["bottle"]["tags"].each do |_tag, tag_hash|
<ide> filename = tag_hash["filename"]
<ide> if system "curl", "-I", "--silent", "--fail", "--output", "/dev/null",
<ide> "#{BottleSpecification::DEFAULT_DOMAIN}/#{bintray_repo}/#{filename}"
<ide> def test_ci_upload(tap)
<ide> safe_system "git", "push", "--force", remote, "master:master", "refs/tags/#{git_tag}"
<ide> end
<ide>
<del> def sanitize_ARGV_and_ENV
<add> def sanitize_argv_and_env
<ide> if Pathname.pwd == HOMEBREW_PREFIX && ARGV.include?("--cleanup")
<ide> odie "cannot use --cleanup from HOMEBREW_PREFIX as it will delete all output."
<ide> end
<ide> def sanitize_ARGV_and_ENV
<ide> end
<ide>
<ide> def test_bot
<del> sanitize_ARGV_and_ENV
<add> sanitize_argv_and_env
<ide>
<ide> tap = resolve_test_tap
<ide> # Tap repository if required, this is done before everything else
<ide> def test_bot
<ide> testcase.add_attribute "status", step.status
<ide> testcase.add_attribute "time", step.time
<ide>
<del> if step.has_output?
<del> output = sanitize_output_for_xml(step.output)
<del> cdata = REXML::CData.new output
<add> next unless step.output?
<add> output = sanitize_output_for_xml(step.output)
<add> cdata = REXML::CData.new output
<ide>
<del> if step.passed?
<del> elem = testcase.add_element "system-out"
<del> else
<del> elem = testcase.add_element "failure"
<del> elem.add_attribute "message", "#{step.status}: #{step.command.join(" ")}"
<del> end
<del>
<del> elem << cdata
<add> if step.passed?
<add> elem = testcase.add_element "system-out"
<add> else
<add> elem = testcase.add_element "failure"
<add> elem.add_attribute "message", "#{step.status}: #{step.command.join(" ")}"
<ide> end
<add>
<add> elem << cdata
<ide> end
<ide> end
<ide> | 1 |
Javascript | Javascript | remove old references to node.loadingmodules | a0c464638c3b04e22b38358b0526308b8dcd1c63 | <ide><path>src/node.js
<ide> node.Module.prototype.loadScript = function (loadPromise) {
<ide> // remove shebang
<ide> content = content.replace(/^\#\!.*/, '');
<ide>
<del> node.loadingModules = [];
<del>
<ide> function requireAsync (url) {
<ide> return self.newChild(url, {});
<ide> }
<ide> node.Module.prototype.loadScript = function (loadPromise) {
<ide> var wrapper = "function (__filename, exports, require) { " + content + "\n};";
<ide> var compiled_wrapper = node.compile(wrapper, self.filename);
<ide>
<del> node.loadingModules.unshift(self);
<ide> compiled_wrapper.apply(self.target, [self.filename, self.target, require]);
<del> node.loadingModules.shift();
<ide>
<ide> self.waitChildrenLoad(function () {
<ide> self.loaded = true; | 1 |
Python | Python | add nvtx ranges to `trainablepipe` components | eaf66e74314cf5262cee0f41a42c36dc39fc0975 | <ide><path>spacy/errors.py
<ide> class Warnings(metaclass=ErrorsWithCodes):
<ide> "Only the last span group will be loaded under "
<ide> "Doc.spans['{group_name}']. Skipping span group with values: "
<ide> "{group_values}")
<add> W121 = ("Attempting to trace non-existent method '{method}' in pipe '{pipe}'")
<add> W122 = ("Couldn't trace method '{method}' in pipe '{pipe}'. This can happen if the pipe class "
<add> "is a Cython extension type.")
<ide>
<ide>
<ide> class Errors(metaclass=ErrorsWithCodes):
<ide><path>spacy/ml/callbacks.py
<del>from functools import partial
<del>from typing import Type, Callable, TYPE_CHECKING
<add>from typing import Type, Callable, Dict, TYPE_CHECKING, List, Optional, Set
<add>import functools
<add>import inspect
<add>import types
<add>import warnings
<ide>
<ide> from thinc.layers import with_nvtx_range
<ide> from thinc.model import Model, wrap_model_recursive
<add>from thinc.util import use_nvtx_range
<ide>
<add>from ..errors import Warnings
<ide> from ..util import registry
<ide>
<ide> if TYPE_CHECKING:
<ide> # This lets us add type hints for mypy etc. without causing circular imports
<ide> from ..language import Language # noqa: F401
<ide>
<ide>
<add>DEFAULT_NVTX_ANNOTATABLE_PIPE_METHODS = [
<add> "pipe",
<add> "predict",
<add> "set_annotations",
<add> "update",
<add> "rehearse",
<add> "get_loss",
<add> "initialize",
<add> "begin_update",
<add> "finish_update",
<add> "update",
<add>]
<add>
<add>
<add>def models_with_nvtx_range(nlp, forward_color: int, backprop_color: int):
<add> pipes = [
<add> pipe
<add> for _, pipe in nlp.components
<add> if hasattr(pipe, "is_trainable") and pipe.is_trainable
<add> ]
<add>
<add> seen_models: Set[int] = set()
<add> for pipe in pipes:
<add> for node in pipe.model.walk():
<add> if id(node) in seen_models:
<add> continue
<add> seen_models.add(id(node))
<add> with_nvtx_range(
<add> node, forward_color=forward_color, backprop_color=backprop_color
<add> )
<add>
<add> return nlp
<add>
<add>
<ide> @registry.callbacks("spacy.models_with_nvtx_range.v1")
<ide> def create_models_with_nvtx_range(
<ide> forward_color: int = -1, backprop_color: int = -1
<ide> ) -> Callable[["Language"], "Language"]:
<del> def models_with_nvtx_range(nlp):
<del> pipes = [
<del> pipe
<del> for _, pipe in nlp.components
<del> if hasattr(pipe, "is_trainable") and pipe.is_trainable
<del> ]
<del>
<del> # We need process all models jointly to avoid wrapping callbacks twice.
<del> models = Model(
<del> "wrap_with_nvtx_range",
<del> forward=lambda model, X, is_train: ...,
<del> layers=[pipe.model for pipe in pipes],
<del> )
<del>
<del> for node in models.walk():
<del> with_nvtx_range(
<del> node, forward_color=forward_color, backprop_color=backprop_color
<add> return functools.partial(
<add> models_with_nvtx_range,
<add> forward_color=forward_color,
<add> backprop_color=backprop_color,
<add> )
<add>
<add>
<add>def nvtx_range_wrapper_for_pipe_method(self, func, *args, **kwargs):
<add> if isinstance(func, functools.partial):
<add> return func(*args, **kwargs)
<add> else:
<add> with use_nvtx_range(f"{self.name} {func.__name__}"):
<add> return func(*args, **kwargs)
<add>
<add>
<add>def pipes_with_nvtx_range(
<add> nlp, additional_pipe_functions: Optional[Dict[str, List[str]]]
<add>):
<add> for _, pipe in nlp.components:
<add> if additional_pipe_functions:
<add> extra_funcs = additional_pipe_functions.get(pipe.name, [])
<add> else:
<add> extra_funcs = []
<add>
<add> for name in DEFAULT_NVTX_ANNOTATABLE_PIPE_METHODS + extra_funcs:
<add> func = getattr(pipe, name, None)
<add> if func is None:
<add> if name in extra_funcs:
<add> warnings.warn(Warnings.W121.format(method=name, pipe=pipe.name))
<add> continue
<add>
<add> wrapped_func = functools.partial(
<add> types.MethodType(nvtx_range_wrapper_for_pipe_method, pipe), func
<ide> )
<ide>
<add> # Try to preserve the original function signature.
<add> try:
<add> wrapped_func.__signature__ = inspect.signature(func) # type: ignore
<add> except:
<add> pass
<add>
<add> try:
<add> setattr(
<add> pipe,
<add> name,
<add> wrapped_func,
<add> )
<add> except AttributeError:
<add> warnings.warn(Warnings.W122.format(method=name, pipe=pipe.name))
<add>
<add> return nlp
<add>
<add>
<add>@registry.callbacks("spacy.models_and_pipes_with_nvtx_range.v1")
<add>def create_models_and_pipes_with_nvtx_range(
<add> forward_color: int = -1,
<add> backprop_color: int = -1,
<add> additional_pipe_functions: Optional[Dict[str, List[str]]] = None,
<add>) -> Callable[["Language"], "Language"]:
<add> def inner(nlp):
<add> nlp = models_with_nvtx_range(nlp, forward_color, backprop_color)
<add> nlp = pipes_with_nvtx_range(nlp, additional_pipe_functions)
<ide> return nlp
<ide>
<del> return models_with_nvtx_range
<add> return inner | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.