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 |
|---|---|---|---|---|---|
Python | Python | test one to one with inheritance | de08f28a9185c09667eace53b637b1cb4529c695 | <ide><path>tests/test_one_to_one_with_inheritance.py
<add>from __future__ import unicode_literals
<add>
<add>from django.db import models
<add>from django.test import TestCase
<add>
<add>from rest_framework import serializers
<add>from tests.models import RESTFrameworkModel
<add>
<add>
<add># Models
<add>from tests.test_multitable_inheritance import ChildModel
<add>
<add>
<add># Regression test for #4290
<add>
<add>class ChildAssociatedModel(RESTFrameworkModel):
<add> child_model = models.OneToOneField(ChildModel)
<add> child_name = models.CharField(max_length=100)
<add>
<add>
<add># Serializers
<add>class DerivedModelSerializer(serializers.ModelSerializer):
<add> class Meta:
<add> model = ChildModel
<add> fields = ['id', 'name1', 'name2', 'childassociatedmodel']
<add>
<add>
<add>class ChildAssociatedModelSerializer(serializers.ModelSerializer):
<add>
<add> class Meta:
<add> model = ChildAssociatedModel
<add> fields = ['id', 'child_name']
<add>
<add>
<add># Tests
<add>class InheritedModelSerializationTests(TestCase):
<add>
<add> def test_multitable_inherited_model_fields_as_expected(self):
<add> """
<add> Assert that the parent pointer field is not included in the fields
<add> serialized fields
<add> """
<add> child = ChildModel(name1='parent name', name2='child name')
<add> serializer = DerivedModelSerializer(child)
<add> self.assertEqual(set(serializer.data.keys()),
<add> set(['name1', 'name2', 'id', 'childassociatedmodel'])) | 1 |
PHP | PHP | add typehint for translatebehavior | b1f50e5c14853406404406009e8fbcc0fe02dcd3 | <ide><path>src/Model/Behavior/TranslateBehavior.php
<ide> public function setupFieldAssociations($fields, $table) {
<ide> * @param \Cake\ORM\Query $query Query
<ide> * @return void
<ide> */
<del> public function beforeFind(Event $event, $query) {
<add> public function beforeFind(Event $event, Query $query) {
<ide> $locale = $this->locale();
<ide>
<ide> if ($locale === $this->config('defaultLocale')) { | 1 |
Python | Python | start arg parser | 8cedd5fbb813e8786ffd1182008672a743604f3f | <ide><path>glances/__init__.py
<ide> from .core.glances_core import GlancesCore
<ide>
<ide> def main(argv=None):
<del> print "!!! %s" % argv
<ide> glances_instance = GlancesCore()
<ide> glances_instance.start()
<ide><path>glances/core/glances_core.py
<ide> # You should have received a copy of the GNU Lesser General Public License
<ide> # along with this program. If not, see <http://www.gnu.org/licenses/>.
<ide>
<add>__appname__ = 'glances'
<add>__version__ = "2.0_Alpha"
<add>__author__ = "Nicolas Hennion <nicolas@nicolargo.com>"
<add>__license__ = "LGPL"
<add>
<add>import sys
<add>import os
<add>import gettext
<add>import locale
<add>import argparse
<add>import psutil
<add>
<add># path definitions
<add>work_path = os.path.realpath(os.path.dirname(__file__))
<add>appname_path = os.path.split(sys.argv[0])[0]
<add>sys_prefix = os.path.realpath(os.path.dirname(appname_path))
<add>
<add># i18n
<add>locale.setlocale(locale.LC_ALL, '')
<add>gettext_domain = __appname__
<add>
<add># get locale directory
<add>i18n_path = os.path.realpath(os.path.join(work_path, '..', 'i18n'))
<add>sys_i18n_path = os.path.join(sys_prefix, 'share', 'locale')
<add>
<add>if os.path.exists(i18n_path):
<add> locale_dir = i18n_path
<add>elif os.path.exists(sys_i18n_path):
<add> locale_dir = sys_i18n_path
<add>else:
<add> locale_dir = None
<add>gettext.install(gettext_domain, locale_dir)
<add>
<add>
<add># !!! To be deleted after 2.0 implementation
<add>def printSyntax():
<add> printVersion()
<add> print(_("Usage: glances [options]"))
<add> print(_("\nOptions:"))
<add> print(_("\t-b\t\tDisplay network rate in Byte per second"))
<add> print(_("\t-B @IP|HOST\tBind server to the given IPv4/IPv6 address or hostname"))
<add> print(_("\t-c @IP|HOST\tConnect to a Glances server by IPv4/IPv6 address or hostname"))
<add> print(_("\t-C FILE\t\tPath to the configuration file"))
<add> print(_("\t-d\t\tDisable disk I/O module"))
<add> print(_("\t-e\t\tEnable sensors module"))
<add> print(_("\t-f FILE\t\tSet the HTML output folder or CSV file"))
<add> print(_("\t-h\t\tDisplay the help and exit"))
<add> print(_("\t-m\t\tDisable mount module"))
<add> print(_("\t-n\t\tDisable network module"))
<add> print(_("\t-o OUTPUT\tDefine additional output (available: HTML or CSV)"))
<add> print(_("\t-p PORT\t\tDefine the client/server TCP port (default: %d)" %
<add> server_port))
<add> print(_("\t-P PASSWORD\tDefine a client/server password"))
<add> print(_("\t--password\tDefine a client/server password from the prompt"))
<add> print(_("\t-r\t\tDisable process list"))
<add> print(_("\t-s\t\tRun Glances in server mode"))
<add> print(_("\t-t SECONDS\tSet refresh time in seconds (default: %d sec)" %
<add> refresh_time))
<add> print(_("\t-v\t\tDisplay the version and exit"))
<add> print(_("\t-y\t\tEnable hddtemp module"))
<add> print(_("\t-z\t\tDo not use the bold color attribute"))
<add> print(_("\t-1\t\tStart Glances in per CPU mode"))
<add>
<add>
<ide> class GlancesCore(object):
<ide> """
<add> Main class to manage Glances instance
<ide> """
<ide>
<add> # Default stats' refresh time is 3 seconds
<add> refresh_time = 3
<add>
<add> def __init__(self):
<add> self.parser = argparse.ArgumentParser(
<add> prog=__appname__,
<add> description='Glances, an eye on your system.')
<add> self.init_arg()
<add>
<add> def init_arg(self):
<add> """
<add> Init all the command line argument
<add> """
<add>
<add> # Version
<add> # !!! Add Ps Util version
<add> self.parser.add_argument('-v', '--version',
<add> action='version',
<add> version='%s v%s' % (__appname__, __version__))
<add> # Refresh time
<add> self.parser.add_argument('-t', '--time',
<add> help='set refresh time in seconds (default: %s sec)' % self.refresh_time,
<add> type=int)
<add>
<add> def parse_arg(self):
<add> """
<add> Parse command line argument
<add> """
<add>
<add> args = self.parser.parse_args()
<add> if (args.time is not None):
<add> self.refresh_time = args.time
<add>
<add> # !!! Debug
<add> print "refresh_time: %s" % self.refresh_time
<add>
<ide> def start(self):
<del> print("Start Glances")
<add> """
<add> Start the instance
<add> It is the 'real' main function for Glances
<add> """
<add>
<add> self.parse_arg() | 2 |
Javascript | Javascript | avoid hardcoding platform on blacklist | e82a7a86494dad5fe77cb035060cbb361e5901d4 | <ide><path>local-cli/bundle/buildBundle.js
<ide> function buildBundle(args, config, output = outputBundle) {
<ide> const options = {
<ide> projectRoots: config.getProjectRoots(),
<ide> assetRoots: config.getAssetRoots(),
<del> blacklistRE: config.getBlacklistRE(),
<add> blacklistRE: config.getBlacklistRE(args.platform),
<ide> getTransformOptionsModulePath: config.getTransformOptionsModulePath,
<ide> transformModulePath: args.transformer,
<ide> verbose: args.verbose,
<ide><path>packager/rn-cli.config.js
<ide> module.exports = {
<ide> return this._getRoots();
<ide> },
<ide>
<del> getBlacklistRE() {
<del> return blacklist('');
<add> getBlacklistRE(platform) {
<add> return blacklist(platform);
<ide> },
<ide>
<ide> _getRoots() { | 2 |
Javascript | Javascript | extract loader.target from target option | eec6fbdd7ce1829ccf839a437371bbd700c498ae | <ide><path>lib/NormalModule.js
<ide> class NormalModule extends Module {
<ide> fs: fs
<ide> };
<ide>
<add> Object.assign(loaderContext, options.loader);
<add>
<ide> NormalModule.getCompilationHooks(compilation).loader.call(
<ide> loaderContext,
<ide> this
<ide> );
<ide>
<del> if (options.loader) {
<del> Object.assign(loaderContext, options.loader);
<del> }
<del>
<ide> return loaderContext;
<ide> }
<ide>
<ide><path>lib/WebpackOptionsApply.js
<ide> const AssetModulesPlugin = require("./asset/AssetModulesPlugin");
<ide> const JavascriptModulesPlugin = require("./javascript/JavascriptModulesPlugin");
<ide> const JsonModulesPlugin = require("./json/JsonModulesPlugin");
<ide>
<del>const LoaderTargetPlugin = require("./LoaderTargetPlugin");
<ide> const ChunkPrefetchPreloadPlugin = require("./prefetch/ChunkPrefetchPreloadPlugin");
<ide>
<ide> const EntryOptionPlugin = require("./EntryOptionPlugin");
<ide> class WebpackOptionsApply extends OptionsApply {
<ide> compiler.name = options.name;
<ide> if (typeof options.target === "string") {
<ide> switch (options.target) {
<del> case "web": {
<del> const NodeSourcePlugin = require("./node/NodeSourcePlugin");
<del> new NodeSourcePlugin(options.node).apply(compiler);
<del> new LoaderTargetPlugin(options.target).apply(compiler);
<del> break;
<del> }
<add> case "web":
<ide> case "webworker": {
<ide> const NodeSourcePlugin = require("./node/NodeSourcePlugin");
<ide> new NodeSourcePlugin(options.node).apply(compiler);
<del> new LoaderTargetPlugin(options.target).apply(compiler);
<ide> break;
<ide> }
<del> case "node":
<del> case "async-node": {
<del> new LoaderTargetPlugin("node").apply(compiler);
<del> break;
<del> }
<del> case "node-webkit": {
<del> new LoaderTargetPlugin(options.target).apply(compiler);
<del> break;
<del> }
<del> case "electron-main": {
<del> new LoaderTargetPlugin(options.target).apply(compiler);
<del> break;
<del> }
<del> case "electron-renderer":
<del> case "electron-preload": {
<del> new LoaderTargetPlugin(options.target).apply(compiler);
<del> break;
<del> }
<del> default:
<del> throw new Error("Unsupported target '" + options.target + "'.");
<ide> }
<ide> } else {
<ide> options.target(compiler);
<ide><path>lib/config/defaults.js
<ide> const { cleverMerge } = require("../util/cleverMerge");
<ide> /** @typedef {import("../../declarations/WebpackOptions").Library} Library */
<ide> /** @typedef {import("../../declarations/WebpackOptions").LibraryName} LibraryName */
<ide> /** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */
<add>/** @typedef {import("../../declarations/WebpackOptions").Loader} Loader */
<ide> /** @typedef {import("../../declarations/WebpackOptions").Mode} Mode */
<ide> /** @typedef {import("../../declarations/WebpackOptions").ModuleOptions} ModuleOptions */
<ide> /** @typedef {import("../../declarations/WebpackOptions").Node} WebpackNode */
<ide> const applyWebpackOptionsDefaults = options => {
<ide>
<ide> applyExternalsPresetsDefaults(options.externalsPresets, { target });
<ide>
<add> applyLoaderDefaults(options.loader, { target });
<add>
<ide> F(options, "externalsType", () => {
<ide> const validExternalTypes = require("../../schemas/WebpackOptions.json")
<ide> .definitions.ExternalsType.enum;
<ide> const applyExternalsPresetsDefaults = (externalsPresets, { target }) => {
<ide> }
<ide> };
<ide>
<add>/**
<add> * @param {Loader} loader options
<add> * @param {Object} options options
<add> * @param {Target} options.target target
<add> * @returns {void}
<add> */
<add>const applyLoaderDefaults = (loader, { target }) => {
<add> F(loader, "target", () => {
<add> switch (target) {
<add> case "web":
<add> return "web";
<add> case "webworker":
<add> return "webworker";
<add> case "async-node":
<add> case "node":
<add> return "node";
<add> case "node-webkit":
<add> return "node-webkit";
<add> case "electron-main":
<add> return "electron-main";
<add> case "electron-preload":
<add> case "electron-renderer":
<add> return "electron-preload";
<add> }
<add> });
<add>};
<add>
<ide> /**
<ide> * @param {WebpackNode} node options
<ide> * @param {Object} options options
<ide><path>lib/config/normalization.js
<ide> const getNormalizedWebpackOptions = config => {
<ide> ...infrastructureLogging
<ide> })
<ide> ),
<del> loader: config.loader,
<add> loader: nestedConfig(config.loader, loader => ({ ...loader })),
<ide> mode: config.mode,
<ide> module: nestedConfig(config.module, module => ({
<ide> ...module,
<ide><path>test/Defaults.unittest.js
<ide> describe("Defaults", () => {
<ide> "debug": false,
<ide> "level": "info",
<ide> },
<del> "loader": undefined,
<add> "loader": Object {
<add> "target": "web",
<add> },
<ide> "mode": "none",
<ide> "module": Object {
<ide> "defaultRules": Array [
<ide> describe("Defaults", () => {
<ide> - "web": true,
<ide> + "node": true,
<ide>
<add> - "target": "web",
<add> + "target": "node",
<add>
<ide> - "__dirname": "mock",
<ide> - "__filename": "mock",
<ide> - "global": true,
<ide> describe("Defaults", () => {
<ide> - Expected
<ide> + Received
<ide>
<add>
<add> - "target": "web",
<add> + "target": "webworker",
<ide>
<ide> - "chunkLoading": "jsonp",
<ide> + "chunkLoading": "import-scripts",
<ide> describe("Defaults", () => {
<ide> + "electronMain": true,
<ide> + "node": true,
<ide>
<add> - "target": "web",
<add> + "target": "electron-main",
<add>
<ide> - "__dirname": "mock",
<ide> - "__filename": "mock",
<ide> - "global": true,
<ide> describe("Defaults", () => {
<ide> + "electronPreload": true,
<ide> + "node": true,
<ide>
<add> - "target": "web",
<add> + "target": "electron-preload",
<add>
<ide> - "chunkFormat": "array-push",
<ide> + "chunkFormat": "commonjs",
<ide> | 5 |
Text | Text | fix typos in readme | 956c917344afc7286f92dbe351050a22c0b04a00 | <ide><path>README.md
<ide> Here is a detailed documentation of the classes in the package and how to use th
<ide>
<ide> ### Loading Google AI's pre-trained weigths and PyTorch dump
<ide>
<del>To load Google AI's pre-trained weight or a PyTorch saved instance of `BertForPreTraining`, the PyTorch model classes and the tokenizer can be instantiated as
<add>To load one of Google AI's pre-trained models or a PyTorch saved model (an instance of `BertForPreTraining` saved with `torch.save()`), the PyTorch model classes and the tokenizer can be instantiated as
<ide>
<ide> ```python
<ide> model = BERT_CLASS.from_pretrain(PRE_TRAINED_MODEL_NAME_OR_PATH)
<ide> where
<ide> - `bert-base-chinese`: Chinese Simplified and Traditional, 12-layer, 768-hidden, 12-heads, 110M parameters
<ide>
<ide> - a path or url to a pretrained model archive containing:
<del> . `bert_config.json` a configuration file for the model
<del> . `pytorch_model.bin` a PyTorch dump of a pre-trained instance `BertForPreTraining` (saved with the usual `torch.save()`)
<add>
<add> - `bert_config.json` a configuration file for the model, and
<add> - `pytorch_model.bin` a PyTorch dump of a pre-trained instance `BertForPreTraining` (saved with the usual `torch.save()`)
<ide>
<ide> If `PRE_TRAINED_MODEL_NAME` is a shortcut name, the pre-trained weights will be downloaded from AWS S3 (see the links [here](pytorch_pretrained_bert/modeling.py)) and stored in a cache folder to avoid future download (the cache folder can be found at `~/.pytorch_pretrained_bert/`).
<ide>
<ide> Please refer to the doc strings and code in [`tokenization.py`](./pytorch_pretra
<ide> The optimizer accepts the following arguments:
<ide>
<ide> - `lr` : learning rate
<del>- `warmup` : portion of t_total for the warmup, -1 means no warmup. Default : -1
<add>- `warmup` : portion of `t_total` for the warmup, `-1` means no warmup. Default : `-1`
<ide> - `t_total` : total number of training steps for the learning
<del> rate schedule, -1 means constant learning rate. Default : -1
<del>- `schedule` : schedule to use for the warmup (see above). Default : 'warmup_linear'
<del>- `b1` : Adams b1. Default : 0.9
<del>- `b2` : Adams b2. Default : 0.999
<del>- `e` : Adams epsilon. Default : 1e-6
<del>- `weight_decay_rate:` Weight decay. Default : 0.01
<del>- `max_grad_norm` : Maximum norm for the gradients (-1 means no clipping). Default : 1.0
<add> rate schedule, `-1` means constant learning rate. Default : `-1`
<add>- `schedule` : schedule to use for the warmup (see above). Default : `'warmup_linear'`
<add>- `b1` : Adams b1. Default : `0.9`
<add>- `b2` : Adams b2. Default : `0.999`
<add>- `e` : Adams epsilon. Default : `1e-6`
<add>- `weight_decay_rate:` Weight decay. Default : `0.01`
<add>- `max_grad_norm` : Maximum norm for the gradients (`-1` means no clipping). Default : `1.0`
<ide>
<ide> ## Examples
<ide>
<ide> The results were similar to the above FP32 results (actually slightly higher):
<ide>
<ide> ## Notebooks
<ide>
<del>Comparing the PyTorch model and the TensorFlow model predictions
<del>
<del>We also include [three Jupyter Notebooks](https://github.com/huggingface/pytorch-pretrained-BERT/tree/master/notebooks) that can be used to check that the predictions of the PyTorch model are identical to the predictions of the original TensorFlow model.
<add>We include [three Jupyter Notebooks](https://github.com/huggingface/pytorch-pretrained-BERT/tree/master/notebooks) that can be used to check that the predictions of the PyTorch model are identical to the predictions of the original TensorFlow model.
<ide>
<ide> - The first NoteBook ([Comparing-TF-and-PT-models.ipynb](./notebooks/Comparing-TF-and-PT-models.ipynb)) extracts the hidden states of a full sequence on each layers of the TensorFlow and the PyTorch models and computes the standard deviation between them. In the given example, we get a standard deviation of 1.5e-7 to 9e-7 on the various hidden state of the models.
<ide>
<ide> - The second NoteBook ([Comparing-TF-and-PT-models-SQuAD.ipynb](./notebooks/Comparing-TF-and-PT-models-SQuAD.ipynb)) compares the loss computed by the TensorFlow and the PyTorch models for identical initialization of the fine-tuning layer of the `BertForQuestionAnswering` and computes the standard deviation between them. In the given example, we get a standard deviation of 2.5e-7 between the models.
<ide>
<del>- The third NoteBook ([Comparing-TF-and-PT-models-MLM-NSP.ipynb](./notebooks/Comparing-TF-and-PT-models-MLM-NSP.ipynb)) compares the predictions computed by the TensorFlow and the PyTorch models for masked token using the pre-trained masked language modeling model.
<add>- The third NoteBook ([Comparing-TF-and-PT-models-MLM-NSP.ipynb](./notebooks/Comparing-TF-and-PT-models-MLM-NSP.ipynb)) compares the predictions computed by the TensorFlow and the PyTorch models for masked token language modeling using the pre-trained masked language modeling model.
<ide>
<ide> Please follow the instructions given in the notebooks to run and modify them.
<ide>
<ide> ## Command-line interface
<ide>
<del>A command-line interface is provided to convert a TensorFlow checkpoint in a PyTorch checkpoint
<add>A command-line interface is provided to convert a TensorFlow checkpoint in a PyTorch dump of the `BertForPreTraining` class (see above).
<ide>
<ide> You can convert any TensorFlow checkpoint for BERT (in particular [the pre-trained models released by Google](https://github.com/google-research/bert#pre-trained-models)) in a PyTorch save file by using the [`convert_tf_checkpoint_to_pytorch.py`](convert_tf_checkpoint_to_pytorch.py) script.
<ide> | 1 |
PHP | PHP | accept a string or array of views | a07bd96a101034a6944e3a58dc50d9936a20e2f9 | <ide><path>src/Illuminate/Contracts/Routing/ResponseFactory.php
<ide> public function noContent($status = 204, array $headers = []);
<ide> /**
<ide> * Create a new response for a given view.
<ide> *
<del> * @param string $view
<add> * @param string|array $view
<ide> * @param array $data
<ide> * @param int $status
<ide> * @param array $headers | 1 |
Ruby | Ruby | use implicit begin | b2ff6e934bad87aaa4a8f4f7d3bc66fa87e8e72b | <ide><path>Library/Homebrew/utils.rb
<ide> def nostdout
<ide>
<ide> module GitHub extend self
<ide> def open url, headers={}, &block
<del> begin
<del> default_headers = {'User-Agent' => HOMEBREW_USER_AGENT}
<del> default_headers['Authorization'] = "token #{HOMEBREW_GITHUB_API_TOKEN}" if HOMEBREW_GITHUB_API_TOKEN
<del> Kernel.open(url, default_headers.merge(headers), &block)
<del> rescue OpenURI::HTTPError => e
<del> if e.io.meta['x-ratelimit-remaining'].to_i <= 0
<del> raise "GitHub #{MultiJson.decode(e.io.read)['message']}"
<del> else
<del> raise e
<del> end
<add> default_headers = {'User-Agent' => HOMEBREW_USER_AGENT}
<add> default_headers['Authorization'] = "token #{HOMEBREW_GITHUB_API_TOKEN}" if HOMEBREW_GITHUB_API_TOKEN
<add> Kernel.open(url, default_headers.merge(headers), &block)
<add> rescue OpenURI::HTTPError => e
<add> if e.io.meta['x-ratelimit-remaining'].to_i <= 0
<add> raise "GitHub #{MultiJson.decode(e.io.read)['message']}"
<add> else
<add> raise e
<ide> end
<ide> end
<ide> | 1 |
Javascript | Javascript | check crypto before requiring tls module | 7307839b559b13c242e9d5341201ec17f83f3eed | <ide><path>test/parallel/test-tls-session-cache.js
<ide>
<ide> 'use strict';
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const fixtures = require('../common/fixtures');
<ide> const assert = require('assert');
<ide> const tls = require('tls');
<ide> const { spawn } = require('child_process');
<ide> if (!common.opensslCli)
<ide> common.skip('node compiled without OpenSSL CLI.');
<ide>
<del>if (!common.hasCrypto)
<del> common.skip('missing crypto');
<ide>
<ide> doTest({ tickets: false }, function() {
<ide> doTest({ tickets: true }, function() { | 1 |
PHP | PHP | fix typehint template | 8ce9c834f9f9124af425c27795853efaa2c6aaad | <ide><path>src/Illuminate/Collections/Collection.php
<ide> public function diff($items)
<ide> * Get the items in the collection that are not present in the given items, using the callback.
<ide> *
<ide> * @param \Illuminate\Contracts\Support\Arrayable<array-key, TValue>|iterable<array-key, TValue> $items
<del> * @param callable(TValue): int $callback
<add> * @param callable(TValue, TValue): int $callback
<ide> * @return static
<ide> */
<ide> public function diffUsing($items, callable $callback)
<ide> public function diffAssoc($items)
<ide> * Get the items in the collection whose keys and values are not present in the given items, using the callback.
<ide> *
<ide> * @param \Illuminate\Contracts\Support\Arrayable<TKey, TValue>|iterable<TKey, TValue> $items
<del> * @param callable(TKey): int $callback
<add> * @param callable(TKey, TKey): int $callback
<ide> * @return static
<ide> */
<ide> public function diffAssocUsing($items, callable $callback)
<ide> public function diffKeys($items)
<ide> * Get the items in the collection whose keys are not present in the given items, using the callback.
<ide> *
<ide> * @param \Illuminate\Contracts\Support\Arrayable<TKey, TValue>|iterable<TKey, TValue> $items
<del> * @param callable(TKey): int $callback
<add> * @param callable(TKey, TKey): int $callback
<ide> * @return static
<ide> */
<ide> public function diffKeysUsing($items, callable $callback)
<ide> public function sortKeysDesc($options = SORT_REGULAR)
<ide> /**
<ide> * Sort the collection keys using a callback.
<ide> *
<del> * @param callable $callback
<add> * @param callable(TKey, TKey): int $callback
<ide> * @return static
<ide> */
<ide> public function sortKeysUsing(callable $callback)
<ide><path>src/Illuminate/Collections/Enumerable.php
<ide> public function diff($items);
<ide> * Get the items that are not present in the given items, using the callback.
<ide> *
<ide> * @param \Illuminate\Contracts\Support\Arrayable<array-key, TValue>|iterable<array-key, TValue> $items
<del> * @param callable(TValue): int $callback
<add> * @param callable(TValue, TValue): int $callback
<ide> * @return static
<ide> */
<ide> public function diffUsing($items, callable $callback);
<ide> public function diffAssoc($items);
<ide> * Get the items whose keys and values are not present in the given items, using the callback.
<ide> *
<ide> * @param \Illuminate\Contracts\Support\Arrayable<TKey, TValue>|iterable<TKey, TValue> $items
<del> * @param callable(TKey): int $callback
<add> * @param callable(TKey, TKey): int $callback
<ide> * @return static
<ide> */
<ide> public function diffAssocUsing($items, callable $callback);
<ide> public function diffKeys($items);
<ide> * Get the items whose keys are not present in the given items, using the callback.
<ide> *
<ide> * @param \Illuminate\Contracts\Support\Arrayable<TKey, TValue>|iterable<TKey, TValue> $items
<del> * @param callable(TKey): int $callback
<add> * @param callable(TKey, TKey): int $callback
<ide> * @return static
<ide> */
<ide> public function diffKeysUsing($items, callable $callback);
<ide> public function sortKeysDesc($options = SORT_REGULAR);
<ide> /**
<ide> * Sort the collection keys using a callback.
<ide> *
<del> * @param callable $callback
<add> * @param callable(TKey, TKey): int $callback
<ide> * @return static
<ide> */
<ide> public function sortKeysUsing(callable $callback);
<ide><path>src/Illuminate/Collections/LazyCollection.php
<ide> public function diff($items)
<ide> * Get the items that are not present in the given items, using the callback.
<ide> *
<ide> * @param \Illuminate\Contracts\Support\Arrayable<array-key, TValue>|iterable<array-key, TValue> $items
<del> * @param callable(TValue): int $callback
<add> * @param callable(TValue, TValue): int $callback
<ide> * @return static
<ide> */
<ide> public function diffUsing($items, callable $callback)
<ide> public function diffAssoc($items)
<ide> * Get the items whose keys and values are not present in the given items, using the callback.
<ide> *
<ide> * @param \Illuminate\Contracts\Support\Arrayable<TKey, TValue>|iterable<TKey, TValue> $items
<del> * @param callable(TKey): int $callback
<add> * @param callable(TKey, TKey): int $callback
<ide> * @return static
<ide> */
<ide> public function diffAssocUsing($items, callable $callback)
<ide> public function diffKeys($items)
<ide> * Get the items whose keys are not present in the given items, using the callback.
<ide> *
<ide> * @param \Illuminate\Contracts\Support\Arrayable<TKey, TValue>|iterable<TKey, TValue> $items
<del> * @param callable(TKey): int $callback
<add> * @param callable(TKey, TKey): int $callback
<ide> * @return static
<ide> */
<ide> public function diffKeysUsing($items, callable $callback)
<ide> public function sortKeysDesc($options = SORT_REGULAR)
<ide> /**
<ide> * Sort the collection keys using a callback.
<ide> *
<del> * @param callable $callback
<add> * @param callable(TKey, TKey): int $callback
<ide> * @return static
<ide> */
<ide> public function sortKeysUsing(callable $callback) | 3 |
Ruby | Ruby | stringify the incoming hash in flashhash | a668beffd64106a1e1fedb71cc25eaaa11baf0c1 | <ide><path>actionpack/lib/action_dispatch/middleware/flash.rb
<add>require 'active_support/core_ext/hash/keys'
<add>
<ide> module ActionDispatch
<ide> class Request < Rack::Request
<ide> # Access the contents of the flash. Use <tt>flash["notice"]</tt> to
<ide> def to_session_value
<ide>
<ide> def initialize(flashes = {}, discard = []) #:nodoc:
<ide> @discard = Set.new(stringify_array(discard))
<del> @flashes = flashes
<add> @flashes = flashes.stringify_keys
<ide> @now = nil
<ide> end
<ide> | 1 |
Javascript | Javascript | use writev instead of the hacky hot end | ec576235f1f4d7f5873cf3c0118b28c022740ffe | <ide><path>lib/_http_outgoing.js
<ide> var crlf_buf = new Buffer('\r\n');
<ide>
<ide>
<ide> OutgoingMessage.prototype.end = function(data, encoding) {
<add> if (data && typeof data !== 'string' && !Buffer.isBuffer(data)) {
<add> throw new TypeError('first argument must be a string or Buffer');
<add> }
<add>
<ide> if (this.finished) {
<ide> return false;
<ide> }
<ide> OutgoingMessage.prototype.end = function(data, encoding) {
<ide> data = false;
<ide> }
<ide>
<del> var ret;
<del>
<del> var hot = this._headerSent === false &&
<del> (data && data.length > 0) &&
<del> this.output.length === 0 &&
<del> this.connection &&
<del> this.connection.writable &&
<del> this.connection._httpMessage === this;
<del>
<del> // The benefits of the hot-path optimization below start to fall
<del> // off when the buffer size gets up near 128KB, because the cost
<del> // of the copy is more than the cost of the extra write() call.
<del> // Switch to the write/end method at that point. Heuristics and
<del> // magic numbers are awful, but slow http responses are worse.
<del> if (hot && Buffer.isBuffer(data) && data.length > 120 * 1024)
<del> hot = false;
<del>
<del> if (hot) {
<del> // Hot path. They're doing
<del> // res.writeHead();
<del> // res.end(blah);
<del> // HACKY.
<del>
<del> if (typeof data === 'string') {
<del> if (this.chunkedEncoding) {
<del> var l = Buffer.byteLength(data, encoding).toString(16);
<del> ret = this.connection.write(this._header + l + CRLF +
<del> data + '\r\n0\r\n' +
<del> this._trailer + '\r\n', encoding);
<del> } else {
<del> ret = this.connection.write(this._header + data, encoding);
<del> }
<del> } else if (Buffer.isBuffer(data)) {
<del> if (this.chunkedEncoding) {
<del> var chunk_size = data.length.toString(16);
<del>
<del> // Skip expensive Buffer.byteLength() calls; only ISO-8859-1 characters
<del> // are allowed in HTTP headers. Therefore:
<del> //
<del> // this._header.length == Buffer.byteLength(this._header.length)
<del> // this._trailer.length == Buffer.byteLength(this._trailer.length)
<del> //
<del> var header_len = this._header.length;
<del> var chunk_size_len = chunk_size.length;
<del> var data_len = data.length;
<del> var trailer_len = this._trailer.length;
<del>
<del> var len = header_len +
<del> chunk_size_len +
<del> 2 + // '\r\n'.length
<del> data_len +
<del> 5 + // '\r\n0\r\n'.length
<del> trailer_len +
<del> 2; // '\r\n'.length
<del>
<del> var buf = new Buffer(len);
<del> var off = 0;
<del>
<del> buf.write(this._header, off, header_len, 'ascii');
<del> off += header_len;
<del>
<del> buf.write(chunk_size, off, chunk_size_len, 'ascii');
<del> off += chunk_size_len;
<del>
<del> crlf_buf.copy(buf, off);
<del> off += 2;
<del>
<del> data.copy(buf, off);
<del> off += data_len;
<del>
<del> zero_chunk_buf.copy(buf, off);
<del> off += 5;
<del>
<del> if (trailer_len > 0) {
<del> buf.write(this._trailer, off, trailer_len, 'ascii');
<del> off += trailer_len;
<del> }
<del>
<del> crlf_buf.copy(buf, off);
<add> if (this.connection && data)
<add> this.connection.cork();
<ide>
<del> ret = this.connection.write(buf);
<del> } else {
<del> var header_len = this._header.length;
<del> var buf = new Buffer(header_len + data.length);
<del> buf.write(this._header, 0, header_len, 'ascii');
<del> data.copy(buf, header_len);
<del> ret = this.connection.write(buf);
<del> }
<del> } else {
<del> throw new TypeError('first argument must be a string or Buffer');
<del> }
<del> this._headerSent = true;
<del>
<del> } else if (data) {
<add> var ret;
<add> if (data) {
<ide> // Normal body write.
<ide> ret = this.write(data, encoding);
<ide> }
<ide>
<del> if (!hot) {
<del> if (this.chunkedEncoding) {
<del> ret = this._send('0\r\n' + this._trailer + '\r\n'); // Last chunk.
<del> } else {
<del> // Force a flush, HACK.
<del> ret = this._send('');
<del> }
<add> if (this.chunkedEncoding) {
<add> ret = this._send('0\r\n' + this._trailer + '\r\n'); // Last chunk.
<add> } else {
<add> // Force a flush, HACK.
<add> ret = this._send('');
<ide> }
<ide>
<add> if (this.connection && data)
<add> this.connection.uncork();
<add>
<ide> this.finished = true;
<ide>
<ide> // There is the first message on the outgoing queue, and we've sent | 1 |
PHP | PHP | revert some unnecessary changes | 3919621558e1635db4327c4b54cafa4f9cba9c82 | <ide><path>src/Illuminate/Database/Query/Builder.php
<ide> class Builder
<ide> '&', '|', '^', '<<', '>>',
<ide> 'rlike', 'regexp', 'not regexp',
<ide> '~', '~*', '!~', '!~*', 'similar to',
<del> 'not similar to',
<add> 'not similar to',
<ide> ];
<ide>
<ide> /**
<ide> protected function runSelect()
<ide> */
<ide> public function paginate($perPage = 15, $columns = ['*'], $pageName = 'page', $page = null)
<ide> {
<add> $page = $page ?: Paginator::resolveCurrentPage($pageName);
<add>
<ide> $total = $this->getCountForPagination($columns);
<ide>
<del> $this->forPage(
<del> $page = $page ?: Paginator::resolveCurrentPage($pageName),
<del> $perPage
<del> );
<add> $results = $this->forPage($page, $perPage)->get($columns);
<ide>
<del> return new LengthAwarePaginator($this->get($columns), $total, $perPage, $page, [
<add> return new LengthAwarePaginator($results, $total, $perPage, $page, [
<ide> 'path' => Paginator::resolveCurrentPath(),
<ide> 'pageName' => $pageName,
<ide> ]); | 1 |
Javascript | Javascript | convert legacy process.binding to internalbinding | 04c839bd8c83eb497340bcd5a15f84a1e6fe473a | <ide><path>lib/internal/idna.js
<ide> 'use strict';
<ide>
<del>if (process.binding('config').hasIntl) {
<add>if (internalBinding('config').hasIntl) {
<ide> const { toASCII, toUnicode } = internalBinding('icu');
<ide> module.exports = { toASCII, toUnicode };
<ide> } else { | 1 |
Python | Python | prepare 2.2.0 release | 9a58f7b29026270afbec58c9255750b527ceff27 | <ide><path>keras/__init__.py
<ide> from .models import Model
<ide> from .models import Sequential
<ide>
<del>__version__ = '2.1.6'
<add>__version__ = '2.2.0'
<ide><path>setup.py
<ide> '''
<ide>
<ide> setup(name='Keras',
<del> version='2.1.6',
<add> version='2.2.0',
<ide> description='Deep Learning for humans',
<ide> long_description=long_description,
<ide> author='Francois Chollet',
<ide> author_email='francois.chollet@gmail.com',
<ide> url='https://github.com/keras-team/keras',
<del> download_url='https://github.com/keras-team/keras/tarball/2.1.6',
<add> download_url='https://github.com/keras-team/keras/tarball/2.2.0',
<ide> license='MIT',
<ide> install_requires=['numpy>=1.9.1',
<ide> 'scipy>=0.14', | 2 |
Ruby | Ruby | remove workaround for non-lazy serialize in tests | bc769581c20e5634debd18a9f6abfadb778e1ac6 | <ide><path>activerecord/test/cases/adapters/postgresql/hstore_test.rb
<ide> def test_update_all
<ide> assert_equal({ }, hstore.reload.tags)
<ide> end
<ide>
<del> # FIXME: remove this lambda once `serialize` no longer issues a db connection.
<del> LAZY_MODELS = lambda do
<del> return if defined?(TagCollection)
<del>
<del> class TagCollection
<del> def initialize(hash); @hash = hash end
<del> def to_hash; @hash end
<del> def self.load(hash); new(hash) end
<del> def self.dump(object); object.to_hash end
<del> end
<add> class TagCollection
<add> def initialize(hash); @hash = hash end
<add> def to_hash; @hash end
<add> def self.load(hash); new(hash) end
<add> def self.dump(object); object.to_hash end
<add> end
<ide>
<del> class HstoreWithSerialize < Hstore
<del> serialize :tags, TagCollection
<del> end
<add> class HstoreWithSerialize < Hstore
<add> serialize :tags, TagCollection
<ide> end
<ide>
<ide> def test_hstore_with_serialized_attributes
<del> LAZY_MODELS.call
<ide> HstoreWithSerialize.create! tags: TagCollection.new({"one" => "two"})
<ide> record = HstoreWithSerialize.first
<ide> assert_instance_of TagCollection, record.tags
<ide> def test_hstore_with_serialized_attributes
<ide> end
<ide>
<ide> def test_clone_hstore_with_serialized_attributes
<del> LAZY_MODELS.call
<ide> HstoreWithSerialize.create! tags: TagCollection.new({"one" => "two"})
<ide> record = HstoreWithSerialize.first
<ide> dupe = record.dup | 1 |
Ruby | Ruby | remove sentinel object | c4c72ad0bbceee2da817dd46d7c2274cb2460fe0 | <ide><path>actionpack/lib/action_dispatch/middleware/debug_exceptions.rb
<ide> def create_template(request, wrapper)
<ide> DebugView.new(
<ide> request: request,
<ide> exception_wrapper: wrapper,
<del> exception: BasicObject.new,
<add> # Everything should use the wrapper, but we need to pass
<add> # `exception` for legacy code.
<add> exception: wrapper.exception,
<ide> traces: wrapper.traces,
<ide> show_source_idx: wrapper.source_to_show_id,
<ide> trace_to_show: wrapper.trace_to_show, | 1 |
Javascript | Javascript | improve error message for circular reexports | 3f6450410af83be217c4f21c0a8ab1bc3e42add4 | <ide><path>lib/optimize/ConcatenatedModule.js
<ide> const getFinalName = (
<ide> moduleToInfoMap,
<ide> requestShortener,
<ide> asCall,
<del> strictHarmonyModule
<add> strictHarmonyModule,
<add> alreadyVisited = new Set()
<ide> ) => {
<ide> switch (info.type) {
<ide> case "concatenated": {
<ide> const getFinalName = (
<ide> }
<ide> const reexport = info.reexportMap.get(exportName);
<ide> if (reexport) {
<add> if (alreadyVisited.has(reexport)) {
<add> throw new Error(
<add> `Circular reexports ${Array.from(
<add> alreadyVisited,
<add> e =>
<add> `"${e.module.readableIdentifier(requestShortener)}".${
<add> e.exportName
<add> }`
<add> ).join(
<add> " --> "
<add> )} -(circular)-> "${reexport.module.readableIdentifier(
<add> requestShortener
<add> )}".${reexport.exportName}`
<add> );
<add> }
<add> alreadyVisited.add(reexport);
<ide> const refInfo = moduleToInfoMap.get(reexport.module);
<ide> if (refInfo) {
<ide> // module is in the concatenation
<ide> const getFinalName = (
<ide> moduleToInfoMap,
<ide> requestShortener,
<ide> asCall,
<del> strictHarmonyModule
<add> strictHarmonyModule,
<add> alreadyVisited
<ide> );
<ide> }
<ide> }
<ide><path>test/configCases/errors/self-reexport/a.js
<add>export { something } from "./a";
<ide><path>test/configCases/errors/self-reexport/aa.js
<add>import { something } from "./a";
<add>
<add>something();
<ide><path>test/configCases/errors/self-reexport/b.js
<add>
<add>import { something, other } from "./b";
<add>
<add>export {
<add> something as other,
<add> other as something
<add>}
<ide><path>test/configCases/errors/self-reexport/bb.js
<add>import {something} from "./b";
<add>
<add>something();
<ide><path>test/configCases/errors/self-reexport/c1.js
<add>export { something } from "./c2";
<ide><path>test/configCases/errors/self-reexport/c2.js
<add>export { something } from "./c1";
<ide><path>test/configCases/errors/self-reexport/cc.js
<add>import {something} from "./c1";
<add>
<add>something();
<ide><path>test/configCases/errors/self-reexport/errors.js
<add>module.exports = [
<add> [/Circular reexports "\.\/a.js"\.something -\(circular\)-> "\.\/a.js"\.something/],
<add> [/Circular reexports "\.\/b.js"\.other --> "\.\/b.js"\.something -\(circular\)-> "\.\/b.js"\.other/],
<add> [/Circular reexports "\.\/c2.js"\.something --> "\.\/c1.js"\.something -\(circular\)-> "\.\/c2.js"\.something/]
<add>];
<ide><path>test/configCases/errors/self-reexport/index.js
<add>it("should not crash on incorrect exports", function() {
<add> if(Math.random() < -1) {
<add> import(/* webpackChunkName: "a" */ "./aa");
<add> import(/* webpackChunkName: "b" */ "./bb");
<add> import(/* webpackChunkName: "c" */ "./cc");
<add> }
<add>});
<ide><path>test/configCases/errors/self-reexport/webpack.config.js
<add>module.exports = {
<add> mode: "production"
<add>}; | 11 |
Ruby | Ruby | add cask cleanup and per-formula cache cleanup | 78658e430259bc030389668d6f6aec9b8e1066b2 | <ide><path>Library/Homebrew/cask/lib/hbc/cask_loader.rb
<add>require "hbc/cask"
<ide> require "uri"
<ide>
<ide> module Hbc
<ide><path>Library/Homebrew/cleanup.rb
<ide> require "hbc/cask_loader"
<ide>
<ide> module CleanupRefinement
<add> LATEST_CASK_DAYS = 7
<add>
<ide> refine Pathname do
<ide> def incomplete?
<ide> extname.end_with?(".incomplete")
<ide> def prune?(days)
<ide> def stale?(scrub = false)
<ide> return false unless file?
<ide>
<del> stale_formula?(scrub)
<add> stale_formula?(scrub) || stale_cask?(scrub)
<ide> end
<ide>
<ide> private
<ide> def stale_formula?(scrub)
<ide> begin
<ide> Utils::Bottles.resolve_version(self)
<ide> rescue
<del> self.version
<add> nil
<ide> end
<del> else
<del> self.version
<ide> end
<ide>
<add> version ||= basename.to_s[/\A.*--(.*?)#{Regexp.escape(extname)}/, 1]
<add>
<ide> return false unless version
<add>
<add> version = Version.parse(version)
<add>
<ide> return false unless (name = basename.to_s[/\A(.*?)\-\-?(?:#{Regexp.escape(version)})/, 1])
<ide>
<ide> formula = begin
<ide> def stale_formula?(scrub)
<ide>
<ide> false
<ide> end
<add>
<add> def stale_cask?(scrub)
<add> return false unless name = basename.to_s[/\A(.*?)\-\-/, 1]
<add>
<add> cask = begin
<add> Hbc::CaskLoader.load(name)
<add> rescue Hbc::CaskUnavailableError
<add> return false
<add> end
<add>
<add> unless basename.to_s.match?(/\A#{Regexp.escape(name)}\-\-#{Regexp.escape(cask.version)}\b/)
<add> return true
<add> end
<add>
<add> return true if scrub && !cask.versions.include?(cask.version)
<add>
<add> if cask.version.latest?
<add> # TODO: Replace with ActiveSupport's `.days.ago`.
<add> return mtime < ((@time ||= Time.now) - LATEST_CASK_DAYS * 60 * 60 * 24)
<add> end
<add>
<add> false
<add> end
<ide> end
<ide> end
<ide>
<ide> def clean!
<ide> end
<ide> end
<ide>
<del> def update_disk_cleanup_size(path_size)
<del> @disk_cleanup_size += path_size
<del> end
<del>
<ide> def unremovable_kegs
<ide> @unremovable_kegs ||= []
<ide> end
<ide>
<ide> def cleanup_formula(formula)
<ide> formula.eligible_kegs_for_cleanup.each(&method(:cleanup_keg))
<add> cleanup_cache(Pathname.glob(cache/"#{formula.name}--*"))
<ide> end
<ide>
<del> def cleanup_cask(cask); end
<add> def cleanup_cask(cask)
<add> cleanup_cache(Pathname.glob(cache/"Cask/#{cask.token}--*"))
<add> end
<ide>
<ide> def cleanup_keg(keg)
<ide> cleanup_path(keg) { keg.uninstall }
<ide> def cleanup_logs
<ide> end
<ide> end
<ide>
<del> def cleanup_cache
<del> return unless cache.directory?
<del> cache.children.each do |path|
<add> def cleanup_cache(entries = nil)
<add> entries ||= [cache, cache/"Cask"].select(&:directory?).flat_map(&:children)
<add>
<add> entries.each do |path|
<ide> next cleanup_path(path) { path.unlink } if path.incomplete?
<ide> next cleanup_path(path) { FileUtils.rm_rf path } if path.nested_cache?
<ide>
<ide> def cleanup_cache
<ide> next
<ide> end
<ide>
<del> next cleanup_path(path) { path.unlink } if path.stale?(ARGV.switch?("s"))
<add> next cleanup_path(path) { path.unlink } if path.stale?(scrub?)
<ide> end
<ide> end
<ide>
<ide> def cleanup_path(path)
<ide> yield
<ide> end
<ide>
<del> update_disk_cleanup_size(disk_usage)
<add> @disk_cleanup_size += disk_usage
<ide> end
<ide>
<ide> def cleanup_lockfiles | 2 |
Java | Java | apply abortoncancel in jettyclienthttpconnector | 0cf5005a3d8bfe387ccc970c95953351fc83fbe5 | <ide><path>spring-web/src/main/java/org/springframework/http/client/reactive/JettyClientHttpConnector.java
<ide> public Mono<ClientHttpResponse> connect(HttpMethod method, URI uri,
<ide> Request request = this.httpClient.newRequest(uri).method(method.toString());
<ide>
<ide> return requestCallback.apply(new JettyClientHttpRequest(request, this.bufferFactory))
<del> .then(Mono.fromDirect(ReactiveRequest.newBuilder(request).build()
<add> .then(Mono.fromDirect(ReactiveRequest.newBuilder(request).abortOnCancel(true).build()
<ide> .response((reactiveResponse, chunkPublisher) -> {
<ide> Flux<DataBuffer> content = Flux.from(chunkPublisher).map(this::toDataBuffer);
<ide> return Mono.just(new JettyClientHttpResponse(reactiveResponse, content)); | 1 |
PHP | PHP | lower method directly | 8f2aeb345a4ce88f0515ae0bdef477d40380f17e | <ide><path>src/Illuminate/Support/Str.php
<ide> public static function slug($title, $separator = '-', $language = 'en')
<ide> $title = str_replace('@', $separator.'at'.$separator, $title);
<ide>
<ide> // Remove all characters that are not the separator, letters, numbers, or whitespace.
<del> $title = preg_replace('![^'.preg_quote($separator).'\pL\pN\s]+!u', '', mb_strtolower($title));
<add> $title = preg_replace('![^'.preg_quote($separator).'\pL\pN\s]+!u', '', static::lower($title));
<ide>
<ide> // Replace all separator characters and whitespace by a single separator
<ide> $title = preg_replace('!['.preg_quote($separator).'\s]+!u', $separator, $title); | 1 |
Go | Go | use ordered array instead of heap for sb.endpoints | 40923e73532e765763c00fec0a27d712b4d219e3 | <ide><path>libnetwork/controller.go
<ide> create network namespaces and allocate interfaces for containers to use.
<ide> package libnetwork
<ide>
<ide> import (
<del> "container/heap"
<ide> "fmt"
<ide> "net"
<ide> "path/filepath"
<ide> func (c *controller) NewSandbox(containerID string, options ...SandboxOption) (S
<ide> sb = &sandbox{
<ide> id: sandboxID,
<ide> containerID: containerID,
<del> endpoints: epHeap{},
<add> endpoints: []*endpoint{},
<ide> epPriority: map[string]int{},
<ide> populatedEndpoints: map[string]struct{}{},
<ide> config: containerConfig{},
<ide> func (c *controller) NewSandbox(containerID string, options ...SandboxOption) (S
<ide> }
<ide> }
<ide>
<del> heap.Init(&sb.endpoints)
<del>
<ide> sb.processOptions(options...)
<ide>
<ide> c.Lock()
<ide><path>libnetwork/endpoint.go
<ide> package libnetwork
<ide>
<ide> import (
<del> "container/heap"
<ide> "encoding/json"
<ide> "fmt"
<ide> "net"
<ide> func (ep *endpoint) sbJoin(sb *sandbox, options ...EndpointOption) (err error) {
<ide> // Current endpoint providing external connectivity for the sandbox
<ide> extEp := sb.getGatewayEndpoint()
<ide>
<del> sb.Lock()
<del> heap.Push(&sb.endpoints, ep)
<del> sb.Unlock()
<add> sb.addEndpoint(ep)
<ide> defer func() {
<ide> if err != nil {
<ide> sb.removeEndpoint(ep)
<ide><path>libnetwork/sandbox.go
<ide> package libnetwork
<ide>
<ide> import (
<del> "container/heap"
<ide> "encoding/json"
<ide> "fmt"
<ide> "net"
<add> "sort"
<ide> "strings"
<ide> "sync"
<ide> "time"
<ide> func (sb *sandbox) processOptions(options ...SandboxOption) {
<ide> }
<ide> }
<ide>
<del>type epHeap []*endpoint
<del>
<ide> type sandbox struct {
<ide> id string
<ide> containerID string
<ide> type sandbox struct {
<ide> resolver Resolver
<ide> resolverOnce sync.Once
<ide> refCnt int
<del> endpoints epHeap
<add> endpoints []*endpoint
<ide> epPriority map[string]int
<ide> populatedEndpoints map[string]struct{}
<ide> joinLeaveDone chan struct{}
<ide> func (sb *sandbox) getConnectedEndpoints() []*endpoint {
<ide> return eps
<ide> }
<ide>
<add>func (sb *sandbox) addEndpoint(ep *endpoint) {
<add> sb.Lock()
<add> defer sb.Unlock()
<add>
<add> l := len(sb.endpoints)
<add> i := sort.Search(l, func(j int) bool {
<add> return ep.Less(sb.endpoints[j])
<add> })
<add>
<add> sb.endpoints = append(sb.endpoints, nil)
<add> copy(sb.endpoints[i+1:], sb.endpoints[i:])
<add> sb.endpoints[i] = ep
<add>}
<add>
<ide> func (sb *sandbox) removeEndpoint(ep *endpoint) {
<ide> sb.Lock()
<ide> defer sb.Unlock()
<ide>
<add> sb.removeEndpointRaw(ep)
<add>}
<add>
<add>func (sb *sandbox) removeEndpointRaw(ep *endpoint) {
<ide> for i, e := range sb.endpoints {
<ide> if e == ep {
<del> heap.Remove(&sb.endpoints, i)
<add> sb.endpoints = append(sb.endpoints[:i], sb.endpoints[i+1:]...)
<ide> return
<ide> }
<ide> }
<ide> func (sb *sandbox) clearNetworkResources(origEp *endpoint) error {
<ide> return nil
<ide> }
<ide>
<del> heap.Remove(&sb.endpoints, index)
<add> sb.removeEndpointRaw(ep)
<ide> for _, e := range sb.endpoints {
<ide> if len(e.Gateway()) > 0 {
<ide> gwepAfter = e
<ide> func OptionIngress() SandboxOption {
<ide> }
<ide> }
<ide>
<del>func (eh epHeap) Len() int { return len(eh) }
<del>
<del>func (eh epHeap) Less(i, j int) bool {
<add>func (epi *endpoint) Less(epj *endpoint) bool {
<ide> var (
<ide> cip, cjp int
<ide> ok bool
<ide> )
<ide>
<del> ci, _ := eh[i].getSandbox()
<del> cj, _ := eh[j].getSandbox()
<del>
<del> epi := eh[i]
<del> epj := eh[j]
<add> ci, _ := epi.getSandbox()
<add> cj, _ := epj.getSandbox()
<ide>
<ide> if epi.endpointInGWNetwork() {
<ide> return false
<ide> func (eh epHeap) Less(i, j int) bool {
<ide> }
<ide>
<ide> if ci != nil {
<del> cip, ok = ci.epPriority[eh[i].ID()]
<add> cip, ok = ci.epPriority[epi.ID()]
<ide> if !ok {
<ide> cip = 0
<ide> }
<ide> }
<ide>
<ide> if cj != nil {
<del> cjp, ok = cj.epPriority[eh[j].ID()]
<add> cjp, ok = cj.epPriority[epj.ID()]
<ide> if !ok {
<ide> cjp = 0
<ide> }
<ide> }
<ide>
<ide> if cip == cjp {
<del> return eh[i].network.Name() < eh[j].network.Name()
<add> return epi.network.Name() < epj.network.Name()
<ide> }
<ide>
<ide> return cip > cjp
<ide> }
<ide>
<del>func (eh epHeap) Swap(i, j int) { eh[i], eh[j] = eh[j], eh[i] }
<del>
<del>func (eh *epHeap) Push(x interface{}) {
<del> *eh = append(*eh, x.(*endpoint))
<del>}
<del>
<del>func (eh *epHeap) Pop() interface{} {
<del> old := *eh
<del> n := len(old)
<del> x := old[n-1]
<del> *eh = old[0 : n-1]
<del> return x
<del>}
<del>
<ide> func (sb *sandbox) NdotsSet() bool {
<ide> return sb.ndotsSet
<ide> }
<ide><path>libnetwork/sandbox_store.go
<ide> package libnetwork
<ide>
<ide> import (
<del> "container/heap"
<ide> "encoding/json"
<ide> "sync"
<ide>
<ide> func (c *controller) sandboxCleanup(activeSandboxes map[string]interface{}) {
<ide> id: sbs.ID,
<ide> controller: sbs.c,
<ide> containerID: sbs.Cid,
<del> endpoints: epHeap{},
<add> endpoints: []*endpoint{},
<ide> populatedEndpoints: map[string]struct{}{},
<ide> dbIndex: sbs.dbIndex,
<ide> isStub: true,
<ide> func (c *controller) sandboxCleanup(activeSandboxes map[string]interface{}) {
<ide> sb.processOptions(opts...)
<ide> sb.restorePath()
<ide> create = !sb.config.useDefaultSandBox
<del> heap.Init(&sb.endpoints)
<ide> }
<ide> sb.osSbox, err = osl.NewSandbox(sb.Key(), create, isRestore)
<ide> if err != nil {
<ide> func (c *controller) sandboxCleanup(activeSandboxes map[string]interface{}) {
<ide> logrus.Errorf("failed to restore endpoint %s in %s for container %s due to %v", eps.Eid, eps.Nid, sb.ContainerID(), err)
<ide> continue
<ide> }
<del> heap.Push(&sb.endpoints, ep)
<add> sb.addEndpoint(ep)
<ide> }
<ide>
<ide> if _, ok := activeSandboxes[sb.ID()]; !ok { | 4 |
Python | Python | return path from the shelloutsshclient.put method | ea3500614aa3b735c36b663f0db807f35d126f0b | <ide><path>libcloud/compute/ssh.py
<ide> def put(self, path, contents=None, chmod=None, mode='w'):
<ide>
<ide> cmd = ['echo "%s" %s %s' % (contents, redirect, path)]
<ide> self._run_remote_shell_command(cmd)
<add> return path
<ide>
<ide> def delete(self, path):
<ide> cmd = ['rm', '-rf', path] | 1 |
PHP | PHP | implement typeinterface from type | 85de77e0a3dcebb21f4a70c3dff996784df42941 | <ide><path>src/Database/Type.php
<ide> * Encapsulates all conversion functions for values coming from database into PHP and
<ide> * going from PHP into database.
<ide> */
<del>class Type
<add>class Type implements TypeInterface
<ide> {
<ide>
<ide> /** | 1 |
Javascript | Javascript | remove return values from validation functions | 6c913fb0287fa7f823fcd0fbe7035bac3c4f75ec | <ide><path>lib/internal/crypto/scrypt.js
<ide> function check(password, salt, keylen, options) {
<ide>
<ide> password = validateArrayBufferView(password, 'password');
<ide> salt = validateArrayBufferView(salt, 'salt');
<del> keylen = validateUint32(keylen, 'keylen');
<add> validateUint32(keylen, 'keylen');
<ide>
<ide> let { N, r, p, maxmem } = defaults;
<ide> if (options && options !== defaults) {
<ide> let has_N, has_r, has_p;
<del> if (has_N = (options.N !== undefined))
<del> N = validateUint32(options.N, 'N');
<add> if (has_N = (options.N !== undefined)) {
<add> validateUint32(options.N, 'N');
<add> N = options.N;
<add> }
<ide> if (options.cost !== undefined) {
<ide> if (has_N) throw new ERR_CRYPTO_SCRYPT_INVALID_PARAMETER();
<del> N = validateUint32(options.cost, 'cost');
<add> validateUint32(options.cost, 'cost');
<add> N = options.cost;
<add> }
<add> if (has_r = (options.r !== undefined)) {
<add> validateUint32(options.r, 'r');
<add> r = options.r;
<ide> }
<del> if (has_r = (options.r !== undefined))
<del> r = validateUint32(options.r, 'r');
<ide> if (options.blockSize !== undefined) {
<ide> if (has_r) throw new ERR_CRYPTO_SCRYPT_INVALID_PARAMETER();
<del> r = validateUint32(options.blockSize, 'blockSize');
<add> validateUint32(options.blockSize, 'blockSize');
<add> r = options.blockSize;
<add> }
<add> if (has_p = (options.p !== undefined)) {
<add> validateUint32(options.p, 'p');
<add> p = options.p;
<ide> }
<del> if (has_p = (options.p !== undefined))
<del> p = validateUint32(options.p, 'p');
<ide> if (options.parallelization !== undefined) {
<ide> if (has_p) throw new ERR_CRYPTO_SCRYPT_INVALID_PARAMETER();
<del> p = validateUint32(options.parallelization, 'parallelization');
<add> validateUint32(options.parallelization, 'parallelization');
<add> p = options.parallelization;
<add> }
<add> if (options.maxmem !== undefined) {
<add> validateUint32(options.maxmem, 'maxmem');
<add> maxmem = options.maxmem;
<ide> }
<del> if (options.maxmem !== undefined)
<del> maxmem = validateUint32(options.maxmem, 'maxmem');
<ide> if (N === 0) N = defaults.N;
<ide> if (r === 0) r = defaults.r;
<ide> if (p === 0) p = defaults.p;
<ide><path>lib/internal/validators.js
<ide> const validateInteger = hideStackFrames((value, name) => {
<ide> throw new ERR_INVALID_ARG_TYPE(name, 'number', value);
<ide> if (!Number.isSafeInteger(value))
<ide> throw new ERR_OUT_OF_RANGE(name, 'an integer', value);
<del> return value;
<ide> });
<ide>
<ide> const validateInt32 = hideStackFrames(
<ide> const validateInt32 = hideStackFrames(
<ide> if (value < min || value > max) {
<ide> throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value);
<ide> }
<del> return value;
<ide> }
<ide> );
<ide>
<ide> const validateUint32 = hideStackFrames((value, name, positive) => {
<ide> if (positive && value === 0) {
<ide> throw new ERR_OUT_OF_RANGE(name, '>= 1 && < 4294967296', value);
<ide> }
<del> // TODO(BridgeAR): Remove return values from validation functions and
<del> // especially reduce side effects caused by validation functions.
<del> return value;
<ide> });
<ide>
<ide> function validateString(value, name) { | 2 |
Go | Go | use correct version for ptrace denial suppression | 284d9d451e93baff311b501018cae2097f76b134 | <ide><path>profiles/apparmor/template.go
<ide> profile {{.Name}} flags=(attach_disconnected,mediate_deleted) {
<ide> deny /sys/firmware/efi/efivars/** rwklx,
<ide> deny /sys/kernel/security/** rwklx,
<ide>
<del>{{if ge .Version 208000}}
<add>{{if ge .Version 208095}}
<ide> # suppress ptrace denials when using 'docker ps' or using 'ps' inside a container
<ide> ptrace (trace,read) peer=docker-default,
<ide> {{end}} | 1 |
Python | Python | add new option 'cfunc_alias' to umath generator | d084917e8f884f43ee172117fe516244ebe728b5 | <ide><path>numpy/core/code_generators/generate_umath.py
<ide> class TypeDescription:
<ide> astype : dict or None, optional
<ide> If astype['x'] is 'y', uses PyUFunc_x_x_As_y_y/PyUFunc_xx_x_As_yy_y
<ide> instead of PyUFunc_x_x/PyUFunc_xx_x.
<add> cfunc_alias : str or none, optional
<add> replaces the suffix of C function name instead of using ufunc_name,
<add> e.g. "FLOAT_{cfunc_alias}" instead of "FLOAT_{ufunc_name}" (see make_arrays)
<add> NOTE: it doesn't support 'astype'
<ide> simd: list
<ide> Available SIMD ufunc loops, dispatched at runtime in specified order
<ide> Currently only supported for simples types (see make_arrays)
<ide> dispatch: str or None, optional
<ide> Dispatch-able source name without its extension '.dispatch.c' that contains the definition of ufunc,
<ide> dispatched at runtime depending on the specified targets of the dispatch-able source.
<del> Currently only supported for simples types (see make_arrays)
<add> NOTE: it doesn't support 'astype'
<ide> """
<del> def __init__(self, type, f=None, in_=None, out=None, astype=None, simd=None, dispatch=None):
<add> def __init__(self, type, f=None, in_=None, out=None, astype=None, cfunc_alias=None, simd=None, dispatch=None):
<ide> self.type = type
<ide> self.func_data = f
<ide> if astype is None:
<ide> def __init__(self, type, f=None, in_=None, out=None, astype=None, simd=None, dis
<ide> if out is not None:
<ide> out = out.replace('P', type)
<ide> self.out = out
<add> self.cfunc_alias = cfunc_alias
<ide> self.simd = simd
<ide> self.dispatch = dispatch
<ide>
<ide> def build_func_data(types, f):
<ide> func_data = [_fdata_map.get(t, '%s') % (f,) for t in types]
<ide> return func_data
<ide>
<del>def TD(types, f=None, astype=None, in_=None, out=None, simd=None, dispatch=None):
<add>def TD(types, f=None, astype=None, in_=None, out=None, cfunc_alias=None, simd=None, dispatch=None):
<ide> if f is not None:
<ide> if isinstance(f, str):
<ide> func_data = build_func_data(types, f)
<ide> def TD(types, f=None, astype=None, in_=None, out=None, simd=None, dispatch=None)
<ide> else:
<ide> dispt = None
<ide> tds.append(TypeDescription(
<del> t, f=fd, in_=i, out=o, astype=astype, simd=simdt, dispatch=dispt
<add> t, f=fd, in_=i, out=o, astype=astype, cfunc_alias=cfunc_alias, simd=simdt, dispatch=dispt
<ide> ))
<ide> return tds
<ide>
<ide> def make_arrays(funcdict):
<ide> sub = 0
<ide>
<ide> for t in uf.type_descriptions:
<del>
<add> cfunc_alias = t.cfunc_alias if t.cfunc_alias else name
<add> cfunc_fname = None
<ide> if t.func_data is FullTypeDescr:
<ide> tname = english_upper(chartoname[t.type])
<ide> datalist.append('(void *)NULL')
<del> funclist.append(
<del> '%s_%s_%s_%s' % (tname, t.in_, t.out, name))
<add> cfunc_fname = f"{tname}_{t.in_}_{t.out}_{cfunc_alias}"
<ide> elif isinstance(t.func_data, FuncNameSuffix):
<ide> datalist.append('(void *)NULL')
<ide> tname = english_upper(chartoname[t.type])
<del> funclist.append(
<del> '%s_%s_%s' % (tname, name, t.func_data.suffix))
<add> cfunc_fname = f"{tname}_{cfunc_alias}_{t.func_data.suffix}"
<ide> elif t.func_data is None:
<ide> datalist.append('(void *)NULL')
<ide> tname = english_upper(chartoname[t.type])
<del> cfunc_name = f"{tname}_{name}"
<del> funclist.append(cfunc_name)
<add> cfunc_fname = f"{tname}_{cfunc_alias}"
<ide> if t.simd is not None:
<ide> for vt in t.simd:
<ide> code2list.append(textwrap.dedent("""\
<ide> #ifdef HAVE_ATTRIBUTE_TARGET_{ISA}
<ide> if (NPY_CPU_HAVE({ISA})) {{
<del> {fname}_functions[{idx}] = {type}_{fname}_{isa};
<add> {fname}_functions[{idx}] = {cname}_{isa};
<ide> }}
<ide> #endif
<ide> """).format(
<ide> ISA=vt.upper(), isa=vt,
<del> fname=name, type=tname, idx=k
<add> fname=name, cname=cfunc_fname, idx=k
<ide> ))
<del> if t.dispatch:
<del> dispdict.setdefault(t.dispatch, []).append((tname, k, cfunc_name))
<ide> else:
<del> funclist.append('NULL')
<ide> try:
<ide> thedict = arity_lookup[uf.nin, uf.nout]
<ide> except KeyError as e:
<ide> def make_arrays(funcdict):
<ide> #datalist.append('(void *)%s' % t.func_data)
<ide> sub += 1
<ide>
<add> if cfunc_fname:
<add> funclist.append(cfunc_fname)
<add> if t.dispatch:
<add> dispdict.setdefault(t.dispatch, []).append((name, k, cfunc_fname))
<add> else:
<add> funclist.append('NULL')
<add>
<ide> for x in t.in_ + t.out:
<ide> siglist.append('NPY_%s' % (english_upper(chartoname[x]),))
<ide> | 1 |
Javascript | Javascript | use custom elements on pane container element | d1f3d4e3bb598900149977647b77179c1e1a998d | <ide><path>src/panel-container-element.js
<ide> const { createFocusTrap } = require('focus-trap');
<ide> const { CompositeDisposable } = require('event-kit');
<ide>
<ide> class PanelContainerElement extends HTMLElement {
<del> createdCallback() {
<add> constructor() {
<add> super();
<ide> this.subscriptions = new CompositeDisposable();
<ide> }
<ide>
<del> attachedCallback() {
<add> connectedCallback() {
<ide> if (this.model.dock) {
<ide> this.model.dock.elementAttached();
<ide> }
<ide> class PanelContainerElement extends HTMLElement {
<ide> }
<ide> }
<ide>
<del>module.exports = document.registerElement('atom-panel-container', {
<del> prototype: PanelContainerElement.prototype
<del>});
<add>window.customElements.define('atom-panel-container', PanelContainerElement);
<add>
<add>function createPanelContainerElement() {
<add> return document.createElement('atom-panel-container');
<add>}
<add>
<add>module.exports = {
<add> createPanelContainerElement
<add>};
<ide><path>src/panel-container.js
<ide> 'use strict';
<ide>
<ide> const { Emitter, CompositeDisposable } = require('event-kit');
<del>const PanelContainerElement = require('./panel-container-element');
<add>const { createPanelContainerElement } = require('./panel-container-element');
<ide>
<ide> module.exports = class PanelContainer {
<ide> constructor({ location, dock, viewRegistry } = {}) {
<ide> module.exports = class PanelContainer {
<ide>
<ide> getElement() {
<ide> if (!this.element) {
<del> this.element = new PanelContainerElement().initialize(
<add> this.element = createPanelContainerElement().initialize(
<ide> this,
<ide> this.viewRegistry
<ide> ); | 2 |
Ruby | Ruby | improve long command output | 347c905a7f5967880c59582c7760e2ed23994ca3 | <ide><path>Library/Contributions/cmd/brew-test-bot.rb
<ide> def puts_command
<ide> end
<ide>
<ide> def puts_result
<del> puts "#{Tty.send status_colour}#{status_upcase}#{Tty.reset}"
<add> puts " #{Tty.send status_colour}#{status_upcase}#{Tty.reset}"
<ide> end
<ide>
<ide> def has_output? | 1 |
Javascript | Javascript | add type argument to module.size | cc34ea42b0844d531db587ca17a84ff6f0b03eee | <ide><path>lib/ContextModule.js
<ide> webpackEmptyAsyncContext.id = ${JSON.stringify(id)};`;
<ide> }
<ide>
<ide> /**
<add> * @param {string=} type the source type for which the size should be estimated
<ide> * @returns {number} the estimated size of the module
<ide> */
<del> size() {
<add> size(type) {
<ide> // base penalty
<ide> const initialSize = 160;
<ide>
<ide><path>lib/DelegatedModule.js
<ide> class DelegatedModule extends Module {
<ide> }
<ide>
<ide> /**
<add> * @param {string=} type the source type for which the size should be estimated
<ide> * @returns {number} the estimated size of the module
<ide> */
<del> size() {
<add> size(type) {
<ide> return 42;
<ide> }
<ide>
<ide><path>lib/DllModule.js
<ide> class DllModule extends Module {
<ide> }
<ide>
<ide> /**
<add> * @param {string=} type the source type for which the size should be estimated
<ide> * @returns {number} the estimated size of the module
<ide> */
<del> size() {
<add> size(type) {
<ide> return 12;
<ide> }
<ide>
<ide><path>lib/ExternalModule.js
<ide> class ExternalModule extends Module {
<ide> }
<ide>
<ide> /**
<add> * @param {string=} type the source type for which the size should be estimated
<ide> * @returns {number} the estimated size of the module
<ide> */
<del> size() {
<add> size(type) {
<ide> return 42;
<ide> }
<ide>
<ide><path>lib/Generator.js
<ide> class Generator {
<ide> throw new Error("Generator.getTypes: must be overridden");
<ide> }
<ide>
<add> /**
<add> * @abstract
<add> * @param {NormalModule} module the module
<add> * @param {string=} type source type
<add> * @returns {number} estimate size of the module
<add> */
<add> getSize(module, type) {
<add> throw new Error("Generator.getSize: must be overridden");
<add> }
<add>
<ide> /**
<ide> * @abstract
<ide> * @param {NormalModule} module module for which the code should be generated
<ide> class ByTypeGenerator extends Generator {
<ide> return this._types;
<ide> }
<ide>
<add> /**
<add> * @param {NormalModule} module the module
<add> * @param {string=} type source type
<add> * @returns {number} estimate size of the module
<add> */
<add> getSize(module, type) {
<add> const t = type || "javascript";
<add> const generator = this.map[t];
<add> return generator ? generator.getSize(module, t) : 0;
<add> }
<add>
<ide> /**
<ide> * @param {NormalModule} module module for which the code should be generated
<ide> * @param {GenerateContext} generateContext context for generate
<ide><path>lib/JavascriptGenerator.js
<ide> class JavascriptGenerator extends Generator {
<ide> return TYPES;
<ide> }
<ide>
<add> /**
<add> * @param {NormalModule} module the module
<add> * @param {string=} type source type
<add> * @returns {number} estimate size of the module
<add> */
<add> getSize(module, type) {
<add> const originalSource = module.originalSource();
<add> if (!originalSource) {
<add> return 39;
<add> }
<add> return originalSource.size();
<add> }
<add>
<ide> /**
<ide> * @param {NormalModule} module module for which the code should be generated
<ide> * @param {GenerateContext} generateContext context for generate
<ide><path>lib/JsonGenerator.js
<ide> class JsonGenerator extends Generator {
<ide> return TYPES;
<ide> }
<ide>
<add> /**
<add> * @param {NormalModule} module the module
<add> * @param {string=} type source type
<add> * @returns {number} estimate size of the module
<add> */
<add> getSize(module, type) {
<add> let data = module.buildInfo.jsonData;
<add> if (!data) return 0;
<add> return stringifySafe(data).length + 10;
<add> }
<add>
<ide> /**
<ide> * @param {NormalModule} module module for which the code should be generated
<ide> * @param {GenerateContext} generateContext context for generate
<ide><path>lib/Module.js
<ide> class Module extends DependenciesBlock {
<ide>
<ide> /**
<ide> * @abstract
<add> * @param {string=} type the source type for which the size should be estimated
<ide> * @returns {number} the estimated size of the module
<ide> */
<del> size() {
<add> size(type) {
<ide> throw new Error("Module.size: Must be overriden");
<ide> }
<ide>
<ide><path>lib/NormalModule.js
<ide> class NormalModule extends Module {
<ide> }
<ide>
<ide> /**
<add> * @param {string=} type the source type for which the size should be estimated
<ide> * @returns {number} the estimated size of the module
<ide> */
<del> size() {
<del> return this._source ? this._source.size() : -1;
<add> size(type) {
<add> return this.generator.getSize(this, type);
<ide> }
<ide>
<ide> /**
<ide><path>lib/RawModule.js
<ide> class RawModule extends Module {
<ide> }
<ide>
<ide> /**
<add> * @param {string=} type the source type for which the size should be estimated
<ide> * @returns {number} the estimated size of the module
<ide> */
<del> size() {
<add> size(type) {
<ide> return this.sourceStr.length;
<ide> }
<ide>
<ide><path>lib/RuntimeModule.js
<ide> class RuntimeModule extends Module {
<ide> }
<ide>
<ide> /**
<add> * @param {string=} type the source type for which the size should be estimated
<ide> * @returns {number} the estimated size of the module
<ide> */
<del> size() {
<add> size(type) {
<ide> return this.getGeneratedCode().length;
<ide> }
<ide>
<ide><path>lib/optimize/ConcatenatedModule.js
<ide> class ConcatenatedModule extends Module {
<ide> }
<ide>
<ide> /**
<add> * @param {string=} type the source type for which the size should be estimated
<ide> * @returns {number} the estimated size of the module
<ide> */
<del> size() {
<add> size(type) {
<ide> // Guess size from embedded modules
<ide> return this._orderedConcatenationList.reduce((sum, info) => {
<ide> switch (info.type) {
<ide> case "concatenated":
<del> return sum + info.module.size();
<add> return sum + info.module.size(type);
<ide> case "external":
<ide> return sum + 5;
<ide> }
<ide><path>lib/wasm/WebAssemblyGenerator.js
<ide> class WebAssemblyGenerator extends Generator {
<ide> return TYPES;
<ide> }
<ide>
<add> /**
<add> * @param {NormalModule} module the module
<add> * @param {string=} type source type
<add> * @returns {number} estimate size of the module
<add> */
<add> getSize(module, type) {
<add> const originalSource = module.originalSource();
<add> if (!originalSource) {
<add> return 0;
<add> }
<add> return originalSource.size();
<add> }
<add>
<ide> /**
<ide> * @param {NormalModule} module module for which the code should be generated
<ide> * @param {GenerateContext} generateContext context for generate
<ide><path>lib/wasm/WebAssemblyJavascriptGenerator.js
<ide> class WebAssemblyJavascriptGenerator extends Generator {
<ide> return TYPES;
<ide> }
<ide>
<add> /**
<add> * @param {NormalModule} module the module
<add> * @param {string=} type source type
<add> * @returns {number} estimate size of the module
<add> */
<add> getSize(module, type) {
<add> return 100 + module.dependencies.length * 5;
<add> }
<add>
<ide> /**
<ide> * @param {NormalModule} module module for which the code should be generated
<ide> * @param {GenerateContext} generateContext context for generate | 14 |
Text | Text | change the typo from ad to as | 972dbd5c27579ffc77c10acc6fec8170943cf1dd | <ide><path>curriculum/challenges/english/09-information-security/information-security-with-helmetjs/understand-bcrypt-hashes.md
<ide> BCrypt hashes will always looks like `$2a$13$ZyprE5MRw2Q3WpNOGZWGbeG7ADUre1Q8QO.
<ide>
<ide> Add all your code for these lessons in the `server.js` file between the code we have started you off with. Do not change or delete the code we have added for you.
<ide>
<del>BCrypt has already been added as a dependency, so require it ad `bcrypt` in your server.
<add>BCrypt has already been added as a dependency, so require it as `bcrypt` in your server.
<ide>
<ide> Submit your page when you think you've got it right.
<ide> | 1 |
Text | Text | fix some translations | 68bb39b9f2414189cffb124540e11c94d2d799ba | <ide><path>guide/spanish/algorithms/exponentiation/index.md
<ide> ---
<ide> title: Exponentiation
<del>localeTitle: Exposiciónción
<add>localeTitle: Potenciación
<ide> ---
<del>## Exposiciónción
<add>## Potenciación
<ide>
<ide> Dados dos enteros a y n, escribe una función para calcular a ^ n.
<ide>
<ide> int power(int x, unsigned int y) {
<ide> }
<ide> ```
<ide>
<del>## Exponentiación modular
<add>## modular
<ide>
<ide> Dados tres números x, yyp, calculamos (x ^ y)% p
<ide>
<ide> int power(int x, unsigned int y, int p) {
<ide> if (y & 1)
<ide> res = (res*x) % p;
<ide>
<del> // y must be even now
<add> // y debe ser par ahora
<ide> y = y>>1;
<ide> x = (x*x) % p;
<ide> }
<ide> return res;
<ide> }
<ide> ```
<ide>
<del>Complejidad del tiempo: O (Log y).
<ide>\ No newline at end of file
<add>Complejidad del tiempo: O (Log y). | 1 |
Javascript | Javascript | remove getterfn wrapper for internal use | b3b476db7d34bc2f8b099ab5b993b1e899b9cffd | <ide><path>src/ng/parse.js
<ide> function ensureSafeFunction(obj, fullExpression) {
<ide> }
<ide> }
<ide>
<add>//Keyword constants
<add>var CONSTANTS = createMap();
<add>forEach({
<add> 'null': function() { return null; },
<add> 'true': function() { return true; },
<add> 'false': function() { return false; },
<add> 'undefined': function() {}
<add>}, function(constantGetter, name) {
<add> constantGetter.constant = constantGetter.literal = constantGetter.sharedGetter = true;
<add> CONSTANTS[name] = constantGetter;
<add>});
<add>
<add>//Operators - will be wrapped by binaryFn/unaryFn/assignment/filter
<ide> var OPERATORS = extend(createMap(), {
<ide> /* jshint bitwise : false */
<del> 'null':function(){return null;},
<del> 'true':function(){return true;},
<del> 'false':function(){return false;},
<del> undefined:noop,
<ide> '+':function(self, locals, a,b){
<ide> a=a(self, locals); b=b(self, locals);
<ide> if (isDefined(a)) {
<ide> Lexer.prototype = {
<ide> }
<ide> }
<ide>
<del>
<del> var token = {
<add> this.tokens.push({
<ide> index: start,
<del> text: ident
<del> };
<del>
<del> var fn = OPERATORS[ident];
<del>
<del> if (fn) {
<del> token.fn = fn;
<del> token.constant = true;
<del> } else {
<del> var getter = getterFn(ident, this.options, expression);
<del> // TODO(perf): consider exposing the getter reference
<del> token.fn = extend(function $parsePathGetter(self, locals) {
<del> return getter(self, locals);
<del> }, {
<del> assign: function(self, value) {
<del> return setter(self, ident, value, expression);
<del> }
<del> });
<del> }
<del>
<del> this.tokens.push(token);
<add> text: ident,
<add> fn: CONSTANTS[ident] || getterFn(ident, this.options, expression)
<add> });
<ide>
<ide> if (methodName) {
<ide> this.tokens.push({
<ide> var Parser = function (lexer, $filter, options) {
<ide> Parser.ZERO = extend(function () {
<ide> return 0;
<ide> }, {
<add> sharedGetter: true,
<ide> constant: true
<ide> });
<ide>
<ide> function getterFn(path, options, fullExp) {
<ide> var evaledFnGetter = new Function('s', 'l', code); // s=scope, l=locals
<ide> /* jshint +W054 */
<ide> evaledFnGetter.toString = valueFn(code);
<add> evaledFnGetter.assign = function(self, value) {
<add> return setter(self, path, value, path);
<add> };
<add>
<ide> fn = evaledFnGetter;
<ide> }
<ide>
<add> fn.sharedGetter = true;
<ide> getterFnCache[path] = fn;
<ide> return fn;
<ide> }
<ide> function $ParseProvider() {
<ide> this.$get = ['$filter', '$sniffer', function($filter, $sniffer) {
<ide> $parseOptions.csp = $sniffer.csp;
<ide>
<add> function wrapSharedExpression(exp) {
<add> var wrapped = exp;
<add>
<add> if (exp.sharedGetter) {
<add> wrapped = function $parseWrapper(self, locals) {
<add> return exp(self, locals);
<add> };
<add> wrapped.literal = exp.literal;
<add> wrapped.constant = exp.constant;
<add> wrapped.assign = exp.assign;
<add> }
<add>
<add> return wrapped;
<add> }
<add>
<ide> return function $parse(exp, interceptorFn) {
<ide> var parsedExpression, oneTime, cacheKey;
<ide>
<ide> function $ParseProvider() {
<ide> if (parsedExpression.constant) {
<ide> parsedExpression.$$watchDelegate = constantWatchDelegate;
<ide> } else if (oneTime) {
<add> //oneTime is not part of the exp passed to the Parser so we may have to
<add> //wrap the parsedExpression before adding a $$watchDelegate
<add> parsedExpression = wrapSharedExpression(parsedExpression);
<ide> parsedExpression.$$watchDelegate = parsedExpression.literal ?
<ide> oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;
<ide> }
<ide><path>test/ng/parseSpec.js
<ide> describe('parser', function() {
<ide> scope.$eval('a.toString.constructor = 1', scope);
<ide> }).toThrowMinErr(
<ide> '$parse', 'isecfn', 'Referencing Function in Angular expressions is disallowed! ' +
<del> 'Expression: a.toString.constructor = 1');
<add> 'Expression: a.toString.constructor');
<ide> });
<ide>
<ide> it('should disallow traversing the Function object in a setter: E02', function() {
<ide> describe('parser', function() {
<ide> scope.$eval('hasOwnProperty.constructor.prototype.valueOf = 1');
<ide> }).toThrowMinErr(
<ide> '$parse', 'isecfn', 'Referencing Function in Angular expressions is disallowed! ' +
<del> 'Expression: hasOwnProperty.constructor.prototype.valueOf = 1');
<add> 'Expression: hasOwnProperty.constructor.prototype.valueOf');
<ide> });
<ide>
<ide> it('should disallow passing the Function object as a parameter: E03', function() { | 2 |
PHP | PHP | fix input() making multiple checkboxes | 086c88b8e5da3aa3442b9ea922ab82ba2acd2fed | <ide><path>src/View/Helper/FormHelper.php
<ide> protected function _getInput($fieldName, $options) {
<ide> $opts = $options['options'];
<ide> unset($options['options']);
<ide> return $this->radio($fieldName, $opts, $options);
<add> case 'multicheckbox':
<add> $opts = $options['options'];
<add> unset($options['options']);
<add> return $this->multicheckbox($fieldName, $opts, $options);
<ide> case 'url':
<ide> $options = $this->_initInputField($fieldName, $options);
<ide> return $this->widget($options['type'], $options);
<ide><path>tests/TestCase/View/Helper/FormHelperTest.php
<ide> public function testSelectCheckboxMultipleOverrideName() {
<ide> $this->assertHtml($expected, $result);
<ide> }
<ide>
<add>/**
<add> * Test that input() works with multicheckbox.
<add> *
<add> * @return void
<add> */
<add> public function testInputMultiCheckbox() {
<add> $result = $this->Form->input('category', [
<add> 'type' => 'multicheckbox',
<add> 'options' => ['1', '2'],
<add> ]);
<add> $expected = [
<add> ['div' => ['class' => 'input multicheckbox']],
<add> ['label' => ['for' => 'category']],
<add> 'Category',
<add> '/label',
<add> 'input' => ['type' => 'hidden', 'name' => 'category', 'value' => ''],
<add> ['div' => ['class' => 'checkbox']],
<add> ['label' => ['for' => 'category-0']],
<add> ['input' => ['type' => 'checkbox', 'name' => 'category[]', 'value' => '0', 'id' => 'category-0']],
<add> '1',
<add> '/label',
<add> '/div',
<add> ['div' => ['class' => 'checkbox']],
<add> ['label' => ['for' => 'category-1']],
<add> ['input' => ['type' => 'checkbox', 'name' => 'category[]', 'value' => '1', 'id' => 'category-1']],
<add> '2',
<add> '/label',
<add> '/div',
<add> '/div',
<add> ];
<add> $this->assertHtml($expected, $result);
<add> }
<add>
<ide> /**
<ide> * testCheckbox method
<ide> * | 2 |
Python | Python | fix mypy errors in airflow/operators | a5dfd63944cfad796e18bbd7a02f713971c27c94 | <ide><path>airflow/operators/bash.py
<ide> def __init__(
<ide> append_env: bool = False,
<ide> output_encoding: str = 'utf-8',
<ide> skip_exit_code: int = 99,
<del> cwd: str = None,
<add> cwd: Optional[str] = None,
<ide> **kwargs,
<ide> ) -> None:
<ide> super().__init__(**kwargs)
<ide><path>airflow/operators/trigger_dagrun.py
<ide> def execute(self, context: Dict):
<ide> else:
<ide> raise e
<ide>
<add> if not dag_run:
<add> raise AirflowException("Invalid DAG run")
<add>
<ide> # Store the execution date from the dag run (either created or found above) to
<ide> # be used when creating the extra link on the webserver.
<ide> ti = context['task_instance'] | 2 |
PHP | PHP | allow orm\table to slip through duplicate checks | a5674371fe351b549e6e1e3ec916b3a0d2d61a28 | <ide><path>src/Shell/Task/TestTask.php
<ide> protected function _processModel($subject) {
<ide> $assoc = $subject->association($alias);
<ide> $target = $assoc->target();
<ide> $name = $target->alias();
<add> $subjectClass = get_class($subject);
<ide>
<del> if (get_class($subject) === get_class($target)) {
<add> if ($subjectClass !== 'Cake\ORM\Table' && $subjectClass === get_class($target)) {
<ide> continue;
<ide> }
<ide>
<ide><path>src/Shell/Task/ViewTask.php
<ide> protected function _associations(Table $model) {
<ide> $assocName = $assoc->name();
<ide> $alias = $target->alias();
<ide>
<del> if (get_class($target) === get_class($model)) {
<add> $modelClass = get_class($model);
<add> if ($modelClass !== 'Cake\ORM\Table' && get_class($target) === $modelClass) {
<ide> continue;
<ide> }
<ide> | 2 |
Ruby | Ruby | reuse details cache key identity object | 6ccddadd847c2c3106867ca8085b51a82b449e14 | <ide><path>actionview/lib/action_view/lookup_context.rb
<ide> class DetailsKey #:nodoc:
<ide> @digest_cache = Concurrent::Map.new
<ide>
<ide> def self.digest_cache(details)
<del> if details[:formats]
<del> details = details.dup
<del> details[:formats] &= Template::Types.symbols
<del> end
<del> @digest_cache[details] ||= Concurrent::Map.new
<add> @digest_cache[details_cache_key(details)] ||= Concurrent::Map.new
<ide> end
<ide>
<ide> def self.details_cache_key(details) | 1 |
Python | Python | add test for find_default_import_path | 5eaed3711685f263d4a34af25b5976f04e6885f2 | <ide><path>tests/test_cli.py
<ide> from flask import Flask, current_app
<ide>
<ide> from flask.cli import AppGroup, FlaskGroup, NoAppException, ScriptInfo, \
<del> find_best_app, locate_app, with_appcontext, prepare_exec_for_file
<add> find_best_app, locate_app, with_appcontext, prepare_exec_for_file, \
<add> find_default_import_path
<ide>
<ide>
<ide> def test_cli_name(test_apps):
<ide> def test_locate_app(test_apps):
<ide> pytest.raises(RuntimeError, locate_app, "cliapp.app:notanapp")
<ide>
<ide>
<add>def test_find_default_import_path(test_apps, monkeypatch, tmpdir):
<add> """Test of find_default_import_path."""
<add> monkeypatch.delitem(os.environ, 'FLASK_APP', raising=False)
<add> assert find_default_import_path() == None
<add> monkeypatch.setitem(os.environ, 'FLASK_APP', 'notanapp')
<add> assert find_default_import_path() == 'notanapp'
<add> tmpfile = tmpdir.join('testapp.py')
<add> tmpfile.write('')
<add> monkeypatch.setitem(os.environ, 'FLASK_APP', str(tmpfile))
<add> expect_rv = prepare_exec_for_file(str(tmpfile))
<add> assert find_default_import_path() == expect_rv
<add>
<add>
<ide> def test_scriptinfo(test_apps):
<ide> """Test of ScriptInfo."""
<ide> obj = ScriptInfo(app_import_path="cliapp.app:testapp") | 1 |
Text | Text | update code conventions.md | 9738b69c0e3babb365cafaa26b872ca1028c9696 | <ide><path>extra/DEVELOPER_DOCS/Code Conventions.md
<ide> Regression tests are tests that refer to bugs reported in specific issues. They
<ide>
<ide> The test suite also provides [fixtures](https://github.com/explosion/spaCy/blob/master/spacy/tests/conftest.py) for different language tokenizers that can be used as function arguments of the same name and will be passed in automatically. Those should only be used for tests related to those specific languages. We also have [test utility functions](https://github.com/explosion/spaCy/blob/master/spacy/tests/util.py) for common operations, like creating a temporary file.
<ide>
<add>### Testing Cython Code
<add>
<add>If you're developing Cython code (`.pyx` files), those extensions will need to be built before the test runner can test that code - otherwise it's going to run the tests with stale code from the last time the extension was built. You can build the extensions locally with `python setup.py build_ext -i`.
<add>
<ide> ### Constructing objects and state
<ide>
<ide> Test functions usually follow the same simple structure: they set up some state, perform the operation you want to test and `assert` conditions that you expect to be true, usually before and after the operation. | 1 |
Mixed | Javascript | watch signals for recursive incompatibility | 67e067eb0658281b647ff68a5a9e64ea2cfdb706 | <ide><path>doc/api/errors.md
<ide> The `--entry-type=...` flag is not compatible with the Node.js REPL.
<ide> Used when an [ES Module][] loader hook specifies `format: 'dynamic'` but does
<ide> not provide a `dynamicInstantiate` hook.
<ide>
<add><a id="ERR_FEATURE_UNAVAILABLE_ON_PLATFORM"></a>
<add>#### `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM`
<add>
<add>Used when a feature that is not available
<add>to the current platform which is running Node.js is used.
<add>
<ide> <a id="ERR_STREAM_HAS_STRINGDECODER"></a>
<ide> #### `ERR_STREAM_HAS_STRINGDECODER`
<ide>
<ide><path>doc/api/fs.md
<ide> The `fs.watch` API is not 100% consistent across platforms, and is
<ide> unavailable in some situations.
<ide>
<ide> The recursive option is only supported on macOS and Windows.
<add>An `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM` exception will be thrown
<add>when the option is used on a platform that does not support it.
<ide>
<ide> #### Availability
<ide>
<ide><path>lib/fs.js
<ide> const {
<ide> ERR_FS_FILE_TOO_LARGE,
<ide> ERR_INVALID_ARG_VALUE,
<ide> ERR_INVALID_ARG_TYPE,
<del> ERR_INVALID_CALLBACK
<add> ERR_INVALID_CALLBACK,
<add> ERR_FEATURE_UNAVAILABLE_ON_PLATFORM
<ide> },
<ide> uvException
<ide> } = require('internal/errors');
<ide> let FileReadStream;
<ide> let FileWriteStream;
<ide>
<ide> const isWindows = process.platform === 'win32';
<add>const isOSX = process.platform === 'darwin';
<ide>
<ide>
<ide> function showTruncateDeprecation() {
<ide> function watch(filename, options, listener) {
<ide>
<ide> if (options.persistent === undefined) options.persistent = true;
<ide> if (options.recursive === undefined) options.recursive = false;
<del>
<add> if (options.recursive && !(isOSX || isWindows))
<add> throw new ERR_FEATURE_UNAVAILABLE_ON_PLATFORM('watch recursively');
<ide> if (!watchers)
<ide> watchers = require('internal/fs/watchers');
<ide> const watcher = new watchers.FSWatcher();
<ide><path>lib/internal/errors.js
<ide> E('ERR_FALSY_VALUE_REJECTION', function(reason) {
<ide> this.reason = reason;
<ide> return 'Promise was rejected with falsy value';
<ide> }, Error);
<add>E('ERR_FEATURE_UNAVAILABLE_ON_PLATFORM',
<add> 'The feature %s is unavailable on the current platform' +
<add> ', which is being used to run Node.js',
<add> TypeError);
<ide> E('ERR_FS_FILE_TOO_LARGE', 'File size (%s) is greater than 2 GB', RangeError);
<ide> E('ERR_FS_INVALID_SYMLINK_TYPE',
<ide> 'Symlink type must be one of "dir", "file", or "junction". Received "%s"',
<ide><path>test/parallel/test-fs-watch-recursive.js
<ide>
<ide> const common = require('../common');
<ide>
<del>if (!(common.isOSX || common.isWindows))
<del> common.skip('recursive option is darwin/windows specific');
<ide>
<ide> const assert = require('assert');
<ide> const path = require('path');
<ide> const testsubdir = fs.mkdtempSync(testDir + path.sep);
<ide> const relativePathOne = path.join(path.basename(testsubdir), filenameOne);
<ide> const filepathOne = path.join(testsubdir, filenameOne);
<ide>
<add>if (!common.isOSX && !common.isWindows) {
<add> assert.throws(() => { fs.watch(testDir, { recursive: true }); },
<add> { code: 'ERR_FEATURE_UNAVAILABLE_ON_PLATFORM' });
<add> return;
<add>}
<ide> const watcher = fs.watch(testDir, { recursive: true });
<ide>
<ide> let watcherClosed = false; | 5 |
Python | Python | improve the `numpy.linalg.eig` doctring. | 8bd5dddda46805928bba355a288815831c50c96c | <ide><path>numpy/linalg/linalg.py
<ide> def eig(a):
<ide> Hermitian (conjugate symmetric) array.
<ide> eigvalsh : eigenvalues of a real symmetric or complex Hermitian
<ide> (conjugate symmetric) array.
<del> scipy.linalg.eig : Similar function in SciPy (but also solves the
<del> generalized eigenvalue problem).
<add> scipy.linalg.eig : Similar function in SciPy that also solves the
<add> generalized eigenvalue problem.
<add> scipy.linalg.schur : Best choice for unitary and other non-Hermitian
<add> normal matrices.
<ide>
<ide> Notes
<ide> -----
<ide> def eig(a):
<ide> the eigenvalues and eigenvectors of general square arrays.
<ide>
<ide> The number `w` is an eigenvalue of `a` if there exists a vector
<del> `v` such that ``dot(a,v) = w * v``. Thus, the arrays `a`, `w`, and
<del> `v` satisfy the equations ``dot(a[:,:], v[:,i]) = w[i] * v[:,i]``
<add> `v` such that ``a @ v = w * v``. Thus, the arrays `a`, `w`, and
<add> `v` satisfy the equations ``a @ v[:,i] = w[i] * v[:,i]``
<ide> for :math:`i \\in \\{0,...,M-1\\}`.
<ide>
<ide> The array `v` of eigenvectors may not be of maximum rank, that is, some
<ide> of the columns may be linearly dependent, although round-off error may
<ide> obscure that fact. If the eigenvalues are all different, then theoretically
<del> the eigenvectors are linearly independent. Likewise, the (complex-valued)
<del> matrix of eigenvectors `v` is unitary if the matrix `a` is normal, i.e.,
<del> if ``dot(a, a.H) = dot(a.H, a)``, where `a.H` denotes the conjugate
<del> transpose of `a`.
<add> the eigenvectors are linearly independent and `a` can be diagonalized by
<add> a similarity transformation using `v`, i.e, ``inv(v) @ a @ v`` is diagonal.
<add>
<add> For non-Hermitian normal matrices the SciPy function `scipy.linalg.schur`
<add> is preferred because the matrix `v` is guaranteed to be unitary, which is
<add> not the case when using `eig`. The Schur factorization produces an
<add> upper triangular matrix rather than a diagonal matrix, but for normal
<add> matrices only the diagonal of the upper triangular matrix is needed, the
<add> rest is roundoff error.
<ide>
<ide> Finally, it is emphasized that `v` consists of the *right* (as in
<ide> right-hand side) eigenvectors of `a`. A vector `y` satisfying
<del> ``dot(y.T, a) = z * y.T`` for some number `z` is called a *left*
<add> ``y.T @ a = z * y.T`` for some number `z` is called a *left*
<ide> eigenvector of `a`, and, in general, the left and right eigenvectors
<ide> of a matrix are not necessarily the (perhaps conjugate) transposes
<ide> of each other. | 1 |
PHP | PHP | fix status code | ec88362ee06ad418db93eb0e19f6d285eed7e701 | <ide><path>src/Illuminate/Foundation/Exceptions/Handler.php
<ide> protected function convertValidationExceptionToResponse(ValidationException $e,
<ide>
<ide> if ($request->expectsJson()) {
<ide> return response()->json(
<del> $this->formatValidationResponse($e)
<add> $this->formatValidationResponse($e), 422
<ide> );
<ide> }
<ide> | 1 |
PHP | PHP | fix coding standard against code sniffer 2.5.0 | 55140a955b5c0048c43b2e559361a2399fed3a83 | <ide><path>src/Database/Query.php
<ide> public function select($fields = [], $overwrite = false)
<ide> * $query->distinct('name', true);
<ide> * ```
<ide> *
<del> * @param array|ExpressionInterface|string|boolean $on Enable/disable distinct class
<add> * @param array|ExpressionInterface|string|bool $on Enable/disable distinct class
<ide> * or list of fields to be filtered on
<ide> * @param bool $overwrite whether to reset fields with passed list or not
<ide> * @return $this
<ide><path>src/Routing/Route/DashedRoute.php
<ide> class DashedRoute extends Route
<ide> * @param string $plugin Plugin name
<ide> * @return string
<ide> */
<del> protected function _camelizePlugin($plugin) {
<add> protected function _camelizePlugin($plugin)
<add> {
<ide> $plugin = str_replace('-', '_', $plugin);
<ide> if (strpos($plugin, '/') === false) {
<ide> return Inflector::camelize($plugin);
<ide><path>src/Shell/Task/CommandTask.php
<ide> public function commands()
<ide> foreach ($shellList as $type => $commands) {
<ide> foreach ($commands as $shell) {
<ide> $prefix = '';
<del> if (
<del> !in_array(strtolower($type), ['app', 'core']) &&
<add> if (!in_array(strtolower($type), ['app', 'core']) &&
<ide> isset($duplicates[$type]) &&
<ide> in_array($shell, $duplicates[$type])
<ide> ) {
<ide><path>tests/TestCase/ORM/Association/HasManyTest.php
<ide> public function testEagerLoaderWithOverrides()
<ide> ];
<ide> $this->assertSelectClause($expected, $query);
<ide>
<del> $expected = new QueryExpression([
<add> $expected = new QueryExpression(
<add> [
<ide> 'Articles.published' => 'Y',
<ide> 'Articles.id !=' => 3,
<ide> 'Articles.author_id IN' => $keys
<ide> public function testEagerLoaderWithQueryBuilder()
<ide> ];
<ide> $this->assertJoin($expected, $query);
<ide>
<del> $expected = new QueryExpression([
<add> $expected = new QueryExpression(
<add> [
<ide> 'Articles.author_id IN' => $keys,
<ide> 'comments.id' => 1,
<ide> ],
<ide><path>tests/TestCase/Routing/Route/DashedRouteTest.php
<ide> public function testMatchThenParse()
<ide> 'controller' => 'ControllerName',
<ide> 'action' => 'actionName'
<ide> ]);
<del> $expected_url = '/plugin/controller-name/action-name';
<del> $this->assertEquals($expected_url, $url);
<del> $result = $route->parse($expected_url);
<add> $expectedUrl = '/plugin/controller-name/action-name';
<add> $this->assertEquals($expectedUrl, $url);
<add> $result = $route->parse($expectedUrl);
<ide> $this->assertEquals('ControllerName', $result['controller']);
<ide> $this->assertEquals('actionName', $result['action']);
<ide> $this->assertEquals('Vendor/PluginName', $result['plugin']);
<ide><path>tests/test_app/Plugin/TestPluginTwo/src/Shell/ExampleShell.php
<ide> public function main()
<ide> */
<ide> public function say_hello()
<ide> {
<del> $this->out('Hello from the TestPluginTwo.ExampleShell');
<add> $this->out('Hello from the TestPluginTwo.ExampleShell');
<ide> }
<ide> }
<ide><path>tests/test_app/TestApp/Shell/Task/SampleTask.php
<ide> public function getOptionParser()
<ide> ]);
<ide> return $parser;
<ide> }
<del>}
<ide>\ No newline at end of file
<add>} | 7 |
Python | Python | improve "repeat" in backends | de8a0133f01b4e9204eb81eb85ff4f9684aeb98f | <ide><path>keras/backend/tensorflow_backend.py
<ide> def repeat(x, n):
<ide> if x has shape (samples, dim) and n=2,
<ide> the output will have shape (samples, 2, dim)
<ide> '''
<add> assert x.ndim == 2
<ide> tensors = [x] * n
<ide> stacked = tf.pack(tensors)
<ide> return tf.transpose(stacked, (1, 0, 2))
<ide><path>keras/backend/theano_backend.py
<ide> def repeat(x, n):
<ide> If x has shape (samples, dim) and n=2,
<ide> the output will have shape (samples, 2, dim).
<ide> '''
<del> tensors = [x] * n
<del> stacked = T.stack(*tensors)
<del> return stacked.dimshuffle((1, 0, 2))
<add> assert x.ndim == 2
<add> x = x.dimshuffle((0, 'x', 1))
<add> return T.extra_ops.repeat(x, n, axis=1)
<ide>
<ide>
<ide> def tile(x, n):
<ide><path>keras/optimizers.py
<ide> def get_config(self):
<ide> "beta_2": float(K.get_value(self.beta_2)),
<ide> "epsilon": self.epsilon}
<ide>
<add>
<ide> class Adamax(Optimizer):
<ide> '''Adamax optimizer from Adam paper's Section 7. It is a variant
<ide> of Adam based on the infinity norm. | 3 |
Text | Text | show error 404 without partial failing | 59cb9e8a77629fcebbc959628c569179e389134f | <ide><path>CHANGELOG.md
<add><a name="1.2.26"></a>
<add># 1.2.26 zucchini-expansion (2014-10-01)
<add>
<add>
<add>## Bug Fixes
<add>
<add>- **$compile:** Resolve leak with asynchronous compilation
<add> ([5c9c1973](https://github.com/angular/angular.js/commit/5c9c19730526d5df6f16c523e578e5305f3796d0),
<add> [#9199](https://github.com/angular/angular.js/issues/9199), [#9079](https://github.com/angular/angular.js/issues/9079), [#8504](https://github.com/angular/angular.js/issues/8504), [#9197](https://github.com/angular/angular.js/issues/9197))
<add>- **select:** make ctrl.hasOption method consistent
<add> ([11d2242d](https://github.com/angular/angular.js/commit/11d2242df65b2ade0dabe366a0c42963b6d37df5),
<add> [#8761](https://github.com/angular/angular.js/issues/8761))
<add>
<add>
<ide> <a name="1.3.0-rc.3"></a>
<ide> # 1.3.0-rc.3 aggressive-pacification (2014-09-23)
<ide> | 1 |
Python | Python | hide program path in short process view | dae8db065c07bda49e608a4a91af3090ef3ad3e3 | <ide><path>glances/plugins/glances_processlist.py
<ide> def get_process_curses_data(self, p, first, args):
<ide> if cmdline == '':
<ide> msg = ' {0}'.format(p['name'])
<ide> ret.append(self.curse_add_line(msg, splittable=True))
<del> elif args.process_short_name:
<del> msg = ' {0}'.format(p['name'])
<del> ret.append(self.curse_add_line(msg, decoration='PROCESS', splittable=True))
<del> msg = ' {0}'.format(argument)
<del> ret.append(self.curse_add_line(msg, splittable=True))
<ide> else:
<ide> cmd = cmdline.split()[0]
<ide> path, basename = os.path.split(cmd)
<del> if os.path.isdir(path):
<add> if os.path.isdir(path) and not args.process_short_name:
<ide> msg = ' {0}'.format(path) + os.sep
<ide> ret.append(self.curse_add_line(msg, splittable=True))
<ide> ret.append(self.curse_add_line(basename, decoration='PROCESS', splittable=True)) | 1 |
PHP | PHP | implement empty options for datetime selects | e4121d27bce67663f020f6b0e0c0bcfb9d1ac931 | <ide><path>src/View/Input/DateTime.php
<ide> public function render(array $data) {
<ide> 'name' => 'data',
<ide> 'empty' => false,
<ide> 'disabled' => null,
<del> 'val' => new \DateTime(),
<add> 'val' => null,
<ide> 'year' => [],
<ide> 'month' => [
<ide> 'names' => false,
<ide> public function render(array $data) {
<ide> $method = $select . 'Select';
<ide> $data[$select]['name'] = $data['name'] . "[" . $select . "]";
<ide> $data[$select]['val'] = $selected[$select];
<del> $data[$select]['empty'] = $data['empty'];
<add>
<add> if (is_bool($data['empty'])) {
<add> $data[$select]['empty'] = $data['empty'];
<add> }
<add> if (isset($data['empty'][$select])) {
<add> $data[$select]['empty'] = $data['empty'][$select];
<add> }
<ide> $data[$select]['disabled'] = $data['disabled'];
<ide> $data[$select] += $data[$select];
<ide> $templateOptions[$select] = $this->{$method}($data[$select]);
<ide> public function render(array $data) {
<ide> * @return array
<ide> */
<ide> protected function _deconstuctDate($value) {
<add> if (empty($value)) {
<add> return [
<add> 'year' => '', 'month' => '', 'day' => '',
<add> 'hour' => '', 'minute' => '', 'second' => ''
<add> ];
<add> }
<ide> if (is_string($value)) {
<ide> $date = new \DateTime($value);
<ide> } elseif (is_int($value)) {
<ide><path>tests/TestCase/View/Input/DateTimeTest.php
<ide> public function testRenderSelected($selected) {
<ide> $this->assertContains('<option value="45" selected="selected">45</option>', $result);
<ide> }
<ide>
<add>/**
<add> * Test rendering widgets with empty values.
<add> *
<add> * @retun void
<add> */
<ide> public function testRenderEmptyValues() {
<del> $this->markTestIncomplete();
<add> $result = $this->DateTime->render([
<add> 'empty' => [
<add> 'year' => 'YEAR',
<add> 'month' => 'MONTH',
<add> 'day' => 'DAY',
<add> 'hour' => 'HOUR',
<add> 'minute' => 'MINUTE',
<add> 'second' => 'SECOND',
<add> 'meridian' => 'MERIDIAN',
<add> ]
<add> ]);
<add> $this->assertContains('<option value="" selected="selected">YEAR</option>', $result);
<add> $this->assertContains('<option value="" selected="selected">MONTH</option>', $result);
<add> $this->assertContains('<option value="" selected="selected">DAY</option>', $result);
<add> $this->assertContains('<option value="" selected="selected">HOUR</option>', $result);
<add> $this->assertContains('<option value="" selected="selected">MINUTE</option>', $result);
<add> $this->assertContains('<option value="" selected="selected">SECOND</option>', $result);
<ide> }
<ide>
<ide> public function testRenderYearWidget() {
<ide> public function testRenderMeridianWidget() {
<ide> $this->markTestIncomplete();
<ide> }
<ide>
<del>
<ide> /**
<ide> * testGenerateNumbers
<ide> * | 2 |
Ruby | Ruby | add autocorrect and tests for test checks | ca59377a90970a88b58aeda8cf74b8803931dcdc | <ide><path>Library/Homebrew/rubocops/class_cop.rb
<ide> def audit_formula(_node, _class_node, _parent_class_node, body_node)
<ide> end
<ide> end
<ide>
<add> def autocorrect(node)
<add> lambda do |corrector|
<add> case node.type
<add> when :str, :dstr
<add> corrector.replace(node.source_range, node.source.to_s.sub(%r{(/usr/local/(s?bin))}, '#{\2}'))
<add> when :int
<add> corrector.remove(range_with_surrounding_comma(range_with_surrounding_space(range: node.source_range, side: :left)))
<add> end
<add> end
<add> end
<add>
<ide> def_node_search :test_calls, <<~EOS
<ide> (send nil? ${:system :shell_output :pipe_output} $...)
<ide> EOS
<ide><path>Library/Homebrew/test/rubocops/class_cop_spec.rb
<ide> class Foo < Formula
<ide> end
<ide> RUBY
<ide> end
<add>
<add> it "supports auto-correcting test calls" do
<add> source = <<~RUBY
<add> class Foo < Formula
<add> url 'https://example.com/foo-1.0.tgz'
<add>
<add> test do
<add> shell_output("/usr/local/sbin/test", 0)
<add> end
<add> end
<add> RUBY
<add>
<add> corrected_source = <<~RUBY
<add> class Foo < Formula
<add> url 'https://example.com/foo-1.0.tgz'
<add>
<add> test do
<add> shell_output("\#{sbin}/test")
<add> end
<add> end
<add> RUBY
<add>
<add> new_source = autocorrect_source(source)
<add> expect(new_source).to eq(corrected_source)
<add> end
<ide> end
<ide>
<ide> describe RuboCop::Cop::FormulaAuditStrict::Test do | 2 |
Ruby | Ruby | fix more version misdetections for urls with archs | a9c4091de733e54cc73bab7e0fe0b729f5f6bde6 | <ide><path>Library/Homebrew/test/test_versions.rb
<ide> def test_win_style
<ide> def test_with_arch
<ide> assert_version_detected '4.0.18-1',
<ide> 'http://ftpmirror.gnu.org/mtools/mtools-4.0.18-1.i686.rpm'
<add> assert_version_detected '5.5.7-5',
<add> 'http://ftpmirror.gnu.org/autogen/autogen-5.5.7-5.i386.rpm'
<ide> assert_version_detected '2.8',
<ide> 'http://ftpmirror.gnu.org/libtasn1/libtasn1-2.8-x86.zip'
<add> assert_version_detected '2.8',
<add> 'http://ftpmirror.gnu.org/libtasn1/libtasn1-2.8-x64.zip'
<add> assert_version_detected '4.0.18',
<add> 'http://ftpmirror.gnu.org/mtools/mtools_4.0.18_i386.deb'
<ide> end
<ide> end
<ide><path>Library/Homebrew/version.rb
<ide> def self._parse spec
<ide> return m.captures.first.gsub('_', '.') unless m.nil?
<ide>
<ide> # e.g. foobar-4.5.1-1
<add> # e.g. unrtf_0.20.4-1
<ide> # e.g. ruby-1.9.1-p243
<del> m = /-((?:\d+\.)*\d\.\d+-(?:p|rc|RC)?\d+)(?:[-._](?:bin|dist|stable|src|sources))?$/.match(stem)
<add> m = /[-_]((?:\d+\.)*\d\.\d+-(?:p|rc|RC)?\d+)(?:[-._](?:bin|dist|stable|src|sources))?$/.match(stem)
<ide> return m.captures.first unless m.nil?
<ide>
<ide> # e.g. lame-398-1
<ide> def self._parse spec
<ide> return m.captures.first unless m.nil?
<ide>
<ide> # e.g. http://ftpmirror.gnu.org/mtools/mtools-4.0.18-1.i686.rpm
<add> # e.g. http://ftpmirror.gnu.org/autogen/autogen-5.5.7-5.i386.rpm
<ide> # e.g. http://ftpmirror.gnu.org/libtasn1/libtasn1-2.8-x86.zip
<del> m = /-(\d+\.\d+(?:\.\d+)?(?:-\d+)?)[-_.](?:i686|x86(?:[-_](?:32|64))?)$/.match(stem)
<add> # e.g. http://ftpmirror.gnu.org/libtasn1/libtasn1-2.8-x64.zip
<add> # e.g. http://ftpmirror.gnu.org/mtools/mtools_4.0.18_i386.deb
<add> m = /[-_](\d+\.\d+(?:\.\d+)?(?:-\d+)?)[-_.](?:i[36]86|x86|x64(?:[-_](?:32|64))?)$/.match(stem)
<ide> return m.captures.first unless m.nil?
<ide>
<ide> # e.g. foobar4.5.1 | 2 |
Java | Java | use softreferences for context caching in the tcf | 0cb22fc8f34a29c42313056671a947444b60050b | <ide><path>spring-test/src/main/java/org/springframework/test/context/ContextCache.java
<ide> import java.util.List;
<ide> import java.util.Map;
<ide> import java.util.Set;
<del>import java.util.concurrent.ConcurrentHashMap;
<ide> import java.util.concurrent.atomic.AtomicInteger;
<ide>
<ide> import org.springframework.context.ApplicationContext;
<ide> import org.springframework.context.ConfigurableApplicationContext;
<ide> import org.springframework.core.style.ToStringCreator;
<ide> import org.springframework.test.annotation.DirtiesContext.HierarchyMode;
<ide> import org.springframework.util.Assert;
<add>import org.springframework.util.ConcurrentReferenceHashMap;
<ide>
<ide> /**
<ide> * Cache for Spring {@link ApplicationContext ApplicationContexts} in a test
<ide> * environment.
<ide> *
<del> * <p>{@code ContextCache} maintains a cache of {@code ApplicationContexts}
<del> * keyed by {@link MergedContextConfiguration} instances.
<del> *
<add> * <h3>Rationale</h3>
<ide> * <p>Caching has significant performance benefits if initializing the context
<ide> * takes a considerable about of time. Although initializing a Spring context
<ide> * itself is very quick, some beans in a context, such as a
<ide> * {@code LocalSessionFactoryBean} for working with Hibernate, may take some
<ide> * time to initialize. Hence it often makes sense to perform that initialization
<ide> * only once per test suite.
<ide> *
<add> * <h3>Implementation Details</h3>
<add> * <p>{@code ContextCache} maintains a cache of {@code ApplicationContexts}
<add> * keyed by {@link MergedContextConfiguration} instances. Behind the scenes,
<add> * Spring's {@link ConcurrentReferenceHashMap} is used to store
<add> * {@linkplain java.lang.ref.SoftReference soft references} to cached contexts
<add> * and {@code MergedContextConfiguration} instances.
<add> *
<ide> * @author Sam Brannen
<ide> * @author Juergen Hoeller
<ide> * @since 2.5
<add> * @see ConcurrentReferenceHashMap
<ide> */
<ide> class ContextCache {
<ide>
<ide> /**
<ide> * Map of context keys to Spring {@code ApplicationContext} instances.
<ide> */
<ide> private final Map<MergedContextConfiguration, ApplicationContext> contextMap =
<del> new ConcurrentHashMap<MergedContextConfiguration, ApplicationContext>(64);
<add> new ConcurrentReferenceHashMap<MergedContextConfiguration, ApplicationContext>(64);
<ide>
<ide> /**
<ide> * Map of parent keys to sets of children keys, representing a top-down <em>tree</em>
<ide> class ContextCache {
<ide> * of other contexts.
<ide> */
<ide> private final Map<MergedContextConfiguration, Set<MergedContextConfiguration>> hierarchyMap =
<del> new ConcurrentHashMap<MergedContextConfiguration, Set<MergedContextConfiguration>>(64);
<add> new ConcurrentReferenceHashMap<MergedContextConfiguration, Set<MergedContextConfiguration>>(64);
<ide>
<ide> private final AtomicInteger hitCount = new AtomicInteger();
<ide> | 1 |
Go | Go | implement docker remove with standalone client lib | fb6533e6cf1793b653ab0ea9f12b6b6876076d97 | <ide><path>api/client/lib/container_remove.go
<add>package lib
<add>
<add>import "net/url"
<add>
<add>// ContainerRemoveOptions holds parameters to remove containers.
<add>type ContainerRemoveOptions struct {
<add> ContainerID string
<add> RemoveVolumes bool
<add> RemoveLinks bool
<add> Force bool
<add>}
<add>
<add>// ContainerRemove kills and removes a container from the docker host.
<add>func (cli *Client) ContainerRemove(options ContainerRemoveOptions) error {
<add> var query url.Values
<add> if options.RemoveVolumes {
<add> query.Set("v", "1")
<add> }
<add> if options.RemoveLinks {
<add> query.Set("link", "1")
<add> }
<add>
<add> if options.Force {
<add> query.Set("force", "1")
<add> }
<add>
<add> resp, err := cli.DELETE("/containers/"+options.ContainerID, query, nil)
<add> ensureReaderClosed(resp)
<add> return err
<add>}
<ide><path>api/client/rm.go
<ide> package client
<ide>
<ide> import (
<ide> "fmt"
<del> "net/url"
<ide> "strings"
<ide>
<add> "github.com/docker/docker/api/client/lib"
<ide> Cli "github.com/docker/docker/cli"
<ide> flag "github.com/docker/docker/pkg/mflag"
<ide> )
<ide> func (cli *DockerCli) CmdRm(args ...string) error {
<ide>
<ide> cmd.ParseFlags(args, true)
<ide>
<del> val := url.Values{}
<del> if *v {
<del> val.Set("v", "1")
<del> }
<del> if *link {
<del> val.Set("link", "1")
<del> }
<del>
<del> if *force {
<del> val.Set("force", "1")
<del> }
<del>
<ide> var errNames []string
<ide> for _, name := range cmd.Args() {
<ide> if name == "" {
<ide> return fmt.Errorf("Container name cannot be empty")
<ide> }
<ide> name = strings.Trim(name, "/")
<ide>
<del> _, _, err := readBody(cli.call("DELETE", "/containers/"+name+"?"+val.Encode(), nil, nil))
<del> if err != nil {
<add> options := lib.ContainerRemoveOptions{
<add> ContainerID: name,
<add> RemoveVolumes: *v,
<add> RemoveLinks: *link,
<add> Force: *force,
<add> }
<add>
<add> if err := cli.client.ContainerRemove(options); err != nil {
<ide> fmt.Fprintf(cli.err, "%s\n", err)
<ide> errNames = append(errNames, name)
<ide> } else { | 2 |
Ruby | Ruby | require the extensions to tests pass in isolation | f9433ef26023174c9dc079441eb7d388f0625f34 | <ide><path>activesupport/test/array_inquirer_test.rb
<ide> require 'abstract_unit'
<add>require 'active_support/core_ext/array'
<ide>
<ide> class ArrayInquirerTest < ActiveSupport::TestCase
<ide> def setup | 1 |
Go | Go | allow set_file_cap capability in container | 80319add5542153146fdaecd46be5549b4397beb | <ide><path>lxc_template.go
<ide> lxc.mount.entry = {{$realPath}} {{$ROOTFS}}/{{$virtualPath}} none bind,{{ if ind
<ide> # (Note: 'lxc.cap.keep' is coming soon and should replace this under the
<ide> # security principle 'deny all unless explicitly permitted', see
<ide> # http://sourceforge.net/mailarchive/message.php?msg_id=31054627 )
<del>lxc.cap.drop = audit_control audit_write mac_admin mac_override mknod setfcap setpcap sys_admin sys_boot sys_module sys_nice sys_pacct sys_rawio sys_resource sys_time sys_tty_config
<add>lxc.cap.drop = audit_control audit_write mac_admin mac_override mknod setpcap sys_admin sys_boot sys_module sys_nice sys_pacct sys_rawio sys_resource sys_time sys_tty_config
<ide> {{end}}
<ide>
<ide> # limits | 1 |
PHP | PHP | add check for valid output type | ce8bc83a2e184c84b33398fe86a3e2b07dcec789 | <ide><path>src/Console/ConsoleOutput.php
<ide> */
<ide> namespace Cake\Console;
<ide>
<add>use InvalidArgumentException;
<add>
<ide> /**
<ide> * Object wrapper for outputting information from a shell application.
<ide> * Can be connected to any stream resource that can be used with fopen()
<ide> public function getOutputAs()
<ide> *
<ide> * @param int $type The output type to use. Should be one of the class constants.
<ide> * @return void
<add> * @throws InvalidArgumentException in case of a not supported output type.
<ide> */
<ide> public function setOutputAs($type)
<ide> {
<add> if (in_array($type, [self::RAW, self::PLAIN, self::COLOR], true) === false) {
<add> throw new InvalidArgumentException(sprintf('Invalid output type "%s".', $type));
<add> }
<add>
<ide> $this->_outputAs = $type;
<ide> }
<ide>
<ide><path>tests/TestCase/Console/ConsoleOutputTest.php
<ide> public function testSetOutputAsPlain()
<ide> $this->output->write('<error>Bad</error> Regular', false);
<ide> }
<ide>
<add> /**
<add> * test set wrong type.
<add> *
<add> * @expectedException \InvalidArgumentException
<add> * @expectedExceptionMessage Invalid output type "Foo".
<add> */
<add> public function testSetOutputWrongType()
<add> {
<add> $this->output->setOutputAs('Foo');
<add> }
<add>
<ide> /**
<ide> * test plain output only strips tags used for formatting.
<ide> * | 2 |
Javascript | Javascript | update code style to arrow functions | f7c2f8e470d44686a2758c2debe59b86b3396c12 | <ide><path>lib/CachePlugin.js
<ide> class CachePlugin {
<ide> callback();
<ide> });
<ide> });
<del> compiler.plugin("after-compile", function(compilation, callback) {
<add> compiler.plugin("after-compile", (compilation, callback) => {
<ide> compilation.compiler._lastCompilationFileDependencies = compilation.fileDependencies;
<ide> compilation.compiler._lastCompilationContextDependencies = compilation.contextDependencies;
<ide> callback();
<ide><path>lib/Chunk.js
<ide> class Chunk {
<ide> const chunksProcessed = [];
<ide> const chunkHashMap = {};
<ide> const chunkNameMap = {};
<del> (function addChunk(chunk) {
<add> const addChunk = chunk => {
<ide> if(chunksProcessed.indexOf(chunk) >= 0) return;
<ide> chunksProcessed.push(chunk);
<ide> if(!chunk.hasRuntime() || includeEntries) {
<ide> class Chunk {
<ide> chunkNameMap[chunk.id] = chunk.name;
<ide> }
<ide> chunk._chunks.forEach(addChunk);
<del> }(this));
<add> };
<add> addChunk(this);
<ide> return {
<ide> hash: chunkHashMap,
<ide> name: chunkNameMap
<ide><path>lib/Compilation.js
<ide> const Stats = require("./Stats");
<ide> const Semaphore = require("./util/Semaphore");
<ide> const Queue = require("./util/Queue");
<ide>
<del>function byId(a, b) {
<add>const byId = (a, b) => {
<ide> if(a.id < b.id) return -1;
<ide> if(a.id > b.id) return 1;
<ide> return 0;
<del>}
<add>};
<ide>
<del>function iterationBlockVariable(variables, fn) {
<add>const iterationBlockVariable = (variables, fn) => {
<ide> for(let indexVariable = 0; indexVariable < variables.length; indexVariable++) {
<ide> let varDep = variables[indexVariable].dependencies;
<ide> for(let indexVDep = 0; indexVDep < varDep.length; indexVDep++) {
<ide> fn(varDep[indexVDep]);
<ide> }
<ide> }
<del>}
<add>};
<ide>
<del>function iterationOfArrayCallback(arr, fn) {
<add>const iterationOfArrayCallback = (arr, fn) => {
<ide> for(let index = 0; index < arr.length; index++) {
<ide> fn(arr[index]);
<ide> }
<del>}
<add>};
<ide>
<ide> class Compilation extends Tapable {
<ide> constructor(compiler) {
<ide> class Compilation extends Tapable {
<ide> processModuleDependencies(module, callback) {
<ide> const dependencies = [];
<ide>
<del> function addDependency(dep) {
<add> const addDependency = dep => {
<ide> for(let i = 0; i < dependencies.length; i++) {
<ide> if(dep.isEqualResource(dependencies[i][0])) {
<ide> return dependencies[i].push(dep);
<ide> }
<ide> }
<ide> dependencies.push([dep]);
<del> }
<add> };
<ide>
<del> function addDependenciesBlock(block) {
<add> const addDependenciesBlock = block => {
<ide> if(block.dependencies) {
<ide> iterationOfArrayCallback(block.dependencies, addDependency);
<ide> }
<ide> class Compilation extends Tapable {
<ide> if(block.variables) {
<ide> iterationBlockVariable(block.variables, addDependency);
<ide> }
<del> }
<add> };
<add>
<ide> addDependenciesBlock(module);
<ide> this.addModuleDependencies(module, dependencies, this.bail, null, true, callback);
<ide> }
<ide> class Compilation extends Tapable {
<ide> }
<ide> factories[i] = [factory, dependencies[i]];
<ide> }
<del> asyncLib.forEach(factories, function iteratorFactory(item, callback) {
<add> asyncLib.forEach(factories, (item, callback) => {
<ide> const dependencies = item[1];
<ide>
<del> const errorAndCallback = function errorAndCallback(err) {
<add> const errorAndCallback = err => {
<ide> err.origin = module;
<ide> _this.errors.push(err);
<ide> if(bail) {
<ide> class Compilation extends Tapable {
<ide> callback();
<ide> }
<ide> };
<del> const warningAndCallback = function warningAndCallback(err) {
<add> const warningAndCallback = err => {
<ide> err.origin = module;
<ide> _this.warnings.push(err);
<ide> callback();
<ide> class Compilation extends Tapable {
<ide> },
<ide> context: module.context,
<ide> dependencies: dependencies
<del> }, function factoryCallback(err, dependentModule) {
<add> }, (err, dependentModule) => {
<ide> if(_this === null) return semaphore.release();
<ide>
<ide> let afterFactory;
<ide>
<del> function isOptional() {
<add> const isOptional = () => {
<ide> return dependencies.every(d => d.optional);
<del> }
<add> };
<ide>
<del> function errorOrWarningAndCallback(err) {
<add> const errorOrWarningAndCallback = err => {
<ide> if(isOptional()) {
<ide> return warningAndCallback(err);
<ide> } else {
<ide> return errorAndCallback(err);
<ide> }
<del> }
<add> };
<ide>
<del> function iterationDependencies(depend) {
<add> const iterationDependencies = depend => {
<ide> for(let index = 0; index < depend.length; index++) {
<ide> const dep = depend[index];
<ide> dep.module = dependentModule;
<ide> dependentModule.addReason(module, dep);
<ide> }
<del> }
<add> };
<ide>
<ide> if(err) {
<ide> semaphore.release();
<ide> class Compilation extends Tapable {
<ide>
<ide> });
<ide> });
<del> }, function finalCallbackAddModuleDependencies(err) {
<add> }, err => {
<ide> // In V8, the Error objects keep a reference to the functions on the stack. These warnings &
<ide> // errors are created inside closures that keep a reference to the Compilation, so errors are
<ide> // leaking the Compilation object. Setting _this to null workarounds the following issue in V8.
<ide> class Compilation extends Tapable {
<ide> return;
<ide> }
<ide>
<add> const moduleReady = () => {
<add> this.semaphore.release();
<add> this.processModuleDependencies(module, err => {
<add> if(err) {
<add> return callback(err);
<add> }
<add>
<add> return callback(null, module);
<add> });
<add> };
<add>
<ide> if(result instanceof Module) {
<ide> if(this.profile) {
<ide> result.profile = module.profile;
<ide> class Compilation extends Tapable {
<ide> dependency.module = module;
<ide> module.addReason(null, dependency);
<ide>
<del> moduleReady.call(this);
<add> moduleReady();
<ide> return;
<ide> }
<ide>
<ide> class Compilation extends Tapable {
<ide> dependency.module = module;
<ide> module.addReason(null, dependency);
<ide>
<del> this.buildModule(module, false, null, null, (err) => {
<add> this.buildModule(module, false, null, null, err => {
<ide> if(err) {
<ide> this.semaphore.release();
<ide> return errorAndCallback(err);
<ide> class Compilation extends Tapable {
<ide> module.profile.building = afterBuilding - afterFactory;
<ide> }
<ide>
<del> moduleReady.call(this);
<add> moduleReady();
<ide> });
<del>
<del> function moduleReady() {
<del> this.semaphore.release();
<del> this.processModuleDependencies(module, err => {
<del> if(err) {
<del> return callback(err);
<del> }
<del>
<del> return callback(null, module);
<del> });
<del> }
<ide> });
<ide> });
<ide> }
<ide> class Compilation extends Tapable {
<ide> }
<ide>
<ide> seal(callback) {
<del> const self = this;
<del> self.applyPlugins0("seal");
<add> this.applyPlugins0("seal");
<ide>
<del> while(self.applyPluginsBailResult1("optimize-dependencies-basic", self.modules) ||
<del> self.applyPluginsBailResult1("optimize-dependencies", self.modules) ||
<del> self.applyPluginsBailResult1("optimize-dependencies-advanced", self.modules)) { /* empty */ }
<del> self.applyPlugins1("after-optimize-dependencies", self.modules);
<add> while(this.applyPluginsBailResult1("optimize-dependencies-basic", this.modules) ||
<add> this.applyPluginsBailResult1("optimize-dependencies", this.modules) ||
<add> this.applyPluginsBailResult1("optimize-dependencies-advanced", this.modules)) { /* empty */ }
<add> this.applyPlugins1("after-optimize-dependencies", this.modules);
<ide>
<del> self.nextFreeModuleIndex = 0;
<del> self.nextFreeModuleIndex2 = 0;
<del> self.preparedChunks.forEach(preparedChunk => {
<add> this.nextFreeModuleIndex = 0;
<add> this.nextFreeModuleIndex2 = 0;
<add> this.preparedChunks.forEach(preparedChunk => {
<ide> const module = preparedChunk.module;
<del> const chunk = self.addChunk(preparedChunk.name, module);
<del> const entrypoint = self.entrypoints[chunk.name] = new Entrypoint(chunk.name);
<add> const chunk = this.addChunk(preparedChunk.name, module);
<add> const entrypoint = this.entrypoints[chunk.name] = new Entrypoint(chunk.name);
<ide> entrypoint.unshiftChunk(chunk);
<ide>
<ide> chunk.addModule(module);
<ide> module.addChunk(chunk);
<ide> chunk.entryModule = module;
<del> self.assignIndex(module);
<del> self.assignDepth(module);
<add> this.assignIndex(module);
<add> this.assignDepth(module);
<ide> });
<del> self.processDependenciesBlocksForChunks(self.chunks.slice());
<del> self.sortModules(self.modules);
<del> self.applyPlugins0("optimize");
<add> this.processDependenciesBlocksForChunks(this.chunks.slice());
<add> this.sortModules(this.modules);
<add> this.applyPlugins0("optimize");
<ide>
<del> while(self.applyPluginsBailResult1("optimize-modules-basic", self.modules) ||
<del> self.applyPluginsBailResult1("optimize-modules", self.modules) ||
<del> self.applyPluginsBailResult1("optimize-modules-advanced", self.modules)) { /* empty */ }
<del> self.applyPlugins1("after-optimize-modules", self.modules);
<add> while(this.applyPluginsBailResult1("optimize-modules-basic", this.modules) ||
<add> this.applyPluginsBailResult1("optimize-modules", this.modules) ||
<add> this.applyPluginsBailResult1("optimize-modules-advanced", this.modules)) { /* empty */ }
<add> this.applyPlugins1("after-optimize-modules", this.modules);
<ide>
<del> while(self.applyPluginsBailResult1("optimize-chunks-basic", self.chunks) ||
<del> self.applyPluginsBailResult1("optimize-chunks", self.chunks) ||
<del> self.applyPluginsBailResult1("optimize-chunks-advanced", self.chunks)) { /* empty */ }
<del> self.applyPlugins1("after-optimize-chunks", self.chunks);
<add> while(this.applyPluginsBailResult1("optimize-chunks-basic", this.chunks) ||
<add> this.applyPluginsBailResult1("optimize-chunks", this.chunks) ||
<add> this.applyPluginsBailResult1("optimize-chunks-advanced", this.chunks)) { /* empty */ }
<add> this.applyPlugins1("after-optimize-chunks", this.chunks);
<ide>
<del> self.applyPluginsAsyncSeries("optimize-tree", self.chunks, self.modules, function sealPart2(err) {
<add> this.applyPluginsAsyncSeries("optimize-tree", this.chunks, this.modules, err => {
<ide> if(err) {
<ide> return callback(err);
<ide> }
<ide>
<del> self.applyPlugins2("after-optimize-tree", self.chunks, self.modules);
<add> this.applyPlugins2("after-optimize-tree", this.chunks, this.modules);
<ide>
<del> while(self.applyPluginsBailResult("optimize-chunk-modules-basic", self.chunks, self.modules) ||
<del> self.applyPluginsBailResult("optimize-chunk-modules", self.chunks, self.modules) ||
<del> self.applyPluginsBailResult("optimize-chunk-modules-advanced", self.chunks, self.modules)) { /* empty */ }
<del> self.applyPlugins2("after-optimize-chunk-modules", self.chunks, self.modules);
<add> while(this.applyPluginsBailResult("optimize-chunk-modules-basic", this.chunks, this.modules) ||
<add> this.applyPluginsBailResult("optimize-chunk-modules", this.chunks, this.modules) ||
<add> this.applyPluginsBailResult("optimize-chunk-modules-advanced", this.chunks, this.modules)) { /* empty */ }
<add> this.applyPlugins2("after-optimize-chunk-modules", this.chunks, this.modules);
<ide>
<del> const shouldRecord = self.applyPluginsBailResult("should-record") !== false;
<add> const shouldRecord = this.applyPluginsBailResult("should-record") !== false;
<ide>
<del> self.applyPlugins2("revive-modules", self.modules, self.records);
<del> self.applyPlugins1("optimize-module-order", self.modules);
<del> self.applyPlugins1("advanced-optimize-module-order", self.modules);
<del> self.applyPlugins1("before-module-ids", self.modules);
<del> self.applyPlugins1("module-ids", self.modules);
<del> self.applyModuleIds();
<del> self.applyPlugins1("optimize-module-ids", self.modules);
<del> self.applyPlugins1("after-optimize-module-ids", self.modules);
<add> this.applyPlugins2("revive-modules", this.modules, this.records);
<add> this.applyPlugins1("optimize-module-order", this.modules);
<add> this.applyPlugins1("advanced-optimize-module-order", this.modules);
<add> this.applyPlugins1("before-module-ids", this.modules);
<add> this.applyPlugins1("module-ids", this.modules);
<add> this.applyModuleIds();
<add> this.applyPlugins1("optimize-module-ids", this.modules);
<add> this.applyPlugins1("after-optimize-module-ids", this.modules);
<ide>
<del> self.sortItemsWithModuleIds();
<add> this.sortItemsWithModuleIds();
<ide>
<del> self.applyPlugins2("revive-chunks", self.chunks, self.records);
<del> self.applyPlugins1("optimize-chunk-order", self.chunks);
<del> self.applyPlugins1("before-chunk-ids", self.chunks);
<del> self.applyChunkIds();
<del> self.applyPlugins1("optimize-chunk-ids", self.chunks);
<del> self.applyPlugins1("after-optimize-chunk-ids", self.chunks);
<add> this.applyPlugins2("revive-chunks", this.chunks, this.records);
<add> this.applyPlugins1("optimize-chunk-order", this.chunks);
<add> this.applyPlugins1("before-chunk-ids", this.chunks);
<add> this.applyChunkIds();
<add> this.applyPlugins1("optimize-chunk-ids", this.chunks);
<add> this.applyPlugins1("after-optimize-chunk-ids", this.chunks);
<ide>
<del> self.sortItemsWithChunkIds();
<add> this.sortItemsWithChunkIds();
<ide>
<ide> if(shouldRecord)
<del> self.applyPlugins2("record-modules", self.modules, self.records);
<add> this.applyPlugins2("record-modules", this.modules, this.records);
<ide> if(shouldRecord)
<del> self.applyPlugins2("record-chunks", self.chunks, self.records);
<add> this.applyPlugins2("record-chunks", this.chunks, this.records);
<ide>
<del> self.applyPlugins0("before-hash");
<del> self.createHash();
<del> self.applyPlugins0("after-hash");
<add> this.applyPlugins0("before-hash");
<add> this.createHash();
<add> this.applyPlugins0("after-hash");
<ide>
<ide> if(shouldRecord)
<del> self.applyPlugins1("record-hash", self.records);
<add> this.applyPlugins1("record-hash", this.records);
<ide>
<del> self.applyPlugins0("before-module-assets");
<del> self.createModuleAssets();
<del> if(self.applyPluginsBailResult("should-generate-chunk-assets") !== false) {
<del> self.applyPlugins0("before-chunk-assets");
<del> self.createChunkAssets();
<add> this.applyPlugins0("before-module-assets");
<add> this.createModuleAssets();
<add> if(this.applyPluginsBailResult("should-generate-chunk-assets") !== false) {
<add> this.applyPlugins0("before-chunk-assets");
<add> this.createChunkAssets();
<ide> }
<del> self.applyPlugins1("additional-chunk-assets", self.chunks);
<del> self.summarizeDependencies();
<add> this.applyPlugins1("additional-chunk-assets", this.chunks);
<add> this.summarizeDependencies();
<ide> if(shouldRecord)
<del> self.applyPlugins2("record", self, self.records);
<add> this.applyPlugins2("record", this, this.records);
<ide>
<del> self.applyPluginsAsync("additional-assets", err => {
<add> this.applyPluginsAsync("additional-assets", err => {
<ide> if(err) {
<ide> return callback(err);
<ide> }
<del> self.applyPluginsAsync("optimize-chunk-assets", self.chunks, err => {
<add> this.applyPluginsAsync("optimize-chunk-assets", this.chunks, err => {
<ide> if(err) {
<ide> return callback(err);
<ide> }
<del> self.applyPlugins1("after-optimize-chunk-assets", self.chunks);
<del> self.applyPluginsAsync("optimize-assets", self.assets, err => {
<add> this.applyPlugins1("after-optimize-chunk-assets", this.chunks);
<add> this.applyPluginsAsync("optimize-assets", this.assets, err => {
<ide> if(err) {
<ide> return callback(err);
<ide> }
<del> self.applyPlugins1("after-optimize-assets", self.assets);
<del> if(self.applyPluginsBailResult("need-additional-seal")) {
<del> self.unseal();
<del> return self.seal(callback);
<add> this.applyPlugins1("after-optimize-assets", this.assets);
<add> if(this.applyPluginsBailResult("need-additional-seal")) {
<add> this.unseal();
<add> return this.seal(callback);
<ide> }
<del> return self.applyPluginsAsync("after-seal", callback);
<add> return this.applyPluginsAsync("after-seal", callback);
<ide> });
<ide> });
<ide> });
<ide> class Compilation extends Tapable {
<ide> assignIndex(module) {
<ide> const _this = this;
<ide>
<del> const queue = [() => {
<del> assignIndexToModule(module);
<del> }];
<del>
<del> const iteratorAllDependencies = d => {
<del> queue.push(() => assignIndexToDependency(d));
<del> };
<del>
<del> function assignIndexToModule(module) {
<add> const assignIndexToModule = module => {
<ide> // enter module
<ide> if(typeof module.index !== "number") {
<ide> module.index = _this.nextFreeModuleIndex++;
<ide> class Compilation extends Tapable {
<ide> // enter it as block
<ide> assignIndexToDependencyBlock(module);
<ide> }
<del> }
<add> };
<ide>
<del> function assignIndexToDependency(dependency) {
<add> const assignIndexToDependency = dependency => {
<ide> if(dependency.module) {
<ide> queue.push(() => assignIndexToModule(dependency.module));
<ide> }
<del> }
<add> };
<ide>
<del> function assignIndexToDependencyBlock(block) {
<add> const assignIndexToDependencyBlock = block => {
<ide> let allDependencies = [];
<ide>
<del> function iteratorDependency(d) {
<del> allDependencies.push(d);
<del> }
<add> const iteratorDependency = d => allDependencies.push(d);
<ide>
<del> function iteratorBlock(b) {
<del> queue.push(() => assignIndexToDependencyBlock(b));
<del> }
<add> const iteratorBlock = b => queue.push(() => assignIndexToDependencyBlock(b));
<ide>
<ide> if(block.variables) {
<ide> iterationBlockVariable(block.variables, iteratorDependency);
<ide> class Compilation extends Tapable {
<ide> while(indexAll--) {
<ide> iteratorAllDependencies(allDependencies[indexAll]);
<ide> }
<del> }
<add> };
<add>
<add> const queue = [() => {
<add> assignIndexToModule(module);
<add> }];
<add>
<add> const iteratorAllDependencies = d => {
<add> queue.push(() => assignIndexToDependency(d));
<add> };
<ide>
<ide> while(queue.length) {
<ide> queue.pop()();
<ide> }
<ide> }
<ide>
<ide> assignDepth(module) {
<del> function assignDepthToModule(module, depth) {
<add> const assignDepthToModule = (module, depth) => {
<ide> // enter module
<ide> if(typeof module.depth === "number" && module.depth <= depth) return;
<ide> module.depth = depth;
<ide>
<ide> // enter it as block
<ide> assignDepthToDependencyBlock(module, depth + 1);
<del> }
<add> };
<ide>
<del> function assignDepthToDependency(dependency, depth) {
<add> const assignDepthToDependency = (dependency, depth) => {
<ide> if(dependency.module) {
<ide> queue.push(() => assignDepthToModule(dependency.module, depth));
<ide> }
<del> }
<add> };
<ide>
<del> function assignDepthToDependencyBlock(block, depth) {
<del> function iteratorDependency(d) {
<del> assignDepthToDependency(d, depth);
<del> }
<add> const assignDepthToDependencyBlock = (block, depth) => {
<add> const iteratorDependency = d => assignDepthToDependency(d, depth);
<ide>
<del> function iteratorBlock(b) {
<del> assignDepthToDependencyBlock(b, depth);
<del> }
<add> const iteratorBlock = b => assignDepthToDependencyBlock(b, depth);
<ide>
<ide> if(block.variables) {
<ide> iterationBlockVariable(block.variables, iteratorDependency);
<ide> class Compilation extends Tapable {
<ide> if(block.blocks) {
<ide> iterationOfArrayCallback(block.blocks, iteratorBlock);
<ide> }
<del> }
<add> };
<ide>
<ide> const queue = [() => {
<ide> assignDepthToModule(module, 0);
<ide> }];
<add>
<ide> while(queue.length) {
<ide> queue.pop()();
<ide> }
<ide> class Compilation extends Tapable {
<ide> const unusedIds = [];
<ide> let nextFreeChunkId = 0;
<ide>
<del> function getNextFreeChunkId(usedChunkIds) {
<del> const keyChunks = Object.keys(usedChunkIds);
<del> let result = -1;
<add> if(this.usedChunkIds) {
<add>
<add> const keyChunks = Object.keys(this.usedChunkIds);
<ide>
<ide> for(let index = 0; index < keyChunks.length; index++) {
<ide> const usedIdKey = keyChunks[index];
<del> const usedIdValue = usedChunkIds[usedIdKey];
<add> const usedIdValue = this.usedChunkIds[usedIdKey];
<ide>
<ide> if(typeof usedIdValue !== "number") {
<ide> continue;
<ide> }
<ide>
<del> result = Math.max(result, usedIdValue);
<add> nextFreeChunkId = Math.max(nextFreeChunkId - 1, usedIdValue) + 1;
<ide> }
<ide>
<del> return result;
<del> }
<del>
<del> if(this.usedChunkIds) {
<del> nextFreeChunkId = getNextFreeChunkId(this.usedChunkIds) + 1;
<ide> let index = nextFreeChunkId;
<ide> while(index--) {
<ide> if(this.usedChunkIds[index] !== index) {
<ide> class Compilation extends Tapable {
<ide> }
<ide>
<ide> summarizeDependencies() {
<del> function filterDups(array) {
<add> const filterDups = array => {
<ide> const newArray = [];
<ide> for(let i = 0; i < array.length; i++) {
<ide> if(i === 0 || array[i - 1] !== array[i])
<ide> newArray.push(array[i]);
<ide> }
<ide> return newArray;
<del> }
<add> };
<ide> this.fileDependencies = (this.compilationDependencies || []).slice();
<ide> this.contextDependencies = [];
<ide> this.missingDependencies = [];
<ide> class Compilation extends Tapable {
<ide> this.mainTemplate.updateHash(hash);
<ide> this.chunkTemplate.updateHash(hash);
<ide> this.moduleTemplate.updateHash(hash);
<del> this.children.forEach(function(child) {
<del> hash.update(child.hash);
<del> });
<del> this.warnings.forEach(function(warning) {
<del> hash.update(`${warning.message}`);
<del> });
<del> this.errors.forEach(function(error) {
<del> hash.update(`${error.message}`);
<del> });
<add> this.children.forEach(child => hash.update(child.hash));
<add> this.warnings.forEach(warning => hash.update(`${warning.message}`));
<add> this.errors.forEach(error => hash.update(`${error.message}`));
<ide> // clone needed as sort below is inplace mutation
<ide> const chunks = this.chunks.slice();
<ide> /**
<ide><path>lib/Compiler.js
<ide> class Watching {
<ide> }
<ide>
<ide> close(callback) {
<del> if(callback === undefined) callback = function() {};
<add> if(callback === undefined) callback = () => {};
<ide>
<ide> this.closed = true;
<ide> if(this.watcher) {
<ide> class Compiler extends Tapable {
<ide> }, err => {
<ide> if(err) return callback(err);
<ide>
<del> afterEmit.call(this);
<add> this.applyPluginsAsyncSeries1("after-emit", compilation, err => {
<add> if(err) return callback(err);
<add>
<add> return callback();
<add> });
<ide> });
<ide> };
<ide>
<ide> class Compiler extends Tapable {
<ide> outputPath = compilation.getPath(this.outputPath);
<ide> this.outputFileSystem.mkdirp(outputPath, emitFiles);
<ide> });
<del>
<del> function afterEmit() {
<del> this.applyPluginsAsyncSeries1("after-emit", compilation, err => {
<del> if(err) return callback(err);
<del>
<del> return callback();
<del> });
<del> }
<del>
<ide> }
<ide>
<ide> emitRecords(callback) {
<ide> class Compiler extends Tapable {
<ide> let recordsOutputPathDirectory = null;
<ide> if(idx1 > idx2) recordsOutputPathDirectory = this.recordsOutputPath.substr(0, idx1);
<ide> if(idx1 < idx2) recordsOutputPathDirectory = this.recordsOutputPath.substr(0, idx2);
<del> if(!recordsOutputPathDirectory) return writeFile.call(this);
<add>
<add> const writeFile = () => {
<add> this.outputFileSystem.writeFile(this.recordsOutputPath, JSON.stringify(this.records, undefined, 2), callback);
<add> };
<add>
<add> if(!recordsOutputPathDirectory)
<add> return writeFile();
<ide> this.outputFileSystem.mkdirp(recordsOutputPathDirectory, err => {
<ide> if(err) return callback(err);
<del> writeFile.call(this);
<add> writeFile();
<ide> });
<del>
<del> function writeFile() {
<del> this.outputFileSystem.writeFile(this.recordsOutputPath, JSON.stringify(this.records, undefined, 2), callback);
<del> }
<ide> }
<ide>
<ide> readRecords(callback) {
<ide><path>lib/ConstPlugin.js
<ide> class ConstPlugin {
<ide> compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
<ide>
<ide> params.normalModuleFactory.plugin("parser", parser => {
<del> parser.plugin("statement if", function(statement) {
<del> const param = this.evaluateExpression(statement.test);
<add> parser.plugin("statement if", statement => {
<add> const param = parser.evaluateExpression(statement.test);
<ide> const bool = param.asBool();
<ide> if(typeof bool === "boolean") {
<ide> if(statement.test.type !== "Literal") {
<ide> const dep = new ConstDependency(`${bool}`, param.range);
<ide> dep.loc = statement.loc;
<del> this.state.current.addDependency(dep);
<add> parser.state.current.addDependency(dep);
<ide> }
<ide> return bool;
<ide> }
<ide> });
<del> parser.plugin("expression ?:", function(expression) {
<del> const param = this.evaluateExpression(expression.test);
<add> parser.plugin("expression ?:", expression => {
<add> const param = parser.evaluateExpression(expression.test);
<ide> const bool = param.asBool();
<ide> if(typeof bool === "boolean") {
<ide> if(expression.test.type !== "Literal") {
<ide> const dep = new ConstDependency(` ${bool}`, param.range);
<ide> dep.loc = expression.loc;
<del> this.state.current.addDependency(dep);
<add> parser.state.current.addDependency(dep);
<ide> }
<ide> return bool;
<ide> }
<ide> });
<del> parser.plugin("evaluate Identifier __resourceQuery", function(expr) {
<del> if(!this.state.module) return;
<del> return ParserHelpers.evaluateToString(getQuery(this.state.module.resource))(expr);
<add> parser.plugin("evaluate Identifier __resourceQuery", expr => {
<add> if(!parser.state.module) return;
<add> return ParserHelpers.evaluateToString(getQuery(parser.state.module.resource))(expr);
<ide> });
<del> parser.plugin("expression __resourceQuery", function() {
<del> if(!this.state.module) return;
<del> this.state.current.addVariable("__resourceQuery", JSON.stringify(getQuery(this.state.module.resource)));
<add> parser.plugin("expression __resourceQuery", () => {
<add> if(!parser.state.module) return;
<add> parser.state.current.addVariable("__resourceQuery", JSON.stringify(getQuery(parser.state.module.resource)));
<ide> return true;
<ide> });
<ide> });
<ide><path>lib/ContextModule.js
<ide> class ContextModule extends Module {
<ide> return 0;
<ide> }
<ide> return a.userRequest < b.userRequest ? -1 : 1;
<del> }).reduce(function(map, dep) {
<add> }).reduce((map, dep) => {
<ide> map[dep.userRequest] = dep.module.id;
<ide> return map;
<ide> }, Object.create(null));
<ide><path>lib/ContextModuleFactory.js
<ide> module.exports = class ContextModuleFactory extends Tapable {
<ide> const resolvers = this.resolvers;
<ide>
<ide> asyncLib.parallel([
<del> function(callback) {
<del> resolvers.context.resolve({}, context, resource, function(err, result) {
<add> callback => {
<add> resolvers.context.resolve({}, context, resource, (err, result) => {
<ide> if(err) return callback(err);
<ide> callback(null, result);
<ide> });
<ide> },
<del> function(callback) {
<del> asyncLib.map(loaders, function(loader, callback) {
<del> resolvers.loader.resolve({}, context, loader, function(err, result) {
<add> callback => {
<add> asyncLib.map(loaders, (loader, callback) => {
<add> resolvers.loader.resolve({}, context, loader, (err, result) => {
<ide> if(err) return callback(err);
<ide> callback(null, result);
<ide> });
<ide> module.exports = class ContextModuleFactory extends Tapable {
<ide> addon: loadersPrefix + result[1].join("!") + (result[1].length > 0 ? "!" : ""),
<ide> resource: result[0],
<ide> resolveDependencies: this.resolveDependencies.bind(this),
<del> }, beforeResolveResult), function(err, result) {
<add> }, beforeResolveResult), (err, result) => {
<ide> if(err) return callback(err);
<ide>
<ide> // Ignored
<ide> module.exports = class ContextModuleFactory extends Tapable {
<ide> let exclude = options.exclude;
<ide> if(!regExp || !resource)
<ide> return callback(null, []);
<del> (function addDirectory(directory, callback) {
<add> const addDirectory = (directory, callback) => {
<ide> fs.readdir(directory, (err, files) => {
<ide> if(err) return callback(err);
<ide> files = cmf.applyPluginsWaterfall("context-module-files", files);
<ide> if(!files || files.length === 0) return callback(null, []);
<del> asyncLib.map(files.filter(function(p) {
<del> return p.indexOf(".") !== 0;
<del> }), (seqment, callback) => {
<add> asyncLib.map(files.filter(p => p.indexOf(".") !== 0), (seqment, callback) => {
<ide>
<ide> const subResource = path.join(directory, seqment);
<ide>
<ide> module.exports = class ContextModuleFactory extends Tapable {
<ide>
<ide> this.applyPluginsAsyncWaterfall("alternatives", [obj], (err, alternatives) => {
<ide> if(err) return callback(err);
<del> alternatives = alternatives.filter(function(obj) {
<del> return regExp.test(obj.request);
<del> }).map(function(obj) {
<add> alternatives = alternatives.filter(obj => regExp.test(obj.request)).map(obj => {
<ide> const dep = new ContextElementDependency(obj.request);
<ide> dep.optional = true;
<ide> return dep;
<ide> module.exports = class ContextModuleFactory extends Tapable {
<ide>
<ide> if(!result) return callback(null, []);
<ide>
<del> callback(null, result.filter(function(i) {
<del> return !!i;
<del> }).reduce(function(a, i) {
<del> return a.concat(i);
<del> }, []));
<add> callback(null, result.filter(Boolean).reduce((a, i) => a.concat(i), []));
<ide> });
<ide> });
<del> }.call(this, resource, callback));
<add> };
<add>
<add> addDirectory(resource, callback);
<ide> }
<ide> };
<ide><path>lib/ContextReplacementPlugin.js
<ide> class ContextReplacementPlugin {
<ide> }
<ide>
<ide> const createResolveDependenciesFromContextMap = (createContextMap) => {
<del> return function resolveDependenciesFromContextMap(fs, options, callback) {
<add> return (fs, options, callback) => {
<ide> createContextMap(fs, (err, map) => {
<ide> if(err) return callback(err);
<ide> const dependencies = Object.keys(map).map((key) => {
<ide><path>lib/DefinePlugin.js
<ide> const BasicEvaluatedExpression = require("./BasicEvaluatedExpression");
<ide> const ParserHelpers = require("./ParserHelpers");
<ide> const NullFactory = require("./NullFactory");
<ide>
<add>const stringifyObj = obj => {
<add> return "Object({" + Object.keys(obj).map((key) => {
<add> const code = obj[key];
<add> return JSON.stringify(key) + ":" + toCode(code);
<add> }).join(",") + "})";
<add>};
<add>
<add>const toCode = code => {
<add> if(code === null) return "null";
<add> else if(code === undefined) return "undefined";
<add> else if(code instanceof RegExp && code.toString) return code.toString();
<add> else if(typeof code === "function" && code.toString) return "(" + code.toString() + ")";
<add> else if(typeof code === "object") return stringifyObj(code);
<add> else return code + "";
<add>};
<add>
<ide> class DefinePlugin {
<ide> constructor(definitions) {
<ide> this.definitions = definitions;
<ide> class DefinePlugin {
<ide> compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
<ide>
<ide> params.normalModuleFactory.plugin("parser", (parser) => {
<del> (function walkDefinitions(definitions, prefix) {
<add> const walkDefinitions = (definitions, prefix) => {
<ide> Object.keys(definitions).forEach((key) => {
<ide> const code = definitions[key];
<ide> if(code && typeof code === "object" && !(code instanceof RegExp)) {
<ide> class DefinePlugin {
<ide> applyDefineKey(prefix, key);
<ide> applyDefine(prefix + key, code);
<ide> });
<del> }(definitions, ""));
<del>
<del> function stringifyObj(obj) {
<del> return "Object({" + Object.keys(obj).map((key) => {
<del> const code = obj[key];
<del> return JSON.stringify(key) + ":" + toCode(code);
<del> }).join(",") + "})";
<del> }
<add> };
<ide>
<del> function toCode(code) {
<del> if(code === null) return "null";
<del> else if(code === undefined) return "undefined";
<del> else if(code instanceof RegExp && code.toString) return code.toString();
<del> else if(typeof code === "function" && code.toString) return "(" + code.toString() + ")";
<del> else if(typeof code === "object") return stringifyObj(code);
<del> else return code + "";
<del> }
<del>
<del> function applyDefineKey(prefix, key) {
<add> const applyDefineKey = (prefix, key) => {
<ide> const splittedKey = key.split(".");
<ide> splittedKey.slice(1).forEach((_, i) => {
<ide> const fullKey = prefix + splittedKey.slice(0, i + 1).join(".");
<ide> parser.plugin("can-rename " + fullKey, ParserHelpers.approve);
<ide> });
<del> }
<add> };
<ide>
<del> function applyDefine(key, code) {
<add> const applyDefine = (key, code) => {
<ide> const isTypeof = /^typeof\s+/.test(key);
<ide> if(isTypeof) key = key.replace(/^typeof\s+/, "");
<ide> let recurse = false;
<ide> class DefinePlugin {
<ide> if(!res.isString()) return;
<ide> return ParserHelpers.toConstantDependency(JSON.stringify(res.string)).bind(parser)(expr);
<ide> });
<del> }
<add> };
<ide>
<del> function applyObjectDefine(key, obj) {
<add> const applyObjectDefine = (key, obj) => {
<ide> const code = stringifyObj(obj);
<ide> parser.plugin("can-rename " + key, ParserHelpers.approve);
<ide> parser.plugin("evaluate Identifier " + key, (expr) => new BasicEvaluatedExpression().setTruthy().setRange(expr.range));
<ide> parser.plugin("evaluate typeof " + key, ParserHelpers.evaluateToString("object"));
<ide> parser.plugin("expression " + key, ParserHelpers.toConstantDependency(code));
<ide> parser.plugin("typeof " + key, ParserHelpers.toConstantDependency(JSON.stringify("object")));
<del> }
<add> };
<add>
<add> walkDefinitions(definitions, "");
<ide> });
<ide> });
<ide> }
<ide><path>lib/DependenciesBlock.js
<ide>
<ide> const DependenciesBlockVariable = require("./DependenciesBlockVariable");
<ide>
<del>function disconnect(i) {
<del> i.disconnect();
<del>}
<add>const disconnect = i => i.disconnect();
<ide>
<del>function unseal(i) {
<del> i.unseal();
<del>}
<add>const unseal = i => i.unseal();
<ide>
<ide> class DependenciesBlock {
<ide> constructor() {
<ide> class DependenciesBlock {
<ide> }
<ide>
<ide> updateHash(hash) {
<del> function updateHash(i) {
<del> i.updateHash(hash);
<del> }
<add> const updateHash = i => i.updateHash(hash);
<ide>
<ide> this.dependencies.forEach(updateHash);
<ide> this.blocks.forEach(updateHash);
<ide><path>lib/DllPlugin.js
<ide> class DllPlugin {
<ide>
<ide> apply(compiler) {
<ide> compiler.plugin("entry-option", (context, entry) => {
<del> function itemToPlugin(item, name) {
<add> const itemToPlugin = (item, name) => {
<ide> if(Array.isArray(item))
<ide> return new DllEntryPlugin(context, item, name);
<ide> else
<ide> throw new Error("DllPlugin: supply an Array as entry");
<del> }
<add> };
<ide> if(typeof entry === "object" && !Array.isArray(entry)) {
<ide> Object.keys(entry).forEach(name => {
<ide> compiler.apply(itemToPlugin(entry[name], name));
<ide><path>lib/DllReferencePlugin.js
<ide> class DllReferencePlugin {
<ide> const manifest = this.options.manifest;
<ide> if(typeof manifest === "string") {
<ide> params.compilationDependencies.push(manifest);
<del> compiler.inputFileSystem.readFile(manifest, function(err, result) {
<add> compiler.inputFileSystem.readFile(manifest, (err, result) => {
<ide> if(err) return callback(err);
<ide> params["dll reference " + manifest] = JSON.parse(result.toString("utf-8"));
<ide> return callback();
<ide><path>lib/DynamicEntryPlugin.js
<ide> class DynamicEntryPlugin {
<ide>
<ide> module.exports = DynamicEntryPlugin;
<ide>
<del>DynamicEntryPlugin.createDependency = function(entry, name) {
<add>DynamicEntryPlugin.createDependency = (entry, name) => {
<ide> if(Array.isArray(entry))
<ide> return MultiEntryPlugin.createDependency(entry, name);
<ide> else
<ide><path>lib/EntryOptionPlugin.js
<ide> const SingleEntryPlugin = require("./SingleEntryPlugin");
<ide> const MultiEntryPlugin = require("./MultiEntryPlugin");
<ide> const DynamicEntryPlugin = require("./DynamicEntryPlugin");
<ide>
<del>function itemToPlugin(context, item, name) {
<add>const itemToPlugin = (context, item, name) => {
<ide> if(Array.isArray(item)) {
<ide> return new MultiEntryPlugin(context, item, name);
<ide> }
<ide> return new SingleEntryPlugin(context, item, name);
<del>}
<add>};
<ide>
<ide> module.exports = class EntryOptionPlugin {
<ide> apply(compiler) {
<ide><path>lib/EnvironmentPlugin.js
<ide> const DefinePlugin = require("./DefinePlugin");
<ide>
<ide> class EnvironmentPlugin {
<del> constructor(keys) {
<del> if(Array.isArray(keys)) {
<del> this.keys = keys;
<add> constructor(...keys) {
<add> if(keys.length === 1 && Array.isArray(keys[0])) {
<add> this.keys = keys[0];
<ide> this.defaultValues = {};
<del> } else if(keys && typeof keys === "object") {
<del> this.keys = Object.keys(keys);
<del> this.defaultValues = keys;
<add> } else if(keys.length === 1 && keys[0] && typeof keys[0] === "object") {
<add> this.keys = Object.keys(keys[0]);
<add> this.defaultValues = keys[0];
<ide> } else {
<del> this.keys = Array.prototype.slice.call(arguments);
<add> this.keys = keys;
<ide> this.defaultValues = {};
<ide> }
<ide> }
<ide><path>lib/EvalSourceMapDevToolModuleTemplatePlugin.js
<ide> class EvalSourceMapDevToolModuleTemplatePlugin {
<ide> apply(moduleTemplate) {
<ide> const self = this;
<ide> const options = this.options;
<del> moduleTemplate.plugin("module", function(source, module) {
<add> moduleTemplate.plugin("module", (source, module) => {
<ide> if(source.__EvalSourceMapDevToolData)
<ide> return source.__EvalSourceMapDevToolData;
<ide> let sourceMap;
<ide> class EvalSourceMapDevToolModuleTemplatePlugin {
<ide> }
<ide>
<ide> // Clone (flat) the sourcemap to ensure that the mutations below do not persist.
<del> sourceMap = Object.keys(sourceMap).reduce(function(obj, key) {
<add> sourceMap = Object.keys(sourceMap).reduce((obj, key) => {
<ide> obj[key] = sourceMap[key];
<ide> return obj;
<ide> }, {});
<del> const modules = sourceMap.sources.map(function(source) {
<add> const modules = sourceMap.sources.map(source => {
<ide> const module = self.compilation.findModule(source);
<ide> return module || source;
<ide> });
<del> let moduleFilenames = modules.map(function(module) {
<del> return ModuleFilenameHelpers.createFilename(module, self.moduleFilenameTemplate, this.requestShortener);
<del> }, this);
<del> moduleFilenames = ModuleFilenameHelpers.replaceDuplicates(moduleFilenames, function(filename, i, n) {
<add> let moduleFilenames = modules.map(module => {
<add> return ModuleFilenameHelpers.createFilename(module, self.moduleFilenameTemplate, moduleTemplate.requestShortener);
<add> });
<add> moduleFilenames = ModuleFilenameHelpers.replaceDuplicates(moduleFilenames, (filename, i, n) => {
<ide> for(let j = 0; j < n; j++)
<ide> filename += "*";
<ide> return filename;
<ide> });
<ide> sourceMap.sources = moduleFilenames;
<ide> if(sourceMap.sourcesContent) {
<del> sourceMap.sourcesContent = sourceMap.sourcesContent.map(function(content, i) {
<del> return `${content}\n\n\n${ModuleFilenameHelpers.createFooter(modules[i], this.requestShortener)}`;
<del> }, this);
<add> sourceMap.sourcesContent = sourceMap.sourcesContent.map((content, i) => {
<add> return `${content}\n\n\n${ModuleFilenameHelpers.createFooter(modules[i], moduleTemplate.requestShortener)}`;
<add> });
<ide> }
<ide> sourceMap.sourceRoot = options.sourceRoot || "";
<ide> sourceMap.file = `${module.id}.js`;
<ide> class EvalSourceMapDevToolModuleTemplatePlugin {
<ide> source.__EvalSourceMapDevToolData = new RawSource(`eval(${JSON.stringify(content + footer)});`);
<ide> return source.__EvalSourceMapDevToolData;
<ide> });
<del> moduleTemplate.plugin("hash", function(hash) {
<add> moduleTemplate.plugin("hash", hash => {
<ide> hash.update("eval-source-map");
<ide> hash.update("2");
<ide> });
<ide><path>lib/ExportPropertyMainTemplatePlugin.js
<ide>
<ide> const ConcatSource = require("webpack-sources").ConcatSource;
<ide>
<del>function accessorToObjectAccess(accessor) {
<add>const accessorToObjectAccess = accessor => {
<ide> return accessor.map(a => `[${JSON.stringify(a)}]`).join("");
<del>}
<add>};
<ide>
<ide> class ExportPropertyMainTemplatePlugin {
<ide> constructor(property) {
<ide><path>lib/ExtendedAPIPlugin.js
<ide> class ExtendedAPIPlugin {
<ide> compiler.plugin("compilation", (compilation, params) => {
<ide> compilation.dependencyFactories.set(ConstDependency, new NullFactory());
<ide> compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
<del> compilation.mainTemplate.plugin("require-extensions", function(source, chunk, hash) {
<add>
<add> const mainTemplate = compilation.mainTemplate;
<add> mainTemplate.plugin("require-extensions", (source, chunk, hash) => {
<ide> const buf = [source];
<ide> buf.push("");
<ide> buf.push("// __webpack_hash__");
<del> buf.push(`${this.requireFn}.h = ${JSON.stringify(hash)};`);
<add> buf.push(`${mainTemplate.requireFn}.h = ${JSON.stringify(hash)};`);
<ide> buf.push("");
<ide> buf.push("// __webpack_chunkname__");
<del> buf.push(`${this.requireFn}.cn = ${JSON.stringify(chunk.name)};`);
<del> return this.asString(buf);
<add> buf.push(`${mainTemplate.requireFn}.cn = ${JSON.stringify(chunk.name)};`);
<add> return mainTemplate.asString(buf);
<ide> });
<del> compilation.mainTemplate.plugin("global-hash", () => true);
<add> mainTemplate.plugin("global-hash", () => true);
<ide>
<ide> params.normalModuleFactory.plugin("parser", (parser, parserOptions) => {
<ide> Object.keys(REPLACEMENTS).forEach(key => {
<ide><path>lib/ExternalModuleFactoryPlugin.js
<ide> class ExternalModuleFactoryPlugin {
<ide> const context = data.context;
<ide> const dependency = data.dependencies[0];
<ide>
<del> function handleExternal(value, type, callback) {
<add> const handleExternal = (value, type, callback) => {
<ide> if(typeof type === "function") {
<ide> callback = type;
<ide> type = undefined;
<ide> class ExternalModuleFactoryPlugin {
<ide> }
<ide> callback(null, new ExternalModule(value, type || globalType, dependency.request));
<ide> return true;
<del> }
<del> (function handleExternals(externals, callback) {
<add> };
<add>
<add> const handleExternals = (externals, callback) => {
<ide> if(typeof externals === "string") {
<ide> if(externals === dependency.request) {
<ide> return handleExternal(dependency.request, callback);
<ide> }
<ide> } else if(Array.isArray(externals)) {
<ide> let i = 0;
<del> (function next() {
<add> const next = () => {
<ide> let asyncFlag;
<del> const handleExternalsAndCallback = function handleExternalsAndCallback(err, module) {
<add> const handleExternalsAndCallback = (err, module) => {
<ide> if(err) return callback(err);
<ide> if(!module) {
<ide> if(asyncFlag) {
<ide> class ExternalModuleFactoryPlugin {
<ide> handleExternals(externals[i++], handleExternalsAndCallback);
<ide> } while (!asyncFlag); // eslint-disable-line keyword-spacing
<ide> asyncFlag = false;
<del> }());
<add> };
<add>
<add> next();
<ide> return;
<ide> } else if(externals instanceof RegExp) {
<ide> if(externals.test(dependency.request)) {
<ide> return handleExternal(dependency.request, callback);
<ide> }
<ide> } else if(typeof externals === "function") {
<del> externals.call(null, context, dependency.request, function(err, value, type) {
<add> externals.call(null, context, dependency.request, (err, value, type) => {
<ide> if(err) return callback(err);
<ide> if(typeof value !== "undefined") {
<ide> handleExternal(value, type, callback);
<ide> class ExternalModuleFactoryPlugin {
<ide> return handleExternal(externals[dependency.request], callback);
<ide> }
<ide> callback();
<del> }(this.externals, function(err, module) {
<add> };
<add>
<add> handleExternals(this.externals, (err, module) => {
<ide> if(err) return callback(err);
<ide> if(!module) return handleExternal(false, callback);
<ide> return callback(null, module);
<del> }));
<add> });
<ide> });
<ide> }
<ide> }
<ide><path>lib/FlagDependencyExportsPlugin.js
<ide> */
<ide> "use strict";
<ide>
<add>const addToSet = (a, b) => {
<add> let changed = false;
<add> b.forEach((item) => {
<add> if(!a.has(item)) {
<add> a.add(item);
<add> changed = true;
<add> }
<add> });
<add> return changed;
<add>};
<add>
<ide> class FlagDependencyExportsPlugin {
<ide>
<ide> apply(compiler) {
<ide> compiler.plugin("compilation", (compilation) => {
<ide> compilation.plugin("finish-modules", (modules) => {
<ide> const dependencies = Object.create(null);
<ide>
<add> // TODO maybe replace with utils/Queue for better performance?
<add> const queue = modules.filter((m) => !m.providedExports);
<add>
<ide> let module;
<ide> let moduleWithExports;
<ide> let moduleProvidedExports;
<del> const queue = modules.filter((m) => !m.providedExports);
<del> for(let i = 0; i < queue.length; i++) {
<del> module = queue[i];
<del>
<del> if(module.providedExports !== true) {
<del> moduleWithExports = module.meta && module.meta.harmonyModule;
<del> moduleProvidedExports = Array.isArray(module.providedExports) ? new Set(module.providedExports) : new Set();
<del> processDependenciesBlock(module);
<del> if(!moduleWithExports) {
<del> module.providedExports = true;
<del> notifyDependencies();
<del> } else if(module.providedExports !== true) {
<del> module.providedExports = Array.from(moduleProvidedExports);
<del> }
<del> }
<del> }
<ide>
<del> function processDependenciesBlock(depBlock) {
<add> const processDependenciesBlock = depBlock => {
<ide> depBlock.dependencies.forEach((dep) => processDependency(dep));
<ide> depBlock.variables.forEach((variable) => {
<ide> variable.dependencies.forEach((dep) => processDependency(dep));
<ide> });
<ide> depBlock.blocks.forEach(processDependenciesBlock);
<del> }
<add> };
<ide>
<del> function processDependency(dep) {
<add> const processDependency = dep => {
<ide> const exportDesc = dep.getExports && dep.getExports();
<ide> if(!exportDesc) return;
<ide> moduleWithExports = true;
<ide> class FlagDependencyExportsPlugin {
<ide> if(changed) {
<ide> notifyDependencies();
<ide> }
<del> }
<add> };
<ide>
<del> function notifyDependencies() {
<add> const notifyDependencies = () => {
<ide> const deps = dependencies[module.identifier()];
<ide> if(deps) {
<ide> deps.forEach((dep) => queue.push(dep));
<ide> }
<del> }
<del> });
<add> };
<add>
<add> for(let i = 0; i < queue.length; i++) {
<add> module = queue[i];
<ide>
<del> function addToSet(a, b) {
<del> let changed = false;
<del> b.forEach((item) => {
<del> if(!a.has(item)) {
<del> a.add(item);
<del> changed = true;
<add> if(module.providedExports !== true) {
<add> moduleWithExports = module.meta && module.meta.harmonyModule;
<add> moduleProvidedExports = Array.isArray(module.providedExports) ? new Set(module.providedExports) : new Set();
<add> processDependenciesBlock(module);
<add> if(!moduleWithExports) {
<add> module.providedExports = true;
<add> notifyDependencies();
<add> } else if(module.providedExports !== true) {
<add> module.providedExports = Array.from(moduleProvidedExports);
<add> }
<ide> }
<del> });
<del> return changed;
<del> }
<add> }
<add> });
<ide> });
<ide> }
<ide> }
<ide><path>lib/FlagDependencyUsagePlugin.js
<ide> */
<ide> "use strict";
<ide>
<add>const addToSet = (a, b) => {
<add> b.forEach(item => {
<add> if(a.indexOf(item) < 0)
<add> a.push(item);
<add> });
<add> return a;
<add>};
<add>
<add>const isSubset = (biggerSet, subset) => {
<add> if(biggerSet === true) return true;
<add> if(subset === true) return false;
<add> return subset.every(item => biggerSet.indexOf(item) >= 0);
<add>};
<add>
<ide> class FlagDependencyUsagePlugin {
<ide> apply(compiler) {
<ide> compiler.plugin("compilation", compilation => {
<ide> compilation.plugin("optimize-modules-advanced", modules => {
<ide>
<del> modules.forEach(module => module.used = false);
<del>
<del> const queue = [];
<del> compilation.chunks.forEach(chunk => {
<del> if(chunk.entryModule) {
<del> processModule(chunk.entryModule, true);
<del> }
<del> });
<del>
<del> while(queue.length) {
<del> const queueItem = queue.pop();
<del> processDependenciesBlock(queueItem[0], queueItem[1]);
<del> }
<del>
<del> function processModule(module, usedExports) {
<add> const processModule = (module, usedExports) => {
<ide> module.used = true;
<ide> if(module.usedExports === true)
<ide> return;
<ide> class FlagDependencyUsagePlugin {
<ide> }
<ide>
<ide> queue.push([module, module.usedExports]);
<del> }
<add> };
<ide>
<del> function processDependenciesBlock(depBlock, usedExports) {
<add> const processDependenciesBlock = (depBlock, usedExports) => {
<ide> depBlock.dependencies.forEach(dep => processDependency(dep));
<ide> depBlock.variables.forEach(variable => variable.dependencies.forEach(dep => processDependency(dep)));
<ide> depBlock.blocks.forEach(block => queue.push([block, usedExports]));
<del> }
<add> };
<ide>
<del> function processDependency(dep) {
<add> const processDependency = dep => {
<ide> const reference = dep.getReference && dep.getReference();
<ide> if(!reference) return;
<ide> const module = reference.module;
<ide> class FlagDependencyUsagePlugin {
<ide> if(!oldUsed || (importedNames && (!oldUsedExports || !isSubset(oldUsedExports, importedNames)))) {
<ide> processModule(module, importedNames);
<ide> }
<del> }
<add> };
<ide>
<del> });
<add> modules.forEach(module => module.used = false);
<ide>
<del> function addToSet(a, b) {
<del> b.forEach(item => {
<del> if(a.indexOf(item) < 0)
<del> a.push(item);
<add> const queue = [];
<add> compilation.chunks.forEach(chunk => {
<add> if(chunk.entryModule) {
<add> processModule(chunk.entryModule, true);
<add> }
<ide> });
<del> return a;
<del> }
<ide>
<del> function isSubset(biggerSet, subset) {
<del> if(biggerSet === true) return true;
<del> if(subset === true) return false;
<del> return subset.every(item => biggerSet.indexOf(item) >= 0);
<del> }
<add> while(queue.length) {
<add> const queueItem = queue.pop();
<add> processDependenciesBlock(queueItem[0], queueItem[1]);
<add> }
<add> });
<ide> });
<ide> }
<ide> }
<ide><path>lib/FunctionModuleTemplatePlugin.js
<ide> const Template = require("./Template");
<ide>
<ide> class FunctionModuleTemplatePlugin {
<ide> apply(moduleTemplate) {
<del> moduleTemplate.plugin("render", function(moduleSource, module) {
<add> moduleTemplate.plugin("render", (moduleSource, module) => {
<ide> const source = new ConcatSource();
<ide> const defaultArguments = [module.moduleArgument || "module", module.exportsArgument || "exports"];
<ide> if((module.arguments && module.arguments.length !== 0) || module.hasDependencies(d => d.requireWebpackRequire !== false)) {
<ide> class FunctionModuleTemplatePlugin {
<ide> return source;
<ide> });
<ide>
<del> moduleTemplate.plugin("package", function(moduleSource, module) {
<del> if(this.outputOptions.pathinfo) {
<add> moduleTemplate.plugin("package", (moduleSource, module) => {
<add> if(moduleTemplate.outputOptions.pathinfo) {
<ide> const source = new ConcatSource();
<del> const req = module.readableIdentifier(this.requestShortener);
<add> const req = module.readableIdentifier(moduleTemplate.requestShortener);
<ide> source.add("/*!****" + req.replace(/./g, "*") + "****!*\\\n");
<ide> source.add(" !*** " + req.replace(/\*\//g, "*_/") + " ***!\n");
<ide> source.add(" \\****" + req.replace(/./g, "*") + "****/\n");
<ide> class FunctionModuleTemplatePlugin {
<ide> source.add(Template.toComment("all exports used") + "\n");
<ide> if(module.optimizationBailout) {
<ide> module.optimizationBailout.forEach(text => {
<del> if(typeof text === "function") text = text(this.requestShortener);
<add> if(typeof text === "function") text = text(moduleTemplate.requestShortener);
<ide> source.add(Template.toComment(`${text}`) + "\n");
<ide> });
<ide> }
<ide> class FunctionModuleTemplatePlugin {
<ide> return moduleSource;
<ide> });
<ide>
<del> moduleTemplate.plugin("hash", function(hash) {
<add> moduleTemplate.plugin("hash", hash => {
<ide> hash.update("FunctionModuleTemplatePlugin");
<ide> hash.update("2");
<ide> });
<ide><path>lib/HotModuleReplacementPlugin.js
<ide> module.exports = class HotModuleReplacementPlugin {
<ide> compilation.dependencyFactories.set(ModuleHotDeclineDependency, normalModuleFactory);
<ide> compilation.dependencyTemplates.set(ModuleHotDeclineDependency, new ModuleHotDeclineDependency.Template());
<ide>
<del> compilation.plugin("record", function(compilation, records) {
<del> if(records.hash === this.hash) return;
<add> compilation.plugin("record", (compilation, records) => {
<add> if(records.hash === compilation.hash) return;
<ide> records.hash = compilation.hash;
<ide> records.moduleHashs = {};
<del> this.modules.forEach(module => {
<add> compilation.modules.forEach(module => {
<ide> const identifier = module.identifier();
<ide> const hash = require("crypto").createHash("md5");
<ide> module.updateHash(hash);
<ide> records.moduleHashs[identifier] = hash.digest("hex");
<ide> });
<ide> records.chunkHashs = {};
<del> this.chunks.forEach(chunk => {
<add> compilation.chunks.forEach(chunk => {
<ide> records.chunkHashs[chunk.id] = chunk.hash;
<ide> });
<ide> records.chunkModuleIds = {};
<del> this.chunks.forEach(chunk => {
<add> compilation.chunks.forEach(chunk => {
<ide> records.chunkModuleIds[chunk.id] = chunk.mapModules(m => m.id);
<ide> });
<ide> });
<ide> let initialPass = false;
<ide> let recompilation = false;
<del> compilation.plugin("after-hash", function() {
<del> let records = this.records;
<add> compilation.plugin("after-hash", () => {
<add> let records = compilation.records;
<ide> if(!records) {
<ide> initialPass = true;
<ide> return;
<ide> module.exports = class HotModuleReplacementPlugin {
<ide> initialPass = true;
<ide> const preHash = records.preHash || "x";
<ide> const prepreHash = records.prepreHash || "x";
<del> if(preHash === this.hash) {
<add> if(preHash === compilation.hash) {
<ide> recompilation = true;
<del> this.modifyHash(prepreHash);
<add> compilation.modifyHash(prepreHash);
<ide> return;
<ide> }
<ide> records.prepreHash = records.hash || "x";
<del> records.preHash = this.hash;
<del> this.modifyHash(records.prepreHash);
<add> records.preHash = compilation.hash;
<add> compilation.modifyHash(records.prepreHash);
<ide> });
<ide> compilation.plugin("should-generate-chunk-assets", () => {
<ide> if(multiStep && !recompilation && !initialPass)
<ide> module.exports = class HotModuleReplacementPlugin {
<ide> return setTimeout(callback, fullBuildTimeout);
<ide> return callback();
<ide> });
<del> compilation.plugin("additional-chunk-assets", function() {
<del> const records = this.records;
<del> if(records.hash === this.hash) return;
<add> compilation.plugin("additional-chunk-assets", () => {
<add> const records = compilation.records;
<add> if(records.hash === compilation.hash) return;
<ide> if(!records.moduleHashs || !records.chunkHashs || !records.chunkModuleIds) return;
<del> this.modules.forEach(module => {
<add> compilation.modules.forEach(module => {
<ide> const identifier = module.identifier();
<ide> let hash = require("crypto").createHash("md5");
<ide> module.updateHash(hash);
<ide> hash = hash.digest("hex");
<ide> module.hotUpdate = records.moduleHashs[identifier] !== hash;
<ide> });
<ide> const hotUpdateMainContent = {
<del> h: this.hash,
<add> h: compilation.hash,
<ide> c: {},
<ide> };
<del> Object.keys(records.chunkHashs).forEach(function(chunkId) {
<add> Object.keys(records.chunkHashs).forEach(chunkId => {
<ide> chunkId = isNaN(+chunkId) ? chunkId : +chunkId;
<del> const currentChunk = this.chunks.find(chunk => chunk.id === chunkId);
<add> const currentChunk = compilation.chunks.find(chunk => chunk.id === chunkId);
<ide> if(currentChunk) {
<ide> const newModules = currentChunk.getModules().filter(module => module.hotUpdate);
<ide> const allModules = {};
<ide> module.exports = class HotModuleReplacementPlugin {
<ide> });
<ide> const removedModules = records.chunkModuleIds[chunkId].filter(id => !allModules[id]);
<ide> if(newModules.length > 0 || removedModules.length > 0) {
<del> const source = hotUpdateChunkTemplate.render(chunkId, newModules, removedModules, this.hash, this.moduleTemplate, this.dependencyTemplates);
<del> const filename = this.getPath(hotUpdateChunkFilename, {
<add> const source = hotUpdateChunkTemplate.render(chunkId, newModules, removedModules, compilation.hash, compilation.moduleTemplate, compilation.dependencyTemplates);
<add> const filename = compilation.getPath(hotUpdateChunkFilename, {
<ide> hash: records.hash,
<ide> chunk: currentChunk
<ide> });
<del> this.additionalChunkAssets.push(filename);
<del> this.assets[filename] = source;
<add> compilation.additionalChunkAssets.push(filename);
<add> compilation.assets[filename] = source;
<ide> hotUpdateMainContent.c[chunkId] = true;
<ide> currentChunk.files.push(filename);
<del> this.applyPlugins("chunk-asset", currentChunk, filename);
<add> compilation.applyPlugins("chunk-asset", currentChunk, filename);
<ide> }
<ide> } else {
<ide> hotUpdateMainContent.c[chunkId] = false;
<ide> }
<del> }, this);
<add> }, compilation);
<ide> const source = new RawSource(JSON.stringify(hotUpdateMainContent));
<del> const filename = this.getPath(hotUpdateMainFilename, {
<add> const filename = compilation.getPath(hotUpdateMainFilename, {
<ide> hash: records.hash
<ide> });
<del> this.assets[filename] = source;
<add> compilation.assets[filename] = source;
<ide> });
<ide>
<del> compilation.mainTemplate.plugin("hash", hash => {
<add> const mainTemplate = compilation.mainTemplate;
<add>
<add> mainTemplate.plugin("hash", hash => {
<ide> hash.update("HotMainTemplateDecorator");
<ide> });
<ide>
<del> compilation.mainTemplate.plugin("module-require", (_, chunk, hash, varModuleId) => {
<add> mainTemplate.plugin("module-require", (_, chunk, hash, varModuleId) => {
<ide> return `hotCreateRequire(${varModuleId})`;
<ide> });
<ide>
<del> compilation.mainTemplate.plugin("require-extensions", function(source) {
<add> mainTemplate.plugin("require-extensions", source => {
<ide> const buf = [source];
<ide> buf.push("");
<ide> buf.push("// __webpack_hash__");
<del> buf.push(this.requireFn + ".h = function() { return hotCurrentHash; };");
<del> return this.asString(buf);
<add> buf.push(mainTemplate.requireFn + ".h = function() { return hotCurrentHash; };");
<add> return mainTemplate.asString(buf);
<ide> });
<ide>
<del> compilation.mainTemplate.plugin("bootstrap", function(source, chunk, hash) {
<del> source = this.applyPluginsWaterfall("hot-bootstrap", source, chunk, hash);
<del> return this.asString([
<add> mainTemplate.plugin("bootstrap", (source, chunk, hash) => {
<add> source = mainTemplate.applyPluginsWaterfall("hot-bootstrap", source, chunk, hash);
<add> return mainTemplate.asString([
<ide> source,
<ide> "",
<ide> hotInitCode
<del> .replace(/\$require\$/g, this.requireFn)
<add> .replace(/\$require\$/g, mainTemplate.requireFn)
<ide> .replace(/\$hash\$/g, JSON.stringify(hash))
<ide> .replace(/\$requestTimeout\$/g, requestTimeout)
<ide> .replace(/\/\*foreachInstalledChunks\*\//g, chunk.getNumberOfChunks() > 0 ? "for(var chunkId in installedChunks)" : `var chunkId = ${JSON.stringify(chunk.id)};`)
<ide> ]);
<ide> });
<ide>
<del> compilation.mainTemplate.plugin("global-hash", () => true);
<add> mainTemplate.plugin("global-hash", () => true);
<ide>
<del> compilation.mainTemplate.plugin("current-hash", (_, length) => {
<add> mainTemplate.plugin("current-hash", (_, length) => {
<ide> if(isFinite(length))
<ide> return `hotCurrentHash.substr(0, ${length})`;
<ide> else
<ide> return "hotCurrentHash";
<ide> });
<ide>
<del> compilation.mainTemplate.plugin("module-obj", function(source, chunk, hash, varModuleId) {
<del> return this.asString([
<add> mainTemplate.plugin("module-obj", (source, chunk, hash, varModuleId) => {
<add> return mainTemplate.asString([
<ide> `${source},`,
<ide> `hot: hotCreateModule(${varModuleId}),`,
<ide> "parents: (hotCurrentParentsTemp = hotCurrentParents, hotCurrentParents = [], hotCurrentParentsTemp),",
<ide> "children: []"
<ide> ]);
<ide> });
<ide>
<del> params.normalModuleFactory.plugin("parser", (parser, parserOptions) => {
<add> normalModuleFactory.plugin("parser", (parser, parserOptions) => {
<ide> parser.plugin("expression __webpack_hash__", ParserHelpers.toConstantDependency("__webpack_require__.h()"));
<ide> parser.plugin("evaluate typeof __webpack_hash__", ParserHelpers.evaluateToString("string"));
<del> parser.plugin("evaluate Identifier module.hot", function(expr) {
<del> return ParserHelpers.evaluateToIdentifier("module.hot", !!this.state.compilation.hotUpdateChunkTemplate)(expr);
<add> parser.plugin("evaluate Identifier module.hot", expr => {
<add> return ParserHelpers.evaluateToIdentifier("module.hot", !!parser.state.compilation.hotUpdateChunkTemplate)(expr);
<ide> });
<del> parser.plugin("call module.hot.accept", function(expr) {
<del> if(!this.state.compilation.hotUpdateChunkTemplate) return false;
<add> parser.plugin("call module.hot.accept", expr => {
<add> if(!parser.state.compilation.hotUpdateChunkTemplate) return false;
<ide> if(expr.arguments.length >= 1) {
<del> const arg = this.evaluateExpression(expr.arguments[0]);
<add> const arg = parser.evaluateExpression(expr.arguments[0]);
<ide> let params = [];
<ide> let requests = [];
<ide> if(arg.isString()) {
<ide> module.exports = class HotModuleReplacementPlugin {
<ide> dep.optional = true;
<ide> dep.loc = Object.create(expr.loc);
<ide> dep.loc.index = idx;
<del> this.state.module.addDependency(dep);
<add> parser.state.module.addDependency(dep);
<ide> requests.push(request);
<ide> });
<ide> if(expr.arguments.length > 1)
<del> this.applyPluginsBailResult("hot accept callback", expr.arguments[1], requests);
<add> parser.applyPluginsBailResult("hot accept callback", expr.arguments[1], requests);
<ide> else
<del> this.applyPluginsBailResult("hot accept without callback", expr, requests);
<add> parser.applyPluginsBailResult("hot accept without callback", expr, requests);
<ide> }
<ide> }
<ide> });
<del> parser.plugin("call module.hot.decline", function(expr) {
<del> if(!this.state.compilation.hotUpdateChunkTemplate) return false;
<add> parser.plugin("call module.hot.decline", expr => {
<add> if(!parser.state.compilation.hotUpdateChunkTemplate) return false;
<ide> if(expr.arguments.length === 1) {
<del> const arg = this.evaluateExpression(expr.arguments[0]);
<add> const arg = parser.evaluateExpression(expr.arguments[0]);
<ide> let params = [];
<ide> if(arg.isString()) {
<ide> params = [arg];
<ide> module.exports = class HotModuleReplacementPlugin {
<ide> dep.optional = true;
<ide> dep.loc = Object.create(expr.loc);
<ide> dep.loc.index = idx;
<del> this.state.module.addDependency(dep);
<add> parser.state.module.addDependency(dep);
<ide> });
<ide> }
<ide> });
<ide><path>lib/JsonpChunkTemplatePlugin.js
<ide> const ConcatSource = require("webpack-sources").ConcatSource;
<ide>
<ide> class JsonpChunkTemplatePlugin {
<ide> apply(chunkTemplate) {
<del> chunkTemplate.plugin("render", function(modules, chunk) {
<del> const jsonpFunction = this.outputOptions.jsonpFunction;
<add> chunkTemplate.plugin("render", (modules, chunk) => {
<add> const jsonpFunction = chunkTemplate.outputOptions.jsonpFunction;
<ide> const source = new ConcatSource();
<ide> source.add(`(window[${JSON.stringify(jsonpFunction)}] = window[${JSON.stringify(jsonpFunction)}] || []).push([${JSON.stringify(chunk.ids)},`);
<ide> source.add(modules);
<ide> class JsonpChunkTemplatePlugin {
<ide> source.add("])");
<ide> return source;
<ide> });
<del> chunkTemplate.plugin("hash", function(hash) {
<add> chunkTemplate.plugin("hash", hash => {
<ide> hash.update("JsonpChunkTemplatePlugin");
<ide> hash.update("4");
<del> hash.update(`${this.outputOptions.jsonpFunction}`);
<del> hash.update(`${this.outputOptions.library}`);
<add> hash.update(`${chunkTemplate.outputOptions.jsonpFunction}`);
<add> hash.update(`${chunkTemplate.outputOptions.library}`);
<ide> });
<ide> }
<ide> }
<ide><path>lib/JsonpHotUpdateChunkTemplatePlugin.js
<ide> const ConcatSource = require("webpack-sources").ConcatSource;
<ide>
<ide> class JsonpHotUpdateChunkTemplatePlugin {
<ide> apply(hotUpdateChunkTemplate) {
<del> hotUpdateChunkTemplate.plugin("render", function(modulesSource, modules, removedModules, hash, id) {
<add> hotUpdateChunkTemplate.plugin("render", (modulesSource, modules, removedModules, hash, id) => {
<ide> const source = new ConcatSource();
<del> source.add(`${this.outputOptions.hotUpdateFunction}(${JSON.stringify(id)},`);
<add> source.add(`${hotUpdateChunkTemplate.outputOptions.hotUpdateFunction}(${JSON.stringify(id)},`);
<ide> source.add(modulesSource);
<ide> source.add(")");
<ide> return source;
<ide> });
<del> hotUpdateChunkTemplate.plugin("hash", function(hash) {
<add> hotUpdateChunkTemplate.plugin("hash", hash => {
<ide> hash.update("JsonpHotUpdateChunkTemplatePlugin");
<ide> hash.update("3");
<del> hash.update(`${this.outputOptions.hotUpdateFunction}`);
<del> hash.update(`${this.outputOptions.library}`);
<add> hash.update(`${hotUpdateChunkTemplate.outputOptions.hotUpdateFunction}`);
<add> hash.update(`${hotUpdateChunkTemplate.outputOptions.library}`);
<ide> });
<ide> }
<ide> }
<ide><path>lib/JsonpMainTemplatePlugin.js
<ide> const Template = require("./Template");
<ide> class JsonpMainTemplatePlugin {
<ide>
<ide> apply(mainTemplate) {
<del> function needChunkLoadingCode(chunk) {
<del> var otherChunksInEntry = chunk.entrypoints.some(function(entrypoint) {
<del> return entrypoint.chunks.length > 1;
<del> });
<add> const needChunkLoadingCode = chunk => {
<add> var otherChunksInEntry = chunk.entrypoints.some(entrypoint => entrypoint.chunks.length > 1);
<ide> var onDemandChunks = chunk.getNumberOfChunks() > 0;
<ide> return otherChunksInEntry || onDemandChunks;
<del> }
<del> mainTemplate.plugin("local-vars", function(source, chunk) {
<add> };
<add> mainTemplate.plugin("local-vars", (source, chunk) => {
<ide> if(needChunkLoadingCode(chunk)) {
<del> return this.asString([
<add> return mainTemplate.asString([
<ide> source,
<ide> "",
<ide> "// objects to store loaded and loading chunks",
<ide> "var installedChunks = {",
<del> this.indent(
<add> mainTemplate.indent(
<ide> chunk.ids.map(id => `${JSON.stringify(id)}: 0`).join(",\n")
<ide> ),
<ide> "};",
<ide> class JsonpMainTemplatePlugin {
<ide> }
<ide> return source;
<ide> });
<del> mainTemplate.plugin("jsonp-script", function(_, chunk, hash) {
<del> const chunkFilename = this.outputOptions.chunkFilename;
<add> mainTemplate.plugin("jsonp-script", (_, chunk, hash) => {
<add> const chunkFilename = mainTemplate.outputOptions.chunkFilename;
<ide> const chunkMaps = chunk.getChunkMaps();
<del> const crossOriginLoading = this.outputOptions.crossOriginLoading;
<del> const chunkLoadTimeout = this.outputOptions.chunkLoadTimeout;
<del> const scriptSrcPath = this.applyPluginsWaterfall("asset-path", JSON.stringify(chunkFilename), {
<del> hash: `" + ${this.renderCurrentHashCode(hash)} + "`,
<del> hashWithLength: length => `" + ${this.renderCurrentHashCode(hash, length)} + "`,
<add> const crossOriginLoading = mainTemplate.outputOptions.crossOriginLoading;
<add> const chunkLoadTimeout = mainTemplate.outputOptions.chunkLoadTimeout;
<add> const scriptSrcPath = mainTemplate.applyPluginsWaterfall("asset-path", JSON.stringify(chunkFilename), {
<add> hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`,
<add> hashWithLength: length => `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`,
<ide> chunk: {
<ide> id: "\" + chunkId + \"",
<ide> hash: `" + ${JSON.stringify(chunkMaps.hash)}[chunkId] + "`,
<ide> class JsonpMainTemplatePlugin {
<ide> name: `" + (${JSON.stringify(chunkMaps.name)}[chunkId]||chunkId) + "`
<ide> }
<ide> });
<del> return this.asString([
<add> return mainTemplate.asString([
<ide> "var script = document.createElement('script');",
<ide> "script.charset = 'utf-8';",
<ide> `script.timeout = ${chunkLoadTimeout};`,
<ide> crossOriginLoading ? `script.crossOrigin = ${JSON.stringify(crossOriginLoading)};` : "",
<del> `if (${this.requireFn}.nc) {`,
<del> this.indent(`script.setAttribute("nonce", ${this.requireFn}.nc);`),
<add> `if (${mainTemplate.requireFn}.nc) {`,
<add> mainTemplate.indent(`script.setAttribute("nonce", ${mainTemplate.requireFn}.nc);`),
<ide> "}",
<del> `script.src = ${this.requireFn}.p + ${scriptSrcPath};`,
<add> `script.src = ${mainTemplate.requireFn}.p + ${scriptSrcPath};`,
<ide> "var timeout = setTimeout(function(){",
<del> this.indent([
<add> mainTemplate.indent([
<ide> "onScriptComplete({ type: 'timeout', target: script });",
<ide> ]),
<ide> `}, ${chunkLoadTimeout});`,
<ide> "script.onerror = script.onload = onScriptComplete;",
<ide> "function onScriptComplete(event) {",
<del> this.indent([
<add> mainTemplate.indent([
<ide> "// avoid mem leaks in IE.",
<ide> "script.onerror = script.onload = null;",
<ide> "clearTimeout(timeout);",
<ide> "var chunk = installedChunks[chunkId];",
<ide> "if(chunk !== 0) {",
<del> this.indent([
<add> mainTemplate.indent([
<ide> "if(chunk) {",
<del> this.indent([
<add> mainTemplate.indent([
<ide> "var errorType = event && (event.type === 'load' ? 'missing' : event.type);",
<ide> "var realSrc = event && event.target && event.target.src;",
<ide> "var error = new Error('Loading chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')');",
<ide> class JsonpMainTemplatePlugin {
<ide> "};",
<ide> ]);
<ide> });
<del> mainTemplate.plugin("require-ensure", function(_, chunk, hash) {
<del> return this.asString([
<add> mainTemplate.plugin("require-ensure", (_, chunk, hash) => {
<add> return mainTemplate.asString([
<ide> "var installedChunkData = installedChunks[chunkId];",
<ide> "if(installedChunkData === 0) {",
<del> this.indent([
<add> mainTemplate.indent([
<ide> "return new Promise(function(resolve) { resolve(); });"
<ide> ]),
<ide> "}",
<ide> "",
<ide> "// a Promise means \"currently loading\".",
<ide> "if(installedChunkData) {",
<del> this.indent([
<add> mainTemplate.indent([
<ide> "return installedChunkData[2];"
<ide> ]),
<ide> "}",
<ide> "",
<ide> "// setup Promise in chunk cache",
<ide> "var promise = new Promise(function(resolve, reject) {",
<del> this.indent([
<add> mainTemplate.indent([
<ide> "installedChunkData = installedChunks[chunkId] = [resolve, reject];"
<ide> ]),
<ide> "});",
<ide> "installedChunkData[2] = promise;",
<ide> "",
<ide> "// start chunk loading",
<ide> "var head = document.getElementsByTagName('head')[0];",
<del> this.applyPluginsWaterfall("jsonp-script", "", chunk, hash),
<add> mainTemplate.applyPluginsWaterfall("jsonp-script", "", chunk, hash),
<ide> "head.appendChild(script);",
<ide> "",
<ide> "return promise;"
<ide> ]);
<ide> });
<del> mainTemplate.plugin("require-extensions", function(source, chunk) {
<add> mainTemplate.plugin("require-extensions", (source, chunk) => {
<ide> if(chunk.getNumberOfChunks() === 0) return source;
<ide>
<del> return this.asString([
<add> return mainTemplate.asString([
<ide> source,
<ide> "",
<ide> "// on error function for async loading",
<del> `${this.requireFn}.oe = function(err) { console.error(err); throw err; };`
<add> `${mainTemplate.requireFn}.oe = function(err) { console.error(err); throw err; };`
<ide> ]);
<ide> });
<del> mainTemplate.plugin("bootstrap", function(source, chunk, hash) {
<add> mainTemplate.plugin("bootstrap", (source, chunk, hash) => {
<ide> if(needChunkLoadingCode(chunk)) {
<del> return this.asString([
<add> return mainTemplate.asString([
<ide> source,
<ide> "",
<ide> "// install a JSONP callback for chunk loading",
<ide> "function webpackJsonpCallback(data) {",
<del> this.indent([
<add> mainTemplate.indent([
<ide> "var chunkIds = data[0], moreModules = data[1], executeModules = data[2];",
<ide> "// add \"moreModules\" to the modules object,",
<ide> "// then flag all \"chunkIds\" as loaded and fire callback",
<ide> "var moduleId, chunkId, i = 0, resolves = [], result;",
<ide> "for(;i < chunkIds.length; i++) {",
<del> this.indent([
<add> mainTemplate.indent([
<ide> "chunkId = chunkIds[i];",
<ide> "if(installedChunks[chunkId]) {",
<del> this.indent("resolves.push(installedChunks[chunkId][0]);"),
<add> mainTemplate.indent("resolves.push(installedChunks[chunkId][0]);"),
<ide> "}",
<ide> "installedChunks[chunkId] = 0;"
<ide> ]),
<ide> "}",
<ide> "for(moduleId in moreModules) {",
<del> this.indent([
<add> mainTemplate.indent([
<ide> "if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) {",
<del> this.indent(this.renderAddModule(hash, chunk, "moduleId", "moreModules[moduleId]")),
<add> mainTemplate.indent(mainTemplate.renderAddModule(hash, chunk, "moduleId", "moreModules[moduleId]")),
<ide> "}"
<ide> ]),
<ide> "}",
<ide> "if(parentJsonpFunction) parentJsonpFunction(data);",
<ide> "while(resolves.length) {",
<del> this.indent("resolves.shift()();"),
<add> mainTemplate.indent("resolves.shift()();"),
<ide> "}",
<del> this.entryPointInChildren(chunk) ? [
<add> mainTemplate.entryPointInChildren(chunk) ? [
<ide> "scheduledModules.push.apply(scheduledModules, executeModules || []);",
<ide> "",
<ide> "for(i = 0; i < scheduledModules.length; i++) {",
<del> this.indent([
<add> mainTemplate.indent([
<ide> "var scheduledModule = scheduledModules[i];",
<ide> "var fullfilled = true;",
<ide> "for(var j = 1; j < scheduledModule.length; j++) {",
<del> this.indent([
<add> mainTemplate.indent([
<ide> "var depId = scheduledModule[j];",
<ide> "if(installedChunks[depId] !== 0) fullfilled = false;"
<ide> ]),
<ide> "}",
<ide> "if(fullfilled) {",
<del> this.indent([
<add> mainTemplate.indent([
<ide> "scheduledModules.splice(i--, 1);",
<del> "result = " + this.requireFn + "(" + this.requireFn + ".s = scheduledModule[0]);",
<add> "result = " + mainTemplate.requireFn + "(" + mainTemplate.requireFn + ".s = scheduledModule[0]);",
<ide> ]),
<ide> "}"
<ide> ]),
<ide> class JsonpMainTemplatePlugin {
<ide> }
<ide> return source;
<ide> });
<del> mainTemplate.plugin("startup", function(source, chunk, hash) {
<add> mainTemplate.plugin("startup", (source, chunk, hash) => {
<ide> if(needChunkLoadingCode(chunk)) {
<del> var jsonpFunction = this.outputOptions.jsonpFunction;
<del> return this.asString([
<add> var jsonpFunction = mainTemplate.outputOptions.jsonpFunction;
<add> return mainTemplate.asString([
<ide> `var jsonpArray = window[${JSON.stringify(jsonpFunction)}] = window[${JSON.stringify(jsonpFunction)}] || [];`,
<ide> "var parentJsonpFunction = jsonpArray.push.bind(jsonpArray);",
<ide> "jsonpArray.push = webpackJsonpCallback;",
<ide> class JsonpMainTemplatePlugin {
<ide> }
<ide> return source;
<ide> });
<del> mainTemplate.plugin("hot-bootstrap", function(source, chunk, hash) {
<del> const hotUpdateChunkFilename = this.outputOptions.hotUpdateChunkFilename;
<del> const hotUpdateMainFilename = this.outputOptions.hotUpdateMainFilename;
<del> const crossOriginLoading = this.outputOptions.crossOriginLoading;
<del> const hotUpdateFunction = this.outputOptions.hotUpdateFunction;
<del> const currentHotUpdateChunkFilename = this.applyPluginsWaterfall("asset-path", JSON.stringify(hotUpdateChunkFilename), {
<del> hash: `" + ${this.renderCurrentHashCode(hash)} + "`,
<del> hashWithLength: length => `" + ${this.renderCurrentHashCode(hash, length)} + "`,
<add> mainTemplate.plugin("hot-bootstrap", (source, chunk, hash) => {
<add> const hotUpdateChunkFilename = mainTemplate.outputOptions.hotUpdateChunkFilename;
<add> const hotUpdateMainFilename = mainTemplate.outputOptions.hotUpdateMainFilename;
<add> const crossOriginLoading = mainTemplate.outputOptions.crossOriginLoading;
<add> const hotUpdateFunction = mainTemplate.outputOptions.hotUpdateFunction;
<add> const currentHotUpdateChunkFilename = mainTemplate.applyPluginsWaterfall("asset-path", JSON.stringify(hotUpdateChunkFilename), {
<add> hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`,
<add> hashWithLength: length => `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`,
<ide> chunk: {
<ide> id: "\" + chunkId + \""
<ide> }
<ide> });
<del> const currentHotUpdateMainFilename = this.applyPluginsWaterfall("asset-path", JSON.stringify(hotUpdateMainFilename), {
<del> hash: `" + ${this.renderCurrentHashCode(hash)} + "`,
<del> hashWithLength: length => `" + ${this.renderCurrentHashCode(hash, length)} + "`
<add> const currentHotUpdateMainFilename = mainTemplate.applyPluginsWaterfall("asset-path", JSON.stringify(hotUpdateMainFilename), {
<add> hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`,
<add> hashWithLength: length => `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`
<ide> });
<ide> const runtimeSource = Template.getFunctionContent(require("./JsonpMainTemplate.runtime.js"))
<ide> .replace(/\/\/\$semicolon/g, ";")
<del> .replace(/\$require\$/g, this.requireFn)
<add> .replace(/\$require\$/g, mainTemplate.requireFn)
<ide> .replace(/\$crossOriginLoading\$/g, crossOriginLoading ? `script.crossOrigin = ${JSON.stringify(crossOriginLoading)}` : "")
<ide> .replace(/\$hotMainFilename\$/g, currentHotUpdateMainFilename)
<ide> .replace(/\$hotChunkFilename\$/g, currentHotUpdateChunkFilename)
<ide> function hotDisposeChunk(chunkId) {
<ide> var parentHotUpdateCallback = this[${JSON.stringify(hotUpdateFunction)}];
<ide> this[${JSON.stringify(hotUpdateFunction)}] = ${runtimeSource}`;
<ide> });
<del> mainTemplate.plugin("hash", function(hash) {
<add> mainTemplate.plugin("hash", hash => {
<ide> hash.update("jsonp");
<ide> hash.update("5");
<del> hash.update(`${this.outputOptions.filename}`);
<del> hash.update(`${this.outputOptions.chunkFilename}`);
<del> hash.update(`${this.outputOptions.jsonpFunction}`);
<del> hash.update(`${this.outputOptions.hotUpdateFunction}`);
<add> hash.update(`${mainTemplate.outputOptions.filename}`);
<add> hash.update(`${mainTemplate.outputOptions.chunkFilename}`);
<add> hash.update(`${mainTemplate.outputOptions.jsonpFunction}`);
<add> hash.update(`${mainTemplate.outputOptions.hotUpdateFunction}`);
<ide> });
<ide> }
<ide> }
<ide><path>lib/LibraryTemplatePlugin.js
<ide>
<ide> const SetVarMainTemplatePlugin = require("./SetVarMainTemplatePlugin");
<ide>
<del>function accessorToObjectAccess(accessor) {
<add>const accessorToObjectAccess = (accessor) => {
<ide> return accessor.map((a) => {
<ide> return `[${JSON.stringify(a)}]`;
<ide> }).join("");
<del>}
<add>};
<ide>
<del>function accessorAccess(base, accessor, joinWith) {
<add>const accessorAccess = (base, accessor, joinWith) => {
<ide> accessor = [].concat(accessor);
<ide> return accessor.map((a, idx) => {
<ide> a = base ?
<ide> function accessorAccess(base, accessor, joinWith) {
<ide> if(idx === 0 && typeof base === "undefined") return `${a} = typeof ${a} === "object" ? ${a} : {}`;
<ide> return `${a} = ${a} || {}`;
<ide> }).join(joinWith || "; ");
<del>}
<add>};
<ide>
<ide> class LibraryTemplatePlugin {
<ide>
<ide><path>lib/ModuleFilenameHelpers.js
<ide> ModuleFilenameHelpers.REGEXP_ID = /\[id\]/gi;
<ide> ModuleFilenameHelpers.HASH = "[hash]";
<ide> ModuleFilenameHelpers.REGEXP_HASH = /\[hash\]/gi;
<ide>
<del>function getAfter(str, token) {
<add>const getAfter = (str, token) => {
<ide> const idx = str.indexOf(token);
<ide> return idx < 0 ? "" : str.substr(idx);
<del>}
<add>};
<ide>
<del>function getBefore(str, token) {
<add>const getBefore = (str, token) => {
<ide> const idx = str.lastIndexOf(token);
<ide> return idx < 0 ? "" : str.substr(0, idx);
<del>}
<add>};
<ide>
<del>function getHash(str) {
<add>const getHash = str => {
<ide> const hash = require("crypto").createHash("md5");
<ide> hash.update(str);
<ide> return hash.digest("hex").substr(0, 4);
<del>}
<add>};
<ide>
<del>function asRegExp(test) {
<add>const asRegExp = test => {
<ide> if(typeof test === "string") test = new RegExp("^" + test.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"));
<ide> return test;
<del>}
<add>};
<ide>
<del>ModuleFilenameHelpers.createFilename = function createFilename(module, moduleFilenameTemplate, requestShortener) {
<add>ModuleFilenameHelpers.createFilename = (module, moduleFilenameTemplate, requestShortener) => {
<ide> let absoluteResourcePath;
<ide> let hash;
<ide> let identifier;
<ide> ModuleFilenameHelpers.createFilename = function createFilename(module, moduleFil
<ide> .replace(ModuleFilenameHelpers.REGEXP_HASH, hash);
<ide> };
<ide>
<del>ModuleFilenameHelpers.createFooter = function createFooter(module, requestShortener) {
<add>ModuleFilenameHelpers.createFooter = (module, requestShortener) => {
<ide> if(!module) module = "";
<ide> if(typeof module === "string") {
<ide> return [
<ide> ModuleFilenameHelpers.createFooter = function createFooter(module, requestShorte
<ide> }
<ide> };
<ide>
<del>ModuleFilenameHelpers.replaceDuplicates = function replaceDuplicates(array, fn, comparator) {
<add>ModuleFilenameHelpers.replaceDuplicates = (array, fn, comparator) => {
<ide> const countMap = Object.create(null);
<ide> const posMap = Object.create(null);
<ide> array.forEach((item, idx) => {
<ide> ModuleFilenameHelpers.replaceDuplicates = function replaceDuplicates(array, fn,
<ide> });
<ide> };
<ide>
<del>ModuleFilenameHelpers.matchPart = function matchPart(str, test) {
<add>ModuleFilenameHelpers.matchPart = (str, test) => {
<ide> if(!test) return true;
<ide> test = asRegExp(test);
<ide> if(Array.isArray(test)) {
<del> return test.map(asRegExp).filter(function(regExp) {
<del> return regExp.test(str);
<del> }).length > 0;
<add> return test.map(asRegExp).some(regExp => regExp.test(str));
<ide> } else {
<ide> return test.test(str);
<ide> }
<ide> };
<ide>
<del>ModuleFilenameHelpers.matchObject = function matchObject(obj, str) {
<add>ModuleFilenameHelpers.matchObject = (obj, str) => {
<ide> if(obj.test)
<ide> if(!ModuleFilenameHelpers.matchPart(str, obj.test)) return false;
<ide> if(obj.include)
<ide><path>lib/MultiModule.js
<ide> class MultiModule extends Module {
<ide>
<ide> source(dependencyTemplates, outputOptions) {
<ide> const str = [];
<del> this.dependencies.forEach(function(dep, idx) {
<add> this.dependencies.forEach((dep, idx) => {
<ide> if(dep.module) {
<ide> if(idx === this.dependencies.length - 1)
<ide> str.push("module.exports = ");
<ide> class MultiModule extends Module {
<ide> str.push(`${JSON.stringify(dep.module.id)}`);
<ide> str.push(")");
<ide> } else {
<add> // TODO replace with WebpackMissingModule module
<ide> str.push("(function webpackMissingModule() { throw new Error(");
<ide> str.push(JSON.stringify(`Cannot find module "${dep.request}"`));
<ide> str.push("); }())");
<ide><path>lib/NewWatchingPlugin.js
<ide>
<ide> class NewWatchingPlugin {
<ide> apply(compiler) {
<del> compiler.plugin("compilation", function(compilation) {
<add> compiler.plugin("compilation", compilation => {
<ide> compilation.warnings.push(new Error("The 'NewWatchingPlugin' is no longer necessary (now default)"));
<ide> });
<ide> }
<ide><path>lib/NodeStuffPlugin.js
<ide> class NodeStuffPlugin {
<ide> if(parserOptions.node)
<ide> localOptions = Object.assign({}, localOptions, parserOptions.node);
<ide>
<del> function setConstant(expressionName, value) {
<del> parser.plugin(`expression ${expressionName}`, function() {
<del> this.state.current.addVariable(expressionName, JSON.stringify(value));
<add> const setConstant = (expressionName, value) => {
<add> parser.plugin(`expression ${expressionName}`, () => {
<add> parser.state.current.addVariable(expressionName, JSON.stringify(value));
<ide> return true;
<ide> });
<del> }
<add> };
<ide>
<del> function setModuleConstant(expressionName, fn) {
<del> parser.plugin(`expression ${expressionName}`, function() {
<del> this.state.current.addVariable(expressionName, JSON.stringify(fn(this.state.module)));
<add> const setModuleConstant = (expressionName, fn) => {
<add> parser.plugin(`expression ${expressionName}`, () => {
<add> parser.state.current.addVariable(expressionName, JSON.stringify(fn(parser.state.module)));
<ide> return true;
<ide> });
<del> }
<add> };
<ide> const context = compiler.context;
<ide> if(localOptions.__filename === "mock") {
<ide> setConstant("__filename", "/index.js");
<ide> } else if(localOptions.__filename) {
<ide> setModuleConstant("__filename", module => path.relative(context, module.resource));
<ide> }
<del> parser.plugin("evaluate Identifier __filename", function(expr) {
<del> if(!this.state.module) return;
<del> const resource = this.state.module.resource;
<add> parser.plugin("evaluate Identifier __filename", expr => {
<add> if(!parser.state.module) return;
<add> const resource = parser.state.module.resource;
<ide> const i = resource.indexOf("?");
<ide> return ParserHelpers.evaluateToString(i < 0 ? resource : resource.substr(0, i))(expr);
<ide> });
<ide> class NodeStuffPlugin {
<ide> } else if(localOptions.__dirname) {
<ide> setModuleConstant("__dirname", module => path.relative(context, module.context));
<ide> }
<del> parser.plugin("evaluate Identifier __dirname", function(expr) {
<del> if(!this.state.module) return;
<del> return ParserHelpers.evaluateToString(this.state.module.context)(expr);
<add> parser.plugin("evaluate Identifier __dirname", expr => {
<add> if(!parser.state.module) return;
<add> return ParserHelpers.evaluateToString(parser.state.module.context)(expr);
<ide> });
<ide> parser.plugin("expression require.main", ParserHelpers.toConstantDependency("__webpack_require__.c[__webpack_require__.s]"));
<ide> parser.plugin(
<ide> class NodeStuffPlugin {
<ide> );
<ide> parser.plugin("expression module.loaded", ParserHelpers.toConstantDependency("module.l"));
<ide> parser.plugin("expression module.id", ParserHelpers.toConstantDependency("module.i"));
<del> parser.plugin("expression module.exports", function() {
<del> const module = this.state.module;
<add> parser.plugin("expression module.exports", () => {
<add> const module = parser.state.module;
<ide> const isHarmony = module.meta && module.meta.harmonyModule;
<ide> if(!isHarmony)
<ide> return true;
<ide> });
<ide> parser.plugin("evaluate Identifier module.hot", ParserHelpers.evaluateToIdentifier("module.hot", false));
<del> parser.plugin("expression module", function() {
<del> const module = this.state.module;
<add> parser.plugin("expression module", () => {
<add> const module = parser.state.module;
<ide> const isHarmony = module.meta && module.meta.harmonyModule;
<ide> let moduleJsPath = path.join(__dirname, "..", "buildin", isHarmony ? "harmony-module.js" : "module.js");
<ide> if(module.context) {
<del> moduleJsPath = path.relative(this.state.module.context, moduleJsPath);
<add> moduleJsPath = path.relative(parser.state.module.context, moduleJsPath);
<ide> if(!/^[A-Z]:/i.test(moduleJsPath)) {
<ide> moduleJsPath = `./${moduleJsPath.replace(/\\/g, "/")}`;
<ide> }
<ide> }
<del> return ParserHelpers.addParsedVariableToModule(this, "module", `require(${JSON.stringify(moduleJsPath)})(module)`);
<add> return ParserHelpers.addParsedVariableToModule(parser, "module", `require(${JSON.stringify(moduleJsPath)})(module)`);
<ide> });
<ide> });
<ide> });
<ide><path>lib/NormalModule.js
<ide> const ModuleWarning = require("./ModuleWarning");
<ide> const runLoaders = require("loader-runner").runLoaders;
<ide> const getContext = require("loader-runner").getContext;
<ide>
<del>function asString(buf) {
<add>const asString = (buf) => {
<ide> if(Buffer.isBuffer(buf)) {
<ide> return buf.toString("utf-8");
<ide> }
<ide> return buf;
<del>}
<add>};
<ide>
<del>function contextify(context, request) {
<del> return request.split("!").map(function(r) {
<add>const contextify = (context, request) => {
<add> return request.split("!").map(r => {
<ide> const splitPath = r.split("?");
<ide> splitPath[0] = path.relative(context, splitPath[0]);
<ide> if(path.sep === "\\")
<ide> function contextify(context, request) {
<ide> splitPath[0] = "./" + splitPath[0];
<ide> return splitPath.join("?");
<ide> }).join("!");
<del>}
<add>};
<ide>
<ide> class NonErrorEmittedError extends WebpackError {
<ide> constructor(error) {
<ide><path>lib/NormalModuleFactory.js
<ide> const RawModule = require("./RawModule");
<ide> const Parser = require("./Parser");
<ide> const RuleSet = require("./RuleSet");
<ide>
<del>function loaderToIdent(data) {
<add>const loaderToIdent = data => {
<ide> if(!data.options)
<ide> return data.loader;
<ide> if(typeof data.options === "string")
<ide> function loaderToIdent(data) {
<ide> if(data.ident)
<ide> return data.loader + "??" + data.ident;
<ide> return data.loader + "?" + JSON.stringify(data.options);
<del>}
<add>};
<ide>
<del>function identToLoaderRequest(resultString) {
<add>const identToLoaderRequest = resultString => {
<ide> const idx = resultString.indexOf("?");
<ide> let options;
<ide>
<ide> function identToLoaderRequest(resultString) {
<ide> loader: resultString
<ide> };
<ide> }
<del>}
<add>};
<ide>
<ide> class NormalModuleFactory extends Tapable {
<ide> constructor(context, resolvers, options) {
<ide><path>lib/OptionsDefaulter.js
<ide> */
<ide> "use strict";
<ide>
<del>function getProperty(obj, name) {
<add>const getProperty = (obj, name) => {
<ide> name = name.split(".");
<ide> for(var i = 0; i < name.length - 1; i++) {
<ide> obj = obj[name[i]];
<ide> if(typeof obj !== "object" || !obj) return;
<ide> }
<ide> return obj[name.pop()];
<del>}
<add>};
<ide>
<del>function setProperty(obj, name, value) {
<add>const setProperty = (obj, name, value) => {
<ide> name = name.split(".");
<ide> for(var i = 0; i < name.length - 1; i++) {
<ide> if(typeof obj[name[i]] !== "object" && typeof obj[name[i]] !== "undefined") return;
<ide> if(!obj[name[i]]) obj[name[i]] = {};
<ide> obj = obj[name[i]];
<ide> }
<ide> obj[name.pop()] = value;
<del>}
<add>};
<ide>
<ide> class OptionsDefaulter {
<ide> constructor() {
<ide> class OptionsDefaulter {
<ide> {
<ide> let oldValue = getProperty(options, name);
<ide> if(!Array.isArray(oldValue)) oldValue = [];
<del> oldValue.push.apply(oldValue, this.defaults[name]);
<add> oldValue.push(...this.defaults[name]);
<ide> setProperty(options, name, oldValue);
<ide> break;
<ide> }
<ide> class OptionsDefaulter {
<ide> }
<ide>
<ide> set(name, config, def) {
<del> if(arguments.length === 3) {
<add> if(def !== undefined) {
<ide> this.defaults[name] = def;
<ide> this.config[name] = config;
<ide> } else {
<ide><path>lib/Parser.js
<ide> const vm = require("vm");
<ide> const BasicEvaluatedExpression = require("./BasicEvaluatedExpression");
<ide> const StackedSetMap = require("./util/StackedSetMap");
<ide>
<del>function joinRanges(startRange, endRange) {
<add>const joinRanges = (startRange, endRange) => {
<ide> if(!endRange) return startRange;
<ide> if(!startRange) return endRange;
<ide> return [startRange[0], endRange[1]];
<del>}
<add>};
<ide>
<ide> const ECMA_VERSION = 2017;
<ide>
<ide> class Parser extends Tapable {
<ide> if(expr.value instanceof RegExp)
<ide> return new BasicEvaluatedExpression().setRegExp(expr.value).setRange(expr.range);
<ide> });
<del> this.plugin("evaluate LogicalExpression", function(expr) {
<add> this.plugin("evaluate LogicalExpression", expr => {
<ide> let left;
<ide> let leftAsBool;
<ide> let right;
<ide> class Parser extends Tapable {
<ide> return right.setRange(expr.range);
<ide> }
<ide> });
<del> this.plugin("evaluate BinaryExpression", function(expr) {
<add> this.plugin("evaluate BinaryExpression", expr => {
<ide> let left;
<ide> let right;
<ide> let res;
<ide> class Parser extends Tapable {
<ide> }
<ide> }
<ide> });
<del> this.plugin("evaluate UnaryExpression", function(expr) {
<add> this.plugin("evaluate UnaryExpression", expr => {
<ide> if(expr.operator === "typeof") {
<ide> let res;
<ide> let name;
<ide> class Parser extends Tapable {
<ide> }
<ide> }
<ide> });
<del> this.plugin("evaluate typeof undefined", function(expr) {
<add> this.plugin("evaluate typeof undefined", expr => {
<ide> return new BasicEvaluatedExpression().setString("undefined").setRange(expr.range);
<ide> });
<del> this.plugin("evaluate Identifier", function(expr) {
<add> this.plugin("evaluate Identifier", expr => {
<ide> const name = this.scope.renames.get(expr.name) || expr.name;
<ide> if(!this.scope.definitions.has(expr.name)) {
<ide> const result = this.applyPluginsBailResult1("evaluate Identifier " + name, expr);
<ide> class Parser extends Tapable {
<ide> return this.applyPluginsBailResult1("evaluate defined Identifier " + name, expr);
<ide> }
<ide> });
<del> this.plugin("evaluate ThisExpression", function(expr) {
<add> this.plugin("evaluate ThisExpression", expr => {
<ide> const name = this.scope.renames.get("this");
<ide> if(name) {
<ide> const result = this.applyPluginsBailResult1("evaluate Identifier " + name, expr);
<ide> if(result) return result;
<ide> return new BasicEvaluatedExpression().setIdentifier(name).setRange(expr.range);
<ide> }
<ide> });
<del> this.plugin("evaluate MemberExpression", function(expression) {
<add> this.plugin("evaluate MemberExpression", expression => {
<ide> let exprName = this.getNameForExpression(expression);
<ide> if(exprName) {
<ide> if(exprName.free) {
<ide> class Parser extends Tapable {
<ide> }
<ide> }
<ide> });
<del> this.plugin("evaluate CallExpression", function(expr) {
<add> this.plugin("evaluate CallExpression", expr => {
<ide> if(expr.callee.type !== "MemberExpression") return;
<ide> if(expr.callee.property.type !== (expr.callee.computed ? "Literal" : "Identifier")) return;
<ide> const param = this.evaluateExpression(expr.callee.object);
<ide> if(!param) return;
<ide> const property = expr.callee.property.name || expr.callee.property.value;
<ide> return this.applyPluginsBailResult2("evaluate CallExpression ." + property, expr, param);
<ide> });
<del> this.plugin("evaluate CallExpression .replace", function(expr, param) {
<add> this.plugin("evaluate CallExpression .replace", (expr, param) => {
<ide> if(!param.isString()) return;
<ide> if(expr.arguments.length !== 2) return;
<ide> let arg1 = this.evaluateExpression(expr.arguments[0]);
<ide> class Parser extends Tapable {
<ide> return new BasicEvaluatedExpression().setString(param.string.replace(arg1, arg2)).setRange(expr.range);
<ide> });
<ide> ["substr", "substring"].forEach(fn => {
<del> this.plugin("evaluate CallExpression ." + fn, function(expr, param) {
<add> this.plugin("evaluate CallExpression ." + fn, (expr, param) => {
<ide> if(!param.isString()) return;
<ide> let arg1;
<ide> let result, str = param.string;
<ide> class Parser extends Tapable {
<ide> * @param {any[]} expressions expressions
<ide> * @return {BasicEvaluatedExpression[]} Simplified template
<ide> */
<del> function getSimplifiedTemplateResult(kind, quasis, expressions) {
<add> const getSimplifiedTemplateResult = (kind, quasis, expressions) => {
<ide> const parts = [];
<ide>
<ide> for(let i = 0; i < quasis.length; i++) {
<ide> class Parser extends Tapable {
<ide> }
<ide> }
<ide> return parts;
<del> }
<add> };
<ide>
<del> this.plugin("evaluate TemplateLiteral", function(node) {
<add> this.plugin("evaluate TemplateLiteral", node => {
<ide> const parts = getSimplifiedTemplateResult.call(this, "cooked", node.quasis, node.expressions);
<ide> if(parts.length === 1) {
<ide> return parts[0].setRange(node.range);
<ide> }
<ide> return new BasicEvaluatedExpression().setTemplateString(parts).setRange(node.range);
<ide> });
<del> this.plugin("evaluate TaggedTemplateExpression", function(node) {
<add> this.plugin("evaluate TaggedTemplateExpression", node => {
<ide> if(this.evaluateExpression(node.tag).identifier !== "String.raw") return;
<ide> const parts = getSimplifiedTemplateResult.call(this, "raw", node.quasi.quasis, node.quasi.expressions);
<ide> return new BasicEvaluatedExpression().setTemplateString(parts).setRange(node.range);
<ide> });
<ide>
<del> this.plugin("evaluate CallExpression .concat", function(expr, param) {
<add> this.plugin("evaluate CallExpression .concat", (expr, param) => {
<ide> if(!param.isString() && !param.isWrapped()) return;
<ide>
<ide> let stringSuffix = null;
<ide> class Parser extends Tapable {
<ide> return new BasicEvaluatedExpression().setString(newString).setRange(expr.range);
<ide> }
<ide> });
<del> this.plugin("evaluate CallExpression .split", function(expr, param) {
<add> this.plugin("evaluate CallExpression .split", (expr, param) => {
<ide> if(!param.isString()) return;
<ide> if(expr.arguments.length !== 1) return;
<ide> let result;
<ide> class Parser extends Tapable {
<ide> } else return;
<ide> return new BasicEvaluatedExpression().setArray(result).setRange(expr.range);
<ide> });
<del> this.plugin("evaluate ConditionalExpression", function(expr) {
<add> this.plugin("evaluate ConditionalExpression", expr => {
<ide> const condition = this.evaluateExpression(expr.test);
<ide> const conditionValue = condition.asBool();
<ide> let res;
<ide> class Parser extends Tapable {
<ide> res.setRange(expr.range);
<ide> return res;
<ide> });
<del> this.plugin("evaluate ArrayExpression", function(expr) {
<del> const items = expr.elements.map(function(element) {
<del> return element !== null && this.evaluateExpression(element);
<add> this.plugin("evaluate ArrayExpression", expr => {
<add> const items = expr.elements.map(element => {
<add> return element !== null && this.evaluateExpression(element);
<ide> }, this);
<ide> if(!items.every(Boolean)) return;
<ide> return new BasicEvaluatedExpression().setItems(items).setRange(expr.range);
<ide> class Parser extends Tapable {
<ide> prewalkImportDeclaration(statement) {
<ide> const source = statement.source.value;
<ide> this.applyPluginsBailResult2("import", statement, source);
<del> statement.specifiers.forEach(function(specifier) {
<add> statement.specifiers.forEach(specifier => {
<ide> const name = specifier.local.name;
<ide> this.scope.renames.set(name, null);
<ide> this.scope.definitions.add(name);
<ide> class Parser extends Tapable {
<ide> walkCallExpression(expression) {
<ide> let result;
<ide>
<del> function walkIIFE(functionExpression, options, currentThis) {
<del> function renameArgOrThis(argOrThis) {
<add> const walkIIFE = (functionExpression, options, currentThis) => {
<add> const renameArgOrThis = argOrThis => {
<ide> const renameIdentifier = this.getRenameIdentifier(argOrThis);
<ide> if(renameIdentifier && this.applyPluginsBailResult1("can-rename " + renameIdentifier, argOrThis)) {
<ide> if(!this.applyPluginsBailResult1("rename " + renameIdentifier, argOrThis))
<ide> return renameIdentifier;
<ide> }
<ide> this.walkExpression(argOrThis);
<del> }
<add> };
<ide> const params = functionExpression.params;
<ide> const renameThis = currentThis ? renameArgOrThis.call(this, currentThis) : null;
<ide> const args = options.map(renameArgOrThis, this);
<del> this.inScope(params.filter(function(identifier, idx) {
<del> return !args[idx];
<del> }), () => {
<add> this.inScope(params.filter((identifier, idx) => !args[idx]), () => {
<ide> if(renameThis) {
<ide> this.scope.renames.set("this", renameThis);
<ide> }
<ide> class Parser extends Tapable {
<ide> } else
<ide> this.walkExpression(functionExpression.body);
<ide> });
<del> }
<add> };
<ide> if(expression.callee.type === "MemberExpression" &&
<ide> expression.callee.object.type === "FunctionExpression" &&
<ide> !expression.callee.computed &&
<ide> class Parser extends Tapable {
<ide> const alternate = this.parseCalculatedString(expression.alternate);
<ide> const items = [];
<ide> if(consequent.conditional)
<del> Array.prototype.push.apply(items, consequent.conditional);
<add> items.push(...consequent.conditional);
<ide> else if(!consequent.code)
<ide> items.push(consequent);
<ide> else break;
<ide> if(alternate.conditional)
<del> Array.prototype.push.apply(items, alternate.conditional);
<add> items.push(...alternate.conditional);
<ide> else if(!alternate.code)
<ide> items.push(alternate);
<ide> else break;
<ide> class Parser extends Tapable {
<ide>
<ide> const arr = [];
<ide> if(expression.elements)
<del> expression.elements.forEach(function(expr) {
<add> expression.elements.forEach(expr => {
<ide> arr.push(this.parseString(expr));
<ide> }, this);
<ide> return arr;
<ide> class Parser extends Tapable {
<ide>
<ide> const arr = [];
<ide> if(expression.elements)
<del> expression.elements.forEach(function(expr) {
<add> expression.elements.forEach(expr => {
<ide> arr.push(this.parseCalculatedString(expr));
<ide> }, this);
<ide> return arr;
<ide><path>lib/ParserHelpers.js
<ide> const UnsupportedFeatureWarning = require("./UnsupportedFeatureWarning");
<ide>
<ide> const ParserHelpers = exports;
<ide>
<del>ParserHelpers.addParsedVariableToModule = function(parser, name, expression) {
<add>ParserHelpers.addParsedVariableToModule = (parser, name, expression) => {
<ide> if(!parser.state.current.addVariable) return false;
<ide> var deps = [];
<ide> parser.parse(expression, {
<ide> current: {
<del> addDependency: function(dep) {
<add> addDependency: dep => {
<ide> dep.userRequest = name;
<ide> deps.push(dep);
<ide> }
<ide> ParserHelpers.addParsedVariableToModule = function(parser, name, expression) {
<ide> return true;
<ide> };
<ide>
<del>ParserHelpers.requireFileAsExpression = function(context, pathToModule) {
<add>ParserHelpers.requireFileAsExpression = (context, pathToModule) => {
<ide> var moduleJsPath = path.relative(context, pathToModule);
<ide> if(!/^[A-Z]:/i.test(moduleJsPath)) {
<ide> moduleJsPath = "./" + moduleJsPath.replace(/\\/g, "/");
<ide> }
<ide> return "require(" + JSON.stringify(moduleJsPath) + ")";
<ide> };
<ide>
<del>ParserHelpers.toConstantDependency = function(value) {
<add>ParserHelpers.toConstantDependency = value => {
<ide> return function constDependency(expr) {
<ide> var dep = new ConstDependency(value, expr.range);
<ide> dep.loc = expr.loc;
<ide> ParserHelpers.toConstantDependency = function(value) {
<ide> };
<ide> };
<ide>
<del>ParserHelpers.evaluateToString = function(value) {
<add>ParserHelpers.evaluateToString = value => {
<ide> return function stringExpression(expr) {
<ide> return new BasicEvaluatedExpression().setString(value).setRange(expr.range);
<ide> };
<ide> };
<ide>
<del>ParserHelpers.evaluateToBoolean = function(value) {
<add>ParserHelpers.evaluateToBoolean = value => {
<ide> return function booleanExpression(expr) {
<ide> return new BasicEvaluatedExpression().setBoolean(value).setRange(expr.range);
<ide> };
<ide> };
<ide>
<del>ParserHelpers.evaluateToIdentifier = function(identifier, truthy) {
<add>ParserHelpers.evaluateToIdentifier = (identifier, truthy) => {
<ide> return function identifierExpression(expr) {
<ide> let evex = new BasicEvaluatedExpression().setIdentifier(identifier).setRange(expr.range);
<ide> if(truthy === true) evex = evex.setTruthy();
<ide> ParserHelpers.evaluateToIdentifier = function(identifier, truthy) {
<ide> };
<ide> };
<ide>
<del>ParserHelpers.expressionIsUnsupported = function(message) {
<add>ParserHelpers.expressionIsUnsupported = (message) => {
<ide> return function unsupportedExpression(expr) {
<ide> var dep = new ConstDependency("(void 0)", expr.range);
<ide> dep.loc = expr.loc;
<ide><path>lib/ProgressPlugin.js
<ide> */
<ide> "use strict";
<ide>
<add>const createDefaultHandler = profile => {
<add>
<add> let lineCaretPosition = 0;
<add> let lastState;
<add> let lastStateTime;
<add>
<add> const defaultHandler = (percentage, msg, ...args) => {
<add> let state = msg;
<add> const details = args;
<add> if(percentage < 1) {
<add> percentage = Math.floor(percentage * 100);
<add> msg = `${percentage}% ${msg}`;
<add> if(percentage < 100) {
<add> msg = ` ${msg}`;
<add> }
<add> if(percentage < 10) {
<add> msg = ` ${msg}`;
<add> }
<add> details.forEach(detail => {
<add> if(!detail) return;
<add> if(detail.length > 40) {
<add> detail = `...${detail.substr(detail.length - 37)}`;
<add> }
<add> msg += ` ${detail}`;
<add> });
<add> }
<add> if(profile) {
<add> state = state.replace(/^\d+\/\d+\s+/, "");
<add> if(percentage === 0) {
<add> lastState = null;
<add> lastStateTime = Date.now();
<add> } else if(state !== lastState || percentage === 1) {
<add> const now = Date.now();
<add> if(lastState) {
<add> const stateMsg = `${now - lastStateTime}ms ${lastState}`;
<add> goToLineStart(stateMsg);
<add> process.stderr.write(stateMsg + "\n");
<add> lineCaretPosition = 0;
<add> }
<add> lastState = state;
<add> lastStateTime = now;
<add> }
<add> }
<add> goToLineStart(msg);
<add> process.stderr.write(msg);
<add> };
<add>
<add> const goToLineStart = nextMessage => {
<add> let str = "";
<add> for(; lineCaretPosition > nextMessage.length; lineCaretPosition--) {
<add> str += "\b \b";
<add> }
<add> for(var i = 0; i < lineCaretPosition; i++) {
<add> str += "\b";
<add> }
<add> lineCaretPosition = nextMessage.length;
<add> if(str) process.stderr.write(str);
<add> };
<add>
<add> return defaultHandler;
<add>
<add>};
<add>
<add>
<ide> class ProgressPlugin {
<ide>
<ide> constructor(options) {
<ide> class ProgressPlugin {
<ide> }
<ide>
<ide> apply(compiler) {
<del> const handler = this.handler || defaultHandler;
<del> const profile = this.profile;
<add> const handler = this.handler || createDefaultHandler(this.profile);
<ide> if(compiler.compilers) {
<ide> const states = new Array(compiler.compilers.length);
<del> compiler.compilers.forEach(function(compiler, idx) {
<del> compiler.apply(new ProgressPlugin(function(p, msg) {
<del> states[idx] = Array.prototype.slice.apply(arguments);
<del> handler.apply(null, [
<add> compiler.compilers.forEach((compiler, idx) => {
<add> compiler.apply(new ProgressPlugin((p, msg, ...args) => {
<add> states[idx] = args;
<add> handler(
<ide> states.map(state => state && state[0] || 0).reduce((a, b) => a + b) / states.length,
<del> `[${idx}] ${msg}`
<del> ].concat(Array.prototype.slice.call(arguments, 2)));
<add> `[${idx}] ${msg}`,
<add> ...args
<add> );
<ide> }));
<ide> });
<ide> } else {
<ide> class ProgressPlugin {
<ide> let doneModules = 0;
<ide> const activeModules = [];
<ide>
<del> const update = function update(module) {
<add> const update = module => {
<ide> handler(
<ide> 0.1 + (doneModules / Math.max(lastModulesCount, moduleCount)) * 0.6,
<ide> "building modules",
<ide> class ProgressPlugin {
<ide> );
<ide> };
<ide>
<del> const moduleDone = function moduleDone(module) {
<add> const moduleDone = module => {
<ide> doneModules++;
<ide> const ident = module.identifier();
<ide> if(ident) {
<ide> class ProgressPlugin {
<ide> }
<ide> update();
<ide> };
<del> compiler.plugin("compilation", function(compilation) {
<add> compiler.plugin("compilation", compilation => {
<ide> if(compilation.compiler.isChild()) return;
<ide> lastModulesCount = moduleCount;
<ide> moduleCount = 0;
<ide> doneModules = 0;
<ide> handler(0, "compiling");
<del> compilation.plugin("build-module", function(module) {
<add> compilation.plugin("build-module", module => {
<ide> moduleCount++;
<ide> const ident = module.identifier();
<ide> if(ident) {
<ide> class ProgressPlugin {
<ide> handler(1, "");
<ide> });
<ide> }
<del>
<del> let lineCaretPosition = 0,
<del> lastState, lastStateTime;
<del>
<del> function defaultHandler(percentage, msg) {
<del> let state = msg;
<del> const details = Array.prototype.slice.call(arguments, 2);
<del> if(percentage < 1) {
<del> percentage = Math.floor(percentage * 100);
<del> msg = `${percentage}% ${msg}`;
<del> if(percentage < 100) {
<del> msg = ` ${msg}`;
<del> }
<del> if(percentage < 10) {
<del> msg = ` ${msg}`;
<del> }
<del> details.forEach(detail => {
<del> if(!detail) return;
<del> if(detail.length > 40) {
<del> detail = `...${detail.substr(detail.length - 37)}`;
<del> }
<del> msg += ` ${detail}`;
<del> });
<del> }
<del> if(profile) {
<del> state = state.replace(/^\d+\/\d+\s+/, "");
<del> if(percentage === 0) {
<del> lastState = null;
<del> lastStateTime = Date.now();
<del> } else if(state !== lastState || percentage === 1) {
<del> const now = Date.now();
<del> if(lastState) {
<del> const stateMsg = `${now - lastStateTime}ms ${lastState}`;
<del> goToLineStart(stateMsg);
<del> process.stderr.write(stateMsg + "\n");
<del> lineCaretPosition = 0;
<del> }
<del> lastState = state;
<del> lastStateTime = now;
<del> }
<del> }
<del> goToLineStart(msg);
<del> process.stderr.write(msg);
<del> }
<del>
<del> function goToLineStart(nextMessage) {
<del> let str = "";
<del> for(; lineCaretPosition > nextMessage.length; lineCaretPosition--) {
<del> str += "\b \b";
<del> }
<del> for(var i = 0; i < lineCaretPosition; i++) {
<del> str += "\b";
<del> }
<del> lineCaretPosition = nextMessage.length;
<del> if(str) process.stderr.write(str);
<del> }
<ide> }
<ide> }
<ide> module.exports = ProgressPlugin;
<ide><path>lib/ProvidePlugin.js
<ide> class ProvidePlugin {
<ide> parser.plugin(`can-rename ${name}`, ParserHelpers.approve);
<ide> });
<ide> }
<del> parser.plugin(`expression ${name}`, function(expr) {
<add> parser.plugin(`expression ${name}`, expr => {
<ide> let nameIdentifier = name;
<ide> const scopedName = name.indexOf(".") >= 0;
<ide> let expression = `require(${JSON.stringify(request[0])})`;
<ide> class ProvidePlugin {
<ide> if(request.length > 1) {
<ide> expression += request.slice(1).map(r => `[${JSON.stringify(r)}]`).join("");
<ide> }
<del> if(!ParserHelpers.addParsedVariableToModule(this, nameIdentifier, expression)) {
<add> if(!ParserHelpers.addParsedVariableToModule(parser, nameIdentifier, expression)) {
<ide> return false;
<ide> }
<ide> if(scopedName) {
<del> ParserHelpers.toConstantDependency(nameIdentifier).bind(this)(expr);
<add> ParserHelpers.toConstantDependency(nameIdentifier).call(parser, expr);
<ide> }
<ide> return true;
<ide> });
<ide><path>lib/RecordIdsPlugin.js
<ide> class RecordIdsPlugin {
<ide> if(!records.modules) records.modules = {};
<ide> if(!records.modules.byIdentifier) records.modules.byIdentifier = {};
<ide> if(!records.modules.usedIds) records.modules.usedIds = {};
<del> modules.forEach(function(module) {
<add> modules.forEach(module => {
<ide> let identifier = portableIdCache.get(module);
<ide> if(!identifier) portableIdCache.set(module, identifier = identifierUtils.makePathsRelative(compiler.context, module.identifier()));
<ide> records.modules.byIdentifier[identifier] = module.id;
<ide> class RecordIdsPlugin {
<ide> if(!records.modules) return;
<ide> if(records.modules.byIdentifier) {
<ide> const usedIds = {};
<del> modules.forEach(function(module) {
<add> modules.forEach(module => {
<ide> if(module.id !== null) return;
<ide> let identifier = portableIdCache.get(module);
<ide> if(!identifier) portableIdCache.set(module, identifier = identifierUtils.makePathsRelative(compiler.context, module.identifier()));
<ide> class RecordIdsPlugin {
<ide> compilation.usedModuleIds = records.modules.usedIds;
<ide> });
<ide>
<del> function getDepBlockIdent(chunk, block) {
<add> const getDepBlockIdent = (chunk, block) => {
<ide> const ident = [];
<ide> if(block.chunks.length > 1)
<ide> ident.push(block.chunks.indexOf(chunk));
<ide> class RecordIdsPlugin {
<ide> if(!block.identifier) return null;
<ide> ident.push(identifierUtils.makePathsRelative(compiler.context, block.identifier()));
<ide> return ident.reverse().join(":");
<del> }
<add> };
<add>
<ide> compilation.plugin("record-chunks", (chunks, records) => {
<ide> records.nextFreeChunkId = compilation.nextFreeChunkId;
<ide> if(!records.chunks) records.chunks = {};
<ide> class RecordIdsPlugin {
<ide> if(!records.chunks) return;
<ide> const usedIds = {};
<ide> if(records.chunks.byName) {
<del> chunks.forEach(function(chunk) {
<add> chunks.forEach(chunk => {
<ide> if(chunk.id !== null) return;
<ide> if(!chunk.name) return;
<ide> const id = records.chunks.byName[chunk.name];
<ide> class RecordIdsPlugin {
<ide> });
<ide> });
<ide> blockIdentsCount = Object.keys(blockIdentsCount).map(accessor => [blockIdentsCount[accessor]].concat(accessor.split(":").map(Number))).sort((a, b) => b[0] - a[0]);
<del> blockIdentsCount.forEach(function(arg) {
<add> blockIdentsCount.forEach(arg => {
<ide> const id = arg[1];
<ide> if(usedIds[id]) return;
<ide> const idx = arg[2];
<ide><path>lib/RequireJsStuffPlugin.js
<ide> const NullFactory = require("./NullFactory");
<ide> module.exports = class RequireJsStuffPlugin {
<ide>
<ide> apply(compiler) {
<del> compiler.plugin("compilation", function(compilation, params) {
<add> compiler.plugin("compilation", (compilation, params) => {
<ide> compilation.dependencyFactories.set(ConstDependency, new NullFactory());
<ide> compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
<del> params.normalModuleFactory.plugin("parser", function(parser, parserOptions) {
<add> params.normalModuleFactory.plugin("parser", (parser, parserOptions) => {
<ide>
<ide> if(typeof parserOptions.requireJs !== "undefined" && !parserOptions.requireJs)
<ide> return;
<ide><path>lib/RuleSet.js
<ide> normalized:
<ide>
<ide> "use strict";
<ide>
<add>const notMatcher = matcher => {
<add> return function(str) {
<add> return !matcher(str);
<add> };
<add>};
<add>
<add>const orMatcher = items => {
<add> return function(str) {
<add> for(let i = 0; i < items.length; i++) {
<add> if(items[i](str))
<add> return true;
<add> }
<add> return false;
<add> };
<add>};
<add>
<add>const andMatcher = items => {
<add> return function(str) {
<add> for(let i = 0; i < items.length; i++) {
<add> if(!items[i](str))
<add> return false;
<add> }
<add> return true;
<add> };
<add>};
<add>
<ide> module.exports = class RuleSet {
<ide> constructor(rules) {
<ide> this.references = Object.create(null);
<ide> module.exports = class RuleSet {
<ide> let resourceSource;
<ide> let condition;
<ide>
<add> const checkUseSource = newSource => {
<add> if(useSource && useSource !== newSource)
<add> throw new Error(RuleSet.buildErrorMessage(rule, new Error("Rule can only have one result source (provided " + newSource + " and " + useSource + ")")));
<add> useSource = newSource;
<add> };
<add>
<add> const checkResourceSource = newSource => {
<add> if(resourceSource && resourceSource !== newSource)
<add> throw new Error(RuleSet.buildErrorMessage(rule, new Error("Rule can only have one resource source (provided " + newSource + " and " + resourceSource + ")")));
<add> resourceSource = newSource;
<add> };
<add>
<add>
<ide> if(rule.test || rule.include || rule.exclude) {
<ide> checkResourceSource("test + include + exclude");
<ide> condition = {
<ide> module.exports = class RuleSet {
<ide> newRule[key] = rule[key];
<ide> });
<ide>
<del> function checkUseSource(newSource) {
<del> if(useSource && useSource !== newSource)
<del> throw new Error(RuleSet.buildErrorMessage(rule, new Error("Rule can only have one result source (provided " + newSource + " and " + useSource + ")")));
<del> useSource = newSource;
<del> }
<del>
<del> function checkResourceSource(newSource) {
<del> if(resourceSource && resourceSource !== newSource)
<del> throw new Error(RuleSet.buildErrorMessage(rule, new Error("Rule can only have one resource source (provided " + newSource + " and " + resourceSource + ")")));
<del> resourceSource = newSource;
<del> }
<del>
<ide> if(Array.isArray(newRule.use)) {
<ide> newRule.use.forEach((item) => {
<ide> if(item.ident) {
<ide> module.exports = class RuleSet {
<ide> return options;
<ide> }
<ide> };
<del>
<del>function notMatcher(matcher) {
<del> return function(str) {
<del> return !matcher(str);
<del> };
<del>}
<del>
<del>function orMatcher(items) {
<del> return function(str) {
<del> for(let i = 0; i < items.length; i++) {
<del> if(items[i](str))
<del> return true;
<del> }
<del> return false;
<del> };
<del>}
<del>
<del>function andMatcher(items) {
<del> return function(str) {
<del> for(let i = 0; i < items.length; i++) {
<del> if(!items[i](str))
<del> return false;
<del> }
<del> return true;
<del> };
<del>}
<ide><path>lib/SourceMapDevToolPlugin.js
<ide> const basename = (name) => {
<ide> return name.substr(name.lastIndexOf("/") + 1);
<ide> };
<ide>
<del>function getTaskForFile(file, chunk, options, compilation) {
<add>const getTaskForFile = (file, chunk, options, compilation) => {
<ide> const asset = compilation.assets[file];
<ide> if(asset.__SourceMapDevToolFile === file && asset.__SourceMapDevToolData) {
<ide> const data = asset.__SourceMapDevToolData;
<ide> function getTaskForFile(file, chunk, options, compilation) {
<ide> modules: undefined
<ide> };
<ide> }
<del>}
<add>};
<ide>
<ide> class SourceMapDevToolPlugin {
<ide> constructor(options) {
<ide> class SourceMapDevToolPlugin {
<ide> compiler.plugin("compilation", compilation => {
<ide> new SourceMapDevToolModuleOptionsPlugin(options).apply(compilation);
<ide>
<del> compilation.plugin("after-optimize-chunk-assets", function(chunks) {
<add> compilation.plugin("after-optimize-chunk-assets", chunks => {
<ide> const moduleToSourceNameMapping = new Map();
<ide> const tasks = [];
<ide>
<del> chunks.forEach(function(chunk) {
<add> chunks.forEach(chunk => {
<ide> chunk.files.forEach(file => {
<ide> if(matchObject(file)) {
<ide> const task = getTaskForFile(file, chunk, options, compilation);
<ide> class SourceMapDevToolPlugin {
<ide> moduleToSourceNameMapping.set(module, sourceName);
<ide> usedNamesSet.add(sourceName);
<ide> }
<del> tasks.forEach(function(task) {
<add> tasks.forEach(task => {
<ide> const chunk = task.chunk;
<ide> const file = task.file;
<ide> const asset = task.asset;
<ide><path>lib/Stats.js
<ide> const SizeFormatHelpers = require("./SizeFormatHelpers");
<ide> const formatLocation = require("./formatLocation");
<ide> const identifierUtils = require("./util/identifier");
<ide>
<del>const optionsOrFallback = function() {
<add>const optionsOrFallback = (...args) => {
<ide> let optionValues = [];
<del> optionValues.push.apply(optionValues, arguments);
<add> optionValues.push(...args);
<ide> return optionValues.find(optionValue => typeof optionValue !== "undefined");
<ide> };
<ide>
<ide> class Stats {
<ide> });
<ide> }
<ide>
<del> function fnModule(module) {
<add> const fnModule = module => {
<ide> const path = [];
<ide> let current = module;
<ide> while(current.issuer) {
<ide> class Stats {
<ide> obj.source = module._source.source();
<ide> }
<ide> return obj;
<del> }
<add> };
<ide> if(showChunks) {
<ide> obj.chunks = compilation.chunks.map(chunk => {
<ide> const obj = {
<ide><path>lib/Template.js
<ide> const COMMENT_END_REGEX = /\*\//g;
<ide> const PATH_NAME_NORMALIZE_REPLACE_REGEX = /[^a-zA-Z0-9_!§$()=\-^°]+/g;
<ide> const MATCH_PADDED_HYPHENS_REPLACE_REGEX = /^-|-$/g;
<ide>
<add>const stringifyIdSortPredicate = (a, b) => {
<add> var aId = a.id + "";
<add> var bId = b.id + "";
<add> if(aId < bId) return -1;
<add> if(aId > bId) return 1;
<add> return 0;
<add>};
<add>
<add>const moduleIdIsNumber = module => {
<add> return typeof module.id === "number";
<add>};
<add>
<ide> module.exports = class Template extends Tapable {
<ide> constructor(outputOptions) {
<ide> super();
<ide> module.exports = class Template extends Tapable {
<ide> return false;
<ide> var maxId = -Infinity;
<ide> var minId = Infinity;
<del> modules.forEach(function(module) {
<add> modules.forEach(module => {
<ide> if(maxId < module.id) maxId = module.id;
<ide> if(minId > module.id) minId = module.id;
<ide> });
<ide> if(minId < 16 + ("" + minId).length) {
<ide> // add minId x ',' instead of 'Array(minId).concat(...)'
<ide> minId = 0;
<ide> }
<del> var objectOverhead = modules.map(function(module) {
<add> var objectOverhead = modules.map(module => {
<ide> var idLength = (module.id + "").length;
<ide> return idLength + 2;
<del> }).reduce(function(a, b) {
<add> }).reduce((a, b) => {
<ide> return a + b;
<ide> }, -1);
<ide> var arrayOverhead = minId === 0 ? maxId : 16 + ("" + minId).length + maxId;
<ide> module.exports = class Template extends Tapable {
<ide> return source;
<ide> }
<ide> var removedModules = chunk.removedModules;
<del> var allModules = chunk.mapModules(function(module) {
<add> var allModules = chunk.mapModules(module => {
<ide> return {
<ide> id: module.id,
<ide> source: moduleTemplate.render(module, dependencyTemplates, chunk)
<ide> };
<ide> });
<ide> if(removedModules && removedModules.length > 0) {
<del> removedModules.forEach(function(id) {
<add> removedModules.forEach(id => {
<ide> allModules.push({
<ide> id: id,
<ide> source: "false"
<ide> module.exports = class Template extends Tapable {
<ide> if(minId !== 0) source.add("Array(" + minId + ").concat(");
<ide> source.add("[\n");
<ide> var modules = {};
<del> allModules.forEach(function(module) {
<add> allModules.forEach(module => {
<ide> modules[module.id] = module;
<ide> });
<ide> for(var idx = minId; idx <= maxId; idx++) {
<ide> module.exports = class Template extends Tapable {
<ide> source.add("{\n");
<ide> allModules
<ide> .sort(stringifyIdSortPredicate)
<del> .forEach(function(module, idx) {
<add> .forEach((module, idx) => {
<ide> if(idx !== 0) source.add(",\n");
<ide> source.add(`\n/***/ ${JSON.stringify(module.id)}:\n`);
<ide> source.add(module.source);
<ide> module.exports = class Template extends Tapable {
<ide> return source;
<ide> }
<ide> };
<del>
<del>function stringifyIdSortPredicate(a, b) {
<del> var aId = a.id + "";
<del> var bId = b.id + "";
<del> if(aId < bId) return -1;
<del> if(aId > bId) return 1;
<del> return 0;
<del>}
<del>
<del>function moduleIdIsNumber(module) {
<del> return typeof module.id === "number";
<del>}
<ide><path>lib/TemplatedPathPlugin.js
<ide> const REGEXP_HASH_FOR_TEST = new RegExp(REGEXP_HASH.source, "i"),
<ide> REGEXP_NAME_FOR_TEST = new RegExp(REGEXP_NAME.source, "i");
<ide>
<ide> const withHashLength = (replacer, handlerFn) => {
<del> return function(_, hashLength) {
<add> return (match, hashLength, ...args) => {
<ide> const length = hashLength && parseInt(hashLength, 10);
<ide> if(length && handlerFn) {
<ide> return handlerFn(length);
<ide> }
<del> const hash = replacer.apply(this, arguments);
<add> const hash = replacer(match, hashLength, ...args);
<ide> return length ? hash.slice(0, length) : hash;
<ide> };
<ide> };
<ide>
<ide> const getReplacer = (value, allowEmpty) => {
<del> return function(match) {
<add> return (match, ...args) => {
<ide> // last argument in replacer is the entire input string
<del> const input = arguments[arguments.length - 1];
<add> const input = args[args.length - 1];
<ide> if(value === null || value === undefined) {
<ide> if(!allowEmpty) throw new Error(`Path variable ${match} not implemented in this context: ${input}`);
<ide> return "";
<ide> class TemplatedPathPlugin {
<ide>
<ide> mainTemplate.plugin("asset-path", replacePathVariables);
<ide>
<del> mainTemplate.plugin("global-hash", function(chunk, paths) {
<del> const outputOptions = this.outputOptions;
<add> mainTemplate.plugin("global-hash", (chunk, paths) => {
<add> const outputOptions = mainTemplate.outputOptions;
<ide> const publicPath = outputOptions.publicPath || "";
<ide> const filename = outputOptions.filename || "";
<ide> const chunkFilename = outputOptions.chunkFilename || outputOptions.filename;
<ide> class TemplatedPathPlugin {
<ide> return true;
<ide> });
<ide>
<del> mainTemplate.plugin("hash-for-chunk", function(hash, chunk) {
<del> const outputOptions = this.outputOptions;
<add> mainTemplate.plugin("hash-for-chunk", (hash, chunk) => {
<add> const outputOptions = mainTemplate.outputOptions;
<ide> const chunkFilename = outputOptions.chunkFilename || outputOptions.filename;
<ide> if(REGEXP_CHUNKHASH_FOR_TEST.test(chunkFilename))
<ide> hash.update(JSON.stringify(chunk.getChunkMaps(true, true).hash));
<ide><path>lib/compareLocations.js
<ide> Author Tobias Koppers @sokra
<ide> */
<ide> "use strict";
<del>module.exports = function compareLocations(a, b) {
<add>module.exports = (a, b) => {
<ide> if(typeof a === "string") {
<ide> if(typeof b === "string") {
<ide> if(a < b) return -1;
<ide><path>lib/dependencies/AMDDefineDependencyParserPlugin.js
<ide> const LocalModuleDependency = require("./LocalModuleDependency");
<ide> const ContextDependencyHelpers = require("./ContextDependencyHelpers");
<ide> const LocalModulesHelpers = require("./LocalModulesHelpers");
<ide>
<del>function isBoundFunctionExpression(expr) {
<add>const isBoundFunctionExpression = expr => {
<ide> if(expr.type !== "CallExpression") return false;
<ide> if(expr.callee.type !== "MemberExpression") return false;
<ide> if(expr.callee.computed) return false;
<ide> if(expr.callee.object.type !== "FunctionExpression") return false;
<ide> if(expr.callee.property.type !== "Identifier") return false;
<ide> if(expr.callee.property.name !== "bind") return false;
<ide> return true;
<del>}
<add>};
<ide>
<ide> class AMDDefineDependencyParserPlugin {
<ide> constructor(options) {
<ide><path>lib/dependencies/AMDPlugin.js
<ide> class AMDPlugin {
<ide> if(typeof parserOptions.amd !== "undefined" && !parserOptions.amd)
<ide> return;
<ide>
<del> function setExpressionToModule(outerExpr, module) {
<add> const setExpressionToModule = (outerExpr, module) => {
<ide> parser.plugin("expression " + outerExpr, (expr) => {
<ide> const dep = new AMDRequireItemDependency(module, expr.range);
<ide> dep.userRequest = outerExpr;
<ide> dep.loc = expr.loc;
<ide> parser.state.current.addDependency(dep);
<ide> return true;
<ide> });
<del> }
<add> };
<ide>
<ide> parser.apply(
<ide> new AMDRequireDependenciesBlockParserPlugin(options),
<ide><path>lib/dependencies/CommonJsRequireDependencyParserPlugin.js
<ide> class CommonJsRequireDependencyParserPlugin {
<ide> const dep = new RequireHeaderDependency(expr.callee.range);
<ide> dep.loc = expr.loc;
<ide> parser.state.current.addDependency(dep);
<del> param.options.forEach(function(param) {
<add> param.options.forEach(param => {
<ide> const result = parser.applyPluginsBailResult("call require:commonjs:item", expr, param);
<ide> if(result === undefined) {
<ide> isExpression = true;
<ide><path>lib/dependencies/ContextDependency.js
<ide> const Dependency = require("../Dependency");
<ide> const CriticalDependencyWarning = require("./CriticalDependencyWarning");
<ide>
<del>function equalRegExp(a, b) {
<add>const equalRegExp = (a, b) => {
<ide> if(a === b) return true;
<ide> if(typeof a !== "object" || typeof b !== "object") return false;
<ide> return a + "" === b + "";
<del>}
<add>};
<ide>
<ide> class ContextDependency extends Dependency {
<ide> // options: { request, recursive, regExp, include, exclude, mode, chunkName }
<ide><path>lib/dependencies/ContextDependencyHelpers.js
<ide> const ContextDependencyHelpers = exports;
<ide> * @param {string} str String to quote
<ide> * @return {string} Escaped string
<ide> */
<del>function quotemeta(str) {
<add>const quotemeta = str => {
<ide> return str.replace(/[-[\]\\/{}()*+?.^$|]/g, "\\$&");
<del>}
<add>};
<ide>
<del>ContextDependencyHelpers.create = function(Dep, range, param, expr, options, contextOptions) {
<add>ContextDependencyHelpers.create = (Dep, range, param, expr, options, contextOptions) => {
<ide> let dep;
<ide> let prefix;
<ide> let postfix;
<ide><path>lib/dependencies/DepBlockHelpers.js
<ide> DepBlockHelpers.getDepBlockPromise = (depBlock, outputOptions, requestShortener,
<ide> const chunks = depBlock.chunks.filter(chunk => !chunk.hasRuntime() && chunk.id !== null);
<ide> const pathChunkCheck = outputOptions.pathinfo && depBlock.chunkName;
<ide> const shortChunkName = requestShortener.shorten(depBlock.chunkName);
<del> const chunkReason = asComment(depBlock.chunkReason);
<add> const chunkReason = Template.toNormalComment(depBlock.chunkReason);
<ide> const requireChunkId = chunk => "__webpack_require__.e(" + JSON.stringify(chunk.id) + ")";
<del> name = asComment(name);
<add> name = Template.toNormalComment(name);
<ide> if(chunks.length === 1) {
<ide> const chunkId = JSON.stringify(chunks[0].id);
<ide> return `__webpack_require__.e${name}(${chunkId}${pathChunkCheck ? Template.toComment(shortChunkName) : ""}${chunkReason})`;
<ide> DepBlockHelpers.getDepBlockPromise = (depBlock, outputOptions, requestShortener,
<ide> }
<ide> return "new Promise(function(resolve) { resolve(); })";
<ide> };
<del>
<del>function asComment(str) {
<del> if(!str) return "";
<del> return `/* ${str} */`;
<del>}
<ide><path>lib/dependencies/HarmonyDetectionParserPlugin.js
<ide> module.exports = class HarmonyDetectionParserPlugin {
<ide> module.exportsArgument = "__webpack_exports__";
<ide> }
<ide> });
<add>
<add> const skipInHarmony = () => {
<add> const module = parser.state.module;
<add> if(module && module.meta && module.meta.harmonyModule)
<add> return true;
<add> };
<add>
<add> const nullInHarmony = () => {
<add> const module = parser.state.module;
<add> if(module && module.meta && module.meta.harmonyModule)
<add> return null;
<add> };
<add>
<ide> var nonHarmonyIdentifiers = ["define", "exports"];
<ide> nonHarmonyIdentifiers.forEach(identifer => {
<ide> parser.plugin(`evaluate typeof ${identifer}`, nullInHarmony);
<ide> module.exports = class HarmonyDetectionParserPlugin {
<ide> parser.plugin(`expression ${identifer}`, skipInHarmony);
<ide> parser.plugin(`call ${identifer}`, skipInHarmony);
<ide> });
<del>
<del> function skipInHarmony() {
<del> const module = this.state.module;
<del> if(module && module.meta && module.meta.harmonyModule)
<del> return true;
<del> }
<del>
<del> function nullInHarmony() {
<del> const module = this.state.module;
<del> if(module && module.meta && module.meta.harmonyModule)
<del> return null;
<del> }
<ide> }
<ide> };
<ide><path>lib/dependencies/HarmonyExportImportedSpecifierDependency.js
<ide> HarmonyExportImportedSpecifierDependency.Template = class HarmonyExportImportedS
<ide> if(Array.isArray(dep.originModule.usedExports)) {
<ide> // we know which exports are used
<ide>
<del> const unused = dep.originModule.usedExports.every(function(id) {
<add> const unused = dep.originModule.usedExports.every(id => {
<ide> if(id === "default") return true;
<ide> if(dep.activeExports.has(id)) return true;
<ide> if(importedModule.isProvided(id) === false) return true;
<ide> HarmonyExportImportedSpecifierDependency.Template = class HarmonyExportImportedS
<ide> } else if(dep.originModule.usedExports && importedModule && Array.isArray(importedModule.providedExports)) {
<ide> // not sure which exports are used, but we know which are provided
<ide>
<del> const unused = importedModule.providedExports.every(function(id) {
<add> const unused = importedModule.providedExports.every(id => {
<ide> if(id === "default") return true;
<ide> if(dep.activeExports.has(id)) return true;
<ide> if(activeFromOtherStarExports.has(id)) return true;
<ide><path>lib/dependencies/LoaderPlugin.js
<ide> class LoaderPlugin {
<ide> });
<ide> compiler.plugin("compilation", (compilation) => {
<ide> compilation.plugin("normal-module-loader", (loaderContext, module) => {
<del> loaderContext.loadModule = function loadModule(request, callback) {
<add> loaderContext.loadModule = (request, callback) => {
<ide> const dep = new LoaderDependency(request);
<ide> dep.loc = request;
<ide> compilation.addModuleDependencies(module, [
<ide> [dep]
<del> ], true, "lm", false, (err) => {
<add> ], true, "lm", false, err => {
<ide> if(err) return callback(err);
<ide>
<ide> if(!dep.module) return callback(new Error("Cannot load the module"));
<ide> class LoaderPlugin {
<ide> source = moduleSource.source();
<ide> }
<ide> if(dep.module.fileDependencies) {
<del> dep.module.fileDependencies.forEach((dep) => loaderContext.addDependency(dep));
<add> dep.module.fileDependencies.forEach(dep => loaderContext.addDependency(dep));
<ide> }
<ide> if(dep.module.contextDependencies) {
<del> dep.module.contextDependencies.forEach((dep) => loaderContext.addContextDependency(dep));
<add> dep.module.contextDependencies.forEach(dep => loaderContext.addContextDependency(dep));
<ide> }
<ide> return callback(null, source, map, dep.module);
<ide> });
<ide><path>lib/dependencies/SystemPlugin.js
<ide> class SystemPlugin {
<ide> if(typeof parserOptions.system !== "undefined" && !parserOptions.system)
<ide> return;
<ide>
<del> function setNotSupported(name) {
<add> const setNotSupported = name => {
<ide> parser.plugin("evaluate typeof " + name, ParserHelpers.evaluateToString("undefined"));
<ide> parser.plugin("expression " + name,
<ide> ParserHelpers.expressionIsUnsupported(name + " is not supported by webpack.")
<ide> );
<del> }
<add> };
<ide>
<ide> parser.plugin("typeof System.import", ParserHelpers.toConstantDependency(JSON.stringify("function")));
<ide> parser.plugin("evaluate typeof System.import", ParserHelpers.evaluateToString("function"));
<ide> class SystemPlugin {
<ide> setNotSupported("System.set");
<ide> setNotSupported("System.get");
<ide> setNotSupported("System.register");
<del> parser.plugin("expression System", function() {
<add> parser.plugin("expression System", () => {
<ide> const systemPolyfillRequire = ParserHelpers.requireFileAsExpression(
<del> this.state.module.context, require.resolve("../../buildin/system.js"));
<del> return ParserHelpers.addParsedVariableToModule(this, "System", systemPolyfillRequire);
<add> parser.state.module.context, require.resolve("../../buildin/system.js"));
<add> return ParserHelpers.addParsedVariableToModule(parser, "System", systemPolyfillRequire);
<ide> });
<ide> });
<ide> });
<ide><path>lib/dependencies/getFunctionExpression.js
<ide> MIT License http://www.opensource.org/licenses/mit-license.php
<ide> Author Tobias Koppers @sokra
<ide> */
<del>module.exports = function(expr) {
<add>module.exports = expr => {
<ide> // <FunctionExpression>
<ide> if(expr.type === "FunctionExpression" || expr.type === "ArrowFunctionExpression") {
<ide> return {
<ide><path>lib/node/NodeChunkTemplatePlugin.js
<ide> const ConcatSource = require("webpack-sources").ConcatSource;
<ide> class NodeChunkTemplatePlugin {
<ide>
<ide> apply(chunkTemplate) {
<del> chunkTemplate.plugin("render", function(modules, chunk) {
<add> chunkTemplate.plugin("render", (modules, chunk) => {
<ide> const source = new ConcatSource();
<ide> source.add(`exports.ids = ${JSON.stringify(chunk.ids)};\nexports.modules = `);
<ide> source.add(modules);
<ide> source.add(";");
<ide> return source;
<ide> });
<del> chunkTemplate.plugin("hash", function(hash) {
<add> chunkTemplate.plugin("hash", hash => {
<ide> hash.update("node");
<ide> hash.update("3");
<ide> });
<ide><path>lib/node/NodeHotUpdateChunkTemplatePlugin.js
<ide> class NodeHotUpdateChunkTemplatePlugin {
<ide> source.add(";");
<ide> return source;
<ide> });
<del> hotUpdateChunkTemplate.plugin("hash", function(hash) {
<add> hotUpdateChunkTemplate.plugin("hash", hash => {
<ide> hash.update("NodeHotUpdateChunkTemplatePlugin");
<ide> hash.update("3");
<del> hash.update(this.outputOptions.hotUpdateFunction + "");
<del> hash.update(this.outputOptions.library + "");
<add> hash.update(hotUpdateChunkTemplate.outputOptions.hotUpdateFunction + "");
<add> hash.update(hotUpdateChunkTemplate.outputOptions.library + "");
<ide> });
<ide> }
<ide> }
<ide><path>lib/node/NodeMainTemplatePlugin.js
<ide> module.exports = class NodeMainTemplatePlugin {
<ide>
<ide> apply(mainTemplate) {
<ide> const asyncChunkLoading = this.asyncChunkLoading;
<del> mainTemplate.plugin("local-vars", function(source, chunk) {
<add> mainTemplate.plugin("local-vars", (source, chunk) => {
<ide> if(chunk.getNumberOfChunks() > 0) {
<del> return this.asString([
<add> return mainTemplate.asString([
<ide> source,
<ide> "",
<ide> "// object to store loaded chunks",
<ide> "// \"0\" means \"already loaded\"",
<ide> "var installedChunks = {",
<del> this.indent(chunk.ids.map((id) => `${id}: 0`).join(",\n")),
<add> mainTemplate.indent(chunk.ids.map((id) => `${id}: 0`).join(",\n")),
<ide> "};"
<ide> ]);
<ide> }
<ide> return source;
<ide> });
<del> mainTemplate.plugin("require-extensions", function(source, chunk) {
<add> mainTemplate.plugin("require-extensions", (source, chunk) => {
<ide> if(chunk.getNumberOfChunks() > 0) {
<del> return this.asString([
<add> return mainTemplate.asString([
<ide> source,
<ide> "",
<ide> "// uncatched error handler for webpack runtime",
<del> `${this.requireFn}.oe = function(err) {`,
<del> this.indent([
<add> `${mainTemplate.requireFn}.oe = function(err) {`,
<add> mainTemplate.indent([
<ide> "process.nextTick(function() {",
<del> this.indent("throw err; // catch this error by using System.import().catch()"),
<add> mainTemplate.indent("throw err; // catch this error by using System.import().catch()"),
<ide> "});"
<ide> ]),
<ide> "};"
<ide> ]);
<ide> }
<ide> return source;
<ide> });
<del> mainTemplate.plugin("require-ensure", function(_, chunk, hash) {
<del> const chunkFilename = this.outputOptions.chunkFilename;
<add> mainTemplate.plugin("require-ensure", (_, chunk, hash) => {
<add> const chunkFilename = mainTemplate.outputOptions.chunkFilename;
<ide> const chunkMaps = chunk.getChunkMaps();
<ide> const insertMoreModules = [
<ide> "var moreModules = chunk.modules, chunkIds = chunk.ids;",
<ide> "for(var moduleId in moreModules) {",
<del> this.indent(this.renderAddModule(hash, chunk, "moduleId", "moreModules[moduleId]")),
<add> mainTemplate.indent(mainTemplate.renderAddModule(hash, chunk, "moduleId", "moreModules[moduleId]")),
<ide> "}"
<ide> ];
<ide> if(asyncChunkLoading) {
<del> return this.asString([
<add> return mainTemplate.asString([
<ide> "// \"0\" is the signal for \"already loaded\"",
<ide> "if(installedChunks[chunkId] === 0)",
<del> this.indent([
<add> mainTemplate.indent([
<ide> "return Promise.resolve();"
<ide> ]),
<ide> "// array of [resolve, reject, promise] means \"currently loading\"",
<ide> "if(installedChunks[chunkId])",
<del> this.indent([
<add> mainTemplate.indent([
<ide> "return installedChunks[chunkId][2];"
<ide> ]),
<ide> "// load the chunk and return promise to it",
<ide> "var promise = new Promise(function(resolve, reject) {",
<del> this.indent([
<add> mainTemplate.indent([
<ide> "installedChunks[chunkId] = [resolve, reject];",
<del> "var filename = __dirname + " + this.applyPluginsWaterfall("asset-path", JSON.stringify(`/${chunkFilename}`), {
<del> hash: `" + ${this.renderCurrentHashCode(hash)} + "`,
<del> hashWithLength: (length) => `" + ${this.renderCurrentHashCode(hash, length)} + "`,
<add> "var filename = __dirname + " + mainTemplate.applyPluginsWaterfall("asset-path", JSON.stringify(`/${chunkFilename}`), {
<add> hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`,
<add> hashWithLength: (length) => `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`,
<ide> chunk: {
<ide> id: "\" + chunkId + \"",
<ide> hash: `" + ${JSON.stringify(chunkMaps.hash)}[chunkId] + "`,
<ide> module.exports = class NodeMainTemplatePlugin {
<ide> }
<ide> }) + ";",
<ide> "require('fs').readFile(filename, 'utf-8', function(err, content) {",
<del> this.indent([
<add> mainTemplate.indent([
<ide> "if(err) return reject(err);",
<ide> "var chunk = {};",
<ide> "require('vm').runInThisContext('(function(exports, require, __dirname, __filename) {' + content + '\\n})', filename)" +
<ide> "(chunk, require, require('path').dirname(filename), filename);"
<ide> ].concat(insertMoreModules).concat([
<ide> "var callbacks = [];",
<ide> "for(var i = 0; i < chunkIds.length; i++) {",
<del> this.indent([
<add> mainTemplate.indent([
<ide> "if(installedChunks[chunkIds[i]])",
<del> this.indent([
<add> mainTemplate.indent([
<ide> "callbacks = callbacks.concat(installedChunks[chunkIds[i]][0]);"
<ide> ]),
<ide> "installedChunks[chunkIds[i]] = 0;"
<ide> ]),
<ide> "}",
<ide> "for(i = 0; i < callbacks.length; i++)",
<del> this.indent("callbacks[i]();")
<add> mainTemplate.indent("callbacks[i]();")
<ide> ])),
<ide> "});"
<ide> ]),
<ide> "});",
<ide> "return installedChunks[chunkId][2] = promise;"
<ide> ]);
<ide> } else {
<del> const request = this.applyPluginsWaterfall("asset-path", JSON.stringify(`./${chunkFilename}`), {
<del> hash: `" + ${this.renderCurrentHashCode(hash)} + "`,
<del> hashWithLength: (length) => `" + ${this.renderCurrentHashCode(hash, length)} + "`,
<add> const request = mainTemplate.applyPluginsWaterfall("asset-path", JSON.stringify(`./${chunkFilename}`), {
<add> hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`,
<add> hashWithLength: (length) => `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`,
<ide> chunk: {
<ide> id: "\" + chunkId + \"",
<ide> hash: `" + ${JSON.stringify(chunkMaps.hash)}[chunkId] + "`,
<ide> module.exports = class NodeMainTemplatePlugin {
<ide> name: `" + (${JSON.stringify(chunkMaps.name)}[chunkId]||chunkId) + "`
<ide> }
<ide> });
<del> return this.asString([
<add> return mainTemplate.asString([
<ide> "// \"0\" is the signal for \"already loaded\"",
<ide> "if(installedChunks[chunkId] !== 0) {",
<del> this.indent([
<add> mainTemplate.indent([
<ide> `var chunk = require(${request});`
<ide> ].concat(insertMoreModules).concat([
<ide> "for(var i = 0; i < chunkIds.length; i++)",
<del> this.indent("installedChunks[chunkIds[i]] = 0;")
<add> mainTemplate.indent("installedChunks[chunkIds[i]] = 0;")
<ide> ])),
<ide> "}",
<ide> "return Promise.resolve();"
<ide> ]);
<ide> }
<ide> });
<del> mainTemplate.plugin("hot-bootstrap", function(source, chunk, hash) {
<del> const hotUpdateChunkFilename = this.outputOptions.hotUpdateChunkFilename;
<del> const hotUpdateMainFilename = this.outputOptions.hotUpdateMainFilename;
<add> mainTemplate.plugin("hot-bootstrap", (source, chunk, hash) => {
<add> const hotUpdateChunkFilename = mainTemplate.outputOptions.hotUpdateChunkFilename;
<add> const hotUpdateMainFilename = mainTemplate.outputOptions.hotUpdateMainFilename;
<ide> const chunkMaps = chunk.getChunkMaps();
<del> const currentHotUpdateChunkFilename = this.applyPluginsWaterfall("asset-path", JSON.stringify(hotUpdateChunkFilename), {
<del> hash: `" + ${this.renderCurrentHashCode(hash)} + "`,
<del> hashWithLength: (length) => `" + ${this.renderCurrentHashCode(hash, length)} + "`,
<add> const currentHotUpdateChunkFilename = mainTemplate.applyPluginsWaterfall("asset-path", JSON.stringify(hotUpdateChunkFilename), {
<add> hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`,
<add> hashWithLength: (length) => `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`,
<ide> chunk: {
<ide> id: "\" + chunkId + \"",
<ide> hash: `" + ${JSON.stringify(chunkMaps.hash)}[chunkId] + "`,
<ide> module.exports = class NodeMainTemplatePlugin {
<ide> name: `" + (${JSON.stringify(chunkMaps.name)}[chunkId]||chunkId) + "`
<ide> }
<ide> });
<del> const currentHotUpdateMainFilename = this.applyPluginsWaterfall("asset-path", JSON.stringify(hotUpdateMainFilename), {
<del> hash: `" + ${this.renderCurrentHashCode(hash)} + "`,
<del> hashWithLength: (length) => `" + ${this.renderCurrentHashCode(hash, length)} + "`
<add> const currentHotUpdateMainFilename = mainTemplate.applyPluginsWaterfall("asset-path", JSON.stringify(hotUpdateMainFilename), {
<add> hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`,
<add> hashWithLength: (length) => `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`
<ide> });
<ide> return Template.getFunctionContent(asyncChunkLoading ? require("./NodeMainTemplateAsync.runtime.js") : require("./NodeMainTemplate.runtime.js"))
<del> .replace(/\$require\$/g, this.requireFn)
<add> .replace(/\$require\$/g, mainTemplate.requireFn)
<ide> .replace(/\$hotMainFilename\$/g, currentHotUpdateMainFilename)
<ide> .replace(/\$hotChunkFilename\$/g, currentHotUpdateChunkFilename);
<ide> });
<del> mainTemplate.plugin("hash", function(hash) {
<add> mainTemplate.plugin("hash", hash => {
<ide> hash.update("node");
<ide> hash.update("3");
<del> hash.update(this.outputOptions.filename + "");
<del> hash.update(this.outputOptions.chunkFilename + "");
<add> hash.update(mainTemplate.outputOptions.filename + "");
<add> hash.update(mainTemplate.outputOptions.chunkFilename + "");
<ide> });
<ide> }
<ide> };
<ide><path>lib/node/NodeSourcePlugin.js
<ide> module.exports = class NodeSourcePlugin {
<ide> if(options === false) // allow single kill switch to turn off this plugin
<ide> return;
<ide>
<del> function getPathToModule(module, type) {
<add> const getPathToModule = (module, type) => {
<ide> if(type === true || (type === undefined && nodeLibsBrowser[module])) {
<ide> if(!nodeLibsBrowser[module]) throw new Error(`No browser version for node.js core module ${module} available`);
<ide> return nodeLibsBrowser[module];
<ide> module.exports = class NodeSourcePlugin {
<ide> } else if(type === "empty") {
<ide> return require.resolve("node-libs-browser/mock/empty");
<ide> } else return module;
<del> }
<add> };
<ide>
<del> function addExpression(parser, name, module, type, suffix) {
<add> const addExpression = (parser, name, module, type, suffix) => {
<ide> suffix = suffix || "";
<del> parser.plugin(`expression ${name}`, function() {
<del> if(this.state.module && this.state.module.resource === getPathToModule(module, type)) return;
<del> const mockModule = ParserHelpers.requireFileAsExpression(this.state.module.context, getPathToModule(module, type));
<del> return ParserHelpers.addParsedVariableToModule(this, name, mockModule + suffix);
<add> parser.plugin(`expression ${name}`, () => {
<add> if(parser.state.module && parser.state.module.resource === getPathToModule(module, type)) return;
<add> const mockModule = ParserHelpers.requireFileAsExpression(parser.state.module.context, getPathToModule(module, type));
<add> return ParserHelpers.addParsedVariableToModule(parser, name, mockModule + suffix);
<ide> });
<del> }
<add> };
<ide>
<del> compiler.plugin("compilation", function(compilation, params) {
<del> params.normalModuleFactory.plugin("parser", function(parser, parserOptions) {
<add> compiler.plugin("compilation", (compilation, params) => {
<add> params.normalModuleFactory.plugin("parser", (parser, parserOptions) => {
<ide>
<ide> if(parserOptions.node === false)
<ide> return;
<ide> module.exports = class NodeSourcePlugin {
<ide> localOptions = Object.assign({}, localOptions, parserOptions.node);
<ide>
<ide> if(localOptions.global) {
<del> parser.plugin("expression global", function() {
<del> const retrieveGlobalModule = ParserHelpers.requireFileAsExpression(this.state.module.context, require.resolve("../../buildin/global.js"));
<del> return ParserHelpers.addParsedVariableToModule(this, "global", retrieveGlobalModule);
<add> parser.plugin("expression global", () => {
<add> const retrieveGlobalModule = ParserHelpers.requireFileAsExpression(parser.state.module.context, require.resolve("../../buildin/global.js"));
<add> return ParserHelpers.addParsedVariableToModule(parser, "global", retrieveGlobalModule);
<ide> });
<ide> }
<ide> if(localOptions.process) {
<ide><path>lib/optimize/AggressiveMergingPlugin.js
<ide> class AggressiveMergingPlugin {
<ide> const options = this.options;
<ide> const minSizeReduce = options.minSizeReduce || 1.5;
<ide>
<del> function getParentsWeight(chunk) {
<add> const getParentsWeight = chunk => {
<ide> return chunk.mapParents((p) => {
<ide> return p.isInitial() ? options.entryChunkMultiplicator || 10 : 1;
<ide> }).reduce((a, b) => {
<ide> return a + b;
<ide> }, 0);
<del> }
<add> };
<add>
<ide> compiler.plugin("this-compilation", (compilation) => {
<ide> compilation.plugin("optimize-chunks-advanced", (chunks) => {
<ide> let combinations = [];
<ide><path>lib/optimize/AggressiveSplittingPlugin.js
<ide>
<ide> const identifierUtils = require("../util/identifier");
<ide>
<del>function moveModuleBetween(oldChunk, newChunk) {
<del> return function(module) {
<add>const moveModuleBetween = (oldChunk, newChunk) => {
<add> return module => {
<ide> oldChunk.moveModule(module, newChunk);
<ide> };
<del>}
<add>};
<ide>
<del>function isNotAEntryModule(entryModule) {
<del> return function(module) {
<add>const isNotAEntryModule = entryModule => {
<add> return module => {
<ide> return entryModule !== module;
<ide> };
<del>}
<add>};
<ide>
<del>function copyWithReason(obj) {
<add>const copyWithReason = obj => {
<ide> const newObj = {};
<del> Object.keys(obj).forEach((key) => {
<add> Object.keys(obj).forEach(key => {
<ide> newObj[key] = obj[key];
<ide> });
<ide> if(!newObj.reasons || newObj.reasons.indexOf("aggressive-splitted") < 0)
<ide> newObj.reasons = (newObj.reasons || []).concat("aggressive-splitted");
<ide> return newObj;
<del>}
<add>};
<ide>
<ide> class AggressiveSplittingPlugin {
<ide> constructor(options) {
<ide><path>lib/optimize/ConcatenatedModule.js
<ide> const HarmonyExportExpressionDependency = require("../dependencies/HarmonyExport
<ide> const HarmonyExportImportedSpecifierDependency = require("../dependencies/HarmonyExportImportedSpecifierDependency");
<ide> const HarmonyCompatibilityDependency = require("../dependencies/HarmonyCompatibilityDependency");
<ide>
<del>function ensureNsObjSource(info, moduleToInfoMap, requestShortener) {
<add>const ensureNsObjSource = (info, moduleToInfoMap, requestShortener) => {
<ide> if(!info.hasNamespaceObject) {
<ide> info.hasNamespaceObject = true;
<ide> const name = info.exportMap.get(true);
<ide> function ensureNsObjSource(info, moduleToInfoMap, requestShortener) {
<ide> }
<ide> info.namespaceObjectSource = nsObj.join("\n") + "\n";
<ide> }
<del>}
<add>};
<ide>
<del>function getExternalImport(importedModule, info, exportName, asCall) {
<add>const getExternalImport = (importedModule, info, exportName, asCall) => {
<ide> if(exportName === true) return info.name;
<ide> const used = importedModule.isUsed(exportName);
<ide> if(!used) return "/* unused reexport */undefined";
<ide> function getExternalImport(importedModule, info, exportName, asCall) {
<ide> if(asCall)
<ide> return `Object(${reference})`;
<ide> return reference;
<del>}
<add>};
<ide>
<del>function getFinalName(info, exportName, moduleToInfoMap, requestShortener, asCall) {
<add>const getFinalName = (info, exportName, moduleToInfoMap, requestShortener, asCall) => {
<ide> switch(info.type) {
<ide> case "concatenated":
<ide> {
<ide> function getFinalName(info, exportName, moduleToInfoMap, requestShortener, asCal
<ide> return getExternalImport(importedModule, info, exportName, asCall);
<ide> }
<ide> }
<del>}
<add>};
<ide>
<del>function getSymbolsFromScope(s, untilScope) {
<add>const getSymbolsFromScope = (s, untilScope) => {
<ide> const allUsedNames = new Set();
<ide> let scope = s;
<ide> while(scope) {
<ide> function getSymbolsFromScope(s, untilScope) {
<ide> scope = scope.upper;
<ide> }
<ide> return allUsedNames;
<del>}
<add>};
<ide>
<del>function getAllReferences(variable) {
<add>const getAllReferences = variable => {
<ide> let set = variable.references;
<ide> // Look for inner scope variables too (like in class Foo { t() { Foo } })
<ide> const identifiers = new Set(variable.identifiers);
<ide> function getAllReferences(variable) {
<ide> }
<ide> }
<ide> return set;
<del>}
<add>};
<ide>
<del>function reduceSet(a, b) {
<add>const reduceSet = (a, b) => {
<ide> for(const item of b)
<ide> a.add(item);
<ide> return a;
<del>}
<add>};
<ide>
<del>function getPathInAst(ast, node) {
<add>const getPathInAst = (ast, node) => {
<ide> if(ast === node) {
<ide> return [];
<ide> }
<add>
<ide> const nr = node.range;
<add>
<add> const enterNode = n => {
<add> const r = n.range;
<add> if(r) {
<add> if(r[0] <= nr[0] && r[1] >= nr[1]) {
<add> const path = getPathInAst(n, node);
<add> if(path) {
<add> path.push(n);
<add> return path;
<add> }
<add> }
<add> }
<add> return undefined;
<add> };
<add>
<ide> var i;
<ide> if(Array.isArray(ast)) {
<ide> for(i = 0; i < ast.length; i++) {
<ide> function getPathInAst(ast, node) {
<ide> }
<ide> }
<ide> }
<del>
<del> function enterNode(n) {
<del> const r = n.range;
<del> if(r) {
<del> if(r[0] <= nr[0] && r[1] >= nr[1]) {
<del> const path = getPathInAst(n, node);
<del> if(path) {
<del> path.push(n);
<del> return path;
<del> }
<del> }
<del> }
<del> return undefined;
<del> }
<del>}
<add>};
<ide>
<ide> class ConcatenatedModule extends Module {
<ide> constructor(rootModule, modules) {
<ide> class ConcatenatedModule extends Module {
<ide> const list = [];
<ide> const set = new Set();
<ide>
<del> function getConcatenatedImports(module) {
<add> const getConcatenatedImports = module => {
<ide> return module.dependencies
<ide> .filter(dep => dep instanceof HarmonyImportDependency)
<ide> .sort((a, b) => a.sourceOrder - b.sourceOrder)
<ide> .map(dep => () => {
<ide> const ref = dep.getReference();
<ide> return ref && ref.module;
<ide> });
<del> }
<add> };
<ide>
<del> function enterModule(getModule) {
<add> const enterModule = getModule => {
<ide> const module = getModule();
<ide> if(!module) return;
<ide> if(set.has(module)) return;
<ide> class ConcatenatedModule extends Module {
<ide> }
<ide> });
<ide> }
<del> }
<add> };
<ide>
<ide> enterModule(() => rootModule);
<ide>
<ide><path>lib/optimize/ModuleConcatenationPlugin.js
<ide> const ModuleHotDeclineDependency = require("../dependencies/ModuleHotDeclineDepe
<ide> const ConcatenatedModule = require("./ConcatenatedModule");
<ide> const HarmonyCompatibilityDependency = require("../dependencies/HarmonyCompatibilityDependency");
<ide>
<del>function formatBailoutReason(msg) {
<add>const formatBailoutReason = msg => {
<ide> return "ModuleConcatenation bailout: " + msg;
<del>}
<add>};
<ide>
<ide> class ModuleConcatenationPlugin {
<ide> constructor(options) {
<ide> class ModuleConcatenationPlugin {
<ide> });
<ide> const bailoutReasonMap = new Map();
<ide>
<del> function setBailoutReason(module, reason) {
<add> const setBailoutReason = (module, reason) => {
<ide> bailoutReasonMap.set(module, reason);
<ide> module.optimizationBailout.push(typeof reason === "function" ? (rs) => formatBailoutReason(reason(rs)) : formatBailoutReason(reason));
<del> }
<add> };
<ide>
<del> function getBailoutReason(module, requestShortener) {
<add> const getBailoutReason = (module, requestShortener) => {
<ide> const reason = bailoutReasonMap.get(module);
<ide> if(typeof reason === "function") return reason(requestShortener);
<ide> return reason;
<del> }
<add> };
<ide>
<ide> compilation.plugin("optimize-chunk-modules", (chunks, modules) => {
<ide> const relevantModules = [];
<ide><path>lib/optimize/OccurrenceOrderPlugin.js
<ide> class OccurrenceOrderPlugin {
<ide> return occursInInitialChunksMap.set(c, result);
<ide> });
<ide>
<del> function occurs(c) {
<add> const occurs = c => {
<ide> return c.getNumberOfBlocks();
<del> }
<add> };
<ide>
<ide> chunks.sort((a, b) => {
<ide> const aEntryOccurs = occursInInitialChunksMap.get(a);
<ide><path>lib/optimize/RemoveParentModulesPlugin.js
<ide> */
<ide> "use strict";
<ide>
<del>function hasModule(chunk, module, checkedChunks) {
<add>const hasModule = (chunk, module, checkedChunks) => {
<ide> if(chunk.containsModule(module)) return [chunk];
<ide> if(chunk.getNumberOfParents() === 0) return false;
<ide> return allHaveModule(chunk.getParents().filter((c) => {
<ide> return !checkedChunks.has(c);
<ide> }), module, checkedChunks);
<del>}
<add>};
<ide>
<del>function allHaveModule(someChunks, module, checkedChunks) {
<add>const allHaveModule = (someChunks, module, checkedChunks) => {
<ide> if(!checkedChunks) checkedChunks = new Set();
<ide> var chunks = new Set();
<ide> for(var i = 0; i < someChunks.length; i++) {
<ide> function allHaveModule(someChunks, module, checkedChunks) {
<ide> }
<ide> }
<ide> return chunks;
<del>}
<add>};
<ide>
<ide> class RemoveParentModulesPlugin {
<ide> apply(compiler) {
<ide><path>lib/performance/SizeLimitsPlugin.js
<ide> module.exports = class SizeLimitsPlugin {
<ide> }
<ide>
<ide> if(hints === "error") {
<del> Array.prototype.push.apply(compilation.errors, warnings);
<add> compilation.errors.push(...warnings);
<ide> } else {
<del> Array.prototype.push.apply(compilation.warnings, warnings);
<add> compilation.warnings.push(...warnings);
<ide> }
<ide> }
<ide> }
<ide><path>lib/prepareOptions.js
<ide> "use strict";
<ide>
<del>module.exports = function prepareOptions(options, argv) {
<add>const handleExport = options => {
<add> const isES6DefaultExported = (
<add> typeof options === "object" && options !== null && typeof options.default !== "undefined"
<add> );
<add> options = isES6DefaultExported ? options.default : options;
<add> return options;
<add>};
<add>
<add>const handleFunction = (options, argv) => {
<add> if(typeof options === "function") {
<add> options = options(argv.env, argv);
<add> }
<add> return options;
<add>};
<add>
<add>module.exports = (options, argv) => {
<ide> argv = argv || {};
<ide>
<ide> options = handleExport(options);
<ide> module.exports = function prepareOptions(options, argv) {
<ide> }
<ide> return options;
<ide> };
<del>
<del>function handleExport(options) {
<del> const isES6DefaultExported = (
<del> typeof options === "object" && options !== null && typeof options.default !== "undefined"
<del> );
<del> options = isES6DefaultExported ? options.default : options;
<del> return options;
<del>}
<del>
<del>function handleFunction(options, argv) {
<del> if(typeof options === "function") {
<del> options = options(argv.env, argv);
<del> }
<del> return options;
<del>}
<ide><path>lib/removeAndDo.js
<ide> */
<ide> "use strict";
<ide>
<del>module.exports = function removeAndDo(collection, thing, action) {
<add>// TODO can this be deleted?
<add>module.exports = (collection, thing, action) => {
<ide> const idx = this[collection].indexOf(thing);
<ide> const hasThingInCollection = idx >= 0;
<ide> if(hasThingInCollection) {
<ide><path>lib/validateSchema.js
<ide> const ajv = new Ajv({
<ide> require("ajv-keywords")(ajv, ["instanceof"]);
<ide> require("../schemas/ajv.absolutePath")(ajv);
<ide>
<del>function validateSchema(schema, options) {
<add>const validateSchema = (schema, options) => {
<ide> if(Array.isArray(options)) {
<ide> const errors = options.map((options) => validateObject(schema, options));
<ide> errors.forEach((list, idx) => {
<del> list.forEach(function applyPrefix(err) {
<add> const applyPrefix = err => {
<ide> err.dataPath = `[${idx}]${err.dataPath}`;
<ide> if(err.children) {
<ide> err.children.forEach(applyPrefix);
<ide> }
<del> });
<add> };
<add> list.forEach(applyPrefix);
<ide> });
<ide> return errors.reduce((arr, items) => {
<ide> return arr.concat(items);
<ide> }, []);
<ide> } else {
<ide> return validateObject(schema, options);
<ide> }
<del>}
<add>};
<ide>
<del>function validateObject(schema, options) {
<add>const validateObject = (schema, options) => {
<ide> const validate = ajv.compile(schema);
<ide> const valid = validate(options);
<ide> return valid ? [] : filterErrors(validate.errors);
<del>}
<add>};
<ide>
<del>function filterErrors(errors) {
<add>const filterErrors = errors => {
<ide> let newErrors = [];
<ide> errors.forEach((err) => {
<ide> const dataPath = err.dataPath;
<ide> function filterErrors(errors) {
<ide> });
<ide>
<ide> return newErrors;
<del>}
<add>};
<ide>
<ide> module.exports = validateSchema;
<ide><path>lib/webpack.js
<ide> const validateSchema = require("./validateSchema");
<ide> const WebpackOptionsValidationError = require("./WebpackOptionsValidationError");
<ide> const webpackOptionsSchema = require("../schemas/webpackOptionsSchema.json");
<ide>
<del>function webpack(options, callback) {
<add>const webpack = (options, callback) => {
<ide> const webpackOptionsValidationErrors = validateSchema(webpackOptionsSchema, options);
<ide> if(webpackOptionsValidationErrors.length) {
<ide> throw new WebpackOptionsValidationError(webpackOptionsValidationErrors);
<ide> function webpack(options, callback) {
<ide> compiler.run(callback);
<ide> }
<ide> return compiler;
<del>}
<add>};
<add>
<ide> exports = module.exports = webpack;
<ide>
<ide> webpack.WebpackOptionsDefaulter = WebpackOptionsDefaulter;
<ide> webpack.validate = validateSchema.bind(this, webpackOptionsSchema);
<ide> webpack.validateSchema = validateSchema;
<ide> webpack.WebpackOptionsValidationError = WebpackOptionsValidationError;
<ide>
<del>function exportPlugins(obj, mappings) {
<add>const exportPlugins = (obj, mappings) => {
<ide> Object.keys(mappings).forEach(name => {
<ide> Object.defineProperty(obj, name, {
<ide> configurable: false,
<ide> enumerable: true,
<ide> get: mappings[name]
<ide> });
<ide> });
<del>}
<add>};
<ide>
<ide> exportPlugins(exports, {
<ide> "DefinePlugin": () => require("./DefinePlugin"),
<ide><path>lib/webworker/WebWorkerChunkTemplatePlugin.js
<ide> const Template = require("../Template");
<ide> class WebWorkerChunkTemplatePlugin {
<ide>
<ide> apply(chunkTemplate) {
<del> chunkTemplate.plugin("render", function(modules, chunk) {
<del> const chunkCallbackName = this.outputOptions.chunkCallbackName || Template.toIdentifier("webpackChunk" + (this.outputOptions.library || ""));
<add> chunkTemplate.plugin("render", (modules, chunk) => {
<add> const chunkCallbackName = chunkTemplate.outputOptions.chunkCallbackName || Template.toIdentifier("webpackChunk" + (chunkTemplate.outputOptions.library || ""));
<ide> const source = new ConcatSource();
<ide> source.add(`${chunkCallbackName}(${JSON.stringify(chunk.ids)},`);
<ide> source.add(modules);
<ide> source.add(")");
<ide> return source;
<ide> });
<del> chunkTemplate.plugin("hash", function(hash) {
<add> chunkTemplate.plugin("hash", hash => {
<ide> hash.update("webworker");
<ide> hash.update("3");
<del> hash.update(`${this.outputOptions.chunkCallbackName}`);
<del> hash.update(`${this.outputOptions.library}`);
<add> hash.update(`${chunkTemplate.outputOptions.chunkCallbackName}`);
<add> hash.update(`${chunkTemplate.outputOptions.library}`);
<ide> });
<ide> }
<ide> }
<ide><path>lib/webworker/WebWorkerHotUpdateChunkTemplatePlugin.js
<ide> const Template = require("../Template");
<ide> class WebWorkerHotUpdateChunkTemplatePlugin {
<ide>
<ide> apply(hotUpdateChunkTemplate) {
<del> hotUpdateChunkTemplate.plugin("render", function(modulesSource, modules, removedModules, hash, id) {
<del> const chunkCallbackName = this.outputOptions.hotUpdateFunction || Template.toIdentifier("webpackHotUpdate" + (this.outputOptions.library || ""));
<add> hotUpdateChunkTemplate.plugin("render", (modulesSource, modules, removedModules, hash, id) => {
<add> const chunkCallbackName = hotUpdateChunkTemplate.outputOptions.hotUpdateFunction || Template.toIdentifier("webpackHotUpdate" + (hotUpdateChunkTemplate.outputOptions.library || ""));
<ide> const source = new ConcatSource();
<ide> source.add(chunkCallbackName + "(" + JSON.stringify(id) + ",");
<ide> source.add(modulesSource);
<ide> source.add(")");
<ide> return source;
<ide> });
<del> hotUpdateChunkTemplate.plugin("hash", function(hash) {
<add> hotUpdateChunkTemplate.plugin("hash", hash => {
<ide> hash.update("WebWorkerHotUpdateChunkTemplatePlugin");
<ide> hash.update("3");
<del> hash.update(this.outputOptions.hotUpdateFunction + "");
<del> hash.update(this.outputOptions.library + "");
<add> hash.update(hotUpdateChunkTemplate.outputOptions.hotUpdateFunction + "");
<add> hash.update(hotUpdateChunkTemplate.outputOptions.library + "");
<ide> });
<ide> }
<ide> }
<ide><path>lib/webworker/WebWorkerMainTemplatePlugin.js
<ide> const Template = require("../Template");
<ide>
<ide> class WebWorkerMainTemplatePlugin {
<ide> apply(mainTemplate) {
<del> mainTemplate.plugin("local-vars", function(source, chunk) {
<add> mainTemplate.plugin("local-vars", (source, chunk) => {
<ide> if(chunk.getNumberOfChunks() > 0) {
<del> return this.asString([
<add> return mainTemplate.asString([
<ide> source,
<ide> "",
<ide> "// object to store loaded chunks",
<ide> "// \"1\" means \"already loaded\"",
<ide> "var installedChunks = {",
<del> this.indent(
<add> mainTemplate.indent(
<ide> chunk.ids.map((id) => `${id}: 1`).join(",\n")
<ide> ),
<ide> "};"
<ide> ]);
<ide> }
<ide> return source;
<ide> });
<del> mainTemplate.plugin("require-ensure", function(_, chunk, hash) {
<del> const chunkFilename = this.outputOptions.chunkFilename;
<del> return this.asString([
<add> mainTemplate.plugin("require-ensure", (_, chunk, hash) => {
<add> const chunkFilename = mainTemplate.outputOptions.chunkFilename;
<add> return mainTemplate.asString([
<ide> "return new Promise(function(resolve) {",
<del> this.indent([
<add> mainTemplate.indent([
<ide> "// \"1\" is the signal for \"already loaded\"",
<ide> "if(!installedChunks[chunkId]) {",
<del> this.indent([
<add> mainTemplate.indent([
<ide> "importScripts(" +
<del> this.applyPluginsWaterfall("asset-path", JSON.stringify(chunkFilename), {
<del> hash: `" + ${this.renderCurrentHashCode(hash)} + "`,
<del> hashWithLength: (length) => `" + ${this.renderCurrentHashCode(hash, length)} + "`,
<add> mainTemplate.applyPluginsWaterfall("asset-path", JSON.stringify(chunkFilename), {
<add> hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`,
<add> hashWithLength: (length) => `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`,
<ide> chunk: {
<ide> id: "\" + chunkId + \""
<ide> }
<ide> class WebWorkerMainTemplatePlugin {
<ide> "});"
<ide> ]);
<ide> });
<del> mainTemplate.plugin("bootstrap", function(source, chunk, hash) {
<add> mainTemplate.plugin("bootstrap", (source, chunk, hash) => {
<ide> if(chunk.getNumberOfChunks() > 0) {
<del> const chunkCallbackName = this.outputOptions.chunkCallbackName || Template.toIdentifier("webpackChunk" + (this.outputOptions.library || ""));
<del> return this.asString([
<add> const chunkCallbackName = mainTemplate.outputOptions.chunkCallbackName || Template.toIdentifier("webpackChunk" + (mainTemplate.outputOptions.library || ""));
<add> return mainTemplate.asString([
<ide> source,
<del> `this[${JSON.stringify(chunkCallbackName)}] = function webpackChunkCallback(chunkIds, moreModules) {`,
<del> this.indent([
<add> `mainTemplate[${JSON.stringify(chunkCallbackName)}] = function webpackChunkCallback(chunkIds, moreModules) {`,
<add> mainTemplate.indent([
<ide> "for(var moduleId in moreModules) {",
<del> this.indent(this.renderAddModule(hash, chunk, "moduleId", "moreModules[moduleId]")),
<add> mainTemplate.indent(mainTemplate.renderAddModule(hash, chunk, "moduleId", "moreModules[moduleId]")),
<ide> "}",
<ide> "while(chunkIds.length)",
<del> this.indent("installedChunks[chunkIds.pop()] = 1;")
<add> mainTemplate.indent("installedChunks[chunkIds.pop()] = 1;")
<ide> ]),
<ide> "};"
<ide> ]);
<ide> }
<ide> return source;
<ide> });
<del> mainTemplate.plugin("hot-bootstrap", function(source, chunk, hash) {
<del> const hotUpdateChunkFilename = this.outputOptions.hotUpdateChunkFilename;
<del> const hotUpdateMainFilename = this.outputOptions.hotUpdateMainFilename;
<del> const hotUpdateFunction = this.outputOptions.hotUpdateFunction || Template.toIdentifier("webpackHotUpdate" + (this.outputOptions.library || ""));
<del> const currentHotUpdateChunkFilename = this.applyPluginsWaterfall("asset-path", JSON.stringify(hotUpdateChunkFilename), {
<del> hash: `" + ${this.renderCurrentHashCode(hash)} + "`,
<del> hashWithLength: (length) => `" + ${this.renderCurrentHashCode(hash, length)} + "`,
<add> mainTemplate.plugin("hot-bootstrap", (source, chunk, hash) => {
<add> const hotUpdateChunkFilename = mainTemplate.outputOptions.hotUpdateChunkFilename;
<add> const hotUpdateMainFilename = mainTemplate.outputOptions.hotUpdateMainFilename;
<add> const hotUpdateFunction = mainTemplate.outputOptions.hotUpdateFunction || Template.toIdentifier("webpackHotUpdate" + (mainTemplate.outputOptions.library || ""));
<add> const currentHotUpdateChunkFilename = mainTemplate.applyPluginsWaterfall("asset-path", JSON.stringify(hotUpdateChunkFilename), {
<add> hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`,
<add> hashWithLength: (length) => `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`,
<ide> chunk: {
<ide> id: "\" + chunkId + \""
<ide> }
<ide> });
<del> const currentHotUpdateMainFilename = this.applyPluginsWaterfall("asset-path", JSON.stringify(hotUpdateMainFilename), {
<del> hash: `" + ${this.renderCurrentHashCode(hash)} + "`,
<del> hashWithLength: (length) => `" + ${this.renderCurrentHashCode(hash, length)} + "`,
<add> const currentHotUpdateMainFilename = mainTemplate.applyPluginsWaterfall("asset-path", JSON.stringify(hotUpdateMainFilename), {
<add> hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`,
<add> hashWithLength: (length) => `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`,
<ide> });
<ide>
<ide> return source + "\n" +
<ide> `var parentHotUpdateCallback = this[${JSON.stringify(hotUpdateFunction)}];\n` +
<ide> `this[${JSON.stringify(hotUpdateFunction)}] = ` +
<ide> Template.getFunctionContent(require("./WebWorkerMainTemplate.runtime.js"))
<ide> .replace(/\/\/\$semicolon/g, ";")
<del> .replace(/\$require\$/g, this.requireFn)
<add> .replace(/\$require\$/g, mainTemplate.requireFn)
<ide> .replace(/\$hotMainFilename\$/g, currentHotUpdateMainFilename)
<ide> .replace(/\$hotChunkFilename\$/g, currentHotUpdateChunkFilename)
<ide> .replace(/\$hash\$/g, JSON.stringify(hash));
<ide> });
<del> mainTemplate.plugin("hash", function(hash) {
<add> mainTemplate.plugin("hash", hash => {
<ide> hash.update("webworker");
<ide> hash.update("3");
<del> hash.update(`${this.outputOptions.publicPath}`);
<del> hash.update(`${this.outputOptions.filename}`);
<del> hash.update(`${this.outputOptions.chunkFilename}`);
<del> hash.update(`${this.outputOptions.chunkCallbackName}`);
<del> hash.update(`${this.outputOptions.library}`);
<add> hash.update(`${mainTemplate.outputOptions.publicPath}`);
<add> hash.update(`${mainTemplate.outputOptions.filename}`);
<add> hash.update(`${mainTemplate.outputOptions.chunkFilename}`);
<add> hash.update(`${mainTemplate.outputOptions.chunkCallbackName}`);
<add> hash.update(`${mainTemplate.outputOptions.library}`);
<ide> });
<ide> }
<ide> } | 75 |
PHP | PHP | prevent $config conflicts within config files | 5311a22735cad8ae34e42e8b4e76b03d5e928399 | <ide><path>src/Illuminate/Foundation/Bootstrap/LoadConfiguration.php
<ide> public function bootstrap(Application $app)
<ide> * @param \Illuminate\Contracts\Config\Repository $config
<ide> * @return void
<ide> */
<del> protected function loadConfigurationFiles(Application $app, RepositoryContract $config)
<add> protected function loadConfigurationFiles(Application $app, RepositoryContract $configRepo)
<ide> {
<ide> foreach ($this->getConfigurationFiles($app) as $key => $path) {
<del> $config->set($key, require $path);
<add> $configRepo->set($key, require $path);
<ide> }
<ide> }
<ide> | 1 |
Ruby | Ruby | fix bintray url for bottle uploading | 5773ca64c509094b261bdcfc43cadc9c8fd566c5 | <ide><path>Library/Homebrew/cmd/test-bot.rb
<ide> def test_ci_upload(tap)
<ide> tag = pr ? "pr-#{pr}" : "testing-#{number}"
<ide> safe_system "git", "push", "--force", remote, "master:master", ":refs/tags/#{tag}"
<ide>
<del> bintray_repo = if tap.nil?
<del> Bintray.repository(tap)
<del> else
<del> Bintray.repository(tap.name)
<del> end
<add> bintray_repo = Bintray.repository(tap)
<ide> bintray_repo_url = "https://api.bintray.com/packages/homebrew/#{bintray_repo}"
<ide> formula_packaged = {}
<ide> | 1 |
Java | Java | fix package cycle | 558d7f3f3efa4bdc03e252474bec46f62c2acb72 | <add><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/socket/HandshakeInfo.java
<del><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/socket/adapter/HandshakeInfo.java
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> */
<del>package org.springframework.web.reactive.socket.adapter;
<add>package org.springframework.web.reactive.socket;
<ide>
<ide> import java.net.URI;
<ide> import java.security.Principal;
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/socket/WebSocketMessage.java
<ide> public String getPayloadAsText() {
<ide> * </pre>
<ide> * @see DataBufferUtils#retain(DataBuffer)
<ide> */
<del> public void retainPayload() {
<add> public WebSocketMessage retain() {
<ide> DataBufferUtils.retain(this.payload);
<add> return this;
<ide> }
<ide>
<ide> /**
<del> * Release the data buffer for the message payload, which is useful on
<del> * runtimes with pooled buffers, e.g. Netty. This is a shortcut for:
<add> * Release the payload {@code DataBuffer} which is useful on runtimes with
<add> * pooled buffers such as Netty. Effectively a shortcut for:
<ide> * <pre>
<ide> * DataBuffer payload = message.getPayload();
<ide> * DataBufferUtils.release(payload);
<ide> * </pre>
<ide> * @see DataBufferUtils#release(DataBuffer)
<ide> */
<del> public void releasePayload() {
<add> public void release() {
<ide> DataBufferUtils.release(this.payload);
<ide> }
<ide>
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/socket/WebSocketSession.java
<ide> */
<ide> package org.springframework.web.reactive.socket;
<ide>
<del>import java.net.URI;
<del>import java.security.Principal;
<del>import java.util.Optional;
<ide> import java.util.function.Function;
<ide>
<ide> import org.reactivestreams.Publisher;
<ide>
<ide> import org.springframework.core.io.buffer.DataBuffer;
<ide> import org.springframework.core.io.buffer.DataBufferFactory;
<del>import org.springframework.http.HttpHeaders;
<del>import org.springframework.web.reactive.socket.adapter.HandshakeInfo;
<ide>
<ide> /**
<ide> * Representation for a WebSocket session.
<ide> public interface WebSocketSession {
<ide> */
<ide> Mono<Void> send(Publisher<WebSocketMessage> messages);
<ide>
<add> /**
<add> * Close the WebSocket session with {@link CloseStatus#NORMAL}.
<add> */
<add> default Mono<Void> close() {
<add> return close(CloseStatus.NORMAL);
<add> }
<add>
<add> /**
<add> * Close the WebSocket session with the given status.
<add> * @param status the close status
<add> */
<add> Mono<Void> close(CloseStatus status);
<add>
<add>
<add> // WebSocketMessage factory methods
<add>
<ide> /**
<ide> * Factory method to create a text {@link WebSocketMessage} using the
<ide> * {@link #bufferFactory()} for the session.
<ide> public interface WebSocketSession {
<ide> */
<ide> WebSocketMessage pongMessage(Function<DataBufferFactory, DataBuffer> payloadFactory);
<ide>
<del> /**
<del> * Close the WebSocket session with {@link CloseStatus#NORMAL}.
<del> */
<del> default Mono<Void> close() {
<del> return close(CloseStatus.NORMAL);
<del> }
<del>
<del> /**
<del> * Close the WebSocket session with the given status.
<del> * @param status the close status
<del> */
<del> Mono<Void> close(CloseStatus status);
<del>
<ide> }
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/socket/adapter/AbstractListenerWebSocketSession.java
<ide> import org.springframework.http.server.reactive.AbstractListenerReadPublisher;
<ide> import org.springframework.http.server.reactive.AbstractListenerWriteProcessor;
<ide> import org.springframework.web.reactive.socket.CloseStatus;
<add>import org.springframework.web.reactive.socket.HandshakeInfo;
<ide> import org.springframework.web.reactive.socket.WebSocketMessage;
<ide> import org.springframework.web.reactive.socket.WebSocketMessage.Type;
<ide> import org.springframework.web.reactive.socket.WebSocketSession;
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/socket/adapter/JettyWebSocketHandlerAdapter.java
<ide> import org.springframework.core.io.buffer.DataBuffer;
<ide> import org.springframework.core.io.buffer.DataBufferFactory;
<ide> import org.springframework.web.reactive.socket.CloseStatus;
<add>import org.springframework.web.reactive.socket.HandshakeInfo;
<ide> import org.springframework.web.reactive.socket.WebSocketHandler;
<ide> import org.springframework.web.reactive.socket.WebSocketMessage;
<ide> import org.springframework.web.reactive.socket.WebSocketMessage.Type;
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/socket/adapter/JettyWebSocketSession.java
<ide> import org.springframework.core.io.buffer.DataBufferFactory;
<ide> import org.springframework.util.ObjectUtils;
<ide> import org.springframework.web.reactive.socket.CloseStatus;
<add>import org.springframework.web.reactive.socket.HandshakeInfo;
<ide> import org.springframework.web.reactive.socket.WebSocketMessage;
<ide> import org.springframework.web.reactive.socket.WebSocketSession;
<ide>
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/socket/adapter/NettyWebSocketSessionSupport.java
<ide> import org.springframework.core.io.buffer.NettyDataBuffer;
<ide> import org.springframework.core.io.buffer.NettyDataBufferFactory;
<ide> import org.springframework.util.ObjectUtils;
<add>import org.springframework.web.reactive.socket.HandshakeInfo;
<ide> import org.springframework.web.reactive.socket.WebSocketMessage;
<ide> import org.springframework.web.reactive.socket.WebSocketSession;
<ide>
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/socket/adapter/ReactorNettyWebSocketSession.java
<ide>
<ide> import org.springframework.core.io.buffer.NettyDataBufferFactory;
<ide> import org.springframework.web.reactive.socket.CloseStatus;
<add>import org.springframework.web.reactive.socket.HandshakeInfo;
<ide> import org.springframework.web.reactive.socket.WebSocketMessage;
<ide> import org.springframework.web.reactive.socket.WebSocketSession;
<ide>
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/socket/adapter/RxNettyWebSocketSession.java
<ide>
<ide> import org.springframework.core.io.buffer.NettyDataBufferFactory;
<ide> import org.springframework.web.reactive.socket.CloseStatus;
<add>import org.springframework.web.reactive.socket.HandshakeInfo;
<ide> import org.springframework.web.reactive.socket.WebSocketMessage;
<ide> import org.springframework.web.reactive.socket.WebSocketSession;
<ide>
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/socket/adapter/TomcatWebSocketHandlerAdapter.java
<ide> import org.springframework.core.io.buffer.DataBuffer;
<ide> import org.springframework.core.io.buffer.DataBufferFactory;
<ide> import org.springframework.web.reactive.socket.CloseStatus;
<add>import org.springframework.web.reactive.socket.HandshakeInfo;
<ide> import org.springframework.web.reactive.socket.WebSocketHandler;
<ide> import org.springframework.web.reactive.socket.WebSocketMessage;
<ide> import org.springframework.web.reactive.socket.WebSocketMessage.Type;
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/socket/adapter/TomcatWebSocketSession.java
<ide>
<ide> import org.springframework.core.io.buffer.DataBufferFactory;
<ide> import org.springframework.web.reactive.socket.CloseStatus;
<add>import org.springframework.web.reactive.socket.HandshakeInfo;
<ide> import org.springframework.web.reactive.socket.WebSocketMessage;
<ide> import org.springframework.web.reactive.socket.WebSocketSession;
<ide>
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/socket/adapter/UndertowWebSocketHandlerAdapter.java
<ide> import org.springframework.core.io.buffer.DataBuffer;
<ide> import org.springframework.core.io.buffer.DataBufferFactory;
<ide> import org.springframework.web.reactive.socket.CloseStatus;
<add>import org.springframework.web.reactive.socket.HandshakeInfo;
<ide> import org.springframework.web.reactive.socket.WebSocketHandler;
<ide> import org.springframework.web.reactive.socket.WebSocketMessage;
<ide> import org.springframework.web.reactive.socket.WebSocketMessage.Type;
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/socket/adapter/UndertowWebSocketSession.java
<ide> import org.springframework.core.io.buffer.DataBufferFactory;
<ide> import org.springframework.util.ObjectUtils;
<ide> import org.springframework.web.reactive.socket.CloseStatus;
<add>import org.springframework.web.reactive.socket.HandshakeInfo;
<ide> import org.springframework.web.reactive.socket.WebSocketMessage;
<ide> import org.springframework.web.reactive.socket.WebSocketSession;
<ide>
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/socket/adapter/WebSocketHandlerAdapterSupport.java
<ide>
<ide> import org.springframework.core.io.buffer.DataBufferFactory;
<ide> import org.springframework.util.Assert;
<add>import org.springframework.web.reactive.socket.HandshakeInfo;
<ide> import org.springframework.web.reactive.socket.WebSocketHandler;
<ide>
<ide> /**
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/socket/adapter/WebSocketSessionSupport.java
<ide> import org.springframework.core.io.buffer.DataBufferFactory;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.web.reactive.socket.CloseStatus;
<add>import org.springframework.web.reactive.socket.HandshakeInfo;
<ide> import org.springframework.web.reactive.socket.WebSocketMessage;
<ide> import org.springframework.web.reactive.socket.WebSocketSession;
<ide>
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/socket/client/RxNettyWebSocketClient.java
<ide> import org.springframework.core.io.buffer.NettyDataBufferFactory;
<ide> import org.springframework.http.HttpHeaders;
<ide> import org.springframework.web.reactive.socket.WebSocketSession;
<del>import org.springframework.web.reactive.socket.adapter.HandshakeInfo;
<add>import org.springframework.web.reactive.socket.HandshakeInfo;
<ide> import org.springframework.web.reactive.socket.adapter.RxNettyWebSocketSession;
<ide>
<ide> /**
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/socket/server/upgrade/JettyRequestUpgradeStrategy.java
<ide> import org.springframework.http.server.reactive.ServletServerHttpResponse;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.web.reactive.socket.WebSocketHandler;
<del>import org.springframework.web.reactive.socket.adapter.HandshakeInfo;
<add>import org.springframework.web.reactive.socket.HandshakeInfo;
<ide> import org.springframework.web.reactive.socket.adapter.JettyWebSocketHandlerAdapter;
<ide> import org.springframework.web.reactive.socket.server.RequestUpgradeStrategy;
<ide> import org.springframework.web.server.ServerWebExchange;
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/socket/server/upgrade/ReactorNettyRequestUpgradeStrategy.java
<ide> import org.springframework.http.server.reactive.ReactorServerHttpResponse;
<ide> import org.springframework.util.StringUtils;
<ide> import org.springframework.web.reactive.socket.WebSocketHandler;
<del>import org.springframework.web.reactive.socket.adapter.HandshakeInfo;
<add>import org.springframework.web.reactive.socket.HandshakeInfo;
<ide> import org.springframework.web.reactive.socket.adapter.ReactorNettyWebSocketSession;
<ide> import org.springframework.web.reactive.socket.server.RequestUpgradeStrategy;
<ide> import org.springframework.web.server.ServerWebExchange;
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/socket/server/upgrade/RxNettyRequestUpgradeStrategy.java
<ide> import org.springframework.http.server.reactive.RxNettyServerHttpResponse;
<ide> import org.springframework.web.reactive.socket.WebSocketHandler;
<ide> import org.springframework.web.reactive.socket.WebSocketSession;
<del>import org.springframework.web.reactive.socket.adapter.HandshakeInfo;
<add>import org.springframework.web.reactive.socket.HandshakeInfo;
<ide> import org.springframework.web.reactive.socket.adapter.RxNettyWebSocketSession;
<ide> import org.springframework.web.reactive.socket.server.RequestUpgradeStrategy;
<ide> import org.springframework.web.server.ServerWebExchange;
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/socket/server/upgrade/TomcatRequestUpgradeStrategy.java
<ide> import org.springframework.http.server.reactive.ServletServerHttpResponse;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.web.reactive.socket.WebSocketHandler;
<del>import org.springframework.web.reactive.socket.adapter.HandshakeInfo;
<add>import org.springframework.web.reactive.socket.HandshakeInfo;
<ide> import org.springframework.web.reactive.socket.adapter.TomcatWebSocketHandlerAdapter;
<ide> import org.springframework.web.reactive.socket.server.RequestUpgradeStrategy;
<ide> import org.springframework.web.server.ServerWebExchange;
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/socket/server/upgrade/UndertowRequestUpgradeStrategy.java
<ide> import org.springframework.http.server.reactive.UndertowServerHttpRequest;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.web.reactive.socket.WebSocketHandler;
<del>import org.springframework.web.reactive.socket.adapter.HandshakeInfo;
<add>import org.springframework.web.reactive.socket.HandshakeInfo;
<ide> import org.springframework.web.reactive.socket.adapter.UndertowWebSocketHandlerAdapter;
<ide> import org.springframework.web.reactive.socket.server.RequestUpgradeStrategy;
<ide> import org.springframework.web.server.ServerWebExchange;
<ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/socket/server/WebSocketIntegrationTests.java
<ide>
<ide> import org.springframework.context.annotation.Bean;
<ide> import org.springframework.context.annotation.Configuration;
<del>import org.springframework.core.io.buffer.DataBufferUtils;
<ide> import org.springframework.web.reactive.HandlerMapping;
<ide> import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping;
<ide> import org.springframework.web.reactive.socket.WebSocketHandler;
<ide> public void echo() throws Exception {
<ide> .take(count)
<ide> .map(message -> {
<ide> String text = message.getPayloadAsText();
<del> DataBufferUtils.release(message.getPayload());
<add> message.release();
<ide> return text;
<ide> })
<ide> )); | 22 |
Go | Go | fix race condition in execcommandgc | e5e62b96ce0d4eb3934a386b07203830f55e07ce | <ide><path>daemon/exec/exec.go
<ide> func NewStore() *Store {
<ide>
<ide> // Commands returns the exec configurations in the store.
<ide> func (e *Store) Commands() map[string]*Config {
<del> return e.commands
<add> e.RLock()
<add> commands := make(map[string]*Config, len(e.commands))
<add> for id, config := range e.commands {
<add> commands[id] = config
<add> }
<add> e.RUnlock()
<add> return commands
<ide> }
<ide>
<ide> // Add adds a new exec configuration to the store. | 1 |
Text | Text | add release notes for v1.5.8 | 228754fe96ae5613bf4b419605891e3be3e3f75f | <ide><path>CHANGELOG.md
<add><a name="1.5.8"></a>
<add># 1.5.8 arbitrary-fallbacks (2016-07-22)
<add>
<add>
<add>## Bug Fixes
<add>
<add>- **$animate:** do not get affected by custom, enumerable properties on `Object.prototype`
<add> ([181e4401](https://github.com/angular/angular.js/commit/181e44019e850e5253378e29415cddf8d768bbef),
<add> [#14804](https://github.com/angular/angular.js/issues/14804), [#14830](https://github.com/angular/angular.js/issues/14830))
<add>- **$compile:** ensure `$doCheck` hooks can be defined in the controller constructor
<add> ([3010ed4e](https://github.com/angular/angular.js/commit/3010ed4ee5c2c18b9848b5664639971b9fdc8919),
<add> [#14811](https://github.com/angular/angular.js/issues/14811))
<add>- **$injector:** fix class detection RegExp
<add> ([4724d56c](https://github.com/angular/angular.js/commit/4724d56c939d02675433e7fe554608dff97ecf81),
<add> [#14533](https://github.com/angular/angular.js/issues/14533))
<add>- **$jsonpCallbacks:** do not overwrite callbacks added by other apps
<add> ([1778d347](https://github.com/angular/angular.js/commit/1778d347cd3c91335e3840eaa49f1e387db8602f),
<add> [#14824](https://github.com/angular/angular.js/issues/14824))
<add>- **$timeout:** make $flush handle new $timeouts added in $timeout callbacks
<add> ([1a387ba5](https://github.com/angular/angular.js/commit/1a387ba5dd1a8a831486fce23f6795bd1eef3d8b),
<add> [#5420](https://github.com/angular/angular.js/issues/5420), [#14686](https://github.com/angular/angular.js/issues/14686))
<add>- **copy:** fix handling of typed subarrays
<add> ([1645924d](https://github.com/angular/angular.js/commit/1645924d49a7905ce55cced4c4276654970bb226),
<add> [#14842](https://github.com/angular/angular.js/issues/14842), [#14845](https://github.com/angular/angular.js/issues/14845))
<add>- **modules:** allow modules to be loaded in any order when using `angular-loader`
<add> ([98e4a220](https://github.com/angular/angular.js/commit/98e4a220fe8301cec35498ae592adc0266f12437),
<add> [#9140](https://github.com/angular/angular.js/issues/9140), [#14794](https://github.com/angular/angular.js/issues/14794))
<add>- **ngAnimate:** allow removal of class that is scheduled to be added with requestAnimationFrame
<add> ([7ccfe92b](https://github.com/angular/angular.js/commit/7ccfe92bed7361832f1b8d25b1a8411eb24d3fb5),
<add> [#14582](https://github.com/angular/angular.js/issues/14582))
<add>- **ngMocks:** allow `ErrorAddingDeclarationLocationStack` to be recognized as an `Error`
<add> ([c6074dc3](https://github.com/angular/angular.js/commit/c6074dc34c31a07269bf7f628b971ef6dc805f17),
<add> [#13821](https://github.com/angular/angular.js/issues/13821), [#14344](https://github.com/angular/angular.js/issues/14344))
<add>- **ngOptions:** don't duplicate groups with falsy values
<add> ([c3bfd7f5](https://github.com/angular/angular.js/commit/c3bfd7f59d0ecbf4ba3253fb407e683c7bb0766c))
<add>- **ngTransclude:**
<add> - ensure that fallback content is compiled and linked correctly
<add> ([c405f88b](https://github.com/angular/angular.js/commit/c405f88bbc743f41591f6f3cfc022eea3c6c34ad),
<add> [#14787](https://github.com/angular/angular.js/issues/14787))
<add> - only compile fallback content if necessary
<add> ([159a68ec](https://github.com/angular/angular.js/commit/159a68ec7ba77e9128b0d0516b813ed3d223b6e3),
<add> [#14768](https://github.com/angular/angular.js/issues/14768), [#14765](https://github.com/angular/angular.js/issues/14765), [#14775](https://github.com/angular/angular.js/issues/14775))
<add>
<add>
<add>## Features
<add>
<add>- **$compile:** backport $doCheck
<add> ([de59ca71](https://github.com/angular/angular.js/commit/de59ca71072eac95ee68de308f92bc5f921dd07b),
<add> [#14656](https://github.com/angular/angular.js/issues/14656))
<add>- **$jsonpCallbacks:** new service to abstract how JSONP callbacks are handled
<add> ([a8cacfe9](https://github.com/angular/angular.js/commit/a8cacfe938287c54ce7099125cb735ad53f4c7c2),
<add> [#14795](https://github.com/angular/angular.js/issues/14795))
<add>- **$q:** implement $q.race
<add> ([b9a56d58](https://github.com/angular/angular.js/commit/b9a56d588f8b597b1dff30d8e184b7c37d94cdcf),
<add> [#12929](https://github.com/angular/angular.js/issues/12929), [#14757](https://github.com/angular/angular.js/issues/14757))
<add>- **$resource:** pass the resource to a dynamic param functions
<add> ([a126fcfe](https://github.com/angular/angular.js/commit/a126fcfee3bd8b02869bd2542c73e1eb21afe927),
<add> [#4899](https://github.com/angular/angular.js/issues/4899))
<add>- **$swipe:** add pointer support
<add> ([f797f83c](https://github.com/angular/angular.js/commit/f797f83cd66f1fd11b3c9399e7894217ffa06c38),
<add> [#14061](https://github.com/angular/angular.js/issues/14061), [#14791](https://github.com/angular/angular.js/issues/14791))
<add>- **filterFilter:** allow overwriting the special `$` property name
<add> ([33514ec3](https://github.com/angular/angular.js/commit/33514ec384d676d84b2a445bc15bae38c8c3ac8d),
<add> [#13313](https://github.com/angular/angular.js/issues/13313))
<add>
<add>
<add>## Performance Improvements
<add>
<add>- **$compile:** wrap try/catch of collect comment directives into a function to avoid V8 deopt
<add> ([acd45518](https://github.com/angular/angular.js/commit/acd455181de1cfa6b34d75f8d71a6c0b6995a777),
<add> [#14848](https://github.com/angular/angular.js/issues/14848))
<add>
<add>
<ide> <a name="1.2.30"></a>
<ide> # 1.2.30 patronal-resurrection (2016-07-21)
<ide> | 1 |
Javascript | Javascript | allow loading pdf fonts into another document | ac723a1760b9d9c67a06fe5e007d8c9a5dd2ca7e | <ide><path>src/display/api.js
<ide> function setPDFNetworkStreamFactory(pdfNetworkStreamFactory) {
<ide> * parsed font data from the worker-thread. This may be useful for debugging
<ide> * purposes (and backwards compatibility), but note that it will lead to
<ide> * increased memory usage. The default value is `false`.
<add> * @property {HTMLDocument} [ownerDocument] - Specify an explicit document
<add> * context to create elements with and to load resources, such as fonts,
<add> * into. Defaults to the current document.
<ide> * @property {boolean} [disableRange] - Disable range request loading of PDF
<ide> * files. When enabled, and if the server supports partial content requests,
<ide> * then the PDF will be fetched in chunks. The default value is `false`.
<ide> function getDocument(src) {
<ide> if (typeof params.disableFontFace !== "boolean") {
<ide> params.disableFontFace = apiCompatibilityParams.disableFontFace || false;
<ide> }
<add> if (typeof params.ownerDocument === "undefined") {
<add> params.ownerDocument = globalThis.document;
<add> }
<ide>
<ide> if (typeof params.disableRange !== "boolean") {
<ide> params.disableRange = false;
<ide> class PDFDocumentProxy {
<ide> * Proxy to a `PDFPage` in the worker thread.
<ide> */
<ide> class PDFPageProxy {
<del> constructor(pageIndex, pageInfo, transport, pdfBug = false) {
<add> constructor(pageIndex, pageInfo, transport, ownerDocument, pdfBug = false) {
<ide> this._pageIndex = pageIndex;
<ide> this._pageInfo = pageInfo;
<add> this._ownerDocument = ownerDocument;
<ide> this._transport = transport;
<ide> this._stats = pdfBug ? new StatTimer() : null;
<ide> this._pdfBug = pdfBug;
<ide> class PDFPageProxy {
<ide> intentState.streamReaderCancelTimeout = null;
<ide> }
<ide>
<del> const canvasFactoryInstance = canvasFactory || new DefaultCanvasFactory();
<add> const canvasFactoryInstance =
<add> canvasFactory ||
<add> new DefaultCanvasFactory({ ownerDocument: this._ownerDocument });
<ide> const webGLContext = new WebGLContext({
<ide> enable: enableWebGL,
<ide> });
<ide> class WorkerTransport {
<ide> this.fontLoader = new FontLoader({
<ide> docId: loadingTask.docId,
<ide> onUnsupportedFeature: this._onUnsupportedFeature.bind(this),
<add> ownerDocument: params.ownerDocument,
<ide> });
<ide> this._params = params;
<ide> this.CMapReaderFactory = new params.CMapReaderFactory({
<ide> class WorkerTransport {
<ide> pageIndex,
<ide> pageInfo,
<ide> this,
<add> this._params.ownerDocument,
<ide> this._params.pdfBug
<ide> );
<ide> this.pageCache[pageIndex] = page;
<ide><path>src/display/display_utils.js
<ide> class BaseCanvasFactory {
<ide> }
<ide>
<ide> class DOMCanvasFactory extends BaseCanvasFactory {
<add> constructor({ ownerDocument = globalThis.document } = {}) {
<add> super();
<add> this._document = ownerDocument;
<add> }
<add>
<ide> create(width, height) {
<ide> if (width <= 0 || height <= 0) {
<ide> throw new Error("Invalid canvas size");
<ide> }
<del> const canvas = document.createElement("canvas");
<add> const canvas = this._document.createElement("canvas");
<ide> const context = canvas.getContext("2d");
<ide> canvas.width = width;
<ide> canvas.height = height;
<ide><path>src/display/font_loader.js
<ide> import {
<ide> } from "../shared/util.js";
<ide>
<ide> class BaseFontLoader {
<del> constructor({ docId, onUnsupportedFeature }) {
<add> constructor({
<add> docId,
<add> onUnsupportedFeature,
<add> ownerDocument = globalThis.document,
<add> }) {
<ide> if (this.constructor === BaseFontLoader) {
<ide> unreachable("Cannot initialize BaseFontLoader.");
<ide> }
<ide> this.docId = docId;
<ide> this._onUnsupportedFeature = onUnsupportedFeature;
<add> this._document = ownerDocument;
<ide>
<ide> this.nativeFontFaces = [];
<ide> this.styleElement = null;
<ide> }
<ide>
<ide> addNativeFontFace(nativeFontFace) {
<ide> this.nativeFontFaces.push(nativeFontFace);
<del> document.fonts.add(nativeFontFace);
<add> this._document.fonts.add(nativeFontFace);
<ide> }
<ide>
<ide> insertRule(rule) {
<ide> let styleElement = this.styleElement;
<ide> if (!styleElement) {
<del> styleElement = this.styleElement = document.createElement("style");
<add> styleElement = this.styleElement = this._document.createElement("style");
<ide> styleElement.id = `PDFJS_FONT_STYLE_TAG_${this.docId}`;
<del> document.documentElement
<add> this._document.documentElement
<ide> .getElementsByTagName("head")[0]
<ide> .appendChild(styleElement);
<ide> }
<ide> class BaseFontLoader {
<ide> }
<ide>
<ide> clear() {
<del> this.nativeFontFaces.forEach(function (nativeFontFace) {
<del> document.fonts.delete(nativeFontFace);
<add> this.nativeFontFaces.forEach(nativeFontFace => {
<add> this._document.fonts.delete(nativeFontFace);
<ide> });
<ide> this.nativeFontFaces.length = 0;
<ide>
<ide> class BaseFontLoader {
<ide> }
<ide>
<ide> get isFontLoadingAPISupported() {
<del> const supported = typeof document !== "undefined" && !!document.fonts;
<add> const supported =
<add> typeof this._document !== "undefined" && !!this._document.fonts;
<ide> return shadow(this, "isFontLoadingAPISupported", supported);
<ide> }
<ide>
<ide> if (typeof PDFJSDev !== "undefined" && PDFJSDev.test("MOZCENTRAL")) {
<ide> // PDFJSDev.test('CHROME || GENERIC')
<ide>
<ide> FontLoader = class GenericFontLoader extends BaseFontLoader {
<del> constructor(docId) {
<del> super(docId);
<add> constructor(params) {
<add> super(params);
<ide> this.loadingContext = {
<ide> requests: [],
<ide> nextRequestId: 0,
<ide> if (typeof PDFJSDev !== "undefined" && PDFJSDev.test("MOZCENTRAL")) {
<ide> let i, ii;
<ide>
<ide> // The temporary canvas is used to determine if fonts are loaded.
<del> const canvas = document.createElement("canvas");
<add> const canvas = this._document.createElement("canvas");
<ide> canvas.width = 1;
<ide> canvas.height = 1;
<ide> const ctx = canvas.getContext("2d");
<ide> if (typeof PDFJSDev !== "undefined" && PDFJSDev.test("MOZCENTRAL")) {
<ide> }
<ide> names.push(loadTestFontId);
<ide>
<del> const div = document.createElement("div");
<add> const div = this._document.createElement("div");
<ide> div.style.visibility = "hidden";
<ide> div.style.width = div.style.height = "10px";
<ide> div.style.position = "absolute";
<ide> div.style.top = div.style.left = "0px";
<ide>
<ide> for (i = 0, ii = names.length; i < ii; ++i) {
<del> const span = document.createElement("span");
<add> const span = this._document.createElement("span");
<ide> span.textContent = "Hi";
<ide> span.style.fontFamily = names[i];
<ide> div.appendChild(span);
<ide> }
<del> document.body.appendChild(div);
<add> this._document.body.appendChild(div);
<ide>
<del> isFontReady(loadTestFontId, function () {
<del> document.body.removeChild(div);
<add> isFontReady(loadTestFontId, () => {
<add> this._document.body.removeChild(div);
<ide> request.complete();
<ide> });
<ide> /** Hack end */
<ide><path>src/display/text_layer.js
<ide> var renderTextLayer = (function renderTextLayerClosure() {
<ide> this._textContent = textContent;
<ide> this._textContentStream = textContentStream;
<ide> this._container = container;
<add> this._document = container.ownerDocument;
<ide> this._viewport = viewport;
<ide> this._textDivs = textDivs || [];
<ide> this._textContentItemsStr = textContentItemsStr || [];
<ide> var renderTextLayer = (function renderTextLayerClosure() {
<ide> let styleCache = Object.create(null);
<ide>
<ide> // The temporary canvas is used to measure text length in the DOM.
<del> const canvas = document.createElement("canvas");
<add> const canvas = this._document.createElement("canvas");
<ide> if (
<ide> typeof PDFJSDev === "undefined" ||
<ide> PDFJSDev.test("MOZCENTRAL || GENERIC")
<ide><path>test/unit/custom_spec.js
<ide> describe("custom canvas rendering", function () {
<ide> .catch(done.fail);
<ide> });
<ide> });
<add>
<add>describe("custom ownerDocument", function () {
<add> const FontFace = globalThis.FontFace;
<add>
<add> const checkFont = font => /g_d\d+_f1/.test(font.family);
<add> const checkFontFaceRule = rule =>
<add> /^@font-face {font-family:"g_d\d+_f1";src:/.test(rule);
<add>
<add> beforeEach(() => {
<add> globalThis.FontFace = function MockFontFace(name) {
<add> this.family = name;
<add> };
<add> });
<add>
<add> afterEach(() => {
<add> globalThis.FontFace = FontFace;
<add> });
<add>
<add> function getMocks() {
<add> const elements = [];
<add> const createElement = name => {
<add> let element =
<add> typeof document !== "undefined" && document.createElement(name);
<add> if (name === "style") {
<add> element = {
<add> tagName: name,
<add> sheet: {
<add> cssRules: [],
<add> insertRule(rule) {
<add> this.cssRules.push(rule);
<add> },
<add> },
<add> };
<add> Object.assign(element, {
<add> remove() {
<add> this.remove.called = true;
<add> },
<add> });
<add> }
<add> elements.push(element);
<add> return element;
<add> };
<add> const ownerDocument = {
<add> fonts: new Set(),
<add> createElement,
<add> documentElement: {
<add> getElementsByTagName: () => [{ appendChild: () => {} }],
<add> },
<add> };
<add>
<add> const CanvasFactory = isNodeJS
<add> ? new NodeCanvasFactory()
<add> : new DOMCanvasFactory({ ownerDocument });
<add> return {
<add> elements,
<add> ownerDocument,
<add> CanvasFactory,
<add> };
<add> }
<add>
<add> it("should use given document for loading fonts (with Font Loading API)", async function () {
<add> const { ownerDocument, elements, CanvasFactory } = getMocks();
<add> const getDocumentParams = buildGetDocumentParams(
<add> "TrueType_without_cmap.pdf",
<add> {
<add> disableFontFace: false,
<add> ownerDocument,
<add> }
<add> );
<add>
<add> const loadingTask = getDocument(getDocumentParams);
<add> const doc = await loadingTask.promise;
<add> const page = await doc.getPage(1);
<add>
<add> const viewport = page.getViewport({ scale: 1 });
<add> const canvasAndCtx = CanvasFactory.create(viewport.width, viewport.height);
<add>
<add> await page.render({
<add> canvasContext: canvasAndCtx.context,
<add> viewport,
<add> }).promise;
<add>
<add> const style = elements.find(element => element.tagName === "style");
<add> expect(style).toBeFalsy();
<add> expect(ownerDocument.fonts.size).toBeGreaterThanOrEqual(1);
<add> expect(Array.from(ownerDocument.fonts).find(checkFont)).toBeTruthy();
<add> await doc.destroy();
<add> await loadingTask.destroy();
<add> CanvasFactory.destroy(canvasAndCtx);
<add> expect(ownerDocument.fonts.size).toBe(0);
<add> });
<add>
<add> it("should use given document for loading fonts (with CSS rules)", async function () {
<add> const { ownerDocument, elements, CanvasFactory } = getMocks();
<add> ownerDocument.fonts = null;
<add> const getDocumentParams = buildGetDocumentParams(
<add> "TrueType_without_cmap.pdf",
<add> {
<add> disableFontFace: false,
<add> ownerDocument,
<add> }
<add> );
<add>
<add> const loadingTask = getDocument(getDocumentParams);
<add> const doc = await loadingTask.promise;
<add> const page = await doc.getPage(1);
<add>
<add> const viewport = page.getViewport({ scale: 1 });
<add> const canvasAndCtx = CanvasFactory.create(viewport.width, viewport.height);
<add>
<add> await page.render({
<add> canvasContext: canvasAndCtx.context,
<add> viewport,
<add> }).promise;
<add>
<add> const style = elements.find(element => element.tagName === "style");
<add> expect(style.sheet.cssRules.length).toBeGreaterThanOrEqual(1);
<add> expect(style.sheet.cssRules.find(checkFontFaceRule)).toBeTruthy();
<add> await doc.destroy();
<add> await loadingTask.destroy();
<add> CanvasFactory.destroy(canvasAndCtx);
<add> expect(style.remove.called).toBe(true);
<add> });
<add>}); | 5 |
Ruby | Ruby | add ignorable module | 8b808308c292e7079a85460dac13d13e1db453aa | <ide><path>Library/Homebrew/debrew.rb
<ide>
<ide> require "mutex_m"
<ide> require "debrew/irb"
<del>require "warnings"
<del>Warnings.ignore(/warning: callcc is obsolete; use Fiber instead/) do
<del> require "continuation"
<del>end
<add>require "ignorable"
<ide>
<ide> # Helper module for debugging formulae.
<ide> #
<ide> # @api private
<ide> module Debrew
<ide> extend Mutex_m
<ide>
<del> # Marks exceptions which can be ignored and provides
<del> # the ability to jump back to where it was raised.
<del> module Ignorable
<del> attr_accessor :continuation
<del>
<del> def ignore
<del> continuation.call
<del> end
<del> end
<del>
<del> # Module for allowing to ignore exceptions.
<del> module Raise
<del> def raise(*)
<del> callcc do |continuation|
<del> super
<del> rescue Exception => e # rubocop:disable Lint/RescueException
<del> e.extend(Ignorable)
<del> e.continuation = continuation
<del> super(e)
<del> end
<del> end
<del>
<del> alias fail raise
<del> end
<del>
<ide> # Module for allowing to debug formulae.
<ide> module Formula
<ide> def install
<ide> def self.choose
<ide>
<ide> class << self
<ide> extend Predicable
<del> alias original_raise raise
<ide> attr_predicate :active?
<ide> attr_reader :debugged_exceptions
<ide> end
<ide>
<ide> def self.debrew
<ide> @active = true
<del> Object.include Raise
<add> Ignorable.hook_raise
<ide>
<ide> begin
<ide> yield
<ide> rescue SystemExit
<del> original_raise
<add> raise
<ide> rescue Exception => e # rubocop:disable Lint/RescueException
<ide> e.ignore if debug(e) == :ignore # execution jumps back to where the exception was thrown
<ide> ensure
<add> Ignorable.unhook_raise
<ide> @active = false
<ide> end
<ide> end
<ide>
<ide> def self.debug(e)
<del> original_raise(e) if !active? || !debugged_exceptions.add?(e) || !try_lock
<add> raise(e) if !active? || !debugged_exceptions.add?(e) || !try_lock
<ide>
<ide> begin
<ide> puts e.backtrace.first.to_s
<ide> def self.debug(e)
<ide> Menu.choose do |menu|
<ide> menu.prompt = "Choose an action: "
<ide>
<del> menu.choice(:raise) { original_raise(e) }
<del> menu.choice(:ignore) { return :ignore } if e.is_a?(Ignorable)
<add> menu.choice(:raise) { raise(e) }
<add> menu.choice(:ignore) { return :ignore } if e.is_a?(Ignorable::ExceptionMixin)
<ide> menu.choice(:backtrace) { puts e.backtrace }
<ide>
<del> if e.is_a?(Ignorable)
<add> if e.is_a?(Ignorable::ExceptionMixin)
<ide> menu.choice(:irb) do
<ide> puts "When you exit this IRB session, execution will continue."
<ide> set_trace_func proc { |event, _, _, id, binding, klass|
<del> if klass == Raise && id == :raise && event == "return"
<add> if klass == Object && id == :raise && event == "return"
<ide> set_trace_func(nil)
<ide> synchronize { IRB.start_within(binding) }
<ide> end
<ide><path>Library/Homebrew/ignorable.rb
<add># typed: false
<add># frozen_string_literal: true
<add>
<add>require "warnings"
<add>Warnings.ignore(/warning: callcc is obsolete; use Fiber instead/) do
<add> require "continuation"
<add>end
<add>
<add># Provides the ability to optionally ignore errors raised and continue execution.
<add>#
<add># @api private
<add>module Ignorable
<add> # Marks exceptions which can be ignored and provides
<add> # the ability to jump back to where it was raised.
<add> module ExceptionMixin
<add> attr_accessor :continuation
<add>
<add> def ignore
<add> continuation.call
<add> end
<add> end
<add>
<add> def self.hook_raise
<add> Object.class_eval do
<add> alias_method :original_raise, :raise
<add>
<add> def raise(*)
<add> callcc do |continuation|
<add> super
<add> rescue Exception => e # rubocop:disable Lint/RescueException
<add> unless e.is_a?(ScriptError)
<add> e.extend(ExceptionMixin)
<add> e.continuation = continuation
<add> end
<add> super(e)
<add> end
<add> end
<add>
<add> alias_method :fail, :raise
<add> end
<add>
<add> return unless block_given?
<add>
<add> yield
<add> unhook_raise
<add> end
<add>
<add> def self.unhook_raise
<add> Object.class_eval do
<add> # False positive - https://github.com/rubocop/rubocop/issues/5022
<add> # rubocop:disable Lint/DuplicateMethods
<add> alias_method :raise, :original_raise
<add> alias_method :fail, :original_raise
<add> # rubocop:enable Lint/DuplicateMethods
<add> undef :original_raise
<add> end
<add> end
<add>end | 2 |
Ruby | Ruby | move complex logic to it's own method | 2afd6c75f18aee67fab85efef2b970572d459db3 | <ide><path>activerecord/lib/active_record/associations/association_collection.rb
<ide> def load_target
<ide> unless loaded?
<ide> begin
<ide> if @target.is_a?(Array) && @target.any?
<del> @target = find_target.map do |f|
<del> i = @target.index(f)
<del> if i
<del> @target.delete_at(i).tap do |t|
<del> keys = ["id"] + t.changes.keys + (f.attribute_names - t.attribute_names)
<del> # FIXME: this call to attributes causes many NoMethodErrors
<del> attributes = f.attributes
<del> (attributes.keys - keys).each do |k|
<del> t.send("#{k}=", attributes[k])
<del> end
<del> end
<del> else
<del> f
<del> end
<del> end + @target
<add> @target = merge_target_lists(find_target, @target)
<ide> else
<ide> @target = find_target
<ide> end
<ide> def add_record_to_target_with_callbacks(record)
<ide> end
<ide>
<ide> private
<add> def merge_target_lists(loaded, existing)
<add> loaded.map do |f|
<add> i = existing.index(f)
<add> if i
<add> existing.delete_at(i).tap do |t|
<add> keys = ["id"] + t.changes.keys + (f.attribute_names - t.attribute_names)
<add> # FIXME: this call to attributes causes many NoMethodErrors
<add> attributes = f.attributes
<add> (attributes.keys - keys).each do |k|
<add> t.send("#{k}=", attributes[k])
<add> end
<add> end
<add> else
<add> f
<add> end
<add> end + existing
<add> end
<add>
<ide> # Do the relevant stuff to insert the given record into the association collection. The
<ide> # force param specifies whether or not an exception should be raised on failure. The
<ide> # validate param specifies whether validation should be performed (if force is false). | 1 |
Python | Python | correct lint error in mqtt exporter | dce2f6a5f6ed77ebf064bcb39a4b54c86ccad018 | <ide><path>glances/exports/glances_mqtt.py
<ide> def whitelisted(s,
<ide> for sensor, value in zip(columns, points):
<ide> try:
<ide> sensor = [whitelisted(name) for name in sensor.split('.')]
<del> topic = '/'.join([self.topic, self.hostname, name, *sensor])
<add> tobeexport = [self.topic, self.hostname, name]
<add> tobeexport.extend(sensor)
<add> topic = '/'.join(tobeexport)
<add>
<ide> self.client.publish(topic, value)
<ide> except Exception as e:
<ide> logger.error("Can not export stats to MQTT server (%s)" % e) | 1 |
PHP | PHP | update docblock + tests | 74fed151b5075918c130848a8f77b91cfd0d59a0 | <ide><path>src/Routing/Router.php
<ide> public static function scope($path, $params = [], $callback = null)
<ide> * For example a path of `admin` would result in `'prefix' => 'admin'` being
<ide> * applied to all connected routes.
<ide> *
<add> * The prefix name will be inflected to the underscore version to create
<add> * the routing path. If you want a custom path name, use the `path` option.
<add> *
<ide> * You can re-open a prefix as many times as necessary, as well as nest prefixes.
<ide> * Nested prefixes will result in prefix values like `admin/api` which translates
<ide> * to the `Controller\Admin\Api\` namespace.
<ide><path>tests/TestCase/Routing/RouterTest.php
<ide> public function testPrefixOptions()
<ide> $this->assertEquals('/admin', $routes->path());
<ide> $this->assertEquals(['prefix' => 'admin', 'param' => 'value'], $routes->params());
<ide> });
<add>
<add> Router::prefix('CustomPath', ['path' => '/custom-path'], function ($routes) {
<add> $this->assertInstanceOf('Cake\Routing\RouteBuilder', $routes);
<add> $this->assertEquals('/custom-path', $routes->path());
<add> $this->assertEquals(['prefix' => 'CustomPath'], $routes->params());
<add> });
<ide> }
<ide>
<ide> /** | 2 |
Text | Text | fix example about ps and linked containers | 0f8f04a77492ddf37ca9c163ef0c3ddaf8a93a40 | <ide><path>docs/sources/reference/commandline/cli.md
<ide> The `docker rename` command allows the container to be renamed to a different na
<ide> -s, --size=false Display total file sizes
<ide> --since="" Show created since Id or Name, include non-running.
<ide>
<del>Running `docker ps` showing 2 linked containers.
<add>Running `docker ps --no-trunc` showing 2 linked containers.
<ide>
<ide> $ sudo docker ps
<del> CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
<del> 4c01db0b339c ubuntu:12.04 bash 17 seconds ago Up 16 seconds webapp
<del> d7886598dbe2 crosbymichael/redis:latest /redis-server --dir 33 minutes ago Up 33 minutes 6379/tcp redis,webapp/db
<add> CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
<add> f7ee772232194fcc088c6bdec6ea09f7b3f6c54d53934658164b8602d7cd4744 ubuntu:12.04 bash 17 seconds ago Up 16 seconds webapp
<add> d0963715a061c7c7b7cc80b2646da913a959fbf13e80a971d4a60f6997a2f595 crosbymichael/redis:latest /redis-server --dir 33 minutes ago Up 33 minutes 6379/tcp redis,webapp/db
<ide>
<ide> `docker ps` will show only running containers by default. To see all containers:
<ide> `docker ps -a` | 1 |
PHP | PHP | use \throwable instead of \exception | 1d9130c08720a30cc4a8dda99170821fd62bb6fa | <ide><path>src/Core/Exception/Exception.php
<ide> namespace Cake\Core\Exception;
<ide>
<ide> use RuntimeException;
<add>use Throwable;
<ide>
<ide> /**
<ide> * Base class that all CakePHP Exceptions extend.
<ide> class Exception extends RuntimeException
<ide> * @param string|array $message Either the string of the error message, or an array of attributes
<ide> * that are made available in the view, and sprintf()'d into Exception::$_messageTemplate
<ide> * @param int|null $code The code of the error, is also the HTTP status code for the error.
<del> * @param \Exception|null $previous the previous exception.
<add> * @param \Throwable|null $previous the previous exception.
<ide> */
<del> public function __construct($message = '', $code = null, $previous = null)
<add> public function __construct($message = '', ?int $code = null, ?Throwable $previous = null)
<ide> {
<ide> if ($code === null) {
<ide> $code = $this->_defaultCode;
<ide><path>src/Datasource/Exception/InvalidPrimaryKeyException.php
<ide> class InvalidPrimaryKeyException extends Exception
<ide> * @inheritDoc
<ide> */
<ide> protected $_defaultCode = 404;
<del>
<del> /**
<del> * Constructor.
<del> *
<del> * @param string $message The error message
<del> * @param int $code The code of the error, is also the HTTP status code for the error.
<del> * @param \Exception|null $previous the previous exception.
<del> */
<del> public function __construct($message, $code = null, $previous = null)
<del> {
<del> parent::__construct($message, $code, $previous);
<del> }
<ide> }
<ide><path>src/Datasource/Exception/RecordNotFoundException.php
<ide> class RecordNotFoundException extends Exception
<ide> * @inheritDoc
<ide> */
<ide> protected $_defaultCode = 404;
<del>
<del> /**
<del> * Constructor.
<del> *
<del> * @param string $message The error message
<del> * @param int $code The code of the error, is also the HTTP status code for the error.
<del> * @param \Exception|null $previous the previous exception.
<del> */
<del> public function __construct($message, $code = null, $previous = null)
<del> {
<del> parent::__construct($message, $code, $previous);
<del> }
<ide> }
<ide><path>src/Error/BaseErrorHandler.php
<ide> protected function _getMessage(Throwable $exception): string
<ide> /**
<ide> * Generate the message for the exception
<ide> *
<del> * @param \Exception $exception The exception to log a message for.
<add> * @param \Throwable $exception The exception to log a message for.
<ide> * @param bool $isPrevious False for original exception, true for previous
<ide> * @return string Error message
<ide> */
<ide><path>src/Error/ErrorHandler.php
<ide> protected function _displayError(array $error, bool $debug): void
<ide> /**
<ide> * Displays an exception response body.
<ide> *
<del> * @param \Exception $exception The exception to display.
<add> * @param \Throwable $exception The exception to display.
<ide> * @return void
<ide> * @throws \Exception When the chosen exception renderer is invalid.
<ide> */
<ide><path>src/Error/ExceptionRenderer.php
<ide> use Cake\Utility\Inflector;
<ide> use Cake\View\Exception\MissingLayoutException;
<ide> use Cake\View\Exception\MissingTemplateException;
<del>use Exception;
<ide> use PDOException;
<ide> use Psr\Http\Message\ResponseInterface;
<ide> use Throwable;
<ide> protected function _outputMessage(string $template)
<ide> }
<ide>
<ide> return $this->_outputMessageSafe('error500');
<del> } catch (Exception $e) {
<add> } catch (Throwable $e) {
<ide> return $this->_outputMessageSafe('error500');
<ide> }
<ide> }
<ide><path>src/Error/FatalErrorException.php
<ide> namespace Cake\Error;
<ide>
<ide> use Cake\Core\Exception\Exception;
<add>use Throwable;
<ide>
<ide> /**
<ide> * Represents a fatal error
<ide> class FatalErrorException extends Exception
<ide> * @param int|null $code Code.
<ide> * @param string|null $file File name.
<ide> * @param int|null $line Line number.
<del> * @param \Exception|null $previous The previous exception.
<add> * @param \Throwable|null $previous The previous exception.
<ide> */
<del> public function __construct($message, $code = null, $file = null, $line = null, $previous = null)
<del> {
<add> public function __construct(
<add> string $message,
<add> ?int $code = null,
<add> ?string $file = null,
<add> ?int $line = null,
<add> ?Throwable $previous = null
<add> ) {
<ide> parent::__construct($message, $code, $previous);
<ide> if ($file) {
<ide> $this->file = $file;
<ide><path>src/Error/Middleware/ErrorHandlerMiddleware.php
<ide> protected function getMessage(ServerRequestInterface $request, Throwable $except
<ide> /**
<ide> * Generate the message for the exception
<ide> *
<del> * @param \Exception $exception The exception to log a message for.
<add> * @param \Throwable $exception The exception to log a message for.
<ide> * @param bool $isPrevious False for original exception, true for previous
<ide> * @return string Error message
<ide> */
<del> protected function getMessageForException($exception, $isPrevious = false)
<add> protected function getMessageForException(Throwable $exception, $isPrevious = false)
<ide> {
<ide> $message = sprintf(
<ide> '%s[%s] %s',
<ide><path>src/Http/Client/Exception/NetworkException.php
<ide> */
<ide> namespace Cake\Http\Client\Exception;
<ide>
<del>use Exception;
<ide> use Psr\Http\Client\NetworkExceptionInterface;
<ide> use Psr\Http\Message\RequestInterface;
<ide> use RuntimeException;
<add>use Throwable;
<ide>
<ide> /**
<ide> * Thrown when the request cannot be completed because of network issues.
<ide> class NetworkException extends RuntimeException implements NetworkExceptionInter
<ide> *
<ide> * @param string $message Exeception message.
<ide> * @param \Psr\Http\Message\RequestInterface $request Request instance.
<del> * @param \Exception|null $previous Previous Exception
<add> * @param \Throwable|null $previous Previous Exception
<ide> */
<del> public function __construct($message, RequestInterface $request, ?Exception $previous = null)
<add> public function __construct($message, RequestInterface $request, ?Throwable $previous = null)
<ide> {
<ide> $this->request = $request;
<ide> parent::__construct($message, 0, $previous);
<ide><path>src/Http/Client/Exception/RequestException.php
<ide> */
<ide> namespace Cake\Http\Client\Exception;
<ide>
<del>use Exception;
<ide> use Psr\Http\Client\RequestExceptionInterface;
<ide> use Psr\Http\Message\RequestInterface;
<ide> use RuntimeException;
<add>use Throwable;
<ide>
<ide> /**
<ide> * Exception for when a request failed.
<ide> class RequestException extends RuntimeException implements RequestExceptionInter
<ide> *
<ide> * @param string $message Exeception message.
<ide> * @param \Psr\Http\Message\RequestInterface $request Request instance.
<del> * @param \Exception|null $previous Previous Exception
<add> * @param \Throwable|null $previous Previous Exception
<ide> */
<del> public function __construct($message, RequestInterface $request, ?Exception $previous = null)
<add> public function __construct($message, RequestInterface $request, ?Throwable $previous = null)
<ide> {
<ide> $this->request = $request;
<ide> parent::__construct($message, 0, $previous);
<ide><path>src/ORM/Exception/PersistenceFailedException.php
<ide> use Cake\Core\Exception\Exception;
<ide> use Cake\Datasource\EntityInterface;
<ide> use Cake\Utility\Hash;
<add>use Throwable;
<ide>
<ide> /**
<ide> * Used when a strict save or delete fails
<ide> class PersistenceFailedException extends Exception
<ide> * @param string|array $message Either the string of the error message, or an array of attributes
<ide> * that are made available in the view, and sprintf()'d into Exception::$_messageTemplate
<ide> * @param int $code The code of the error, is also the HTTP status code for the error.
<del> * @param \Exception|null $previous the previous exception.
<add> * @param \Throwable|null $previous the previous exception.
<ide> */
<del> public function __construct(EntityInterface $entity, $message, $code = null, $previous = null)
<add> public function __construct(EntityInterface $entity, $message, ?int $code = null, ?Throwable $previous = null)
<ide> {
<ide> $this->_entity = $entity;
<ide> if (is_array($message)) {
<ide><path>src/Routing/Exception/DuplicateNamedRouteException.php
<ide> namespace Cake\Routing\Exception;
<ide>
<ide> use Cake\Core\Exception\Exception;
<add>use Throwable;
<ide>
<ide> /**
<ide> * Exception raised when a route names used twice.
<ide> class DuplicateNamedRouteException extends Exception
<ide> /**
<ide> * @inheritDoc
<ide> */
<del> public function __construct($message, $code = 404, $previous = null)
<add> public function __construct($message, int $code = 404, ?Throwable $previous = null)
<ide> {
<ide> if (is_array($message) && isset($message['message'])) {
<ide> $this->_messageTemplate = $message['message'];
<ide><path>src/Routing/Exception/MissingControllerException.php
<ide> namespace Cake\Routing\Exception;
<ide>
<ide> use Cake\Core\Exception\Exception;
<add>use Throwable;
<ide>
<ide> /**
<ide> * Missing Controller exception - used when a controller
<ide> class MissingControllerException extends Exception
<ide> /**
<ide> * @inheritDoc
<ide> */
<del> public function __construct($message, $code = 404, $previous = null)
<add> public function __construct($message, int $code = 404, ?Throwable $previous = null)
<ide> {
<ide> parent::__construct($message, $code, $previous);
<ide> }
<ide><path>src/Routing/Exception/MissingRouteException.php
<ide> namespace Cake\Routing\Exception;
<ide>
<ide> use Cake\Core\Exception\Exception;
<add>use Throwable;
<ide>
<ide> /**
<ide> * Exception raised when a URL cannot be reverse routed
<ide> class MissingRouteException extends Exception
<ide> /**
<ide> * @inheritDoc
<ide> */
<del> public function __construct($message, $code = 404, $previous = null)
<add> public function __construct($message, int $code = 404, ?Throwable $previous = null)
<ide> {
<ide> if (is_array($message)) {
<ide> if (isset($message['message'])) {
<ide><path>src/View/Exception/MissingCellTemplateException.php
<ide> */
<ide> namespace Cake\View\Exception;
<ide>
<add>use Throwable;
<add>
<ide> /**
<ide> * Used when a template file for a cell cannot be found.
<ide> */
<ide> class MissingCellTemplateException extends MissingTemplateException
<ide> * @param string $file The view filename.
<ide> * @param array $paths The path list that template could not be found in.
<ide> * @param int|null $code The code of the error.
<del> * @param \Exception|null $previous the previous exception.
<add> * @param \Throwable|null $previous the previous exception.
<ide> */
<del> public function __construct(string $name, string $file, array $paths = [], $code = null, $previous = null)
<del> {
<add> public function __construct(
<add> string $name,
<add> string $file,
<add> array $paths = [],
<add> ?int $code = null,
<add> ?Throwable $previous = null
<add> ) {
<ide> $this->name = $name;
<ide>
<ide> parent::__construct($file, $paths, $code, $previous);
<ide><path>src/View/Exception/MissingTemplateException.php
<ide> class MissingTemplateException extends Exception
<ide> /**
<ide> * Constructor
<ide> *
<del> * @param string|array $file Either the file name as a string, or in an array * for backwards compatibility.
<add> * @param string|array $file Either the file name as a string, or in an array for backwards compatibility.
<ide> * @param array $paths The path list that template could not be found in.
<ide> * @param int|null $code The code of the error.
<del> * @param \Exception|null $previous the previous exception.
<add> * @param \Throwable|null $previous the previous exception.
<ide> */
<del> public function __construct($file, array $paths = [], $code = null, $previous = null)
<add> public function __construct($file, array $paths = [], ?int $code = null, ?Throwable $previous = null)
<ide> {
<ide> $this->file = is_array($file) ? array_pop($file) : $file;
<ide> $this->paths = $paths; | 16 |
Python | Python | correct pb if array stats are none | 522acfca352b2259a77a1b26883e390abd7c0062 | <ide><path>glances/plugins/glances_raid.py
<ide> def update(self):
<ide> # Update stats using the PyMDstat lib (https://github.com/nicolargo/pymdstat)
<ide> try:
<ide> # !!! Path ONLY for dev
<del> mds = MdStat('/home/nicolargo/dev/pymdstat/tests/mdstat.09')
<add> mds = MdStat('/home/nicolargo/dev/pymdstat/tests/mdstat.08')
<ide> self.stats = mds.get_stats()['arrays']
<ide> except Exception as e:
<ide> logger.debug("Can not grab RAID stats (%s)" % e)
<ide> def msg_curse(self, args=None):
<ide> # Display the current status
<ide> status = self.raid_alert(self.stats[array]['status'], self.stats[array]['used'], self.stats[array]['available'])
<ide> # Data: RAID type name | disk used | disk available
<del> msg = '{0:<5}{1:>6}'.format(self.stats[array]['type'].upper(), array)
<add> array_type = self.stats[array]['type'].upper() if self.stats[array]['type'] is not None else _('UNKNOWN')
<add> msg = '{0:<5}{1:>6}'.format(array_type, array)
<ide> ret.append(self.curse_add_line(msg))
<ide> if self.stats[array]['status'] == 'active':
<ide> msg = '{0:>5}'.format(self.stats[array]['used']) | 1 |
PHP | PHP | fix various docblocks | 79c1d50b4e53ab00a38b5c2e443fce88ee1fb528 | <ide><path>src/Illuminate/Console/AppNamespaceDetectorTrait.php
<ide> trait AppNamespaceDetectorTrait {
<ide> /**
<ide> * Get the application namespace from the Composer file.
<ide> *
<del> * @param string $namespacePath
<ide> * @return string
<add> *
<add> * @throws \RuntimeException
<ide> */
<ide> protected function getAppNamespace()
<ide> {
<ide><path>src/Illuminate/Events/Annotations/Annotations/Hears.php
<ide> class Hears {
<ide> /**
<ide> * Create a new annotation instance.
<ide> *
<add> * @param array $values
<ide> * @return void
<ide> */
<ide> public function __construct(array $values = array())
<ide><path>src/Illuminate/Events/Annotations/Scanner.php
<ide> protected function getClassesToScan()
<ide>
<ide> foreach ($this->scan as $class)
<ide> {
<del> try {
<add> try
<add> {
<ide> $classes[] = new ReflectionClass($class);
<del> } catch (\Exception $e) {
<add> }
<add> catch (\Exception $e)
<add> {
<ide> //
<ide> }
<ide> } | 3 |
Javascript | Javascript | replace new app template with new app screen | fe88e9e48ce99cb8b9da913051cc36575310018b | <ide><path>Libraries/NewAppScreen/components/DebugInstructions.js
<add>/**
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> *
<add> * @flow
<add> * @format
<add> */
<add>
<add>import React from 'react';
<add>import {Platform, StyleSheet, Text} from 'react-native';
<add>
<add>const styles = StyleSheet.create({
<add> highlight: {
<add> fontWeight: '700',
<add> },
<add>});
<add>
<add>const DebugInstructions = Platform.select({
<add> ios: () => (
<add> <Text>
<add> Press <Text style={styles.highlight}>Cmd+D</Text> in the simulator or{' '}
<add> <Text style={styles.highlight}>Shake</Text> your device to open the React
<add> Native debug menu.
<add> </Text>
<add> ),
<add> default: () => (
<add> <Text>
<add> Press <Text style={styles.highlight}>menu button</Text> or
<add> <Text style={styles.highlight}>Shake</Text> your device to open the React
<add> Native debug menu.
<add> </Text>
<add> ),
<add>});
<add>
<add>export default DebugInstructions;
<ide><path>Libraries/NewAppScreen/components/ReloadInstructions.js
<add>/**
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> *
<add> * @flow
<add> * @format
<add> */
<add>
<add>import React from 'react';
<add>import {Platform, StyleSheet, Text} from 'react-native';
<add>
<add>const styles = StyleSheet.create({
<add> highlight: {
<add> fontWeight: '700',
<add> },
<add>});
<add>
<add>const ReloadInstructions = Platform.select({
<add> ios: () => (
<add> <Text>
<add> Press <Text style={styles.highlight}>Cmd+R</Text> in the simulator to
<add> reload your app's code
<add> </Text>
<add> ),
<add> default: () => (
<add> <Text>
<add> Double tap <Text style={styles.highlight}>R</Text> on your keyboard to
<add> reload your app's code
<add> </Text>
<add> ),
<add>});
<add>
<add>export default ReloadInstructions;
<ide><path>Libraries/NewAppScreen/index.js
<ide>
<ide> 'use strict';
<ide>
<del>import React, {Fragment} from 'react';
<del>import {
<del> StyleSheet,
<del> ScrollView,
<del> View,
<del> Text,
<del> Platform,
<del> StatusBar,
<del>} from 'react-native';
<del>
<ide> import Header from './components/Header';
<ide> import LearnMoreLinks from './components/LearnMoreLinks';
<ide> import Colors from './components/Colors';
<add>import DebugInstructions from './components/DebugInstructions';
<add>import ReloadInstructions from './components/ReloadInstructions';
<ide>
<del>const Section = ({children}) => (
<del> <View style={styles.sectionContainer}>{children}</View>
<del>);
<del>
<del>const ReloadInstructions = () => {
<del> return Platform.OS === 'ios' ? (
<del> <Text style={styles.sectionDescription}>
<del> Press <Text style={styles.highlight}>Cmd+R</Text> in the simulator to
<del> reload your app's code
<del> </Text>
<del> ) : (
<del> <Text style={styles.sectionDescription}>
<del> Double tap <Text style={styles.highlight}>R</Text> on your keyboard to
<del> reload your app's code
<del> </Text>
<del> );
<del>};
<del>
<del>const DebugInstructions = () => {
<del> return Platform.OS === 'ios' ? (
<del> <Text style={styles.sectionDescription}>
<del> Press <Text style={styles.highlight}>Cmd+D</Text> in the simulator or{' '}
<del> <Text style={styles.highlight}>Shake</Text> your device to open the React
<del> Native debug menu.
<del> </Text>
<del> ) : (
<del> <Text style={styles.sectionDescription}>
<del> Press <Text style={styles.highlight}>menu button</Text> or
<del> <Text style={styles.highlight}>Shake</Text> your device to open the React
<del> Native debug menu.
<del> </Text>
<del> );
<del>};
<del>
<del>const App = () => {
<del> return (
<del> <Fragment>
<del> <StatusBar barStyle="dark-content" />
<del> <ScrollView
<del> contentInsetAdjustmentBehavior="automatic"
<del> style={styles.scrollView}>
<del> <Header />
<del> <View style={styles.body}>
<del> <Section>
<del> <Text style={styles.sectionTitle}>Step One</Text>
<del> <Text style={styles.sectionDescription}>
<del> Edit <Text style={styles.highlight}>App.js</Text> to change this
<del> screen and then come back to see your edits.
<del> </Text>
<del> </Section>
<del>
<del> <Section>
<del> <Text style={styles.sectionTitle}>See Your Changes</Text>
<del> <ReloadInstructions />
<del> </Section>
<del>
<del> <Section>
<del> <Text style={styles.sectionTitle}>Debug</Text>
<del> <DebugInstructions />
<del> </Section>
<del>
<del> <Section>
<del> <Text style={styles.sectionTitle}>Learn More</Text>
<del> <Text style={styles.sectionDescription}>
<del> Read the docs on what to do once seen how to work in React Native.
<del> </Text>
<del> </Section>
<del> <LearnMoreLinks />
<del> </View>
<del> </ScrollView>
<del> </Fragment>
<del> );
<del>};
<del>
<del>const styles = StyleSheet.create({
<del> scrollView: {
<del> backgroundColor: Colors.lighter,
<del> },
<del> body: {
<del> backgroundColor: Colors.white,
<del> },
<del> sectionContainer: {
<del> marginTop: 32,
<del> paddingHorizontal: 24,
<del> },
<del> sectionTitle: {
<del> fontSize: 24,
<del> fontWeight: '600',
<del> color: Colors.black,
<del> },
<del> sectionDescription: {
<del> marginTop: 8,
<del> fontSize: 18,
<del> fontWeight: '400',
<del> color: Colors.dark,
<del> },
<del> highlight: {
<del> fontWeight: '700',
<del> },
<del>});
<del>
<del>export default App;
<add>export {Header, LearnMoreLinks, Colors, DebugInstructions, ReloadInstructions};
<ide><path>RNTester/js/NewAppScreenExample.js
<ide> 'use strict';
<ide>
<ide> const React = require('react');
<del>const NewAppScreen = require('../../Libraries/NewAppScreen').default;
<add>const {View} = require('react-native');
<add>const {
<add> Header,
<add> LearnMoreLinks,
<add> Colors,
<add> DebugInstructions,
<add> ReloadInstructions,
<add>} = require('../../Libraries/NewAppScreen');
<ide>
<ide> exports.title = 'New App Screen';
<ide> exports.description = 'Displays the content of the new app screen';
<ide> exports.examples = [
<ide> {
<del> title: 'New App Screen',
<del> description: 'Displays the content of the new app screen',
<add> title: 'New App Screen Header',
<add> description: 'Displays a welcome to building a React Native app',
<ide> render(): React.Element<any> {
<del> return <NewAppScreen />;
<add> return (
<add> <View style={{overflow: 'hidden'}}>
<add> <Header />
<add> </View>
<add> );
<add> },
<add> },
<add> {
<add> title: 'Learn More Links',
<add> description:
<add> 'Learn more about the tools and techniques for building React Native apps.',
<add> render(): React.Element<any> {
<add> return <LearnMoreLinks />;
<add> },
<add> },
<add> {
<add> title: 'New App Screen Colors',
<add> description: 'Consistent colors to use throughout the new app screen.',
<add> render(): React.Element<any> {
<add> return (
<add> <View style={{flexDirection: 'row'}}>
<add> {Object.keys(Colors).map(key => (
<add> <View
<add> style={{width: 50, height: 50, backgroundColor: Colors[key]}}
<add> />
<add> ))}
<add> </View>
<add> );
<add> },
<add> },
<add> {
<add> title: 'Debug Instructions',
<add> description:
<add> 'Platform-specific instructions on how to start debugging a React Native app.',
<add> render(): React.Element<any> {
<add> return <DebugInstructions />;
<add> },
<add> },
<add> {
<add> title: 'Reload Instructions',
<add> description:
<add> 'Platform-specific instructions on how to reload a React Native app.',
<add> render(): React.Element<any> {
<add> return <ReloadInstructions />;
<ide> },
<ide> },
<ide> ];
<ide><path>template/App.js
<ide> * @flow
<ide> */
<ide>
<del>import React, {Component} from 'react';
<del>import {Platform, StyleSheet, Text, View} from 'react-native';
<add>import React, {Fragment} from 'react';
<add>import {StyleSheet, ScrollView, View, Text, StatusBar} from 'react-native';
<ide>
<del>const instructions = Platform.select({
<del> ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu',
<del> android:
<del> 'Double tap R on your keyboard to reload,\n' +
<del> 'Shake or press menu button for dev menu',
<del>});
<add>import {
<add> Header,
<add> LearnMoreLinks,
<add> Colors,
<add> DebugInstructions,
<add> ReloadInstructions,
<add>} from 'react-native/Libraries/NewAppScreen';
<ide>
<del>type Props = {};
<del>export default class App extends Component<Props> {
<del> render() {
<del> return (
<del> <View style={styles.container}>
<del> <Text style={styles.welcome}>Welcome to React Native!</Text>
<del> <Text style={styles.instructions}>To get started, edit App.js</Text>
<del> <Text style={styles.instructions}>{instructions}</Text>
<del> </View>
<del> );
<del> }
<del>}
<add>const App = () => {
<add> return (
<add> <Fragment>
<add> <StatusBar barStyle="dark-content" />
<add> <ScrollView
<add> contentInsetAdjustmentBehavior="automatic"
<add> style={styles.scrollView}>
<add> <Header />
<add> <View style={styles.body}>
<add> <View style={styles.sectionContainer}>
<add> <Text style={styles.sectionTitle}>Step One</Text>
<add> <Text style={styles.sectionDescription}>
<add> Edit <Text style={styles.highlight}>App.js</Text> to change this
<add> screen and then come back to see your edits.
<add> </Text>
<add> </View>
<add> <View style={styles.sectionContainer}>
<add> <Text style={styles.sectionTitle}>See Your Changes</Text>
<add> <Text style={styles.sectionDescription}>
<add> <ReloadInstructions />
<add> </Text>
<add> </View>
<add> <View style={styles.sectionContainer}>
<add> <Text style={styles.sectionTitle}>Debug</Text>
<add> <Text style={styles.sectionDescription}>
<add> <DebugInstructions />
<add> </Text>
<add> </View>
<add> <View style={styles.sectionContainer}>
<add> <Text style={styles.sectionTitle}>Learn More</Text>
<add> <Text style={styles.sectionDescription}>
<add> Read the docs on what to do once seen how to work in React Native.
<add> </Text>
<add> </View>
<add> <LearnMoreLinks />
<add> </View>
<add> </ScrollView>
<add> </Fragment>
<add> );
<add>};
<ide>
<ide> const styles = StyleSheet.create({
<del> container: {
<del> flex: 1,
<del> justifyContent: 'center',
<del> alignItems: 'center',
<del> backgroundColor: '#F5FCFF',
<add> scrollView: {
<add> backgroundColor: Colors.lighter,
<add> },
<add> body: {
<add> backgroundColor: Colors.white,
<add> },
<add> sectionContainer: {
<add> marginTop: 32,
<add> paddingHorizontal: 24,
<ide> },
<del> welcome: {
<del> fontSize: 20,
<del> textAlign: 'center',
<del> margin: 10,
<add> sectionTitle: {
<add> fontSize: 24,
<add> fontWeight: '600',
<add> color: Colors.black,
<ide> },
<del> instructions: {
<del> textAlign: 'center',
<del> color: '#333333',
<del> marginBottom: 5,
<add> sectionDescription: {
<add> marginTop: 8,
<add> fontSize: 18,
<add> fontWeight: '400',
<add> color: Colors.dark,
<add> },
<add> highlight: {
<add> fontWeight: '700',
<ide> },
<ide> });
<add>
<add>export default App; | 5 |
Python | Python | add comments in the code | 23a9149a8da92767b18f1e0e02de99d60e4e602f | <ide><path>keras/regularizers.py
<ide> def __call__(self, x):
<ide> if self.l1:
<ide> regularization += self.l1 * tf.reduce_sum(tf.abs(x))
<ide> if self.l2:
<add> # equivalent to "self.l2 * tf.reduce_sum(tf.square(x))"
<ide> regularization += 2.0 * self.l2 * tf.nn.l2_loss(x)
<ide> return regularization
<ide>
<ide> def __init__(self, l2=0.01, **kwargs): # pylint: disable=redefined-outer-name
<ide> self.l2 = backend.cast_to_floatx(l2)
<ide>
<ide> def __call__(self, x):
<add> # equivalent to "self.l2 * tf.reduce_sum(tf.square(x))"
<ide> return 2.0 * self.l2 * tf.nn.l2_loss(x)
<ide>
<ide> def get_config(self): | 1 |
Text | Text | move the coc text to the rails website | 90bcb6dea7f8fc8b93b4266180465fc0c0785c01 | <ide><path>CODE_OF_CONDUCT.md
<ide> # Contributor Code of Conduct
<ide>
<del>As contributors and maintainers of this project, and in the interest of fostering an open and welcoming community, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities.
<add>The Rails team is committed to fostering a welcoming community.
<ide>
<del>We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, or nationality.
<add>**Our Code of Conduct can be found here**:
<ide>
<del>Examples of unacceptable behavior by participants include:
<add>http://rubyonrails.org/conduct/
<ide>
<del>* The use of sexualized language or imagery
<del>* Personal attacks
<del>* Trolling or insulting/derogatory comments
<del>* Public or private harassment
<del>* Publishing other's private information, such as physical or electronic addresses, without explicit permission
<del>* Other unethical or unprofessional conduct.
<add>For a history of updates, see the page history here:
<ide>
<del>Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. By adopting this Code of Conduct, project maintainers commit themselves to fairly and consistently applying these principles to every aspect of managing this project. Project maintainers who do not follow or enforce the Code of Conduct may be permanently removed from the project team.
<add>https://github.com/rails/rails.github.com/commits/master/conduct/index.html
<ide>
<del>This code of conduct applies both within project spaces and in public spaces when an individual is representing the project or its community.
<del>
<del>Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers.
<del>
<del>This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.2.0, available at [http://contributor-covenant.org/version/1/2/0/](http://contributor-covenant.org/version/1/2/0/)
<ide>\ No newline at end of file
<ide><path>README.md
<ide> and may also be used independently outside Rails.
<ide> We encourage you to contribute to Ruby on Rails! Please check out the
<ide> [Contributing to Ruby on Rails guide](http://edgeguides.rubyonrails.org/contributing_to_ruby_on_rails.html) for guidelines about how to proceed. [Join us!](http://contributors.rubyonrails.org)
<ide>
<del>Everyone interacting in Rails and its sub-project’s codebases, issue trackers, chat rooms, and mailing lists is expected to follow the Rails [code of conduct](CODE_OF_CONDUCT.md).
<add>Everyone interacting in Rails and its sub-project’s codebases, issue trackers, chat rooms, and mailing lists is expected to follow the Rails [code of conduct](http://rubyonrails.org/conduct/).
<ide>
<ide> ## Code Status
<ide> | 2 |
Go | Go | make "validateopts()" a method on root | e106e3f5c6edd07750f1422f84d5f3e3d16ac03e | <ide><path>volume/local/local.go
<ide> func (r *Root) Create(name string, opts map[string]string) (volume.Volume, error
<ide> if err := r.validateName(name); err != nil {
<ide> return nil, err
<ide> }
<del> if err := validateOpts(opts); err != nil {
<add> if err := r.validateOpts(opts); err != nil {
<ide> return nil, err
<ide> }
<ide>
<ide><path>volume/local/local_unix.go
<ide> func (o *optsConfig) String() string {
<ide> return fmt.Sprintf("type='%s' device='%s' o='%s' size='%d'", o.MountType, o.MountDevice, o.MountOpts, o.Quota.Size)
<ide> }
<ide>
<del>func (v *localVolume) setOpts(opts map[string]string) error {
<add>func (r *Root) validateOpts(opts map[string]string) error {
<ide> if len(opts) == 0 {
<ide> return nil
<ide> }
<del> v.opts = &optsConfig{
<del> MountType: opts["type"],
<del> MountOpts: opts["o"],
<del> MountDevice: opts["device"],
<add> for opt := range opts {
<add> if _, ok := validOpts[opt]; !ok {
<add> return errdefs.InvalidParameter(errors.Errorf("invalid option: %q", opt))
<add> }
<ide> }
<ide> if val, ok := opts["size"]; ok {
<ide> size, err := units.RAMInBytes(val)
<ide> if err != nil {
<ide> return errdefs.InvalidParameter(err)
<ide> }
<del> if size > 0 && v.quotaCtl == nil {
<add> if size > 0 && r.quotaCtl == nil {
<ide> return errdefs.InvalidParameter(errors.New("quota size requested but no quota support"))
<ide> }
<del> v.opts.Quota.Size = uint64(size)
<add> }
<add> for opt, reqopts := range mandatoryOpts {
<add> if _, ok := opts[opt]; ok {
<add> for _, reqopt := range reqopts {
<add> if _, ok := opts[reqopt]; !ok {
<add> return errdefs.InvalidParameter(errors.Errorf("missing required option: %q", reqopt))
<add> }
<add> }
<add> }
<ide> }
<ide> return nil
<ide> }
<ide>
<del>func validateOpts(opts map[string]string) error {
<add>func (v *localVolume) setOpts(opts map[string]string) error {
<ide> if len(opts) == 0 {
<ide> return nil
<ide> }
<del> for opt := range opts {
<del> if _, ok := validOpts[opt]; !ok {
<del> return errdefs.InvalidParameter(errors.Errorf("invalid option: %q", opt))
<del> }
<add> v.opts = &optsConfig{
<add> MountType: opts["type"],
<add> MountOpts: opts["o"],
<add> MountDevice: opts["device"],
<ide> }
<ide> if val, ok := opts["size"]; ok {
<del> _, err := units.RAMInBytes(val)
<add> size, err := units.RAMInBytes(val)
<ide> if err != nil {
<ide> return errdefs.InvalidParameter(err)
<ide> }
<del> }
<del> for opt, reqopts := range mandatoryOpts {
<del> if _, ok := opts[opt]; ok {
<del> for _, reqopt := range reqopts {
<del> if _, ok := opts[reqopt]; !ok {
<del> return errdefs.InvalidParameter(errors.Errorf("missing required option: %q", reqopt))
<del> }
<del> }
<add> if size > 0 && v.quotaCtl == nil {
<add> return errdefs.InvalidParameter(errors.New("quota size requested but no quota support"))
<ide> }
<add> v.opts.Quota.Size = uint64(size)
<ide> }
<ide> return nil
<ide> }
<ide><path>volume/local/local_windows.go
<ide> import (
<ide>
<ide> type optsConfig struct{}
<ide>
<del>func (v *localVolume) setOpts(opts map[string]string) error {
<del> // Windows does not support any options currently
<del> return nil
<add>func (r *Root) validateOpts(opts map[string]string) error {
<add> if len(opts) == 0 {
<add> return nil
<add> }
<add> return errdefs.InvalidParameter(errors.New("options are not supported on this platform"))
<ide> }
<ide>
<del>func validateOpts(opts map[string]string) error {
<del> if len(opts) > 0 {
<del> return errdefs.InvalidParameter(errors.New("options are not supported on this platform"))
<del> }
<add>func (v *localVolume) setOpts(opts map[string]string) error {
<add> // Windows does not support any options currently
<ide> return nil
<ide> }
<ide> | 3 |
Java | Java | fix failing test | 0f47732523865e360bfe8de4ba9ec708e0accaa0 | <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/SockJsThreadPoolTaskScheduler.java
<ide> public class SockJsThreadPoolTaskScheduler extends ThreadPoolTaskScheduler {
<ide>
<ide> // Check for setRemoveOnCancelPolicy method - available on JDK 7 and higher
<ide> private static boolean hasRemoveOnCancelPolicyMethod = ClassUtils.hasMethod(
<del> ScheduledThreadPoolExecutor.class, "setRemoveOnCancelPolicy", Boolean.class);
<add> ScheduledThreadPoolExecutor.class, "setRemoveOnCancelPolicy", boolean.class);
<ide>
<ide>
<ide> public SockJsThreadPoolTaskScheduler() { | 1 |
Javascript | Javascript | accept texture.source/sampler=0 in gltf2loader | ebbe091bc4814762ad7da5c7676070adea0a12ad | <ide><path>examples/js/loaders/GLTF2Loader.js
<ide> THREE.GLTF2Loader = ( function () {
<ide>
<ide> return _each( json.textures, function ( texture ) {
<ide>
<del> if ( texture.source ) {
<add> if ( texture.source !== undefined ) {
<ide>
<ide> return new Promise( function ( resolve ) {
<ide>
<ide> THREE.GLTF2Loader = ( function () {
<ide>
<ide> _texture.type = texture.type !== undefined ? WEBGL_TEXTURE_DATATYPES[ texture.type ] : THREE.UnsignedByteType;
<ide>
<del> if ( texture.sampler ) {
<add> if ( texture.sampler !== undefined ) {
<ide>
<ide> var sampler = json.samplers[ texture.sampler ];
<ide> | 1 |
Text | Text | update grammer error in step 68 of project 2 | 60f6fd2f017036c85cdfdf04805c9a87c22dc87f | <ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-basic-css-by-building-a-cafe-menu/5f3f26fa39591db45e5cd7a0.md
<ide> dashedName: step-68
<ide>
<ide> The default properties of an `hr` element will make it appear as a thin light grey line. You can change the height of the line by specifying a value for the `height` property.
<ide>
<del>Change the height the `hr` element to be `3px`.
<add>Change the height of the `hr` element to be `3px`.
<ide>
<ide> # --hints--
<ide> | 1 |
Text | Text | fix typo in sequence model card | dc552b9b7025ea9c38717f30ad3d69c2a972049d | <ide><path>model_cards/facebook/rag-sequence-nq/README.md
<ide> The model can generate answers to any factoid question as follows:
<ide> ```python
<ide> from transformers import RagTokenizer, RagRetriever, RagSequenceForGeneration
<ide>
<del>tokenizer = RagTokenizer.from_pretrained("facebook/rag-token-nq")
<del>retriever = RagRetriever.from_pretrained("facebook/rag-token-nq", index_name="exact", use_dummy_dataset=True)
<del>model = RagSequenceForGeneration.from_pretrained("facebook/rag-token-nq", retriever=retriever)
<add>tokenizer = RagTokenizer.from_pretrained("facebook/rag-sequence-nq")
<add>retriever = RagRetriever.from_pretrained("facebook/rag-sequence-nq", index_name="exact", use_dummy_dataset=True)
<add>model = RagSequenceForGeneration.from_pretrained("facebook/rag-sequence-nq", retriever=retriever)
<ide>
<ide> input_dict = tokenizer.prepare_seq2seq_batch("how many countries are in europe", return_tensors="pt")
<ide> | 1 |
Text | Text | release notes on non-text detail arguments. closes | 00531ec937206e7e0af949c67872c915d0752b5a | <ide><path>docs/topics/3.0-announcement.md
<ide> The default JSON renderer will return float objects for un-coerced `Decimal` ins
<ide> * The serializer `ChoiceField` does not currently display nested choices, as was the case in 2.4. This will be address as part of 3.1.
<ide> * Due to the new templated form rendering, the 'widget' option is no longer valid. This means there's no easy way of using third party "autocomplete" widgets for rendering select inputs that contain a large number of choices. You'll either need to use a regular select or a plain text input. We may consider addressing this in 3.1 or 3.2 if there's sufficient demand.
<ide> * Some of the default validation error messages were rewritten and might no longer be pre-translated. You can still [create language files with Django][django-localization] if you wish to localize them.
<add>* `APIException` subclasses could previously take could previously take any arbitrary type in the `detail` argument. These exceptions now use translatable text strings, and as a result call `force_text` on the `detail` argument, which *must be a string*. If you need complex arguments to an `APIException` class, you should subclass it and override the `__init__()` method. Typically you'll instead want to use a custom exception handler to provide for non-standard error responses.
<ide>
<ide> ---
<ide> | 1 |
Javascript | Javascript | update common.js path for new test layout | b08f2af34439685432c37723232edb48c10649b8 | <ide><path>test/common.js
<ide> var path = require("path");
<ide>
<ide> exports.testDir = path.dirname(__filename);
<ide> exports.fixturesDir = path.join(exports.testDir, "fixtures");
<del>exports.libDir = path.join(exports.testDir, "../../lib");
<add>exports.libDir = path.join(exports.testDir, "../lib");
<ide>
<ide> require.paths.unshift(exports.libDir);
<ide> | 1 |
Mixed | Java | add scrollwithoutanimationto to android | 3b68869fc83e9ea02ea0527cb1c32ae8df209738 | <ide><path>Libraries/Components/ScrollResponder.js
<ide> var ScrollResponderMixin = {
<ide> }
<ide> },
<ide>
<add> /**
<add> * Like `scrollResponderScrollTo` but immediately scrolls to the given
<add> * position
<add> */
<add> scrollResponderScrollWithouthAnimationTo: function(offsetX: number, offsetY: number) {
<add> if (Platform.OS === 'android') {
<add> RCTUIManager.dispatchViewManagerCommand(
<add> React.findNodeHandle(this),
<add> RCTUIManager.RCTScrollView.Commands.scrollWithoutAnimationTo,
<add> [offsetX, offsetY],
<add> );
<add> } else {
<add> RCTUIManager.scrollWithoutAnimationTo(
<add> React.findNodeHandle(this),
<add> offsetX,
<add> offsetY
<add> );
<add> }
<add> },
<add>
<ide> /**
<ide> * A helper function to zoom to a specific rect in the scrollview.
<ide> * @param {object} rect Should have shape {x, y, width, height}
<ide><path>Libraries/Components/ScrollView/ScrollView.js
<ide> var ScrollView = React.createClass({
<ide> },
<ide>
<ide> scrollWithoutAnimationTo: function(destY?: number, destX?: number) {
<del> RCTUIManager.scrollWithoutAnimationTo(
<del> React.findNodeHandle(this),
<add> // $FlowFixMe - Don't know how to pass Mixin correctly. Postpone for now
<add> this.getScrollResponder().scrollResponderScrollWithouthAnimationTo(
<ide> destX || 0,
<del> destY || 0
<add> destY || 0,
<ide> );
<ide> },
<ide>
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactHorizontalScrollViewManager.java
<ide> public void scrollTo(
<ide> ReactScrollViewCommandHelper.ScrollToCommandData data) {
<ide> scrollView.smoothScrollTo(data.mDestX, data.mDestY);
<ide> }
<add>
<add> @Override
<add> public void scrollWithoutAnimationTo(
<add> ReactHorizontalScrollView scrollView,
<add> ReactScrollViewCommandHelper.ScrollToCommandData data) {
<add> scrollView.scrollTo(data.mDestX, data.mDestY);
<add> }
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollViewCommandHelper.java
<ide> public class ReactScrollViewCommandHelper {
<ide>
<ide> public static final int COMMAND_SCROLL_TO = 1;
<add> public static final int COMMAND_SCROLL_WITHOUT_ANIMATION_TO = 2;
<ide>
<ide> public interface ScrollCommandHandler<T> {
<ide> void scrollTo(T scrollView, ScrollToCommandData data);
<add> void scrollWithoutAnimationTo(T scrollView, ScrollToCommandData data);
<ide> }
<ide>
<ide> public static class ScrollToCommandData {
<ide> public static class ScrollToCommandData {
<ide> }
<ide>
<ide> public static Map<String,Integer> getCommandsMap() {
<del> return MapBuilder.of("scrollTo", COMMAND_SCROLL_TO);
<add> return MapBuilder.of(
<add> "scrollTo",
<add> COMMAND_SCROLL_TO,
<add> "scrollWithoutAnimationTo",
<add> COMMAND_SCROLL_WITHOUT_ANIMATION_TO);
<ide> }
<ide>
<ide> public static <T> void receiveCommand(
<ide> public static <T> void receiveCommand(
<ide> Assertions.assertNotNull(scrollView);
<ide> Assertions.assertNotNull(args);
<ide> switch (commandType) {
<del> case COMMAND_SCROLL_TO:
<add> case COMMAND_SCROLL_TO: {
<ide> int destX = Math.round(PixelUtil.toPixelFromDIP(args.getInt(0)));
<ide> int destY = Math.round(PixelUtil.toPixelFromDIP(args.getInt(1)));
<ide> viewManager.scrollTo(scrollView, new ScrollToCommandData(destX, destY));
<ide> return;
<add> }
<add> case COMMAND_SCROLL_WITHOUT_ANIMATION_TO: {
<add> int destX = Math.round(PixelUtil.toPixelFromDIP(args.getInt(0)));
<add> int destY = Math.round(PixelUtil.toPixelFromDIP(args.getInt(1)));
<add> viewManager.scrollWithoutAnimationTo(scrollView, new ScrollToCommandData(destX, destY));
<add> return;
<add> }
<ide> default:
<ide> throw new IllegalArgumentException(String.format(
<ide> "Unsupported command %d received by %s.",
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollViewManager.java
<ide> public void scrollTo(
<ide> scrollView.smoothScrollTo(data.mDestX, data.mDestY);
<ide> }
<ide>
<add> @Override
<add> public void scrollWithoutAnimationTo(
<add> ReactScrollView scrollView,
<add> ReactScrollViewCommandHelper.ScrollToCommandData data) {
<add> scrollView.scrollTo(data.mDestX, data.mDestY);
<add> }
<add>
<ide> @Override
<ide> public @Nullable Map getExportedCustomDirectEventTypeConstants() {
<ide> return MapBuilder.builder() | 5 |
Java | Java | add header support to websocketconnectionmanager | 172a0b9f5d2b6caf5ed5e3d8cfe529c75ff145d5 | <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/client/AbstractWebSocketClient.java
<add>/*
<add> * Copyright 2002-2013 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.web.socket.client;
<add>
<add>import java.net.URI;
<add>import java.util.ArrayList;
<add>import java.util.HashSet;
<add>import java.util.List;
<add>import java.util.Set;
<add>
<add>import org.apache.commons.logging.Log;
<add>import org.apache.commons.logging.LogFactory;
<add>import org.springframework.http.HttpHeaders;
<add>import org.springframework.util.Assert;
<add>import org.springframework.web.socket.WebSocketHandler;
<add>import org.springframework.web.socket.WebSocketSession;
<add>import org.springframework.web.util.UriComponentsBuilder;
<add>
<add>
<add>/**
<add> * Abstract base class for {@link WebSocketClient} implementations.
<add> *
<add> * @author Rossen Stoyanchev
<add> * @since 4.0
<add> */
<add>public abstract class AbstractWebSocketClient implements WebSocketClient {
<add>
<add> protected final Log logger = LogFactory.getLog(getClass());
<add>
<add> private static final Set<String> disallowedHeaders = new HashSet<String>();
<add>
<add> static {
<add> disallowedHeaders.add("cache-control");
<add> disallowedHeaders.add("cookie");
<add> disallowedHeaders.add("connection");
<add> disallowedHeaders.add("host");
<add> disallowedHeaders.add("sec-websocket-extensions");
<add> disallowedHeaders.add("sec-websocket-key");
<add> disallowedHeaders.add("sec-websocket-protocol");
<add> disallowedHeaders.add("sec-websocket-version");
<add> disallowedHeaders.add("pragma");
<add> disallowedHeaders.add("upgrade");
<add> }
<add>
<add>
<add> @Override
<add> public WebSocketSession doHandshake(WebSocketHandler webSocketHandler, String uriTemplate,
<add> Object... uriVars) throws WebSocketConnectFailureException {
<add>
<add> Assert.notNull(uriTemplate, "uriTemplate must not be null");
<add> URI uri = UriComponentsBuilder.fromUriString(uriTemplate).buildAndExpand(uriVars).encode().toUri();
<add> return doHandshake(webSocketHandler, null, uri);
<add> }
<add>
<add> @Override
<add> public final WebSocketSession doHandshake(WebSocketHandler webSocketHandler,
<add> HttpHeaders headers, URI uri) throws WebSocketConnectFailureException {
<add>
<add> Assert.notNull(webSocketHandler, "webSocketHandler must not be null");
<add> Assert.notNull(uri, "uri must not be null");
<add>
<add> if (logger.isDebugEnabled()) {
<add> logger.debug("Connecting to " + uri);
<add> }
<add>
<add> HttpHeaders headersToUse = new HttpHeaders();
<add> if (headers != null) {
<add> for (String header : headers.keySet()) {
<add> if (!disallowedHeaders.contains(header.toLowerCase())) {
<add> headersToUse.put(header, headers.get(header));
<add> }
<add> }
<add> }
<add>
<add> List<String> subProtocols = new ArrayList<String>();
<add> if ((headers != null) && (headers.getSecWebSocketProtocol() != null)) {
<add> subProtocols.addAll(headers.getSecWebSocketProtocol());
<add> }
<add>
<add> return doHandshakeInternal(webSocketHandler, headersToUse, uri, subProtocols);
<add> }
<add>
<add> /**
<add> *
<add> *
<add> * @param webSocketHandler the client-side handler for WebSocket messages
<add> * @param headers HTTP headers to use for the handshake, with unwanted (forbidden)
<add> * headers filtered out, never {@code null}
<add> * @param uri the target URI for the handshake, never {@code null}
<add> * @param subProtocols requested sub-protocols, or an empty list
<add> * @return the established WebSocket session
<add> * @throws WebSocketConnectFailureException
<add> */
<add> protected abstract WebSocketSession doHandshakeInternal(WebSocketHandler webSocketHandler,
<add> HttpHeaders headers, URI uri, List<String> subProtocols) throws WebSocketConnectFailureException;
<add>
<add>}
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/client/WebSocketConnectionManager.java
<ide> public class WebSocketConnectionManager extends ConnectionManagerSupport {
<ide>
<ide> private final List<String> protocols = new ArrayList<String>();
<ide>
<add> private HttpHeaders headers;
<add>
<ide> private final boolean syncClientLifecycle;
<ide>
<ide>
<ide> protected WebSocketHandler decorateWebSocketHandler(WebSocketHandler handler) {
<ide> return new LoggingWebSocketHandlerDecorator(handler);
<ide> }
<ide>
<del> public void setSupportedProtocols(List<String> protocols) {
<add> /**
<add> * Set the sub-protocols to use. If configured, specified sub-protocols will be
<add> * requested in the handshake through the {@code Sec-WebSocket-Protocol} header. The
<add> * resulting WebSocket session will contain the protocol accepted by the server, if
<add> * any.
<add> */
<add> public void setSubProtocols(List<String> protocols) {
<ide> this.protocols.clear();
<ide> if (!CollectionUtils.isEmpty(protocols)) {
<ide> this.protocols.addAll(protocols);
<ide> }
<ide> }
<ide>
<del> public List<String> getSupportedProtocols() {
<add> /**
<add> * Return the configured sub-protocols to use.
<add> */
<add> public List<String> getSubProtocols() {
<ide> return this.protocols;
<ide> }
<ide>
<add> /**
<add> * Provide default headers to add to the WebSocket handshake request.
<add> */
<add> public void setHeaders(HttpHeaders headers) {
<add> this.headers = headers;
<add> }
<add>
<add> /**
<add> * Return the default headers for the WebSocket handshake request.
<add> */
<add> public HttpHeaders getHeaders() {
<add> return this.headers;
<add> }
<add>
<add>
<ide> @Override
<ide> public void startInternal() {
<ide> if (this.syncClientLifecycle) {
<ide> public void stopInternal() throws Exception {
<ide>
<ide> @Override
<ide> protected void openConnection() throws Exception {
<add>
<ide> HttpHeaders headers = new HttpHeaders();
<add> if (this.headers != null) {
<add> headers.putAll(this.headers);
<add> }
<ide> headers.setSecWebSocketProtocol(this.protocols);
<add>
<ide> this.webSocketSession = this.client.doHandshake(this.webSocketHandler, headers, getUri());
<ide> }
<ide>
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/client/endpoint/StandardWebSocketClient.java
<ide> package org.springframework.web.socket.client.endpoint;
<ide>
<ide> import java.net.URI;
<del>import java.util.Arrays;
<del>import java.util.HashSet;
<ide> import java.util.List;
<ide> import java.util.Map;
<del>import java.util.Set;
<ide>
<ide> import javax.websocket.ClientEndpointConfig;
<ide> import javax.websocket.ClientEndpointConfig.Configurator;
<ide> import javax.websocket.HandshakeResponse;
<ide> import javax.websocket.WebSocketContainer;
<ide>
<del>import org.apache.commons.logging.Log;
<del>import org.apache.commons.logging.LogFactory;
<ide> import org.springframework.http.HttpHeaders;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.web.socket.WebSocketHandler;
<ide> import org.springframework.web.socket.WebSocketSession;
<ide> import org.springframework.web.socket.adapter.StandardEndpointAdapter;
<ide> import org.springframework.web.socket.adapter.StandardWebSocketSessionAdapter;
<del>import org.springframework.web.socket.client.WebSocketClient;
<add>import org.springframework.web.socket.client.AbstractWebSocketClient;
<ide> import org.springframework.web.socket.client.WebSocketConnectFailureException;
<del>import org.springframework.web.util.UriComponents;
<del>import org.springframework.web.util.UriComponentsBuilder;
<ide>
<ide> /**
<ide> * Initiates WebSocket requests to a WebSocket server programatically through the standard
<ide> * @author Rossen Stoyanchev
<ide> * @since 4.0
<ide> */
<del>public class StandardWebSocketClient implements WebSocketClient {
<del>
<del> private static final Log logger = LogFactory.getLog(StandardWebSocketClient.class);
<add>public class StandardWebSocketClient extends AbstractWebSocketClient {
<ide>
<ide> private final WebSocketContainer webSocketContainer;
<ide>
<ide> public StandardWebSocketClient(WebSocketContainer webSocketContainer) {
<ide>
<ide>
<ide> @Override
<del> public WebSocketSession doHandshake(WebSocketHandler webSocketHandler, String uriTemplate, Object... uriVariables)
<del> throws WebSocketConnectFailureException {
<del>
<del> Assert.notNull(uriTemplate, "uriTemplate must not be null");
<del> UriComponents uriComponents = UriComponentsBuilder.fromUriString(uriTemplate).buildAndExpand(uriVariables).encode();
<del> return doHandshake(webSocketHandler, null, uriComponents.toUri());
<del> }
<del>
<del> @Override
<del> public WebSocketSession doHandshake(WebSocketHandler webSocketHandler, HttpHeaders httpHeaders, URI uri)
<del> throws WebSocketConnectFailureException {
<del>
<del> Assert.notNull(webSocketHandler, "webSocketHandler must not be null");
<del> Assert.notNull(uri, "uri must not be null");
<del>
<del> httpHeaders = (httpHeaders != null) ? httpHeaders : new HttpHeaders();
<del>
<del> if (logger.isDebugEnabled()) {
<del> logger.debug("Connecting to " + uri);
<del> }
<add> protected WebSocketSession doHandshakeInternal(WebSocketHandler webSocketHandler,
<add> HttpHeaders httpHeaders, URI uri, List<String> protocols) throws WebSocketConnectFailureException {
<ide>
<ide> StandardWebSocketSessionAdapter session = new StandardWebSocketSessionAdapter();
<ide> session.setUri(uri);
<ide> session.setRemoteHostName(uri.getHost());
<ide>
<ide> ClientEndpointConfig.Builder configBuidler = ClientEndpointConfig.Builder.create();
<ide> configBuidler.configurator(new StandardWebSocketClientConfigurator(httpHeaders));
<del>
<del> List<String> protocols = httpHeaders.getSecWebSocketProtocol();
<del> if (!protocols.isEmpty()) {
<del> configBuidler.preferredSubprotocols(protocols);
<del> }
<add> configBuidler.preferredSubprotocols(protocols);
<ide>
<ide> try {
<ide> // TODO: do not block
<ide> public WebSocketSession doHandshake(WebSocketHandler webSocketHandler, HttpHeade
<ide> }
<ide>
<ide>
<del> private static class StandardWebSocketClientConfigurator extends Configurator {
<del>
<del> private static final Set<String> EXCLUDED_HEADERS = new HashSet<String>(
<del> Arrays.asList("Sec-WebSocket-Accept", "Sec-WebSocket-Extensions", "Sec-WebSocket-Key",
<del> "Sec-WebSocket-Protocol", "Sec-WebSocket-Version"));
<add> private class StandardWebSocketClientConfigurator extends Configurator {
<ide>
<ide> private final HttpHeaders httpHeaders;
<ide>
<ide> public StandardWebSocketClientConfigurator(HttpHeaders httpHeaders) {
<ide>
<ide> @Override
<ide> public void beforeRequest(Map<String, List<String>> headers) {
<del> for (String headerName : this.httpHeaders.keySet()) {
<del> if (!EXCLUDED_HEADERS.contains(headerName)) {
<del> List<String> value = this.httpHeaders.get(headerName);
<del> if (logger.isTraceEnabled()) {
<del> logger.trace("Adding header [" + headerName + "=" + value + "]");
<del> }
<del> headers.put(headerName, value);
<del> }
<del> }
<add> headers.putAll(this.httpHeaders);
<ide> if (logger.isDebugEnabled()) {
<ide> logger.debug("Handshake request headers: " + headers);
<ide> }
<ide> }
<ide> @Override
<del> public void afterResponse(HandshakeResponse handshakeResponse) {
<add> public void afterResponse(HandshakeResponse response) {
<ide> if (logger.isDebugEnabled()) {
<del> logger.debug("Handshake response headers: " + handshakeResponse.getHeaders());
<add> logger.debug("Handshake response headers: " + response.getHeaders());
<ide> }
<ide> }
<ide> }
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/client/jetty/JettyWebSocketClient.java
<ide> package org.springframework.web.socket.client.jetty;
<ide>
<ide> import java.net.URI;
<add>import java.util.List;
<ide>
<del>import org.apache.commons.logging.Log;
<del>import org.apache.commons.logging.LogFactory;
<add>import org.eclipse.jetty.websocket.client.ClientUpgradeRequest;
<ide> import org.springframework.context.SmartLifecycle;
<ide> import org.springframework.http.HttpHeaders;
<del>import org.springframework.util.Assert;
<ide> import org.springframework.web.socket.WebSocketHandler;
<ide> import org.springframework.web.socket.WebSocketSession;
<ide> import org.springframework.web.socket.adapter.JettyWebSocketListenerAdapter;
<ide> import org.springframework.web.socket.adapter.JettyWebSocketSessionAdapter;
<del>import org.springframework.web.socket.client.WebSocketClient;
<add>import org.springframework.web.socket.client.AbstractWebSocketClient;
<ide> import org.springframework.web.socket.client.WebSocketConnectFailureException;
<ide> import org.springframework.web.util.UriComponents;
<ide> import org.springframework.web.util.UriComponentsBuilder;
<ide> * @author Rossen Stoyanchev
<ide> * @since 4.0
<ide> */
<del>public class JettyWebSocketClient implements WebSocketClient, SmartLifecycle {
<del>
<del> private static final Log logger = LogFactory.getLog(JettyWebSocketClient.class);
<add>public class JettyWebSocketClient extends AbstractWebSocketClient implements SmartLifecycle {
<ide>
<ide> private final org.eclipse.jetty.websocket.client.WebSocketClient client;
<ide>
<ide> public WebSocketSession doHandshake(WebSocketHandler webSocketHandler, String ur
<ide> }
<ide>
<ide> @Override
<del> public WebSocketSession doHandshake(WebSocketHandler webSocketHandler, HttpHeaders headers, URI uri)
<del> throws WebSocketConnectFailureException {
<add> public WebSocketSession doHandshakeInternal(WebSocketHandler webSocketHandler, HttpHeaders headers,
<add> URI uri, List<String> protocols) throws WebSocketConnectFailureException {
<ide>
<del> Assert.notNull(webSocketHandler, "webSocketHandler must not be null");
<del> Assert.notNull(uri, "uri must not be null");
<add> ClientUpgradeRequest request = new ClientUpgradeRequest();
<add> request.setSubProtocols(protocols);
<ide>
<del> if (logger.isDebugEnabled()) {
<del> logger.debug("Connecting to " + uri);
<add> for (String header : headers.keySet()) {
<add> request.setHeader(header, headers.get(header));
<ide> }
<ide>
<del> // TODO: populate headers
<del>
<ide> JettyWebSocketSessionAdapter session = new JettyWebSocketSessionAdapter();
<ide> session.setUri(uri);
<ide> session.setRemoteHostName(uri.getHost());
<ide> public WebSocketSession doHandshake(WebSocketHandler webSocketHandler, HttpHeade
<ide>
<ide> try {
<ide> // TODO: do not block
<del> this.client.connect(listener, uri).get();
<add> this.client.connect(listener, uri, request).get();
<ide> return session;
<ide> }
<ide> catch (Exception e) {
<ide><path>spring-websocket/src/test/java/org/springframework/web/socket/client/AbstractWebSocketClientTests.java
<add>/*
<add> * Copyright 2002-2013 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.web.socket.client;
<add>
<add>
<add>/**
<add> * Test fixture for {@link AbstractWebSocketClient}.
<add> * @author Rossen Stoyanchev
<add> */
<add>public class AbstractWebSocketClientTests {
<add>
<add>}
<ide><path>spring-websocket/src/test/java/org/springframework/web/socket/client/WebSocketConnectionManagerTests.java
<ide> public class WebSocketConnectionManagerTests {
<ide> public void openConnection() throws Exception {
<ide>
<ide> List<String> subprotocols = Arrays.asList("abc");
<del> HttpHeaders headers = new HttpHeaders();
<del> headers.setSecWebSocketProtocol(subprotocols);
<ide>
<ide> WebSocketClient client = mock(WebSocketClient.class);
<ide> WebSocketHandler handler = new WebSocketHandlerAdapter();
<ide>
<ide> WebSocketConnectionManager manager = new WebSocketConnectionManager(client, handler , "/path/{id}", "123");
<del> manager.setSupportedProtocols(subprotocols);
<add> manager.setSubProtocols(subprotocols);
<ide> manager.openConnection();
<ide>
<ide> ArgumentCaptor<WebSocketHandlerDecorator> captor = ArgumentCaptor.forClass(WebSocketHandlerDecorator.class);
<ide> public void openConnection() throws Exception {
<ide>
<ide> verify(client).doHandshake(captor.capture(), headersCaptor.capture(), uriCaptor.capture());
<ide>
<del> assertEquals(headers, headersCaptor.getValue());
<add> HttpHeaders expectedHeaders = new HttpHeaders();
<add> expectedHeaders.setSecWebSocketProtocol(subprotocols);
<add>
<add> assertEquals(expectedHeaders, headersCaptor.getValue());
<ide> assertEquals(new URI("/path/123"), uriCaptor.getValue());
<ide>
<ide> WebSocketHandlerDecorator loggingHandler = captor.getValue();
<ide><path>spring-websocket/src/test/java/org/springframework/web/socket/client/jetty/JettyWebSocketClientTests.java
<add>/*
<add> * Copyright 2002-2013 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.web.socket.client.jetty;
<add>
<add>import java.net.URI;
<add>import java.util.Arrays;
<add>
<add>import org.eclipse.jetty.server.Server;
<add>import org.eclipse.jetty.server.ServerConnector;
<add>import org.eclipse.jetty.websocket.api.UpgradeRequest;
<add>import org.eclipse.jetty.websocket.api.UpgradeResponse;
<add>import org.eclipse.jetty.websocket.servlet.WebSocketCreator;
<add>import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;
<add>import org.junit.After;
<add>import org.junit.Before;
<add>import org.junit.Test;
<add>import org.springframework.http.HttpHeaders;
<add>import org.springframework.util.CollectionUtils;
<add>import org.springframework.util.SocketUtils;
<add>import org.springframework.web.socket.WebSocketHandler;
<add>import org.springframework.web.socket.WebSocketSession;
<add>import org.springframework.web.socket.adapter.JettyWebSocketListenerAdapter;
<add>import org.springframework.web.socket.adapter.JettyWebSocketSessionAdapter;
<add>import org.springframework.web.socket.adapter.TextWebSocketHandlerAdapter;
<add>
<add>import static org.junit.Assert.*;
<add>
<add>
<add>/**
<add> * Tests for {@link JettyWebSocketClient}.
<add> * @author Rossen Stoyanchev
<add> */
<add>public class JettyWebSocketClientTests {
<add>
<add> private JettyWebSocketClient client;
<add>
<add> private TestJettyWebSocketServer server;
<add>
<add> private String wsUrl;
<add>
<add> private WebSocketSession wsSession;
<add>
<add>
<add> @Before
<add> public void setup() throws Exception {
<add>
<add> int port = SocketUtils.findAvailableTcpPort();
<add>
<add> this.server = new TestJettyWebSocketServer(port, new TextWebSocketHandlerAdapter());
<add> this.server.start();
<add>
<add> this.client = new JettyWebSocketClient();
<add> this.client.start();
<add>
<add> this.wsUrl = "ws://localhost:" + port + "/test";
<add> }
<add>
<add> @After
<add> public void teardown() throws Exception {
<add> this.wsSession.close();
<add> this.client.stop();
<add> this.server.stop();
<add> }
<add>
<add>
<add> @Test
<add> public void doHandshake() throws Exception {
<add>
<add> HttpHeaders headers = new HttpHeaders();
<add> headers.setSecWebSocketProtocol(Arrays.asList("echo"));
<add>
<add> this.wsSession = this.client.doHandshake(new TextWebSocketHandlerAdapter(), headers, new URI(this.wsUrl));
<add>
<add> assertEquals(this.wsUrl, this.wsSession.getUri().toString());
<add> assertEquals("echo", this.wsSession.getAcceptedProtocol());
<add> }
<add>
<add>
<add> private static class TestJettyWebSocketServer {
<add>
<add> private final Server server;
<add>
<add>
<add> public TestJettyWebSocketServer(int port, final WebSocketHandler webSocketHandler) {
<add>
<add> this.server = new Server();
<add> ServerConnector connector = new ServerConnector(this.server);
<add> connector.setPort(port);
<add>
<add> this.server.addConnector(connector);
<add> this.server.setHandler(new org.eclipse.jetty.websocket.server.WebSocketHandler() {
<add> @Override
<add> public void configure(WebSocketServletFactory factory) {
<add> factory.setCreator(new WebSocketCreator() {
<add> @Override
<add> public Object createWebSocket(UpgradeRequest req, UpgradeResponse resp) {
<add>
<add> if (!CollectionUtils.isEmpty(req.getSubProtocols())) {
<add> resp.setAcceptedSubProtocol(req.getSubProtocols().get(0));
<add> }
<add>
<add> JettyWebSocketSessionAdapter session = new JettyWebSocketSessionAdapter();
<add> return new JettyWebSocketListenerAdapter(webSocketHandler, session);
<add> }
<add> });
<add> }
<add> });
<add> }
<add>
<add> public void start() throws Exception {
<add> this.server.start();
<add> }
<add>
<add> public void stop() throws Exception {
<add> this.server.stop();
<add> }
<add> }
<add>
<add>} | 7 |
Python | Python | fix lint issues | 9f21f1f91a2dd35b34f37d322f2dd2e75cc3caa3 | <ide><path>libcloud/compute/drivers/cloudstack.py
<ide> from libcloud.utils.networking import is_private_subnet
<ide>
<ide>
<del>"""
<del>Define the extra dictionary for specific resources
<del>"""
<del>
<add># Utility functions
<ide> def transform_int_or_unlimited(value):
<ide> try:
<ide> return int(value)
<ide> def transform_int_or_unlimited(value):
<ide> raise e
<ide>
<ide>
<add>"""
<add>Define the extra dictionary for specific resources
<add>"""
<ide> RESOURCE_EXTRA_ATTRIBUTES_MAP = {
<ide> 'network': {
<ide> 'broadcast_domain_type': {
<ide> def transform_int_or_unlimited(value):
<ide> },
<ide> 'project': {
<ide> 'account': {'key_name': 'account', 'transform_func': str},
<del> 'cpuavailable': {'key_name': 'cpuavailable', 'transform_func': transform_int_or_unlimited},
<del> 'cpulimit': {'key_name': 'cpulimit', 'transform_func': transform_int_or_unlimited},
<del> 'cputotal': {'key_name': 'cputotal', 'transform_func': transform_int_or_unlimited},
<add> 'cpuavailable': {'key_name': 'cpuavailable',
<add> 'transform_func': transform_int_or_unlimited},
<add> 'cpulimit': {'key_name': 'cpulimit',
<add> 'transform_func': transform_int_or_unlimited},
<add> 'cputotal': {'key_name': 'cputotal',
<add> 'transform_func': transform_int_or_unlimited},
<ide> 'domain': {'key_name': 'domain', 'transform_func': str},
<ide> 'domainid': {'key_name': 'domainid', 'transform_func': str},
<del> 'ipavailable': {'key_name': 'ipavailable', 'transform_func': transform_int_or_unlimited},
<del> 'iplimit': {'key_name': 'iplimit', 'transform_func': transform_int_or_unlimited},
<del> 'iptotal': {'key_name': 'iptotal', 'transform_func': transform_int_or_unlimited},
<add> 'ipavailable': {'key_name': 'ipavailable',
<add> 'transform_func': transform_int_or_unlimited},
<add> 'iplimit': {'key_name': 'iplimit',
<add> 'transform_func': transform_int_or_unlimited},
<add> 'iptotal': {'key_name': 'iptotal',
<add> 'transform_func': transform_int_or_unlimited},
<ide> 'memoryavailable': {'key_name': 'memoryavailable',
<ide> 'transform_func': transform_int_or_unlimited},
<del> 'memorylimit': {'key_name': 'memorylimit', 'transform_func': transform_int_or_unlimited},
<del> 'memorytotal': {'key_name': 'memorytotal', 'transform_func': transform_int_or_unlimited},
<add> 'memorylimit': {'key_name': 'memorylimit',
<add> 'transform_func': transform_int_or_unlimited},
<add> 'memorytotal': {'key_name': 'memorytotal',
<add> 'transform_func': transform_int_or_unlimited},
<ide> 'networkavailable': {'key_name': 'networkavailable',
<ide> 'transform_func': transform_int_or_unlimited},
<del> 'networklimit': {'key_name': 'networklimit', 'transform_func': transform_int_or_unlimited},
<del> 'networktotal': {'key_name': 'networktotal', 'transform_func': transform_int_or_unlimited},
<del> 'primarystorageavailable': {'key_name': 'primarystorageavailable',
<del> 'transform_func': transform_int_or_unlimited},
<add> 'networklimit': {'key_name': 'networklimit',
<add> 'transform_func': transform_int_or_unlimited},
<add> 'networktotal': {'key_name': 'networktotal',
<add> 'transform_func': transform_int_or_unlimited},
<add> 'primarystorageavailable': {
<add> 'key_name': 'primarystorageavailable',
<add> 'transform_func': transform_int_or_unlimited},
<ide> 'primarystoragelimit': {'key_name': 'primarystoragelimit',
<ide> 'transform_func': transform_int_or_unlimited},
<ide> 'primarystoragetotal': {'key_name': 'primarystoragetotal',
<ide> 'transform_func': transform_int_or_unlimited},
<del> 'secondarystorageavailable': {'key_name': 'secondarystorageavailable',
<del> 'transform_func': transform_int_or_unlimited},
<del> 'secondarystoragelimit': {'key_name': 'secondarystoragelimit',
<del> 'transform_func': transform_int_or_unlimited},
<del> 'secondarystoragetotal': {'key_name': 'secondarystoragetotal',
<del> 'transform_func': transform_int_or_unlimited},
<add> 'secondarystorageavailable': {
<add> 'key_name': 'secondarystorageavailable',
<add> 'transform_func': transform_int_or_unlimited},
<add> 'secondarystoragelimit': {
<add> 'key_name': 'secondarystoragelimit',
<add> 'transform_func': transform_int_or_unlimited},
<add> 'secondarystoragetotal': {
<add> 'key_name': 'secondarystoragetotal',
<add> 'transform_func': transform_int_or_unlimited},
<ide> 'snapshotavailable': {'key_name': 'snapshotavailable',
<ide> 'transform_func': transform_int_or_unlimited},
<del> 'snapshotlimit': {'key_name': 'snapshotlimit', 'transform_func': transform_int_or_unlimited},
<del> 'snapshottotal': {'key_name': 'snapshottotal', 'transform_func': transform_int_or_unlimited},
<add> 'snapshotlimit': {'key_name': 'snapshotlimit',
<add> 'transform_func': transform_int_or_unlimited},
<add> 'snapshottotal': {'key_name': 'snapshottotal',
<add> 'transform_func': transform_int_or_unlimited},
<ide> 'state': {'key_name': 'state', 'transform_func': str},
<ide> 'tags': {'key_name': 'tags', 'transform_func': str},
<ide> 'templateavailable': {'key_name': 'templateavailable',
<ide> 'transform_func': transform_int_or_unlimited},
<del> 'templatelimit': {'key_name': 'templatelimit', 'transform_func': transform_int_or_unlimited},
<del> 'templatetotal': {'key_name': 'templatetotal', 'transform_func': transform_int_or_unlimited},
<del> 'vmavailable': {'key_name': 'vmavailable', 'transform_func': transform_int_or_unlimited},
<del> 'vmlimit': {'key_name': 'vmlimit', 'transform_func': transform_int_or_unlimited},
<del> 'vmrunning': {'key_name': 'vmrunning', 'transform_func': transform_int_or_unlimited},
<del> 'vmtotal': {'key_name': 'vmtotal', 'transform_func': transform_int_or_unlimited},
<add> 'templatelimit': {'key_name': 'templatelimit',
<add> 'transform_func': transform_int_or_unlimited},
<add> 'templatetotal': {'key_name': 'templatetotal',
<add> 'transform_func': transform_int_or_unlimited},
<add> 'vmavailable': {'key_name': 'vmavailable',
<add> 'transform_func': transform_int_or_unlimited},
<add> 'vmlimit': {'key_name': 'vmlimit',
<add> 'transform_func': transform_int_or_unlimited},
<add> 'vmrunning': {'key_name': 'vmrunning',
<add> 'transform_func': transform_int_or_unlimited},
<add> 'vmtotal': {'key_name': 'vmtotal',
<add> 'transform_func': transform_int_or_unlimited},
<ide> 'volumeavailable': {'key_name': 'volumeavailable',
<ide> 'transform_func': transform_int_or_unlimited},
<del> 'volumelimit': {'key_name': 'volumelimit', 'transform_func': transform_int_or_unlimited},
<del> 'volumetotal': {'key_name': 'volumetotal', 'transform_func': transform_int_or_unlimited},
<del> 'vpcavailable': {'key_name': 'vpcavailable', 'transform_func': transform_int_or_unlimited},
<del> 'vpclimit': {'key_name': 'vpclimit', 'transform_func': transform_int_or_unlimited},
<del> 'vpctotal': {'key_name': 'vpctotal', 'transform_func': transform_int_or_unlimited}
<add> 'volumelimit': {'key_name': 'volumelimit',
<add> 'transform_func': transform_int_or_unlimited},
<add> 'volumetotal': {'key_name': 'volumetotal',
<add> 'transform_func': transform_int_or_unlimited},
<add> 'vpcavailable': {'key_name': 'vpcavailable',
<add> 'transform_func': transform_int_or_unlimited},
<add> 'vpclimit': {'key_name': 'vpclimit',
<add> 'transform_func': transform_int_or_unlimited},
<add> 'vpctotal': {'key_name': 'vpctotal',
<add> 'transform_func': transform_int_or_unlimited}
<ide> },
<ide> 'nic': {
<ide> 'secondary_ip': { | 1 |
Python | Python | set rcond to precision of x as default | 658b94aa185b341ddf638ec488ac5acd8cdf28fa | <ide><path>numpy/lib/polynomial.py
<ide> import numpy.core.numeric as NX
<ide>
<ide> from numpy.core import isscalar, abs
<add>from numpy.lib.machar import MachAr
<ide> from numpy.lib.twodim_base import diag, vander
<ide> from numpy.lib.shape_base import hstack, atleast_1d
<ide> from numpy.lib.function_base import trim_zeros, sort_complex
<ide> eigvals = None
<ide> lstsq = None
<add>_single_eps = MachAr(NX.single).eps
<add>_double_eps = MachAr(NX.double).eps
<ide>
<ide> def get_linalg_funcs():
<ide> "Look for linear algebra functions in numpy"
<ide> def polyder(p, m=1):
<ide> val = poly1d(val)
<ide> return val
<ide>
<del>def polyfit(x, y, deg, rcond=-1):
<add>def polyfit(x, y, deg, rcond=None):
<ide> """
<ide>
<ide> Do a best fit polynomial of degree 'deg' of 'x' to 'y'. Return value is a
<ide> def polyfit(x, y, deg, rcond=-1):
<ide> if x.shape[0] != y.shape[0] :
<ide> raise TypeError, "expected x and y to have same length"
<ide>
<add> # set rcond
<add> if rcond is None :
<add> xtype = x.dtype
<add> if xtype == NX.single or xtype == NX.csingle :
<add> rcond = _single_eps
<add> else :
<add> rcond = _double_eps
<add>
<ide> # scale x to improve condition number
<ide> scale = abs(x).max()
<ide> if scale != 0 :
<ide> def polyfit(x, y, deg, rcond=-1):
<ide> # warn on rank reduction, which indicates an ill conditioned matrix
<ide> if rank != order :
<ide> # fixme -- want a warning here, not an exception
<del> raise RuntimeError, "degree reduced to %d" % (rank - 1)
<add> raise RuntimeError, "Rank deficit fit. Try degree %d." % (rank - 1)
<ide>
<ide> # scale returned coefficients
<ide> if scale != 0 : | 1 |
Ruby | Ruby | update clang for 10.11 | 6a534f569d617e6323c736be4e1753fa6ad597a9 | <ide><path>Library/Homebrew/os/mac/xcode.rb
<ide> def installed?
<ide>
<ide> def latest_version
<ide> case MacOS.version
<del> when "10.11" then "700.0.53.3"
<add> when "10.11" then "700.0.57.2"
<ide> when "10.10" then "602.0.53"
<ide> when "10.9" then "600.0.57"
<ide> when "10.8" then "503.0.40" | 1 |
PHP | PHP | add ability to pass exceptions as flash message | 4fc8d4725b5537c1521f9fd365690c3438a4f657 | <ide><path>src/Controller/Component/FlashComponent.php
<ide> public function __construct(ComponentRegistry $collection, array $config = []) {
<ide> }
<ide>
<ide> public function set($message, $element = null, array $params = array(), $key = 'flash') {
<add> if ($message instanceof \Exception) {
<add> $message = $message->getMessage();
<add> }
<ide> $this->_writeFlash($message, 'info', $params + compact('element', 'key'));
<ide> }
<ide>
<ide><path>tests/TestCase/Controller/Component/FlashComponentTest.php
<ide> public function testSet() {
<ide> $result = $this->Session->read('Message.foobar');
<ide> $this->assertEquals($expected, $result);
<ide> }
<add>
<add>/**
<add> * testSetWithException method
<add> *
<add> * @return void
<add> * @covers \Cake\Controller\Component\FlashComponent::set
<add> */
<add> public function testSetWithException() {
<add> $this->assertNull($this->Session->read('Message.flash'));
<add>
<add> $this->Flash->set(new \Exception('This is a test message'));
<add> $expected = ['message' => 'This is a test message', 'params' => ['element' => null], 'type' => 'info'];
<add> $result = $this->Session->read('Message.flash');
<add> $this->assertEquals($expected, $result);
<add> }
<ide> } | 2 |
Python | Python | fix eval batch size | 2fa56484b251baf1eb0245b033db0104aad29b23 | <ide><path>spacy/cli/train.py
<ide> def evaluate():
<ide>
<ide> if optimizer.averages:
<ide> with nlp.use_params(optimizer.averages):
<del> scorer = nlp.evaluate(dev_examples, batch_size=eval_batch_size)
<add> scorer = nlp.evaluate(dev_examples, batch_size=batch_size)
<ide> else:
<del> scorer = nlp.evaluate(dev_examples, batch_size=eval_batch_size)
<add> scorer = nlp.evaluate(dev_examples, batch_size=batch_size)
<ide> end_time = timer()
<ide> wps = n_words / (end_time - start_time)
<ide> scores = scorer.scores | 1 |
Python | Python | remove duplicate entry | 58b7955ecbdc157e5647fdd1eba06252dacd64de | <ide><path>libcloud/compute/types.py
<ide> class Provider(Type):
<ide>
<ide> CLOUDSIGMA_US = 'cloudsigma_us'
<ide>
<del> MAXIHOST = "maxihost"
<del>
<ide> # Removed
<ide> # SLICEHOST = 'slicehost'
<ide> | 1 |
Text | Text | add changelogs for stream | a70aa589faec204cc61f19406976fa3ffe1e3bbf | <ide><path>doc/api/stream.md
<ide> file.end('world!');
<ide> ##### writable.setDefaultEncoding(encoding)
<ide> <!-- YAML
<ide> added: v0.11.15
<add>changes:
<add> - version: v6.1.0
<add> pr-url: https://github.com/nodejs/node/pull/5040
<add> description: This method now returns a reference to `writable`.
<ide> -->
<ide>
<ide> * `encoding` {String} The new default encoding
<ide> See also: [`writable.cork()`][].
<ide> ##### writable.write(chunk[, encoding][, callback])
<ide> <!-- YAML
<ide> added: v0.9.4
<add>changes:
<add> - version: v6.0.0
<add> pr-url: https://github.com/nodejs/node/pull/6170
<add> description: Passing `null` as the `chunk` parameter will always be
<add> considered invalid now, even in object mode.
<ide> -->
<ide>
<ide> * `chunk` {String|Buffer} The data to write
<ide> myReader.on('readable', () => {
<ide> #### Class: stream.Duplex
<ide> <!-- YAML
<ide> added: v0.9.4
<add>changes:
<add> - version: v6.8.0
<add> pr-url: https://github.com/nodejs/node/pull/8834
<add> description: Instances of `Duplex` now return `true` when
<add> checking `instanceof stream.Writable`.
<ide> -->
<ide>
<ide> <!--type=class-->
<ide> the [API for Stream Consumers][] section). Doing so may lead to adverse
<ide> side effects in application code consuming the stream.
<ide>
<ide> ### Simplified Construction
<add><!-- YAML
<add>added: v1.2.0
<add>-->
<ide>
<ide> For many simple cases, it is possible to construct a stream without relying on
<ide> inheritance. This can be accomplished by directly creating instances of the | 1 |
Ruby | Ruby | remove extraneous response_obj | a470bb36128cfdddd888492b7ac972ee582f6acb | <ide><path>actionpack/lib/action_controller/abstract/base.rb
<ide> def initialize(message = nil)
<ide>
<ide> class Base
<ide> attr_internal :response_body
<del> attr_internal :response_obj
<ide> attr_internal :action_name
<ide>
<ide> class << self
<ide> def action_methods
<ide>
<ide> abstract!
<ide>
<del> def initialize
<del> self.response_obj = {}
<del> end
<del>
<ide> def process(action)
<ide> @_action_name = action_name = action.to_s
<ide> | 1 |
Python | Python | fix ticket link in test docstring | 86ea969e1154de20a53fc5b853e8340508648e98 | <ide><path>rest_framework/tests/test_serializer_nested.py
<ide> def test_create_via_foreign_key_with_source(self):
<ide> """
<ide> Check that we can both *create* and *update* into objects across
<ide> ForeignKeys that have a `source` specified.
<del> Regression test for #<ticket>
<add> Regression test for #1170
<ide> """
<ide> data = {
<ide> 'name': 'Discovery', | 1 |
Ruby | Ruby | add formula renames to report | e4480cf6bf80e8de737581f8b3ce3068334747c4 | <ide><path>Library/Homebrew/cmd/update.rb
<ide> def update
<ide> tabs.each(&:write)
<ide> end if load_tap_migrations
<ide>
<del> # Migrate installed renamed formulae from main Homebrew repository.
<del> if load_formula_renames
<del> report.select_formula(:D).each do |oldname|
<del> newname = FORMULA_RENAMES[oldname]
<del> next unless newname
<del> next unless (dir = HOMEBREW_CELLAR/oldname).directory? && !dir.subdirs.empty?
<del>
<del> begin
<del> migrator = Migrator.new(Formulary.factory("homebrew/homebrew/#{newname}"))
<del> migrator.migrate
<del> rescue Migrator::MigratorDifferentTapsError
<del> end
<add> load_formula_renames
<add> report.update_renamed
<add>
<add> # Migrate installed renamed formulae from core and taps.
<add> report.select_formula(:R).each do |oldname, newname|
<add> if oldname.include?("/")
<add> user, repo, oldname = oldname.split("/", 3)
<add> newname = newname.split("/", 3).last
<add> else
<add> user, repo = "homebrew", "homebrew"
<ide> end
<del> end
<ide>
<del> # Migrate installed renamed formulae from taps
<del> report.select_formula(:D).each do |oldname|
<del> user, repo, oldname = oldname.split("/", 3)
<del> next unless user && repo && oldname
<del> tap = Tap.new(user, repo)
<del> next unless newname = tap.formula_renames[oldname]
<ide> next unless (dir = HOMEBREW_CELLAR/oldname).directory? && !dir.subdirs.empty?
<ide>
<ide> begin
<ide> def dump
<ide>
<ide> dump_formula_report :A, "New Formulae"
<ide> dump_formula_report :M, "Updated Formulae"
<add> dump_formula_report :R, "Renamed Formulae"
<ide> dump_formula_report :D, "Deleted Formulae"
<ide> end
<ide>
<del> def select_formula(key)
<del> fetch(key, []).map do |path|
<add> def update_renamed
<add> @hash[:R] ||= []
<add>
<add> fetch(:D, []).each do |path|
<ide> case path.to_s
<ide> when HOMEBREW_TAP_PATH_REGEX
<del> "#{$1}/#{$2.sub("homebrew-", "")}/#{path.basename(".rb")}"
<add> user = $1
<add> repo = $2.sub("homebrew-", "")
<add> oldname = path.basename(".rb").to_s
<add> next unless newname = Tap.new(user, repo).formula_renames[oldname]
<add> else
<add> oldname = path.basename(".rb").to_s
<add> next unless newname = FORMULA_RENAMES[oldname]
<add> end
<add>
<add> if fetch(:A, []).include?(newpath = path.dirname.join("#{newname}.rb"))
<add> @hash[:R] << [path, newpath]
<add> end
<add> end
<add>
<add> @hash[:A] -= @hash[:R].map(&:last) if @hash[:A]
<add> @hash[:D] -= @hash[:R].map(&:first) if @hash[:D]
<add> end
<add>
<add> def select_formula(key)
<add> fetch(key, []).map do |path, newpath|
<add> if path.to_s =~ HOMEBREW_TAP_PATH_REGEX
<add> tap = "#{$1}/#{$2.sub("homebrew-", "")}"
<add> if newpath
<add> ["#{tap}/#{path.basename(".rb")}", "#{tap}/#{newpath.basename(".rb")}"]
<add> else
<add> "#{tap}/#{path.basename(".rb")}"
<add> end
<add> elsif newpath
<add> ["#{path.basename(".rb")}", "#{newpath.basename(".rb")}"]
<ide> else
<ide> path.basename(".rb").to_s
<ide> end
<ide> def select_formula(key)
<ide>
<ide> def dump_formula_report(key, title)
<ide> formula = select_formula(key)
<add> formula.map! { |oldname, newname| "#{oldname} -> #{newname}" } if key == :R
<ide> unless formula.empty?
<ide> ohai title
<ide> puts_columns formula | 1 |
Ruby | Ruby | handle non-extent methods passed as arguments | 6017811397b7ee0797fe452309e37fb5018689a5 | <ide><path>Library/Homebrew/cmd/doctor.rb
<ide> def doctor
<ide>
<ide> first_warning = true
<ide> methods.each do |method|
<del> out = checks.send(method)
<add> begin
<add> out = checks.send(method)
<add> rescue NoMethodError
<add> Homebrew.failed = true
<add> puts "No check available by the name: #{method}"
<add> next
<add> end
<ide> unless out.nil? or out.empty?
<ide> if first_warning
<ide> puts <<-EOS.undent | 1 |
PHP | PHP | add merge option to instanceconfig trait | 08a6faf077511393792f9b26733ab58b5f77a1f2 | <ide><path>src/Controller/Component.php
<ide> class Component extends Object implements EventListener {
<ide> public function __construct(ComponentRegistry $registry, $config = []) {
<ide> $this->_registry = $registry;
<ide>
<del> $this->config($config);
<add> $this->config($config, null, true);
<ide>
<ide> $this->_set($this->config());
<ide>
<ide><path>src/Controller/Component/Auth/AbstractPasswordHasher.php
<ide> abstract class AbstractPasswordHasher {
<ide> * @param array $config Array of config.
<ide> */
<ide> public function __construct($config = array()) {
<del> $this->config($config);
<add> $this->config($config, null, true);
<ide> }
<ide>
<ide> /**
<ide><path>src/Controller/Component/Auth/BaseAuthenticate.php
<ide> abstract class BaseAuthenticate {
<ide> */
<ide> public function __construct(ComponentRegistry $registry, $config) {
<ide> $this->_registry = $registry;
<del> $this->config($config);
<add> $this->config($config, null, true);
<ide> }
<ide>
<ide> /**
<ide><path>src/Controller/Component/Auth/BaseAuthorize.php
<ide> public function __construct(ComponentRegistry $registry, $config = array()) {
<ide> $this->_registry = $registry;
<ide> $controller = $registry->getController();
<ide> $this->controller($controller);
<del> $this->config($config);
<add> $this->config($config, null, true);
<ide> }
<ide>
<ide> /**
<ide><path>src/Core/InstanceConfigTrait.php
<ide> namespace Cake\Core;
<ide>
<ide> use Cake\Error;
<add>use Cake\Utility\Hash;
<ide>
<ide> /**
<ide> * A trait for reading and writing instance config
<ide> trait InstanceConfigTrait {
<ide> * @param string|array|null $key the key to get/set, or a complete array of configs
<ide> * @param mixed|null $value the value to set
<ide> * @return mixed|null null for write, or whatever is in the config on read
<add> * @param bool $merge whether to merge or overwrite existing config
<ide> * @throws \Cake\Error\Exception When trying to set a key that is invalid
<ide> */
<del> public function config($key = null, $value = null) {
<add> public function config($key = null, $value = null, $merge = false) {
<ide> if (!$this->_configInitialized) {
<ide> $this->_config = $this->_defaultConfig;
<ide> $this->_configInitialized = true;
<ide> }
<ide>
<del> if (is_array($key) || func_num_args() === 2) {
<del> return $this->_configWrite($key, $value);
<add> if (is_array($key) || func_num_args() >= 2) {
<add> return $this->_configWrite($key, $value, $merge);
<ide> }
<ide>
<ide> return $this->_configRead($key);
<ide> protected function _configRead($key) {
<ide> *
<ide> * @throws Cake\Error\Exception if attempting to clobber existing config
<ide> * @param string|array $key
<del> * @param mixed|null $value
<add> * @param mixed $value
<add> * @param bool $merge
<ide> * @return void
<ide> */
<del> protected function _configWrite($key, $value = null) {
<add> protected function _configWrite($key, $value, $merge = null) {
<add> if (is_string($key) && $value === null) {
<add> return $this->_configDelete($key);
<add> }
<add>
<add> if ($merge) {
<add> if (is_array($key)) {
<add> $update = $key;
<add> } else {
<add> $update = [$key => $value];
<add> }
<add> $this->_config = Hash::merge($this->_config, Hash::expand($update));
<add> return;
<add> }
<add>
<ide> if (is_array($key)) {
<ide> foreach ($key as $k => $val) {
<ide> $this->_configWrite($k, $val);
<ide> }
<ide> return;
<ide> }
<ide>
<del> if ($value === null) {
<del> return $this->_configDelete($key);
<del> }
<del>
<ide> if (strpos($key, '.') === false) {
<ide> $this->_config[$key] = $value;
<ide> return;
<ide><path>src/ORM/Behavior.php
<ide> class Behavior implements EventListener {
<ide> * @param array $config The config for this behavior.
<ide> */
<ide> public function __construct(Table $table, array $config = []) {
<del> $this->config($config);
<add> $this->config($config, null, true);
<ide> }
<ide>
<ide> /**
<ide><path>src/Routing/DispatcherFilter.php
<ide> abstract class DispatcherFilter implements EventListener {
<ide> * @param array $config Settings for the filter.
<ide> */
<ide> public function __construct($config = []) {
<del> $this->config($config);
<add> $this->config($config, null, true);
<ide> }
<ide>
<ide> /**
<ide><path>src/View/Helper.php
<ide> public function __construct(View $View, $config = array()) {
<ide> if ($config) {
<ide> $config = Hash::merge($this->_defaultConfig, $config);
<ide> }
<del> $this->config($config);
<add> $this->config($config, null, true);
<ide>
<ide> if (!empty($this->helpers)) {
<ide> $this->_helperMap = $View->Helpers->normalizeArray($this->helpers);
<ide><path>src/View/StringTemplate.php
<ide> class StringTemplate {
<ide> * @param array $templates A set of templates to add.
<ide> */
<ide> public function __construct(array $config = null) {
<del> $this->config($config);
<add> $this->config($config, null, true);
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/Core/InstanceConfigTraitTest.php
<ide> public function testSetArray() {
<ide> * @return void
<ide> */
<ide> public function testSetClobber() {
<del> $this->object->config(['a.nested.value' => 'not possible']);
<add> $this->object->config(['a.nested.value' => 'not possible'], null, false);
<add> $result = $this->object->config();
<add> }
<add>
<add>/**
<add> * testMerge
<add> *
<add> * @return void
<add> */
<add> public function testMerge() {
<add> $this->object->config(['a' => ['nother' => 'value']], null, true);
<add>
<add> $this->assertSame(
<add> [
<add> 'some' => 'string',
<add> 'a' => [
<add> 'nested' => 'value',
<add> 'nother' => 'value'
<add> ]
<add> ],
<add> $this->object->config(),
<add> 'Merging should not delete untouched array values'
<add> );
<add> }
<add>
<add>/**
<add> * testMergeDotKey
<add> *
<add> * @return void
<add> */
<add> public function testMergeDotKey() {
<add> $this->object->config('a.nother', 'value', true);
<add>
<add> $this->assertSame(
<add> [
<add> 'some' => 'string',
<add> 'a' => [
<add> 'nested' => 'value',
<add> 'nother' => 'value'
<add> ]
<add> ],
<add> $this->object->config(),
<add> 'Should act the same as having passed the equivalent array to the config function'
<add> );
<add>
<add> $this->object->config(['a.nextra' => 'value'], null, true);
<add>
<add> $this->assertSame(
<add> [
<add> 'some' => 'string',
<add> 'a' => [
<add> 'nested' => 'value',
<add> 'nother' => 'value',
<add> 'nextra' => 'value'
<add> ]
<add> ],
<add> $this->object->config(),
<add> 'Merging should not delete untouched array values'
<add> );
<add> }
<add>
<add>/**
<add> * testSetDefaultsMerge
<add> *
<add> * @return void
<add> */
<add> public function testSetDefaultsMerge() {
<add> $this->object->config(['a' => ['nother' => 'value']], null, true);
<add>
<add> $this->assertSame(
<add> [
<add> 'some' => 'string',
<add> 'a' => [
<add> 'nested' => 'value',
<add> 'nother' => 'value'
<add> ]
<add> ],
<add> $this->object->config(),
<add> 'First access should act like any subsequent access'
<add> );
<add> }
<add>
<add>/**
<add> * testSetDefaultsNoMerge
<add> *
<add> * @return void
<add> */
<add> public function testSetDefaultsNoMerge() {
<add> $this->object->config(['a' => ['nother' => 'value']], null, false);
<add>
<add> $this->assertSame(
<add> [
<add> 'some' => 'string',
<add> 'a' => [
<add> 'nother' => 'value'
<add> ]
<add> ],
<add> $this->object->config(),
<add> 'If explicitly no-merge, array values should be overwritten'
<add> );
<add> }
<add>
<add>/**
<add> * testSetMergeNoClobber
<add> *
<add> * Merging offers no such protection of clobbering a value whilst implemented
<add> * using the Hash class
<add> *
<add> * @return void
<add> */
<add> public function testSetMergeNoClobber() {
<add> $this->object->config(['a.nested.value' => 'it is possible'], null, true);
<add>
<add> $this->assertSame(
<add> [
<add> 'some' => 'string',
<add> 'a' => [
<add> 'nested' => [
<add> 'value' => 'it is possible'
<add> ]
<add> ]
<add> ],
<add> $this->object->config(),
<add> 'When merging a scalar property will be overwritten with an array'
<add> );
<ide> }
<ide>
<ide> /**
<ide> public function testDeleteNested() {
<ide> }
<ide>
<ide> /**
<del> * testSetClobber
<add> * testDeleteClobber
<ide> *
<ide> * @expectedException \Exception
<ide> * @expectedExceptionMessage Cannot unset a.nested.value.whoops | 10 |
Python | Python | remove duplicate code from perf_kit | 7d69987eddd0d5793339ccfd272bac8721d95894 | <ide><path>scripts/perf/perf_kit/sqlalchemy.py
<ide> def after_cursor_execute(self, conn, cursor, statement, parameters, context, exe
<ide> if self.display_time:
<ide> output_parts.append(f"{total:.5f}")
<ide>
<del> if self.display_time:
<del> output_parts.append(f"{total:.5f}")
<del>
<ide> if self.display_trace:
<ide> output_parts.extend([f"{file_name}", f"{stack_info}"])
<ide> | 1 |
Text | Text | add a dot to a note in readme.md | abae1734d85f453e0f4d56af073df8a8a276ea40 | <ide><path>packages/next/README.md
<ide> export default IndexPage
<ide>
<ide> In this case only the second `<meta name="viewport" />` is rendered.
<ide>
<del>_Note: The contents of `<head>` get cleared upon unmounting the component, so make sure each page completely defines what it needs in `<head>`, without making assumptions about what other pages added_
<add>_Note: The contents of `<head>` get cleared upon unmounting the component, so make sure each page completely defines what it needs in `<head>`, without making assumptions about what other pages added._
<ide>
<ide> _Note: `<title>` and `<meta>` elements need to be contained as **direct** children of the `<Head>` element, or wrapped into maximum one level of `<React.Fragment>`, otherwise the metatags won't be correctly picked up on clientside navigation._
<ide> | 1 |
Text | Text | add import notes in docs. closes | a636320ff3b381a6d7d8685f1b4fba8bdd6c8b94 | <ide><path>docs/api-guide/generic-views.md
<ide> You won't typically need to override the following methods, although you might n
<ide>
<ide> The mixin classes provide the actions that are used to provide the basic view behavior. Note that the mixin classes provide action methods rather than defining the handler methods, such as `.get()` and `.post()`, directly. This allows for more flexible composition of behavior.
<ide>
<add>The mixin classes can be imported from `rest_framework.mixins`.
<add>
<ide> ## ListModelMixin
<ide>
<ide> Provides a `.list(request, *args, **kwargs)` method, that implements listing a queryset.
<ide> If an object is deleted this returns a `204 No Content` response, otherwise it w
<ide>
<ide> The following classes are the concrete generic views. If you're using generic views this is normally the level you'll be working at unless you need heavily customized behavior.
<ide>
<add>The view classes can be imported from `rest_framework.generics`.
<add>
<ide> ## CreateAPIView
<ide>
<ide> Used for **create-only** endpoints. | 1 |
Javascript | Javascript | add missing ; | dd538fe64944d8df18f970b7a23a55ca88848129 | <ide><path>src/extras/FontUtils.js
<ide> THREE.FontUtils.generateShapes = function ( text, parameters ) {
<ide> // To use the typeface.js face files, hook up the API
<ide> var typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };
<ide> if ( typeof self !== 'undefined' ){
<del> self._typeface_js = typeface_js
<add> self._typeface_js = typeface_js;
<ide> }
<del>THREE.typeface_js = typeface_js
<add>THREE.typeface_js = typeface_js;
<ide>
<ide> | 1 |
Python | Python | fix dataset creation in test | 76ba9e70c2f6669eeb84a71437cd13daa3b15bf1 | <ide><path>keras/tests/integration_test.py
<ide> class TokenClassificationIntegrationTest(test_combinations.TestCase):
<ide> """
<ide> def test_token_classification(self):
<ide> np.random.seed(1337)
<del> data = [np.random.randint(low=0, high=16, size=random.randint(4, 16)) for _ in range(100)]
<del> labels = [np.random.randint(low=0, high=3, size=len(arr)) for arr in data]
<add> def densify(x, y):
<add> return x.to_tensor(), y.to_tensor()
<add> data = tf.ragged.stack([np.random.randint(low=0, high=16, size=random.randint(4, 16)) for _ in range(100)])
<add> labels = tf.ragged.stack([np.random.randint(low=0, high=3, size=len(arr)) for arr in data])
<ide> features_dataset = tf.data.Dataset.from_tensor_slices(data)
<ide> labels_dataset = tf.data.Dataset.from_tensor_slices(labels)
<del> dataset = tf.data.Dataset.zip(features_dataset, labels_dataset)
<del> dataset = dataset.padded_batch(batch_size=10) # Pads with 0 values by default
<add> dataset = tf.data.Dataset.zip((features_dataset, labels_dataset))
<add> dataset = dataset.batch(batch_size=10)
<add> dataset = dataset.map(densify) # Pads with 0 values by default
<ide>
<ide> layers = [
<ide> keras.layers.Embedding(16, 4), | 1 |
Text | Text | improve testing suggestions | 76767f3d6e89e540241e973b8ffe04690a9a2ccb | <ide><path>share/doc/homebrew/Formula-Cookbook.md
<ide> The [`test do`](http://www.rubydoc.info/github/Homebrew/homebrew/master/Formula#
<ide>
<ide> We want tests that don't require any user input and test the basic functionality of the application. For example `foo build-foo input.foo` is a good test and (despite their widespread use) `foo --version` and `foo --help` are bad tests. However, a bad test is better than no test at all.
<ide>
<del>See [cmake](https://github.com/Homebrew/homebrew/blob/master/Library/Formula/cmake.rb) for an example of a formula with a good test. A basic `CMakeLists.txt` file is written CMake uses it to generate Makefiles. This test checks that CMake doesn't e.g. segfault during basic operation.
<add>See [cmake](https://github.com/Homebrew/homebrew/blob/master/Library/Formula/cmake.rb) for an example of a formula with a good test. The formula writes a basic `CMakeLists.txt` file into the test directory then calls CMake to generate Makefiles. This test checks that CMake doesn't e.g. segfault during basic operation. Another good example is [tinyxml2](https://github.com/Homebrew/homebrew/blob/master/Library/Formula/tinyxml2.rb), which writes a small C++ source file into the test directory, compiles and links it against the tinyxml2 library and finally checks that the resulting program runs successfully.
<ide>
<ide> ## Manuals
<ide> | 1 |
PHP | PHP | put domain in route output. closes | c9878249b8fd4b8ee0c854bb1b267f5956f2e99c | <ide><path>src/Illuminate/Foundation/Console/RoutesCommand.php
<ide> protected function getRouteInformation($name, Route $route)
<ide> $action = $route->getAction() ?: 'Closure';
<ide>
<ide> return array(
<add> 'host' => $route->getHost(),
<ide> 'uri' => $uri,
<ide> 'name' => $this->getRouteName($name),
<ide> 'action' => $action,
<ide> protected function getRouteInformation($name, Route $route)
<ide> */
<ide> protected function displayRoutes(array $routes)
<ide> {
<del> $headers = array('URI', 'Name', 'Action', 'Before Filters', 'After Filters');
<add> $headers = array('Domain', 'URI', 'Name', 'Action', 'Before Filters', 'After Filters');
<ide>
<ide> $this->table->setHeaders($headers)->setRows($routes);
<ide> | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.