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 |
|---|---|---|---|---|---|
Ruby | Ruby | remove conditional adding a new method | 863ea1b82691b5d10ff189fef162b9f760423ed6 | <ide><path>activerecord/lib/active_record/aggregations.rb
<ide> def composed_of(part_id, options = {})
<ide> writer_method(name, class_name, mapping, allow_nil, converter)
<ide>
<ide> reflection = ActiveRecord::Reflection.create(:composed_of, part_id, nil, options, self)
<del> Reflection.add_reflection self, part_id, reflection
<add> Reflection.add_aggregate_reflection self, part_id, reflection
<ide> end
<ide>
<ide> private
<ide><path>activerecord/lib/active_record/reflection.rb
<ide> def self.create(macro, name, scope, options, ar)
<ide> end
<ide>
<ide> def self.add_reflection(ar, name, reflection)
<del> if reflection.class == AggregateReflection
<del> ar.aggregate_reflections = ar.aggregate_reflections.merge(name => reflection)
<del> else
<del> ar.reflections = ar.reflections.merge(name => reflection)
<del> end
<add> ar.reflections = ar.reflections.merge(name => reflection)
<add> end
<add>
<add> def self.add_aggregate_reflection(ar, name, reflection)
<add> ar.aggregate_reflections = ar.aggregate_reflections.merge(name => reflection)
<ide> end
<ide>
<ide> # \Reflection enables to interrogate Active Record classes and objects | 2 |
Go | Go | add unlock key rotation | a6030a50c95cd4e8b39b5f4d5705bb23ebdb28c5 | <ide><path>api/server/router/swarm/cluster_routes.go
<ide> func (sr *swarmRouter) updateCluster(ctx context.Context, w http.ResponseWriter,
<ide> flags.RotateManagerToken = rot
<ide> }
<ide>
<add> if value := r.URL.Query().Get("rotateManagerUnlockKey"); value != "" {
<add> rot, err := strconv.ParseBool(value)
<add> if err != nil {
<add> return fmt.Errorf("invalid value for rotateManagerUnlockKey: %s", value)
<add> }
<add>
<add> flags.RotateManagerUnlockKey = rot
<add> }
<add>
<ide> if err := sr.backend.Update(version, swarm, flags); err != nil {
<ide> logrus.Errorf("Error configuring swarm: %v", err)
<ide> return err
<ide><path>cli/command/swarm/unlock_key.go
<ide> import (
<ide>
<ide> "github.com/spf13/cobra"
<ide>
<add> "github.com/docker/docker/api/types/swarm"
<ide> "github.com/docker/docker/cli"
<ide> "github.com/docker/docker/cli/command"
<ide> "github.com/pkg/errors"
<ide> func newUnlockKeyCommand(dockerCli *command.DockerCli) *cobra.Command {
<ide> ctx := context.Background()
<ide>
<ide> if rotate {
<del> // FIXME(aaronl)
<add> flags := swarm.UpdateFlags{RotateManagerUnlockKey: true}
<add>
<add> swarm, err := client.SwarmInspect(ctx)
<add> if err != nil {
<add> return err
<add> }
<add>
<add> if !swarm.Spec.EncryptionConfig.AutoLockManagers {
<add> return errors.New("cannot rotate because autolock is not turned on")
<add> }
<add>
<add> err = client.SwarmUpdate(ctx, swarm.Version, swarm.Spec, flags)
<add> if err != nil {
<add> return err
<add> }
<add> if !quiet {
<add> fmt.Fprintf(dockerCli.Out(), "Successfully rotated manager unlock key.\n\n")
<add> }
<ide> }
<ide>
<ide> unlockKeyResp, err := client.SwarmGetUnlockKey(ctx)
<ide> if err != nil {
<ide> return errors.Wrap(err, "could not fetch unlock key")
<ide> }
<ide>
<add> if unlockKeyResp.UnlockKey == "" {
<add> return errors.New("no unlock key is set")
<add> }
<add>
<ide> if quiet {
<ide> fmt.Fprintln(dockerCli.Out(), unlockKeyResp.UnlockKey)
<ide> } else {
<ide><path>client/swarm_update.go
<ide> func (cli *Client) SwarmUpdate(ctx context.Context, version swarm.Version, swarm
<ide> query.Set("version", strconv.FormatUint(version.Index, 10))
<ide> query.Set("rotateWorkerToken", fmt.Sprintf("%v", flags.RotateWorkerToken))
<ide> query.Set("rotateManagerToken", fmt.Sprintf("%v", flags.RotateManagerToken))
<add> query.Set("rotateManagerUnlockKey", fmt.Sprintf("%v", flags.RotateManagerUnlockKey))
<ide> resp, err := cli.post(ctx, "/swarm/update", query, swarm, nil)
<ide> ensureReaderClosed(resp)
<ide> return err
<ide><path>daemon/cluster/cluster.go
<ide> func (c *Cluster) GetUnlockKey() (string, error) {
<ide> return "", err
<ide> }
<ide>
<add> if len(r.UnlockKey) == 0 {
<add> // no key
<add> return "", nil
<add> }
<add>
<ide> return encryption.HumanReadableKey(r.UnlockKey), nil
<ide> }
<ide> | 4 |
Python | Python | put dimensions into variables | b5dac6bd6415838f95cf936e473a70fd00b0c8b1 | <ide><path>tests/auto/keras/layers/test_recurrent.py
<ide>
<ide> from keras.layers import recurrent
<ide>
<del>def recursive_runner(layer):
<del> layer.input = theano.shared(value=np.ones((10,10,10)))
<add>nb_samples, timesteps, input_dim, output_dim = 3, 3, 10, 5
<ide>
<del> config = layer.get_config()
<ide>
<del> for train in [True,False]:
<del> out = layer.get_output(train).eval()
<del> mask = layer.get_output_mask(train)
<add>def _runner(layer_class):
<add> for weights in [None, [np.ones((input_dim, output_dim))]]:
<add> for ret_seq in [True, False]:
<add> layer = layer_class(input_dim, output_dim, return_sequences=ret_seq, weights=weights)
<add> layer.input = theano.shared(value=np.ones((nb_samples, timesteps, input_dim)))
<add> config = layer.get_config()
<add>
<add> for train in [True, False]:
<add> out = layer.get_output(train).eval()
<add> mask = layer.get_output_mask(train)
<add>
<ide>
<ide> class TestRNNS(unittest.TestCase):
<ide> def test_simple(self):
<del> for weights in [None, [np.ones((10,5))]]:
<del> for ret_seq in [True, False]:
<del> layer = recurrent.SimpleRNN(10, 5, return_sequences=ret_seq, weights=weights)
<del> recursive_runner(layer)
<add> _runner(recurrent.SimpleRNN)
<ide>
<ide> def test_simple_deep(self):
<del> for weights in [None, [np.ones((10,5))]]:
<del> for ret_seq in [True, False]:
<del> layer = recurrent.SimpleDeepRNN(10, 5, return_sequences=ret_seq, weights=weights)
<del> recursive_runner(layer)
<add> _runner(recurrent.SimpleDeepRNN)
<ide>
<ide> def test_gru(self):
<del> for weights in [None, [np.ones((10,5))]]:
<del> for ret_seq in [True, False]:
<del> layer = recurrent.GRU(10, 5, return_sequences=ret_seq, weights=weights)
<del> recursive_runner(layer)
<add> _runner(recurrent.GRU)
<ide>
<ide> def test_lstm(self):
<del> for weights in [None, [np.ones((10,5))]]:
<del> for ret_seq in [True, False]:
<del> layer = recurrent.LSTM(10, 5, return_sequences=ret_seq, weights=weights)
<del> recursive_runner(layer)
<del>
<add> _runner(recurrent.LSTM)
<ide>
<ide> def test_jzs1(self):
<del> for weights in [None, [np.ones((10,5))]]:
<del> for ret_seq in [True, False]:
<del> layer = recurrent.JZS1(10, 5, return_sequences=ret_seq, weights=weights)
<del> recursive_runner(layer)
<add> _runner(recurrent.JZS1)
<ide>
<ide> def test_jzs2(self):
<del> for weights in [None, [np.ones((10,5))]]:
<del> for ret_seq in [True, False]:
<del> layer = recurrent.JZS2(10, 5, return_sequences=ret_seq, weights=weights)
<del> recursive_runner(layer)
<add> _runner(recurrent.JZS2)
<ide>
<ide> def test_jzs3(self):
<del> for weights in [None, [np.ones((10,5))]]:
<del> for ret_seq in [True, False]:
<del> layer = recurrent.JZS3(10, 5, return_sequences=ret_seq, weights=weights)
<del> recursive_runner(layer)
<add> _runner(recurrent.JZS3)
<add>
<ide>
<ide> if __name__ == '__main__':
<ide> unittest.main() | 1 |
Text | Text | update unprefixed css props doc | 51b6092264608c258d70451df9ed3f3f172c8d4f | <ide><path>docs/tips/06-style-props-value-px.md
<ide> See [Inline Styles](/react/tips/inline-styles.html) for more info.
<ide> Sometimes you _do_ want to keep the CSS properties unitless. Here's a list of properties that won't get the automatic "px" suffix:
<ide>
<ide> - `boxFlex`
<add>- `boxFlexGroup`
<ide> - `columnCount`
<ide> - `fillOpacity`
<ide> - `flex` | 1 |
Javascript | Javascript | specify global object for globals | 44243e59df293c3579eb1dc779d5c2aaefb4d8bd | <ide><path>test/parallel/test-fs-write.js
<ide> const fn4 = path.join(tmpdir.path, 'write4.txt');
<ide> const expected = 'ümlaut.';
<ide> const constants = fs.constants;
<ide>
<del>/* eslint-disable no-undef */
<del>common.allowGlobals(externalizeString, isOneByteString, x);
<add>const { externalizeString, isOneByteString } = global;
<add>
<add>// Account for extra globals exposed by --expose_externalize_string.
<add>common.allowGlobals(externalizeString, isOneByteString, global.x);
<ide>
<ide> {
<ide> const expected = 'ümlaut sechzig'; // Must be a unique string.
<ide> common.allowGlobals(externalizeString, isOneByteString, x);
<ide> fs.closeSync(fd);
<ide> assert.strictEqual(fs.readFileSync(fn, 'utf8'), expected);
<ide> }
<del>/* eslint-enable no-undef */
<ide>
<ide> fs.open(fn, 'w', 0o644, common.mustSucceed((fd) => {
<ide> const done = common.mustSucceed((written) => { | 1 |
Python | Python | fix url generation for triggerdagrunoperatorlink | aaa3bf6b44238241bd61178426b692df53770c22 | <ide><path>airflow/utils/helpers.py
<ide> from typing import Any, Callable, Dict, Generator, Iterable, List, Optional, TypeVar
<ide> from urllib import parse
<ide>
<add>from flask import url_for
<ide> from jinja2 import Template
<ide>
<ide> from airflow.configuration import conf
<ide> def build_airflow_url_with_query(query: Dict[str, Any]) -> str:
<ide> 'http://0.0.0.0:8000/base/graph?dag_id=my-task&root=&execution_date=2020-10-27T10%3A59%3A25.615587
<ide> """
<ide> view = conf.get('webserver', 'dag_default_view').lower()
<del> return f"/{view}?{parse.urlencode(query)}"
<add> url = url_for(f"Airflow.{view}")
<add> return f"{url}?{parse.urlencode(query)}"
<ide><path>tests/utils/test_helpers.py
<ide> def test_merge_dicts_recursive_right_only(self):
<ide>
<ide> @conf_vars(
<ide> {
<del> ("webserver", "dag_default_view"): "custom",
<add> ("webserver", "dag_default_view"): "graph",
<ide> }
<ide> )
<ide> def test_build_airflow_url_with_query(self):
<add> """
<add> Test query generated with dag_id and params
<add> """
<ide> query = {"dag_id": "test_dag", "param": "key/to.encode"}
<del> url = build_airflow_url_with_query(query)
<del> assert url == "/custom?dag_id=test_dag¶m=key%2Fto.encode"
<add> expected_url = "/graph?dag_id=test_dag¶m=key%2Fto.encode"
<add>
<add> from airflow.www.app import cached_app
<add>
<add> with cached_app(testing=True).test_request_context():
<add> assert build_airflow_url_with_query(query) == expected_url | 2 |
Python | Python | fix data types in after_request test | f9e9e774646ff7cbd2df6386c7055760936a9fcd | <ide><path>flask/testsuite/basic.py
<ide> def before_request():
<ide> evts.append('before')
<ide> @app.after_request
<ide> def after_request(response):
<del> response.data += '|after'
<add> response.data += b'|after'
<ide> evts.append('after')
<ide> return response
<ide> @app.route('/')
<ide> def index():
<ide> return 'request'
<ide> self.assert_not_in('after', evts)
<ide> rv = app.test_client().get('/').data
<del> self.assert_in(b'after', evts)
<add> self.assert_in('after', evts)
<ide> self.assert_equal(rv, b'request|after')
<ide>
<ide> def test_after_request_processing(self): | 1 |
PHP | PHP | remove unneeded variable assignment | 4d0757b64f1b0565bf86b2767d290c9b2ff7ea0f | <ide><path>src/Http/Middleware/CallableMiddleware.php
<ide> public function __construct(callable $callable)
<ide>
<ide> public function process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface
<ide> {
<del> return $response = ($this->callable)(
<add> return ($this->callable)(
<ide> $request,
<ide> $handler
<ide> ); | 1 |
Javascript | Javascript | verify npm version | 634c995a71d29f25282c772ae8b1ed28a8aa9281 | <ide><path>script/utils/verify-requirements.js
<ide> module.exports = function(cb) {
<ide> return;
<ide> }
<ide>
<del> verifyPython27(function(error, pythonSuccessMessage) {
<del> cb(error, (nodeSuccessMessage + "\n" + pythonSuccessMessage).trim());
<add> verifyNpm(function(error, npmSuccessMessage) {
<add> if (error) {
<add> cb(error);
<add> return;
<add> }
<add>
<add> verifyPython27(function(error, pythonSuccessMessage) {
<add> cb(error, (nodeSuccessMessage + "\n" + npmSuccessMessage + "\n" + pythonSuccessMessage).trim());
<add> });
<ide> });
<ide> });
<ide>
<ide> function verifyNode(cb) {
<ide> }
<ide> }
<ide>
<add>function verifyNpm(cb) {
<add> childProcess.execFile('npm', ['-v'], { env: process.env }, function(err, stdout) {
<add> if (err)
<add> return cb("npm 1.4 is required to build Atom. An error (" + err + ") occured when checking the version.");
<add>
<add> var npmVersion = stdout ? stdout.trim() : '';
<add> var versionArray = npmVersion.split('.');
<add> var npmMajorVersion = +versionArray[0] || 0;
<add> var npmMinorVersion = +versionArray[1] || 0;
<add> if (npmMajorVersion === 1 && npmMinorVersion < 4)
<add> cb("npm v1.4+ is required to build Atom.");
<add> else
<add> cb(null, "npm: v" + npmVersion);
<add> });
<add>}
<add>
<add>
<ide> function verifyPython27(cb) {
<ide> if (process.platform == 'win32') {
<ide> if (!pythonExecutable) { | 1 |
Javascript | Javascript | fix regression introduced in | 269103a0e5e30cc217bde1660087e87dfc722b8a | <ide><path>lib/_stream_readable.js
<ide> function onEofChunk(stream, state) {
<ide> }
<ide> }
<ide> state.ended = true;
<del> state.needReadable = false;
<ide>
<del> // We are not protecting if emittedReadable = true,
<del> // so 'readable' gets scheduled anyway.
<del> state.emittedReadable = true;
<del> process.nextTick(emitReadable_, stream);
<add> if (state.sync) {
<add> // If we are sync, wait until next tick to emit the data.
<add> // Otherwise we risk emitting data in the flow()
<add> // the readable code triggers during a read() call
<add> emitReadable(stream);
<add> } else {
<add> // Emit 'readable' now to make sure it gets picked up.
<add> state.needReadable = false;
<add> state.emittedReadable = true;
<add> // We have to emit readable now that we are EOF. Modules
<add> // in the ecosystem (e.g. dicer) rely on this event being sync.
<add> if (state.ended) {
<add> emitReadable_(stream);
<add> } else {
<add> process.nextTick(emitReadable_, stream);
<add> }
<add> }
<ide> }
<ide>
<ide> // Don't emit readable right away in sync mode, because this can trigger
<ide><path>test/parallel/test-stream-readable-emit-readable-short-stream.js
<ide> const assert = require('assert');
<ide> break;
<ide> assert.strictEqual(chunk.toString(), 'content');
<ide> }
<del> }, 2));
<add> }));
<ide> }
<ide>
<ide> {
<ide> const assert = require('assert');
<ide> break;
<ide> assert.strictEqual(chunk.toString(), 'content');
<ide> }
<del> }, 2));
<add> }));
<ide> }
<ide>
<ide> {
<ide> const assert = require('assert');
<ide> break;
<ide> assert.strictEqual(chunk.toString(), 'content');
<ide> }
<del> }, 2));
<add> }));
<ide>
<ide> t.push('content');
<ide> t.push(null);
<ide><path>test/parallel/test-stream-readable-emittedReadable.js
<ide> const noRead = new Readable({
<ide> read: () => {}
<ide> });
<ide>
<del>noRead.once('readable', common.mustCall(() => {
<add>noRead.on('readable', common.mustCall(() => {
<ide> // emittedReadable should be true when the readable event is emitted
<ide> assert.strictEqual(noRead._readableState.emittedReadable, true);
<ide> noRead.read(0);
<ide> // emittedReadable is not reset during read(0)
<ide> assert.strictEqual(noRead._readableState.emittedReadable, true);
<del>
<del> noRead.on('readable', common.mustCall(() => {
<del> // The second 'readable' is emitted because we are ending
<del>
<del> // emittedReadable should be true when the readable event is emitted
<del> assert.strictEqual(noRead._readableState.emittedReadable, false);
<del> noRead.read(0);
<del> // emittedReadable is not reset during read(0)
<del> assert.strictEqual(noRead._readableState.emittedReadable, false);
<del>
<del> }));
<ide> }));
<ide>
<ide> noRead.push('foo');
<ide><path>test/parallel/test-stream-readable-needReadable.js
<ide> readable.on('readable', common.mustCall(() => {
<ide> // When the readable event fires, needReadable is reset.
<ide> assert.strictEqual(readable._readableState.needReadable, false);
<ide> readable.read();
<del>}, 2));
<add>}));
<ide>
<ide> // If a readable listener is attached, then a readable event is needed.
<ide> assert.strictEqual(readable._readableState.needReadable, true);
<ide><path>test/parallel/test-stream-readable-reading-readingMore.js
<ide> const Readable = require('stream').Readable;
<ide> assert.strictEqual(state.reading, false);
<ide> }
<ide>
<del> const expectedReadingMore = [true, false, false];
<add> const expectedReadingMore = [true, true, false];
<ide> readable.on('readable', common.mustCall(() => {
<ide> // There is only one readingMore scheduled from on('data'),
<ide> // after which everything is governed by the .read() call
<ide><path>test/parallel/test-stream2-httpclient-response-end.js
<ide> const server = http.createServer(function(req, res) {
<ide> while ((chunk = res.read()) !== null) {
<ide> data += chunk;
<ide> }
<del> }, 2));
<add> }));
<ide> res.on('end', common.mustCall(function() {
<ide> console.log('end event');
<ide> assert.strictEqual(msg, data);
<ide><path>test/parallel/test-stream2-transform.js
<ide> const Transform = require('_stream_transform');
<ide>
<ide> pt.end();
<ide>
<del> // The next readable is emitted on the next tick.
<del> assert.strictEqual(emits, 0);
<del>
<del> process.on('nextTick', function() {
<del> assert.strictEqual(emits, 1);
<del> assert.strictEqual(pt.read(5).toString(), 'l');
<del> assert.strictEqual(pt.read(5), null);
<del>
<del> assert.strictEqual(emits, 1);
<del> });
<add> assert.strictEqual(emits, 1);
<add> assert.strictEqual(pt.read(5).toString(), 'l');
<add> assert.strictEqual(pt.read(5), null);
<add> assert.strictEqual(emits, 1);
<ide> }
<ide>
<ide> { | 7 |
Javascript | Javascript | enable eslint no-constant-condition rule | 5bce5b706ff192bd30138ced1b0862dcbe957f6c | <ide><path>.eslintrc.js
<ide> module.exports = {
<ide> 'no-class-assign': 'error',
<ide> 'no-confusing-arrow': 'error',
<ide> 'no-const-assign': 'error',
<add> 'no-constant-condition': ['error', { checkLoops: false }],
<ide> 'no-constructor-return': 'error',
<ide> 'no-control-regex': 'error',
<ide> 'no-debugger': 'error', | 1 |
Javascript | Javascript | update htmlmesh.js | b3119d196ae99ed45eabbf173671db53a0001a97 | <ide><path>examples/jsm/interactive/HTMLMesh.js
<ide> function html2canvas( element ) {
<ide> drawBorder( style, 'borderBottom', x, y + height, width, 0 );
<ide> drawBorder( style, 'borderRight', x + width, y, 0, height );
<ide>
<del> if ( element.type === 'color' || element.type === 'text' ) {
<add> if ( element.type === 'color' || element.type === 'text' || element.type === 'number' ) {
<ide>
<ide> clipper.add( { x: x, y: y, width: width, height: height } );
<ide> | 1 |
Javascript | Javascript | update auth0 example with getserversideprops | f2315ffc8fc484177e5b9e4e08aeaa5f930da5a1 | <ide><path>examples/auth0/pages/advanced/ssr-profile.js
<del>import React from 'react'
<del>
<del>// This import is only needed when checking authentication status directly from getInitialProps
<add>// This import is only included in the server build, because it's only used by getServerSideProps
<ide> import auth0 from '../../lib/auth0'
<del>import { fetchUser } from '../../lib/user'
<ide> import Layout from '../../components/layout'
<ide>
<ide> function Profile({ user }) {
<ide> function Profile({ user }) {
<ide> )
<ide> }
<ide>
<del>Profile.getInitialProps = async ({ req, res }) => {
<del> // On the server-side you can check authentication status directly
<del> // However in general you might want to call API Routes to fetch data
<del> // An example of directly checking authentication:
<del> if (typeof window === 'undefined') {
<del> const { user } = await auth0.getSession(req)
<del> if (!user) {
<del> res.writeHead(302, {
<del> Location: '/api/login',
<del> })
<del> res.end()
<del> return
<del> }
<del> return { user }
<del> }
<del>
<del> // To do fetches to API routes you can pass the cookie coming from the incoming request on to the fetch
<del> // so that a request to the API is done on behalf of the user
<del> // keep in mind that server-side fetches need a full URL, meaning that the full url has to be provided to the application
<del> const cookie = req && req.headers.cookie
<del> const user = await fetchUser(cookie)
<add>export async function getServerSideProps({ req, res }) {
<add> // Here you can check authentication status directly before rendering the page,
<add> // however the page would be a serverless function, which is more expensive and
<add> // slower than a static page with client side authentication
<add> const { user } = await auth0.getSession(req)
<ide>
<del> // A redirect is needed to authenticate to Auth0
<ide> if (!user) {
<del> if (typeof window === 'undefined') {
<del> res.writeHead(302, {
<del> Location: '/api/login',
<del> })
<del> return res.end()
<del> }
<del>
<del> window.location.href = '/api/login'
<add> res.writeHead(302, {
<add> Location: '/api/login',
<add> })
<add> res.end()
<add> return
<ide> }
<ide>
<del> return { user }
<add> return { props: { user } }
<ide> }
<ide>
<ide> export default Profile
<ide><path>examples/auth0/pages/profile.js
<ide> function ProfileCard({ user }) {
<ide> <h1>Profile</h1>
<ide>
<ide> <div>
<del> <h3>Profile (server rendered)</h3>
<add> <h3>Profile (client rendered)</h3>
<ide> <img src={user.picture} alt="user picture" />
<ide> <p>nickname: {user.nickname}</p>
<ide> <p>name: {user.name}</p> | 2 |
Python | Python | build documentation breeze | 81c85a09d944021989ab530bc6caf1d9091a753c | <ide><path>dev/breeze/src/airflow_breeze/breeze.py
<ide> import subprocess
<ide> import sys
<ide> from pathlib import Path
<del>from typing import Optional
<add>from typing import Optional, Tuple
<ide>
<ide> import click
<ide> import click_completion
<ide> from click import ClickException
<ide> from click_completion import get_auto_shell
<ide>
<ide> from airflow_breeze.ci.build_image import build_image
<add>from airflow_breeze.ci.build_params import BuildParams
<ide> from airflow_breeze.console import console
<del>from airflow_breeze.global_constants import ALLOWED_BACKENDS, ALLOWED_PYTHON_MAJOR_MINOR_VERSION
<del>from airflow_breeze.utils.path_utils import __AIRFLOW_SOURCES_ROOT, BUILD_CACHE_DIR, find_airflow_sources_root
<add>from airflow_breeze.docs_generator import build_documentation
<add>from airflow_breeze.docs_generator.doc_builder import DocBuilder
<add>from airflow_breeze.global_constants import (
<add> ALLOWED_BACKENDS,
<add> ALLOWED_PYTHON_MAJOR_MINOR_VERSION,
<add> get_available_packages,
<add>)
<add>from airflow_breeze.utils.docker_command_utils import check_docker_resources
<add>from airflow_breeze.utils.path_utils import (
<add> __AIRFLOW_SOURCES_ROOT,
<add> BUILD_CACHE_DIR,
<add> find_airflow_sources_root,
<add> get_airflow_sources_root,
<add>)
<ide> from airflow_breeze.visuals import ASCIIART, ASCIIART_STYLE, CHEATSHEET, CHEATSHEET_STYLE
<ide>
<ide> AIRFLOW_SOURCES_DIR = Path(__file__).resolve().parent.parent.parent.parent.parent
<ide> def setup_autocomplete():
<ide> @click.option('--cheatsheet/--no-cheatsheet', default=None)
<ide> @click.option('--asciiart/--no-asciiart', default=None)
<ide> def change_config(python, backend, cheatsheet, asciiart):
<add> """
<add> Toggles on/off cheatsheet, asciiart
<add> """
<ide> from airflow_breeze.cache import delete_cache, touch_cache_file, write_to_cache_file
<ide>
<ide> if asciiart:
<ide> def change_config(python, backend, cheatsheet, asciiart):
<ide> console.print(f'[blue]Backend cached_value {backend}')
<ide>
<ide>
<add>@option_verbose
<add>@main.command(name='build-docs')
<add>@click.option('--docs-only', is_flag=True)
<add>@click.option('--spellcheck-only', is_flag=True)
<add>@click.option('--package-filter', type=click.Choice(get_available_packages()), multiple=True)
<add>def build_docs(verbose: bool, docs_only: bool, spellcheck_only: bool, package_filter: Tuple[str]):
<add> """
<add> Builds documentation in the container
<add> """
<add> params = BuildParams()
<add> airflow_sources = str(get_airflow_sources_root())
<add> mount_all_flag = False
<add> ci_image_name = params.airflow_ci_image_name
<add> check_docker_resources(verbose, mount_all_flag, airflow_sources, ci_image_name)
<add> doc_builder = DocBuilder(
<add> package_filter=package_filter, docs_only=docs_only, spellcheck_only=spellcheck_only
<add> )
<add> build_documentation.build(verbose, mount_all_flag, airflow_sources, ci_image_name, doc_builder)
<add>
<add>
<ide> if __name__ == '__main__':
<ide> BUILD_CACHE_DIR.mkdir(parents=True, exist_ok=True)
<ide> main()
<ide><path>dev/breeze/src/airflow_breeze/cache.py
<ide>
<ide> from airflow_breeze import global_constants
<ide> from airflow_breeze.console import console
<del>from airflow_breeze.global_constants import BUILD_CACHE_DIR
<add>from airflow_breeze.utils.path_utils import BUILD_CACHE_DIR
<ide>
<ide>
<ide> def check_if_cache_exists(param_name: str) -> bool:
<ide><path>dev/breeze/src/airflow_breeze/docs_generator/__init__.py
<add># Licensed to the Apache Software Foundation (ASF) under one
<add># or more contributor license agreements. See the NOTICE file
<add># distributed with this work for additional information
<add># regarding copyright ownership. The ASF licenses this file
<add># to you under the Apache License, Version 2.0 (the
<add># "License"); you may not use this file except in compliance
<add># with the License. You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing,
<add># software distributed under the License is distributed on an
<add># "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
<add># KIND, either express or implied. See the License for the
<add># specific language governing permissions and limitations
<add># under the License.
<ide><path>dev/breeze/src/airflow_breeze/docs_generator/build_documentation.py
<add># Licensed to the Apache Software Foundation (ASF) under one
<add># or more contributor license agreements. See the NOTICE file
<add># distributed with this work for additional information
<add># regarding copyright ownership. The ASF licenses this file
<add># to you under the Apache License, Version 2.0 (the
<add># "License"); you may not use this file except in compliance
<add># with the License. You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing,
<add># software distributed under the License is distributed on an
<add># "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
<add># KIND, either express or implied. See the License for the
<add># specific language governing permissions and limitations
<add># under the License.
<add>from airflow_breeze.docs_generator.doc_builder import DocBuilder
<add>from airflow_breeze.utils.docker_command_utils import get_extra_docker_flags
<add>from airflow_breeze.utils.run_utils import run_command
<add>
<add>
<add>def build(
<add> verbose: bool,
<add> mount_all_flag: bool,
<add> airflow_sources: str,
<add> airflow_ci_image_name: str,
<add> doc_builder: DocBuilder,
<add>):
<add> extra_docker_flags = get_extra_docker_flags(mount_all_flag, airflow_sources)
<add> cmd = []
<add> cmd.extend(["docker", "run"])
<add> cmd.extend(extra_docker_flags)
<add> cmd.extend(["-t", "-e", "GITHUB_ACTIONS="])
<add> cmd.extend(["--entrypoint", "/usr/local/bin/dumb-init", "--pull", "never"])
<add> cmd.extend([airflow_ci_image_name, "--", "/opt/airflow/scripts/in_container/run_docs_build.sh"])
<add> cmd.extend(doc_builder.args_doc_builder)
<add> run_command(cmd, verbose=verbose, text=True)
<ide><path>dev/breeze/src/airflow_breeze/docs_generator/doc_builder.py
<add># Licensed to the Apache Software Foundation (ASF) under one
<add># or more contributor license agreements. See the NOTICE file
<add># distributed with this work for additional information
<add># regarding copyright ownership. The ASF licenses this file
<add># to you under the Apache License, Version 2.0 (the
<add># "License"); you may not use this file except in compliance
<add># with the License. You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing,
<add># software distributed under the License is distributed on an
<add># "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
<add># KIND, either express or implied. See the License for the
<add># specific language governing permissions and limitations
<add># under the License.
<add>
<add>from dataclasses import dataclass
<add>from typing import List, Tuple
<add>
<add>
<add>@dataclass
<add>class DocBuilder:
<add> package_filter: Tuple[str]
<add> docs_only: bool
<add> spellcheck_only: bool
<add>
<add> @property
<add> def args_doc_builder(self) -> List[str]:
<add> doc_args = []
<add> if self.docs_only:
<add> doc_args.append("--docs-only")
<add> if self.spellcheck_only:
<add> doc_args.append("--spellcheck-only")
<add> if self.package_filter and len(self.package_filter) > 0:
<add> for single_filter in self.package_filter:
<add> doc_args.extend(["--package-filter", single_filter])
<add> return doc_args
<ide><path>dev/breeze/src/airflow_breeze/global_constants.py
<ide> # KIND, either express or implied. See the License for the
<ide> # specific language governing permissions and limitations
<ide> # under the License.
<add>from pathlib import Path
<add>from typing import List
<ide>
<add>from airflow_breeze.utils.path_utils import get_airflow_sources_root
<ide>
<ide> AIRFLOW_SOURCES = ""
<ide>
<ide> MSSQL_HOST_PORT = "21433"
<ide> FLOWER_HOST_PORT = "25555"
<ide> REDIS_HOST_PORT = "26379"
<add>
<add>EXCLUDE_DOCS_PACKAGE_FOLDER = [
<add> 'exts',
<add> 'integration-logos',
<add> 'rtd-deprecation',
<add> '_build',
<add> '_doctrees',
<add> '_inventory_cache',
<add>]
<add>
<add>
<add>def get_available_packages() -> List[str]:
<add> docs_path_content = Path(get_airflow_sources_root(), 'docs').glob('*/')
<add> available_packages = [x.name for x in docs_path_content if x.is_dir()]
<add> return list(set(available_packages) - set(EXCLUDE_DOCS_PACKAGE_FOLDER))
<ide><path>dev/breeze/src/airflow_breeze/utils/docker_command_utils.py
<add># Licensed to the Apache Software Foundation (ASF) under one
<add># or more contributor license agreements. See the NOTICE file
<add># distributed with this work for additional information
<add># regarding copyright ownership. The ASF licenses this file
<add># to you under the Apache License, Version 2.0 (the
<add># "License"); you may not use this file except in compliance
<add># with the License. You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing,
<add># software distributed under the License is distributed on an
<add># "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
<add># KIND, either express or implied. See the License for the
<add># specific language governing permissions and limitations
<add># under the License.
<add>
<add>from typing import List
<add>
<add>from airflow_breeze.utils.run_utils import run_command
<add>
<add>NECESSARY_HOST_VOLUMES = [
<add> "/.bash_aliases:/root/.bash_aliases:cached",
<add> "/.bash_history:/root/.bash_history:cached",
<add> "/.coveragerc:/opt/airflow/.coveragerc:cached",
<add> "/.dockerignore:/opt/airflow/.dockerignore:cached",
<add> "/.flake8:/opt/airflow/.flake8:cached",
<add> "/.github:/opt/airflow/.github:cached",
<add> "/.inputrc:/root/.inputrc:cached",
<add> "/.rat-excludes:/opt/airflow/.rat-excludes:cached",
<add> "/CHANGELOG.txt:/opt/airflow/CHANGELOG.txt:cached",
<add> "/LICENSE:/opt/airflow/LICENSE:cached",
<add> "/MANIFEST.in:/opt/airflow/MANIFEST.in:cached",
<add> "/NOTICE:/opt/airflow/NOTICE:cached",
<add> "/airflow:/opt/airflow/airflow:cached",
<add> "/provider_packages:/opt/airflow/provider_packages:cached",
<add> "/dags:/opt/airflow/dags:cached",
<add> "/dev:/opt/airflow/dev:cached",
<add> "/docs:/opt/airflow/docs:cached",
<add> "/hooks:/opt/airflow/hooks:cached",
<add> "/logs:/root/airflow/logs:cached",
<add> "/pyproject.toml:/opt/airflow/pyproject.toml:cached",
<add> "/pytest.ini:/opt/airflow/pytest.ini:cached",
<add> "/scripts:/opt/airflow/scripts:cached",
<add> "/scripts/in_container/entrypoint_ci.sh:/entrypoint:cached",
<add> "/setup.cfg:/opt/airflow/setup.cfg:cached",
<add> "/setup.py:/opt/airflow/setup.py:cached",
<add> "/tests:/opt/airflow/tests:cached",
<add> "/kubernetes_tests:/opt/airflow/kubernetes_tests:cached",
<add> "/docker_tests:/opt/airflow/docker_tests:cached",
<add> "/chart:/opt/airflow/chart:cached",
<add> "/metastore_browser:/opt/airflow/metastore_browser:cached",
<add>]
<add>
<add>
<add>def get_extra_docker_flags(all: bool, airflow_sources: str) -> List:
<add> # get_extra_docker_flags(False, str(airflow_source))
<add> EXTRA_DOCKER_FLAGS = []
<add> if all:
<add> EXTRA_DOCKER_FLAGS.extend(["-v", f"{airflow_sources}:/opt/airflow/:cached"])
<add> else:
<add> for flag in NECESSARY_HOST_VOLUMES:
<add> EXTRA_DOCKER_FLAGS.extend(["-v", airflow_sources + flag])
<add> EXTRA_DOCKER_FLAGS.extend(["-v", f"{airflow_sources}/files:/files"])
<add> EXTRA_DOCKER_FLAGS.extend(["-v", f"{airflow_sources}/dist:/dist"])
<add> EXTRA_DOCKER_FLAGS.extend(["--rm"])
<add> EXTRA_DOCKER_FLAGS.extend(["--env-file", f"{airflow_sources}/scripts/ci/docker-compose/_docker.env"])
<add> return EXTRA_DOCKER_FLAGS
<add>
<add>
<add>def check_docker_resources(
<add> verbose: bool, mount_all_flag: bool, airflow_sources: str, airflow_ci_image_name: str
<add>):
<add> extra_docker_flags = get_extra_docker_flags(mount_all_flag, airflow_sources)
<add> cmd = []
<add> cmd.extend(["docker", "run", "-t"])
<add> cmd.extend(extra_docker_flags)
<add> cmd.extend(["--entrypoint", "/bin/bash", airflow_ci_image_name])
<add> cmd.extend(["-c", "python /opt/airflow/scripts/in_container/run_resource_check.py"])
<add> run_command(cmd, verbose=verbose, text=True)
<ide><path>dev/breeze/tests/test_commands.py
<ide> # specific language governing permissions and limitations
<ide> # under the License.
<ide>
<add>from airflow_breeze.utils.docker_command_utils import get_extra_docker_flags
<add>from airflow_breeze.utils.path_utils import get_airflow_sources_root
<ide> from airflow_breeze.visuals import ASCIIART
<ide>
<ide>
<ide> def test_visuals():
<ide> assert 2051 == len(ASCIIART)
<add>
<add>
<add>def test_get_extra_docker_flags():
<add> airflow_sources = get_airflow_sources_root()
<add> all = True
<add> assert len(get_extra_docker_flags(all, str(airflow_sources))) < 10
<add> all = False
<add> assert len(get_extra_docker_flags(all, str(airflow_sources))) > 60
<ide><path>dev/breeze/tests/test_global_constants.py
<add># Licensed to the Apache Software Foundation (ASF) under one
<add># or more contributor license agreements. See the NOTICE file
<add># distributed with this work for additional information
<add># regarding copyright ownership. The ASF licenses this file
<add># to you under the Apache License, Version 2.0 (the
<add># "License"); you may not use this file except in compliance
<add># with the License. You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing,
<add># software distributed under the License is distributed on an
<add># "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
<add># KIND, either express or implied. See the License for the
<add># specific language governing permissions and limitations
<add># under the License.
<add>
<add>from airflow_breeze.global_constants import get_available_packages
<add>
<add>AVAILABLE_PACKAGES_STARTING_LIST = ("apache-airflow", "helm-chart", "docker-stack")
<add>
<add>
<add>def test_get_available_packages():
<add> assert len(get_available_packages()) > 70
<add> for package in get_available_packages():
<add> assert package.startswith(AVAILABLE_PACKAGES_STARTING_LIST) | 9 |
Python | Python | handle empty inputs in cov and corrcoef. closes | 1dcf0c96df5e2f7b861c6054ead2ad7ebc77aa79 | <ide><path>numpy/lib/function_base.py
<ide> def cov(m, y=None, rowvar=1, bias=0, ddof=None):
<ide> raise ValueError("ddof must be integer")
<ide>
<ide> X = array(m, ndmin=2, dtype=float)
<add> if X.size == 0:
<add> # handle empty arrays
<add> return np.array(m)
<ide> if X.shape[0] == 1:
<ide> rowvar = 1
<ide> if rowvar:
<ide> def corrcoef(x, y=None, rowvar=1, bias=0, ddof=None):
<ide>
<ide> Parameters
<ide> ----------
<del> m : array_like
<add> x : array_like
<ide> A 1-D or 2-D array containing multiple variables and observations.
<ide> Each row of `m` represents a variable, and each column a single
<ide> observation of all those variables. Also see `rowvar` below.
<ide> def corrcoef(x, y=None, rowvar=1, bias=0, ddof=None):
<ide>
<ide> """
<ide> c = cov(x, y, rowvar, bias, ddof)
<add> if c.size == 0:
<add> # handle empty arrays
<add> return c
<ide> try:
<ide> d = diag(c)
<ide> except ValueError: # scalar covariance
<ide><path>numpy/lib/tests/test_function_base.py
<ide> def test_ddof(self):
<ide> assert_almost_equal(corrcoef(self.A, ddof=-1), self.res1)
<ide> assert_almost_equal(corrcoef(self.A, self.B, ddof=-1), self.res2)
<ide>
<add> def test_empty(self):
<add> assert_equal(corrcoef(np.array([])).size, 0)
<add> assert_equal(corrcoef(np.array([]).reshape(0, 2)).shape, (0, 2))
<add>
<add>
<add>class TestCov(TestCase):
<add> def test_basic(self):
<add> x = np.array([[0, 2], [1, 1], [2, 0]]).T
<add> assert_allclose(np.cov(x), np.array([[ 1.,-1.], [-1.,1.]]))
<add>
<add> def test_empty(self):
<add> assert_equal(cov(np.array([])).size, 0)
<add> assert_equal(cov(np.array([]).reshape(0, 2)).shape, (0, 2))
<add>
<ide>
<ide> class Test_i0(TestCase):
<ide> def test_simple(self): | 2 |
Mixed | Javascript | fix compose() to have a less surprising api | 5b9a8b09e9573fcf88afbff8dd3b39dbbf837e04 | <ide><path>docs/api/compose.md
<ide> # `compose(...functions)`
<ide>
<del>Composes functions from left to right.
<add>Composes functions from right to left.
<ide>
<ide> This is a functional programming utility, and is included in Redux as a convenience.
<ide> You might want to use it to apply several [store enhancers](../Glossary.md#store-enhancer) in a row.
<ide>
<ide> #### Arguments
<ide>
<del>1. (*arguments*): The functions to compose. Each function is expected to accept a function as an argument and to return a function.
<add>1. (*arguments*): The functions to compose. Each function is expected to accept a single parameter. Its return value will be provided as an argument to the function standing to the left, and so on.
<ide>
<ide> #### Returns
<ide>
<del>(*Function*): The final function obtained by composing the given functions from left to right.
<add>(*Function*): The final function obtained by composing the given functions from right to left.
<ide>
<ide> #### Example
<ide>
<ide> if (process.env.NODE_ENV === 'production') {
<ide> require('redux-devtools').devTools(),
<ide> require('redux-devtools').persistState(
<ide> window.location.href.match(/[?&]debug_session=([^&]+)\b/)
<del> ),
<del> createStore
<del> );
<add> )
<add> )(createStore);
<ide>
<del> // Same code without the compose helper:
<add> // Same code without the `compose` helper:
<ide> //
<del> // finalCreateStore =
<del> // applyMiddleware(middleware)(
<del> // devTools()(
<del> // persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/))(
<del> // createStore
<del> // )
<del> // )
<del> // );
<add> // finalCreateStore = applyMiddleware(middleware)(
<add> // require('redux-devtools').devTools()(
<add> // require('redux-devtools').persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/))()
<add> // )
<add> // )(createStore);
<ide> }
<ide>
<ide> let store = finalCreateStore(reducer);
<ide><path>src/utils/applyMiddleware.js
<ide> export default function applyMiddleware(...middlewares) {
<ide> dispatch: (action) => dispatch(action)
<ide> };
<ide> chain = middlewares.map(middleware => middleware(middlewareAPI));
<del> dispatch = compose(...chain, store.dispatch);
<add> dispatch = compose(...chain)(store.dispatch);
<ide>
<ide> return {
<ide> ...store,
<ide><path>src/utils/compose.js
<ide> /**
<del> * Composes functions from left to right.
<add> * Composes single-argument functions from right to left.
<ide> *
<del> * @param {...Function} funcs - The functions to compose. Each is expected to
<del> * accept a function as an argument and to return a function.
<del> * @returns {Function} A function obtained by composing functions from left to
<del> * right.
<add> * @param {...Function} funcs The functions to compose.
<add> * @returns {Function} A function obtained by composing functions from right to
<add> * left. For example, compose(f, g, h) is identical to x => h(g(f(x))).
<ide> */
<ide> export default function compose(...funcs) {
<del> return funcs.reduceRight((composed, f) => f(composed));
<add> return arg => funcs.reduceRight((composed, f) => f(composed), arg);
<ide> }
<ide><path>test/utils/compose.spec.js
<ide> import { compose } from '../../src';
<ide>
<ide> describe('Utils', () => {
<ide> describe('compose', () => {
<del> it('composes functions from left to right', () => {
<add> it('composes from right to left', () => {
<add> const double = x => x * 2;
<add> const square = x => x * x;
<add> expect(compose(square)(5)).toBe(25);
<add> expect(compose(square, double)(5)).toBe(100);
<add> expect(compose(double, square, double)(5)).toBe(200);
<add> });
<add>
<add> it('composes functions from right to left', () => {
<ide> const a = next => x => next(x + 'a');
<ide> const b = next => x => next(x + 'b');
<ide> const c = next => x => next(x + 'c');
<ide> const final = x => x;
<ide>
<del> expect(compose(a, b, c, final)('')).toBe('abc');
<del> expect(compose(b, c, a, final)('')).toBe('bca');
<del> expect(compose(c, a, b, final)('')).toBe('cab');
<add> expect(compose(a, b, c)(final)('')).toBe('abc');
<add> expect(compose(b, c, a)(final)('')).toBe('bca');
<add> expect(compose(c, a, b)(final)('')).toBe('cab');
<ide> });
<ide> });
<ide> }); | 4 |
Text | Text | organize structure and add section on packages | 65f02eab50f137e3da7bdd9c0e89d2c23946f494 | <ide><path>CONTRIBUTING.md
<ide>
<ide> :+1::tada: First off, thanks for taking the time to contribute! :tada::+1:
<ide>
<del>The following is a set of guidelines for contributing to Atom and its packages,
<del>which are hosted in the [Atom Organization](https://github.com/atom) on GitHub.
<del>These are just guidelines, not rules, use your best judgment and feel free to
<del>propose changes to this document in a pull request.
<add>The following is a set of guidelines for contributing to Atom and its packages, which are hosted in the [Atom Organization](https://github.com/atom) on GitHub.
<add>These are just guidelines, not rules, use your best judgment and feel free to propose changes to this document in a pull request.
<add>
<add>#### Table Of Contents
<add>
<add>[What should I know before I get started?](#introduction)
<add> * [Code of Conduct](#code-of-conduct)
<add> * [Atom and Packages](#atom-and-packages)
<add>
<add>[How Can I Contribute?](#how-can-i-contribute)
<add> * [Your First Contribution](#your-first-contribution)
<add> * [Submitting Issues](#submitting-issues)
<add> * [Pull Requests](#pull-requests)
<add>
<add>[Styleguides](#styleguides)
<add> * [Git Commit Messages](#git-commit-messages)
<add> * [CoffeeScript Styleguide](#coffeescript-styleguide)
<add> * [Specs Styleguide](#specs-styleguide)
<add> * [Documentation Styleguide](#documentation-styleguide)
<add>
<add>[Additional Notes](#additional-notes)
<add> * [Issue and Pull Request Labels](#issue-and-pull-request-labels)
<add>
<add>## What should I know before I get started?
<add>
<add>### Code of Conduct
<ide>
<ide> This project adheres to the [Contributor Covenant 1.2](http://contributor-covenant.org/version/1/2/0).
<del>By participating, you are expected to uphold this code. Please report unacceptable behavior to [atom@github.com](mailto:atom@github.com).
<add>By participating, you are expected to uphold this code.
<add>Please report unacceptable behavior to [atom@github.com](mailto:atom@github.com).
<ide>
<del>#### Table Of Contents
<add>### Atom and Packages
<add>
<add>Atom is a large open source project - it's made up of over [200 repositories](https://github.com/atom).
<add>When you initially consider contributing to Atom, you might be unsure about which of those 200 repositories implements the functionality you want to change or report a bug for.
<add>This section should help you with that.
<add>
<add>Atom is intentionally very modular.
<add>Nearly every non-editor UI element you interact with comes from a package, even fundamental things like tabs and the status-bar.
<add>These packages are packages in the same way that packages in the [package store](https://atom.io/packages) are packages, with one difference: they are bundled into the [default distribution](https://github.com/atom/atom/blob/10b8de6fc499a7def9b072739486e68530d67ab4/package.json#L58).
<add>
<add>
<add>
<add>To get a sense for the packages that are bundled with Atom, you can go to Settings > Packages within Atom and take a look at the Core Packages section.
<add>
<add>Here's a list of the big ones:
<add>
<add>* [atom/atom](https://github.com/atom/atom) - Atom Core! The core editor component is responsible for basic text editing (e.g. cursors, selections, scrolling), text indentation, wrapping, and folding, text rendering, editor rendering, file system operations (e.g. saving), and installation and auto-updating. You should also use this repository for feedback related to the [core API](https://atom.io/docs/api/latest/Notification) and for large, overarching design proposals.
<add>
<add>* [tree-view](https://github.com/atom/tree-view) - file and directory listing on the left of the UI.
<add>* [fuzzy-finder](https://github.com/atom/fuzzy-finder) - the quick file open chooser.
<add>* [find-and-replace](https://github.com/atom/find-and-replace) - all search and replace functionality.
<add>* [tabs](https://github.com/atom/tabs) - the tabs for open editors at the top of the UI.
<add>* [status-bar](https://github.com/atom/status-bar) - the status bar at the bottom of the UI.
<add>* [markdown-preview](https://github.com/atom/markdown-preview) - the rendered markdown pane item.
<add>* [settings-view](https://github.com/atom/settings-view) - the settings UI pane item.
<add>* [autocomplete-plus](https://github.com/atom/autocomplete-plus) - autocompletions shown while typing. Some languages have additional packages for autocompletion functionality, such as [autocomplete-html](https://github.com/atom/autocomplete-html).
<add>* [git-diff](https://github.com/atom/git-diff) - Git change indicators shown in the editor's gutter.
<add>* [language-javascript](https://github.com/atom/language-javascript) - all bundled languages are packages too, and each one has a separate package `language-[name]`. Use these for feedback on syntax highlighting issues that only appear for a specific language.
<add>* [one-dark-ui](https://github.com/atom/one-dark-ui) - the default UI styling for anything but the text editor. UI theme packages (i.e. packages with a `-ui` suffix) provide only styling and it's possible that a bundled package is responsible for a UI issue. There are other other bundled UI themes, such as [one-light-ui](https://github.com/atom/one-light-ui).
<add>* [one-dark-syntax](https://github.com/atom/one-dark-syntax) - the default syntax highlighting styles applied for all languages. There are other other bundled syntax themes, such as [solarized-dark](https://github.com/atom/solarized-dark). You should use these packages for reporting issues that appear in many languages, but disappear if you change to another syntax theme.
<add>* [apm](https://github.com/atom/apm) - the `apm` command line tool (Atom Package Manager). You should use this repository for any contributions related to the `apm` tool and to publishing packages.
<add>* [atom.io](https://github.com/atom/atom.io) - the repository for feedback on the [Atom.io website](https://atom.io) and the [Atom.io package API](https://github.com/atom/atom/blob/master/docs/apm-rest-api.md) used by [apm](https://github.com/atom/apm).
<add>
<add>There are many more, but this list should be a good starting point.
<add>For more information on how to work with Atom's official packages, see [Contributing to Atom Packages](https://github.com/atom/atom/blob/master/docs/contributing-to-packages.md).
<ide>
<del>* [Submitting Issues](#submitting-issues)
<del>* [Your First Contribution](#your-first-contribution)
<del>* [Pull Requests](#pull-requests)
<del>* [Git Commit Messages](#git-commit-messages)
<del>* [CoffeeScript Styleguide](#coffeescript-styleguide)
<del>* [Specs Styleguide](#specs-styleguide)
<del>* [Documentation Styleguide](#documentation-styleguide)
<del>* [Issue and Pull Request Labels](#issue-and-pull-request-labels)
<add>Also, because Atom is so extensible, it's possible that a feature you've become accustomed to in Atom or an issue you're encountering aren't coming from a bundled package at all, but rather a [community package](https://atom.io/packages) you've installed.
<add>Each community package has its own repository too, and you should be able to find it in Settings > Packages for the packages you installed and contribute there.
<ide>
<del>## Submitting Issues
<add>## How can I contribute?
<add>
<add>### Your First Contribution
<add>
<add>Unsure where to begin contributing to Atom? You can start by looking through these `beginner` and `help-wanted` issues:
<add>
<add>* [Beginner issues][beginner] - issues which should only require a few lines of code, and a test or two.
<add>* [Help wanted issues][help-wanted] - issues which should be a bit more involved than `beginner` issues.
<add>
<add>Both issue lists are sorted by total number of comments. While not perfect, number of comments is a reasonable proxy for impact a given change will have.
<add>
<add>### Submitting Issues
<ide>
<ide> * You can create an issue [here](https://github.com/atom/atom/issues/new), but
<ide> before doing that please read the notes below on debugging and submitting issues,
<ide> By participating, you are expected to uphold this code. Please report unacceptab
<ide> * Please setup a [profile picture](https://help.github.com/articles/how-do-i-set-up-my-profile-picture)
<ide> to make yourself recognizable and so we can all get to know each other better.
<ide>
<del>### Package Repositories
<del>
<del>This is the repository for the core Atom editor only. Atom comes bundled with
<del>many packages and themes that are stored in other repos under the
<del>[Atom organization](https://github.com/atom) such as
<del>[tabs](https://github.com/atom/tabs),
<del>[find-and-replace](https://github.com/atom/find-and-replace),
<del>[language-javascript](https://github.com/atom/language-javascript), and
<del>[atom-light-ui](https://github.com/atom/atom-light-ui).
<del>
<del>If your issue is related to a specific package, open an issue on that package's
<del>issue tracker. If you're unsure which package is causing your problem or if
<del>you're having an issue with Atom core, open an issue on this repository.
<del>
<del>For more information on how to work with Atom's official packages, see
<del>[Contributing to Atom Packages](https://github.com/atom/atom/blob/master/docs/contributing-to-packages.md)
<del>
<del>## Your First Contribution
<del>
<del>Unsure where to begin contributing to Atom? You can start by looking through these `beginner` and `help-wanted` issues:
<del>
<del>* [Beginner issues][beginner]
<del>* [Help wanted issues][help-wanted]
<del>
<del>## Pull Requests
<add>### Pull Requests
<ide>
<ide> * Include screenshots and animated GIFs in your pull request whenever possible.
<ide> * Follow the [CoffeeScript](#coffeescript-styleguide),
<ide> Unsure where to begin contributing to Atom? You can start by looking through the
<ide> * Using a plain `return` when returning explicitly at the end of a function.
<ide> * Not `return null`, `return undefined`, `null`, or `undefined`
<ide>
<del>## Git Commit Messages
<add>## Styleguides
<add>
<add>### Git Commit Messages
<ide>
<ide> * Use the present tense ("Add feature" not "Added feature")
<ide> * Use the imperative mood ("Move cursor to..." not "Moves cursor to...")
<ide> Unsure where to begin contributing to Atom? You can start by looking through the
<ide> * :arrow_down: `:arrow_down:` when downgrading dependencies
<ide> * :shirt: `:shirt:` when removing linter warnings
<ide>
<del>## CoffeeScript Styleguide
<add>### CoffeeScript Styleguide
<ide>
<ide> * Set parameter defaults without spaces around the equal sign
<ide> * `clear = (count=1) ->` instead of `clear = (count = 1) ->`
<ide> Unsure where to begin contributing to Atom? You can start by looking through the
<ide> * Use `this` instead of a standalone `@`
<ide> * `return this` instead of `return @`
<ide>
<del>## Specs Styleguide
<add>### Specs Styleguide
<ide>
<ide> - Include thoughtfully-worded, well-structured
<ide> [Jasmine](http://jasmine.github.io/) specs in the `./spec` folder.
<ide> - treat `describe` as a noun or situation.
<ide> - treat `it` as a statement about state or how an operation changes state.
<ide>
<del>### Example
<add>#### Example
<ide>
<ide> ```coffee
<ide> describe 'a dog', ->
<ide> describe 'a dog', ->
<ide> # spec here
<ide> ```
<ide>
<del>## Documentation Styleguide
<add>### Documentation Styleguide
<ide>
<ide> * Use [AtomDoc](https://github.com/atom/atomdoc).
<ide> * Use [Markdown](https://daringfireball.net/projects/markdown).
<ide> describe 'a dog', ->
<ide> * Reference instance methods with `{ClassName::methodName}`
<ide> * Reference class methods with `{ClassName.methodName}`
<ide>
<del>### Example
<add>#### Example
<ide>
<ide> ```coffee
<ide> # Public: Disable the package with the given name.
<ide> describe 'a dog', ->
<ide> disablePackage: (name, options, callback) ->
<ide> ```
<ide>
<del>## Issue and Pull Request Labels
<add>## Additional Notes
<add>
<add>### Issue and Pull Request Labels
<ide>
<ide> This section lists the labels we use to help us track and manage issues and pull requests. Most labels are used across all Atom repositories, but some are specific to `atom/atom`.
<ide> | 1 |
PHP | PHP | get/has with null values | 5b057e4d840d63e265268112be40074ceec076b2 | <ide><path>tests/Support/SupportArrayTest.php
<ide> public function testGet()
<ide> $value = Arr::get($array, 'products.desk');
<ide> $this->assertEquals(['price' => 100], $value);
<ide>
<add> // Test null array values
<add> $array = ['foo' => null, 'bar' => ['baz' => null]];
<add> $this->assertNull(Arr::get($array, 'foo', 'default'));
<add> $this->assertNull(Arr::get($array, 'bar.baz', 'default'));
<add>
<ide> // Test direct ArrayAccess object
<ide> $array = ['products' => ['desk' => ['price' => 100]]];
<ide> $arrayAccessObject = new ArrayObject($array);
<ide> public function testGet()
<ide> $value = Arr::get($array, 'parent.child.desk');
<ide> $this->assertNull($value);
<ide>
<del> // Test null ArrayAccess object field
<add> // Test missing ArrayAccess object field
<ide> $arrayAccessObject = new ArrayObject(['products' => ['desk' => null]]);
<ide> $array = ['parent' => $arrayAccessObject];
<ide> $value = Arr::get($array, 'parent.products.desk.price');
<ide> $this->assertNull($value);
<add>
<add> // Test null ArrayAccess object fields
<add> $array = new ArrayObject(['foo' => null, 'bar' => new ArrayObject(['baz' => null])]);
<add> $this->assertNull(Arr::get($array, 'foo', 'default'));
<add> $this->assertNull(Arr::get($array, 'bar.baz', 'default'));
<ide> }
<ide>
<ide> public function testHas()
<ide> public function testHas()
<ide> $this->assertTrue(Arr::has($array, 'products.desk.price'));
<ide> $this->assertFalse(Arr::has($array, 'products.foo'));
<ide> $this->assertFalse(Arr::has($array, 'products.desk.foo'));
<add>
<add> $array = ['foo' => null, 'bar' => ['baz' => null]];
<add> $this->assertTrue(Arr::has($array, 'foo'));
<add> $this->assertTrue(Arr::has($array, 'bar.baz'));
<ide> }
<ide>
<ide> public function testIsAssoc() | 1 |
Javascript | Javascript | add hashley app to showcase | e56ec9da359238d45a09138b65ed9bc796d25e98 | <ide><path>website/src/react-native/showcase.js
<ide> var apps = [
<ide> link: 'https://itunes.apple.com/us/app/fast-paper/id1001174614',
<ide> author: 'Liubomyr Mykhalchenko (@liubko)',
<ide> },
<add> {
<add> name: 'Hashley',
<add> icon: 'http://a2.mzstatic.com/us/r30/Purple4/v4/5f/19/fc/5f19fc13-e7af-cd6b-6749-cedabdaeee7d/icon350x350.png',
<add> link: 'https://itunes.apple.com/us/app/hashtag-by-hashley-ironic/id1022724462?mt=8',
<add> author: 'Elephant, LLC',
<add> },
<ide> {
<ide> name: 'HSK Level 1 Chinese Flashcards',
<ide> icon: 'http://is2.mzstatic.com/image/pf/us/r30/Purple1/v4/b2/4f/3a/b24f3ae3-2597-cc70-1040-731b425a5904/mzl.amxdcktl.jpg', | 1 |
PHP | PHP | apply fixes from styleci | 53675f12c79495abf7525731c1e784d02800c129 | <ide><path>src/Illuminate/Mail/Mailable.php
<ide> protected function setAddress($address, $name = null, $property = 'to')
<ide>
<ide> $this->{$property}[] = [
<ide> 'name' => isset($recipient->name) ? $recipient->name : null,
<del> 'address' => $recipient->email
<add> 'address' => $recipient->email,
<ide> ];
<ide> }
<ide>
<ide><path>tests/Mail/MailMailableTest.php
<ide> public function testMailableSetsRecipientsCorrectly()
<ide> $this->assertEquals([['name' => null, 'address' => 'taylor@laravel.com']], $mailable->to);
<ide>
<ide> $mailable = new WelcomeMailableStub;
<del> $mailable->to([['name' => 'Taylor Otwell', 'email' => 'taylor@laravel.com']]);;
<add> $mailable->to([['name' => 'Taylor Otwell', 'email' => 'taylor@laravel.com']]);
<ide> $this->assertEquals([['name' => 'Taylor Otwell', 'address' => 'taylor@laravel.com']], $mailable->to);
<ide>
<ide> $mailable = new WelcomeMailableStub;
<ide> public function testMailableSetsRecipientsCorrectly()
<ide> $mailable->to(collect([new MailableTestUserStub, new MailableTestUserStub]));
<ide> $this->assertEquals([
<ide> ['name' => 'Taylor Otwell', 'address' => 'taylor@laravel.com'],
<del> ['name' => 'Taylor Otwell', 'address' => 'taylor@laravel.com']
<add> ['name' => 'Taylor Otwell', 'address' => 'taylor@laravel.com'],
<ide> ], $mailable->to);
<ide> }
<ide> | 2 |
Text | Text | add tests to anonymous-message-board | 8f8a2cc0c588f320b6543aeb7a3ed6ab5591704f | <ide><path>curriculum/challenges/english/09-information-security/information-security-projects/anonymous-message-board.md
<ide> async (getUserInput) => {
<ide> You can send a POST request to `/api/replies/{board}` with form data including `text`, `delete_password`, & `thread_id`. This will update the `bumped_on` date to the comment's date. In the thread's `replies` array, an object will be saved with at least the properties `_id`, `text`, `created_on`, `delete_password`, & `reported`.
<ide>
<ide> ```js
<add>async (getUserInput) => {
<add> const url = getUserInput('url');
<add> const body = await fetch(url + '/api/threads/fcc_test');
<add> const thread = await body.json();
<add>
<add> const date = new Date();
<add> const text = `fcc_test_reply_${date}`;
<add> const delete_password = 'delete_me';
<add> const thread_id = thread[0]._id;
<add> const replyCount = thread[0].replies.length;
<ide>
<add> const data = { text, delete_password, thread_id };
<add> const res = await fetch(url + '/api/replies/fcc_test', {
<add> method: 'POST',
<add> headers: { 'Content-Type': 'application/json' },
<add> body: JSON.stringify(data)
<add> });
<add> if (res.ok) {
<add> const checkData = await fetch(`${url}/api/replies/fcc_test?thread_id=${thread_id}`);
<add> const parsed = await checkData.json();
<add> try {
<add> assert.equal(parsed.replies.length, replyCount + 1);
<add> assert.equal(parsed.replies[0].text, text);
<add> assert.equal(parsed._id, thread_id);
<add> assert.equal(parsed.bumped_on, parsed.replies[0].created_on);
<add> } catch (err) {
<add> throw new Error(err.responseText || err.message);
<add> }
<add> } else {
<add> throw new Error(`${res.status} ${res.statusText}`);
<add> }
<add>};
<ide> ```
<ide>
<ide> You can send a GET request to `/api/threads/{board}`. Returned will be an array of the most recent 10 bumped threads on the board with only the most recent 3 replies for each. The `reported` and `delete_password` fields will not be sent to the client.
<ide>
<ide> ```js
<add>async (getUserInput) => {
<add> const url = getUserInput('url');
<add> const res = await fetch(url + '/api/threads/fcc_test');
<ide>
<add> if (res.ok) {
<add> const threads = await res.json();
<add> try {
<add> assert.equal(res.status, 200);
<add> assert.isAtMost(threads.length, 10);
<add> for (let i = 0; i < threads.length; i++) {
<add> assert.containsAllKeys(threads[i], ["_id", "text", "created_on", "bumped_on", "replies"]);
<add> assert.isAtMost(threads[i].replies.length, 3);
<add> assert.notExists(threads[i].delete_password);
<add> assert.notExists(threads[i].reported);
<add> for (let j = 0; j < threads[i].replies.length; j++) {
<add> assert.notExists(threads[i].replies[j].delete_password);
<add> assert.notExists(threads[i].replies[j].reported);
<add> }
<add> }
<add> } catch (err) {
<add> throw new Error(err.responseText || err.message);
<add> }
<add> } else {
<add> throw new Error(`${res.status} ${res.statusText}`);
<add> }
<add>};
<ide> ```
<ide>
<ide> You can send a GET request to `/api/replies/{board}?thread_id={thread_id}`. Returned will be the entire thread with all its replies, also excluding the same fields from the client as the previous test.
<ide>
<ide> ```js
<add>async (getUserInput) => {
<add> const url = getUserInput('url');
<add> let res = await fetch(url + '/api/threads/fcc_test');
<add> const threads = await res.json();
<add> const thread_id = threads[0]._id;
<add> res = await fetch(`${url}/api/replies/fcc_test?thread_id=${thread_id}`);
<ide>
<add> if (res.ok) {
<add> const thread = await res.json();
<add> try {
<add> assert.equal(res.status, 200);
<add> assert.isObject(thread);
<add> assert.containsAllKeys(thread, ["_id", "text", "created_on", "bumped_on", "replies"]);
<add> assert.isArray(thread.replies);
<add> assert.notExists(thread.delete_password);
<add> assert.notExists(thread.reported);
<add> for (let i = 0; i < thread.replies.length; i++) {
<add> assert.notExists(thread.replies[i].delete_password);
<add> assert.notExists(thread.replies[i].reported);
<add> }
<add> } catch (err) {
<add> throw new Error(err.responseText || err.message);
<add> }
<add> } else {
<add> throw new Error(`${res.status} ${res.statusText}`);
<add> }
<add>};
<ide> ```
<ide>
<ide> You can send a DELETE request to `/api/threads/{board}` and pass along the `thread_id` & `delete_password` to delete the thread. Returned will be the string `incorrect password` or `success`.
<ide>
<ide> ```js
<add>async (getUserInput) => {
<add> const url = getUserInput('url');
<add> let res = await fetch(url + '/api/threads/fcc_test');
<add> const threads = await res.json();
<add> const thread_id = threads[0]._id;
<add> let data = { thread_id, delete_password: "wrong_password" };
<add> const res_invalid = await fetch(url + '/api/threads/fcc_test', {
<add> method: 'DELETE',
<add> headers: { 'Content-Type': 'application/json' },
<add> body: JSON.stringify(data)
<add> });
<add> data = { thread_id, delete_password: "delete_me" };
<add> res = await fetch(url + '/api/threads/fcc_test', {
<add> method: 'DELETE',
<add> headers: { 'Content-Type': 'application/json' },
<add> body: JSON.stringify(data)
<add> });
<ide>
<add> if (res.ok) {
<add> const deleted = await res.text();
<add> const not_deleted = await res_invalid.text();
<add> try {
<add> assert.equal(res.status, 200);
<add> assert.equal(deleted, "success");
<add> assert.equal(not_deleted, "incorrect password");
<add> } catch (err) {
<add> throw new Error(err.responseText || err.message);
<add> }
<add> } else {
<add> throw new Error(`${res.status} ${res.statusText}`);
<add> }
<add>};
<ide> ```
<ide>
<ide> You can send a DELETE request to `/api/replies/{board}` and pass along the `thread_id`, `reply_id`, & `delete_password`. Returned will be the string `incorrect password` or `success`. On success, the text of the `reply_id` will be changed to `[deleted]`.
<ide>
<ide> ```js
<add>async (getUserInput) => {
<add> const url = getUserInput('url');
<add>
<add> const thread_data = {
<add> text: "fcc_test_thread",
<add> delete_password: "delete_me",
<add> };
<add> await fetch(`${url}/api/threads/fcc_test`, {
<add> method: "POST",
<add> headers: { 'Content-Type': 'application/json' },
<add> body: JSON.stringify(thread_data)
<add> });
<add> let res = await fetch(`${url}/api/threads/fcc_test`);
<add> let threads = await res.json();
<add> const thread_id = threads[0]._id;
<add>
<add> const reply_data = { thread_id, text: "fcc_test_reply", delete_password: "delete_me" };
<add> await fetch(`${url}/api/replies/fcc_test`, {
<add> method: 'POST',
<add> headers: { 'Content-Type': 'application/json' },
<add> body: JSON.stringify(reply_data)
<add> });
<add> res = await fetch(`${url}/api/threads/fcc_test`);
<add> threads = await res.json();
<add> const reply_id = threads[0].replies[0]._id;
<ide>
<add> const data = { thread_id, reply_id, delete_password: "delete_me" };
<add> res = await fetch(url + '/api/replies/fcc_test', {
<add> method: 'DELETE',
<add> headers: { 'Content-Type': 'application/json' },
<add> body: JSON.stringify(data)
<add> });
<add>
<add> if (res.ok) {
<add> const deleted = await res.text();
<add> try {
<add> assert.equal(res.status, 200);
<add> assert.equal(deleted, "success");
<add> res = await fetch(`${url}/api/replies/fcc_test?thread_id=${thread_id}`);
<add> const thread = await res.json();
<add> assert.equal(thread._id, thread_id);
<add> assert.equal(thread.replies[0]._id, reply_id);
<add> assert.equal(thread.replies[0].text, "[deleted]");
<add> } catch (err) {
<add> throw new Error(err.responseText || err.message);
<add> }
<add> } else {
<add> throw new Error(`${res.status} ${res.statusText}`);
<add> }
<add>};
<ide> ```
<ide>
<del>You can send a PUT request to `/api/threads/{board}` and pass along the `thread_id`. Returned will be the string `success`. The `reported` value of the `thread_id` will be changed to `true`.
<add>You can send a PUT request to `/api/threads/{board}` and pass along the `thread_id`. Returned will be the string `reported`. The `reported` value of the `thread_id` will be changed to `true`.
<ide>
<ide> ```js
<add>async (getUserInput) => {
<add> const url = getUserInput('url');
<add>
<add> let res = await fetch(`${url}/api/threads/fcc_test`);
<add> const threads = await res.json();
<add> const report_id = threads[0]._id;
<add> const data = { report_id };
<add>
<add> res = await fetch(`${url}/api/threads/fcc_test`, {
<add> method: 'PUT',
<add> headers: { 'Content-Type': 'application/json' },
<add> body: JSON.stringify(data)
<add> });
<ide>
<add> if (res.ok) {
<add> const reported = await res.text();
<add> try {
<add> assert.equal(res.status, 200);
<add> assert.equal(reported, "reported");
<add> } catch (err) {
<add> throw new Error(err.responseText || err.message);
<add> }
<add> } else {
<add> throw new Error(`${res.status} ${res.statusText}`);
<add> }
<add>};
<ide> ```
<ide>
<del>You can send a PUT request to `/api/replies/{board}` and pass along the `thread_id` & `reply_id`. Returned will be the string `success`. The `reported` value of the `reply_id` will be changed to `true`.
<add>You can send a PUT request to `/api/replies/{board}` and pass along the `thread_id` & `reply_id`. Returned will be the string `reported`. The `reported` value of the `reply_id` will be changed to `true`.
<ide>
<ide> ```js
<add>async (getUserInput) => {
<add> const url = getUserInput('url');
<add>
<add> let res = await fetch(`${url}/api/threads/fcc_test`);
<add> const threads = await res.json();
<add> const thread_id = threads[0]._id;
<add> const reply_id = threads[0].replies[0]._id;
<add> const data = { thread_id, reply_id };
<add>
<add> res = await fetch(`${url}/api/replies/fcc_test`, {
<add> method: 'PUT',
<add> headers: { 'Content-Type': 'application/json' },
<add> body: JSON.stringify(data)
<add> });
<ide>
<add> if (res.ok) {
<add> const reported = await res.text();
<add> try {
<add> assert.equal(res.status, 200);
<add> assert.equal(reported, "reported");
<add> } catch (err) {
<add> throw new Error(err.responseText || err.message);
<add> }
<add> } else {
<add> throw new Error(`${res.status} ${res.statusText}`);
<add> }
<add>};
<ide> ```
<ide>
<ide> All 10 functional tests are complete and passing.
<ide>
<ide> ```js
<del>
<add>async (getUserInput) => {
<add> const tests = await fetch(getUserInput('url') + '/_api/get-tests');
<add> const parsed = await tests.json();
<add> assert.isTrue(parsed.length >= 10);
<add> parsed.forEach((test) => {
<add> assert.equal(test.state, 'passed');
<add> assert.isAtLeast(test.assertions.length, 1);
<add> });
<add>};
<ide> ```
<ide>
<ide> # --solutions-- | 1 |
Javascript | Javascript | fix header on rntester file | c78ddf2c3d00ececffd6634fc23df8df3cf33023 | <ide><path>RNTester/js/ARTExample.js
<ide> * LICENSE file in the root directory of this source tree. An additional grant
<ide> * of patent rights can be found in the PATENTS file in the same directory.
<ide> *
<del> * The examples provided by Facebook are for non-commercial testing and
<del> * evaluation purposes only.
<del> *
<del> * Facebook reserves all rights not expressly granted.
<del> *
<del> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
<del> * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
<del> * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL
<del> * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
<del> * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
<del> * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
<del> *
<ide> * @flow
<ide> * @providesModule ARTExample
<ide> */ | 1 |
Go | Go | fix small \n error un docker build | ba17f4a06a75a66e11b6cf2ca2cdb5bee4f7bfa8 | <ide><path>commands.go
<ide> func (cli *DockerCli) CmdBuild(args ...string) error {
<ide> // FIXME: ProgressReader shouldn't be this annoyning to use
<ide> if context != nil {
<ide> sf := utils.NewStreamFormatter(false)
<del> body = utils.ProgressReader(ioutil.NopCloser(context), 0, cli.err, sf.FormatProgress("", "Uploading context", "%v bytes%0.0s%0.0s"), sf)
<add> body = utils.ProgressReader(ioutil.NopCloser(context), 0, cli.err, sf.FormatProgress("", "Uploading context", "%v bytes%0.0s%0.0s"), sf, true)
<ide> }
<ide> // Upload the build context
<ide> v := &url.Values{}
<ide><path>graph.go
<ide> func (graph *Graph) TempLayerArchive(id string, compression Compression, sf *uti
<ide> if err != nil {
<ide> return nil, err
<ide> }
<del> return NewTempArchive(utils.ProgressReader(ioutil.NopCloser(archive), 0, output, sf.FormatProgress("", "Buffering to disk", "%v/%v (%v)"), sf), tmp.Root)
<add> return NewTempArchive(utils.ProgressReader(ioutil.NopCloser(archive), 0, output, sf.FormatProgress("", "Buffering to disk", "%v/%v (%v)"), sf, true), tmp.Root)
<ide> }
<ide>
<ide> // Mktemp creates a temporary sub-directory inside the graph's filesystem.
<ide><path>server.go
<ide> func (srv *Server) ImageInsert(name, url, path string, out io.Writer, sf *utils.
<ide> return "", err
<ide> }
<ide>
<del> if err := c.Inject(utils.ProgressReader(file.Body, int(file.ContentLength), out, sf.FormatProgress("", "Downloading", "%8v/%v (%v)"), sf), path); err != nil {
<add> if err := c.Inject(utils.ProgressReader(file.Body, int(file.ContentLength), out, sf.FormatProgress("", "Downloading", "%8v/%v (%v)"), sf, true), path); err != nil {
<ide> return "", err
<ide> }
<ide> // FIXME: Handle custom repo, tag comment, author
<ide> func (srv *Server) pullImage(r *registry.Registry, out io.Writer, imgID, endpoin
<ide> return err
<ide> }
<ide> defer layer.Close()
<del> if err := srv.runtime.graph.Register(imgJSON, utils.ProgressReader(layer, imgSize, out, sf.FormatProgress(utils.TruncateID(id), "Downloading", "%8v/%v (%v)"), sf), img); err != nil {
<add> if err := srv.runtime.graph.Register(imgJSON, utils.ProgressReader(layer, imgSize, out, sf.FormatProgress(utils.TruncateID(id), "Downloading", "%8v/%v (%v)"), sf, false), img); err != nil {
<ide> return err
<ide> }
<ide> }
<ide> func (srv *Server) pushImage(r *registry.Registry, out io.Writer, remote, imgID,
<ide> }
<ide>
<ide> // Send the layer
<del> if checksum, err := r.PushImageLayerRegistry(imgData.ID, utils.ProgressReader(layerData, int(layerData.Size), out, sf.FormatProgress("", "Pushing", "%8v/%v (%v)"), sf), ep, token, jsonRaw); err != nil {
<add> if checksum, err := r.PushImageLayerRegistry(imgData.ID, utils.ProgressReader(layerData, int(layerData.Size), out, sf.FormatProgress("", "Pushing", "%8v/%v (%v)"), sf, true), ep, token, jsonRaw); err != nil {
<ide> return "", err
<ide> } else {
<ide> imgData.Checksum = checksum
<ide> func (srv *Server) ImageImport(src, repo, tag string, in io.Reader, out io.Write
<ide> if err != nil {
<ide> return err
<ide> }
<del> archive = utils.ProgressReader(resp.Body, int(resp.ContentLength), out, sf.FormatProgress("", "Importing", "%8v/%v (%v)"), sf)
<add> archive = utils.ProgressReader(resp.Body, int(resp.ContentLength), out, sf.FormatProgress("", "Importing", "%8v/%v (%v)"), sf, true)
<ide> }
<ide> img, err := srv.runtime.graph.Create(archive, nil, "Imported from "+src, "", nil)
<ide> if err != nil {
<ide><path>utils/utils.go
<ide> type progressReader struct {
<ide> lastUpdate int // How many bytes read at least update
<ide> template string // Template to print. Default "%v/%v (%v)"
<ide> sf *StreamFormatter
<add> newLine bool
<ide> }
<ide>
<ide> func (r *progressReader) Read(p []byte) (n int, err error) {
<ide> func (r *progressReader) Read(p []byte) (n int, err error) {
<ide> }
<ide> r.lastUpdate = r.readProgress
<ide> }
<add> // Send newline when complete
<add> if r.newLine && err != nil {
<add> r.output.Write(r.sf.FormatStatus("", ""))
<add> }
<ide> return read, err
<ide> }
<ide> func (r *progressReader) Close() error {
<ide> return io.ReadCloser(r.reader).Close()
<ide> }
<del>func ProgressReader(r io.ReadCloser, size int, output io.Writer, template []byte, sf *StreamFormatter) *progressReader {
<del> tpl := string(template)
<del> if tpl == "" {
<del> tpl = string(sf.FormatProgress("", "%8v/%v (%v)", ""))
<add>func ProgressReader(r io.ReadCloser, size int, output io.Writer, tpl []byte, sf *StreamFormatter, newline bool) *progressReader {
<add> return &progressReader{
<add> reader: r,
<add> output: NewWriteFlusher(output),
<add> readTotal: size,
<add> template: string(tpl),
<add> sf: sf,
<add> newLine: newline,
<ide> }
<del> return &progressReader{r, NewWriteFlusher(output), size, 0, 0, tpl, sf}
<ide> }
<ide>
<ide> // HumanDuration returns a human-readable approximation of a duration | 4 |
Python | Python | fix t5 head mask in model_parallel | 248fa1ae72f01460c76c2450d747fa1cc29d85b0 | <ide><path>src/transformers/models/t5/modeling_t5.py
<ide> def forward(
<ide> hidden_states = self.dropout(inputs_embeds)
<ide>
<ide> for i, (layer_module, past_key_value) in enumerate(zip(self.block, past_key_values)):
<add> layer_head_mask = head_mask[i]
<add> encoder_layer_head_mask = encoder_head_mask[i]
<ide> # Model parallel
<ide> if self.model_parallel:
<ide> torch.cuda.set_device(hidden_states.device)
<ide> def forward(
<ide> encoder_extended_attention_mask = encoder_extended_attention_mask.to(hidden_states.device)
<ide> if encoder_decoder_position_bias is not None:
<ide> encoder_decoder_position_bias = encoder_decoder_position_bias.to(hidden_states.device)
<del> if not (isinstance(head_mask, list) and head_mask[0] is None):
<del> head_mask = head_mask.to(hidden_states.device)
<del> if not (isinstance(encoder_head_mask, list) and encoder_head_mask[0] is None):
<del> encoder_head_mask = encoder_head_mask.to(hidden_states.device)
<add> if layer_head_mask is not None:
<add> layer_head_mask = layer_head_mask.to(hidden_states.device)
<add> if encoder_layer_head_mask is not None:
<add> encoder_layer_head_mask = encoder_layer_head_mask.to(hidden_states.device)
<ide> if output_hidden_states:
<ide> all_hidden_states = all_hidden_states + (hidden_states,)
<ide>
<ide> def forward(
<ide> encoder_hidden_states=encoder_hidden_states,
<ide> encoder_attention_mask=encoder_extended_attention_mask,
<ide> encoder_decoder_position_bias=encoder_decoder_position_bias,
<del> layer_head_mask=head_mask[i],
<del> encoder_layer_head_mask=encoder_head_mask[i] if encoder_head_mask is not None else None,
<add> layer_head_mask=layer_head_mask,
<add> encoder_layer_head_mask=encoder_layer_head_mask,
<ide> past_key_value=past_key_value,
<ide> use_cache=use_cache,
<ide> output_attentions=output_attentions, | 1 |
PHP | PHP | remove deprecation notice | 650afd814a81edeba93471f747a839d2fd35e496 | <ide><path>src/Collection/CollectionInterface.php
<ide> public function zipWith($items, $callable);
<ide> *
<ide> * @param int $chunkSize The maximum size for each chunk
<ide> * @return \Cake\Collection\CollectionInterface
<del> * @deprecated 4.0.0 Deprecated in favor of chunks
<ide> */
<ide> public function chunk($chunkSize);
<ide> | 1 |
Mixed | Java | add showsoftinputonfocus to textinput | d88e4701fc46b028861ddcfa3e6ffb141b3ede3d | <ide><path>Libraries/Components/TextInput/TextInput.js
<ide> type AndroidProps = $ReadOnly<{|
<ide> | 'yes'
<ide> | 'yesExcludeDescendants'
<ide> ),
<add> showSoftInputOnFocus?: ?boolean,
<ide> |}>;
<ide>
<ide> type Props = $ReadOnly<{|
<ide> const TextInput = createReactClass({
<ide> 'newPassword',
<ide> 'oneTimeCode',
<ide> ]),
<add> /**
<add> * When `false`, it will prevent the soft keyboard from showing when the field is focused.
<add> * Defaults to `true`.
<add> * @platform android
<add> */
<add> showSoftInputOnFocus: PropTypes.bool,
<ide> },
<ide> getDefaultProps() {
<ide> return {
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactEditText.java
<ide> public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
<ide> }
<ide> setFocusableInTouchMode(true);
<ide> boolean focused = super.requestFocus(direction, previouslyFocusedRect);
<del> showSoftKeyboard();
<add> if (getShowSoftInputOnFocus()) {
<add> showSoftKeyboard();
<add> }
<ide> return focused;
<ide> }
<ide>
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputManager.java
<ide> public void setBorderStyle(ReactEditText view, @Nullable String borderStyle) {
<ide> view.setBorderStyle(borderStyle);
<ide> }
<ide>
<add> @ReactProp(name = "showSoftInputOnFocus", defaultBoolean = true)
<add> public void showKeyboardOnFocus(ReactEditText view, boolean showKeyboardOnFocus) {
<add> view.setShowSoftInputOnFocus(showKeyboardOnFocus);
<add> }
<add>
<add>
<ide> @ReactPropGroup(names = {
<ide> ViewProps.BORDER_WIDTH,
<ide> ViewProps.BORDER_LEFT_WIDTH, | 3 |
Text | Text | add jenkins and godoc badges | 10005433eb3434d3f59ad99030591e5b1d8fc692 | <ide><path>README.md
<del>Docker: the container engine
<add>Docker: the container engine [](https://github.com/docker/docker/releases/latest)
<ide> ============================
<ide>
<ide> Docker is an open source project to pack, ship and run any application
<ide> Under the hood, Docker is built on the following components:
<ide> * The [Docker Image Specification](https://github.com/docker/docker/blob/master/image/spec/v1.md)
<ide> * The [Libcontainer Specification](https://github.com/opencontainers/runc/blob/master/libcontainer/SPEC.md)
<ide>
<del>Contributing to Docker
<add>Contributing to Docker [](https://godoc.org/github.com/docker/docker)
<ide> ======================
<ide>
<del>[](https://godoc.org/github.com/docker/docker)
<del>[](https://jenkins.dockerproject.org/job/Docker%20Master/)
<add>| **Master** (Linux) | **Experimental** (linux) | **Windows** | **FreeBSD** |
<add>|------------------|----------------------|---------|---------|
<add>| [](https://jenkins.dockerproject.org/view/Docker/job/Docker%20Master/) | [](https://jenkins.dockerproject.org/view/Docker/job/Docker%20Master%20%28experimental%29/) | [/badge/icon)](http://jenkins.dockerproject.org/job/Docker%20Master%20(windows)/) | [/badge/icon)](http://jenkins.dockerproject.org/job/Docker%20Master%20(freebsd)/) |
<ide>
<ide> Want to hack on Docker? Awesome! We have [instructions to help you get
<ide> started contributing code or documentation](https://docs.docker.com/project/who-written-for/). | 1 |
Java | Java | fix javadoc for single.flatmapobservable | 39a4e42e0aa18670e4af39c152a4dd0a74d01ad4 | <ide><path>src/main/java/io/reactivex/Single.java
<ide> public final <U> Observable<U> flattenAsObservable(final Function<? super T, ? e
<ide> }
<ide>
<ide> /**
<del> * Returns a Single that is based on applying a specified function to the item emitted by the source Single,
<del>>>>>>>> refs/remotes/akarnokd/SoloFlatMapIterable
<add> * Returns an Observable that is based on applying a specified function to the item emitted by the source Single,
<ide> * where that function returns a SingleSource.
<ide> * <p>
<ide> * <img width="640" height="300" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.flatMap.png" alt=""> | 1 |
Javascript | Javascript | fix minor grammar and typo errors in comments | 972ae4c18643535289a2e03f224911c668e5aba8 | <ide><path>Libraries/Components/MapView/MapView.js
<ide> var MapView = React.createClass({
<ide>
<ide> /**
<ide> * If `false` the user won't be able to pinch/zoom the map.
<del> * Default `value` is true.
<add> * Default value is `true`.
<ide> */
<ide> zoomEnabled: React.PropTypes.bool,
<ide>
<ide> var MapView = React.createClass({
<ide> onRegionChangeComplete: React.PropTypes.func,
<ide>
<ide> /**
<del> * Callback that is called once, when the user is clicked on a annotation.
<add> * Callback that is called once, when the user taps an annotation.
<ide> */
<ide> onAnnotationPress: React.PropTypes.func,
<ide> }, | 1 |
Go | Go | add error check after parsestorageopt | 373654f43e87a2e0bd5388ca4ab1852fd51a7199 | <ide><path>daemon/graphdriver/zfs/zfs.go
<ide> func (d *Driver) Create(id string, parent string, mountLabel string, storageOpt
<ide> func (d *Driver) create(id, parent string, storageOpt map[string]string) error {
<ide> name := d.zfsPath(id)
<ide> quota, err := parseStorageOpt(storageOpt)
<add> if err != nil {
<add> return err
<add> }
<ide> if parent == "" {
<ide> mountoptions := map[string]string{"mountpoint": "legacy"}
<ide> fs, err := zfs.CreateFilesystem(name, mountoptions) | 1 |
Text | Text | add missing tick marks | 887da7f6c5a9e7b5007f5e4af32a6b93b18c70ea | <ide><path>docs/api-guide/throttling.md
<ide> The default throttling policy may be set globally, using the `DEFAULT_THROTTLE_C
<ide>
<ide> The rate descriptions used in `DEFAULT_THROTTLE_RATES` may include `second`, `minute`, `hour` or `day` as the throttle period.
<ide>
<del>By default Django REST Framework will try to use the `HTTP_X_FORWARDED_FOR` header to uniquely identify client machines for throttling. If HTTP_X_FORWARDED_FOR is not present `REMOTE_ADDR` header value will be used.
<add>By default Django REST Framework will try to use the `HTTP_X_FORWARDED_FOR` header to uniquely identify client machines for throttling. If `HTTP_X_FORWARDED_FOR` is not present `REMOTE_ADDR` header value will be used.
<ide>
<ide> To help Django REST Framework identify unique clients the number of application proxies can be set using `NUM_PROXIES`. This setting will allow the throttle to correctly identify unique requests when there are multiple application side proxies in front of the server. `NUM_PROXIES` should be set to an integer. It is important to understand that if you configure `NUM_PROXIES > 0` all clients behind a unique [NAT'd](http://en.wikipedia.org/wiki/Network_address_translation) gateway will be treated as a single client.
<ide> | 1 |
Python | Python | fix e231 flake8 warning (x9) | ea89bec185f7acaeb4b7e5c0ee1082e541becedd | <ide><path>transformers/hf_api.py
<ide> def presign_and_upload(self, token, filename, filepath):
<ide> pf = TqdmProgressFileReader(f)
<ide> data = f if pf.total_size > 0 else ""
<ide>
<del> r = requests.put(urls.write, data=data, headers={"content-type": urls.type,})
<add> r = requests.put(urls.write, data=data, headers={"content-type": urls.type})
<ide> r.raise_for_status()
<ide> pf.close()
<ide> return urls.access
<ide><path>transformers/optimization_tf.py
<ide> def _resource_apply_sparse(self, grad, var, indices, apply_state=None):
<ide>
<ide> def get_config(self):
<ide> config = super(AdamWeightDecay, self).get_config()
<del> config.update(
<del> {"weight_decay_rate": self.weight_decay_rate,}
<del> )
<add> config.update({"weight_decay_rate": self.weight_decay_rate})
<ide> return config
<ide>
<ide> def _do_use_weight_decay(self, param_name):
<ide><path>transformers/pipelines.py
<ide> def span_to_answer(self, text: str, start: int, end: int):
<ide> "tf": TFAutoModel if is_tf_available() else None,
<ide> "pt": AutoModel if is_torch_available() else None,
<ide> "default": {
<del> "model": {"pt": "distilbert-base-uncased", "tf": "distilbert-base-uncased",},
<add> "model": {"pt": "distilbert-base-uncased", "tf": "distilbert-base-uncased"},
<ide> "config": None,
<ide> "tokenizer": "distilbert-base-uncased",
<ide> },
<ide><path>transformers/tests/model_card_test.py
<ide> def setUp(self):
<ide> },
<ide> "metrics": "BLEU and ROUGE-1",
<ide> "evaluation_data": {
<del> "Datasets": {"BLEU": "My-great-dataset-v1", "ROUGE-1": "My-short-dataset-v2.1",},
<add> "Datasets": {"BLEU": "My-great-dataset-v1", "ROUGE-1": "My-short-dataset-v2.1"},
<ide> "Preprocessing": "See details on https://arxiv.org/pdf/1810.03993.pdf",
<ide> },
<ide> "training_data": {
<ide> "Dataset": "English Wikipedia dump dated 2018-12-01",
<ide> "Preprocessing": "Using SentencePiece vocabulary of size 52k tokens. See details on https://arxiv.org/pdf/1810.03993.pdf",
<ide> },
<del> "quantitative_analyses": {"BLEU": 55.1, "ROUGE-1": 76,},
<add> "quantitative_analyses": {"BLEU": 55.1, "ROUGE-1": 76},
<ide> }
<ide>
<ide> def test_model_card_common_properties(self):
<ide><path>transformers/tokenization_ctrl.py
<ide> }
<ide>
<ide> PRETRAINED_VOCAB_FILES_MAP = {
<del> "vocab_file": {"ctrl": "https://raw.githubusercontent.com/salesforce/ctrl/master/ctrl-vocab.json",},
<del> "merges_file": {"ctrl": "https://raw.githubusercontent.com/salesforce/ctrl/master/ctrl-merges.txt",},
<add> "vocab_file": {"ctrl": "https://raw.githubusercontent.com/salesforce/ctrl/master/ctrl-vocab.json"},
<add> "merges_file": {"ctrl": "https://raw.githubusercontent.com/salesforce/ctrl/master/ctrl-merges.txt"},
<ide> }
<ide>
<ide> PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
<ide><path>transformers/tokenization_openai.py
<ide> }
<ide>
<ide> PRETRAINED_VOCAB_FILES_MAP = {
<del> "vocab_file": {"openai-gpt": "https://s3.amazonaws.com/models.huggingface.co/bert/openai-gpt-vocab.json",},
<del> "merges_file": {"openai-gpt": "https://s3.amazonaws.com/models.huggingface.co/bert/openai-gpt-merges.txt",},
<add> "vocab_file": {"openai-gpt": "https://s3.amazonaws.com/models.huggingface.co/bert/openai-gpt-vocab.json"},
<add> "merges_file": {"openai-gpt": "https://s3.amazonaws.com/models.huggingface.co/bert/openai-gpt-merges.txt"},
<ide> }
<ide>
<ide> PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = { | 6 |
PHP | PHP | fix method name | f3d3a654726a55d8b0959e136070ad80e4683a6f | <ide><path>src/Illuminate/Database/Eloquent/Model.php
<ide> public static function find($id, $columns = array('*'))
<ide> *
<ide> * @return \Illuminate\Database\Query\Builder
<ide> */
<del> public static function onWrite()
<add> public static function onWriteConnection()
<ide> {
<ide> $instance = new static;
<ide> | 1 |
Java | Java | correlate data buffers to request log messages | ad420107852bafa141dcd68120be6d6a24153bf8 | <ide><path>spring-core/src/main/java/org/springframework/core/codec/Hints.java
<ide>
<ide> import org.apache.commons.logging.Log;
<ide>
<add>import org.springframework.core.io.buffer.DataBuffer;
<add>import org.springframework.core.io.buffer.DataBufferUtils;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.CollectionUtils;
<ide>
<ide> public static Map<String, Object> merge(Map<String, Object> hints, String hintNa
<ide> }
<ide> }
<ide>
<add> /**
<add> * If the hints contain a {@link #LOG_PREFIX_HINT} and the given logger has
<add> * DEBUG level enabled, apply the log prefix as a hint to the given buffer
<add> * via {@link DataBufferUtils#touch(DataBuffer, Object)}.
<add> * @param buffer the buffer to touch
<add> * @param hints the hints map to check for a log prefix
<add> * @param logger the logger whose level to check
<add> * @since 5.3.2
<add> */
<add> public static void touchDataBuffer(DataBuffer buffer, @Nullable Map<String, Object> hints, Log logger) {
<add> if (logger.isDebugEnabled() && hints != null) {
<add> Object logPrefix = hints.get(LOG_PREFIX_HINT);
<add> if (logPrefix != null) {
<add> DataBufferUtils.touch(buffer, logPrefix);
<add> }
<add> }
<add> }
<add>
<ide> }
<ide><path>spring-core/src/main/java/org/springframework/core/codec/ResourceRegionEncoder.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2020 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> private Flux<DataBuffer> writeResourceRegion(
<ide> }
<ide>
<ide> Flux<DataBuffer> in = DataBufferUtils.read(resource, position, bufferFactory, this.bufferSize);
<add> if (logger.isDebugEnabled()) {
<add> in = in.doOnNext(buffer -> Hints.touchDataBuffer(buffer, hints, logger));
<add> }
<ide> return DataBufferUtils.takeUntilByteCount(in, count);
<ide> }
<ide>
<ide><path>spring-core/src/main/java/org/springframework/core/io/buffer/DataBufferUtils.java
<ide> public static <T extends DataBuffer> T retain(T dataBuffer) {
<ide> }
<ide> }
<ide>
<add> /**
<add> * Associate the given hint with the data buffer if it is a pooled buffer
<add> * and supports leak tracking.
<add> * @param dataBuffer the data buffer to attach the hint to
<add> * @param hint the hint to attach
<add> * @return the input buffer
<add> * @since 5.3.2
<add> */
<add> @SuppressWarnings("unchecked")
<add> public static <T extends DataBuffer> T touch(T dataBuffer, Object hint) {
<add> if (dataBuffer instanceof PooledDataBuffer) {
<add> return (T) ((PooledDataBuffer) dataBuffer).touch(hint);
<add> }
<add> else {
<add> return dataBuffer;
<add> }
<add> }
<add>
<ide> /**
<ide> * Release the given data buffer, if it is a {@link PooledDataBuffer} and
<ide> * has been {@linkplain PooledDataBuffer#isAllocated() allocated}.
<ide><path>spring-core/src/main/java/org/springframework/core/io/buffer/NettyDataBuffer.java
<ide> public PooledDataBuffer retain() {
<ide> return new NettyDataBuffer(this.byteBuf.retain(), this.dataBufferFactory);
<ide> }
<ide>
<add> @Override
<add> public PooledDataBuffer touch(Object hint) {
<add> this.byteBuf.touch(hint);
<add> return this;
<add> }
<add>
<ide> @Override
<ide> public boolean release() {
<ide> return this.byteBuf.release();
<ide><path>spring-core/src/main/java/org/springframework/core/io/buffer/PooledDataBuffer.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2020 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public interface PooledDataBuffer extends DataBuffer {
<ide> */
<ide> PooledDataBuffer retain();
<ide>
<add> /**
<add> * Associate the given hint with the data buffer for debugging purposes.
<add> * @return this buffer
<add> * @since 5.3.2
<add> */
<add> PooledDataBuffer touch(Object hint);
<add>
<ide> /**
<ide> * Decrease the reference count for this buffer by one,
<ide> * and deallocate it once the count reaches zero.
<ide><path>spring-core/src/testFixtures/java/org/springframework/core/testfixture/io/buffer/LeakAwareDataBuffer.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2020 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> package org.springframework.core.testfixture.io.buffer;
<ide>
<ide> import org.springframework.core.io.buffer.DataBuffer;
<add>import org.springframework.core.io.buffer.DataBufferUtils;
<ide> import org.springframework.core.io.buffer.DataBufferWrapper;
<ide> import org.springframework.core.io.buffer.PooledDataBuffer;
<ide> import org.springframework.util.Assert;
<ide> public boolean isAllocated() {
<ide>
<ide> @Override
<ide> public PooledDataBuffer retain() {
<del> DataBuffer delegate = dataBuffer();
<del> if (delegate instanceof PooledDataBuffer) {
<del> ((PooledDataBuffer) delegate).retain();
<del> }
<add> DataBufferUtils.retain(dataBuffer());
<add> return this;
<add> }
<add>
<add> @Override
<add> public PooledDataBuffer touch(Object hint) {
<add> DataBufferUtils.touch(dataBuffer(), hint);
<ide> return this;
<ide> }
<ide>
<ide> @Override
<ide> public boolean release() {
<del> DataBuffer delegate = dataBuffer();
<del> if (delegate instanceof PooledDataBuffer) {
<del> ((PooledDataBuffer) delegate).release();
<del> }
<add> DataBufferUtils.release(dataBuffer());
<ide> return isAllocated();
<ide> }
<ide>
<ide><path>spring-web/src/main/java/org/springframework/http/codec/EncoderHttpMessageWriter.java
<ide> */
<ide> public class EncoderHttpMessageWriter<T> implements HttpMessageWriter<T> {
<ide>
<add> private static final Log logger = HttpLogging.forLogName(EncoderHttpMessageWriter.class);
<add>
<add>
<ide> private final Encoder<T> encoder;
<ide>
<ide> private final List<MediaType> mediaTypes;
<ide> public Mono<Void> write(Publisher<? extends T> inputStream, ResolvableType eleme
<ide> return message.setComplete().then(Mono.empty());
<ide> }))
<ide> .flatMap(buffer -> {
<add> Hints.touchDataBuffer(buffer, hints, logger);
<ide> message.getHeaders().setContentLength(buffer.readableByteCount());
<ide> return message.writeWith(Mono.just(buffer)
<ide> .doOnDiscard(PooledDataBuffer.class, DataBufferUtils::release));
<ide> });
<ide> }
<ide>
<ide> if (isStreamingMediaType(contentType)) {
<del> return message.writeAndFlushWith(body.map(buffer ->
<del> Mono.just(buffer).doOnDiscard(PooledDataBuffer.class, DataBufferUtils::release)));
<add> return message.writeAndFlushWith(body.map(buffer -> {
<add> Hints.touchDataBuffer(buffer, hints, logger);
<add> return Mono.just(buffer).doOnDiscard(PooledDataBuffer.class, DataBufferUtils::release);
<add> }));
<ide> }
<ide>
<add> if (logger.isDebugEnabled()) {
<add> body = body.doOnNext(buffer -> Hints.touchDataBuffer(buffer, hints, logger));
<add> }
<ide> return message.writeWith(body);
<ide> }
<ide>
<ide> private static MediaType addDefaultCharset(MediaType main, @Nullable MediaType d
<ide> return main;
<ide> }
<ide>
<add> private static void touch(DataBuffer buffer, Map<String, Object> hints) {
<add> }
<add>
<ide> private boolean isStreamingMediaType(@Nullable MediaType mediaType) {
<ide> if (mediaType == null || !(this.encoder instanceof HttpMessageEncoder)) {
<ide> return false;
<ide><path>spring-web/src/main/java/org/springframework/http/codec/ResourceHttpMessageWriter.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2020 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> private Mono<Void> writeResource(Resource resource, ResolvableType type, @Nullab
<ide> Mono<Resource> input = Mono.just(resource);
<ide> DataBufferFactory factory = message.bufferFactory();
<ide> Flux<DataBuffer> body = this.encoder.encode(input, factory, type, resourceMediaType, hints);
<add> if (logger.isDebugEnabled()) {
<add> body = body.doOnNext(buffer -> Hints.touchDataBuffer(buffer, hints, logger));
<add> }
<ide> return message.writeWith(body);
<ide> });
<ide> }
<ide><path>spring-web/src/main/java/org/springframework/http/codec/ServerSentEventHttpMessageWriter.java
<ide> import java.util.List;
<ide> import java.util.Map;
<ide>
<add>import org.apache.commons.logging.Log;
<ide> import org.reactivestreams.Publisher;
<ide> import reactor.core.publisher.Flux;
<ide> import reactor.core.publisher.Mono;
<ide> import org.springframework.core.io.buffer.DataBufferFactory;
<ide> import org.springframework.core.io.buffer.DataBufferUtils;
<ide> import org.springframework.core.io.buffer.PooledDataBuffer;
<add>import org.springframework.http.HttpLogging;
<ide> import org.springframework.http.MediaType;
<ide> import org.springframework.http.ReactiveHttpOutputMessage;
<ide> import org.springframework.http.server.reactive.ServerHttpRequest;
<ide> public class ServerSentEventHttpMessageWriter implements HttpMessageWriter<Objec
<ide>
<ide> private static final List<MediaType> WRITABLE_MEDIA_TYPES = Collections.singletonList(MediaType.TEXT_EVENT_STREAM);
<ide>
<add> private static final Log logger = HttpLogging.forLogName(ServerSentEventHttpMessageWriter.class);
<add>
<ide>
<ide> @Nullable
<ide> private final Encoder<?> encoder;
<ide> private <T> Flux<DataBuffer> encodeEvent(StringBuilder eventContent, T data, Res
<ide> if (this.encoder == null) {
<ide> throw new CodecException("No SSE encoder configured and the data is not String.");
<ide> }
<add> DataBuffer buffer = ((Encoder<T>) this.encoder).encodeValue(data, factory, dataType, mediaType, hints);
<add> Hints.touchDataBuffer(buffer, hints, logger);
<ide> return Flux.just(factory.join(Arrays.asList(
<ide> encodeText(eventContent, mediaType, factory),
<del> ((Encoder<T>) this.encoder).encodeValue(data, factory, dataType, mediaType, hints),
<add> buffer,
<ide> encodeText("\n\n", mediaType, factory))));
<ide> }
<ide>
<ide><path>spring-web/src/main/java/org/springframework/http/codec/multipart/MultipartHttpMessageWriter.java
<ide> private Mono<Void> writeMultipart(MultiValueMap<String, ?> map,
<ide> .concatWith(generateLastLine(boundary, bufferFactory))
<ide> .doOnDiscard(PooledDataBuffer.class, DataBufferUtils::release);
<ide>
<add> if (logger.isDebugEnabled()) {
<add> body = body.doOnNext(buffer -> Hints.touchDataBuffer(buffer, hints, logger));
<add> }
<add>
<ide> return outputMessage.writeWith(body);
<ide> }
<ide>
<ide><path>spring-web/src/main/java/org/springframework/http/codec/multipart/PartHttpMessageWriter.java
<ide> public Mono<Void> write(Publisher<? extends Part> parts,
<ide> .concatWith(generateLastLine(boundary, outputMessage.bufferFactory()))
<ide> .doOnDiscard(PooledDataBuffer.class, DataBufferUtils::release);
<ide>
<add> if (logger.isDebugEnabled()) {
<add> body = body.doOnNext(buffer -> Hints.touchDataBuffer(buffer, hints, logger));
<add> }
<add>
<ide> return outputMessage.writeWith(body);
<ide> }
<ide> | 11 |
Javascript | Javascript | fix user deletion of credentials | 0f5f92b937768adf3bc29a7d4dc39f51a5d8ad43 | <ide><path>server/boot/a-extendUser.js
<ide> var Rx = require('rx');
<ide> var debug = require('debug')('freecc:user:remote');
<ide>
<del>function destroyById(id, Model) {
<del> return Rx.Observable.create(function(observer) {
<del> Model.destroyById(id, function(err) {
<del> if (err) { return observer.onError(err); }
<del> observer.onCompleted();
<del> });
<del> return Rx.Disposable(Rx.helpers.noop);
<del> });
<add>function destroyAllRelated(id, Model) {
<add> return Rx.Observable.fromNodeCallback(
<add> Model.destroyAll,
<add> Model
<add> )({ userId: id });
<ide> }
<ide>
<ide> module.exports = function(app) {
<ide> var User = app.models.User;
<ide> var UserIdentity = app.models.UserIdentity;
<ide> var UserCredential = app.models.UserCredential;
<del> User.observe('after delete', function(ctx, next) {
<add> User.observe('before delete', function(ctx, next) {
<ide> debug('removing user', ctx.where);
<ide> var id = ctx.where && ctx.where.id ? ctx.where.id : null;
<ide> if (!id) {
<ide> return next();
<ide> }
<ide> Rx.Observable.combineLatest(
<del> destroyById(id, UserIdentity),
<del> destroyById(id, UserCredential),
<del> Rx.helpers.noop
<add> destroyAllRelated(id, UserIdentity),
<add> destroyAllRelated(id, UserCredential),
<add> function(identData, credData) {
<add> return {
<add> identData: identData,
<add> credData: credData
<add> };
<add> }
<ide> ).subscribe(
<del> Rx.helpers.noop,
<add> function(data) {
<add> debug('deleted', data);
<add> },
<ide> function(err) {
<ide> debug('error deleting user %s stuff', id, err);
<ide> next(err); | 1 |
Go | Go | fix a typo in comment | d30990d7b1468488768847521a3a7ce66a081015 | <ide><path>api/client/restart.go
<ide> import (
<ide>
<ide> // CmdRestart restarts one or more running containers.
<ide> //
<del>// Usage: docker stop [OPTIONS] CONTAINER [CONTAINER...]
<add>// Usage: docker restart [OPTIONS] CONTAINER [CONTAINER...]
<ide> func (cli *DockerCli) CmdRestart(args ...string) error {
<ide> cmd := Cli.Subcmd("restart", []string{"CONTAINER [CONTAINER...]"}, "Restart a running container", true)
<ide> nSeconds := cmd.Int([]string{"t", "-time"}, 10, "Seconds to wait for stop before killing the container") | 1 |
Javascript | Javascript | update pdbloader.js with comments | 6e0892b963bfc3d0d1f1dc162804dafca2fb4f18 | <ide><path>examples/js/loaders/PDBLoader.js
<ide> */
<ide>
<ide> THREE.PDBLoader = function ( manager ) {
<del>
<add> //add your own manager or use default manager
<ide> this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
<ide>
<ide> };
<ide> THREE.PDBLoader.prototype = {
<ide> }
<ide>
<ide> function parseBond( start, length ) {
<del>
<add> /*
<add>
<add> line1 CONECT 1 2
<add> 12345678901234567890123456789001234567890
<add> Siiii)
<add> P1iii)
<add> P2iii)
<add> P3iii)
<add> P4iii)
<add> line2 CONECT 2 1 9 49
<add>
<add> satomL1 = 1, satomL2 = 2
<add> P1 = eatomL1 = 2, eatomL2_i = 1,
<add> P2 eatomL2_ii = 9
<add> P3 eatomL2_iii = 49
<add> P4
<add>
<add> hL1 = s1e2
<add> hL2 = s1e2 X, s2e9, s2e49
<add> bhash = {s1e2: 0, s2e9: 1, s2e49: 2 ...} //bond connections
<add> bonds = [ [0,1,1], [1, 8, 1], [1, 48, 1 ...]
<add>
<add>
<add> */
<add>
<ide> var eatom = parseInt( lines[ i ].substr( start, length ) );
<ide>
<ide> if ( eatom ) {
<del>
<add> //Generate Hash Key from Starting Atom and Connecting End Atom corresponding Connection
<ide> var h = hash( satom, eatom );
<del>
<add>
<add> //if already exists do not create, skip
<ide> if ( bhash[ h ] === undefined ) {
<del>
<add>
<add> //reduce satom and eatom connection by factor of 1 (single bond)
<ide> bonds.push( [ satom - 1, eatom - 1, 1 ] );
<del> bhash[ h ] = bonds.length - 1;
<add> bhash[ h ] = bonds.length - 1; //identifies bond entry in bonds[bhash[s1e2]] array (key: endpoints Index: bond)
<ide>
<ide> } else {
<ide>
<ide> // doesn't really work as almost all PDBs
<ide> // have just normal bonds appearing multiple
<ide> // times instead of being double/triple bonds
<add> //increase last entry by 1, represents multiple bond
<ide> // bonds[bhash[h]][2] += 1;
<ide>
<ide> }
<ide> THREE.PDBLoader.prototype = {
<ide> function buildGeometry() {
<ide>
<ide> var build = {
<add> /*
<add> This class is an efficient alternative to Geometry, because it stores all data,
<add> including vertex positions, face indices, normals, colors, UVs, and custom attributes
<add> within buffers; this reduces the cost of passing all this data to the GPU.
<add> */
<ide> geometryAtoms: new THREE.BufferGeometry(),
<ide> geometryBonds: new THREE.BufferGeometry(),
<ide> json: {
<ide> THREE.PDBLoader.prototype = {
<ide>
<ide> for ( i = 0, l = atoms.length; i < l; i ++ ) {
<ide>
<add> /*
<add> //Array of Atoms, Arrays consisting of 4 entries:
<add> [ [X-Coord, Y-Coord, Z-Coord, Color_Array[element_name], Element_Name], ... ]
<add>
<add> atoms.push( [ x, y, z, CPK[ e ], capitalize( e ) ] );
<add> */
<add>
<ide> var atom = atoms[ i ];
<del>
<del> var x = atom[ 0 ];
<add>
<add>
<add> var x = atom[ 0 ];
<ide> var y = atom[ 1 ];
<ide> var z = atom[ 2 ];
<del>
<add>
<add> // Array of Atoms Coord Positions
<ide> verticesAtoms.push( x, y, z );
<del>
<add>
<add>
<add> /*
<add> Generate float value representations for each color channels for use
<add> in Float32BufferAttribute for color:
<add> THREE.Float32BufferAttribute( colorsAtoms, 3 ) in
<add> geometryAtoms.addAttribute( 'color', new THREE.Float32BufferAttribute( colorsAtoms, 3 ) );
<add> where geometryAtoms is a BufferGeometry Object
<add>
<add> */
<ide> var r = atom[ 3 ][ 0 ] / 255;
<ide> var g = atom[ 3 ][ 1 ] / 255;
<ide> var b = atom[ 3 ][ 2 ] / 255;
<del>
<add>
<add> //Generate Array of Color Float32 Arrays Entries for each Atom
<ide> colorsAtoms.push( r, g, b );
<ide>
<ide> }
<ide>
<ide> // bonds
<del>
<add> /* Graphite
<add> bonds = [ [0,1,1], [1, 8, 1], [1, 48, 1 ...]
<add> */
<ide> for ( i = 0, l = bonds.length; i < l; i ++ ) {
<ide>
<ide> var bond = bonds[ i ];
<ide>
<ide> var start = bond[ 0 ];
<ide> var end = bond[ 1 ];
<add>
<add> // verticesBonds == verticesAtoms positions multiplied by factor of 3 and incremented
<add> verticesBonds.push( verticesAtoms[ ( start * 3 ) + 0 ] ); //verticesAtoms[0] -- verticesAtoms[3]
<add> verticesBonds.push( verticesAtoms[ ( start * 3 ) + 1 ] ); //verticesAtoms[1] -- verticesAtoms[4]
<add> verticesBonds.push( verticesAtoms[ ( start * 3 ) + 2 ] ); //verticesAtoms[2] -- verticesAtoms[5]
<ide>
<del> verticesBonds.push( verticesAtoms[ ( start * 3 ) + 0 ] );
<del> verticesBonds.push( verticesAtoms[ ( start * 3 ) + 1 ] );
<del> verticesBonds.push( verticesAtoms[ ( start * 3 ) + 2 ] );
<del>
<del> verticesBonds.push( verticesAtoms[ ( end * 3 ) + 0 ] );
<del> verticesBonds.push( verticesAtoms[ ( end * 3 ) + 1 ] );
<del> verticesBonds.push( verticesAtoms[ ( end * 3 ) + 2 ] );
<add> verticesBonds.push( verticesAtoms[ ( end * 3 ) + 0 ] ); //verticesAtoms[3] -- verticesAtoms[24]
<add> verticesBonds.push( verticesAtoms[ ( end * 3 ) + 1 ] ); //verticesAtoms[4] -- verticesAtoms[25]
<add> verticesBonds.push( verticesAtoms[ ( end * 3 ) + 2 ] ); //verticesAtoms[5] -- verticesAtoms[26]
<ide>
<ide> }
<ide>
<ide> // build geometry
<del>
<add>
<add>
<add> /* BufferAttribute class stores data for an attribute (such as vertex positions, face indices, normals, colors, UVs, and any custom attributes )
<add> associated with a BufferGeometry, which allows for more efficient passing of data to the GPU.
<add> */
<add>
<ide> geometryAtoms.addAttribute( 'position', new THREE.Float32BufferAttribute( verticesAtoms, 3 ) );
<ide> geometryAtoms.addAttribute( 'color', new THREE.Float32BufferAttribute( colorsAtoms, 3 ) );
<ide>
<ide> THREE.PDBLoader.prototype = {
<ide> return build;
<ide>
<ide> }
<del>
<add>
<add> /* https://en.wikipedia.org/wiki/CPK_coloring?oldformat=true
<add>
<add> CPK coloring is a popular color convention for distinguishing atoms of different chemical elements in molecular models.
<add> (CPK <== Corey, Pauling, Koltun)
<add> CPK molecular models designed by chemists Robert Corey and Linus Pauling, and improved by Walter Koltun
<add> Koltun Colors Scheme for Periodic Table:
<add> White for hydrogen
<add> Black for carbon
<add> Blue for nitrogen
<add> Red for oxygen
<add> Deep yellow for sulfur
<add> Purple for phosphorus
<add> Light, medium, medium dark, and dark green for the halogens (F, Cl, Br, I)
<add> Silver for metals (Co, Fe, Ni, Cu)
<add>
<add> */
<ide> var CPK = { h: [ 255, 255, 255 ], he: [ 217, 255, 255 ], li: [ 204, 128, 255 ], be: [ 194, 255, 0 ], b: [ 255, 181, 181 ], c: [ 144, 144, 144 ], n: [ 48, 80, 248 ], o: [ 255, 13, 13 ], f: [ 144, 224, 80 ], ne: [ 179, 227, 245 ], na: [ 171, 92, 242 ], mg: [ 138, 255, 0 ], al: [ 191, 166, 166 ], si: [ 240, 200, 160 ], p: [ 255, 128, 0 ], s: [ 255, 255, 48 ], cl: [ 31, 240, 31 ], ar: [ 128, 209, 227 ], k: [ 143, 64, 212 ], ca: [ 61, 255, 0 ], sc: [ 230, 230, 230 ], ti: [ 191, 194, 199 ], v: [ 166, 166, 171 ], cr: [ 138, 153, 199 ], mn: [ 156, 122, 199 ], fe: [ 224, 102, 51 ], co: [ 240, 144, 160 ], ni: [ 80, 208, 80 ], cu: [ 200, 128, 51 ], zn: [ 125, 128, 176 ], ga: [ 194, 143, 143 ], ge: [ 102, 143, 143 ], as: [ 189, 128, 227 ], se: [ 255, 161, 0 ], br: [ 166, 41, 41 ], kr: [ 92, 184, 209 ], rb: [ 112, 46, 176 ], sr: [ 0, 255, 0 ], y: [ 148, 255, 255 ], zr: [ 148, 224, 224 ], nb: [ 115, 194, 201 ], mo: [ 84, 181, 181 ], tc: [ 59, 158, 158 ], ru: [ 36, 143, 143 ], rh: [ 10, 125, 140 ], pd: [ 0, 105, 133 ], ag: [ 192, 192, 192 ], cd: [ 255, 217, 143 ], in: [ 166, 117, 115 ], sn: [ 102, 128, 128 ], sb: [ 158, 99, 181 ], te: [ 212, 122, 0 ], i: [ 148, 0, 148 ], xe: [ 66, 158, 176 ], cs: [ 87, 23, 143 ], ba: [ 0, 201, 0 ], la: [ 112, 212, 255 ], ce: [ 255, 255, 199 ], pr: [ 217, 255, 199 ], nd: [ 199, 255, 199 ], pm: [ 163, 255, 199 ], sm: [ 143, 255, 199 ], eu: [ 97, 255, 199 ], gd: [ 69, 255, 199 ], tb: [ 48, 255, 199 ], dy: [ 31, 255, 199 ], ho: [ 0, 255, 156 ], er: [ 0, 230, 117 ], tm: [ 0, 212, 82 ], yb: [ 0, 191, 56 ], lu: [ 0, 171, 36 ], hf: [ 77, 194, 255 ], ta: [ 77, 166, 255 ], w: [ 33, 148, 214 ], re: [ 38, 125, 171 ], os: [ 38, 102, 150 ], ir: [ 23, 84, 135 ], pt: [ 208, 208, 224 ], au: [ 255, 209, 35 ], hg: [ 184, 184, 208 ], tl: [ 166, 84, 77 ], pb: [ 87, 89, 97 ], bi: [ 158, 79, 181 ], po: [ 171, 92, 0 ], at: [ 117, 79, 69 ], rn: [ 66, 130, 150 ], fr: [ 66, 0, 102 ], ra: [ 0, 125, 0 ], ac: [ 112, 171, 250 ], th: [ 0, 186, 255 ], pa: [ 0, 161, 255 ], u: [ 0, 143, 255 ], np: [ 0, 128, 255 ], pu: [ 0, 107, 255 ], am: [ 84, 92, 242 ], cm: [ 120, 92, 227 ], bk: [ 138, 79, 227 ], cf: [ 161, 54, 212 ], es: [ 179, 31, 212 ], fm: [ 179, 31, 186 ], md: [ 179, 13, 166 ], no: [ 189, 13, 135 ], lr: [ 199, 0, 102 ], rf: [ 204, 0, 89 ], db: [ 209, 0, 79 ], sg: [ 217, 0, 69 ], bh: [ 224, 0, 56 ], hs: [ 230, 0, 46 ], mt: [ 235, 0, 38 ],
<ide> ds: [ 235, 0, 38 ], rg: [ 235, 0, 38 ], cn: [ 235, 0, 38 ], uut: [ 235, 0, 38 ], uuq: [ 235, 0, 38 ], uup: [ 235, 0, 38 ], uuh: [ 235, 0, 38 ], uus: [ 235, 0, 38 ], uuo: [ 235, 0, 38 ] };
<ide>
<ide> THREE.PDBLoader.prototype = {
<ide> var x, y, z, e;
<ide>
<ide> // parse
<del>
<add>
<add> //Decompose text into Array: (an array entry for each line)
<ide> var lines = text.split( '\n' );
<ide>
<ide> for ( var i = 0, l = lines.length; i < l; i ++ ) {
<del>
<del> if ( lines[ i ].substr( 0, 4 ) === 'ATOM' || lines[ i ].substr( 0, 6 ) === 'HETATM' ) {
<del>
<add>
<add> // extract atom coords from pdb
<add> //Also SDF file Format similar to PDB file format: http://link.fyicenter.com/out.php?ID=571
<add>
<add>
<add> /*
<add> https://www.wwpdb.org/documentation/file-format-content/format33/sect9.html#ATOM
<add>
<add> e x y z
<add> ATOM 2 C 1 -8.580 0.025 -4.537 1.00 0.00
<add> 12345678901234567890123456789012345678901234567890123456789012345678901234567890
<add> 0**4 Ei) Xiiiiii)Yiiiiii)Ziiiiii)
<add>
<add> or
<add>
<add> https://www.wwpdb.org/documentation/file-format-content/format33/sect9.html#HETATM
<add>
<add> x y z
<add> HETATM 1 C01 UNK A 1 -10.447 3.465 0.000 0.00 0.00 0
<add> 12345678901234567890123456789012345678901234567890123456789012345678901234567890
<add> 0****6 Xiiiiii)Yiiiiii)Ziiiiii)
<add>
<add> */
<add>
<add> if ( lines[ i ].substr( 0, 4 ) === 'ATOM' || lines[ i ].substr( 0, 6 ) === 'HETATM' ) {
<add>
<add> //extract x,y,z coord for each atom from pdb file extracted lines
<add> //extract values from locations for each coord
<ide> x = parseFloat( lines[ i ].substr( 30, 7 ) );
<ide> y = parseFloat( lines[ i ].substr( 38, 7 ) );
<ide> z = parseFloat( lines[ i ].substr( 46, 7 ) );
<ide>
<add> //If long line extract Chemistry Element from near the end of line
<ide> e = trim( lines[ i ].substr( 76, 2 ) ).toLowerCase();
<del>
<add>
<add> //If not a long line extract the Chemistry from near the beginning of line
<ide> if ( e === '' ) {
<del>
<add> //extract first 2 characters of Chemical Element Name
<add> /*
<add> e
<add> ATOM 2 C 1 -8.580 0.025 -4.537 1.00 0.00
<add> 1234567890123567890123567890123567890123567890123567890123567890123567890
<add> 0**4 E i)
<add> */
<ide> e = trim( lines[ i ].substr( 12, 2 ) ).toLowerCase();
<ide>
<ide> }
<del>
<add>
<add> //add atoms to atoms array
<ide> atoms.push( [ x, y, z, CPK[ e ], capitalize( e ) ] );
<del>
<add>
<add> //create histogram
<ide> if ( histogram[ e ] === undefined ) {
<ide>
<ide> histogram[ e ] = 1;
<ide> THREE.PDBLoader.prototype = {
<ide> }
<ide>
<ide> } else if ( lines[ i ].substr( 0, 6 ) === 'CONECT' ) {
<del>
<add> /*
<add> https://www.wwpdb.org/documentation/file-format-content/format33/sect10.html#CONECT
<add>
<add> The CONECT records specify connectivity between atoms for which coordinates are supplied.
<add>
<add> CONECT 1 2
<add> 12345678901234567890123456789001234567890
<add> Siiii)
<add> Piiii)
<add> Piiii)
<add> Piiii)
<add> Piiii)
<add> CONECT 2 1 9 49
<add> CONECT 3 4
<add>
<add> */
<add>
<add> //Extract Bonds per line
<add> //Get the 1st atom_serial_num per line & convert String Representation to Int
<ide> var satom = parseInt( lines[ i ].substr( 6, 5 ) );
<ide>
<ide> parseBond( 11, 5 ); | 1 |
PHP | PHP | add macroable trait to filesystem adapter | 943ed618870ad525824693d2dc9a0db1a20c36d0 | <ide><path>src/Illuminate/Filesystem/FilesystemAdapter.php
<ide> use Illuminate\Support\Arr;
<ide> use Illuminate\Support\Collection;
<ide> use Illuminate\Support\Str;
<add>use Illuminate\Support\Traits\Macroable;
<ide> use InvalidArgumentException;
<ide> use League\Flysystem\Adapter\Ftp;
<ide> use League\Flysystem\Adapter\Local as LocalAdapter;
<ide> */
<ide> class FilesystemAdapter implements CloudFilesystemContract
<ide> {
<add> use Macroable {
<add> __call as macroCall;
<add> }
<add>
<ide> /**
<ide> * The Flysystem filesystem implementation.
<ide> *
<ide> protected function parseVisibility($visibility)
<ide> */
<ide> public function __call($method, array $parameters)
<ide> {
<add> if (static::hasMacro($method)) {
<add> return $this->macroCall($method, $parameters);
<add> }
<add>
<ide> return $this->driver->{$method}(...array_values($parameters));
<ide> }
<ide> }
<ide><path>tests/Filesystem/FilesystemAdapterTest.php
<ide> public function testPutFileWithAbsoluteFilePath()
<ide> 'uploaded file content'
<ide> );
<ide> }
<add>
<add> public function testMacroable()
<add> {
<add> $this->filesystem->write('foo.txt', 'Hello World');
<add>
<add> $filesystemAdapter = new FilesystemAdapter($this->filesystem);
<add> $filesystemAdapter->macro('getFoo', function () {
<add> return $this->get('foo.txt');
<add> });
<add>
<add> $this->assertSame('Hello World', $filesystemAdapter->getFoo());
<add> }
<ide> } | 2 |
Javascript | Javascript | make isstackoverflowerror() engine-agnostic | cd5f353405842329fc44d25d677735a8538d6c43 | <ide><path>lib/internal/errors.js
<ide> function dnsException(err, syscall, hostname) {
<ide> return ex;
<ide> }
<ide>
<del>let MAX_STACK_MESSAGE;
<add>let maxStack_ErrorName;
<add>let maxStack_ErrorMessage;
<ide> /**
<del> * Returns true if `err` is a `RangeError` with an engine-specific message.
<add> * Returns true if `err.name` and `err.message` are equal to engine-specific
<add> * values indicating max call stack size has been exceeded.
<ide> * "Maximum call stack size exceeded" in V8.
<ide> *
<ide> * @param {Error} err
<ide> * @returns {boolean}
<ide> */
<ide> function isStackOverflowError(err) {
<del> if (MAX_STACK_MESSAGE === undefined) {
<add> if (maxStack_ErrorMessage === undefined) {
<ide> try {
<ide> function overflowStack() { overflowStack(); }
<ide> overflowStack();
<ide> } catch (err) {
<del> MAX_STACK_MESSAGE = err.message;
<add> maxStack_ErrorMessage = err.message;
<add> maxStack_ErrorName = err.name;
<ide> }
<ide> }
<ide>
<del> return err.name === 'RangeError' && err.message === MAX_STACK_MESSAGE;
<add> return err.name === maxStack_ErrorName &&
<add> err.message === maxStack_ErrorMessage;
<ide> }
<ide>
<ide> module.exports = exports = { | 1 |
Python | Python | fix flax examples tests | 75ae287aecf20a37c232a41e25443a3421a8b5e2 | <ide><path>examples/flax/question-answering/run_qa.py
<ide> import transformers
<ide> from flax import struct, traverse_util
<ide> from flax.jax_utils import replicate, unreplicate
<del>from flax.metrics import tensorboard
<ide> from flax.training import train_state
<ide> from flax.training.common_utils import get_metrics, onehot, shard
<ide> from huggingface_hub import Repository
<ide> HfArgumentParser,
<ide> PreTrainedTokenizerFast,
<ide> TrainingArguments,
<add> is_tensorboard_available,
<ide> )
<ide> from transformers.file_utils import get_full_repo_name
<ide> from transformers.utils import check_min_version
<ide> def create_and_fill_np_array(start_or_end_logits, dataset, max_len):
<ide> logger.info(f"Sample {index} of the training set: {train_dataset[index]}.")
<ide>
<ide> # Define a summary writer
<del> summary_writer = tensorboard.SummaryWriter(training_args.output_dir)
<del> summary_writer.hparams({**training_args.to_dict(), **vars(model_args), **vars(data_args)})
<add> has_tensorboard = is_tensorboard_available()
<add> if has_tensorboard and jax.process_index() == 0:
<add> try:
<add> from flax.metrics.tensorboard import SummaryWriter
<add>
<add> summary_writer = SummaryWriter(training_args.output_dir)
<add> summary_writer.hparams({**training_args.to_dict(), **vars(model_args), **vars(data_args)})
<add> except ImportError as ie:
<add> has_tensorboard = False
<add> logger.warning(
<add> f"Unable to display metrics through TensorBoard because some package are not installed: {ie}"
<add> )
<add> else:
<add> logger.warning(
<add> "Unable to display metrics through TensorBoard because the package is not installed: "
<add> "Please run pip install tensorboard to enable."
<add> )
<ide>
<ide> def write_train_metric(summary_writer, train_metrics, train_time, step):
<ide> summary_writer.scalar("train_time", train_time, step)
<ide> def eval_step(state, batch):
<ide> # Save metrics
<ide> train_metric = unreplicate(train_metric)
<ide> train_time += time.time() - train_start
<del> if jax.process_index() == 0:
<add> if has_tensorboard and jax.process_index() == 0:
<ide> write_train_metric(summary_writer, train_metrics, train_time, cur_step)
<ide>
<ide> epochs.write(
<ide> def eval_step(state, batch):
<ide>
<ide> logger.info(f"Step... ({cur_step}/{total_steps} | Evaluation metrics: {eval_metrics})")
<ide>
<del> if jax.process_index() == 0:
<add> if has_tensorboard and jax.process_index() == 0:
<ide> write_eval_metric(summary_writer, eval_metrics, cur_step)
<ide>
<ide> if (cur_step % training_args.save_steps == 0 and cur_step > 0) or (cur_step == total_steps):
<ide><path>examples/flax/test_examples.py
<ide> def test_run_glue(self):
<ide> result = get_results(tmp_dir)
<ide> self.assertGreaterEqual(result["eval_accuracy"], 0.75)
<ide>
<add> @slow
<ide> def test_run_clm(self):
<ide> stream_handler = logging.StreamHandler(sys.stdout)
<ide> logger.addHandler(stream_handler)
<ide> def test_run_summarization(self):
<ide> self.assertGreaterEqual(result["test_rougeL"], 7)
<ide> self.assertGreaterEqual(result["test_rougeLsum"], 7)
<ide>
<add> @slow
<ide> def test_run_mlm(self):
<ide> stream_handler = logging.StreamHandler(sys.stdout)
<ide> logger.addHandler(stream_handler)
<ide> def test_run_t5_mlm(self):
<ide> result = get_results(tmp_dir)
<ide> self.assertGreaterEqual(result["eval_accuracy"], 0.42)
<ide>
<add> @slow
<ide> def test_run_ner(self):
<ide> stream_handler = logging.StreamHandler(sys.stdout)
<ide> logger.addHandler(stream_handler)
<ide> def test_run_ner(self):
<ide> self.assertGreaterEqual(result["eval_accuracy"], 0.75)
<ide> self.assertGreaterEqual(result["eval_f1"], 0.3)
<ide>
<add> @slow
<ide> def test_run_qa(self):
<ide> stream_handler = logging.StreamHandler(sys.stdout)
<ide> logger.addHandler(stream_handler)
<ide><path>examples/flax/text-classification/run_flax_glue.py
<ide> import transformers
<ide> from flax import struct, traverse_util
<ide> from flax.jax_utils import replicate, unreplicate
<del>from flax.metrics import tensorboard
<ide> from flax.training import train_state
<ide> from flax.training.common_utils import get_metrics, onehot, shard
<ide> from huggingface_hub import Repository
<del>from transformers import AutoConfig, AutoTokenizer, FlaxAutoModelForSequenceClassification, PretrainedConfig
<add>from transformers import (
<add> AutoConfig,
<add> AutoTokenizer,
<add> FlaxAutoModelForSequenceClassification,
<add> PretrainedConfig,
<add> is_tensorboard_available,
<add>)
<ide> from transformers.file_utils import get_full_repo_name
<ide>
<ide>
<ide> def preprocess_function(examples):
<ide> logger.info(f"Sample {index} of the training set: {train_dataset[index]}.")
<ide>
<ide> # Define a summary writer
<del> summary_writer = tensorboard.SummaryWriter(args.output_dir)
<del> summary_writer.hparams(vars(args))
<add> has_tensorboard = is_tensorboard_available()
<add> if has_tensorboard and jax.process_index() == 0:
<add> try:
<add> from flax.metrics.tensorboard import SummaryWriter
<add>
<add> summary_writer = SummaryWriter(args.output_dir)
<add> summary_writer.hparams(vars(args))
<add> except ImportError as ie:
<add> has_tensorboard = False
<add> logger.warning(
<add> f"Unable to display metrics through TensorBoard because some package are not installed: {ie}"
<add> )
<add> else:
<add> logger.warning(
<add> "Unable to display metrics through TensorBoard because the package is not installed: "
<add> "Please run pip install tensorboard to enable."
<add> )
<ide>
<ide> def write_metric(train_metrics, eval_metrics, train_time, step):
<ide> summary_writer.scalar("train_time", train_time, step)
<ide> def eval_step(state, batch):
<ide> logger.info(f" Done! Eval metrics: {eval_metric}")
<ide>
<ide> cur_step = epoch * (len(train_dataset) // train_batch_size)
<del> write_metric(train_metrics, eval_metric, train_time, cur_step)
<add>
<add> # Save metrics
<add> if has_tensorboard and jax.process_index() == 0:
<add> write_metric(train_metrics, eval_metric, train_time, cur_step)
<ide>
<ide> # save checkpoint after each epoch and push checkpoint to the hub
<ide> if jax.process_index() == 0:
<ide><path>examples/flax/token-classification/run_flax_ner.py
<ide> import transformers
<ide> from flax import struct, traverse_util
<ide> from flax.jax_utils import replicate, unreplicate
<del>from flax.metrics import tensorboard
<ide> from flax.training import train_state
<ide> from flax.training.common_utils import get_metrics, onehot, shard
<ide> from huggingface_hub import Repository
<ide> FlaxAutoModelForTokenClassification,
<ide> HfArgumentParser,
<ide> TrainingArguments,
<add> is_tensorboard_available,
<ide> )
<ide> from transformers.file_utils import get_full_repo_name
<ide> from transformers.utils import check_min_version
<ide> def tokenize_and_align_labels(examples):
<ide> logger.info(f"Sample {index} of the training set: {train_dataset[index]}.")
<ide>
<ide> # Define a summary writer
<del> summary_writer = tensorboard.SummaryWriter(training_args.output_dir)
<del> summary_writer.hparams({**training_args.to_dict(), **vars(model_args), **vars(data_args)})
<add> has_tensorboard = is_tensorboard_available()
<add> if has_tensorboard and jax.process_index() == 0:
<add> try:
<add> from flax.metrics.tensorboard import SummaryWriter
<add>
<add> summary_writer = SummaryWriter(training_args.output_dir)
<add> summary_writer.hparams({**training_args.to_dict(), **vars(model_args), **vars(data_args)})
<add> except ImportError as ie:
<add> has_tensorboard = False
<add> logger.warning(
<add> f"Unable to display metrics through TensorBoard because some package are not installed: {ie}"
<add> )
<add> else:
<add> logger.warning(
<add> "Unable to display metrics through TensorBoard because the package is not installed: "
<add> "Please run pip install tensorboard to enable."
<add> )
<ide>
<ide> def write_train_metric(summary_writer, train_metrics, train_time, step):
<ide> summary_writer.scalar("train_time", train_time, step)
<ide> def compute_metrics():
<ide> # Save metrics
<ide> train_metric = unreplicate(train_metric)
<ide> train_time += time.time() - train_start
<del> if jax.process_index() == 0:
<add> if has_tensorboard and jax.process_index() == 0:
<ide> write_train_metric(summary_writer, train_metrics, train_time, cur_step)
<ide>
<ide> epochs.write(
<ide> def compute_metrics():
<ide> f"Step... ({cur_step}/{total_steps} | Validation f1: {eval_metrics['f1']}, Validation Acc: {eval_metrics['accuracy']})"
<ide> )
<ide>
<del> if jax.process_index() == 0:
<add> if has_tensorboard and jax.process_index() == 0:
<ide> write_eval_metric(summary_writer, eval_metrics, cur_step)
<ide>
<ide> if (cur_step % training_args.save_steps == 0 and cur_step > 0) or (cur_step == total_steps):
<ide><path>utils/tests_fetcher.py
<ide> def infer_tests_to_run(output_file, diff_with_last_commit=False, filters=None):
<ide> # Example files are tested separately
<ide> elif f.startswith("examples/pytorch"):
<ide> test_files_to_run.append("examples/pytorch/test_examples.py")
<add> elif f.startswith("examples/flax"):
<add> test_files_to_run.append("examples/flax/test_examples.py")
<ide> else:
<ide> new_tests = module_to_test_file(f)
<ide> if new_tests is not None: | 5 |
Ruby | Ruby | use $stderr for debug and errors | 604323e641ccd0b125716f4a337b1f9384236716 | <ide><path>Library/brew.rb
<ide> def require?(path)
<ide> if empty_argv || (help_flag && (cmd.nil? || internal_cmd))
<ide> # TODO: - `brew help cmd` should display subcommand help
<ide> require "cmd/help"
<del> puts ARGV.usage
<add> if empty_argv
<add> $stderr.puts ARGV.usage
<add> else
<add> puts ARGV.usage
<add> end
<ide> exit ARGV.any? ? 0 : 1
<ide> end
<ide>
<ide> def require?(path)
<ide> abort ARGV.usage
<ide> rescue SystemExit => e
<ide> onoe "Kernel.exit" if ARGV.verbose? && !e.success?
<del> puts e.backtrace if ARGV.debug?
<add> $stderr.puts e.backtrace if ARGV.debug?
<ide> raise
<ide> rescue Interrupt => e
<del> puts # seemingly a newline is typical
<add> $stderr.puts # seemingly a newline is typical
<ide> exit 130
<ide> rescue BuildError => e
<ide> e.dump
<ide> exit 1
<ide> rescue RuntimeError, SystemCallError => e
<ide> raise if e.message.empty?
<ide> onoe e
<del> puts e.backtrace if ARGV.debug?
<add> $stderr.puts e.backtrace if ARGV.debug?
<ide> exit 1
<ide> rescue Exception => e
<ide> onoe e
<ide> if internal_cmd
<del> puts "#{Tty.white}Please report this bug:"
<del> puts " #{Tty.em}#{OS::ISSUES_URL}#{Tty.reset}"
<add> $stderr.puts "#{Tty.white}Please report this bug:"
<add> $stderr.puts " #{Tty.em}#{OS::ISSUES_URL}#{Tty.reset}"
<ide> end
<del> puts e.backtrace
<add> $stderr.puts e.backtrace
<ide> exit 1
<ide> else
<ide> exit 1 if Homebrew.failed? | 1 |
Text | Text | fix typo in doc at /set-up-dev-env | dd6f988b23b56ce0ca17ab892143db53f1fa2f84 | <ide><path>docs/sources/project/set-up-dev-env.md
<ide> with the `make.sh` script.
<ide> root@5f8630b873fe:/go/src/github.com/docker/docker# docker --version
<ide> Docker version 1.5.0-dev, build 6e728fb
<ide>
<del> Inside the container you are running a development version. This is version
<del> on the current branch it reflects the value of the `VERSION` file at the
<add> Inside the container you are running a development version. This is the version
<add> on the current branch. It reflects the value of the `VERSION` file at the
<ide> root of your `docker-fork` repository.
<ide>
<ide> 8. Start a `docker` daemon running inside your container. | 1 |
PHP | PHP | remove comment from duplicate bootstrap instance | c170d0dc38dd17ed8451177b23fba4968b610c1e | <ide><path>resources/views/app.blade.php
<ide> <meta name="viewport" content="width=device-width, initial-scale=1">
<ide> <title>Laravel</title>
<ide>
<del> <!-- Bootstrap -->
<ide> <link href="/css/app.css" rel="stylesheet">
<ide>
<ide> <!-- Fonts --> | 1 |
PHP | PHP | remove unused objects | 475ef7e3b9ed7938c0404a6ef962a45f445f0fb0 | <ide><path>tests/TestCase/View/ViewTest.php
<ide> public function tearDown()
<ide> */
<ide> public function testGetTemplate()
<ide> {
<del> $request = $this->getMockBuilder('Cake\Http\ServerRequest')->getMock();
<del> $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
<del>
<ide> $viewOptions = [
<ide> 'plugin' => null,
<ide> 'name' => 'Pages',
<ide> 'viewPath' => 'Pages'
<ide> ];
<del> $request->action = 'display';
<del> $request->params['pass'] = ['home'];
<ide>
<ide> $ThemeView = new TestView(null, null, null, $viewOptions);
<ide> $ThemeView->theme = 'TestTheme';
<ide> public function testPluginGetTemplate()
<ide> public function testPluginGetTemplateAbsoluteFail()
<ide> {
<ide> $this->expectException(\Cake\View\Exception\MissingTemplateException::class);
<del> $request = $this->getMockBuilder('Cake\Http\ServerRequest')->getMock();
<del> $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
<del>
<ide> $viewOptions = [
<ide> 'plugin' => null,
<ide> 'name' => 'Pages',
<ide> 'viewPath' => 'Pages'
<ide> ];
<del> $request->action = 'display';
<del> $request->params['pass'] = ['home'];
<ide>
<ide> $view = new TestView(null, null, null, $viewOptions);
<ide> $expected = TEST_APP . 'Plugin' . DS . 'Company' . DS . 'TestPluginThree' . DS . 'src' . DS . 'Template' . DS . 'Pages' . DS . 'index.ctp'; | 1 |
Javascript | Javascript | add js error to animatedvalue constructor | a3aaa471eca58b31597b9a0669f7ade385ccb175 | <ide><path>Libraries/Animated/src/nodes/AnimatedValue.js
<ide> class AnimatedValue extends AnimatedWithChildren {
<ide>
<ide> constructor(value: number) {
<ide> super();
<add> if (typeof value !== 'number') {
<add> throw new Error('AnimatedValue: Attempting to set value to undefined');
<add> }
<ide> this._startingValue = this._value = value;
<ide> this._offset = 0;
<ide> this._animation = null;
<ide> class AnimatedValue extends AnimatedWithChildren {
<ide>
<ide> _updateValue(value: number, flush: boolean): void {
<ide> if (value === undefined) {
<del> throw new Error('Attempting to set value to undefined');
<add> throw new Error('AnimatedValue: Attempting to set value to undefined');
<ide> }
<ide>
<ide> this._value = value; | 1 |
Javascript | Javascript | remove the support of json parsing mode | 1d37239eaf18d46d76f510eec22fade8c250550e | <ide><path>src/ng/parse.js
<ide> Lexer.prototype = {
<ide>
<ide> this.tokens = [];
<ide>
<del> var token;
<del> var json = [];
<del>
<ide> while (this.index < this.text.length) {
<ide> this.ch = this.text.charAt(this.index);
<ide> if (this.is('"\'')) {
<ide> Lexer.prototype = {
<ide> this.readNumber();
<ide> } else if (this.isIdent(this.ch)) {
<ide> this.readIdent();
<del> // identifiers can only be if the preceding char was a { or ,
<del> if (this.was('{,') && json[0] === '{' &&
<del> (token = this.tokens[this.tokens.length - 1])) {
<del> token.json = token.text.indexOf('.') === -1;
<del> }
<ide> } else if (this.is('(){}[].,;:?')) {
<ide> this.tokens.push({
<ide> index: this.index,
<del> text: this.ch,
<del> json: (this.was(':[,') && this.is('{[')) || this.is('}]:,')
<add> text: this.ch
<ide> });
<del> if (this.is('{[')) json.unshift(this.ch);
<del> if (this.is('}]')) json.shift();
<ide> this.index++;
<ide> } else if (this.isWhitespace(this.ch)) {
<ide> this.index++;
<ide> Lexer.prototype = {
<ide> this.tokens.push({
<ide> index: this.index,
<ide> text: this.ch,
<del> fn: fn,
<del> json: (this.was('[,:') && this.is('+-'))
<add> fn: fn
<ide> });
<ide> this.index += 1;
<ide> } else {
<ide> Lexer.prototype = {
<ide> this.tokens.push({
<ide> index: start,
<ide> text: number,
<del> json: true,
<add> literal: true,
<add> constant: true,
<ide> fn: function() { return number; }
<ide> });
<ide> },
<ide> Lexer.prototype = {
<ide> // OPERATORS is our own object so we don't need to use special hasOwnPropertyFn
<ide> if (OPERATORS.hasOwnProperty(ident)) {
<ide> token.fn = OPERATORS[ident];
<del> token.json = OPERATORS[ident];
<add> token.literal = true;
<add> token.constant = true;
<ide> } else {
<ide> var getter = getterFn(ident, this.options, this.text);
<ide> token.fn = extend(function(self, locals) {
<ide> Lexer.prototype = {
<ide> if (methodName) {
<ide> this.tokens.push({
<ide> index:lastDot,
<del> text: '.',
<del> json: false
<add> text: '.'
<ide> });
<ide> this.tokens.push({
<ide> index: lastDot + 1,
<del> text: methodName,
<del> json: false
<add> text: methodName
<ide> });
<ide> }
<ide> },
<ide> Lexer.prototype = {
<ide> index: start,
<ide> text: rawString,
<ide> string: string,
<del> json: true,
<add> literal: true,
<add> constant: true,
<ide> fn: function() { return string; }
<ide> });
<ide> return;
<ide> Parser.ZERO = extend(function () {
<ide> Parser.prototype = {
<ide> constructor: Parser,
<ide>
<del> parse: function (text, json) {
<add> parse: function (text) {
<ide> this.text = text;
<ide>
<del> //TODO(i): strip all the obsolte json stuff from this file
<del> this.json = json;
<del>
<ide> this.tokens = this.lexer.lex(text);
<ide>
<del> if (json) {
<del> // The extra level of aliasing is here, just in case the lexer misses something, so that
<del> // we prevent any accidental execution in JSON.
<del> this.assignment = this.logicalOR;
<del>
<del> this.functionCall =
<del> this.fieldAccess =
<del> this.objectIndex =
<del> this.filterChain = function() {
<del> this.throwError('is not valid json', {text: text, index: 0});
<del> };
<del> }
<del>
<del> var value = json ? this.primary() : this.statements();
<add> var value = this.statements();
<ide>
<ide> if (this.tokens.length !== 0) {
<ide> this.throwError('is an unexpected token', this.tokens[0]);
<ide> Parser.prototype = {
<ide> if (!primary) {
<ide> this.throwError('not a primary expression', token);
<ide> }
<del> if (token.json) {
<del> primary.constant = true;
<del> primary.literal = true;
<del> }
<add> primary.literal = !!token.literal;
<add> primary.constant = !!token.constant;
<ide> }
<ide>
<ide> var next, context;
<ide> Parser.prototype = {
<ide> expect: function(e1, e2, e3, e4){
<ide> var token = this.peek(e1, e2, e3, e4);
<ide> if (token) {
<del> if (this.json && !token.json) {
<del> this.throwError('is not valid json', token);
<del> }
<ide> this.tokens.shift();
<ide> return token;
<ide> }
<ide> function $ParseProvider() {
<ide>
<ide> var lexer = new Lexer($parseOptions);
<ide> var parser = new Parser(lexer, $filter, $parseOptions);
<del> parsedExpression = parser.parse(exp, false);
<add> parsedExpression = parser.parse(exp);
<ide>
<ide> if (exp !== 'hasOwnProperty') {
<ide> // Only cache the value if it's not going to mess up the cache object | 1 |
Ruby | Ruby | remove deprecation warnings from action pack | 6c57177f2c7f4f934716d588545902d5fc00fa99 | <ide><path>actionpack/lib/action_dispatch/middleware/show_exceptions.rb
<ide> class ShowExceptions
<ide> "application's log file and/or the web server's log file to find out what " <<
<ide> "went wrong.</body></html>"]]
<ide>
<del> class << self
<del> def rescue_responses
<del> ActiveSupport::Deprecation.warn "ActionDispatch::ShowExceptions.rescue_responses is deprecated. " \
<del> "Please configure your exceptions using a railtie or in your application config instead."
<del> ExceptionWrapper.rescue_responses
<del> end
<del>
<del> def rescue_templates
<del> ActiveSupport::Deprecation.warn "ActionDispatch::ShowExceptions.rescue_templates is deprecated. " \
<del> "Please configure your exceptions using a railtie or in your application config instead."
<del> ExceptionWrapper.rescue_templates
<del> end
<del> end
<del>
<del> def initialize(app, exceptions_app = nil)
<del> if [true, false].include?(exceptions_app)
<del> ActiveSupport::Deprecation.warn "Passing consider_all_requests_local option to ActionDispatch::ShowExceptions middleware no longer works"
<del> exceptions_app = nil
<del> end
<del>
<del> if exceptions_app.nil?
<del> raise ArgumentError, "You need to pass an exceptions_app when initializing ActionDispatch::ShowExceptions. " \
<del> "In case you want to render pages from a public path, you can use ActionDispatch::PublicExceptions.new('path/to/public')"
<del> end
<del>
<add> def initialize(app, exceptions_app)
<ide> @app = app
<ide> @exceptions_app = exceptions_app
<ide> end
<ide><path>actionpack/lib/action_dispatch/routing/redirection.rb
<ide> def redirect(*args, &block)
<ide> } if String === path
<ide>
<ide> block = path if path.respond_to? :call
<del>
<del> # :FIXME: remove in Rails 4.0
<del> if block && block.respond_to?(:arity) && block.arity < 2
<del> msg = "redirect blocks with arity of #{block.arity} are deprecated. Your block must take 2 parameters: the environment, and a request object"
<del> ActiveSupport::Deprecation.warn msg
<del> block = lambda { |params, _| block.call(params) }
<del> end
<del>
<ide> raise ArgumentError, "redirection argument not supported" unless block
<del>
<ide> Redirect.new status, block
<ide> end
<ide> end
<ide><path>actionpack/lib/action_view/helpers/asset_paths.rb
<del>ActiveSupport::Deprecation.warn "ActionView::Helpers::AssetPaths is deprecated. Please use ActionView::AssetPaths instead."
<del>
<del>module ActionView
<del> module Helpers
<del> AssetPaths = ::ActionView::AssetPaths
<del> end
<del>end
<ide>\ No newline at end of file
<ide><path>actionpack/lib/action_view/lookup_context.rb
<ide> def detail_args_for(options)
<ide> # as well as incorrectly putting part of the path in the template
<ide> # name instead of the prefix.
<ide> def normalize_name(name, prefixes) #:nodoc:
<del> name = name.to_s.sub(handlers_regexp) do |match|
<del> ActiveSupport::Deprecation.warn "Passing a template handler in the template name is deprecated. " \
<del> "You can simply remove the handler name or pass render :handlers => [:#{match[1..-1]}] instead.", caller
<del> ""
<del> end
<del>
<ide> prefixes = nil if prefixes.blank?
<del> parts = name.split('/')
<add> parts = name.to_s.split('/')
<ide> name = parts.pop
<ide>
<ide> return name, prefixes || [""] if parts.empty?
<ide> def normalize_name(name, prefixes) #:nodoc:
<ide>
<ide> return name, prefixes
<ide> end
<del>
<del> def handlers_regexp #:nodoc:
<del> @@handlers_regexp ||= /\.(?:#{default_handlers.join('|')})$/
<del> end
<ide> end
<ide>
<ide> include Accessors
<ide><path>actionpack/lib/action_view/renderer/abstract_renderer.rb
<ide> def extract_details(options)
<ide> details
<ide> end
<ide>
<del> def extract_format(value, details)
<del> if value.is_a?(String) && value.sub!(formats_regexp, "")
<del> ActiveSupport::Deprecation.warn "Passing the format in the template name is deprecated. " \
<del> "Please pass render with :formats => [:#{$1}] instead.", caller
<del> details[:formats] ||= [$1.to_sym]
<del> end
<del> end
<del>
<del> def formats_regexp
<del> @@formats_regexp ||= /\.(#{Mime::SET.symbols.join('|')})$/
<del> end
<del>
<ide> def instrument(name, options={})
<ide> ActiveSupport::Notifications.instrument("render_#{name}.action_view", options){ yield }
<ide> end
<ide><path>actionpack/lib/action_view/renderer/partial_renderer.rb
<ide> def setup(context, options, block)
<ide> "and is followed by any combinations of letters, numbers, or underscores.")
<ide> end
<ide>
<del> extract_format(@path, @details)
<ide> self
<ide> end
<ide>
<ide> def partial_path(object = @object)
<ide> path = if object.respond_to?(:to_partial_path)
<ide> object.to_partial_path
<ide> else
<del> klass = object.class
<del> if klass.respond_to?(:model_name)
<del> ActiveSupport::Deprecation.warn "ActiveModel-compatible objects whose classes return a #model_name that responds to #partial_path are deprecated. Please respond to #to_partial_path directly instead."
<del> klass.model_name.partial_path
<del> else
<del> raise ArgumentError.new("'#{object.inspect}' is not an ActiveModel-compatible object that returns a valid partial path.")
<del> end
<add> raise ArgumentError.new("'#{object.inspect}' is not an ActiveModel-compatible object. It must implement :to_partial_path.")
<ide> end
<ide>
<ide> @partial_names[path] ||= merge_prefix_into_object_path(@context_prefix, path.dup)
<ide><path>actionpack/lib/action_view/renderer/template_renderer.rb
<ide> class TemplateRenderer < AbstractRenderer #:nodoc:
<ide> def render(context, options)
<ide> @view = context
<ide> @details = extract_details(options)
<del> extract_format(options[:file] || options[:template], @details)
<ide> template = determine_template(options)
<ide> freeze_formats(template.formats, true)
<ide> render_template(template, options[:layout], options[:locals])
<ide><path>actionpack/test/controller/render_test.rb
<ide> def hello_world
<ide> end
<ide>
<ide> def hello_world_file
<del> render :file => File.expand_path("../../fixtures/hello.html", __FILE__)
<add> render :file => File.expand_path("../../fixtures/hello", __FILE__), :formats => [:html]
<ide> end
<ide>
<ide> def conditional_hello
<ide> def test_render_file_with_instance_variables
<ide> end
<ide>
<ide> def test_render_file
<del> assert_deprecated do
<del> get :hello_world_file
<del> end
<add> get :hello_world_file
<ide> assert_equal "Hello world!", @response.body
<ide> end
<ide>
<ide><path>actionpack/test/template/render_test.rb
<ide> def test_render_partial_with_incompatible_object
<ide> @view.render(:partial => nil)
<ide> flunk "Render did not raise ArgumentError"
<ide> rescue ArgumentError => e
<del> assert_equal "'#{nil.inspect}' is not an ActiveModel-compatible object that returns a valid partial path.", e.message
<add> assert_equal "'#{nil.inspect}' is not an ActiveModel-compatible object. It must implement :to_partial_path.", e.message
<ide> end
<ide>
<ide> def test_render_partial_with_errors
<ide> def test_render_partial_using_collection
<ide> @controller_view.render(customers, :greeting => "Hello")
<ide> end
<ide>
<del> class CustomerWithDeprecatedPartialPath
<del> attr_reader :name
<del>
<del> def self.model_name
<del> Struct.new(:partial_path).new("customers/customer")
<del> end
<del>
<del> def initialize(name)
<del> @name = name
<del> end
<del> end
<del>
<del> def test_render_partial_using_object_with_deprecated_partial_path
<del> assert_deprecated(/#model_name.*#partial_path.*#to_partial_path/) do
<del> assert_equal "Hello: nertzy",
<del> @controller_view.render(CustomerWithDeprecatedPartialPath.new("nertzy"), :greeting => "Hello")
<del> end
<del> end
<del>
<del> def test_render_partial_using_collection_with_deprecated_partial_path
<del> assert_deprecated(/#model_name.*#partial_path.*#to_partial_path/) do
<del> customers = [
<del> CustomerWithDeprecatedPartialPath.new("nertzy"),
<del> CustomerWithDeprecatedPartialPath.new("peeja")
<del> ]
<del> assert_equal "Hello: nertzyHello: peeja",
<del> @controller_view.render(customers, :greeting => "Hello")
<del> end
<del> end
<del>
<ide> # TODO: The reason for this test is unclear, improve documentation
<ide> def test_render_partial_and_fallback_to_layout
<ide> assert_equal "Before (Josh)\n\nAfter", @view.render(:partial => "test/layout_for_partial", :locals => { :name => "Josh" }) | 9 |
Javascript | Javascript | return promise.all from dispatch | 03d16c4f5d111373a4a7275fd07bb096805c9950 | <ide><path>spec/command-registry-spec.js
<ide> describe("CommandRegistry", () => {
<ide> expect(calls).toEqual([]);
<ide> });
<ide>
<del> it("invokes callbacks registered with ::onWillDispatch and ::onDidDispatch and ::onDidFinish", () => {
<add> it("invokes callbacks registered with ::onWillDispatch and ::onDidDispatch", () => {
<ide> const sequence = [];
<ide>
<del> registry.onDidFinish(event => sequence.push(['onDidFinish', event]));
<del>
<ide> registry.onDidDispatch(event => sequence.push(['onDidDispatch', event]));
<ide>
<ide> registry.add('.grandchild', 'command', event => sequence.push(['listener', event]));
<ide> describe("CommandRegistry", () => {
<ide> expect(sequence[1][0]).toBe('listener');
<ide> expect(sequence[2][0]).toBe('onDidDispatch');
<ide>
<del> waitsFor(() => sequence.length === 4, "onDidFinish never called");
<del>
<del> runs(() => {
<del> expect(sequence[3][0]).toBe('onDidFinish');
<del>
<del> expect(sequence[0][1] === sequence[1][1] && sequence[1][1] === sequence[2][1] && sequence[2][1] === sequence[3][1]).toBe(true);
<del> expect(sequence[0][1].constructor).toBe(CustomEvent);
<del> expect(sequence[0][1].target).toBe(grandchild);
<del> });
<del> });
<del>
<del> it("invokes callbacks registered with ::onDidFinish on resolve", () => {
<del> const sequence = [];
<del>
<del> registry.onDidFinish(event => {
<del> sequence.push(['onDidFinish', event]);
<del> });
<del>
<del> registry.add('.grandchild', 'command', event => {
<del> sequence.push(['listener', event]);
<del> return new Promise(resolve => {
<del> setTimeout(() => {
<del> sequence.push(['resolve', event]);
<del> resolve();
<del> }, 100);
<del> });
<del> });
<del>
<del> grandchild.dispatchEvent(new CustomEvent('command', {bubbles: true}));
<del> advanceClock(100);
<del>
<del> waitsFor(() => sequence.length === 3, "onDidFinish never called for resolve");
<del>
<del> runs(() => {
<del> expect(sequence[0][0]).toBe('listener')
<del> expect(sequence[1][0]).toBe('resolve')
<del> expect(sequence[2][0]).toBe('onDidFinish')
<del>
<del> expect(sequence[0][1] === sequence[1][1] && sequence[1][1] === sequence[2][1]).toBe(true)
<del> expect(sequence[0][1].constructor).toBe(CustomEvent)
<del> expect(sequence[0][1].target).toBe(grandchild)
<del> });
<add> expect(sequence[0][1] === sequence[1][1] && sequence[1][1] === sequence[2][1]).toBe(true);
<add> expect(sequence[0][1].constructor).toBe(CustomEvent);
<add> expect(sequence[0][1].target).toBe(grandchild);
<ide> });
<ide>
<del> it("invokes callbacks registered with ::onDidFinish on reject", () => {
<del> const sequence = [];
<del>
<del> registry.onDidFinish(event => {
<del> sequence.push(['onDidFinish', event]);
<del> });
<del>
<del> registry.add('.grandchild', 'command', event => {
<del> sequence.push(['listener', event]);
<del> return new Promise((_, reject) => {
<del> setTimeout(() => {
<del> sequence.push(['reject', event]);
<del> reject();
<del> }, 100);
<del> });
<del> });
<del>
<del> grandchild.dispatchEvent(new CustomEvent('command', {bubbles: true}));
<del> advanceClock(100);
<add> it("returns a promise", () => {
<add> const calls = [];
<add> registry.add('.grandchild', 'command', () => 'grandchild');
<add> registry.add(child, 'command', () => 'child-inline');
<add> registry.add('.child', 'command', () => 'child');
<add> registry.add('.parent', 'command', () => 'parent');
<ide>
<del> waitsFor(() => sequence.length === 3, "onDidFinish never called for reject");
<add> waitsForPromise(() => grandchild.dispatchEvent(new CustomEvent('command', {bubbles: true})).then(args => { calls = args; }));
<ide>
<ide> runs(() => {
<del> expect(sequence[0][0]).toBe('listener')
<del> expect(sequence[1][0]).toBe('reject')
<del> expect(sequence[2][0]).toBe('onDidFinish')
<del>
<del> expect(sequence[0][1] === sequence[1][1] && sequence[1][1] === sequence[2][1]).toBe(true)
<del> expect(sequence[0][1].constructor).toBe(CustomEvent)
<del> expect(sequence[0][1].target).toBe(grandchild)
<add> expect(calls).toEqual(['grandchild', 'child-inline', 'child', 'parent']);
<ide> });
<ide> });
<ide> });
<ide><path>src/command-registry.js
<ide> module.exports = class CommandRegistry {
<ide> return this.emitter.on('did-dispatch', callback)
<ide> }
<ide>
<del> // Public: Invoke the given callback after finishing a command event.
<del> //
<del> // * `callback` {Function} to be called after finishing each command
<del> // * `event` The Event that was dispatched
<del> onDidFinish (callback) {
<del> return this.emitter.on('did-finish', callback)
<del> }
<del>
<ide> getSnapshot () {
<ide> const snapshot = {}
<ide> for (const commandName in this.selectorBasedListenersByCommandName) {
<ide> module.exports = class CommandRegistry {
<ide>
<ide> this.emitter.emit('did-dispatch', dispatchedEvent)
<ide>
<del> Promise.all(matched).then(
<del> _ => this.emitter.emit('did-finish', dispatchedEvent),
<del> _ => this.emitter.emit('did-finish', dispatchedEvent)
<del> )
<del>
<del> return matched.length > 0
<add> return (matched.length > 0 ? Promise.all(matched) : null)
<ide> }
<ide>
<ide> commandRegistered (commandName) { | 2 |
Javascript | Javascript | add dblclick method to the ngscenario dsl | 8cb9c99ec064fd95567118d29bfa4a19b8613ab3 | <ide><path>src/ngScenario/dsl.js
<ide> angular.scenario.dsl('element', function() {
<ide> });
<ide> };
<ide>
<add> chain.dblclick = function() {
<add> return this.addFutureAction("element '" + this.label + "' dblclick", function($window, $document, done) {
<add> var elements = $document.elements();
<add> var href = elements.attr('href');
<add> var eventProcessDefault = elements.trigger('dblclick')[0];
<add>
<add> if (href && elements[0].nodeName.toUpperCase() === 'A' && eventProcessDefault) {
<add> this.application.navigateTo(href, function() {
<add> done();
<add> }, done);
<add> } else {
<add> done();
<add> }
<add> });
<add> };
<add>
<ide> chain.query = function(fn) {
<ide> return this.addFutureAction('element ' + this.label + ' custom query', function($window, $document, done) {
<ide> fn.call(this, $document.elements(), done);
<ide><path>test/ngScenario/dslSpec.js
<ide> describe("angular.scenario.dsl", function() {
<ide> dealoc(elm);
<ide> });
<ide>
<add> it('should execute dblclick', function() {
<add> var clicked;
<add> // Hash is important, otherwise we actually
<add> // go to a different page and break the runner
<add> doc.append('<a href="#"></a>');
<add> doc.find('a').dblclick(function() {
<add> clicked = true;
<add> });
<add> $root.dsl.element('a').dblclick();
<add> });
<add>
<add> it('should navigate page if dblclick on anchor', function() {
<add> expect($window.location).not.toEqual('#foo');
<add> doc.append('<a href="#foo"></a>');
<add> $root.dsl.element('a').dblclick();
<add> expect($window.location).toMatch(/#foo$/);
<add> });
<add>
<add> it('should not navigate if dblclick event was cancelled', function() {
<add> var initLocation = $window.location,
<add> elm = jqLite('<a href="#foo"></a>');
<add>
<add> doc.append(elm);
<add> elm.bind('dblclick', function(event) {
<add> event.preventDefault();
<add> });
<add>
<add> $root.dsl.element('a').dblclick();
<add> expect($window.location).toBe(initLocation);
<add> dealoc(elm);
<add> });
<add>
<ide> it('should count matching elements', function() {
<ide> doc.append('<span></span><span></span>');
<ide> $root.dsl.element('span').count(); | 2 |
Python | Python | fix warnings in deberta | b6204c9e9b0c03a5a1209842d77a05eadbeb007e | <ide><path>src/transformers/models/deberta/modeling_deberta.py
<ide> def linear(w, b, x):
<ide> qkvw = [torch.cat([ws[i * 3 + k] for i in range(self.num_attention_heads)], dim=0) for k in range(3)]
<ide> qkvb = [None] * 3
<ide>
<del> q = linear(qkvw[0], qkvb[0], torch.tensor(query_states, dtype=qkvw[0].dtype))
<del> k, v = [linear(qkvw[i], qkvb[i], torch.tensor(hidden_states, dtype=qkvw[i].dtype)) for i in range(1, 3)]
<add> q = linear(qkvw[0], qkvb[0], query_states.to(dtype=qkvw[0].dtype))
<add> k, v = [linear(qkvw[i], qkvb[i], hidden_states.to(dtype=qkvw[i].dtype)) for i in range(1, 3)]
<ide> query_layer, key_layer, value_layer = [self.transpose_for_scores(x) for x in [q, k, v]]
<ide>
<ide> query_layer = query_layer + self.transpose_for_scores(self.q_bias[None, None, :])
<ide> def linear(w, b, x):
<ide> # Take the dot product between "query" and "key" to get the raw attention scores.
<ide> scale_factor = 1 + len(self.pos_att_type)
<ide> scale = torch.sqrt(torch.tensor(query_layer.size(-1), dtype=torch.float) * scale_factor)
<del> query_layer = query_layer / torch.tensor(scale, dtype=query_layer.dtype)
<add> query_layer = query_layer / scale.to(dtype=query_layer.dtype)
<ide> attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
<ide> if self.relative_attention:
<ide> rel_embeddings = self.pos_dropout(rel_embeddings)
<ide> def disentangled_att_bias(self, query_layer, key_layer, relative_pos, rel_embedd
<ide> else:
<ide> r_pos = relative_pos
<ide> p2c_pos = torch.clamp(-r_pos + att_span, 0, att_span * 2 - 1)
<del> p2c_att = torch.matmul(key_layer, torch.tensor(pos_query_layer.transpose(-1, -2), dtype=key_layer.dtype))
<add> p2c_att = torch.matmul(key_layer, pos_query_layer.transpose(-1, -2).to(dtype=key_layer.dtype))
<ide> p2c_att = torch.gather(
<ide> p2c_att, dim=-1, index=p2c_dynamic_expand(p2c_pos, query_layer, key_layer)
<ide> ).transpose(-1, -2)
<ide><path>src/transformers/models/deberta_v2/modeling_deberta_v2.py
<ide> def forward(
<ide> if "p2c" in self.pos_att_type:
<ide> scale_factor += 1
<ide> scale = torch.sqrt(torch.tensor(query_layer.size(-1), dtype=torch.float) * scale_factor)
<del> attention_scores = torch.bmm(query_layer, key_layer.transpose(-1, -2)) / torch.tensor(
<del> scale, dtype=query_layer.dtype
<del> )
<add> attention_scores = torch.bmm(query_layer, key_layer.transpose(-1, -2)) / scale.to(dtype=query_layer.dtype)
<ide> if self.relative_attention:
<ide> rel_embeddings = self.pos_dropout(rel_embeddings)
<ide> rel_att = self.disentangled_attention_bias(
<ide> def disentangled_attention_bias(self, query_layer, key_layer, relative_pos, rel_
<ide> dim=-1,
<ide> index=c2p_pos.squeeze(0).expand([query_layer.size(0), query_layer.size(1), relative_pos.size(-1)]),
<ide> )
<del> score += c2p_att / torch.tensor(scale, dtype=c2p_att.dtype)
<add> score += c2p_att / scale.to(dtype=c2p_att.dtype)
<ide>
<ide> # position->content
<ide> if "p2c" in self.pos_att_type:
<ide> def disentangled_attention_bias(self, query_layer, key_layer, relative_pos, rel_
<ide> dim=-1,
<ide> index=p2c_pos.squeeze(0).expand([query_layer.size(0), key_layer.size(-2), key_layer.size(-2)]),
<ide> ).transpose(-1, -2)
<del> score += p2c_att / torch.tensor(scale, dtype=p2c_att.dtype)
<add> score += p2c_att / scale.to(dtype=p2c_att.dtype)
<ide>
<ide> return score
<ide>
<ide><path>src/transformers/models/sew_d/modeling_sew_d.py
<ide> def forward(
<ide> if "p2c" in self.pos_att_type:
<ide> scale_factor += 1
<ide> scale = torch.sqrt(torch.tensor(query_layer.size(-1), dtype=torch.float) * scale_factor)
<del> attention_scores = torch.bmm(query_layer, key_layer.transpose(-1, -2)) / torch.tensor(
<del> scale, dtype=query_layer.dtype
<del> )
<add> attention_scores = torch.bmm(query_layer, key_layer.transpose(-1, -2)) / scale.to(dtype=query_layer.dtype)
<ide> if self.relative_attention:
<ide> rel_embeddings = self.pos_dropout(rel_embeddings)
<ide> rel_att = self.disentangled_attention_bias(
<ide> def disentangled_attention_bias(self, query_layer, key_layer, relative_pos, rel_
<ide> dim=-1,
<ide> index=c2p_pos.squeeze(0).expand([query_layer.size(0), query_layer.size(1), relative_pos.size(-1)]),
<ide> )
<del> score += c2p_att / torch.tensor(scale, dtype=c2p_att.dtype)
<add> score += c2p_att / scale.to(dtype=c2p_att.dtype)
<ide>
<ide> # position->content
<ide> if "p2c" in self.pos_att_type:
<ide> def disentangled_attention_bias(self, query_layer, key_layer, relative_pos, rel_
<ide> dim=-1,
<ide> index=p2c_pos.squeeze(0).expand([query_layer.size(0), key_layer.size(-2), key_layer.size(-2)]),
<ide> ).transpose(-1, -2)
<del> score += p2c_att / torch.tensor(scale, dtype=p2c_att.dtype)
<add> score += p2c_att / scale.to(dtype=p2c_att.dtype)
<ide>
<ide> return score
<ide> | 3 |
Text | Text | improve translation for russian locale | e2832fe714b4096ff036b011c907d1320c161664 | <ide><path>curriculum/challenges/russian/02-javascript-algorithms-and-data-structures/functional-programming/remove-elements-from-an-array-using-slice-instead-of-splice.russian.md
<ide> id: 9d7123c8c441eeafaeb5bdef
<ide> title: Remove Elements from an Array Using slice Instead of splice
<ide> challengeType: 1
<ide> videoUrl: ''
<del>localeTitle: Удаление элементов из массива Использование среза Вместо сращивания
<add>localeTitle: Удаление элементов из массива используя slice вместо splice
<ide> ---
<ide>
<del>## Description
<del><section id="description"> Обычный шаблон при работе с массивами - это когда вы хотите удалить элементы и сохранить остальную часть массива. JavaScript предлагает метод <code>splice</code> для этого, который принимает аргументы для индекса того, где следует начинать удаление элементов, а затем количество элементов для удаления. Если второй аргумент не указан, по умолчанию используется удаление элементов в конце. Однако метод <code>splice</code> мутирует исходный массив, на который он вызывается. Вот пример: <blockquote> var cities = ["Чикаго", "Дели", "Исламабад", "Лондон", "Берлин"]; <br> cities.splice (3, 1); // Возвращает «Лондон» и удаляет его из массива городов <br> // города теперь [«Чикаго», «Дели», «Исламабад», «Берлин»] </blockquote> Как мы видели в последнем вызове, метод <code>slice</code> не мутирует исходный массив, а возвращает новый, который можно сохранить в переменной. Напомним, что метод <code>slice</code> принимает два аргумента, чтобы индексы начинались и заканчивались срезом (конец не включен) и возвращает эти элементы в новом массиве. Использование метода <code>slice</code> вместо <code>splice</code> помогает избежать любых побочных эффектов, связанных с массивом. </section>
<add>## Описание
<add><section id="description"> Обычный случай при работе с массивами - это когда вы хотите удалить элементы и сохранить остальную часть массива. Для этого JavaScript предлагает метод <code>splice</code>, который принимает индекс того, где следует начинать удаление элементов, и количество элементов для удаления. Если второй аргумент не указан, по умолчанию удаляются элементы до конца массива. Однако метод <code>splice</code> мутирует исходный массив, на котором он вызывается. Вот пример: <blockquote> var cities = ["Чикаго", "Дели", "Исламабад", "Лондон", "Берлин"]; <br> cities.splice (3, 1); // Возвращает «Лондон» и удаляет его из массива городов <br> // города теперь [«Чикаго», «Дели», «Исламабад», «Берлин»] </blockquote> Как мы видели в последней задаче, метод <code>slice</code> не мутирует исходный массив, а возвращает новый, который можно сохранить в переменной. Напомним, что метод <code>slice</code> принимает два аргумента - индексы начала и канца среза (конец не включен) и возвращает эти элементы в новом массиве. Использование метода <code>slice</code> вместо <code>splice</code> помогает избежать любых побочных эффектов, связанных с массивом. </section>
<ide>
<del>## Instructions
<add>## Указания
<ide> <section id="instructions"> Перепишите функцию <code>nonMutatingSplice</code> , используя <code>slice</code> вместо <code>splice</code> . Он должен ограничивать массив предоставленных <code>cities</code> длиной до 3 и возвращать новый массив только с первыми тремя элементами. Не мутируйте исходный массив, предоставленный функции. </section>
<ide>
<del>## Tests
<add>## Тесты
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<ide>
<ide> </section>
<ide>
<del>## Challenge Seed
<add>## Исходные данные
<ide> <section id='challengeSeed'>
<ide>
<ide> <div id='js-seed'>
<ide> nonMutatingSplice(inputCities);
<ide>
<ide> </section>
<ide>
<del>## Solution
<add>## Решение
<ide> <section id='solution'>
<ide>
<ide> ```js | 1 |
Javascript | Javascript | use more primordials | 1f6ca18c3b7c9527747bc23de8be87bfe338f239 | <ide><path>lib/internal/console/constructor.js
<ide> const {
<ide> ArrayFrom,
<ide> ArrayIsArray,
<add> ArrayPrototypePush,
<add> ArrayPrototypeUnshift,
<ide> Boolean,
<ide> ErrorCaptureStackTrace,
<del> Map,
<add> FunctionPrototypeBind,
<ide> MathFloor,
<ide> Number,
<add> NumberPrototypeToFixed,
<ide> ObjectDefineProperties,
<ide> ObjectDefineProperty,
<ide> ObjectKeys,
<ide> ObjectPrototypeHasOwnProperty,
<ide> ObjectValues,
<ide> ReflectOwnKeys,
<add> SafeMap,
<add> SafeWeakMap,
<add> StringPrototypeIncludes,
<add> StringPrototypePadStart,
<add> StringPrototypeRepeat,
<add> StringPrototypeReplace,
<add> StringPrototypeSlice,
<add> StringPrototypeSplit,
<ide> Symbol,
<ide> SymbolHasInstance,
<ide> SymbolToStringTag,
<del> WeakMap,
<ide> } = primordials;
<ide>
<ide> const { trace } = internalBinding('trace_events');
<ide> const kBindStreamsLazy = Symbol('kBindStreamsLazy');
<ide> const kUseStdout = Symbol('kUseStdout');
<ide> const kUseStderr = Symbol('kUseStderr');
<ide>
<del>const optionsMap = new WeakMap();
<add>const optionsMap = new SafeWeakMap();
<ide>
<ide> function Console(options /* or: stdout, stderr, ignoreErrors = true */) {
<ide> // We have to test new.target here to see if this function is called
<ide> function Console(options /* or: stdout, stderr, ignoreErrors = true */) {
<ide> // We have to bind the methods grabbed from the instance instead of from
<ide> // the prototype so that users extending the Console can override them
<ide> // from the prototype chain of the subclass.
<del> this[key] = this[key].bind(this);
<add> this[key] = FunctionPrototypeBind(this[key], this);
<ide> ObjectDefineProperty(this[key], 'name', {
<ide> value: key
<ide> });
<ide> ObjectDefineProperties(Console.prototype, {
<ide> ...consolePropAttributes,
<ide> value: Boolean(ignoreErrors)
<ide> },
<del> '_times': { ...consolePropAttributes, value: new Map() },
<add> '_times': { ...consolePropAttributes, value: new SafeMap() },
<ide> // Corresponds to https://console.spec.whatwg.org/#count-map
<del> [kCounts]: { ...consolePropAttributes, value: new Map() },
<add> [kCounts]: { ...consolePropAttributes, value: new SafeMap() },
<ide> [kColorMode]: { ...consolePropAttributes, value: colorMode },
<ide> [kIsConsole]: { ...consolePropAttributes, value: true },
<ide> [kGroupIndent]: { ...consolePropAttributes, value: '' },
<ide> ObjectDefineProperties(Console.prototype, {
<ide> this._stdoutErrorHandler : this._stderrErrorHandler;
<ide>
<ide> if (groupIndent.length !== 0) {
<del> if (string.includes('\n')) {
<del> string = string.replace(/\n/g, `\n${groupIndent}`);
<add> if (StringPrototypeIncludes(string, '\n')) {
<add> string = StringPrototypeReplace(string, /\n/g, `\n${groupIndent}`);
<ide> }
<ide> string = groupIndent + string;
<ide> }
<ide> const consoleMethods = {
<ide> if (data.length > 0) {
<ide> this.log(...data);
<ide> }
<del> this[kGroupIndent] += ' '.repeat(this[kGroupIndentationWidth]);
<add> this[kGroupIndent] +=
<add> StringPrototypeRepeat(' ', this[kGroupIndentationWidth]);
<ide> },
<ide>
<ide> groupEnd() {
<del> this[kGroupIndent] =
<del> this[kGroupIndent].slice(0, this[kGroupIndent].length -
<del> this[kGroupIndentationWidth]);
<add> this[kGroupIndent] = StringPrototypeSlice(
<add> this[kGroupIndent],
<add> 0,
<add> this[kGroupIndent].length - this[kGroupIndentationWidth]
<add> );
<ide> },
<ide>
<ide> // https://console.spec.whatwg.org/#table
<ide> const consoleMethods = {
<ide> let length = 0;
<ide> if (mapIter) {
<ide> for (; i < tabularData.length / 2; ++i) {
<del> keys.push(_inspect(tabularData[i * 2]));
<del> values.push(_inspect(tabularData[i * 2 + 1]));
<add> ArrayPrototypePush(keys, _inspect(tabularData[i * 2]));
<add> ArrayPrototypePush(values, _inspect(tabularData[i * 2 + 1]));
<ide> length++;
<ide> }
<ide> } else {
<ide> for (const [k, v] of tabularData) {
<del> keys.push(_inspect(k));
<del> values.push(_inspect(v));
<add> ArrayPrototypePush(keys, _inspect(k));
<add> ArrayPrototypePush(values, _inspect(v));
<ide> length++;
<ide> }
<ide> }
<ide> const consoleMethods = {
<ide> const values = [];
<ide> let length = 0;
<ide> for (const v of tabularData) {
<del> values.push(_inspect(v));
<add> ArrayPrototypePush(values, _inspect(v));
<ide> length++;
<ide> }
<ide> return final([iterKey, valuesKey], [getIndexArray(length), values]);
<ide> const consoleMethods = {
<ide> const keys = ObjectKeys(map);
<ide> const values = ObjectValues(map);
<ide> if (hasPrimitives) {
<del> keys.push(valuesKey);
<del> values.push(valuesKeyArray);
<add> ArrayPrototypePush(keys, valuesKey);
<add> ArrayPrototypePush(values, valuesKeyArray);
<ide> }
<del> keys.unshift(indexKey);
<del> values.unshift(indexKeyArray);
<add> ArrayPrototypeUnshift(keys, indexKey);
<add> ArrayPrototypeUnshift(values, indexKeyArray);
<ide>
<ide> return final(keys, values);
<ide> },
<ide> function timeLogImpl(self, name, label, data) {
<ide> }
<ide>
<ide> function pad(value) {
<del> return `${value}`.padStart(2, '0');
<add> return StringPrototypePadStart(`${value}`, 2, '0');
<ide> }
<ide>
<ide> function formatTime(ms) {
<ide> function formatTime(ms) {
<ide> }
<ide>
<ide> if (hours !== 0 || minutes !== 0) {
<del> [seconds, ms] = seconds.toFixed(3).split('.');
<add> [seconds, ms] = StringPrototypeSplit(
<add> NumberPrototypeToFixed(seconds, 3),
<add> '.'
<add> );
<ide> const res = hours !== 0 ? `${hours}:${pad(minutes)}` : minutes;
<ide> return `${res}:${pad(seconds)}.${ms} (${hours !== 0 ? 'h:m' : ''}m:ss.mmm)`;
<ide> }
<ide>
<ide> if (seconds !== 0) {
<del> return `${seconds.toFixed(3)}s`;
<add> return `${NumberPrototypeToFixed(seconds, 3)}s`;
<ide> }
<ide>
<del> return `${Number(ms.toFixed(3))}ms`;
<add> return `${Number(NumberPrototypeToFixed(ms, 3))}ms`;
<ide> }
<ide>
<ide> const keyKey = 'Key';
<ide><path>lib/internal/console/global.js
<ide> // in the global console prototype chain anymore.
<ide>
<ide> const {
<add> FunctionPrototypeBind,
<ide> ObjectCreate,
<ide> ReflectDefineProperty,
<ide> ReflectGetOwnPropertyDescriptor,
<ide> for (const prop of ReflectOwnKeys(Console.prototype)) {
<ide> const desc = ReflectGetOwnPropertyDescriptor(Console.prototype, prop);
<ide> if (typeof desc.value === 'function') { // fix the receiver
<ide> const name = desc.value.name;
<del> desc.value = desc.value.bind(globalConsole);
<add> desc.value = FunctionPrototypeBind(desc.value, globalConsole);
<ide> ReflectDefineProperty(desc.value, 'name', { value: name });
<ide> }
<ide> ReflectDefineProperty(globalConsole, prop, desc); | 2 |
Ruby | Ruby | require global_identification in serialisations | fc9267e34ac7ccb7f5cdfc9296bb38cd105c728b | <ide><path>lib/active_job/arguments.rb
<ide> require 'active_model/global_locator'
<add>require 'active_model/global_identification'
<ide>
<ide> module ActiveJob
<ide> class Arguments | 1 |
PHP | PHP | remove noise docblock annotations | 6dcabd25c407a40efb627728f03225dfa8416735 | <ide><path>src/Auth/BaseAuthenticate.php
<ide>
<ide> /**
<ide> * Base Authentication class with common methods and properties.
<del> *
<del> * @mixin \Cake\Core\InstanceConfigTrait
<ide> */
<ide> abstract class BaseAuthenticate implements EventListenerInterface
<ide> {
<del>
<ide> use InstanceConfigTrait;
<ide> use LocatorAwareTrait;
<ide>
<ide><path>src/Auth/BaseAuthorize.php
<ide> * Abstract base authorization adapter for AuthComponent.
<ide> *
<ide> * @see \Cake\Controller\Component\AuthComponent::$authenticate
<del> * @mixin \Cake\Core\InstanceConfigTrait
<ide> */
<ide> abstract class BaseAuthorize
<ide> {
<del>
<ide> use InstanceConfigTrait;
<ide>
<ide> /**
<ide><path>src/Auth/Storage/SessionStorage.php
<ide>
<ide> /**
<ide> * Session based persistent storage for authenticated user record.
<del> *
<del> * @mixin \Cake\Core\InstanceConfigTrait
<ide> */
<ide> class SessionStorage implements StorageInterface
<ide> {
<del>
<ide> use InstanceConfigTrait;
<ide>
<ide> /**
<ide><path>src/Cache/CacheEngine.php
<ide>
<ide> /**
<ide> * Storage engine for CakePHP caching
<del> *
<del> * @mixin \Cake\Core\InstanceConfigTrait
<ide> */
<ide> abstract class CacheEngine
<ide> {
<del>
<ide> use InstanceConfigTrait;
<ide>
<ide> /**
<ide><path>src/Controller/Component.php
<ide> *
<ide> * @link https://book.cakephp.org/3.0/en/controllers/components.html
<ide> * @see \Cake\Controller\Controller::$components
<del> * @mixin \Cake\Core\InstanceConfigTrait
<ide> */
<ide> class Component implements EventListenerInterface
<ide> {
<del>
<ide> use InstanceConfigTrait;
<ide> use LogTrait;
<ide>
<ide><path>src/Error/Middleware/ErrorHandlerMiddleware.php
<ide> *
<ide> * Traps exceptions and converts them into HTML or content-type appropriate
<ide> * error pages using the CakePHP ExceptionRenderer.
<del> *
<del> * @mixin \Cake\Core\InstanceConfigTrait
<ide> */
<ide> class ErrorHandlerMiddleware
<ide> {
<ide><path>src/Http/Client.php
<ide> * a proxy if you need to use one. The type sub option can be used to
<ide> * specify which authentication strategy you want to use.
<ide> * CakePHP comes with built-in support for basic authentication.
<del> *
<del> * @mixin \Cake\Core\InstanceConfigTrait
<ide> */
<ide> class Client
<ide> {
<del>
<ide> use InstanceConfigTrait;
<ide>
<ide> /**
<ide><path>src/Log/Engine/BaseLog.php
<ide>
<ide> /**
<ide> * Base log engine class.
<del> *
<del> * @mixin \Cake\Core\InstanceConfigTrait
<ide> */
<ide> abstract class BaseLog extends AbstractLogger
<ide> {
<del>
<ide> use InstanceConfigTrait;
<ide>
<ide> /**
<ide><path>src/Mailer/AbstractTransport.php
<ide>
<ide> /**
<ide> * Abstract transport for sending email
<del> *
<del> * @mixin \Cake\Core\InstanceConfigTrait
<ide> */
<ide> abstract class AbstractTransport
<ide> {
<del>
<ide> use InstanceConfigTrait;
<ide>
<ide> /**
<ide><path>src/Network/Socket.php
<ide> * CakePHP network socket connection class.
<ide> *
<ide> * Core base class for network communication.
<del> *
<del> * @mixin \Cake\Core\InstanceConfigTrait
<ide> */
<ide> class Socket
<ide> {
<del>
<ide> use InstanceConfigTrait;
<ide>
<ide> /**
<ide><path>src/ORM/Behavior.php
<ide> *
<ide> * @see \Cake\ORM\Table::addBehavior()
<ide> * @see \Cake\Event\EventManager
<del> * @mixin \Cake\Core\InstanceConfigTrait
<ide> */
<ide> class Behavior implements EventListenerInterface
<ide> {
<ide><path>src/ORM/Query.php
<ide> * with the first rows of the query and each of the items, then the second rows and so on.
<ide> * @method \Cake\Collection\CollectionInterface chunk($size) Groups the results in arrays of $size rows each.
<ide> * @method bool isEmpty() Returns true if this query found no results.
<del> * @mixin \Cake\Datasource\QueryTrait
<ide> */
<ide> class Query extends DatabaseQuery implements JsonSerializable, QueryInterface
<ide> {
<del>
<ide> use QueryTrait {
<ide> cache as private _cache;
<ide> all as private _all;
<ide><path>src/Routing/DispatcherFilter.php
<ide> *
<ide> * When using the `for` or `when` matchers, conditions will be re-checked on the before and after
<ide> * callback as the conditions could change during the dispatch cycle.
<del> *
<del> * @mixin \Cake\Core\InstanceConfigTrait
<ide> */
<ide> class DispatcherFilter implements EventListenerInterface
<ide> {
<del>
<ide> use InstanceConfigTrait;
<ide>
<ide> /** | 13 |
Javascript | Javascript | add testids and names to animated examples | 7d4612b076529a1a868e52890c236375bb3f2814 | <ide><path>packages/rn-tester/js/components/RNTesterButton.js
<ide> const {StyleSheet, Text, TouchableHighlight} = require('react-native');
<ide> import type {PressEvent} from 'react-native/Libraries/Types/CoreEventTypes';
<ide>
<ide> type Props = $ReadOnly<{|
<add> testID?: string,
<ide> children?: React.Node,
<ide> onPress?: ?(event: PressEvent) => mixed,
<ide> |}>;
<ide> class RNTesterButton extends React.Component<Props> {
<ide> render(): React.Node {
<ide> return (
<ide> <TouchableHighlight
<add> testID={this.props.testID}
<ide> onPress={this.props.onPress}
<ide> style={styles.button}
<ide> underlayColor="grey">
<ide><path>packages/rn-tester/js/examples/Animated/AnimatedExample.js
<ide>
<ide> const RNTesterButton = require('../../components/RNTesterButton');
<ide> const React = require('react');
<del>
<ide> const {Animated, Easing, StyleSheet, Text, View} = require('react-native');
<ide>
<add>import type {RNTesterExampleModuleItem} from '../../types/RNTesterTypes';
<add>
<ide> const styles = StyleSheet.create({
<ide> content: {
<ide> backgroundColor: 'deepskyblue',
<ide> exports.description = ('Animated provides a powerful ' +
<ide> 'and easy-to-use API for building modern, ' +
<ide> 'interactive user experiences.': string);
<ide>
<del>exports.examples = [
<add>exports.examples = ([
<ide> {
<ide> title: 'FadeInView',
<add> name: 'fadeInView',
<ide> description: ('Uses a simple timing animation to ' +
<ide> 'bring opacity from 0 to 1 when the component ' +
<ide> 'mounts.': string),
<ide> exports.examples = [
<ide> return (
<ide> <View>
<ide> <RNTesterButton
<add> testID="toggle-button"
<ide> onPress={() => {
<ide> this.setState(state => ({show: !state.show}));
<ide> }}>
<ide> Press to {this.state.show ? 'Hide' : 'Show'}
<ide> </RNTesterButton>
<ide> {this.state.show && (
<ide> <FadeInView>
<del> <View style={styles.content}>
<add> <View testID="fade-in-view" style={styles.content}>
<ide> <Text>FadeInView</Text>
<ide> </View>
<ide> </FadeInView>
<ide> exports.examples = [
<ide> },
<ide> {
<ide> title: 'Moving box example',
<add> name: 'movingView',
<ide> description: ('Click arrow buttons to move the box.' +
<ide> 'Then hide the box and reveal it again.' +
<ide> 'After that the box position will reset to initial position.': string),
<ide> exports.examples = [
<ide> <View style={movingBoxStyles.container}>
<ide> {this.renderBox()}
<ide> <View style={movingBoxStyles.buttonsContainer}>
<del> <RNTesterButton onPress={() => this.moveTo(0)}>
<add> <RNTesterButton
<add> testID="move-left-button"
<add> onPress={() => this.moveTo(0)}>
<ide> {'<-'}
<ide> </RNTesterButton>
<ide> <RNTesterButton onPress={this.toggleVisibility}>
<ide> {toggleText}
<ide> </RNTesterButton>
<ide> <RNTesterButton
<add> testID="move-right-button"
<ide> onPress={() => this.moveTo(containerWidth - boxSize)}>
<ide> {'->'}
<ide> </RNTesterButton>
<ide> exports.examples = [
<ide> return (
<ide> <View style={movingBoxStyles.boxContainer}>
<ide> <Animated.View
<add> testID="moving-view"
<ide> style={[
<ide> styles.content,
<ide> movingBoxStyles.box,
<ide> exports.examples = [
<ide> <Text>Checkout the Gratuitous Animation App!</Text>
<ide> ),
<ide> },
<del>];
<add>]: Array<RNTesterExampleModuleItem>); | 2 |
PHP | PHP | use table locator in databasesession | 9d2e619d848cef737a304f8902470ef6e2031792 | <ide><path>src/Network/Session/DatabaseSession.php
<ide> class DatabaseSession implements SessionHandlerInterface
<ide> */
<ide> public function __construct(array $config = [])
<ide> {
<add> $tableLocator = isset($config['tableLocator']) ? $config['tableLocator'] : TableRegistry::locator();
<add>
<ide> if (empty($config['model'])) {
<del> $config = TableRegistry::exists('Sessions') ? [] : ['table' => 'sessions'];
<del> $this->_table = TableRegistry::get('Sessions', $config);
<add> $config = $tableLocator->exists('Sessions') ? [] : ['table' => 'sessions'];
<add> $this->_table = $tableLocator->get('Sessions', $config);
<ide> } else {
<del> $this->_table = TableRegistry::get($config['model']);
<add> $this->_table = $tableLocator->get($config['model']);
<ide> }
<ide>
<ide> $this->_timeout = ini_get('session.gc_maxlifetime'); | 1 |
Go | Go | add test for exec tty stdin close | 243a640d3e593ee11e31ac55a4df8c887c2b09c9 | <ide><path>integration-cli/docker_cli_exec_test.go
<ide> func TestExecPausedContainer(t *testing.T) {
<ide>
<ide> logDone("exec - exec should not exec a pause container")
<ide> }
<add>
<add>// regression test for #9476
<add>func TestExecTtyCloseStdin(t *testing.T) {
<add> defer deleteAllContainers()
<add>
<add> cmd := exec.Command(dockerBinary, "run", "-d", "-it", "--name", "exec_tty_stdin", "busybox")
<add> if out, _, err := runCommandWithOutput(cmd); err != nil {
<add> t.Fatal(out, err)
<add> }
<add>
<add> cmd = exec.Command(dockerBinary, "exec", "-it", "exec_tty_stdin", "cat")
<add> stdinRw, err := cmd.StdinPipe()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> stdinRw.Write([]byte("test"))
<add> stdinRw.Close()
<add>
<add> if out, _, err := runCommandWithOutput(cmd); err != nil {
<add> t.Fatal(out, err)
<add> }
<add>
<add> cmd = exec.Command(dockerBinary, "top", "exec_tty_stdin")
<add> out, _, err := runCommandWithOutput(cmd)
<add> if err != nil {
<add> t.Fatal(out, err)
<add> }
<add>
<add> outArr := strings.Split(out, "\n")
<add> if len(outArr) > 3 || strings.Contains(out, "nsenter-exec") {
<add> // This is the really bad part
<add> if out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "rm", "-f", "exec_tty_stdin")); err != nil {
<add> t.Fatal(out, err)
<add> }
<add>
<add> t.Fatalf("exec process left running\n\t %s", out)
<add> }
<add>
<add> logDone("exec - stdin is closed properly with tty enabled")
<add>} | 1 |
Javascript | Javascript | return http request on load | 82a5a52b164137637908dd4a4eede6e7e7d703f7 | <ide><path>src/loaders/XHRLoader.js
<ide> THREE.XHRLoader.prototype = {
<ide>
<ide> scope.manager.itemStart( url );
<ide>
<add> return request;
<add>
<ide> },
<ide>
<ide> setResponseType: function ( value ) { | 1 |
Text | Text | add docs for --dns-search= | 36ffbd7acf60d15942c0591bb4fec498f021331e | <ide><path>docs/man/docker-create.1.md
<ide> docker-create - Create a new container
<ide> Add a host device to the container (e.g. --device=/dev/sdc:/dev/xvdc:rwm)
<ide>
<ide> **--dns-search**=[]
<del> Set custom DNS search domains
<add> Set custom DNS search domains (Use --dns-search=. if you don't wish to set the search domain)
<ide>
<ide> **--dns**=[]
<ide> Set custom DNS servers
<ide><path>docs/man/docker-run.1.md
<ide> stopping the process by pressing the keys CTRL-P CTRL-Q.
<ide> Add a host device to the container (e.g. --device=/dev/sdc:/dev/xvdc:rwm)
<ide>
<ide> **--dns-search**=[]
<del> Set custom DNS search domains
<add> Set custom DNS search domains (Use --dns-search=. if you don't wish to set the search domain)
<ide>
<ide> **--dns**=*IP-address*
<ide> Set custom DNS servers. This option can be used to override the DNS
<ide> and foreground Docker containers.
<ide> When set to true publish all exposed ports to the host interfaces. The
<ide> default is false. If the operator uses -P (or -p) then Docker will make the
<ide> exposed port accessible on the host and the ports will be available to any
<del>client that can reach the host. When using -P, Docker will bind the exposed
<del>ports to a random port on the host between 49153 and 65535. To find the
<add>client that can reach the host. When using -P, Docker will bind the exposed
<add>ports to a random port on the host between 49153 and 65535. To find the
<ide> mapping between the host ports and the exposed ports, use **docker port**.
<ide>
<ide> **-p**, **--publish**=[]
<ide> interactive shell. The default is value is false.
<ide>
<ide>
<ide> **-v**, **--volume**=*volume*[:ro|:rw]
<del> Bind mount a volume to the container.
<add> Bind mount a volume to the container.
<ide>
<ide> The **-v** option can be used one or
<ide> more times to add one or more mounts to a container. These mounts can then be
<del>used in other containers using the **--volumes-from** option.
<add>used in other containers using the **--volumes-from** option.
<ide>
<ide> The volume may be optionally suffixed with :ro or :rw to mount the volumes in
<ide> read-only or read-write mode, respectively. By default, the volumes are mounted
<ide> read-write. See examples.
<ide> Once a volume is mounted in a one container it can be shared with other
<ide> containers using the **--volumes-from** option when running those other
<ide> containers. The volumes can be shared even if the original container with the
<del>mount is not running.
<add>mount is not running.
<ide>
<del>The container ID may be optionally suffixed with :ro or
<del>:rw to mount the volumes in read-only or read-write mode, respectively. By
<del>default, the volumes are mounted in the same mode (read write or read only) as
<add>The container ID may be optionally suffixed with :ro or
<add>:rw to mount the volumes in read-only or read-write mode, respectively. By
<add>default, the volumes are mounted in the same mode (read write or read only) as
<ide> the reference container.
<ide>
<ide>
<ide><path>docs/sources/articles/networking.md
<ide> Docker made the choice `172.17.42.1/16` when I started it a few minutes
<ide> ago, for example — a 16-bit netmask providing 65,534 addresses for the
<ide> host machine and its containers.
<ide>
<del>> **Note:**
<add>> **Note:**
<ide> > This document discusses advanced networking configuration
<ide> > and options for Docker. In most cases you won't need this information.
<ide> > If you're looking to get started with a simpler explanation of Docker
<ide> Four different options affect container domain name services.
<ide> When a container process attempts to access `host` and the search
<ide> domain `example.com` is set, for instance, the DNS logic will not
<ide> only look up `host` but also `host.example.com`.
<add> Use `--dns-search=.` if you don't wish to set the search domain.
<ide>
<ide> Note that Docker, in the absence of either of the last two options
<ide> above, will make `/etc/resolv.conf` inside of each container look like
<ide><path>docs/sources/reference/commandline/cli.md
<ide> proxy in front of it. You can listen on port `2375` on all network interfaces
<ide> with `-H tcp://0.0.0.0:2375`, or on a particular network interface using its IP
<ide> address: `-H tcp://192.168.59.103:2375`.
<ide>
<del>On Systemd based systems, you can communicate with the daemon via
<add>On Systemd based systems, you can communicate with the daemon via
<ide> [systemd socket activation](http://0pointer.de/blog/projects/socket-activation.html), use
<ide> `docker -d -H fd://`. Using `fd://` will work perfectly for most setups but
<ide> you can also specify individual sockets: `docker -d -H fd://3`. If the
<ide> used, which is observable by the process being suspended. With the cgroups freez
<ide> the process is unaware, and unable to capture, that it is being suspended,
<ide> and subsequently resumed.
<ide>
<del>See the
<add>See the
<ide> [cgroups freezer documentation](https://www.kernel.org/doc/Documentation/cgroups/freezer-subsystem.txt)
<ide> for further details.
<ide>
<ide> removed before the image is removed.
<ide> -d, --detach=false Detached mode: run the container in the background and print the new container ID
<ide> --device=[] Add a host device to the container (e.g. --device=/dev/sdc:/dev/xvdc:rwm)
<ide> --dns=[] Set custom DNS servers
<del> --dns-search=[] Set custom DNS search domains
<add> --dns-search=[] Set custom DNS search domains (Use --dns-search=. if you don't wish to set the search domain)
<ide> -e, --env=[] Set environment variables
<ide> --entrypoint="" Overwrite the default ENTRYPOINT of the image
<ide> --env-file=[] Read in a line delimited file of environment variables
<ide> them to [*Share Images via Repositories*](
<ide> The `docker unpause` command uses the cgroups freezer to un-suspend all
<ide> processes in a container.
<ide>
<del>See the
<add>See the
<ide> [cgroups freezer documentation](https://www.kernel.org/doc/Documentation/cgroups/freezer-subsystem.txt)
<ide> for further details.
<ide> | 4 |
Python | Python | fix build on rtd | be8f1ac0d730cf943743091fa865cdbbdde93b50 | <ide><path>docs/conf.py
<ide> ROOT_DIR = os.path.abspath(os.path.join(CONF_DIR, os.pardir))
<ide>
<ide> # By default (e.g. on RTD), build docs for `airflow` package
<del>PACKAGE_NAME = os.environ.get('AIRFLOW_PACKAGE_NAME', 'airflow')
<add>PACKAGE_NAME = os.environ.get('AIRFLOW_PACKAGE_NAME', 'apache-airflow')
<ide> if PACKAGE_NAME == 'apache-airflow':
<del> os.environ['AIRFLOW_PACKAGE_NAME'] = 'airflow'
<del> os.environ['AIRFLOW_PACKAGE_DIR'] = os.path.abspath(os.getcwd())
<del> os.environ['AIRFLOW_PACKAGE_VERSION'] = airflow.__version__
<ide> PACKAGE_DIR = os.path.join(ROOT_DIR, 'airflow')
<ide> PACKAGE_VERSION = airflow.__version__
<ide> else:
<del> PACKAGE_NAME = os.environ['AIRFLOW_PACKAGE_NAME']
<ide> from provider_yaml_utils import load_package_data # pylint: disable=no-name-in-module
<ide>
<ide> ALL_PROVIDER_YAMLS = load_package_data()
<ide> raise Exception(f"Could not find provider.yaml file for package: {PACKAGE_NAME}")
<ide> PACKAGE_DIR = CURRENT_PROVIDER['package-dir']
<ide> PACKAGE_VERSION = 'master'
<add># Adds to environment variables for easy access from other plugins like airflow_internsphinx.
<add>os.environ['AIRFLOW_PACKAGE_NAME'] = PACKAGE_NAME
<add>os.environ['AIRFLOW_PACKAGE_DIR'] = PACKAGE_DIR
<add>os.environ['AIRFLOW_PACKAGE_VERSION'] = PACKAGE_VERSION
<ide>
<ide>
<ide> # Hack to allow changing for piece of the code to behave differently while | 1 |
PHP | PHP | last | 7d7b73231bbb6c5c1916ff4263b207f18b9342c9 | <ide><path>src/Illuminate/Support/Arr.php
<ide> public static function last($array, callable $callback = null, $default = null)
<ide> return empty($array) ? value($default) : end($array);
<ide> }
<ide>
<del> return static::first(array_reverse($array), $callback, $default);
<add> return static::first(array_reverse($array, true), $callback, $default);
<ide> }
<ide>
<ide> /**
<ide><path>tests/Support/SupportArrTest.php
<ide> public function testLast()
<ide> $last = Arr::last($array, function ($key, $value) { return $value < 250; });
<ide> $this->assertEquals(200, $last);
<ide>
<add> $last = Arr::last($array, function ($key, $value) { return $key < 2; });
<add> $this->assertEquals(200, $last);
<add>
<ide> $this->assertEquals(300, Arr::last($array));
<ide> }
<ide>
<ide><path>tests/Support/SupportCollectionTest.php
<ide> public function testLastWithCallback()
<ide> $data = new Collection([100, 200, 300]);
<ide> $result = $data->last(function ($key, $value) { return $value < 250; });
<ide> $this->assertEquals(200, $result);
<add> $result = $data->last(function ($key, $value) { return $key < 2; });
<add> $this->assertEquals(200, $result);
<ide> }
<ide>
<ide> public function testLastWithCallbackAndDefault() | 3 |
Javascript | Javascript | fix minor typo | 543cf1803b2a9a89b55115ad1b665bbc38feb1db | <ide><path>src/ng/compile.js
<ide> * local name. Given `<widget my-attr="count = count + value">` and widget definition of
<ide> * `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to
<ide> * a function wrapper for the `count = count + value` expression. Often it's desirable to
<del> * pass data from the isolated scope via an expression and to the parent scope, this can be
<add> * pass data from the isolated scope via an expression to the parent scope, this can be
<ide> * done by passing a map of local variable names and values into the expression wrapper fn.
<ide> * For example, if the expression is `increment(amount)` then we can specify the amount value
<ide> * by calling the `localFn` as `localFn({amount: 22})`. | 1 |
Text | Text | add example to if else in jsx | b9cf0d2bddf451167a8c8ea82b3f2d81c2a66935 | <ide><path>docs/tips/03-if-else-in-JSX.md
<ide> That's not valid JS. You probably want to make use of a ternary expression:
<ide> React.renderComponent(<div id={condition ? 'msg' : ''}>Hello World!</div>, mountNode);
<ide> ```
<ide>
<add>If a ternary expression isn't robust enough, you can use `if` statements to determine which
<add>components should be used.
<add>
<add>```js
<add>/** @jsx React.DOM */
<add>
<add>var loginButton;
<add>if (loggedIn) {
<add> loginButton = <LogoutButton />;
<add>} else {
<add> loginButton = <LoginButton />;
<add>}
<add>
<add>return (
<add> <nav>
<add> <Home />
<add> {loginButton}
<add> </nav>
<add>)
<add>```
<add>
<ide> Try using it today with the [JSX compiler](/react/jsx-compiler.html). | 1 |
Javascript | Javascript | add workaround for safari / webdriver problem | ab36c4b487032183833ab62656ed2dfaefb32b9e | <ide><path>src/Angular.js
<ide> function angularInit(element, bootstrap) {
<ide> });
<ide> if (appElement) {
<ide> if (!isAutoBootstrapAllowed) {
<del> try {
<del> window.console.error('AngularJS: disabling automatic bootstrap. <script> protocol indicates ' +
<add> window.console.error('AngularJS: disabling automatic bootstrap. <script> protocol indicates ' +
<ide> 'an extension, document.location.href does not match.');
<del> } catch (e) {
<del> // Support: Safari 11 w/ Webdriver
<del> // The console.error will throw and make the test fail
<del> }
<ide> return;
<ide> }
<ide> config.strictDi = getNgAttribute(appElement, 'strict-di') !== null; | 1 |
Javascript | Javascript | add unit test for ie11 url parsing failure | b2b896f949b79f1d8c558f462fabad1c04bf564e | <ide><path>test/ng/directive/booleanAttrsSpec.js
<ide> describe('ngHref', function() {
<ide> expect(element.attr('href')).toEqual(undefined);
<ide> }));
<ide>
<add> if (msie) {
<add> // IE11/10/Edge fail when setting a href to a URL containing a % that isn't a valid escape sequence
<add> // See https://github.com/angular/angular.js/issues/13388
<add> it('should throw error if ng-href contains a non-escaped percent symbol', inject(function($rootScope, $compile) {
<add> element = $compile('<a ng-href="http://www.google.com/{{\'a%link\'}}">')($rootScope);
<add>
<add> expect(function() {
<add> $rootScope.$digest();
<add> }).toThrow();
<add> }));
<add> }
<add>
<ide> if (isDefined(window.SVGElement)) {
<ide> describe('SVGAElement', function() {
<ide> it('should interpolate the expression and bind to xlink:href', inject(function($compile, $rootScope) { | 1 |
Go | Go | remove 256 character limit of libdm logs | 63328c6882c3d1f54c66499ef9963adfbf1883f0 | <ide><path>pkg/devicemapper/devmapper_wrapper.go
<ide> package devicemapper
<ide>
<ide> /*
<ide> #cgo LDFLAGS: -L. -ldevmapper
<add>#define _GNU_SOURCE
<ide> #include <libdevmapper.h>
<ide> #include <linux/fs.h> // FIXME: present only for BLKGETSIZE64, maybe we can remove it?
<ide>
<ide> extern void DevmapperLogCallback(int level, char *file, int line, int dm_errno_o
<ide>
<ide> static void log_cb(int level, const char *file, int line, int dm_errno_or_class, const char *f, ...)
<ide> {
<del> char buffer[256];
<del> va_list ap;
<add> char *buffer = NULL;
<add> va_list ap;
<ide>
<del> va_start(ap, f);
<del> vsnprintf(buffer, 256, f, ap);
<del> va_end(ap);
<add> va_start(ap, f);
<add> vasprintf(&buffer, f, ap);
<add> va_end(ap);
<ide>
<del> DevmapperLogCallback(level, (char *)file, line, dm_errno_or_class, buffer);
<add> DevmapperLogCallback(level, (char *)file, line, dm_errno_or_class, buffer);
<add> free(buffer);
<ide> }
<ide>
<ide> static void log_with_errno_init()
<ide> {
<del> dm_log_with_errno_init(log_cb);
<add> dm_log_with_errno_init(log_cb);
<ide> }
<ide> */
<ide> import "C" | 1 |
Javascript | Javascript | use tempdir by default | 44cd9fcdeda000368d9927b784b3cfa80be87723 | <ide><path>packager/index.js
<ide> 'use strict';
<ide>
<ide> const Logger = require('./src/Logger');
<add>const TransformCaching = require('./src/lib/TransformCaching');
<ide>
<ide> const debug = require('debug');
<ide> const invariant = require('fbjs/lib/invariant');
<ide> function createServer(options: StrictOptions): Server {
<ide>
<ide> // Some callsites may not be Flowified yet.
<ide> invariant(options.reporter != null, 'createServer() requires reporter');
<del> invariant(options.transformCache != null, 'createServer() requires transformCache');
<add> if (options.transformCache == null) {
<add> options.transformCache = TransformCaching.useTempDir();
<add> }
<ide> const serverOptions = Object.assign({}, options);
<ide> delete serverOptions.verbose;
<ide> const ServerClass = require('./src/Server'); | 1 |
Go | Go | fix panic on daemon restart with running plugin | dbeb4329655e91dbe0e6574405937f03fabf3f2f | <ide><path>plugin/executor/containerd/containerd.go
<ide> type Executor struct {
<ide> exitHandler ExitHandler
<ide> }
<ide>
<add>// deleteTaskAndContainer deletes plugin task and then plugin container from containerd
<add>func deleteTaskAndContainer(ctx context.Context, cli Client, id string) {
<add> _, _, err := cli.DeleteTask(ctx, id)
<add> if err != nil && !errdefs.IsNotFound(err) {
<add> logrus.WithError(err).WithField("id", id).Error("failed to delete plugin task from containerd")
<add> }
<add>
<add> err = cli.Delete(ctx, id)
<add> if err != nil && !errdefs.IsNotFound(err) {
<add> logrus.WithError(err).WithField("id", id).Error("failed to delete plugin container from containerd")
<add> }
<add>}
<add>
<ide> // Create creates a new container
<ide> func (e *Executor) Create(id string, spec specs.Spec, stdout, stderr io.WriteCloser) error {
<ide> opts := runctypes.RuncOptions{
<ide> func (e *Executor) Create(id string, spec specs.Spec, stdout, stderr io.WriteClo
<ide>
<ide> _, err = e.client.Start(ctx, id, "", false, attachStreamsFunc(stdout, stderr))
<ide> if err != nil {
<del> if _, _, err2 := e.client.DeleteTask(ctx, id); err2 != nil && !errdefs.IsNotFound(err2) {
<del> logrus.WithError(err2).WithField("id", id).Warn("Received an error while attempting to clean up containerd plugin task after failed start")
<del> }
<del> if err2 := e.client.Delete(ctx, id); err2 != nil && !errdefs.IsNotFound(err2) {
<del> logrus.WithError(err2).WithField("id", id).Warn("Received an error while attempting to clean up containerd plugin container after failed start")
<del> }
<add> deleteTaskAndContainer(ctx, e.client, id)
<ide> }
<ide> return err
<ide> }
<ide>
<ide> // Restore restores a container
<del>func (e *Executor) Restore(id string, stdout, stderr io.WriteCloser) error {
<add>func (e *Executor) Restore(id string, stdout, stderr io.WriteCloser) (bool, error) {
<ide> alive, _, err := e.client.Restore(context.Background(), id, attachStreamsFunc(stdout, stderr))
<ide> if err != nil && !errdefs.IsNotFound(err) {
<del> return err
<add> return false, err
<ide> }
<ide> if !alive {
<del> _, _, err = e.client.DeleteTask(context.Background(), id)
<del> if err != nil && !errdefs.IsNotFound(err) {
<del> logrus.WithError(err).Errorf("failed to delete container plugin %s task from containerd", id)
<del> }
<del>
<del> err = e.client.Delete(context.Background(), id)
<del> if err != nil && !errdefs.IsNotFound(err) {
<del> logrus.WithError(err).Errorf("failed to delete container plugin %s from containerd", id)
<del> }
<add> deleteTaskAndContainer(context.Background(), e.client, id)
<ide> }
<del> return nil
<add> return alive, nil
<ide> }
<ide>
<ide> // IsRunning returns if the container with the given id is running
<ide> func (e *Executor) Signal(id string, signal int) error {
<ide> func (e *Executor) ProcessEvent(id string, et libcontainerd.EventType, ei libcontainerd.EventInfo) error {
<ide> switch et {
<ide> case libcontainerd.EventExit:
<del> // delete task and container
<del> if _, _, err := e.client.DeleteTask(context.Background(), id); err != nil {
<del> logrus.WithError(err).Errorf("failed to delete container plugin %s task from containerd", id)
<del> }
<del>
<del> if err := e.client.Delete(context.Background(), id); err != nil {
<del> logrus.WithError(err).Errorf("failed to delete container plugin %s from containerd", id)
<del> }
<add> deleteTaskAndContainer(context.Background(), e.client, id)
<ide> return e.exitHandler.HandleExitEvent(ei.ContainerID)
<ide> }
<ide> return nil
<ide><path>plugin/manager.go
<ide> var validFullID = regexp.MustCompile(`^([a-f0-9]{64})$`)
<ide> // Executor is the interface that the plugin manager uses to interact with for starting/stopping plugins
<ide> type Executor interface {
<ide> Create(id string, spec specs.Spec, stdout, stderr io.WriteCloser) error
<del> Restore(id string, stdout, stderr io.WriteCloser) error
<ide> IsRunning(id string) (bool, error)
<add> Restore(id string, stdout, stderr io.WriteCloser) (alive bool, err error)
<ide> Signal(id string, signal int) error
<ide> }
<ide>
<del>func (pm *Manager) restorePlugin(p *v2.Plugin) error {
<add>func (pm *Manager) restorePlugin(p *v2.Plugin, c *controller) error {
<ide> if p.IsEnabled() {
<del> return pm.restore(p)
<add> return pm.restore(p, c)
<ide> }
<ide> return nil
<ide> }
<ide> func (pm *Manager) HandleExitEvent(id string) error {
<ide> return err
<ide> }
<ide>
<del> os.RemoveAll(filepath.Join(pm.config.ExecRoot, id))
<add> if err := os.RemoveAll(filepath.Join(pm.config.ExecRoot, id)); err != nil && !os.IsNotExist(err) {
<add> logrus.WithError(err).WithField("id", id).Error("Could not remove plugin bundle dir")
<add> }
<ide>
<ide> pm.mu.RLock()
<ide> c := pm.cMap[p]
<ide> if c.exitChan != nil {
<ide> close(c.exitChan)
<add> c.exitChan = nil // ignore duplicate events (containerd issue #2299)
<ide> }
<ide> restart := c.restart
<ide> pm.mu.RUnlock()
<ide> func (pm *Manager) reload() error { // todo: restore
<ide> var wg sync.WaitGroup
<ide> wg.Add(len(plugins))
<ide> for _, p := range plugins {
<del> c := &controller{} // todo: remove this
<add> c := &controller{exitChan: make(chan bool)}
<add> pm.mu.Lock()
<ide> pm.cMap[p] = c
<add> pm.mu.Unlock()
<add>
<ide> go func(p *v2.Plugin) {
<ide> defer wg.Done()
<del> if err := pm.restorePlugin(p); err != nil {
<del> logrus.Errorf("failed to restore plugin '%s': %s", p.Name(), err)
<add> if err := pm.restorePlugin(p, c); err != nil {
<add> logrus.WithError(err).WithField("id", p.GetID()).Error("Failed to restore plugin")
<ide> return
<ide> }
<ide>
<ide> func (pm *Manager) reload() error { // todo: restore
<ide> if requiresManualRestore {
<ide> // if liveRestore is not enabled, the plugin will be stopped now so we should enable it
<ide> if err := pm.enable(p, c, true); err != nil {
<del> logrus.Errorf("failed to enable plugin '%s': %s", p.Name(), err)
<add> logrus.WithError(err).WithField("id", p.GetID()).Error("failed to enable plugin")
<ide> }
<ide> }
<ide> }(p)
<ide><path>plugin/manager_linux.go
<ide> func (pm *Manager) pluginPostStart(p *v2.Plugin, c *controller) error {
<ide> client, err := plugins.NewClientWithTimeout(addr.Network()+"://"+addr.String(), nil, p.Timeout())
<ide> if err != nil {
<ide> c.restart = false
<del> shutdownPlugin(p, c, pm.executor)
<add> shutdownPlugin(p, c.exitChan, pm.executor)
<ide> return errors.WithStack(err)
<ide> }
<ide>
<ide> func (pm *Manager) pluginPostStart(p *v2.Plugin, c *controller) error {
<ide> c.restart = false
<ide> // While restoring plugins, we need to explicitly set the state to disabled
<ide> pm.config.Store.SetState(p, false)
<del> shutdownPlugin(p, c, pm.executor)
<add> shutdownPlugin(p, c.exitChan, pm.executor)
<ide> return err
<ide> }
<ide>
<ide> func (pm *Manager) pluginPostStart(p *v2.Plugin, c *controller) error {
<ide> return pm.save(p)
<ide> }
<ide>
<del>func (pm *Manager) restore(p *v2.Plugin) error {
<add>func (pm *Manager) restore(p *v2.Plugin, c *controller) error {
<ide> stdout, stderr := makeLoggerStreams(p.GetID())
<del> if err := pm.executor.Restore(p.GetID(), stdout, stderr); err != nil {
<add> alive, err := pm.executor.Restore(p.GetID(), stdout, stderr)
<add> if err != nil {
<ide> return err
<ide> }
<ide>
<ide> if pm.config.LiveRestoreEnabled {
<del> c := &controller{}
<del> if isRunning, _ := pm.executor.IsRunning(p.GetID()); !isRunning {
<del> // plugin is not running, so follow normal startup procedure
<add> if !alive {
<ide> return pm.enable(p, c, true)
<ide> }
<ide>
<ide> func (pm *Manager) restore(p *v2.Plugin) error {
<ide> return pm.pluginPostStart(p, c)
<ide> }
<ide>
<add> if alive {
<add> // TODO(@cpuguy83): Should we always just re-attach to the running plugin instead of doing this?
<add> c.restart = false
<add> shutdownPlugin(p, c.exitChan, pm.executor)
<add> }
<add>
<ide> return nil
<ide> }
<ide>
<del>func shutdownPlugin(p *v2.Plugin, c *controller, executor Executor) {
<add>func shutdownPlugin(p *v2.Plugin, ec chan bool, executor Executor) {
<ide> pluginID := p.GetID()
<ide>
<ide> err := executor.Signal(pluginID, int(unix.SIGTERM))
<ide> if err != nil {
<ide> logrus.Errorf("Sending SIGTERM to plugin failed with error: %v", err)
<ide> } else {
<ide> select {
<del> case <-c.exitChan:
<add> case <-ec:
<ide> logrus.Debug("Clean shutdown of plugin")
<ide> case <-time.After(time.Second * 10):
<ide> logrus.Debug("Force shutdown plugin")
<ide> if err := executor.Signal(pluginID, int(unix.SIGKILL)); err != nil {
<ide> logrus.Errorf("Sending SIGKILL to plugin failed with error: %v", err)
<ide> }
<ide> select {
<del> case <-c.exitChan:
<add> case <-ec:
<ide> logrus.Debug("SIGKILL plugin shutdown")
<ide> case <-time.After(time.Second * 10):
<ide> logrus.Debug("Force shutdown plugin FAILED")
<ide> func (pm *Manager) disable(p *v2.Plugin, c *controller) error {
<ide> }
<ide>
<ide> c.restart = false
<del> shutdownPlugin(p, c, pm.executor)
<add> shutdownPlugin(p, c.exitChan, pm.executor)
<ide> pm.config.Store.SetState(p, false)
<ide> return pm.save(p)
<ide> }
<ide> func (pm *Manager) Shutdown() {
<ide> }
<ide> if pm.executor != nil && p.IsEnabled() {
<ide> c.restart = false
<del> shutdownPlugin(p, c, pm.executor)
<add> shutdownPlugin(p, c.exitChan, pm.executor)
<ide> }
<ide> }
<ide> if err := mount.RecursiveUnmount(pm.config.Root); err != nil {
<ide><path>plugin/manager_linux_test.go
<ide> package plugin // import "github.com/docker/docker/plugin"
<ide> import (
<ide> "io"
<ide> "io/ioutil"
<add> "net"
<ide> "os"
<ide> "path/filepath"
<ide> "testing"
<ide>
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/pkg/mount"
<add> "github.com/docker/docker/pkg/stringid"
<ide> "github.com/docker/docker/pkg/system"
<ide> "github.com/docker/docker/plugin/v2"
<ide> "github.com/gotestyourself/gotestyourself/skip"
<ide> func TestManagerWithPluginMounts(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> if err := m.Remove(p1.Name(), &types.PluginRmConfig{ForceRemove: true}); err != nil {
<add> if err := m.Remove(p1.GetID(), &types.PluginRmConfig{ForceRemove: true}); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> if mounted, err := mount.Mounted(p2Mount); !mounted || err != nil {
<ide> func TestManagerWithPluginMounts(t *testing.T) {
<ide> }
<ide>
<ide> func newTestPlugin(t *testing.T, name, cap, root string) *v2.Plugin {
<del> rootfs := filepath.Join(root, name)
<add> id := stringid.GenerateNonCryptoID()
<add> rootfs := filepath.Join(root, id)
<ide> if err := os.MkdirAll(rootfs, 0755); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> p := v2.Plugin{PluginObj: types.Plugin{Name: name}}
<add> p := v2.Plugin{PluginObj: types.Plugin{ID: id, Name: name}}
<ide> p.Rootfs = rootfs
<ide> iType := types.PluginInterfaceType{Capability: cap, Prefix: "docker", Version: "1.0"}
<del> i := types.PluginConfigInterface{Socket: "plugins.sock", Types: []types.PluginInterfaceType{iType}}
<add> i := types.PluginConfigInterface{Socket: "plugin.sock", Types: []types.PluginInterfaceType{iType}}
<ide> p.PluginObj.Config.Interface = i
<del> p.PluginObj.ID = name
<add> p.PluginObj.ID = id
<ide>
<ide> return &p
<ide> }
<ide> func (e *simpleExecutor) Create(id string, spec specs.Spec, stdout, stderr io.Wr
<ide> return errors.New("Create failed")
<ide> }
<ide>
<del>func (e *simpleExecutor) Restore(id string, stdout, stderr io.WriteCloser) error {
<del> return nil
<add>func (e *simpleExecutor) Restore(id string, stdout, stderr io.WriteCloser) (bool, error) {
<add> return false, nil
<ide> }
<ide>
<ide> func (e *simpleExecutor) IsRunning(id string) (bool, error) {
<ide> func TestCreateFailed(t *testing.T) {
<ide> t.Fatalf("expected Create failed error, got %v", err)
<ide> }
<ide>
<del> if err := m.Remove(p.Name(), &types.PluginRmConfig{ForceRemove: true}); err != nil {
<add> if err := m.Remove(p.GetID(), &types.PluginRmConfig{ForceRemove: true}); err != nil {
<add> t.Fatal(err)
<add> }
<add>}
<add>
<add>type executorWithRunning struct {
<add> m *Manager
<add> root string
<add> exitChans map[string]chan struct{}
<add>}
<add>
<add>func (e *executorWithRunning) Create(id string, spec specs.Spec, stdout, stderr io.WriteCloser) error {
<add> sockAddr := filepath.Join(e.root, id, "plugin.sock")
<add> ch := make(chan struct{})
<add> if e.exitChans == nil {
<add> e.exitChans = make(map[string]chan struct{})
<add> }
<add> e.exitChans[id] = ch
<add> listenTestPlugin(sockAddr, ch)
<add> return nil
<add>}
<add>
<add>func (e *executorWithRunning) IsRunning(id string) (bool, error) {
<add> return true, nil
<add>}
<add>func (e *executorWithRunning) Restore(id string, stdout, stderr io.WriteCloser) (bool, error) {
<add> return true, nil
<add>}
<add>
<add>func (e *executorWithRunning) Signal(id string, signal int) error {
<add> ch := e.exitChans[id]
<add> ch <- struct{}{}
<add> <-ch
<add> e.m.HandleExitEvent(id)
<add> return nil
<add>}
<add>
<add>func TestPluginAlreadyRunningOnStartup(t *testing.T) {
<add> t.Parallel()
<add>
<add> root, err := ioutil.TempDir("", t.Name())
<add> if err != nil {
<ide> t.Fatal(err)
<ide> }
<add> defer system.EnsureRemoveAll(root)
<add>
<add> for _, test := range []struct {
<add> desc string
<add> config ManagerConfig
<add> }{
<add> {
<add> desc: "live-restore-disabled",
<add> config: ManagerConfig{
<add> LogPluginEvent: func(_, _, _ string) {},
<add> },
<add> },
<add> {
<add> desc: "live-restore-enabled",
<add> config: ManagerConfig{
<add> LogPluginEvent: func(_, _, _ string) {},
<add> LiveRestoreEnabled: true,
<add> },
<add> },
<add> } {
<add> t.Run(test.desc, func(t *testing.T) {
<add> config := test.config
<add> desc := test.desc
<add> t.Parallel()
<add>
<add> p := newTestPlugin(t, desc, desc, config.Root)
<add> p.PluginObj.Enabled = true
<add>
<add> // Need a short-ish path here so we don't run into unix socket path length issues.
<add> config.ExecRoot, err = ioutil.TempDir("", "plugintest")
<add>
<add> executor := &executorWithRunning{root: config.ExecRoot}
<add> config.CreateExecutor = func(m *Manager) (Executor, error) { executor.m = m; return executor, nil }
<add>
<add> if err := executor.Create(p.GetID(), specs.Spec{}, nil, nil); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> root := filepath.Join(root, desc)
<add> config.Root = filepath.Join(root, "manager")
<add> if err := os.MkdirAll(filepath.Join(config.Root, p.GetID()), 0755); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> if !p.IsEnabled() {
<add> t.Fatal("plugin should be enabled")
<add> }
<add> if err := (&Manager{config: config}).save(p); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> s := NewStore()
<add> config.Store = s
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> defer system.EnsureRemoveAll(config.ExecRoot)
<add>
<add> m, err := NewManager(config)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> defer m.Shutdown()
<add>
<add> p = s.GetAll()[p.GetID()] // refresh `p` with what the manager knows
<add> if p.Client() == nil {
<add> t.Fatal("plugin client should not be nil")
<add> }
<add> })
<add> }
<add>}
<add>
<add>func listenTestPlugin(sockAddr string, exit chan struct{}) (net.Listener, error) {
<add> if err := os.MkdirAll(filepath.Dir(sockAddr), 0755); err != nil {
<add> return nil, err
<add> }
<add> l, err := net.Listen("unix", sockAddr)
<add> if err != nil {
<add> return nil, err
<add> }
<add> go func() {
<add> for {
<add> conn, err := l.Accept()
<add> if err != nil {
<add> return
<add> }
<add> conn.Close()
<add> }
<add> }()
<add> go func() {
<add> <-exit
<add> l.Close()
<add> os.Remove(sockAddr)
<add> exit <- struct{}{}
<add> }()
<add> return l, nil
<ide> }
<ide><path>plugin/manager_windows.go
<ide> func (pm *Manager) disable(p *v2.Plugin, c *controller) error {
<ide> return fmt.Errorf("Not implemented")
<ide> }
<ide>
<del>func (pm *Manager) restore(p *v2.Plugin) error {
<add>func (pm *Manager) restore(p *v2.Plugin, c *controller) error {
<ide> return fmt.Errorf("Not implemented")
<ide> }
<ide> | 5 |
Javascript | Javascript | assemble cmap table from strings instead of arrays | 70887f617fc5a8c9b953a3ebbfc507fb9c131bff | <ide><path>fonts.js
<ide> var Font = (function () {
<ide> function createCMAPTable(aGlyphs) {
<ide> var ranges = getRanges(aGlyphs);
<ide>
<del> // The size in bytes of the header is equal to the size of the
<del> // different fields * length of a short + (size of the 4 parallels arrays
<del> // describing segments * length of a short).
<ide> var headerSize = (12 * 2 + (ranges.length * 4 * 2));
<del>
<ide> var segCount = ranges.length + 1;
<ide> var segCount2 = segCount * 2;
<ide> var searchRange = FontsUtils.getMaxPower2(segCount) * 2;
<ide> var Font = (function () {
<ide> s16(searchRange) +
<ide> s16(searchEntry) +
<ide> s16(rangeShift);
<del> cmap = s2a(cmap);
<ide>
<ide> // Fill up the 4 parallel arrays describing the segments.
<del> var startCount = [];
<del> var endCount = [];
<del> var idDeltas = [];
<del> var idRangeOffsets = [];
<del> var glyphsIdsArray = [];
<add> var startCount = "";
<add> var endCount = "";
<add> var idDeltas = "";
<add> var idRangeOffsets = "";
<add> var glyphsIds = "";
<ide> var bias = 0;
<ide> for (var i = 0; i < segCount - 1; i++) {
<ide> var range = ranges[i];
<ide> var Font = (function () {
<ide> var delta = (((start - 1) - bias) ^ 0xffff) + 1;
<ide> bias += (end - start + 1);
<ide>
<del> var start = FontsUtils.integerToBytes(start, 2);
<del> var end = FontsUtils.integerToBytes(end, 2);
<del> var delta = FontsUtils.integerToBytes(delta, 2);
<del>
<del> startCount.push(start[0], start[1]);
<del> endCount.push(end[0], end[1]);
<del> idDeltas.push(delta[0], delta[1]);
<del> idRangeOffsets.push(0x00, 0x00);
<add> startCount += s16(start);
<add> endCount += s16(end);
<add> idDeltas += s16(delta);
<add> idRangeOffsets += s16(0);
<ide>
<ide> for (var j = start; j <= end; j++)
<del> glyphsIdsArray.push(j);
<add> glyphsIds += String.fromCharCode(j);
<ide> }
<del> startCount.push(0xFF, 0xFF);
<del> endCount.push(0xFF, 0xFF);
<del> idDeltas.push(0x00, 0x01);
<del> idRangeOffsets.push(0x00, 0x00);
<ide>
<del> return cmap.concat(endCount, [0x00, 0x00], startCount,
<del> idDeltas, idRangeOffsets, glyphsIdsArray);
<add> startCount += "\xFF\xFF";
<add> endCount += "\xFF\xFF";
<add> idDeltas += "\x00\x01";
<add> idRangeOffsets += "\x00\x00";
<add>
<add> return s2a(cmap + endCount + "\x00\x00" + startCount +
<add> idDeltas + idRangeOffsets + glyphsIds);
<ide> }
<ide>
<ide> // Required Tables | 1 |
Javascript | Javascript | fix typo in testflags | cbafbf4f323ebbc13e9e24214978594d87e9b094 | <ide><path>scripts/jest/TestFlags.js
<ide> function getTestFlags() {
<ide> return new Proxy(
<ide> {
<ide> // Feature flag aliases
<del> old: featureFlags.enableNewReconciler === true,
<add> old: featureFlags.enableNewReconciler === false,
<ide> new: featureFlags.enableNewReconciler === true,
<ide>
<ide> channel: releaseChannel, | 1 |
Python | Python | add extrapolation tests | 98cf811e27138c41e365222cb70f06d70c0db4ee | <ide><path>numpy/lib/tests/test_function_base.py
<ide> def test_nearest(self, dtype):
<ide> assert_equal(np.percentile(np.arange(10, dtype=dtype), 49,
<ide> interpolation='nearest'), 4)
<ide>
<add> def test_linear_interpolation_extrapolation(self):
<add> arr = np.random.rand(5)
<add>
<add> actual = np.percentile(arr, 100)
<add> np.testing.assert_equal(actual, arr.max())
<add>
<add> actual = np.percentile(arr, 0)
<add> np.testing.assert_equal(actual, arr.min())
<add>
<ide> def test_sequence(self):
<ide> x = np.arange(8) * 0.5
<ide> assert_equal(np.percentile(x, [0, 100, 50]), [0, 3.5, 1.75]) | 1 |
PHP | PHP | fix failing test in debugger test case | e9779e71266c68919e3a7221bc0147484f47ee18 | <ide><path>lib/Cake/Test/Case/Utility/DebuggerTest.php
<ide> public function testExportVar() {
<ide> $expected = <<<TEXT
<ide> object(View) {
<ide> Helpers => object(HelperCollection) {}
<add> Blocks => object(ViewBlock) {}
<ide> plugin => null
<ide> name => ''
<ide> passedArgs => array()
<ide> public function testExportVar() {
<ide> validationErrors => array()
<ide> hasRendered => false
<ide> uuids => array()
<del> output => false
<ide> request => null
<ide> elementCache => 'default'
<ide> int => (int) 2
<ide> float => (float) 1.333
<ide> }
<ide> TEXT;
<del> $result = str_replace(array("\r\n", "\n"), "", $result);
<del> $expected = str_replace(array("\r\n", "\n"), "", $expected);
<add> // $result = str_replace(array("\r\n", "\n"), "", $result);
<add> // $expected = str_replace(array("\r\n", "\n"), "", $expected);
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide>
<ide><path>lib/Cake/View/View.php
<ide> public function render($view = null, $layout = null) {
<ide> if (!$this->_helpersLoaded) {
<ide> $this->loadHelpers();
<ide> }
<del> $this->output = '';
<add> $this->Blocks->set('content', '');
<ide>
<ide> if ($view !== false && $viewFileName = $this->_getViewFileName($view)) {
<ide> $this->_currentType = self::TYPE_VIEW;
<ide> $this->Helpers->trigger('beforeRender', array($viewFileName));
<del> $this->output = $this->_render($viewFileName);
<add> $this->Blocks->set('content', $this->_render($viewFileName));
<ide> $this->Helpers->trigger('afterRender', array($viewFileName));
<ide> }
<ide>
<ide> if ($layout === null) {
<ide> $layout = $this->layout;
<ide> }
<ide> if ($layout && $this->autoLayout) {
<del> $this->output = $this->renderLayout('', $layout);
<add> $this->Blocks->set('content', $this->renderLayout('', $layout));
<ide> }
<ide> $this->hasRendered = true;
<del> return $this->output;
<add> return $this->Blocks->get('content');
<ide> }
<ide>
<ide> /**
<ide> public function renderLayout($content, $layout = null) {
<ide> }
<ide>
<ide> $this->_currentType = self::TYPE_LAYOUT;
<del> $this->output = $this->_render($layoutFileName);
<add> $this->Blocks->set('content', $this->_render($layoutFileName));
<ide>
<ide> $this->Helpers->trigger('afterLayout', array($layoutFileName));
<del> return $this->output;
<add> return $this->Blocks->get('content');
<ide> }
<ide>
<ide> /**
<ide> public function __get($name) {
<ide> return $this->request;
<ide> case 'output':
<ide> return $this->Blocks->get('content');
<add> default:
<add> return $this->{$name};
<ide> }
<ide> return null;
<ide> }
<ide> public function __set($name, $value) {
<ide> switch ($name) {
<ide> case 'output':
<ide> return $this->Blocks->set('content', $value);
<add> default:
<add> $this->{$name} = $value;
<ide> }
<ide> }
<ide> | 2 |
Python | Python | unbreak non-linux platforms | 837193ef7bdaf2b37d176cd750235ab0008c2e12 | <ide><path>unitest.py
<ide> import time
<ide> import unittest
<ide>
<del>from glances.outputs.glances_bars import Bar
<del>from glances.core.glances_globals import (
<del> appname,
<del> is_linux,
<del> version
<del>)
<del>
<ide> # Global variables
<ide> # =================
<ide>
<del># Unitary test is only available from a GNU/Linus machine
<del>if not is_linux:
<del> print('ERROR: Unitaries tests should be ran on GNU/Linux operating system')
<del> sys.exit(2)
<del>else:
<del> print('Unitary tests for {0} {1}'.format(appname, version))
<del>
<ide> # Init Glances core
<ide> from glances.core.glances_main import GlancesMain
<ide> core = GlancesMain()
<ide> from glances.core.glances_stats import GlancesStats
<ide> stats = GlancesStats()
<ide>
<add>from glances.core.glances_globals import is_windows, version
<add>from glances.outputs.glances_bars import Bar
<ide>
<ide> # Unitest class
<ide> # ==============
<add>print('Unitary tests for Glances %s' % version)
<add>
<ide>
<ide> class TestGlances(unittest.TestCase):
<ide>
<ide> def test_003_cpu(self):
<ide> self.assertLessEqual(stats_grab[stat], 100)
<ide> print('INFO: CPU stats: %s' % stats_grab)
<ide>
<add> @unittest.skipIf(is_windows, "Load average not available on Windows")
<ide> def test_004_load(self):
<ide> """Check LOAD plugin."""
<ide> stats_to_check = ['cpucore', 'min1', 'min5', 'min15'] | 1 |
Javascript | Javascript | fix typos in optional locale definitions | 8e1ec1e74ba68c0bb68ccd0257a37064e03d7b50 | <ide><path>src/locale/en-GB.js
<ide> import "locale";
<ide>
<del>var d3.locale.en_GB = d3.locale({
<add>d3.locale.en_GB = d3.locale({
<ide> decimal: ".",
<ide> thousands: ",",
<ide> grouping: [3],
<ide><path>src/locale/zh-CN.js
<ide> import "locale";
<ide>
<del>var d3.locale.zh_CN = d3.locale({
<add>d3.locale.zh_CN = d3.locale({
<ide> decimal: ".",
<ide> thousands: ",",
<ide> grouping: [3], | 2 |
Javascript | Javascript | set hot test cases timeout to 5s | f072fd2978a2e02f453aa7853953f11dcb94c079 | <ide><path>test/HotTestCases.test.js
<ide> describe("HotTestCases", () => {
<ide>
<ide> function _it(title, fn) {
<ide> const test = new Test(title, fn);
<add> test.timeout(5000);
<ide> suite.addTest(test);
<ide> exportedTests++;
<ide> return test; | 1 |
PHP | PHP | avoid failing tests by 1 second diff | 7e5ef1dc0d25fa6e4efdd4c8e2448871732a5fc2 | <ide><path>lib/Cake/Test/Case/Network/Email/DebugTransportTest.php
<ide> public function testSend() {
<ide> $email->bcc('phpnut@cakephp.org');
<ide> $email->messageID('<4d9946cf-0a44-4907-88fe-1d0ccbdd56cb@localhost>');
<ide> $email->subject('Testing Message');
<add> $date = date(DATE_RFC2822);
<add> $email->setHeaders(array('X-Mailer' => $email::EMAIL_CLIENT, 'Date' => $date));
<ide> $email->expects($this->any())->method('message')->will($this->returnValue(array('First Line', 'Second Line', '')));
<ide>
<ide> $headers = "From: CakePHP Test <noreply@cakephp.org>\r\n";
<ide> $headers .= "To: CakePHP <cake@cakephp.org>\r\n";
<ide> $headers .= "Cc: Mark Story <mark@cakephp.org>, Juan Basso <juan@cakephp.org>\r\n";
<ide> $headers .= "X-Mailer: CakePHP Email\r\n";
<del> $headers .= "Date: " . date(DATE_RFC2822) . "\r\n";
<add> $headers .= "Date: " . $date . "\r\n";
<ide> $headers .= "Message-ID: <4d9946cf-0a44-4907-88fe-1d0ccbdd56cb@localhost>\r\n";
<ide> $headers .= "Subject: Testing Message\r\n";
<ide> $headers .= "MIME-Version: 1.0\r\n";
<ide><path>lib/Cake/Test/Case/Network/Email/SmtpTransportTest.php
<ide> public function testSendData() {
<ide> $email->bcc('phpnut@cakephp.org');
<ide> $email->messageID('<4d9946cf-0a44-4907-88fe-1d0ccbdd56cb@localhost>');
<ide> $email->subject('Testing SMTP');
<add> $date = date(DATE_RFC2822);
<add> $email->setHeaders(array('X-Mailer' => $email::EMAIL_CLIENT, 'Date' => $date));
<ide> $email->expects($this->any())->method('message')->will($this->returnValue(array('First Line', 'Second Line', '')));
<ide>
<ide> $data = "From: CakePHP Test <noreply@cakephp.org>\r\n";
<ide> $data .= "Return-Path: CakePHP Return <pleasereply@cakephp.org>\r\n";
<ide> $data .= "To: CakePHP <cake@cakephp.org>\r\n";
<ide> $data .= "Cc: Mark Story <mark@cakephp.org>, Juan Basso <juan@cakephp.org>\r\n";
<ide> $data .= "X-Mailer: CakePHP Email\r\n";
<del> $data .= "Date: " . date(DATE_RFC2822) . "\r\n";
<add> $data .= "Date: " . $date . "\r\n";
<ide> $data .= "Message-ID: <4d9946cf-0a44-4907-88fe-1d0ccbdd56cb@localhost>\r\n";
<ide> $data .= "Subject: Testing SMTP\r\n";
<ide> $data .= "MIME-Version: 1.0\r\n"; | 2 |
Javascript | Javascript | remove unneeded callback check | c9d7b753469e63bee13badff16ed6dbfb9222e6c | <ide><path>lib/_debugger.js
<ide> Client.prototype.mirrorObject = function(handle, depth, cb) {
<ide>
<ide> waitForOthers();
<ide> function waitForOthers() {
<del> if (--waiting === 0 && cb) {
<add> if (--waiting === 0) {
<ide> keyValues.forEach(function(kv) {
<ide> mirror[kv.name] = kv.value;
<ide> }); | 1 |
Javascript | Javascript | fix typo of unkown to unknown | b95228ed89fa163056945210f4ebd3554165f390 | <ide><path>examples/with-context-api/components/Counter.js
<ide> const reducer = (state, action) => {
<ide> case 'INCREASE_BY':
<ide> return state + action.payload
<ide> default:
<del> throw new Error(`Unkown action: ${action.type}`)
<add> throw new Error(`Unknown action: ${action.type}`)
<ide> }
<ide> }
<ide> | 1 |
Javascript | Javascript | remove outdated support tests | ccf7abafa6843e70fb71f458cea5d5567cb5984d | <ide><path>test/unit/support.js
<ide> testIframeWithCallback( "box-sizing does not affect jQuery.support.shrinkWrapBlo
<ide> expect( 1 );
<ide> strictEqual( shrinkWrapBlocks, jQuery.support.shrinkWrapBlocks, "jQuery.support.shrinkWrapBlocks properties are the same" );
<ide> });
<del>
<del>(function() {
<del> var expected,
<del> userAgent = window.navigator.userAgent;
<del>
<del> // These tests do not have to stay
<del> // They are here to help with upcoming support changes for 1.8
<del> if ( /chrome/i.test( userAgent ) ) {
<del> expected = {
<del> "leadingWhitespace":true,
<del> "tbody":true,
<del> "htmlSerialize":true,
<del> "style":true,
<del> "hrefNormalized":true,
<del> "opacity":true,
<del> "cssFloat":true,
<del> "checkOn":true,
<del> "optSelected":true,
<del> "getSetAttribute":true,
<del> "enctype":true,
<del> "html5Clone":true,
<del> "submitBubbles":true,
<del> "changeBubbles":true,
<del> "focusinBubbles":false,
<del> "deleteExpando":true,
<del> "noCloneEvent":true,
<del> "inlineBlockNeedsLayout":false,
<del> "shrinkWrapBlocks":false,
<del> "reliableMarginRight":true,
<del> "noCloneChecked":true,
<del> "optDisabled":true,
<del> "radioValue":true,
<del> "checkClone":true,
<del> "appendChecked":true,
<del> "boxModel":true,
<del> "reliableHiddenOffsets":true,
<del> "ajax":true,
<del> "cors":true,
<del> "doesNotIncludeMarginInBodyOffset":true
<del> };
<del> } else if ( /opera.*version\/12\.1/i.test( userAgent ) ) {
<del> expected = {
<del> "leadingWhitespace":true,
<del> "tbody":true,
<del> "htmlSerialize":true,
<del> "style":true,
<del> "hrefNormalized":true,
<del> "opacity":true,
<del> "cssFloat":true,
<del> "checkOn":true,
<del> "optSelected":true,
<del> "getSetAttribute":true,
<del> "enctype":true,
<del> "html5Clone":true,
<del> "submitBubbles":true,
<del> "changeBubbles":true,
<del> "focusinBubbles":false,
<del> "deleteExpando":true,
<del> "noCloneEvent":true,
<del> "inlineBlockNeedsLayout":false,
<del> "shrinkWrapBlocks":false,
<del> "reliableMarginRight":true,
<del> "noCloneChecked":true,
<del> "optDisabled":true,
<del> "radioValue":false,
<del> "checkClone":true,
<del> "appendChecked":true,
<del> "boxModel":true,
<del> "reliableHiddenOffsets":true,
<del> "ajax":true,
<del> "cors":true,
<del> "doesNotIncludeMarginInBodyOffset":true
<del> };
<del> } else if ( /msie 10\.0/i.test( userAgent ) ) {
<del> expected = {
<del> "leadingWhitespace":true,
<del> "tbody":true,
<del> "htmlSerialize":true,
<del> "style":true,
<del> "hrefNormalized":true,
<del> "opacity":true,
<del> "cssFloat":true,
<del> "checkOn":true,
<del> "optSelected":false,
<del> "getSetAttribute":true,
<del> "enctype":true,
<del> "html5Clone":true,
<del> "submitBubbles":true,
<del> "changeBubbles":true,
<del> "focusinBubbles":true,
<del> "deleteExpando":true,
<del> "noCloneEvent":true,
<del> "inlineBlockNeedsLayout":false,
<del> "shrinkWrapBlocks":false,
<del> "reliableMarginRight":true,
<del> "noCloneChecked":false,
<del> "optDisabled":true,
<del> "radioValue":false,
<del> "checkClone":true,
<del> "appendChecked":true,
<del> "boxModel":true,
<del> "reliableHiddenOffsets":true,
<del> "ajax":true,
<del> "cors":true,
<del> "doesNotIncludeMarginInBodyOffset":true
<del> };
<del> } else if ( /msie 9\.0/i.test( userAgent ) ) {
<del> expected = {
<del> "leadingWhitespace":true,
<del> "tbody":true,
<del> "htmlSerialize":true,
<del> "style":true,
<del> "hrefNormalized":true,
<del> "opacity":true,
<del> "cssFloat":true,
<del> "checkOn":true,
<del> "optSelected":false,
<del> "getSetAttribute":true,
<del> "enctype":true,
<del> "html5Clone":true,
<del> "submitBubbles":true,
<del> "changeBubbles":true,
<del> "focusinBubbles":true,
<del> "deleteExpando":true,
<del> "noCloneEvent":true,
<del> "inlineBlockNeedsLayout":false,
<del> "shrinkWrapBlocks":false,
<del> "reliableMarginRight":true,
<del> "noCloneChecked":false,
<del> "optDisabled":true,
<del> "radioValue":false,
<del> "checkClone":true,
<del> "appendChecked":true,
<del> "boxModel":true,
<del> "reliableHiddenOffsets":true,
<del> "ajax":true,
<del> "cors":false,
<del> "doesNotIncludeMarginInBodyOffset":true
<del> };
<del> } else if ( /msie 8\.0/i.test( userAgent ) ) {
<del> expected = {
<del> "leadingWhitespace":false,
<del> "tbody":true,
<del> "htmlSerialize":false,
<del> "style":false,
<del> "hrefNormalized":true,
<del> "opacity":false,
<del> "cssFloat":false,
<del> "checkOn":true,
<del> "optSelected":false,
<del> "getSetAttribute":true,
<del> "enctype":true,
<del> "html5Clone":false,
<del> "submitBubbles":false,
<del> "changeBubbles":false,
<del> "focusinBubbles":true,
<del> "deleteExpando":false,
<del> "noCloneEvent":false,
<del> "inlineBlockNeedsLayout":false,
<del> "shrinkWrapBlocks":false,
<del> "reliableMarginRight":true,
<del> "noCloneChecked":false,
<del> "optDisabled":true,
<del> "radioValue":false,
<del> "checkClone":true,
<del> "appendChecked":true,
<del> "boxModel":true,
<del> "reliableHiddenOffsets":false,
<del> "ajax":true,
<del> "cors":false,
<del> "doesNotIncludeMarginInBodyOffset":true
<del> };
<del> } else if ( /msie 7\.0/i.test( userAgent ) ) {
<del> expected = {
<del> "ajax": true,
<del> "appendChecked": false,
<del> "boxModel": true,
<del> "changeBubbles": false,
<del> "checkClone": false,
<del> "checkOn": true,
<del> "cors": false,
<del> "cssFloat": false,
<del> "deleteExpando": false,
<del> "doesNotIncludeMarginInBodyOffset": true,
<del> "enctype": true,
<del> "focusinBubbles": true,
<del> "getSetAttribute": false,
<del> "hrefNormalized": false,
<del> "html5Clone": false,
<del> "htmlSerialize": false,
<del> "inlineBlockNeedsLayout": true,
<del> "leadingWhitespace": false,
<del> "noCloneChecked": false,
<del> "noCloneEvent": false,
<del> "opacity": false,
<del> "optDisabled": true,
<del> "optSelected": false,
<del> "radioValue": false,
<del> "reliableHiddenOffsets": false,
<del> "reliableMarginRight": true,
<del> "shrinkWrapBlocks": false,
<del> "submitBubbles": false,
<del> "tbody": false,
<del> "style": false
<del> };
<del> } else if ( /msie 6\.0/i.test( userAgent ) ) {
<del> expected = {
<del> "leadingWhitespace":false,
<del> "tbody":false,
<del> "htmlSerialize":false,
<del> "style":false,
<del> "hrefNormalized":false,
<del> "opacity":false,
<del> "cssFloat":false,
<del> "checkOn":true,
<del> "optSelected":false,
<del> "getSetAttribute":false,
<del> "enctype":true,
<del> "html5Clone":false,
<del> "submitBubbles":false,
<del> "changeBubbles":false,
<del> "focusinBubbles":true,
<del> "deleteExpando":false,
<del> "noCloneEvent":false,
<del> "inlineBlockNeedsLayout":true,
<del> "shrinkWrapBlocks":true,
<del> "reliableMarginRight":true,
<del> "noCloneChecked":false,
<del> "optDisabled":true,
<del> "radioValue":false,
<del> "checkClone":false,
<del> "appendChecked":false,
<del> "boxModel":true,
<del> "reliableHiddenOffsets":false,
<del> "ajax":true,
<del> "cors":false,
<del> "doesNotIncludeMarginInBodyOffset":true
<del> };
<del> } else if ( /5\.1\.1 safari/i.test( userAgent ) ) {
<del> expected = {
<del> "leadingWhitespace":true,
<del> "tbody":true,
<del> "htmlSerialize":true,
<del> "style":true,
<del> "hrefNormalized":true,
<del> "opacity":true,
<del> "cssFloat":true,
<del> "checkOn":false,
<del> "optSelected":true,
<del> "getSetAttribute":true,
<del> "enctype":true,
<del> "html5Clone":true,
<del> "submitBubbles":true,
<del> "changeBubbles":true,
<del> "focusinBubbles":false,
<del> "deleteExpando":true,
<del> "noCloneEvent":true,
<del> "inlineBlockNeedsLayout":false,
<del> "shrinkWrapBlocks":false,
<del> "reliableMarginRight":true,
<del> "noCloneChecked":true,
<del> "optDisabled":true,
<del> "radioValue":true,
<del> "checkClone":false,
<del> "appendChecked":false,
<del> "boxModel":true,
<del> "reliableHiddenOffsets":true,
<del> "ajax":true,
<del> "cors":true,
<del> "doesNotIncludeMarginInBodyOffset":true
<del> };
<del> } else if ( /firefox/i.test( userAgent ) ) {
<del> expected = {
<del> "leadingWhitespace":true,
<del> "tbody":true,
<del> "htmlSerialize":true,
<del> "style":true,
<del> "hrefNormalized":true,
<del> "opacity":true,
<del> "cssFloat":true,
<del> "checkOn":true,
<del> "optSelected":true,
<del> "getSetAttribute":true,
<del> "enctype":true,
<del> "html5Clone":true,
<del> "submitBubbles":true,
<del> "changeBubbles":true,
<del> "focusinBubbles":false,
<del> "deleteExpando":true,
<del> "noCloneEvent":true,
<del> "inlineBlockNeedsLayout":false,
<del> "shrinkWrapBlocks":false,
<del> "reliableMarginRight":true,
<del> "noCloneChecked":true,
<del> "optDisabled":true,
<del> "radioValue":true,
<del> "checkClone":true,
<del> "appendChecked":true,
<del> "boxModel":true,
<del> "reliableHiddenOffsets":true,
<del> "ajax":true,
<del> "cors":true,
<del> "doesNotIncludeMarginInBodyOffset":true
<del> };
<del> }
<del>
<del> if ( expected ) {
<del> test("Verify that the support tests resolve as expected per browser", function() {
<del> expect( 30 );
<del>
<del> for ( var i in expected ) {
<del> if ( jQuery.ajax || i !== "ajax" && i !== "cors" ) {
<del> equal( jQuery.support[i], expected[i], "jQuery.support['" + i + "']: " + jQuery.support[i] + ", expected['" + i + "']: " + expected[i]);
<del> } else {
<del> ok( true, "no ajax; skipping jQuery.support['" + i + "']" );
<del> }
<del> }
<del> });
<del> }
<del>
<del>})(); | 1 |
Ruby | Ruby | require git log only when not strict | 84f544f08ff280ea1750a647933e4bb6420c5b22 | <ide><path>Library/Homebrew/formula_auditor.rb
<ide> def audit_conflicts
<ide> def audit_gcc_dependency
<ide> return unless @git
<ide> return unless @core_tap
<del> return unless formula.tap.git? # git log is required
<add> return if !@strict && !formula.tap.git? # git log is required for non-strict audit
<ide> return unless Homebrew::SimulateSystem.simulating_or_running_on_linux?
<ide> return unless linux_only_gcc_dep?(formula)
<ide> | 1 |
Javascript | Javascript | add fix for overwriting style attribute bindings | db465aefdbe4472dc90bfdd481b7cdedd1095bda | <ide><path>packages/ember-views/lib/system/build-component-template.js
<ide> function normalizeComponentAttributes(component, attrs) {
<ide> }
<ide>
<ide> if (component.isVisible === false) {
<del> normalized.style = ['value', "display: none;"];
<add> var hiddenStyle = ['value', "display: none;"];
<add> var existingStyle = normalized.style;
<add>
<add> if (existingStyle) {
<add> normalized.style = ['subexpr', '-concat', [existingStyle, hiddenStyle], ['separator', ' ']];
<add> } else {
<add> normalized.style = hiddenStyle;
<add> }
<ide> }
<ide>
<ide> return normalized;
<ide><path>packages/ember-views/tests/views/view/is_visible_test.js
<ide> QUnit.test("should hide element if isVisible is false before element is created"
<ide> });
<ide> });
<ide>
<add>QUnit.test("doesn't overwrite existing style attribute bindings", function() {
<add> view = EmberView.create({
<add> isVisible: false,
<add> attributeBindings: ['style'],
<add> style: 'color: blue;'
<add> });
<add>
<add> run(function() {
<add> view.append();
<add> });
<add>
<add> equal(view.$().attr('style'), 'color: blue; display: none;', "has concatenated style attribute");
<add>});
<add>
<ide> QUnit.module("EmberView#isVisible with Container", {
<ide> setup() {
<ide> expectDeprecation("Setting `childViews` on a Container is deprecated."); | 2 |
Python | Python | fix gpu installation. closes | 02d7b41893a98800c3a9514234a1d525868e611e | <ide><path>setup.py
<ide> def setup_package():
<ide> ],
<ide> setup_requires=["wheel"],
<ide> extras_require={
<del> "cuda": ["cupy>=4.0"],
<del> "cuda80": ["cupy-cuda80>=4.0"],
<del> "cuda90": ["cupy-cuda90>=4.0"],
<del> "cuda91": ["cupy-cuda91>=4.0"],
<del> "cuda92": ["cupy-cuda92>=4.0"],
<del> "cuda100": ["cupy-cuda100>=4.0"],
<add> "cuda": ["thinc_gpu_ops>=0.0.1,<0.1.0", "cupy>=5.0.0b4"],
<add> "cuda80": ["thinc_gpu_ops>=0.0.1,<0.1.0", "cupy-cuda80>=5.0.0b4"],
<add> "cuda90": ["thinc_gpu_ops>=0.0.1,<0.1.0", "cupy-cuda90>=5.0.0b4"],
<add> "cuda91": ["thinc_gpu_ops>=0.0.1,<0.1.0", "cupy-cuda91>=5.0.0b4"],
<add> "cuda92": ["thinc_gpu_ops>=0.0.1,<0.1.0", "cupy-cuda92>=5.0.0b4"],
<add> "cuda100": ["thinc_gpu_ops>=0.0.1,<0.1.0", "cupy-cuda100>=5.0.0b4"],
<ide> # Language tokenizers with external dependencies
<ide> "ja": ["mecab-python3==0.7"],
<ide> }, | 1 |
Text | Text | add guide for gatsby.js caching | 2b40551efb4addaa227f8ad4b3af9b937a475bf1 | <ide><path>guide/english/gatsbyjs/gatsbyjs-caching/index.md
<add>---
<add>title: Gatsby.js Caching
<add>---
<add>
<add>## Gatsby.js Caching Static Sites
<add>
<add>An important part of creating a very fast website is setting up proper HTTP caching. HTTP caching allows browsers to cache resources from a website so that when the user returns to a site, very few parts of the website have to be downloaded. Gatsby does this job automatically for you through Webpack.
<add>
<add>HTML files should never be cached while all files in `public/static/` should be cached forever. Also, other files e.g. JavaScript files should also be cached forever.
<add>
<add>## Cache Controls Headers
<add>
<add>HTML - The `cache-control` header should be `cache-control: public, max-age=0, must-revalidate`
<add>Static Files (`/public/static`) - The `cache-control` header should be `cache-control: public,max-age=31536000,immutable`
<add>JavaScript - The `cache-control` header should be `cache-control: public, max-age=31536000,immutable`
<add>
<add>## Plugins
<add>
<add>[Gatsby Plugin Netlify](https://www.gatsbyjs.org/packages/gatsby-plugin-netlify/) was created for automating caching when hosting your site at [Netlify](www.netlify.com).
<add>
<add>### More Information:
<add>Check out the Gatsby.js official docs for caching at [Gatsby Caching](https://www.gatsbyjs.org/docs/caching). For more information and learn more, visit: [Gatsby.js official site](https://www.gatsbyjs.org/tutorial/) | 1 |
Python | Python | fix high memory usage in download command | 692eb0603d5305a19407302721d4cd6790235496 | <ide><path>spacy/cli/download.py
<ide> def get_version(model, comp):
<ide> def download_model(filename):
<ide> util.print_msg("Downloading {f}".format(f=filename))
<ide> download_url = about.__download_url__ + '/' + filename
<del> subprocess.call([sys.executable, '-m', 'pip', 'install', download_url],
<add> subprocess.call([sys.executable, '-m',
<add> 'pip', 'install', '--no-cache-dir', download_url],
<ide> env=os.environ.copy())
<ide>
<ide> | 1 |
Javascript | Javascript | remove time check | 9a6cfcef33f5c9d0bd53420987764bf06e9e6a8a | <ide><path>test/parallel/test-child-process-fork-net2.js
<ide> if (process.argv[2] === 'child') {
<ide> });
<ide>
<ide> var closeEmitted = false;
<del> server.on('close', function() {
<del> console.error('[m] server close');
<add> server.on('close', common.mustCall(function() {
<ide> closeEmitted = true;
<ide>
<del> console.error('[m] killing child processes');
<ide> child1.kill();
<ide> child2.kill();
<ide> child3.kill();
<del> });
<add> }));
<ide>
<ide> server.listen(common.PORT, '127.0.0.1');
<ide>
<del> var timeElapsed = 0;
<ide> var closeServer = function() {
<del> console.error('[m] closeServer');
<del> var startTime = Date.now();
<del> server.on('close', function() {
<del> console.error('[m] emit(close)');
<del> timeElapsed = Date.now() - startTime;
<del> });
<del>
<del> console.error('[m] calling server.close');
<ide> server.close();
<ide>
<ide> setTimeout(function() {
<ide> assert(!closeEmitted);
<del> console.error('[m] sending close to children');
<ide> child1.send('close');
<ide> child2.send('close');
<ide> child3.disconnect();
<ide> }, 200);
<ide> };
<ide>
<del> var min = 190;
<del> var max = common.platformTimeout(2000);
<ide> process.on('exit', function() {
<ide> assert.equal(disconnected, count);
<ide> assert.equal(connected, count);
<del> assert.ok(closeEmitted);
<del> assert.ok(timeElapsed >= min && timeElapsed <= max,
<del> `timeElapsed was not between ${min} and ${max} ms:` +
<del> `${timeElapsed}`);
<ide> });
<ide> } | 1 |
Text | Text | tweak the prose a little | 814916457b50082e4299691ae92b4ed368ddb076 | <ide><path>docs/sources/articles/host_integration.md
<ide> a new service that will be started after the docker daemon service has started.
<ide> [Service]
<ide> Restart=always
<ide> ExecStart=/usr/bin/docker start -a redis_server
<del> # for more options, use 'run' instead of 'start', but not suggested
<del> # ExecStart=/usr/bin/docker run redis_server
<ide> ExecStop=/usr/bin/docker stop -t 2 redis_server
<ide>
<ide> [Install]
<ide> WantedBy=local.target
<ide>
<del>if you need to pass options to the redis container (such as '--env'),
<del>then you'll need to use 'docker run' rather than 'docker start'.
<add>If you need to pass options to the redis container (such as `--env`),
<add>then you'll need to use `docker run` rather than `docker start`. This will
<add>create a new container every time the service is started, which will be stopped
<add>and removed when the service is stopped.
<ide>
<ide> [Service]
<ide> ...
<del> ExecStart=/usr/bin/docker run --env foo=bar redis_server
<add> ExecStart=/usr/bin/docker run --env foo=bar --name redis_server redis
<add> ExecStop=/usr/bin/docker stop -t 2 redis_server ; /usr/bin/docker rm -f redis_server
<ide> ... | 1 |
Ruby | Ruby | add comment about refinement scope | ccf396887a283595affef49d8a1e445f45fecf06 | <ide><path>Library/Homebrew/cleanup.rb
<ide> def cleanup_unreferenced_downloads
<ide> return if dry_run?
<ide> return unless (cache/"downloads").directory?
<ide>
<add> # We can't use `.reject(&:incomplete?) here due to the refinement scope.
<ide> downloads = (cache/"downloads").children.reject { |path| path.incomplete? } # rubocop:disable Style/SymbolProc
<ide> referenced_downloads = [cache, cache/"Cask"].select(&:directory?)
<ide> .flat_map(&:children) | 1 |
Go | Go | remove hack in version | b2b9334f27e1a773b77241efa214af2e87439d3b | <ide><path>server/server.go
<ide> func (srv *Server) DockerInfo(job *engine.Job) engine.Status {
<ide> func (srv *Server) DockerVersion(job *engine.Job) engine.Status {
<ide> v := &engine.Env{}
<ide> v.Set("Version", dockerversion.VERSION)
<del> v.SetJson("ApiVersion", api.APIVERSION)
<add> v.Set("ApiVersion", string(api.APIVERSION))
<ide> v.Set("GitCommit", dockerversion.GITCOMMIT)
<ide> v.Set("GoVersion", goruntime.Version())
<ide> v.Set("Os", goruntime.GOOS) | 1 |
PHP | PHP | improve doc blocks | 61608ca46d77c23de110419ee3d44845703d7848 | <ide><path>src/Validation/Validation.php
<ide> public static function truthy($check, array $truthyValues = [])
<ide> /**
<ide> * Validates if passed value is falsey.
<ide> *
<del> * The list of what is considered to be truthy values, may be set via $falseyValues.
<add> * The list of what is considered to be falsey values, may be set via $falseyValues.
<ide> *
<ide> * @param boolean|integer|string $check Value to check.
<ide> * @param array $falseyValues List of valid falsey values, defaults to `[false, 0, '0']`. | 1 |
Text | Text | remove the link for code.whytheluckystiff.net | 0dea33f770305f32ed7476f520f7c1ff17434fdc | <ide><path>guides/source/rails_application_templates.md
<ide> end
<ide>
<ide> Adds the given source to the generated application's `Gemfile`.
<ide>
<del>For example, if you need to source a gem from "[http://code.whytheluckystiff.net](http://code.whytheluckystiff.net)":
<add>For example, if you need to source a gem from `"http://code.whytheluckystiff.net"`:
<ide>
<ide> ```ruby
<ide> add_source "http://code.whytheluckystiff.net" | 1 |
PHP | PHP | add missing underscore to _decodebody | b8b382f8e7f2e577d38650a5f73c74b01785e4fb | <ide><path>cake/libs/http_socket.php
<ide> function _decodeBody($body, $encoding = 'chunked') {
<ide> if (empty($encoding)) {
<ide> return array('body' => $body, 'header' => false);
<ide> }
<del> $decodeMethod = 'decode'.Inflector::camelize(str_replace('-', '_', $encoding)).'Body';
<add> $decodeMethod = '_decode'.Inflector::camelize(str_replace('-', '_', $encoding)).'Body';
<ide>
<ide> if (!is_callable(array(&$this, $decodeMethod))) {
<ide> if (!$this->quirksMode) { | 1 |
Text | Text | add cdnjs to docs. fixes #244 | 3d1cc16a9b143b96b353b7b03c06ca0f7e544304 | <ide><path>README.md
<ide> You'll notice that we used an XML-like syntax; [we call it JSX](http://facebook.
<ide>
<ide> ## Installation
<ide>
<del>The fastest way to get started is to serve JavaScript from the CDN:
<add>The fastest way to get started is to serve JavaScript from the CDN (also available on [CDNJS](http://cdnjs.com/#react)):
<ide>
<ide> ```html
<ide> <!-- The core React library -->
<ide><path>docs/downloads.md
<ide> The JSX transformer used to support [XML syntax](/react/docs/jsx-in-depth.html)
<ide> <script src="http://fb.me/JSXTransformer-{{site.react_version}}.js"></script>
<ide> ```
<ide>
<add>All scripts are also available via [CDNJS](http://cdnjs.com/#react).
<add>
<ide> ## Bower
<ide>
<ide> ```sh | 2 |
Javascript | Javascript | ensure callback runs in test-vm-sigint | fd02c93d29da1ff18f33cc561bdddce2facd28db | <ide><path>test/parallel/test-vm-sigint.js
<ide> process.on('SIGUSR2', common.mustCall(() => {
<ide> process.kill(child.pid, 'SIGINT');
<ide> }));
<ide>
<del>child.on('close', function(code, signal) {
<add>child.on('close', common.mustCall((code, signal) => {
<ide> assert.strictEqual(signal, null);
<ide> assert.strictEqual(code, 0);
<del>});
<add>})); | 1 |
Text | Text | update cloudml job counts in running_pets.md | 20da786b078c85af57a4c88904f7889139739ab0 | <ide><path>research/object_detection/g3doc/running_pets.md
<ide> python setup.py sdist
<ide> This will create python packages dist/object_detection-0.1.tar.gz,
<ide> slim/dist/slim-0.1.tar.gz, and /tmp/pycocotools/pycocotools-2.0.tar.gz.
<ide>
<del>For running the training Cloud ML job, we'll configure the cluster to use 10
<del>training jobs (1 master + 9 workers) and three parameters servers. The
<add>For running the training Cloud ML job, we'll configure the cluster to use 5
<add>training jobs and three parameters servers. The
<ide> configuration file can be found at `object_detection/samples/cloud/cloud.yml`.
<ide>
<ide> Note: This sample is supported for use with 1.8 runtime version. | 1 |
PHP | PHP | fix double space in doc string | 475b19139e024f159a72d78a450e105ed204f7d5 | <ide><path>src/Routing/Exception/MissingRouteException.php
<ide> class MissingRouteException extends Exception
<ide> /**
<ide> * Message template to use when the requested method is included.
<ide> *
<del> * @var string
<add> * @var string
<ide> */
<ide> protected $_messageTemplateWithMethod = 'A "%s" route matching "%s" could not be found.';
<ide> | 1 |
Javascript | Javascript | pass modulegraph along with multiple methods | 11e127d162f7643ee8c4b684ec4b8ec848ea3903 | <ide><path>lib/CaseSensitiveModulesWarning.js
<ide> const WebpackError = require("./WebpackError");
<ide>
<ide> /** @typedef {import("./Module")} Module */
<add>/** @typedef {import("./ModuleGraph")} ModuleGraph */
<ide>
<ide> /**
<ide> * @param {Module[]} modules the modules to be sorted
<ide> const sortModules = modules => {
<ide>
<ide> /**
<ide> * @param {Module[]} modules each module from throw
<add> * @param {ModuleGraph} moduleGraph the module graph
<ide> * @returns {string} each message from provided moduels
<ide> */
<del>const createModulesListMessage = modules => {
<add>const createModulesListMessage = (modules, moduleGraph) => {
<ide> return modules
<ide> .map(m => {
<ide> let message = `* ${m.identifier()}`;
<ide> class CaseSensitiveModulesWarning extends WebpackError {
<ide> /**
<ide> * Creates an instance of CaseSensitiveModulesWarning.
<ide> * @param {Module[]} modules modules that were detected
<add> * @param {ModuleGraph} moduleGraph the module graph
<ide> */
<del> constructor(modules) {
<add> constructor(modules, moduleGraph) {
<ide> const sortedModules = sortModules(modules);
<del> const modulesList = createModulesListMessage(sortedModules);
<add> const modulesList = createModulesListMessage(sortedModules, moduleGraph);
<ide> super(`There are multiple modules with names that only differ in casing.
<ide> This can lead to unexpected behavior when compiling on a filesystem with other case-semantic.
<ide> Use equal casing. Compare these module identifiers:
<ide><path>lib/ChunkTemplate.js
<ide> const { SyncWaterfallHook, SyncHook } = require("tapable");
<ide> /** @typedef {import("./Module")} Module} */
<ide> /** @typedef {import("./util/createHash").Hash} Hash} */
<ide> /** @typedef {import("./DependencyTemplates")} DependencyTemplates} */
<add>/** @typedef {import("webpack-sources").Source} Source} */
<add>/** @typedef {import("./ModuleTemplate").RenderContext} RenderContext} */
<ide>
<ide> /**
<ide> * @typedef {Object} RenderManifestOptions
<ide> module.exports = class ChunkTemplate {
<ide> this.hooks = Object.freeze({
<ide> /** @type {SyncWaterfallHook<TODO[], RenderManifestOptions>} */
<ide> renderManifest: new SyncWaterfallHook(["result", "options"]),
<add> /** @type {SyncWaterfallHook<Source, ModuleTemplate, RenderContext>} */
<ide> modules: new SyncWaterfallHook([
<ide> "source",
<del> "chunk",
<ide> "moduleTemplate",
<del> "dependencyTemplates"
<add> "renderContext"
<ide> ]),
<add> /** @type {SyncWaterfallHook<Source, ModuleTemplate, RenderContext>} */
<ide> render: new SyncWaterfallHook([
<ide> "source",
<del> "chunk",
<ide> "moduleTemplate",
<del> "dependencyTemplates"
<add> "renderContext"
<ide> ]),
<ide> renderWithEntry: new SyncWaterfallHook(["source", "chunk"]),
<ide> hash: new SyncHook(["hash"]),
<ide><path>lib/Compilation.js
<ide> class Compilation {
<ide> for (let indexDep = 0; indexDep < dependencies.length; indexDep++) {
<ide> const d = dependencies[indexDep];
<ide>
<del> const warnings = d.getWarnings();
<add> const warnings = d.getWarnings(this.moduleGraph);
<ide> if (warnings) {
<ide> for (let indexWar = 0; indexWar < warnings.length; indexWar++) {
<ide> const w = warnings[indexWar];
<ide> class Compilation {
<ide> this.warnings.push(warning);
<ide> }
<ide> }
<del> const errors = d.getErrors();
<add> const errors = d.getErrors(this.moduleGraph);
<ide> if (errors) {
<ide> for (let indexErr = 0; indexErr < errors.length; indexErr++) {
<ide> const e = errors[indexErr];
<ide> class Compilation {
<ide> * @returns {DependencyReference} a reference for the dependency
<ide> */
<ide> getDependencyReference(module, dependency) {
<del> const ref = dependency.getReference();
<add> const ref = dependency.getReference(this.moduleGraph);
<ide> if (!ref) return null;
<ide> return this.hooks.dependencyReference.call(ref, dependency, module);
<ide> }
<ide> class Compilation {
<ide> * @returns {void}
<ide> */
<ide> patchChunksAfterReasonRemoval(module, chunk) {
<del> if (!module.hasReasons()) {
<add> if (!module.hasReasons(this.moduleGraph)) {
<ide> this.removeReasonsOfDependencyBlock(module, module);
<ide> }
<del> if (!module.hasReasonForChunk(chunk)) {
<add> if (!module.hasReasonForChunk(chunk, this.moduleGraph)) {
<ide> if (module.removeChunk(chunk)) {
<ide> this.removeChunkFromDependencies(module, chunk);
<ide> }
<ide><path>lib/ContextModule.js
<ide> const contextify = require("./util/identifier").contextify;
<ide> /** @typedef {import("./DependencyTemplates")} DependencyTemplates */
<ide> /** @typedef {import("./Module").LibIdentOptions} LibIdentOptions */
<ide> /** @typedef {import("./Module").SourceContext} SourceContext */
<add>/** @typedef {import("./ModuleGraph")} ModuleGraph */
<ide> /** @typedef {import("./RequestShortener")} RequestShortener */
<ide> /** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
<ide> /** @typedef {import("./dependencies/ContextElementDependency")} ContextElementDependency */
<ide> class ContextModule extends Module {
<ide> });
<ide> }
<ide>
<del> getUserRequestMap(dependencies) {
<add> /**
<add> * @param {ContextElementDependency[]} dependencies all dependencies
<add> * @param {ModuleGraph} moduleGraph module graph
<add> * @returns {TODO} TODO
<add> */
<add> getUserRequestMap(dependencies, moduleGraph) {
<ide> // if we filter first we get a new array
<ide> // therefor we dont need to create a clone of dependencies explicitly
<ide> // therefore the order of this is !important!
<ide> class ContextModule extends Module {
<ide> }, Object.create(null));
<ide> }
<ide>
<del> getFakeMap(dependencies) {
<add> /**
<add> * @param {ContextElementDependency[]} dependencies all dependencies
<add> * @param {ModuleGraph} moduleGraph module graph
<add> * @returns {TODO} TODO
<add> */
<add> getFakeMap(dependencies, moduleGraph) {
<ide> if (!this.options.namespaceObject) {
<ide> return 9;
<ide> }
<ide> class ContextModule extends Module {
<ide> let hasNamespace = false;
<ide> let hasNamed = false;
<ide> const fakeMap = dependencies
<del> .filter(dependency => dependency.module)
<add> .map(dependency => ({
<add> module: dependency.module,
<add> dependency
<add> }))
<add> .filter(item => item.module)
<ide> .sort((a, b) => {
<del> return b.module.id - a.module.id;
<add> if (a.module.id < b.module.id) return -1;
<add> if (a.module.id > b.module.id) return 1;
<add> return 0;
<ide> })
<del> .reduce((map, dep) => {
<del> const exportsType =
<del> dep.module.buildMeta && dep.module.buildMeta.exportsType;
<del> const id = dep.module.id;
<add> .reduce((map, { dependency: dep, module }) => {
<add> const exportsType = module.buildMeta && module.buildMeta.exportsType;
<add> const id = module.id;
<ide> if (!exportsType) {
<ide> map[id] = this.options.namespaceObject === "strict" ? 1 : 7;
<ide> hasNonHarmony = true;
<ide> class ContextModule extends Module {
<ide> return `return __webpack_require__.t(id, ${fakeMapDataExpression})`;
<ide> }
<ide>
<del> getSyncSource(dependencies, id) {
<del> const map = this.getUserRequestMap(dependencies);
<del> const fakeMap = this.getFakeMap(dependencies);
<add> getSyncSource(dependencies, id, moduleGraph) {
<add> const map = this.getUserRequestMap(dependencies, moduleGraph);
<add> const fakeMap = this.getFakeMap(dependencies, moduleGraph);
<ide> const returnModuleObject = this.getReturnModuleObjectSource(fakeMap);
<ide>
<ide> return `var map = ${JSON.stringify(map, null, "\t")};
<ide> module.exports = webpackContext;
<ide> webpackContext.id = ${JSON.stringify(id)};`;
<ide> }
<ide>
<del> getWeakSyncSource(dependencies, id) {
<del> const map = this.getUserRequestMap(dependencies);
<del> const fakeMap = this.getFakeMap(dependencies);
<add> getWeakSyncSource(dependencies, id, moduleGraph) {
<add> const map = this.getUserRequestMap(dependencies, moduleGraph);
<add> const fakeMap = this.getFakeMap(dependencies, moduleGraph);
<ide> const returnModuleObject = this.getReturnModuleObjectSource(fakeMap);
<ide>
<ide> return `var map = ${JSON.stringify(map, null, "\t")};
<ide> webpackContext.id = ${JSON.stringify(id)};
<ide> module.exports = webpackContext;`;
<ide> }
<ide>
<del> getAsyncWeakSource(dependencies, id) {
<del> const map = this.getUserRequestMap(dependencies);
<del> const fakeMap = this.getFakeMap(dependencies);
<add> getAsyncWeakSource(dependencies, id, moduleGraph) {
<add> const map = this.getUserRequestMap(dependencies, moduleGraph);
<add> const fakeMap = this.getFakeMap(dependencies, moduleGraph);
<ide> const returnModuleObject = this.getReturnModuleObjectSource(fakeMap);
<ide>
<ide> return `var map = ${JSON.stringify(map, null, "\t")};
<ide> webpackAsyncContext.id = ${JSON.stringify(id)};
<ide> module.exports = webpackAsyncContext;`;
<ide> }
<ide>
<del> getEagerSource(dependencies, id) {
<del> const map = this.getUserRequestMap(dependencies);
<del> const fakeMap = this.getFakeMap(dependencies);
<add> getEagerSource(dependencies, id, moduleGraph) {
<add> const map = this.getUserRequestMap(dependencies, moduleGraph);
<add> const fakeMap = this.getFakeMap(dependencies, moduleGraph);
<ide> const thenFunction =
<ide> fakeMap !== 9
<ide> ? `function(id) {
<ide> webpackAsyncContext.id = ${JSON.stringify(id)};
<ide> module.exports = webpackAsyncContext;`;
<ide> }
<ide>
<del> getLazyOnceSource(block, dependencies, id, runtimeTemplate) {
<add> getLazyOnceSource(block, dependencies, id, { runtimeTemplate, moduleGraph }) {
<ide> const promise = runtimeTemplate.blockPromise({
<ide> block,
<ide> message: "lazy-once context"
<ide> });
<del> const map = this.getUserRequestMap(dependencies);
<del> const fakeMap = this.getFakeMap(dependencies);
<add> const map = this.getUserRequestMap(dependencies, moduleGraph);
<add> const fakeMap = this.getFakeMap(dependencies, moduleGraph);
<ide> const thenFunction =
<ide> fakeMap !== 9
<ide> ? `function(id) {
<ide> webpackAsyncContext.id = ${JSON.stringify(id)};
<ide> module.exports = webpackAsyncContext;`;
<ide> }
<ide>
<del> getLazySource(blocks, id) {
<add> getLazySource(blocks, id, moduleGraph) {
<ide> let hasMultipleOrNoChunks = false;
<del> const fakeMap = this.getFakeMap(blocks.map(b => b.dependencies[0]));
<add> const fakeMap = this.getFakeMap(
<add> blocks.map(b => b.dependencies[0]),
<add> moduleGraph
<add> );
<ide> const map = blocks
<del> .filter(block => block.dependencies[0].module)
<del> .map(block => ({
<del> dependency: block.dependencies[0],
<del> block: block,
<del> userRequest: block.dependencies[0].userRequest
<del> }))
<add> .map(block => {
<add> const dependency = block.dependencies[0];
<add> return {
<add> dependency: dependency,
<add> module: dependency.module,
<add> block: block,
<add> userRequest: dependency.userRequest
<add> };
<add> })
<add> .filter(item => item.module)
<ide> .sort((a, b) => {
<ide> if (a.userRequest === b.userRequest) return 0;
<ide> return a.userRequest < b.userRequest ? -1 : 1;
<ide> module.exports = webpackEmptyAsyncContext;
<ide> webpackEmptyAsyncContext.id = ${JSON.stringify(id)};`;
<ide> }
<ide>
<del> getSourceString(asyncMode, runtimeTemplate) {
<add> getSourceString(asyncMode, { runtimeTemplate, moduleGraph }) {
<ide> if (asyncMode === "lazy") {
<ide> if (this.blocks && this.blocks.length > 0) {
<del> return this.getLazySource(this.blocks, this.id);
<add> return this.getLazySource(this.blocks, this.id, moduleGraph);
<ide> }
<ide> return this.getSourceForEmptyAsyncContext(this.id);
<ide> }
<ide> if (asyncMode === "eager") {
<ide> if (this.dependencies && this.dependencies.length > 0) {
<del> return this.getEagerSource(this.dependencies, this.id);
<add> return this.getEagerSource(this.dependencies, this.id, moduleGraph);
<ide> }
<ide> return this.getSourceForEmptyAsyncContext(this.id);
<ide> }
<ide> if (asyncMode === "lazy-once") {
<ide> const block = this.blocks[0];
<ide> if (block) {
<del> return this.getLazyOnceSource(
<del> block,
<del> block.dependencies,
<del> this.id,
<del> runtimeTemplate
<del> );
<add> return this.getLazyOnceSource(block, block.dependencies, this.id, {
<add> runtimeTemplate,
<add> moduleGraph
<add> });
<ide> }
<ide> return this.getSourceForEmptyAsyncContext(this.id);
<ide> }
<ide> if (asyncMode === "async-weak") {
<ide> if (this.dependencies && this.dependencies.length > 0) {
<del> return this.getAsyncWeakSource(this.dependencies, this.id);
<add> return this.getAsyncWeakSource(this.dependencies, this.id, moduleGraph);
<ide> }
<ide> return this.getSourceForEmptyAsyncContext(this.id);
<ide> }
<ide> if (asyncMode === "weak") {
<ide> if (this.dependencies && this.dependencies.length > 0) {
<del> return this.getWeakSyncSource(this.dependencies, this.id);
<add> return this.getWeakSyncSource(this.dependencies, this.id, moduleGraph);
<ide> }
<ide> }
<ide> if (this.dependencies && this.dependencies.length > 0) {
<del> return this.getSyncSource(this.dependencies, this.id);
<add> return this.getSyncSource(this.dependencies, this.id, moduleGraph);
<ide> }
<ide> return this.getSourceForEmptyContext(this.id);
<ide> }
<ide> webpackEmptyAsyncContext.id = ${JSON.stringify(id)};`;
<ide> * @param {SourceContext} sourceContext source context
<ide> * @returns {Source} generated source
<ide> */
<del> source({ runtimeTemplate }) {
<add> source({ runtimeTemplate, moduleGraph }) {
<ide> return this.getSource(
<del> this.getSourceString(this.options.mode, runtimeTemplate)
<add> this.getSourceString(this.options.mode, { runtimeTemplate, moduleGraph })
<ide> );
<ide> }
<ide>
<ide><path>lib/DelegatedModule.js
<ide> class DelegatedModule extends Module {
<ide> * @param {SourceContext} sourceContext source context
<ide> * @returns {Source} generated source
<ide> */
<del> source({ runtimeTemplate }) {
<add> source({ runtimeTemplate, moduleGraph }) {
<ide> const dep = /** @type {DelegatedSourceDependency} */ (this.dependencies[0]);
<ide> const sourceModule = dep.module;
<ide> let str;
<ide><path>lib/Dependency.js
<ide> class Dependency {
<ide>
<ide> /**
<ide> * Returns the referenced module and export
<add> * @param {ModuleGraph} moduleGraph module graph
<ide> * @returns {DependencyReference} reference
<ide> */
<del> getReference() {
<add> getReference(moduleGraph) {
<ide> if (!this.module) return null;
<ide> return new DependencyReference(() => this.module, true, this.weak);
<ide> }
<ide> class Dependency {
<ide>
<ide> /**
<ide> * Returns warnings
<add> * @param {ModuleGraph} moduleGraph module graph
<ide> * @returns {WebpackError[]} warnings
<ide> */
<del> getWarnings() {
<add> getWarnings(moduleGraph) {
<ide> return null;
<ide> }
<ide>
<ide> /**
<ide> * Returns errors
<add> * @param {ModuleGraph} moduleGraph module graph
<ide> * @returns {WebpackError[]} errors
<ide> */
<del> getErrors() {
<add> getErrors(moduleGraph) {
<ide> return null;
<ide> }
<ide>
<ide><path>lib/DependencyTemplate.js
<ide> /** @typedef {import("./DependencyTemplates")} DependencyTemplates */
<ide> /** @typedef {import("./InitFragment")} InitFragment */
<ide> /** @typedef {import("./Module")} Module */
<add>/** @typedef {import("./ModuleGraph")} ModuleGraph */
<ide> /** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
<ide>
<ide> /**
<ide> * @typedef {Object} DependencyTemplateContext
<ide> * @property {RuntimeTemplate} runtimeTemplate the runtime template
<ide> * @property {DependencyTemplates} dependencyTemplates the dependency templates
<add> * @property {ModuleGraph} moduleGraph the module graph
<ide> * @property {Module} module current module
<ide> */
<ide>
<ide><path>lib/ExternalModule.js
<ide> class ExternalModule extends Module {
<ide> callback();
<ide> }
<ide>
<del> getSourceString(runtimeTemplate) {
<add> getSourceString(runtimeTemplate, moduleGraph) {
<ide> const request =
<ide> typeof this.request === "object"
<ide> ? this.request[this.externalType]
<ide> class ExternalModule extends Module {
<ide> case "umd2":
<ide> return getSourceForAmdOrUmdExternal(
<ide> this.id,
<del> this.optional,
<add> this.isOptional(moduleGraph),
<ide> request,
<ide> runtimeTemplate
<ide> );
<ide> default:
<del> return getSourceForDefaultCase(this.optional, request, runtimeTemplate);
<add> return getSourceForDefaultCase(
<add> this.isOptional(moduleGraph),
<add> request,
<add> runtimeTemplate
<add> );
<ide> }
<ide> }
<ide>
<ide> /**
<ide> * @param {SourceContext} sourceContext source context
<ide> * @returns {Source} generated source
<ide> */
<del> source({ runtimeTemplate }) {
<del> const sourceString = this.getSourceString(runtimeTemplate);
<add> source({ runtimeTemplate, moduleGraph }) {
<add> const sourceString = this.getSourceString(runtimeTemplate, moduleGraph);
<ide> if (this.useSourceMap) {
<ide> return new OriginalSource(sourceString, this.identifier());
<ide> } else {
<ide> class ExternalModule extends Module {
<ide> updateHash(hash, compilation) {
<ide> hash.update(this.externalType);
<ide> hash.update(JSON.stringify(this.request));
<del> hash.update(JSON.stringify(Boolean(this.optional)));
<add> hash.update(
<add> JSON.stringify(Boolean(this.isOptional(compilation.moduleGraph)))
<add> );
<ide> super.updateHash(hash, compilation);
<ide> }
<ide> }
<ide><path>lib/Generator.js
<ide> /** @typedef {import("webpack-sources").Source} Source */
<ide> /** @typedef {import("./DependencyTemplate")} DependencyTemplate */
<ide> /** @typedef {import("./DependencyTemplates")} DependencyTemplates */
<add>/** @typedef {import("./ModuleGraph")} ModuleGraph */
<ide> /** @typedef {import("./NormalModule")} NormalModule */
<ide> /** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
<ide>
<ide> /**
<ide> * @typedef {Object} GenerateContext
<ide> * @property {DependencyTemplates} dependencyTemplates mapping from dependencies to templates
<ide> * @property {RuntimeTemplate} runtimeTemplate the runtime template
<add> * @property {ModuleGraph} moduleGraph the module graph
<ide> * @property {string} type which kind of code should be generated
<ide> */
<ide>
<ide> class Generator {
<ide> * @param {GenerateContext} generateContext context for generate
<ide> * @returns {Source} generated code
<ide> */
<del> generate(module, { dependencyTemplates, runtimeTemplate, type }) {
<add> generate(
<add> module,
<add> { dependencyTemplates, runtimeTemplate, moduleGraph, type }
<add> ) {
<ide> throw new Error("Generator.generate: must be overridden");
<ide> }
<ide> }
<ide><path>lib/HotModuleReplacementPlugin.js
<ide>
<ide> const { SyncBailHook } = require("tapable");
<ide> const { RawSource } = require("webpack-sources");
<add>const HotUpdateChunk = require("./HotUpdateChunk");
<ide> const JavascriptParser = require("./JavascriptParser");
<ide> const {
<ide> evaluateToIdentifier,
<ide> module.exports = class HotModuleReplacementPlugin {
<ide> id => !allModules.has(id)
<ide> );
<ide> if (newModules.length > 0 || removedModules.length > 0) {
<add> const hotUpdateChunk = new HotUpdateChunk();
<add> hotUpdateChunk.id = chunkId;
<add> hotUpdateChunk.setModules(newModules);
<add> hotUpdateChunk.removedModules = removedModules;
<ide> const source = hotUpdateChunkTemplate.render(
<del> chunkId,
<del> newModules,
<del> removedModules,
<del> compilation.hash,
<add> {
<add> chunk: hotUpdateChunk,
<add> dependencyTemplates: compilation.dependencyTemplates,
<add> runtimeTemplate: compilation.runtimeTemplate,
<add> moduleGraph: compilation.moduleGraph
<add> },
<ide> compilation.moduleTemplates.javascript,
<del> compilation.dependencyTemplates
<add> compilation.hash
<ide> );
<ide> const filename = compilation.getPath(hotUpdateChunkFilename, {
<ide> hash: records.hash,
<ide><path>lib/HotUpdateChunkTemplate.js
<ide> "use strict";
<ide>
<ide> const { SyncWaterfallHook, SyncHook } = require("tapable");
<del>const HotUpdateChunk = require("./HotUpdateChunk");
<ide> const Template = require("./Template");
<ide>
<add>/** @typedef {import("webpack-sources").Source} Source */
<add>/** @typedef {import("./ModuleTemplate")} ModuleTemplate */
<add>/** @typedef {import("./ModuleTemplate").RenderContext} RenderContext */
<add>
<ide> module.exports = class HotUpdateChunkTemplate {
<ide> constructor(outputOptions) {
<ide> this.outputOptions = outputOptions || {};
<ide> this.hooks = Object.freeze({
<add> /** @type {SyncWaterfallHook<Source, ModuleTemplate, RenderContext>} */
<ide> modules: new SyncWaterfallHook([
<ide> "source",
<del> "modules",
<del> "removedModules",
<ide> "moduleTemplate",
<del> "dependencyTemplates"
<add> "renderContext"
<ide> ]),
<add> /** @type {SyncWaterfallHook<Source, ModuleTemplate, RenderContext>} */
<ide> render: new SyncWaterfallHook([
<ide> "source",
<del> "modules",
<del> "removedModules",
<del> "hash",
<del> "id",
<ide> "moduleTemplate",
<del> "dependencyTemplates"
<add> "renderContext",
<add> "hash"
<ide> ]),
<ide> hash: new SyncHook(["hash"])
<ide> });
<ide> }
<ide>
<del> render(
<del> id,
<del> modules,
<del> removedModules,
<del> hash,
<del> moduleTemplate,
<del> dependencyTemplates
<del> ) {
<del> const hotUpdateChunk = new HotUpdateChunk();
<del> hotUpdateChunk.id = id;
<del> hotUpdateChunk.setModules(modules);
<del> hotUpdateChunk.removedModules = removedModules;
<add> /**
<add> *
<add> * @param {RenderContext} renderContext the render context
<add> * @param {ModuleTemplate} moduleTemplate the module template
<add> * @param {string} hash hash of the compilation
<add> * @returns {Source} rendered source
<add> */
<add> render(renderContext, moduleTemplate, hash) {
<ide> const modulesSource = Template.renderChunkModules(
<del> hotUpdateChunk,
<add> renderContext,
<ide> m => typeof m.source === "function",
<del> moduleTemplate,
<del> dependencyTemplates
<add> moduleTemplate
<ide> );
<ide> const core = this.hooks.modules.call(
<ide> modulesSource,
<del> modules,
<del> removedModules,
<ide> moduleTemplate,
<del> dependencyTemplates
<add> renderContext
<ide> );
<ide> const source = this.hooks.render.call(
<ide> core,
<del> modules,
<del> removedModules,
<del> hash,
<del> id,
<ide> moduleTemplate,
<del> dependencyTemplates
<add> renderContext,
<add> hash
<ide> );
<ide> return source;
<ide> }
<ide><path>lib/JavascriptGenerator.js
<ide> class JavascriptGenerator extends Generator {
<ide> * @param {GenerateContext} generateContext context for generate
<ide> * @returns {Source} generated code
<ide> */
<del> generate(module, { dependencyTemplates, runtimeTemplate }) {
<add> generate(module, generateContext) {
<ide> const originalSource = module.originalSource();
<ide> if (!originalSource) {
<ide> return new RawSource("throw new Error('No source available');");
<ide> }
<ide>
<ide> const source = new ReplaceSource(originalSource);
<del> // TODO: remove this hack
<del> const sourceAsAny = /** @type {any} */ (source);
<del> sourceAsAny.module = module;
<ide> const initFragments = [];
<ide>
<del> this.sourceBlock(
<del> module,
<del> module,
<del> dependencyTemplates,
<del> initFragments,
<del> source,
<del> runtimeTemplate
<del> );
<add> this.sourceBlock(module, module, initFragments, source, generateContext);
<ide>
<ide> if (initFragments.length > 0) {
<ide> // Sort fragments by position. If 2 fragments have the same position,
<ide> class JavascriptGenerator extends Generator {
<ide> /**
<ide> * @param {Module} module the module to generate
<ide> * @param {DependenciesBlock} block the dependencies block which will be processed
<del> * @param {DependencyTemplates} dependencyTemplates the dependency templates
<ide> * @param {InitFragment[]} initFragments mutable list of init fragments
<ide> * @param {ReplaceSource} source the current replace source which can be modified
<del> * @param {RuntimeTemplate} runtimeTemplate the runtime template
<add> * @param {GenerateContext} generateContext the generateContext
<ide> * @returns {void}
<ide> */
<del> sourceBlock(
<del> module,
<del> block,
<del> dependencyTemplates,
<del> initFragments,
<del> source,
<del> runtimeTemplate
<del> ) {
<add> sourceBlock(module, block, initFragments, source, generateContext) {
<ide> for (const dependency of block.dependencies) {
<ide> this.sourceDependency(
<ide> module,
<ide> dependency,
<del> dependencyTemplates,
<ide> initFragments,
<ide> source,
<del> runtimeTemplate
<add> generateContext
<ide> );
<ide> }
<ide>
<ide> for (const childBlock of block.blocks) {
<ide> this.sourceBlock(
<ide> module,
<ide> childBlock,
<del> dependencyTemplates,
<ide> initFragments,
<ide> source,
<del> runtimeTemplate
<add> generateContext
<ide> );
<ide> }
<ide> }
<ide>
<ide> /**
<ide> * @param {Module} module the current module
<ide> * @param {Dependency} dependency the dependency to generate
<del> * @param {DependencyTemplates} dependencyTemplates the dependency templates
<ide> * @param {InitFragment[]} initFragments mutable list of init fragments
<ide> * @param {ReplaceSource} source the current replace source which can be modified
<del> * @param {RuntimeTemplate} runtimeTemplate the runtime template
<add> * @param {GenerateContext} generateContext the render context
<ide> * @returns {void}
<ide> */
<del> sourceDependency(
<del> module,
<del> dependency,
<del> dependencyTemplates,
<del> initFragments,
<del> source,
<del> runtimeTemplate
<del> ) {
<add> sourceDependency(module, dependency, initFragments, source, generateContext) {
<ide> const constructor =
<ide> /** @type {new (...args: any[]) => Dependency} */ (dependency.constructor);
<del> const template = dependencyTemplates.get(constructor);
<add> const template = generateContext.dependencyTemplates.get(constructor);
<ide> if (!template) {
<ide> throw new Error(
<ide> "No template for dependency: " + dependency.constructor.name
<ide> );
<ide> }
<ide>
<del> template.apply(dependency, source, {
<del> module,
<del> runtimeTemplate,
<del> dependencyTemplates
<del> });
<del>
<del> const fragments = template.getInitFragments(dependency, {
<del> runtimeTemplate,
<del> dependencyTemplates,
<add> const templateContext = {
<add> runtimeTemplate: generateContext.runtimeTemplate,
<add> dependencyTemplates: generateContext.dependencyTemplates,
<add> moduleGraph: generateContext.moduleGraph,
<ide> module
<del> });
<add> };
<add>
<add> template.apply(dependency, source, templateContext);
<add>
<add> const fragments = template.getInitFragments(dependency, templateContext);
<ide>
<ide> if (fragments) {
<ide> for (const fragment of fragments) {
<ide><path>lib/JavascriptModulesPlugin.js
<ide> const JavascriptParser = require("./JavascriptParser");
<ide> const Template = require("./Template");
<ide> const createHash = require("./util/createHash");
<ide>
<add>/** @typedef {import("webpack-sources").Source} Source */
<add>/** @typedef {import("./ChunkTemplate")} ChunkTemplate */
<add>/** @typedef {import("./Compiler")} Compiler */
<add>/** @typedef {import("./ModuleTemplate")} ModuleTemplate */
<add>/** @typedef {import("./ModuleTemplate").RenderContext} RenderContext */
<add>/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
<add>
<ide> const compilationHooksMap = new WeakMap();
<ide>
<ide> class JavascriptModulesPlugin {
<ide> class JavascriptModulesPlugin {
<ide> return hooks;
<ide> }
<ide>
<add> /**
<add> * @param {Compiler} compiler webpack compiler
<add> * @returns {void}
<add> */
<ide> apply(compiler) {
<ide> compiler.hooks.compilation.tap(
<ide> "JavascriptModulesPlugin",
<ide> class JavascriptModulesPlugin {
<ide> "JavascriptModulesPlugin",
<ide> (source, chunk, hash, moduleTemplate, dependencyTemplates) => {
<ide> return Template.renderChunkModules(
<del> chunk,
<add> {
<add> chunk,
<add> dependencyTemplates,
<add> runtimeTemplate: compilation.runtimeTemplate,
<add> moduleGraph: compilation.moduleGraph
<add> },
<ide> m => typeof m.source === "function",
<ide> moduleTemplate,
<del> dependencyTemplates,
<ide> "/******/ "
<ide> );
<ide> }
<ide> class JavascriptModulesPlugin {
<ide> render: () =>
<ide> this.renderJavascript(
<ide> compilation.chunkTemplate,
<del> chunk,
<ide> moduleTemplates.javascript,
<del> dependencyTemplates
<add> {
<add> chunk,
<add> dependencyTemplates,
<add> runtimeTemplate: compilation.runtimeTemplate,
<add> moduleGraph: compilation.moduleGraph
<add> }
<ide> ),
<ide> filenameTemplate,
<ide> pathOptions: {
<ide> class JavascriptModulesPlugin {
<ide> );
<ide> }
<ide>
<del> renderJavascript(chunkTemplate, chunk, moduleTemplate, dependencyTemplates) {
<add> /**
<add> * @param {ChunkTemplate} chunkTemplate the chunk template
<add> * @param {ModuleTemplate} moduleTemplate the module template
<add> * @param {RenderContext} renderContext the render context
<add> * @returns {Source} the rendered source
<add> */
<add> renderJavascript(chunkTemplate, moduleTemplate, renderContext) {
<ide> const moduleSources = Template.renderChunkModules(
<del> chunk,
<add> renderContext,
<ide> m => typeof m.source === "function",
<del> moduleTemplate,
<del> dependencyTemplates
<add> moduleTemplate
<ide> );
<ide> const core = chunkTemplate.hooks.modules.call(
<ide> moduleSources,
<del> chunk,
<ide> moduleTemplate,
<del> dependencyTemplates
<add> renderContext
<ide> );
<ide> let source = chunkTemplate.hooks.render.call(
<ide> core,
<del> chunk,
<ide> moduleTemplate,
<del> dependencyTemplates
<add> renderContext
<ide> );
<add> const chunk = renderContext.chunk;
<ide> if (chunk.hasEntryModule()) {
<ide> source = chunkTemplate.hooks.renderWithEntry.call(source, chunk);
<ide> }
<ide><path>lib/Module.js
<ide> const SortableSet = require("./util/SortableSet");
<ide> /** @typedef {import("./Compilation")} Compilation */
<ide> /** @typedef {import("./Dependency")} Dependency */
<ide> /** @typedef {import("./DependencyTemplates")} DependencyTemplates */
<add>/** @typedef {import("./ModuleGraph")} ModuleGraph */
<ide> /** @typedef {import("./RequestShortener")} RequestShortener */
<ide> /** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
<ide> /** @typedef {import("./WebpackError")} WebpackError */
<ide> const SortableSet = require("./util/SortableSet");
<ide> * @typedef {Object} SourceContext
<ide> * @property {DependencyTemplates} dependencyTemplates the dependency templates
<ide> * @property {RuntimeTemplate} runtimeTemplate the runtime template
<add> * @property {ModuleGraph} moduleGraph the module graph
<ide> * @property {string=} type the type of source that should be generated
<ide> */
<ide>
<ide> class Module extends DependenciesBlock {
<ide> }
<ide>
<ide> /**
<add> * @param {ModuleGraph} moduleGraph the module graph
<ide> * @returns {boolean} true, if the module is optional
<ide> */
<del> get optional() {
<add> isOptional(moduleGraph) {
<ide> return (
<ide> this.reasons.length > 0 &&
<ide> this.reasons.every(r => r.dependency && r.dependency.optional)
<ide> class Module extends DependenciesBlock {
<ide>
<ide> /**
<ide> * @param {Chunk} chunk a chunk
<add> * @param {ModuleGraph} moduleGraph the module graph
<ide> * @returns {boolean} true, if the module has any reason why "chunk" should be included
<ide> */
<del> hasReasonForChunk(chunk) {
<add> hasReasonForChunk(chunk, moduleGraph) {
<ide> // check for each reason if we need the chunk
<ide> for (const reason of this.reasons) {
<ide> const fromModule = reason.module;
<ide> class Module extends DependenciesBlock {
<ide> }
<ide>
<ide> /**
<del> * @returns {boolean} true, if there are references to this module
<add> * @param {ModuleGraph} moduleGraph the module graph
<add> * @returns {boolean} true if at least one other module depends on this module
<ide> */
<del> hasReasons() {
<add> hasReasons(moduleGraph) {
<ide> return this.reasons.length > 0;
<ide> }
<ide>
<ide><path>lib/ModuleTemplate.js
<ide> const { SyncWaterfallHook, SyncHook } = require("tapable");
<ide>
<ide> /** @typedef {import("webpack-sources").Source} Source */
<add>/** @typedef {import("./Chunk")} Chunk */
<add>/** @typedef {import("./DependencyTemplates")} DependencyTemplates */
<ide> /** @typedef {import("./Module")} Module */
<add>/** @typedef {import("./ModuleGraph")} ModuleGraph */
<add>/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
<add>
<add>/**
<add> * @typedef {Object} RenderContext
<add> * @property {Chunk} chunk the chunk
<add> * @property {DependencyTemplates} dependencyTemplates the dependency templates
<add> * @property {RuntimeTemplate} runtimeTemplate the runtime template
<add> * @property {ModuleGraph} moduleGraph the module graph
<add> */
<ide>
<ide> module.exports = class ModuleTemplate {
<ide> constructor(runtimeTemplate, type) {
<ide> this.runtimeTemplate = runtimeTemplate;
<ide> this.type = type;
<ide> this.hooks = Object.freeze({
<del> content: new SyncWaterfallHook([
<del> "source",
<del> "module",
<del> "options",
<del> "dependencyTemplates"
<del> ]),
<del> module: new SyncWaterfallHook([
<del> "source",
<del> "module",
<del> "options",
<del> "dependencyTemplates"
<del> ]),
<del> render: new SyncWaterfallHook([
<del> "source",
<del> "module",
<del> "options",
<del> "dependencyTemplates"
<del> ]),
<del> package: new SyncWaterfallHook([
<del> "source",
<del> "module",
<del> "options",
<del> "dependencyTemplates"
<del> ]),
<add> /** @type {SyncWaterfallHook<Source, Module, RenderContext>} */
<add> content: new SyncWaterfallHook(["source", "module", "context"]),
<add> /** @type {SyncWaterfallHook<Source, Module, RenderContext>} */
<add> module: new SyncWaterfallHook(["source", "module", "context"]),
<add> /** @type {SyncWaterfallHook<Source, Module, RenderContext>} */
<add> render: new SyncWaterfallHook(["source", "module", "context"]),
<add> /** @type {SyncWaterfallHook<Source, Module, RenderContext>} */
<add> package: new SyncWaterfallHook(["source", "module", "context"]),
<ide> hash: new SyncHook(["hash"])
<ide> });
<ide> }
<ide>
<ide> /**
<ide> * @param {Module} module the module
<del> * @param {TODO} dependencyTemplates templates for dependencies
<del> * @param {TODO} options render options
<add> * @param {RenderContext} ctx render ctx
<ide> * @returns {Source} the source
<ide> */
<del> render(module, dependencyTemplates, options) {
<add> render(module, ctx) {
<ide> try {
<add> const { runtimeTemplate, dependencyTemplates, moduleGraph } = ctx;
<ide> const moduleSource = module.source({
<ide> dependencyTemplates,
<del> runtimeTemplate: this.runtimeTemplate,
<add> runtimeTemplate,
<add> moduleGraph,
<ide> type: this.type
<ide> });
<ide> const moduleSourcePostContent = this.hooks.content.call(
<ide> moduleSource,
<ide> module,
<del> options,
<del> dependencyTemplates
<add> ctx
<ide> );
<ide> const moduleSourcePostModule = this.hooks.module.call(
<ide> moduleSourcePostContent,
<ide> module,
<del> options,
<del> dependencyTemplates
<add> ctx
<ide> );
<ide> const moduleSourcePostRender = this.hooks.render.call(
<ide> moduleSourcePostModule,
<ide> module,
<del> options,
<del> dependencyTemplates
<del> );
<del> return this.hooks.package.call(
<del> moduleSourcePostRender,
<del> module,
<del> options,
<del> dependencyTemplates
<add> ctx
<ide> );
<add> return this.hooks.package.call(moduleSourcePostRender, module, ctx);
<ide> } catch (e) {
<ide> e.message = `${module.identifier()}\n${e.message}`;
<ide> throw e;
<ide><path>lib/MultiModule.js
<ide> class MultiModule extends Module {
<ide> * @param {SourceContext} sourceContext source context
<ide> * @returns {Source} generated source
<ide> */
<del> source({ runtimeTemplate }) {
<add> source({ runtimeTemplate, moduleGraph }) {
<ide> const str = [];
<ide> let idx = 0;
<ide> for (const dep of this.dependencies) {
<ide><path>lib/NormalModule.js
<ide> class NormalModule extends Module {
<ide> * @param {SourceContext} sourceContext source context
<ide> * @returns {Source} generated source
<ide> */
<del> source({ dependencyTemplates, runtimeTemplate, type = "javascript" }) {
<add> source({
<add> dependencyTemplates,
<add> runtimeTemplate,
<add> moduleGraph,
<add> type = "javascript"
<add> }) {
<ide> const hashDigest = this.getHashDigest(dependencyTemplates);
<ide> const cacheEntry = this._cachedSources.get(type);
<ide> if (cacheEntry !== undefined && cacheEntry.hash === hashDigest) {
<ide> class NormalModule extends Module {
<ide> const source = this.generator.generate(this, {
<ide> dependencyTemplates,
<ide> runtimeTemplate,
<add> moduleGraph,
<ide> type
<ide> });
<ide>
<ide><path>lib/Stats.js
<ide> class Stats {
<ide> };
<ide>
<ide> const compilation = this.compilation;
<add> const moduleGraph = compilation.moduleGraph;
<ide> const context = optionsOrFallback(
<ide> options.context,
<ide> compilation.compiler.context
<ide> class Stats {
<ide> size: module.size(),
<ide> cacheable: module.buildInfo.cacheable,
<ide> built: !!module.built,
<del> optional: module.optional,
<add> optional: module.isOptional(moduleGraph),
<ide> prefetched: module.prefetched,
<ide> chunks: Array.from(module.chunksIterable, chunk => chunk.id),
<ide> issuer: module.issuer && module.issuer.identifier(),
<ide> class Stats {
<ide> return 0;
<ide> })
<ide> .map(reason => {
<add> const depAsAny = /** @type {any} */ (reason.dependency);
<ide> const obj = {
<ide> moduleId: reason.module ? reason.module.id : null,
<ide> moduleIdentifier: reason.module
<ide> class Stats {
<ide> : null,
<ide> type: reason.dependency ? reason.dependency.type : null,
<ide> explanation: reason.explanation,
<del> userRequest: reason.dependency
<del> ? reason.dependency.userRequest
<del> : null
<add> userRequest:
<add> depAsAny && "userRequest" in depAsAny
<add> ? depAsAny.userRequest
<add> : null
<ide> };
<ide> if (reason.dependency) {
<ide> const locInfo = formatLocation(reason.dependency.loc);
<ide> class Stats {
<ide> if (chunk.origins) {
<ide> for (const origin of chunk.origins) {
<ide> colors.normal(" > ");
<del> if (origin.reasons && origin.reasons.length) {
<del> colors.yellow(origin.reasons.join(" "));
<del> colors.normal(" ");
<del> }
<ide> if (origin.request) {
<ide> colors.normal(origin.request);
<ide> colors.normal(" ");
<ide><path>lib/Template.js
<ide> const HotUpdateChunk = require("./HotUpdateChunk");
<ide> /** @typedef {import("webpack-sources").ConcatSource} ConcatSource */
<ide> /** @typedef {import("webpack-sources").Source} Source */
<ide> /** @typedef {import("./Chunk")} Chunk */
<add>/** @typedef {import("./DependencyTemplates")} DependencyTemplates */
<ide> /** @typedef {import("./Module")} Module */
<add>/** @typedef {import("./ModuleGraph")} ModuleGraph */
<ide> /** @typedef {import("./ModuleTemplate")} ModuleTemplate */
<add>/** @typedef {import("./ModuleTemplate").RenderContext} RenderContext */
<add>/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
<ide>
<ide> const START_LOWERCASE_ALPHABET_CODE = "a".charCodeAt(0);
<ide> const START_UPPERCASE_ALPHABET_CODE = "A".charCodeAt(0);
<ide> class Template {
<ide> }
<ide>
<ide> /**
<del> * @param {Chunk} chunk chunk whose modules will be rendered
<add> * @param {RenderContext} renderContext render context
<ide> * @param {ModuleFilterPredicate} filterFn function used to filter modules from chunk to render
<ide> * @param {ModuleTemplate} moduleTemplate ModuleTemplate instance used to render modules
<del> * @param {TODO | TODO[]} dependencyTemplates templates needed for each module to render dependencies
<ide> * @param {string=} prefix applying prefix strings
<del> * @returns {ConcatSource} rendered chunk modules in a Source object
<add> * @returns {Source} rendered chunk modules in a Source object
<ide> */
<ide> static renderChunkModules(
<del> chunk,
<add> renderContext,
<ide> filterFn,
<ide> moduleTemplate,
<del> dependencyTemplates,
<ide> prefix = ""
<ide> ) {
<del> const source = new ConcatSource();
<add> const chunk = renderContext.chunk;
<add> var source = new ConcatSource();
<ide> const modules = chunk.getModules().filter(filterFn);
<ide> let removedModules;
<ide> if (chunk instanceof HotUpdateChunk) {
<ide> class Template {
<ide> const allModules = modules.map(module => {
<ide> return {
<ide> id: module.id,
<del> source: moduleTemplate.render(module, dependencyTemplates, {
<del> chunk
<del> })
<add> source: moduleTemplate.render(module, renderContext)
<ide> };
<ide> });
<ide> if (removedModules && removedModules.length > 0) {
<ide><path>lib/UmdMainTemplatePlugin.js
<ide> class UmdMainTemplatePlugin {
<ide> let requiredExternals = [];
<ide> if (this.optionalAmdExternalAsGlobal) {
<ide> for (const m of externals) {
<del> if (m.optional) {
<add> if (m.isOptional(compilation.moduleGraph)) {
<ide> optionalExternals.push(m);
<ide> } else {
<ide> requiredExternals.push(m);
<ide> class UmdMainTemplatePlugin {
<ide> } else {
<ide> expr = `require(${JSON.stringify(request)})`;
<ide> }
<del> if (m.optional) {
<add> if (m.isOptional(compilation.moduleGraph)) {
<ide> expr = `(function webpackLoadOptionalExternalModule() { try { return ${expr}; } catch(e) {} }())`;
<ide> }
<ide> return expr;
<ide><path>lib/WarnCaseSensitiveModulesPlugin.js
<ide> class WarnCaseSensitiveModulesPlugin {
<ide> for (const pair of moduleWithoutCase) {
<ide> const array = pair[1];
<ide> if (array.length > 1) {
<del> compilation.warnings.push(new CaseSensitiveModulesWarning(array));
<add> compilation.warnings.push(
<add> new CaseSensitiveModulesWarning(array, compilation.moduleGraph)
<add> );
<ide> }
<ide> }
<ide> });
<ide><path>lib/dependencies/AMDRequireArrayDependency.js
<ide> AMDRequireArrayDependency.Template = class AMDRequireArrayDependencyTemplate ext
<ide> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, { runtimeTemplate }) {
<add> apply(dependency, source, { runtimeTemplate, moduleGraph }) {
<ide> const dep = /** @type {AMDRequireArrayDependency} */ (dependency);
<del> const content = this.getContent(dep, runtimeTemplate);
<add> const content = this.getContent(dep, { runtimeTemplate, moduleGraph });
<ide> source.replace(dep.range[0], dep.range[1] - 1, content);
<ide> }
<ide>
<del> getContent(dep, runtime) {
<add> getContent(dep, { runtimeTemplate, moduleGraph }) {
<ide> const requires = dep.depsArray.map(dependency => {
<del> return this.contentForDependency(dependency, runtime);
<add> return this.contentForDependency(dependency, {
<add> runtimeTemplate,
<add> moduleGraph
<add> });
<ide> });
<ide> return `[${requires.join(", ")}]`;
<ide> }
<ide>
<del> contentForDependency(dep, runtime) {
<add> contentForDependency(dep, { runtimeTemplate, moduleGraph }) {
<ide> if (typeof dep === "string") {
<ide> return dep;
<ide> }
<ide>
<ide> if (dep.localModule) {
<ide> return dep.localModule.variableName();
<ide> } else {
<del> return runtime.moduleExports({
<add> return runtimeTemplate.moduleExports({
<ide> module: dep.module,
<ide> request: dep.request
<ide> });
<ide><path>lib/dependencies/ContextDependency.js
<ide> const Dependency = require("../Dependency");
<ide> const DependencyTemplate = require("../DependencyTemplate");
<ide> const CriticalDependencyWarning = require("./CriticalDependencyWarning");
<ide>
<add>/** @typedef {import("../ModuleGraph")} ModuleGraph */
<ide> /** @typedef {import("../WebpackError")} WebpackError */
<ide>
<ide> const regExpToString = r => (r ? r + "" : "");
<ide> class ContextDependency extends Dependency {
<ide>
<ide> /**
<ide> * Returns warnings
<add> * @param {ModuleGraph} moduleGraph module graph
<ide> * @returns {WebpackError[]} warnings
<ide> */
<del> getWarnings() {
<del> let warnings = super.getWarnings() || [];
<add> getWarnings(moduleGraph) {
<add> let warnings = super.getWarnings(moduleGraph) || [];
<ide> if (this.critical) {
<ide> warnings.push(new CriticalDependencyWarning(this.critical));
<ide> }
<ide><path>lib/dependencies/ContextDependencyTemplateAsId.js
<ide> class ContextDependencyTemplateAsId extends ContextDependency.Template {
<ide> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, { runtimeTemplate }) {
<add> apply(dependency, source, { runtimeTemplate, moduleGraph }) {
<ide> const dep = /** @type {ContextDependency} */ (dependency);
<ide> const moduleExports = runtimeTemplate.moduleExports({
<ide> module: dep.module,
<ide><path>lib/dependencies/ContextDependencyTemplateAsRequireCall.js
<ide> class ContextDependencyTemplateAsRequireCall extends ContextDependency.Template
<ide> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, { runtimeTemplate }) {
<add> apply(dependency, source, { runtimeTemplate, moduleGraph }) {
<ide> const dep = /** @type {ContextDependency} */ (dependency);
<ide> const moduleExports = runtimeTemplate.moduleExports({
<ide> module: dep.module,
<ide><path>lib/dependencies/DelegatedExportsDependency.js
<ide> class DelegatedExportsDependency extends NullDependency {
<ide>
<ide> /**
<ide> * Returns the referenced module and export
<add> * @param {ModuleGraph} moduleGraph module graph
<ide> * @returns {DependencyReference} reference
<ide> */
<del> getReference() {
<add> getReference(moduleGraph) {
<ide> if (!this.originModule) return null;
<ide> return new DependencyReference(() => this.originModule, true, false);
<ide> }
<ide><path>lib/dependencies/HarmonyAcceptDependency.js
<ide> const NullDependency = require("./NullDependency");
<ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
<ide> /** @typedef {import("../Dependency")} Dependency */
<ide> /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
<add>/** @typedef {import("./HarmonyAcceptImportDependency")} HarmonyAcceptImportDependency */
<ide>
<ide> class HarmonyAcceptDependency extends NullDependency {
<add> /**
<add> * @param {[number, number]} range expression range
<add> * @param {HarmonyAcceptImportDependency[]} dependencies import dependencies
<add> * @param {boolean} hasCallback true, if the range wraps an existing callback
<add> */
<ide> constructor(range, dependencies, hasCallback) {
<ide> super();
<ide> this.range = range;
<ide> HarmonyAcceptDependency.Template = class HarmonyAcceptDependencyTemplate extends
<ide> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, { runtimeTemplate }) {
<add> apply(dependency, source, templateContext) {
<ide> const dep = /** @type {HarmonyAcceptDependency} */ (dependency);
<del> // TODO: remove this hack
<del> const sourceAsAny = /** @type {any} */ (source);
<add> const { module } = templateContext;
<ide> const content = dep.dependencies
<ide> .filter(dependency =>
<del> HarmonyImportDependency.Template.isImportEmitted(
<del> dependency,
<del> sourceAsAny.module
<del> )
<add> HarmonyImportDependency.Template.isImportEmitted(dependency, module)
<ide> )
<del> .map(dependency => dependency.getImportStatement(true, runtimeTemplate))
<add> .map(dependency => dependency.getImportStatement(true, templateContext))
<ide> .join("");
<ide>
<ide> if (dep.hasCallback) {
<ide><path>lib/dependencies/HarmonyExportImportedSpecifierDependency.js
<ide> class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency {
<ide> return "harmony export imported specifier";
<ide> }
<ide>
<del> getMode(ignoreUnused) {
<add> /**
<add> * @param {ModuleGraph} moduleGraph the module graph
<add> * @param {boolean=} ignoreUnused ignore the fact that exports are unused
<add> * @returns {ExportMode} the export mode
<add> */
<add> getMode(moduleGraph, ignoreUnused) {
<ide> const name = this.name;
<ide> const id = this.id;
<ide> const used = this.originModule.isUsed(name);
<ide> class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency {
<ide>
<ide> /**
<ide> * Returns the referenced module and export
<add> * @param {ModuleGraph} moduleGraph module graph
<ide> * @returns {DependencyReference} reference
<ide> */
<del> getReference() {
<del> const mode = this.getMode(false);
<add> getReference(moduleGraph) {
<add> const mode = this.getMode(moduleGraph, false);
<ide>
<ide> switch (mode.type) {
<ide> case "missing":
<ide> class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency {
<ide>
<ide> /**
<ide> * Returns warnings
<add> * @param {ModuleGraph} moduleGraph module graph
<ide> * @returns {WebpackError[]} warnings
<ide> */
<del> getWarnings() {
<add> getWarnings(moduleGraph) {
<ide> if (
<ide> this.strictExportPresence ||
<ide> this.originModule.buildMeta.strictHarmonyModule
<ide> ) {
<ide> return [];
<ide> }
<del> return this._getErrors();
<add> return this._getErrors(moduleGraph);
<ide> }
<ide>
<ide> /**
<ide> * Returns errors
<add> * @param {ModuleGraph} moduleGraph module graph
<ide> * @returns {WebpackError[]} errors
<ide> */
<del> getErrors() {
<add> getErrors(moduleGraph) {
<ide> if (
<ide> this.strictExportPresence ||
<ide> this.originModule.buildMeta.strictHarmonyModule
<ide> ) {
<del> return this._getErrors();
<add> return this._getErrors(moduleGraph);
<ide> }
<ide> return [];
<ide> }
<ide>
<del> _getErrors() {
<add> _getErrors(moduleGraph) {
<ide> const importedModule = this._module;
<ide> if (!importedModule) {
<ide> return;
<ide> HarmonyExportImportedSpecifierDependency.Template = class HarmonyExportImportedS
<ide> if (this.isUsed(dep)) {
<ide> const importFragments = super.getInitFragments(dep, templateContext);
<ide> const exportFragment = new InitFragment(
<del> this.getContent(dep),
<add> this.getContent(dep, templateContext.moduleGraph),
<ide> InitFragment.STAGE_HARMONY_IMPORTS,
<ide> dep.sourceOrder
<ide> );
<ide> HarmonyExportImportedSpecifierDependency.Template = class HarmonyExportImportedS
<ide> }
<ide> }
<ide>
<del> getContent(dep) {
<del> const mode = dep.getMode(false);
<add> /**
<add> * @param {HarmonyExportImportedSpecifierDependency} dep dependency
<add> * @param {ModuleGraph} moduleGraph the module graph
<add> * @returns {string} the generated code
<add> */
<add> getContent(dep, moduleGraph) {
<add> const mode = dep.getMode(moduleGraph, false);
<ide> const module = dep.originModule;
<ide> const importedModule = dep._module;
<del> const importVar = dep.getImportVar();
<add> const importVar = dep.getImportVar(moduleGraph);
<ide>
<ide> switch (mode.type) {
<ide> case "missing":
<ide><path>lib/dependencies/HarmonyImportDependency.js
<ide> const DependencyReference = require("./DependencyReference");
<ide> const ModuleDependency = require("./ModuleDependency");
<ide>
<ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
<add>/** @typedef {import("webpack-sources").Source} Source */
<ide> /** @typedef {import("../Dependency")} Dependency */
<ide> /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
<ide> /** @typedef {import("../Module")} Module */
<ide> /** @typedef {import("../ModuleGraph")} ModuleGraph */
<add>/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
<ide> /** @typedef {import("../util/createHash").Hash} Hash */
<ide>
<ide> class HarmonyImportDependency extends ModuleDependency {
<ide> class HarmonyImportDependency extends ModuleDependency {
<ide>
<ide> /**
<ide> * Returns the referenced module and export
<add> * @param {ModuleGraph} moduleGraph module graph
<ide> * @returns {DependencyReference} reference
<ide> */
<del> getReference() {
<add> getReference(moduleGraph) {
<ide> if (!this._module) return null;
<ide> return new DependencyReference(
<ide> () => this._module,
<ide> class HarmonyImportDependency extends ModuleDependency {
<ide> );
<ide> }
<ide>
<del> getImportVar() {
<add> /**
<add> * @param {ModuleGraph} moduleGraph the module graph
<add> * @returns {string} name of the variable for the import
<add> */
<add> getImportVar(moduleGraph) {
<ide> let importVarMap = this.parserScope.importVarMap;
<ide> if (!importVarMap) this.parserScope.importVarMap = importVarMap = new Map();
<ide> let importVar = importVarMap.get(this._module);
<ide> class HarmonyImportDependency extends ModuleDependency {
<ide> return importVar;
<ide> }
<ide>
<del> getImportStatement(update, runtime) {
<add> /**
<add> * @param {boolean} update create new variables or update existing one
<add> * @param {DependencyTemplateContext} templateContext the template context
<add> * @returns {string} name of the variable for the import
<add> */
<add> getImportStatement(update, { runtimeTemplate: runtime, moduleGraph }) {
<ide> return runtime.importStatement({
<ide> update,
<ide> module: this._module,
<del> importVar: this.getImportVar(),
<add> importVar: this.getImportVar(moduleGraph),
<ide> request: this.request,
<ide> originModule: this.originModule
<ide> });
<ide> HarmonyImportDependency.Template = class HarmonyImportDependencyTemplate extends
<ide> * @param {DependencyTemplateContext} templateContext the template context
<ide> * @returns {InitFragment[]|null} the init fragments
<ide> */
<del> getInitFragments(dependency, { runtimeTemplate, module }) {
<add> getInitFragments(dependency, templateContext) {
<ide> const dep = /** @type {HarmonyImportDependency} */ (dependency);
<add> const { module } = templateContext;
<ide>
<ide> const moduleKey = dep._module ? dep._module.identifier() : dep.request;
<ide> const key = `harmony import ${moduleKey}`;
<ide> HarmonyImportDependency.Template = class HarmonyImportDependencyTemplate extends
<ide>
<ide> return [
<ide> new InitFragment(
<del> dep.getImportStatement(false, runtimeTemplate),
<add> dep.getImportStatement(false, templateContext),
<ide> InitFragment.STAGE_HARMONY_IMPORTS,
<ide> dep.sourceOrder,
<ide> key
<ide><path>lib/dependencies/HarmonyImportSideEffectDependency.js
<ide> const HarmonyImportDependency = require("./HarmonyImportDependency");
<ide> /** @typedef {import("../Dependency")} Dependency */
<ide> /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
<ide> /** @typedef {import("../InitFragment")} InitFragment */
<add>/** @typedef {import("../ModuleGraph")} ModuleGraph */
<ide> /** @typedef {import("../util/createHash").Hash} Hash */
<ide> /** @typedef {import("./DependencyReference")} DependencyReference */
<ide>
<ide> class HarmonyImportSideEffectDependency extends HarmonyImportDependency {
<ide>
<ide> /**
<ide> * Returns the referenced module and export
<add> * @param {ModuleGraph} moduleGraph module graph
<ide> * @returns {DependencyReference} reference
<ide> */
<del> getReference() {
<add> getReference(moduleGraph) {
<ide> if (this._module && this._module.factoryMeta.sideEffectFree) {
<ide> return null;
<ide> }
<del> return super.getReference();
<add> return super.getReference(moduleGraph);
<ide> }
<ide>
<ide> get type() {
<ide><path>lib/dependencies/HarmonyImportSpecifierDependency.js
<ide> class HarmonyImportSpecifierDependency extends HarmonyImportDependency {
<ide> return "harmony import specifier";
<ide> }
<ide>
<del> get _id() {
<add> /**
<add> * @param {ModuleGraph} moduleGraph the module graph
<add> * @returns {string} the imported id
<add> */
<add> getId(moduleGraph) {
<ide> return this.redirectedId || this.id;
<ide> }
<ide>
<ide> /**
<ide> * Returns the referenced module and export
<add> * @param {ModuleGraph} moduleGraph module graph
<ide> * @returns {DependencyReference} reference
<ide> */
<del> getReference() {
<add> getReference(moduleGraph) {
<ide> if (!this._module) return null;
<ide> return new DependencyReference(
<ide> () => this._module,
<del> this._id && !this.namespaceObjectAsContext ? [this._id] : true,
<add> this.getId(moduleGraph) && !this.namespaceObjectAsContext
<add> ? [this.getId(moduleGraph)]
<add> : true,
<ide> false,
<ide> this.sourceOrder
<ide> );
<ide> }
<ide>
<ide> /**
<ide> * Returns warnings
<add> * @param {ModuleGraph} moduleGraph module graph
<ide> * @returns {WebpackError[]} warnings
<ide> */
<del> getWarnings() {
<add> getWarnings(moduleGraph) {
<ide> if (
<ide> this.strictExportPresence ||
<ide> this.originModule.buildMeta.strictHarmonyModule
<ide> ) {
<ide> return [];
<ide> }
<del> return this._getErrors();
<add> return this._getErrors(moduleGraph);
<ide> }
<ide>
<ide> /**
<ide> * Returns errors
<add> * @param {ModuleGraph} moduleGraph module graph
<ide> * @returns {WebpackError[]} errors
<ide> */
<del> getErrors() {
<add> getErrors(moduleGraph) {
<ide> if (
<ide> this.strictExportPresence ||
<ide> this.originModule.buildMeta.strictHarmonyModule
<ide> ) {
<del> return this._getErrors();
<add> return this._getErrors(moduleGraph);
<ide> }
<ide> return [];
<ide> }
<ide>
<del> _getErrors() {
<add> _getErrors(moduleGraph) {
<ide> const importedModule = this._module;
<ide> if (!importedModule) {
<ide> return;
<ide> class HarmonyImportSpecifierDependency extends HarmonyImportDependency {
<ide> // It's not an harmony module
<ide> if (
<ide> this.originModule.buildMeta.strictHarmonyModule &&
<del> this._id !== "default"
<add> this.getId(moduleGraph) !== "default"
<ide> ) {
<ide> // In strict harmony modules we only support the default export
<del> const exportName = this._id
<del> ? `the named export '${this._id}'`
<add> const exportName = this.getId(moduleGraph)
<add> ? `the named export '${this.getId(moduleGraph)}'`
<ide> : "the namespace object";
<ide> return [
<ide> new HarmonyLinkingError(
<ide> class HarmonyImportSpecifierDependency extends HarmonyImportDependency {
<ide> return;
<ide> }
<ide>
<del> if (!this._id) {
<add> if (!this.getId(moduleGraph)) {
<ide> return;
<ide> }
<ide>
<del> if (importedModule.isProvided(this._id) !== false) {
<add> if (importedModule.isProvided(this.getId(moduleGraph)) !== false) {
<ide> // It's provided or we are not sure
<ide> return;
<ide> }
<ide>
<ide> // We are sure that it's not provided
<ide> const idIsNotNameMessage =
<del> this._id !== this.name ? ` (imported as '${this.name}')` : "";
<del> const errorMessage = `"export '${
<del> this._id
<del> }'${idIsNotNameMessage} was not found in '${this.userRequest}'`;
<add> this.getId(moduleGraph) !== this.name
<add> ? ` (imported as '${this.name}')`
<add> : "";
<add> const errorMessage = `"export '${this.getId(
<add> moduleGraph
<add> )}'${idIsNotNameMessage} was not found in '${this.userRequest}'`;
<ide> return [new HarmonyLinkingError(errorMessage)];
<ide> }
<ide>
<ide> class HarmonyImportSpecifierDependency extends HarmonyImportDependency {
<ide> updateHash(hash, moduleGraph) {
<ide> super.updateHash(hash, moduleGraph);
<ide> const importedModule = this._module;
<del> hash.update((importedModule && this._id) + "");
<add> hash.update((importedModule && this.getId(moduleGraph)) + "");
<ide> hash.update(
<del> (importedModule && this._id && importedModule.isUsed(this._id)) + ""
<add> (importedModule &&
<add> this.getId(moduleGraph) &&
<add> importedModule.isUsed(this.getId(moduleGraph))) + ""
<ide> );
<ide> hash.update(
<ide> (importedModule &&
<ide> HarmonyImportSpecifierDependency.Template = class HarmonyImportSpecifierDependen
<ide> apply(dependency, source, templateContext) {
<ide> super.apply(dependency, source, templateContext);
<ide> const dep = /** @type {HarmonyImportSpecifierDependency} */ (dependency);
<del> const content = this.getContent(dep, templateContext.runtimeTemplate);
<add> const content = this.getContent(dep, templateContext);
<ide> source.replace(dep.range[0], dep.range[1] - 1, content);
<ide> }
<ide>
<del> getContent(dep, runtime) {
<add> getContent(dep, { runtimeTemplate: runtime, moduleGraph }) {
<ide> const exportExpr = runtime.exportFromImport({
<ide> module: dep._module,
<ide> request: dep.request,
<del> exportName: dep._id,
<add> exportName: dep.getId(moduleGraph),
<ide> originModule: dep.originModule,
<ide> asiSafe: dep.shorthand,
<ide> isCall: dep.call,
<ide> callContext: !dep.directImport,
<del> importVar: dep.getImportVar()
<add> importVar: dep.getImportVar(moduleGraph)
<ide> });
<ide> return dep.shorthand ? `${dep.name}: ${exportExpr}` : exportExpr;
<ide> }
<ide><path>lib/dependencies/ImportDependency.js
<ide> ImportDependency.Template = class ImportDependencyTemplate extends ModuleDepende
<ide> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, { runtimeTemplate }) {
<add> apply(dependency, source, { runtimeTemplate, moduleGraph }) {
<ide> const dep = /** @type {ImportDependency} */ (dependency);
<ide> const content = runtimeTemplate.moduleNamespacePromise({
<ide> block: dep.block,
<ide><path>lib/dependencies/ImportEagerDependency.js
<ide> ImportEagerDependency.Template = class ImportEagerDependencyTemplate extends Mod
<ide> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, { runtimeTemplate }) {
<add> apply(dependency, source, { runtimeTemplate, moduleGraph }) {
<ide> const dep = /** @type {ImportEagerDependency} */ (dependency);
<ide> const content = runtimeTemplate.moduleNamespacePromise({
<ide> module: dep.module,
<ide><path>lib/dependencies/ImportWeakDependency.js
<ide> ImportWeakDependency.Template = class ImportDependencyTemplate extends ModuleDep
<ide> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, { runtimeTemplate }) {
<add> apply(dependency, source, { runtimeTemplate, moduleGraph }) {
<ide> const dep = /** @type {ImportWeakDependency} */ (dependency);
<ide> const content = runtimeTemplate.moduleNamespacePromise({
<ide> module: dep.module,
<ide><path>lib/dependencies/LoaderPlugin.js
<ide> class LoaderPlugin {
<ide> if (err) {
<ide> return callback(err);
<ide> }
<del> if (!dep.module) {
<add> const referencedModule = dep.module;
<add> if (!referencedModule) {
<ide> return callback(new Error("Cannot load the module"));
<ide> }
<ide> // TODO consider removing this in webpack 5
<del> if (dep.module instanceof NormalModule && dep.module.error) {
<del> return callback(dep.module.error);
<add> if (
<add> referencedModule instanceof NormalModule &&
<add> referencedModule.error
<add> ) {
<add> return callback(referencedModule.error);
<ide> }
<del> const moduleSource = dep.module.originalSource();
<add> const moduleSource = referencedModule.originalSource();
<ide> if (!moduleSource) {
<ide> throw new Error(
<ide> "The module created for a LoaderDependency must have an original source"
<ide> class LoaderPlugin {
<ide> map = moduleSource.map();
<ide> source = moduleSource.source();
<ide> }
<del> if (dep.module.buildInfo.fileDependencies) {
<del> for (const d of dep.module.buildInfo.fileDependencies) {
<add> if (referencedModule.buildInfo.fileDependencies) {
<add> for (const d of referencedModule.buildInfo
<add> .fileDependencies) {
<ide> loaderContext.addDependency(d);
<ide> }
<ide> }
<del> if (dep.module.buildInfo.contextDependencies) {
<del> for (const d of dep.module.buildInfo.contextDependencies) {
<add> if (referencedModule.buildInfo.contextDependencies) {
<add> for (const d of referencedModule.buildInfo
<add> .contextDependencies) {
<ide> loaderContext.addContextDependency(d);
<ide> }
<ide> }
<del> return callback(null, source, map, dep.module);
<add> return callback(null, source, map, referencedModule);
<ide> });
<ide> }
<ide> );
<ide><path>lib/dependencies/ModuleDependencyTemplateAsId.js
<ide> class ModuleDependencyTemplateAsId extends ModuleDependency.Template {
<ide> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, { runtimeTemplate }) {
<add> apply(dependency, source, { runtimeTemplate, moduleGraph }) {
<ide> const dep = /** @type {ModuleDependency} */ (dependency);
<ide> if (!dep.range) return;
<ide> const content = runtimeTemplate.moduleId({
<ide><path>lib/dependencies/ModuleDependencyTemplateAsRequireId.js
<ide> class ModuleDependencyTemplateAsRequireId extends ModuleDependency.Template {
<ide> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, { runtimeTemplate }) {
<add> apply(dependency, source, { runtimeTemplate, moduleGraph }) {
<ide> const dep = /** @type {ModuleDependency} */ (dependency);
<ide> if (!dep.range) return;
<ide> const content = runtimeTemplate.moduleExports({
<ide><path>lib/dependencies/RequireIncludeDependency.js
<ide> const ModuleDependency = require("./ModuleDependency");
<ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
<ide> /** @typedef {import("../Dependency")} Dependency */
<ide> /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
<add>/** @typedef {import("../ModuleGraph")} ModuleGraph */
<ide>
<ide> class RequireIncludeDependency extends ModuleDependency {
<ide> constructor(request, range) {
<ide> class RequireIncludeDependency extends ModuleDependency {
<ide>
<ide> /**
<ide> * Returns the referenced module and export
<add> * @param {ModuleGraph} moduleGraph module graph
<ide> * @returns {DependencyReference} reference
<ide> */
<del> getReference() {
<add> getReference(moduleGraph) {
<ide> if (!this.module) return null;
<ide> // This doesn't use any export
<ide> return new DependencyReference(() => this.module, [], false);
<ide><path>lib/dependencies/WebAssemblyExportImportedDependency.js
<ide> const DependencyReference = require("./DependencyReference");
<ide> const ModuleDependency = require("./ModuleDependency");
<ide>
<add>/** @typedef {import("../ModuleGraph")} ModuleGraph */
<add>
<ide> class WebAssemblyExportImportedDependency extends ModuleDependency {
<ide> constructor(exportName, request, name) {
<ide> super(request);
<ide> class WebAssemblyExportImportedDependency extends ModuleDependency {
<ide>
<ide> /**
<ide> * Returns the referenced module and export
<add> * @param {ModuleGraph} moduleGraph module graph
<ide> * @returns {DependencyReference} reference
<ide> */
<del> getReference() {
<add> getReference(moduleGraph) {
<ide> if (!this.module) return null;
<ide> return new DependencyReference(() => this.module, [this.name], false);
<ide> }
<ide><path>lib/dependencies/WebAssemblyImportDependency.js
<ide> const DependencyReference = require("./DependencyReference");
<ide> const ModuleDependency = require("./ModuleDependency");
<ide>
<ide> /** @typedef {import("@webassemblyjs/ast").ModuleImportDescription} ModuleImportDescription */
<add>/** @typedef {import("../ModuleGraph")} ModuleGraph */
<ide> /** @typedef {import("../WebpackError")} WebpackError */
<ide>
<ide> class WebAssemblyImportDependency extends ModuleDependency {
<ide> class WebAssemblyImportDependency extends ModuleDependency {
<ide>
<ide> /**
<ide> * Returns the referenced module and export
<add> * @param {ModuleGraph} moduleGraph module graph
<ide> * @returns {DependencyReference} reference
<ide> */
<del> getReference() {
<add> getReference(moduleGraph) {
<ide> if (!this.module) return null;
<ide> return new DependencyReference(() => this.module, [this.name], false);
<ide> }
<ide>
<ide> /**
<ide> * Returns errors
<add> * @param {ModuleGraph} moduleGraph module graph
<ide> * @returns {WebpackError[]} errors
<ide> */
<del> getErrors() {
<add> getErrors(moduleGraph) {
<ide> if (
<ide> this.onlyDirectImport &&
<ide> this.module &&
<ide><path>lib/node/NodeChunkTemplatePlugin.js
<ide> class NodeChunkTemplatePlugin {
<ide> apply(chunkTemplate) {
<ide> chunkTemplate.hooks.render.tap(
<ide> "NodeChunkTemplatePlugin",
<del> (modules, chunk) => {
<add> (modules, moduleTemplate, { chunk }) => {
<ide> const source = new ConcatSource();
<ide> source.add(
<ide> `exports.ids = ${JSON.stringify(chunk.ids)};\nexports.modules = `
<ide><path>lib/node/NodeHotUpdateChunkTemplatePlugin.js
<ide>
<ide> const { ConcatSource } = require("webpack-sources");
<ide>
<add>/** @typedef {import("../HotUpdateChunkTemplate")} HotUpdateChunkTemplate */
<add>
<ide> class NodeHotUpdateChunkTemplatePlugin {
<add> /**
<add> * @param {HotUpdateChunkTemplate} hotUpdateChunkTemplate the hot update chunk template
<add> * @returns {void}
<add> */
<ide> apply(hotUpdateChunkTemplate) {
<ide> hotUpdateChunkTemplate.hooks.render.tap(
<ide> "NodeHotUpdateChunkTemplatePlugin",
<del> (modulesSource, modules, removedModules, hash, id) => {
<add> (modulesSource, moduleTemplate, { chunk }) => {
<ide> const source = new ConcatSource();
<ide> source.add(
<del> "exports.id = " + JSON.stringify(id) + ";\nexports.modules = "
<add> "exports.id = " + JSON.stringify(chunk.id) + ";\nexports.modules = "
<ide> );
<ide> source.add(modulesSource);
<ide> source.add(";");
<ide><path>lib/node/ReadFileCompileWasmTemplatePlugin.js
<ide> class ReadFileCompileWasmTemplatePlugin {
<ide> ]);
<ide>
<ide> const plugin = new WasmMainTemplatePlugin(
<add> compilation.moduleGraph,
<ide> Object.assign(
<ide> {
<ide> generateLoadBinaryCode,
<ide><path>lib/optimize/ConcatenatedModule.js
<ide> const createHash = require("../util/createHash");
<ide> /** @typedef {import("../InitFragment")} InitFragment */
<ide> /** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */
<ide> /** @typedef {import("../Module").SourceContext} SourceContext */
<add>/** @typedef {import("../ModuleGraph")} ModuleGraph */
<ide> /** @typedef {import("../RequestShortener")} RequestShortener */
<ide> /** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
<ide> /** @typedef {import("../util/createHash").Hash} Hash */
<ide> const getPathInAst = (ast, node) => {
<ide> };
<ide>
<ide> class ConcatenatedModule extends Module {
<del> constructor(rootModule, modules, concatenationList) {
<add> /**
<add> * @param {Module} rootModule the root module of the concatenation
<add> * @param {Set<Module>} modules all modules in the concantenation (including the root module)
<add> * @param {Compilation} compilation the compilation
<add> */
<add> constructor(rootModule, modules, compilation) {
<ide> super("javascript/esm", null);
<ide> super.setChunks(rootModule._chunks);
<ide>
<ide> class ConcatenatedModule extends Module {
<ide> this.used = rootModule.used;
<ide> this.usedExports = rootModule.usedExports;
<ide>
<add> const modulesArray = Array.from(modules);
<add>
<ide> // Info from Build
<ide> this.buildInfo = {
<ide> strict: true,
<del> cacheable: modules.every(m => m.buildInfo.cacheable),
<add> cacheable: modulesArray.every(m => m.buildInfo.cacheable),
<ide> moduleArgument: rootModule.buildInfo.moduleArgument,
<ide> exportsArgument: rootModule.buildInfo.exportsArgument,
<ide> fileDependencies: new Set(),
<ide> contextDependencies: new Set(),
<ide> assets: undefined
<ide> };
<del> this.built = modules.some(m => m.built);
<add> this.built = modulesArray.some(m => m.built);
<ide> this.buildMeta = rootModule.buildMeta;
<ide>
<ide> // Caching
<del> this._numberOfConcatenatedModules = modules.length;
<add> this._numberOfConcatenatedModules = modules.size;
<ide>
<ide> // Graph
<ide> const modulesSet = new Set(modules);
<ide> class ConcatenatedModule extends Module {
<ide>
<ide> this.warnings = [];
<ide> this.errors = [];
<del> this._orderedConcatenationList =
<del> concatenationList ||
<del> ConcatenatedModule.createConcatenationList(rootModule, modulesSet, null);
<add> this._orderedConcatenationList = ConcatenatedModule._createConcatenationList(
<add> rootModule,
<add> modulesSet,
<add> compilation
<add> );
<ide> for (const info of this._orderedConcatenationList) {
<ide> if (info.type === "concatenated") {
<ide> const m = info.module;
<ide> class ConcatenatedModule extends Module {
<ide> }
<ide>
<ide> /**
<add> * @private
<ide> * @param {Module} rootModule the root of the concatenation
<ide> * @param {Set<Module>} modulesSet a set of modules which should be concatenated
<ide> * @param {Compilation} compilation the compilation context
<ide> * @returns {ConcatenationEntry[]} concatenation list
<ide> */
<del> static createConcatenationList(rootModule, modulesSet, compilation) {
<add> static _createConcatenationList(rootModule, modulesSet, compilation) {
<ide> const list = [];
<ide> const set = new Set();
<ide>
<ide> class ConcatenatedModule extends Module {
<ide> * @param {SourceContext} sourceContext source context
<ide> * @returns {Source} generated source
<ide> */
<del> source({ dependencyTemplates, runtimeTemplate }) {
<add> source({ dependencyTemplates, runtimeTemplate, moduleGraph }) {
<ide> const requestShortener = runtimeTemplate.requestShortener;
<ide> // Metainfo for each module
<ide> const modulesWithInfo = this._orderedConcatenationList.map((info, idx) => {
<ide> class ConcatenatedModule extends Module {
<ide> const m = info.module;
<ide> const source = m.source({
<ide> dependencyTemplates: innerDependencyTemplates,
<del> runtimeTemplate
<add> runtimeTemplate,
<add> moduleGraph
<ide> });
<ide> const code = source.source();
<ide> let ast;
<ide> class HarmonyImportSpecifierDependencyConcatenatedTemplate extends DependencyTem
<ide> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, { runtimeTemplate, dependencyTemplates }) {
<add> apply(dependency, source, templateContext) {
<add> const { moduleGraph } = templateContext;
<ide> const dep = /** @type {HarmonyImportSpecifierDependency} */ (dependency);
<ide> const module = dep._module;
<ide> const info = this.modulesMap.get(module);
<ide> if (!info) {
<del> this.originalTemplate.apply(dependency, source, {
<del> runtimeTemplate,
<del> dependencyTemplates
<del> });
<add> this.originalTemplate.apply(dependency, source, templateContext);
<ide> return;
<ide> }
<ide> let content;
<ide> const callFlag = dep.call ? "_call" : "";
<ide> const strictFlag = dep.originModule.buildMeta.strictHarmonyModule
<ide> ? "_strict"
<ide> : "";
<del> if (dep._id === null) {
<add> const id = dep.getId(moduleGraph);
<add> if (id === null) {
<ide> content = `__WEBPACK_MODULE_REFERENCE__${info.index}_ns${strictFlag}__`;
<ide> } else if (dep.namespaceObjectAsContext) {
<ide> content = `__WEBPACK_MODULE_REFERENCE__${
<ide> info.index
<del> }_ns${strictFlag}__[${JSON.stringify(dep._id)}]`;
<add> }_ns${strictFlag}__[${JSON.stringify(id)}]`;
<ide> } else {
<del> const exportData = Buffer.from(dep._id, "utf-8").toString("hex");
<add> const exportData = Buffer.from(id, "utf-8").toString("hex");
<ide> content = `__WEBPACK_MODULE_REFERENCE__${
<ide> info.index
<ide> }_${exportData}${callFlag}${strictFlag}__`;
<ide> class HarmonyImportSideEffectDependencyConcatenatedTemplate extends DependencyTe
<ide> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, { runtimeTemplate, dependencyTemplates }) {
<add> apply(dependency, source, templateContext) {
<add> const { moduleGraph } = templateContext;
<ide> const dep = /** @type {HarmonyImportSideEffectDependency} */ (dependency);
<ide> const module = dep._module;
<ide> const info = this.modulesMap.get(module);
<ide> if (!info) {
<del> this.originalTemplate.apply(dependency, source, {
<del> runtimeTemplate,
<del> dependencyTemplates
<del> });
<add> this.originalTemplate.apply(dependency, source, templateContext);
<ide> return;
<ide> }
<ide> }
<ide> class HarmonyExportSpecifierDependencyConcatenatedTemplate extends DependencyTem
<ide> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, { runtimeTemplate, dependencyTemplates }) {
<add> apply(dependency, source, templateContext) {
<ide> const dep = /** @type {HarmonyExportSpecifierDependency} */ (dependency);
<ide> if (dep.originModule === this.rootModule) {
<del> this.originalTemplate.apply(dependency, source, {
<del> runtimeTemplate,
<del> dependencyTemplates
<del> });
<add> this.originalTemplate.apply(dependency, source, templateContext);
<ide> }
<ide> }
<ide> }
<ide> class HarmonyExportExpressionDependencyConcatenatedTemplate extends DependencyTe
<ide> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, { runtimeTemplate, dependencyTemplates }) {
<add> apply(
<add> dependency,
<add> source,
<add> { runtimeTemplate, dependencyTemplates, moduleGraph }
<add> ) {
<ide> const dep = /** @type {HarmonyExportExpressionDependency} */ (dependency);
<ide> let content =
<ide> "/* harmony default export */ var __WEBPACK_MODULE_DEFAULT_EXPORT__ = ";
<ide> class HarmonyExportImportedSpecifierDependencyConcatenatedTemplate extends Depen
<ide> this.modulesMap = modulesMap;
<ide> }
<ide>
<del> getExports(dep) {
<add> getExports(dep, { moduleGraph }) {
<ide> const importModule = dep._module;
<ide> if (dep.id) {
<ide> // export { named } from "module"
<ide> class HarmonyExportImportedSpecifierDependencyConcatenatedTemplate extends Depen
<ide> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, { runtimeTemplate, dependencyTemplates }) {
<add> apply(dependency, source, templateContext) {
<add> const { moduleGraph } = templateContext;
<ide> const dep = /** @type {HarmonyExportImportedSpecifierDependency} */ (dependency);
<ide> if (dep.originModule === this.rootModule) {
<ide> if (this.modulesMap.get(dep._module)) {
<del> const exportDefs = this.getExports(dep);
<add> const exportDefs = this.getExports(dep, { moduleGraph });
<ide> for (const def of exportDefs) {
<ide> const info = this.modulesMap.get(def.module);
<ide> const used = dep.originModule.isUsed(def.name);
<ide> class HarmonyExportImportedSpecifierDependencyConcatenatedTemplate extends Depen
<ide> source.insert(-1, content);
<ide> }
<ide> } else {
<del> this.originalTemplate.apply(dependency, source, {
<del> runtimeTemplate,
<del> dependencyTemplates
<del> });
<add> this.originalTemplate.apply(dependency, source, templateContext);
<ide> }
<ide> }
<ide> }
<ide> class HarmonyCompatibilityDependencyConcatenatedTemplate extends DependencyTempl
<ide> * @param {DependencyTemplateContext} templateContext the context object
<ide> * @returns {void}
<ide> */
<del> apply(dependency, source, { runtimeTemplate, dependencyTemplates }) {
<add> apply(
<add> dependency,
<add> source,
<add> { runtimeTemplate, dependencyTemplates, moduleGraph }
<add> ) {
<ide> // do nothing
<ide> }
<ide> }
<ide><path>lib/optimize/ModuleConcatenationPlugin.js
<ide> const ModuleHotDeclineDependency = require("../dependencies/ModuleHotDeclineDepe
<ide> const StackedSetMap = require("../util/StackedSetMap");
<ide> const ConcatenatedModule = require("./ConcatenatedModule");
<ide>
<add>/** @typedef {import("../Compilation")} Compilation */
<add>/** @typedef {import("../Compiler")} Compiler */
<add>/** @typedef {import("../Module")} Module */
<add>
<ide> const formatBailoutReason = msg => {
<ide> return "ModuleConcatenation bailout: " + msg;
<ide> };
<ide> class ModuleConcatenationPlugin {
<ide> this.options = options;
<ide> }
<ide>
<add> /**
<add> * @param {Compiler} compiler webpack compiler
<add> * @returns {void}
<add> */
<ide> apply(compiler) {
<ide> compiler.hooks.compilation.tap(
<ide> "ModuleConcatenationPlugin",
<ide> class ModuleConcatenationPlugin {
<ide> );
<ide> const importingModuleTypes = new Map(
<ide> Array.from(importingModules).map(
<del> m => /** @type {[string, Set]} */ ([
<add> m => /** @type {[Module, Set<string>]} */ ([
<ide> m,
<ide> new Set(
<ide> nonHarmonyReasons
<ide> class ModuleConcatenationPlugin {
<ide> const rootModule = concatConfiguration.rootModule;
<ide> const newModule = new ConcatenatedModule(
<ide> rootModule,
<del> Array.from(modules),
<del> ConcatenatedModule.createConcatenationList(
<del> rootModule,
<del> modules,
<del> compilation
<del> )
<add> modules,
<add> compilation
<ide> );
<ide> for (const warning of concatConfiguration.getWarningsSorted()) {
<ide> newModule.optimizationBailout.push(requestShortener => {
<ide> class ModuleConcatenationPlugin {
<ide> if (reason.dependency.module === concatConfiguration.rootModule)
<ide> reason.dependency.module = newModule;
<ide> if (
<add> reason.dependency instanceof HarmonyImportDependency &&
<ide> reason.dependency.redirectedModule ===
<del> concatConfiguration.rootModule
<add> concatConfiguration.rootModule
<ide> )
<ide> reason.dependency.redirectedModule = newModule;
<ide> }
<ide> class ModuleConcatenationPlugin {
<ide> // Get reference info only for harmony Dependencies
<ide> .map(dep => {
<ide> if (!(dep instanceof HarmonyImportDependency)) return null;
<del> if (!compilation) return dep.getReference();
<add> if (!compilation) return dep.getReference(compilation.moduleGraph);
<ide> return compilation.getDependencyReference(module, dep);
<ide> })
<ide>
<ide> class ModuleConcatenationPlugin {
<ide> );
<ide> }
<ide>
<add> /**
<add> * @param {Compilation} compilation webpack compilation
<add> * @param {ConcatConfiguration} config concat configuration (will be modified when added)
<add> * @param {Module} module the module to be added
<add> * @param {Set<Module>} possibleModules modules that are candidates
<add> * @param {Map<Module, Module>} failureCache cache for problematic modules to be more performant
<add> * @returns {Module} the problematic module
<add> */
<ide> _tryToAdd(compilation, config, module, possibleModules, failureCache) {
<ide> const cacheEntry = failureCache.get(module);
<ide> if (cacheEntry) {
<ide><path>lib/optimize/SideEffectsFlagPlugin.js
<ide> class SideEffectsFlagPlugin {
<ide> });
<ide> });
<ide> compiler.hooks.compilation.tap("SideEffectsFlagPlugin", compilation => {
<add> const moduleGraph = compilation.moduleGraph;
<ide> compilation.hooks.optimizeDependencies.tap(
<ide> "SideEffectsFlagPlugin",
<ide> modules => {
<ide> class SideEffectsFlagPlugin {
<ide> for (const dep of module.dependencies) {
<ide> if (dep instanceof HarmonyExportImportedSpecifierDependency) {
<ide> if (module.factoryMeta.sideEffectFree) {
<del> const mode = dep.getMode(true);
<add> const mode = dep.getMode(moduleGraph, true);
<ide> if (mode.type === "safe-reexport") {
<ide> let map = reexportMaps.get(module);
<ide> if (!map) {
<ide><path>lib/wasm/WasmMainTemplatePlugin.js
<ide> const WebAssemblyUtils = require("./WebAssemblyUtils");
<ide>
<ide> /** @typedef {import("../MainTemplate")} MainTemplate */
<ide> /** @typedef {import("../Module")} Module */
<add>/** @typedef {import("../ModuleGraph")} ModuleGraph */
<ide>
<ide> // Get all wasm modules
<ide> const getAllWasmModules = chunk => {
<ide> const getAllWasmModules = chunk => {
<ide>
<ide> /**
<ide> * generates the import object function for a module
<add> * @param {ModuleGraph} moduleGraph the module graph
<ide> * @param {Module} module the module
<ide> * @param {boolean} mangle mangle imports
<ide> * @returns {string} source code
<ide> */
<del>const generateImportObject = (module, mangle) => {
<add>const generateImportObject = (moduleGraph, module, mangle) => {
<ide> const waitForInstances = new Map();
<ide> const properties = [];
<ide> const usedWasmDependencies = WebAssemblyUtils.getUsedDependencies(
<add> moduleGraph,
<ide> module,
<ide> mangle
<ide> );
<ide> const generateImportObject = (module, mangle) => {
<ide> };
<ide>
<ide> class WasmMainTemplatePlugin {
<del> constructor({ generateLoadBinaryCode, supportsStreaming, mangleImports }) {
<add> /**
<add> * @param {ModuleGraph} moduleGraph the module graph
<add> * @param {Object} options options
<add> * @param {function(string): string} options.generateLoadBinaryCode function to generate the load code
<add> * @param {boolean=} options.supportsStreaming whether the generateLoadBinaryCode function supports streaming compilation
<add> * @param {boolean=} options.mangleImports whether imports should be mangled
<add> */
<add> constructor(
<add> moduleGraph,
<add> { generateLoadBinaryCode, supportsStreaming, mangleImports }
<add> ) {
<add> this.moduleGraph = moduleGraph;
<ide> this.generateLoadBinaryCode = generateLoadBinaryCode;
<ide> this.supportsStreaming = supportsStreaming;
<ide> this.mangleImports = mangleImports;
<ide> class WasmMainTemplatePlugin {
<ide> const wasmModules = getAllWasmModules(chunk);
<ide> if (wasmModules.length === 0) return source;
<ide> const importObjects = wasmModules.map(module => {
<del> return generateImportObject(module, this.mangleImports);
<add> return generateImportObject(
<add> this.moduleGraph,
<add> module,
<add> this.mangleImports
<add> );
<ide> });
<ide> return Template.asString([
<ide> source,
<ide><path>lib/wasm/WebAssemblyGenerator.js
<ide> const WebAssemblyExportImportedDependency = require("../dependencies/WebAssembly
<ide> /** @typedef {import("../DependencyTemplates")} DependencyTemplates */
<ide> /** @typedef {import("../Generator").GenerateContext} GenerateContext */
<ide> /** @typedef {import("../Module")} Module */
<add>/** @typedef {import("../ModuleGraph")} ModuleGraph */
<ide> /** @typedef {import("../NormalModule")} NormalModule */
<ide> /** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
<ide> /** @typedef {import("./WebAssemblyUtils").UsedWasmDependency} UsedWasmDependency */
<ide> const addInitFunction = ({
<ide>
<ide> /**
<ide> * Extract mangle mappings from module
<add> * @param {ModuleGraph} moduleGraph module graph
<ide> * @param {Module} module current module
<ide> * @param {boolean} mangle mangle imports
<ide> * @returns {Map<string, UsedWasmDependency>} mappings to mangled names
<ide> */
<del>const getUsedDependencyMap = (module, mangle) => {
<add>const getUsedDependencyMap = (moduleGraph, module, mangle) => {
<ide> /** @type {Map<string, UsedWasmDependency>} */
<ide> const map = new Map();
<del> for (const usedDep of WebAssemblyUtils.getUsedDependencies(module, mangle)) {
<add> for (const usedDep of WebAssemblyUtils.getUsedDependencies(
<add> moduleGraph,
<add> module,
<add> mangle
<add> )) {
<ide> const dep = usedDep.dependency;
<ide> const request = dep.request;
<ide> const exportName = dep.name;
<ide> class WebAssemblyGenerator extends Generator {
<ide> * @param {GenerateContext} generateContext context for generate
<ide> * @returns {Source} generated code
<ide> */
<del> generate(module, { dependencyTemplates, runtimeTemplate, type }) {
<add> generate(module, { moduleGraph }) {
<ide> const source = module.originalSource().source();
<ide> // TODO remove this casts when webpack-sources is fixed
<ide> // source() should have return type (string | Buffer)
<ide> class WebAssemblyGenerator extends Generator {
<ide> const nextTypeIndex = getNextTypeIndex(ast);
<ide>
<ide> const usedDependencyMap = getUsedDependencyMap(
<add> moduleGraph,
<ide> module,
<ide> this.options.mangleImports
<ide> );
<ide><path>lib/wasm/WebAssemblyInInitialChunkError.js
<ide> const WebpackError = require("../WebpackError");
<ide>
<ide> /** @typedef {import("../Module")} Module */
<add>/** @typedef {import("../ModuleGraph")} ModuleGraph */
<ide> /** @typedef {import("../RequestShortener")} RequestShortener */
<ide>
<ide> /**
<ide> * @param {Module} module module to get chains from
<add> * @param {ModuleGraph} moduleGraph the module graph
<ide> * @param {RequestShortener} requestShortener to make readable identifiers
<ide> * @returns {string[]} all chains to the module
<ide> */
<del>const getInitialModuleChains = (module, requestShortener) => {
<add>const getInitialModuleChains = (module, moduleGraph, requestShortener) => {
<ide> const queue = [
<ide> { head: module, message: module.readableIdentifier(requestShortener) }
<ide> ];
<ide> const getInitialModuleChains = (module, requestShortener) => {
<ide> module.exports = class WebAssemblyInInitialChunkError extends WebpackError {
<ide> /**
<ide> * @param {Module} module WASM module
<add> * @param {ModuleGraph} moduleGraph the module graph
<ide> * @param {RequestShortener} requestShortener request shortener
<ide> */
<del> constructor(module, requestShortener) {
<del> const moduleChains = getInitialModuleChains(module, requestShortener);
<add> constructor(module, moduleGraph, requestShortener) {
<add> const moduleChains = getInitialModuleChains(
<add> module,
<add> moduleGraph,
<add> requestShortener
<add> );
<ide> const message = `WebAssembly module is included in initial chunk.
<ide> This is not allowed, because WebAssembly download and compilation must happen asynchronous.
<ide> Add an async splitpoint (i. e. import()) somewhere between your entrypoint and the WebAssembly module:
<ide><path>lib/wasm/WebAssemblyJavascriptGenerator.js
<ide> class WebAssemblyJavascriptGenerator extends Generator {
<ide> * @param {GenerateContext} generateContext context for generate
<ide> * @returns {Source} generated code
<ide> */
<del> generate(module, { dependencyTemplates, runtimeTemplate }) {
<add> generate(module, { runtimeTemplate, moduleGraph }) {
<ide> const initIdentifer = Array.isArray(module.usedExports)
<ide> ? Template.numberToIdentifer(module.usedExports.length)
<ide> : "__webpack_init__";
<ide><path>lib/wasm/WebAssemblyModulesPlugin.js
<ide> const WebAssemblyInInitialChunkError = require("./WebAssemblyInInitialChunkError
<ide> const WebAssemblyJavascriptGenerator = require("./WebAssemblyJavascriptGenerator");
<ide> const WebAssemblyParser = require("./WebAssemblyParser");
<ide>
<add>/** @typedef {import("webpack-sources").Source} Source */
<ide> /** @typedef {import("../Compiler")} Compiler */
<add>/** @typedef {import("../Module")} Module */
<add>/** @typedef {import("../ModuleTemplate")} ModuleTemplate */
<add>/** @typedef {import("../ModuleTemplate").RenderContext} RenderContext */
<ide>
<ide> class WebAssemblyModulesPlugin {
<ide> constructor(options) {
<ide> class WebAssemblyModulesPlugin {
<ide> this.renderWebAssembly(
<ide> module,
<ide> moduleTemplates.webassembly,
<del> dependencyTemplates
<add> {
<add> chunk,
<add> dependencyTemplates,
<add> runtimeTemplate: compilation.runtimeTemplate,
<add> moduleGraph: compilation.moduleGraph
<add> }
<ide> ),
<ide> filenameTemplate,
<ide> pathOptions: {
<ide> class WebAssemblyModulesPlugin {
<ide> compilation.errors.push(
<ide> new WebAssemblyInInitialChunkError(
<ide> module,
<add> compilation.moduleGraph,
<ide> compilation.requestShortener
<ide> )
<ide> );
<ide> class WebAssemblyModulesPlugin {
<ide> );
<ide> }
<ide>
<del> renderWebAssembly(module, moduleTemplate, dependencyTemplates) {
<del> return moduleTemplate.render(module, dependencyTemplates, {});
<add> /**
<add> *
<add> * @param {Module} module the wasm module
<add> * @param {ModuleTemplate} moduleTemplate the module tempalte
<add> * @param {RenderContext} renderContext render context
<add> * @returns {Source} rendered source
<add> */
<add> renderWebAssembly(module, moduleTemplate, renderContext) {
<add> return moduleTemplate.render(module, renderContext);
<ide> }
<ide> }
<ide>
<ide><path>lib/wasm/WebAssemblyUtils.js
<ide> const Template = require("../Template");
<ide> const WebAssemblyImportDependency = require("../dependencies/WebAssemblyImportDependency");
<ide>
<ide> /** @typedef {import("../Module")} Module */
<add>/** @typedef {import("../ModuleGraph")} ModuleGraph */
<ide>
<ide> /** @typedef {Object} UsedWasmDependency
<ide> * @property {WebAssemblyImportDependency} dependency the dependency
<ide> const WebAssemblyImportDependency = require("../dependencies/WebAssemblyImportDe
<ide> const MANGLED_MODULE = "a";
<ide>
<ide> /**
<add> * @param {ModuleGraph} moduleGraph the module graph
<ide> * @param {Module} module the module
<ide> * @param {boolean} mangle mangle module and export names
<ide> * @returns {UsedWasmDependency[]} used dependencies and (mangled) name
<ide> */
<del>const getUsedDependencies = (module, mangle) => {
<add>const getUsedDependencies = (moduleGraph, module, mangle) => {
<ide> /** @type {UsedWasmDependency[]} */
<ide> const array = [];
<ide> let importIndex = 0;
<ide><path>lib/web/FetchCompileWasmTemplatePlugin.js
<ide> class FetchCompileWasmTemplatePlugin {
<ide> `fetch(${mainTemplate.requireFn}.p + ${path})`;
<ide>
<ide> const plugin = new WasmMainTemplatePlugin(
<add> compilation.moduleGraph,
<ide> Object.assign(
<ide> {
<ide> generateLoadBinaryCode,
<ide><path>lib/web/JsonpChunkTemplatePlugin.js
<ide> class JsonpChunkTemplatePlugin {
<ide> apply(chunkTemplate) {
<ide> chunkTemplate.hooks.render.tap(
<ide> "JsonpChunkTemplatePlugin",
<del> (modules, chunk) => {
<add> (modules, moduleTemplate, { chunk }) => {
<ide> const jsonpFunction = chunkTemplate.outputOptions.jsonpFunction;
<ide> const globalObject = chunkTemplate.outputOptions.globalObject;
<ide> const source = new ConcatSource();
<ide><path>lib/web/JsonpHotUpdateChunkTemplatePlugin.js
<ide>
<ide> const { ConcatSource } = require("webpack-sources");
<ide>
<add>/** @typedef {import("../HotUpdateChunkTemplate")} HotUpdateChunkTemplate */
<add>
<ide> class JsonpHotUpdateChunkTemplatePlugin {
<add> /**
<add> * @param {HotUpdateChunkTemplate} hotUpdateChunkTemplate the hot update chunk template
<add> * @returns {void}
<add> */
<ide> apply(hotUpdateChunkTemplate) {
<ide> hotUpdateChunkTemplate.hooks.render.tap(
<ide> "JsonpHotUpdateChunkTemplatePlugin",
<del> (modulesSource, modules, removedModules, hash, id) => {
<add> (modulesSource, moduleTemplate, { chunk }) => {
<ide> const source = new ConcatSource();
<ide> source.add(
<ide> `${
<ide> hotUpdateChunkTemplate.outputOptions.hotUpdateFunction
<del> }(${JSON.stringify(id)},`
<add> }(${JSON.stringify(chunk.id)},`
<ide> );
<ide> source.add(modulesSource);
<ide> source.add(")");
<ide><path>lib/webworker/WebWorkerChunkTemplatePlugin.js
<ide>
<ide> const { ConcatSource } = require("webpack-sources");
<ide>
<add>/** @typedef {import("../ChunkTemplate")} ChunkTemplate */
<add>
<ide> class WebWorkerChunkTemplatePlugin {
<add> /**
<add> * @param {ChunkTemplate} chunkTemplate the chunk template
<add> * @returns {void}
<add> */
<ide> apply(chunkTemplate) {
<ide> chunkTemplate.hooks.render.tap(
<ide> "WebWorkerChunkTemplatePlugin",
<del> (modules, chunk) => {
<add> (modules, moduleTemplate, { chunk }) => {
<ide> const chunkCallbackName = chunkTemplate.outputOptions.chunkCallbackName;
<ide> const globalObject = chunkTemplate.outputOptions.globalObject;
<ide> const source = new ConcatSource();
<ide><path>lib/webworker/WebWorkerHotUpdateChunkTemplatePlugin.js
<ide>
<ide> const { ConcatSource } = require("webpack-sources");
<ide>
<add>/** @typedef {import("../HotUpdateChunkTemplate")} HotUpdateChunkTemplate */
<add>
<ide> class WebWorkerHotUpdateChunkTemplatePlugin {
<add> /**
<add> * @param {HotUpdateChunkTemplate} hotUpdateChunkTemplate the hot update chunk template
<add> * @returns {void}
<add> */
<ide> apply(hotUpdateChunkTemplate) {
<ide> hotUpdateChunkTemplate.hooks.render.tap(
<ide> "WebWorkerHotUpdateChunkTemplatePlugin",
<del> (modulesSource, modules, removedModules, hash, id) => {
<add> (modulesSource, moduleTemplate, { chunk }) => {
<ide> const hotUpdateFunction =
<ide> hotUpdateChunkTemplate.outputOptions.hotUpdateFunction;
<ide> const globalObject = hotUpdateChunkTemplate.outputOptions.globalObject;
<ide> const source = new ConcatSource();
<ide> source.add(
<ide> `${globalObject}[${JSON.stringify(
<ide> hotUpdateFunction
<del> )}](${JSON.stringify(id)},`
<add> )}](${JSON.stringify(chunk.id)},`
<ide> );
<ide> source.add(modulesSource);
<ide> source.add(")"); | 57 |
Ruby | Ruby | add missing install require | e43d400fd20256411851b3b58ef58b27c3d27cde | <ide><path>Library/Homebrew/cmd/gist-logs.rb
<ide> #: If no logs are found, an error message is presented.
<ide>
<ide> require "formula"
<add>require "install"
<ide> require "system_config"
<ide> require "stringio"
<ide> require "socket" | 1 |
PHP | PHP | fix cs error | 342230f85d1662d9014bf9724a23ce5ad93f27e1 | <ide><path>src/Event/EventManager.php
<ide> namespace Cake\Event;
<ide>
<ide> use Cake\Core\Exception\Exception;
<del>use InvalidArgumentException;
<ide>
<ide> /**
<ide> * The event manager is responsible for keeping track of event listeners, passing the correct | 1 |
Java | Java | support @ordering of conditions | 70b5f319a956d2d6a89ac316c51e566a93856468 | <ide><path>spring-context/src/main/java/org/springframework/context/annotation/ConditionEvaluator.java
<ide>
<ide> package org.springframework.context.annotation;
<ide>
<add>import java.util.ArrayList;
<ide> import java.util.Collections;
<ide> import java.util.List;
<ide>
<ide> import org.springframework.beans.factory.support.BeanDefinitionRegistry;
<ide> import org.springframework.context.ConfigurableApplicationContext;
<ide> import org.springframework.context.annotation.ConfigurationCondition.ConfigurationPhase;
<add>import org.springframework.core.annotation.AnnotationAwareOrderComparator;
<ide> import org.springframework.core.env.Environment;
<ide> import org.springframework.core.env.EnvironmentCapable;
<ide> import org.springframework.core.io.ResourceLoader;
<ide> public boolean shouldSkip(AnnotatedTypeMetadata metadata, ConfigurationPhase pha
<ide> return shouldSkip(metadata, ConfigurationPhase.REGISTER_BEAN);
<ide> }
<ide>
<add> List<Condition> conditions = new ArrayList<Condition>();
<ide> for (String[] conditionClasses : getConditionClasses(metadata)) {
<ide> for (String conditionClass : conditionClasses) {
<ide> Condition condition = getCondition(conditionClass, this.context.getClassLoader());
<del> ConfigurationPhase requiredPhase = null;
<del> if (condition instanceof ConfigurationCondition) {
<del> requiredPhase = ((ConfigurationCondition) condition).getConfigurationPhase();
<del> }
<del> if (requiredPhase == null || requiredPhase == phase) {
<del> if (!condition.matches(this.context, metadata)) {
<del> return true;
<del> }
<add> conditions.add(condition);
<add> }
<add> }
<add>
<add> Collections.sort(conditions, AnnotationAwareOrderComparator.INSTANCE);
<add>
<add> for (Condition condition : conditions) {
<add> ConfigurationPhase requiredPhase = null;
<add> if (condition instanceof ConfigurationCondition) {
<add> requiredPhase = ((ConfigurationCondition) condition).getConfigurationPhase();
<add> }
<add> if (requiredPhase == null || requiredPhase == phase) {
<add> if (!condition.matches(this.context, metadata)) {
<add> return true;
<ide> }
<ide> }
<ide> } | 1 |
Python | Python | fix typo in shape_base | e4630a2f5273307983b6ddca9b72aa0cf5a65784 | <ide><path>numpy/core/shape_base.py
<ide> def _accumulate(values):
<ide> def _concatenate_shapes(shapes, axis):
<ide> """Given array shapes, return the resulting shape and slices prefixes.
<ide>
<del> These help in nested concatation.
<add> These help in nested concatenation.
<add>
<ide> Returns
<ide> -------
<ide> shape: tuple of int | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.