content_type stringclasses 8 values | main_lang stringclasses 7 values | message stringlengths 1 50 | sha stringlengths 40 40 | patch stringlengths 52 962k | file_count int64 1 300 |
|---|---|---|---|---|---|
Text | Text | use proper link | fec2d82721bd1b143af00de54f11883876738186 | <ide><path>README.md
<ide> In order to ensure that the Laravel community is welcoming to all, please review
<ide>
<ide> ## Security Vulnerabilities
<ide>
<del>Please review [our security policy](SECURITY.md) on how to report security vulnerabilities.
<add>Please review [our security policy](https://github.com/laravel/framework/security/policy) on how to report security vulnerabilities.
<ide>
<ide> ## License
<ide> | 1 |
Javascript | Javascript | avoid function call where possible | 20347d51549bc7319ec3a44fe8b5fd25994df462 | <ide><path>lib/internal/streams/utils.js
<ide> function isReadableFinished(stream, strict) {
<ide>
<ide> function isReadable(stream) {
<ide> if (stream && stream[kIsReadable] != null) return stream[kIsReadable];
<del> const r = isReadableNodeStream(stream);
<ide> if (typeof stream?.readable !== 'boolean') return null;
<ide> if (isDestroyed(stream)) return false;
<del> return r && stream.readable && !isReadableFinished(stream);
<add> return isReadableNodeStream(stream) &&
<add> stream.readable &&
<add> !isReadableFinished(stream);
<ide> }
<ide>
<ide> function isWritable(stream) {
<del> const r = isWritableNodeStream(stream);
<ide> if (typeof stream?.writable !== 'boolean') return null;
<ide> if (isDestroyed(stream)) return false;
<del> return r && stream.writable && !isWritableEnded(stream);
<add> return isWritableNodeStream(stream) &&
<add> stream.writable &&
<add> !isWritableEnded(stream);
<ide> }
<ide>
<ide> function isFinished(stream, opts) { | 1 |
PHP | PHP | remove php7 specific syntax | ced58b479cff986604e72753ea66518ec1fbc86c | <ide><path>src/Console/Command.php
<ide> public function abort($code = self::CODE_ERROR)
<ide> * @param \Cake\Console\ConsoleIo $io The ConsoleIo instance to use for the executed command.
<ide> * @return int|null The exit code or null for success of the command.
<ide> */
<del> public function executeCommand($command, array $args = [], ?ConsoleIo $io = null)
<add> public function executeCommand($command, array $args = [], ConsoleIo $io = null)
<ide> {
<ide> if (is_string($command)) {
<ide> if (!class_exists($command)) { | 1 |
Python | Python | add regression test | 7c1260e98c92d01192dd92534215da3f98f7684c | <ide><path>spacy/tests/regression/test_issue852.py
<add># encoding: utf8
<add>from __future__ import unicode_literals
<add>
<add>import pytest
<add>
<add>
<add>@pytest.mark.parametrize('text', ["au-delàs", "pair-programmâmes",
<add> "terra-formées", "σ-compacts"])
<add>def test_issue852(fr_tokenizer, text):
<add> """Test that French tokenizer exceptions are imported correctly."""
<add> tokens = fr_tokenizer(text)
<add> assert len(tokens) == 1 | 1 |
Ruby | Ruby | convert languagemodulerequirement test to spec | f33efbe7c46d4a148af00c83dff73c14717ed0d1 | <ide><path>Library/Homebrew/test/language_module_requirement_spec.rb
<add>require "requirements/language_module_requirement"
<add>
<add>describe LanguageModuleRequirement do
<add> specify "unique dependencies are not equal" do
<add> x = described_class.new(:node, "less")
<add> y = described_class.new(:node, "coffee-script")
<add> expect(x).not_to eq(y)
<add> expect(x.hash).not_to eq(y.hash)
<add> end
<add>
<add> context "when module and import name differ" do
<add> subject { described_class.new(:python, mod_name, import_name) }
<add> let(:mod_name) { "foo" }
<add> let(:import_name) { "bar" }
<add>
<add> its(:message) { is_expected.to include(mod_name) }
<add> its(:the_test) { is_expected.to include("import #{import_name}") }
<add> end
<add>
<add> context "when the language is Perl" do
<add> it "does not satisfy invalid dependencies" do
<add> expect(described_class.new(:perl, "notapackage")).not_to be_satisfied
<add> end
<add>
<add> it "satisfies valid dependencies" do
<add> expect(described_class.new(:perl, "Env")).to be_satisfied
<add> end
<add> end
<add>
<add> context "when the language is Python", :needs_python do
<add> it "does not satisfy invalid dependencies" do
<add> expect(described_class.new(:python, "notapackage")).not_to be_satisfied
<add> end
<add>
<add> it "satisfies valid dependencies" do
<add> expect(described_class.new(:python, "datetime")).to be_satisfied
<add> end
<add> end
<add>
<add> context "when the language is Ruby" do
<add> it "does not satisfy invalid dependencies" do
<add> expect(described_class.new(:ruby, "notapackage")).not_to be_satisfied
<add> end
<add>
<add> it "satisfies valid dependencies" do
<add> expect(described_class.new(:ruby, "date")).to be_satisfied
<add> end
<add> end
<add>end
<ide><path>Library/Homebrew/test/language_module_requirement_test.rb
<del>require "testing_env"
<del>require "requirements/language_module_requirement"
<del>
<del>class LanguageModuleRequirementTests < Homebrew::TestCase
<del> parallelize_me!
<del>
<del> def assert_deps_fail(spec)
<del> refute_predicate LanguageModuleRequirement.new(*spec.shift.reverse), :satisfied?
<del> end
<del>
<del> def assert_deps_pass(spec)
<del> assert_predicate LanguageModuleRequirement.new(*spec.shift.reverse), :satisfied?
<del> end
<del>
<del> def test_unique_deps_are_not_eql
<del> x = LanguageModuleRequirement.new(:node, "less")
<del> y = LanguageModuleRequirement.new(:node, "coffee-script")
<del> refute_eql x, y
<del> refute_equal x.hash, y.hash
<del> end
<del>
<del> def test_differing_module_and_import_name
<del> mod_name = "foo"
<del> import_name = "bar"
<del> l = LanguageModuleRequirement.new(:python, mod_name, import_name)
<del> assert_includes l.message, mod_name
<del> assert_includes l.the_test, "import #{import_name}"
<del> end
<del>
<del> def test_bad_perl_deps
<del> assert_deps_fail "notapackage" => :perl
<del> end
<del>
<del> def test_good_perl_deps
<del> assert_deps_pass "Env" => :perl
<del> end
<del>
<del> def test_bad_python_deps
<del> needs_python
<del> assert_deps_fail "notapackage" => :python
<del> end
<del>
<del> def test_good_python_deps
<del> needs_python
<del> assert_deps_pass "datetime" => :python
<del> end
<del>
<del> def test_bad_ruby_deps
<del> assert_deps_fail "notapackage" => :ruby
<del> end
<del>
<del> def test_good_ruby_deps
<del> assert_deps_pass "date" => :ruby
<del> end
<del>end
<ide><path>Library/Homebrew/test/spec_helper.rb
<ide> if example.metadata[:needs_macos]
<ide> skip "not on macOS" unless OS.mac?
<ide> end
<add>
<add> if example.metadata[:needs_python]
<add> skip "Python not installed." unless which("python")
<add> end
<ide> end
<ide> config.around(:each) do |example|
<ide> begin | 3 |
Python | Python | fix typos in hiveoperator | 457949d49f12cffcb3466ad44f4349bfd0c68f1c | <ide><path>airflow/operators/hive_operator.py
<ide> class HiveOperator(BaseOperator):
<ide> :param hive_cli_conn_id: reference to the Hive database
<ide> :type hive_cli_conn_id: string
<ide> :param hiveconf_jinja_translate: when True, hiveconf-type templating
<del> ${var} gets translated into jina-type templating {{ var }}. Note that
<del> you may want to use along this along with the
<add> ${var} gets translated into jinja-type templating {{ var }}. Note that
<add> you may want to use this along with the
<ide> ``DAG(user_defined_macros=myargs)`` parameter. View the DAG
<ide> object documentation for more details.
<ide> :type hiveconf_jinja_translate: boolean | 1 |
Ruby | Ruby | fix schema leakage from dirty_test.rb | de24b8cb9c38a02b521d762d4b8eef11f6a78978 | <ide><path>activerecord/test/cases/dirty_test.rb
<ide> def test_field_named_field
<ide> end
<ide> ensure
<ide> ActiveRecord::Base.connection.drop_table :testings rescue nil
<add> ActiveRecord::Base.clear_cache!
<ide> end
<ide> end
<ide> | 1 |
Python | Python | add tests for lagfit with deg specified as list | 84e0b6ec1b686b908eb2d8bba38337a13f02cb82 | <ide><path>numpy/polynomial/tests/test_laguerre.py
<ide> def f(x):
<ide> assert_raises(TypeError, lag.lagfit, [1], [1, 2], 0)
<ide> assert_raises(TypeError, lag.lagfit, [1], [1], 0, w=[[1]])
<ide> assert_raises(TypeError, lag.lagfit, [1], [1], 0, w=[1, 1])
<add> assert_raises(ValueError, lag.lagfit, [1], [1], [-1,])
<add> assert_raises(ValueError, lag.lagfit, [1], [1], [2, -1, 6])
<add> assert_raises(TypeError, lag.lagfit, [1], [1], [])
<ide>
<ide> # Test fit
<ide> x = np.linspace(0, 2)
<ide> def f(x):
<ide> coef3 = lag.lagfit(x, y, 3)
<ide> assert_equal(len(coef3), 4)
<ide> assert_almost_equal(lag.lagval(x, coef3), y)
<add> coef3 = lag.lagfit(x, y, [0, 1, 2, 3])
<add> assert_equal(len(coef3), 4)
<add> assert_almost_equal(lag.lagval(x, coef3), y)
<ide> #
<ide> coef4 = lag.lagfit(x, y, 4)
<ide> assert_equal(len(coef4), 5)
<ide> assert_almost_equal(lag.lagval(x, coef4), y)
<add> coef4 = lag.lagfit(x, y, [0, 1, 2, 3, 4])
<add> assert_equal(len(coef4), 5)
<add> assert_almost_equal(lag.lagval(x, coef4), y)
<ide> #
<ide> coef2d = lag.lagfit(x, np.array([y, y]).T, 3)
<ide> assert_almost_equal(coef2d, np.array([coef3, coef3]).T)
<add> coef2d = lag.lagfit(x, np.array([y, y]).T, [0, 1, 2, 3])
<add> assert_almost_equal(coef2d, np.array([coef3, coef3]).T)
<ide> # test weighting
<ide> w = np.zeros_like(x)
<ide> yw = y.copy()
<ide> w[1::2] = 1
<ide> y[0::2] = 0
<ide> wcoef3 = lag.lagfit(x, yw, 3, w=w)
<ide> assert_almost_equal(wcoef3, coef3)
<add> wcoef3 = lag.lagfit(x, yw, [0, 1, 2, 3], w=w)
<add> assert_almost_equal(wcoef3, coef3)
<ide> #
<ide> wcoef2d = lag.lagfit(x, np.array([yw, yw]).T, 3, w=w)
<ide> assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)
<add> wcoef2d = lag.lagfit(x, np.array([yw, yw]).T, [0, 1, 2, 3], w=w)
<add> assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)
<ide> # test scaling with complex values x points whose square
<ide> # is zero when summed.
<ide> x = [1, 1j, -1, -1j]
<ide> assert_almost_equal(lag.lagfit(x, x, 1), [1, -1])
<add> assert_almost_equal(lag.lagfit(x, x, [0, 1]), [1, -1])
<ide>
<ide>
<ide> class TestCompanion(TestCase): | 1 |
Javascript | Javascript | use a class for whatwg url[context] | 14a91957f8bce2d614ec361f982aa56378f1c24e | <ide><path>lib/internal/url.js
<ide> const util = require('util');
<ide> const {
<ide> hexTable,
<del> isHexTable,
<del> StorageObject
<add> isHexTable
<ide> } = require('internal/querystring');
<ide> const binding = process.binding('url');
<ide> const context = Symbol('context');
<ide> class TupleOrigin {
<ide> }
<ide> }
<ide>
<add>// This class provides the internal state of a URL object. An instance of this
<add>// class is stored in every URL object and is accessed internally by setters
<add>// and getters. It roughly corresponds to the concept of a URL record in the
<add>// URL Standard, with a few differences. It is also the object transported to
<add>// the C++ binding.
<add>// Refs: https://url.spec.whatwg.org/#concept-url
<add>class URLContext {
<add> constructor() {
<add> this.flags = 0;
<add> this.scheme = undefined;
<add> this.username = undefined;
<add> this.password = undefined;
<add> this.host = undefined;
<add> this.port = undefined;
<add> this.path = [];
<add> this.query = undefined;
<add> this.fragment = undefined;
<add> }
<add>}
<add>
<ide> function onParseComplete(flags, protocol, username, password,
<ide> host, port, path, query, fragment) {
<ide> var ctx = this[context];
<ide> function onParseError(flags, input) {
<ide> // Reused by URL constructor and URL#href setter.
<ide> function parse(url, input, base) {
<ide> const base_context = base ? base[context] : undefined;
<del> url[context] = new StorageObject();
<add> url[context] = new URLContext();
<ide> binding.parse(input.trim(), -1,
<ide> base_context, undefined,
<ide> onParseComplete.bind(url), onParseError); | 1 |
Javascript | Javascript | add tabbarios.item on android | 5e20b7bcfbefa9084ab6cdac9c24926ba8a64126 | <ide><path>Libraries/Components/TabBarIOS/TabBarIOS.android.js
<ide> * of patent rights can be found in the PATENTS file in the same directory.
<ide> *
<ide> * @providesModule TabBarIOS
<add> * @flow
<ide> */
<ide>
<ide> 'use strict';
<ide>
<del>var React = require('React');
<del>var View = require('View');
<del>var StyleSheet = require('StyleSheet');
<add>const React = require('React');
<add>const StyleSheet = require('StyleSheet');
<add>const TabBarItemIOS = require('TabBarItemIOS');
<add>const View = require('View');
<ide>
<ide> class DummyTabBarIOS extends React.Component {
<add> static Item = TabBarItemIOS;
<add>
<ide> render() {
<ide> return (
<ide> <View style={[this.props.style, styles.tabGroup]}>
<ide> class DummyTabBarIOS extends React.Component {
<ide> }
<ide> }
<ide>
<del>var styles = StyleSheet.create({
<add>const styles = StyleSheet.create({
<ide> tabGroup: {
<ide> flex: 1,
<ide> } | 1 |
Java | Java | fix links in javadoc | c7f44ff671fe13e8474316ebe074fdde8d413326 | <ide><path>spring-beans/src/test/java/org/springframework/beans/factory/xml/DuplicateBeanIdTests.java
<ide> *
<ide> * @author Chris Beams
<ide> * @since 3.1
<del> * @see org.springframework.beans.factory.xml.XmlBeanFactoryTests#testWithDuplicateName
<del> * @see org.springframework.beans.factory.xml.XmlBeanFactoryTests#testWithDuplicateNameInAlias
<add> * @see org.springframework.beans.factory.xml.XmlBeanFactoryTests#withDuplicateName
<add> * @see org.springframework.beans.factory.xml.XmlBeanFactoryTests#withDuplicateNameInAlias
<ide> */
<ide> public class DuplicateBeanIdTests {
<ide>
<ide><path>spring-context/src/test/java/org/springframework/aop/framework/AbstractAopProxyTests.java
<ide> public void testIntroductionThrowsUncheckedException() throws Throwable {
<ide> @SuppressWarnings("serial")
<ide> class MyDi extends DelegatingIntroductionInterceptor implements TimeStamped {
<ide> /**
<del> * @see org.springframework.core.testfixture.util.TimeStamped#getTimeStamp()
<add> * @see org.springframework.core.testfixture.TimeStamped#getTimeStamp()
<ide> */
<ide> @Override
<ide> public long getTimeStamp() {
<ide><path>spring-core/src/main/java/org/springframework/core/env/ReadOnlySystemAttributesMap.java
<ide> * Read-only {@code Map<String, String>} implementation that is backed by system
<ide> * properties or environment variables.
<ide> *
<del> * <p>Used by {@link AbstractApplicationContext} when a {@link SecurityManager} prohibits
<add> * <p>Used by {@link AbstractEnvironment} when a {@link SecurityManager} prohibits
<ide> * access to {@link System#getProperties()} or {@link System#getenv()}. It is for this
<ide> * reason that the implementations of {@link #keySet()}, {@link #entrySet()}, and
<ide> * {@link #values()} always return empty even though {@link #get(Object)} may in fact
<ide><path>spring-core/src/test/java/org/springframework/core/annotation/AnnotatedElementUtilsTests.java
<ide> void findMergedAnnotationAttributesInheritedFromBridgedMethod() throws NoSuchMet
<ide>
<ide> /**
<ide> * Bridge/bridged method setup code copied from
<del> * {@link org.springframework.core.BridgeMethodResolverTests#testWithGenericParameter()}.
<add> * {@link org.springframework.core.BridgeMethodResolverTests#withGenericParameter()}.
<ide> * @since 4.2
<ide> */
<ide> @Test
<ide><path>spring-core/src/test/java/org/springframework/core/annotation/MultipleComposedAnnotationsOnSingleAnnotatedElementTests.java
<ide> void findMultipleComposedAnnotationsOnBridgeMethod() throws Exception {
<ide>
<ide> /**
<ide> * Bridge/bridged method setup code copied from
<del> * {@link org.springframework.core.BridgeMethodResolverTests#testWithGenericParameter()}.
<add> * {@link org.springframework.core.BridgeMethodResolverTests#withGenericParameter()}.
<ide> */
<ide> Method getBridgeMethod() throws NoSuchMethodException {
<ide> Method[] methods = StringGenericParameter.class.getMethods();
<ide><path>spring-web/src/main/java/org/springframework/http/codec/protobuf/ProtobufDecoder.java
<ide> public Iterable<? extends Message> apply(DataBuffer input) {
<ide> *
<ide> * @return {code true} when the message size is parsed successfully, {code false} when the message size is
<ide> * truncated
<del> * @see <a href ="https://developers.google.com/protocol-buffers/docs/encoding#varints">Base 128 Varints</a>
<add> * @see <a href="https://developers.google.com/protocol-buffers/docs/encoding#varints">Base 128 Varints</a>
<ide> */
<ide> private boolean readMessageSize(DataBuffer input) {
<ide> if (this.offset == 0) {
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/view/tiles3/AbstractSpringPreparerFactory.java
<ide> import org.springframework.web.servlet.DispatcherServlet;
<ide>
<ide> /**
<del> * Abstract implementation of the Tiles {@link org.apache.tiles.preparer.PreparerFactory}
<add> * Abstract implementation of the Tiles {@link org.apache.tiles.preparer.factory.PreparerFactory}
<ide> * interface, obtaining the current Spring WebApplicationContext and delegating to
<ide> * {@link #getPreparer(String, org.springframework.web.context.WebApplicationContext)}.
<ide> *
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/view/tiles3/SimpleSpringPreparerFactory.java
<ide> import org.springframework.web.context.WebApplicationContext;
<ide>
<ide> /**
<del> * Tiles {@link org.apache.tiles.preparer.PreparerFactory} implementation
<add> * Tiles {@link org.apache.tiles.preparer.factory.PreparerFactory} implementation
<ide> * that expects preparer class names and builds preparer instances for those,
<ide> * creating them through the Spring ApplicationContext in order to apply
<ide> * Spring container callbacks and configured Spring BeanPostProcessors.
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/view/tiles3/SpringBeanPreparerFactory.java
<ide> import org.springframework.web.context.WebApplicationContext;
<ide>
<ide> /**
<del> * Tiles {@link org.apache.tiles.preparer.PreparerFactory} implementation
<add> * Tiles {@link org.apache.tiles.preparer.factory.PreparerFactory} implementation
<ide> * that expects preparer bean names and obtains preparer beans from the
<ide> * Spring ApplicationContext. The full bean creation process will be in
<ide> * the control of the Spring application context in this case, allowing | 9 |
Python | Python | add test for gufunc scalar case | b5c77332b0ef46d7373c92e71866a8885f375ddf | <ide><path>numpy/core/tests/test_ufunc.py
<ide> def test_forced_sig(self):
<ide> def test_inner1d(self):
<ide> a = np.arange(6).reshape((2,3))
<ide> assert_array_equal(umt.inner1d(a,a), np.sum(a*a,axis=-1))
<add> a = np.arange(6)
<add> assert_array_equal(umt.inner1d(a,a), np.sum(a*a))
<ide>
<ide> def test_broadcast(self):
<ide> msg = "broadcast" | 1 |
PHP | PHP | add integration test | f970b65732ed0688434b277d25afaf5c28b57021 | <ide><path>tests/Redis/RedisConnectionTest.php
<ide> public function connections()
<ide> $prefixedPhpredis = new RedisManager(new Application, 'phpredis', [
<ide> 'cluster' => false,
<ide> 'default' => [
<del> 'host' => $host,
<del> 'port' => $port,
<add> 'url' => "redis://user@$host:$port",
<add> 'host' => 'overwrittenByUrl',
<add> 'port' => 'overwrittenByUrl',
<ide> 'database' => 5,
<ide> 'options' => ['prefix' => 'laravel:'],
<ide> 'timeout' => 0.5, | 1 |
Text | Text | remove errors within a challenge solution | c201e415647c9e2a993cacb1aeb1df5a7978b142 | <ide><path>guide/arabic/certifications/coding-interview-prep/algorithms/inventory-update/index.md
<ide> localeTitle: تحديث المخزون
<ide> // A helper method to return the index of a specified product (undefined if not found)
<ide> var getProductIndex = function (name) {
<ide> for (var i = 0; i < this.length; i++) {
<del> if (this<a href='https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:"' target='_blank' rel='nofollow'>i][1] === name) {
<add> if (this[i][1] === name) {
<ide> return i;
<ide> }
<ide> }
<ide> localeTitle: تحديث المخزون
<ide> // All inventory must be accounted for or you're fired!
<ide>
<ide> var index;
<del> var arrCurInvName = <a href='https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:"' target='_blank' rel='nofollow'>]; // Names of arr1's items
<add> var arrCurInvName = []; // Names of arr1's items
<ide> var arrNeInvName = []; // Names of arr2's items
<ide>
<ide> // Same as using two for loops, this takes care of increasing the number of stock quantity.
<ide> localeTitle: تحديث المخزون
<ide> * تصنيف الحل في واحدة من الفئات التالية - **الأساسي** **والمتوسط** **والمتقدم** . 
<ide> * الرجاء إضافة اسم المستخدم الخاص بك فقط إذا قمت بإضافة أي **محتويات رئيسية ذات صلة** . (  **_لا_** _تزيل أي أسماء مستخدمين حالية_ )
<ide>
<del>> نرى  [**`Wiki Challenge Solution Template`**](http://forum.freecodecamp.com/t/algorithm-article-template/14272) كمرجع.
<ide>\ No newline at end of file
<add>> نرى  [**`Wiki Challenge Solution Template`**](http://forum.freecodecamp.com/t/algorithm-article-template/14272) كمرجع.
<ide><path>guide/chinese/certifications/coding-interview-prep/algorithms/inventory-update/index.md
<ide> localeTitle: 库存更新
<ide> // A helper method to return the index of a specified product (undefined if not found)
<ide> var getProductIndex = function (name) {
<ide> for (var i = 0; i < this.length; i++) {
<del> if (this<a href='https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:"' target='_blank' rel='nofollow'>i][1] === name) {
<add> if (this[i][1] === name) {
<ide> return i;
<ide> }
<ide> }
<ide> localeTitle: 库存更新
<ide> // All inventory must be accounted for or you're fired!
<ide>
<ide> var index;
<del> var arrCurInvName = <a href='https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:"' target='_blank' rel='nofollow'>]; // Names of arr1's items
<add> var arrCurInvName = []; // Names of arr1's items
<ide> var arrNeInvName = []; // Names of arr2's items
<ide>
<ide> // Same as using two for loops, this takes care of increasing the number of stock quantity.
<ide> localeTitle: 库存更新
<ide> * 将解决方案分为以下类别之一 - **基本** , **中级**和**高级** 。 
<ide> * 如果您添加了任何**相关的主要内容,**请仅添加您的用户名。 (  **_不要_** _删除任何现有的用户名_ )
<ide>
<del>> 看到 [**`Wiki Challenge Solution Template`**](http://forum.freecodecamp.com/t/algorithm-article-template/14272)供参考。
<ide>\ No newline at end of file
<add>> 看到 [**`Wiki Challenge Solution Template`**](http://forum.freecodecamp.com/t/algorithm-article-template/14272)供参考。
<ide><path>guide/english/certifications/coding-interview-prep/algorithms/inventory-update/index.md
<ide> Return the completed inventory in alphabetical order.
<ide> // A helper method to return the index of a specified product (undefined if not found)
<ide> var getProductIndex = function (name) {
<ide> for (var i = 0; i < this.length; i++) {
<del> if (this<a href='https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:"' target='_blank' rel='nofollow'>i][1] === name) {
<add> if (this[i][1] === name) {
<ide> return i;
<ide> }
<ide> }
<ide> Return the completed inventory in alphabetical order.
<ide> // All inventory must be accounted for or you're fired!
<ide>
<ide> var index;
<del> var arrCurInvName = <a href='https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:"' target='_blank' rel='nofollow'>]; // Names of arr1's items
<add> var arrCurInvName = []; // Names of arr1's items
<ide> var arrNeInvName = []; // Names of arr2's items
<ide>
<ide> // Same as using two for loops, this takes care of increasing the number of stock quantity.
<ide><path>guide/portuguese/certifications/coding-interview-prep/algorithms/inventory-update/index.md
<ide> Retorne o inventário completo em ordem alfabética.
<ide> // A helper method to return the index of a specified product (undefined if not found)
<ide> var getProductIndex = function (name) {
<ide> for (var i = 0; i < this.length; i++) {
<del> if (this<a href='https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:"' target='_blank' rel='nofollow'>i][1] === name) {
<add> if (this[i][1] === name) {
<ide> return i;
<ide> }
<ide> }
<ide> Retorne o inventário completo em ordem alfabética.
<ide> // All inventory must be accounted for or you're fired!
<ide>
<ide> var index;
<del> var arrCurInvName = <a href='https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:"' target='_blank' rel='nofollow'>]; // Names of arr1's items
<add> var arrCurInvName = []; // Names of arr1's items
<ide> var arrNeInvName = []; // Names of arr2's items
<ide>
<ide> // Same as using two for loops, this takes care of increasing the number of stock quantity.
<ide> Retorne o inventário completo em ordem alfabética.
<ide> * Categorize a solução em uma das seguintes categorias - **Básica** , **Intermediária** e **Avançada** . 
<ide> * Por favor, adicione seu nome de usuário somente se você adicionou qualquer **conteúdo principal relevante** . (  **_NÃO_** _remova nenhum nome de usuário existente_ )
<ide>
<del>> Vejo  [**`Wiki Challenge Solution Template`**](http://forum.freecodecamp.com/t/algorithm-article-template/14272) para referência.
<ide>\ No newline at end of file
<add>> Vejo  [**`Wiki Challenge Solution Template`**](http://forum.freecodecamp.com/t/algorithm-article-template/14272) para referência.
<ide><path>guide/russian/certifications/coding-interview-prep/algorithms/inventory-update/index.md
<ide> localeTitle: Обновление инвентаря
<ide> // A helper method to return the index of a specified product (undefined if not found)
<ide> var getProductIndex = function (name) {
<ide> for (var i = 0; i < this.length; i++) {
<del> if (this<a href='https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:"' target='_blank' rel='nofollow'>i][1] === name) {
<add> if (this[i][1] === name) {
<ide> return i;
<ide> }
<ide> }
<ide> localeTitle: Обновление инвентаря
<ide> // All inventory must be accounted for or you're fired!
<ide>
<ide> var index;
<del> var arrCurInvName = <a href='https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:"' target='_blank' rel='nofollow'>]; // Names of arr1's items
<add> var arrCurInvName = []; // Names of arr1's items
<ide> var arrNeInvName = []; // Names of arr2's items
<ide>
<ide> // Same as using two for loops, this takes care of increasing the number of stock quantity.
<ide> localeTitle: Обновление инвентаря
<ide> * Классифицируйте решение в одной из следующих категорий - **Basic** , **Intermediate** и **Advanced** . 
<ide> * Пожалуйста, добавьте свое имя пользователя, только если вы добавили **соответствующее основное содержимое** . (  **_НЕ_** _удаляйте существующие имена пользователей_ )
<ide>
<del>> Видеть  [**`Wiki Challenge Solution Template`**](http://forum.freecodecamp.com/t/algorithm-article-template/14272) для [**`Wiki Challenge Solution Template`**](http://forum.freecodecamp.com/t/algorithm-article-template/14272) для справки.
<ide>\ No newline at end of file
<add>> Видеть  [**`Wiki Challenge Solution Template`**](http://forum.freecodecamp.com/t/algorithm-article-template/14272) для [**`Wiki Challenge Solution Template`**](http://forum.freecodecamp.com/t/algorithm-article-template/14272) для справки.
<ide><path>guide/spanish/certifications/coding-interview-prep/algorithms/inventory-update/index.md
<ide> Devuelve el inventario completado en orden alfabético.
<ide> // A helper method to return the index of a specified product (undefined if not found)
<ide> var getProductIndex = function (name) {
<ide> for (var i = 0; i < this.length; i++) {
<del> if (this<a href='https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:"' target='_blank' rel='nofollow'>i][1] === name) {
<add> if (this[i][1] === name) {
<ide> return i;
<ide> }
<ide> }
<ide> Devuelve el inventario completado en orden alfabético.
<ide> // All inventory must be accounted for or you're fired!
<ide>
<ide> var index;
<del> var arrCurInvName = <a href='https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:"' target='_blank' rel='nofollow'>]; // Names of arr1's items
<add> var arrCurInvName = []; // Names of arr1's items
<ide> var arrNeInvName = []; // Names of arr2's items
<ide>
<ide> // Same as using two for loops, this takes care of increasing the number of stock quantity.
<ide> Devuelve el inventario completado en orden alfabético.
<ide> * Categorice la solución en una de las siguientes categorías: **Básica** , **Intermedia** y **Avanzada** . 
<ide> * Agregue su nombre de usuario solo si ha agregado algún **contenido principal relevante** . (  **_NO_** _elimine ningún nombre de usuario existente_ )
<ide>
<del>> Ver  [**`Wiki Challenge Solution Template`**](http://forum.freecodecamp.com/t/algorithm-article-template/14272) para referencia.
<ide>\ No newline at end of file
<add>> Ver  [**`Wiki Challenge Solution Template`**](http://forum.freecodecamp.com/t/algorithm-article-template/14272) para referencia. | 6 |
Text | Text | add changelog entry for [ci skip] | 2a90d60c941deb4ba31fa7bcfd5ebee1b536c963 | <ide><path>activerecord/CHANGELOG.md
<add>* Alias `ActiveRecord::Relation#left_joins` to
<add> `ActiveRecord::Relation#left_outer_joins`.
<add>
<add> *Takashi Kokubun*
<add>
<ide> * Use advisory locking to raise a ConcurrentMigrationError instead of
<ide> attempting to migrate when another migration is currently running.
<ide> | 1 |
Javascript | Javascript | fix one last alias case | 149fe898645e45e499b2b1acf31095b9c859599a | <ide><path>packages/ember-metal/lib/mixin.js
<ide> function applyMixin(obj, mixins, partial) {
<ide> } else {
<ide> while (desc && desc instanceof Alias) {
<ide> var altKey = desc.methodName;
<del> if (descs[altKey]) {
<add> if (descs[altKey] || values[altKey]) {
<ide> value = values[altKey];
<ide> desc = descs[altKey];
<ide> } else if (m.descs[altKey]) { | 1 |
Ruby | Ruby | add outdated_versions tests | d47df68cbd03fb621825d12a531f91938571ec04 | <ide><path>Library/Homebrew/test/test_formula.rb
<ide> def test_pour_bottle_dsl
<ide> assert f_true.pour_bottle?
<ide> end
<ide> end
<add>
<add>class OutdatedVersionsTests < Homebrew::TestCase
<add> attr_reader :outdated_prefix, :same_prefix, :greater_prefix, :head_prefix
<add> attr_reader :f
<add>
<add> def setup
<add> @f = formula { url "foo"; version "1.20" }
<add> @outdated_prefix = HOMEBREW_CELLAR/"#{f.name}/1.11"
<add> @same_prefix = HOMEBREW_CELLAR/"#{f.name}/1.20"
<add> @greater_prefix = HOMEBREW_CELLAR/"#{f.name}/1.21"
<add> @head_prefix = HOMEBREW_CELLAR/"#{f.name}/HEAD"
<add> end
<add>
<add> def teardown
<add> @f.rack.rmtree
<add> end
<add>
<add> def setup_tab_for_prefix(prefix, tap_string=nil)
<add> prefix.mkpath
<add> tab = Tab.empty
<add> tab.tabfile = prefix.join("INSTALL_RECEIPT.json")
<add> tab.source["tap"] = tap_string if tap_string
<add> tab.write
<add> tab
<add> end
<add>
<add> def test_greater_different_tap_installed
<add> setup_tab_for_prefix(greater_prefix, "user/repo")
<add> assert_predicate f.outdated_versions, :empty?
<add> end
<add>
<add> def test_greater_same_tap_installed
<add> f.instance_variable_set(:@tap, CoreTap.instance)
<add> setup_tab_for_prefix(greater_prefix, "homebrew/core")
<add> assert_predicate f.outdated_versions, :empty?
<add> end
<add>
<add> def test_outdated_different_tap_installed
<add> setup_tab_for_prefix(outdated_prefix, "user/repo")
<add> refute_predicate f.outdated_versions, :empty?
<add> end
<add>
<add> def test_outdated_same_tap_installed
<add> f.instance_variable_set(:@tap, CoreTap.instance)
<add> setup_tab_for_prefix(outdated_prefix, "homebrew/core")
<add> refute_predicate f.outdated_versions, :empty?
<add> end
<add>
<add> def test_same_head_installed
<add> f.instance_variable_set(:@tap, CoreTap.instance)
<add> setup_tab_for_prefix(head_prefix, "homebrew/core")
<add> assert_predicate f.outdated_versions, :empty?
<add> end
<add>
<add> def test_different_head_installed
<add> f.instance_variable_set(:@tap, CoreTap.instance)
<add> setup_tab_for_prefix(head_prefix, "user/repo")
<add> assert_predicate f.outdated_versions, :empty?
<add> end
<add>
<add> def test_mixed_taps_greater_version_installed
<add> f.instance_variable_set(:@tap, CoreTap.instance)
<add> setup_tab_for_prefix(outdated_prefix, "homebrew/core")
<add> setup_tab_for_prefix(greater_prefix, "user/repo")
<add>
<add> assert_predicate f.outdated_versions, :empty?
<add>
<add> setup_tab_for_prefix(greater_prefix, "homebrew/core")
<add>
<add> assert_predicate f.outdated_versions, :empty?
<add> end
<add>
<add> def test_mixed_taps_outdated_version_installed
<add> f.instance_variable_set(:@tap, CoreTap.instance)
<add>
<add> extra_outdated_prefix = HOMEBREW_CELLAR/"#{f.name}/1.0"
<add>
<add> setup_tab_for_prefix(outdated_prefix)
<add> setup_tab_for_prefix(extra_outdated_prefix, "homebrew/core")
<add>
<add> refute_predicate f.outdated_versions, :empty?
<add>
<add> setup_tab_for_prefix(outdated_prefix, "user/repo")
<add>
<add> refute_predicate f.outdated_versions, :empty?
<add> end
<add>
<add> def test_same_version_tap_installed
<add> f.instance_variable_set(:@tap, CoreTap.instance)
<add> setup_tab_for_prefix(same_prefix, "homebrew/core")
<add>
<add> assert_predicate f.outdated_versions, :empty?
<add>
<add> setup_tab_for_prefix(same_prefix, "user/repo")
<add>
<add> assert_predicate f.outdated_versions, :empty?
<add> end
<add>end | 1 |
Ruby | Ruby | pass strings to factory | a6777838d44c66fa6c5051af3b43cd6e596a502b | <ide><path>Library/Homebrew/formula.rb
<ide> class << self
<ide> end
<ide>
<ide> def self.installed
<del> HOMEBREW_CELLAR.children.map{ |rack| factory(rack.basename) rescue nil }.compact
<add> # `rescue nil` is here to skip kegs with no corresponding formulae
<add> HOMEBREW_CELLAR.children.map{ |rack| factory(rack.basename.to_s) rescue nil }.compact
<ide> end
<ide>
<ide> def self.aliases | 1 |
Go | Go | change integration test to use variable | ce1059973a4a46acc272a8c0fea521c96e628ba7 | <ide><path>integration-cli/docker_cli_network_unix_test.go
<ide> func (s *DockerNetworkSuite) TestDockerNetworkHostModeUngracefulDaemonRestart(c
<ide> c.Assert(err, checker.IsNil, check.Commentf(out))
<ide>
<ide> // verfiy container has finished starting before killing daemon
<del> err = s.d.waitRun(fmt.Sprintf("hostc-%d", i))
<add> err = s.d.waitRun(cName)
<ide> c.Assert(err, checker.IsNil)
<ide> }
<ide> | 1 |
PHP | PHP | add nullcontext class | 15ac7ff83aeefde80468d5b7060dbca6fcc293e9 | <ide><path>src/View/Form/NullContext.php
<add><?php
<add>/**
<add> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<add> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * For full copyright and license information, please see the LICENSE.txt
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> * @link http://cakephp.org CakePHP(tm) Project
<add> * @since CakePHP(tm) v 3.0
<add> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<add> */
<add>namespace Cake\View\Form;
<add>
<add>use Cake\Network\Request;
<add>
<add>/**
<add> * Provides a context provider that does nothing.
<add> *
<add> * This context provider simply fulfils the interface requirements
<add> * that FormHelper has and allows access to the request data.
<add> */
<add>class NullContext {
<add>
<add>/**
<add> * The request object.
<add> *
<add> * @var Cake\Network\Request
<add> */
<add> protected $_request;
<add>
<add>/**
<add> * Constructor.
<add> *
<add> * @param Cake\Network\Request
<add> * @param array
<add> */
<add> public function __construct(Request $request, array $context) {
<add> $this->_request = $request;
<add> }
<add>
<add>/**
<add> * Get the current value for a given field.
<add> *
<add> * This method will coalesce the current request data and the 'defaults'
<add> * array.
<add> *
<add> * @param string $field A dot separated path to the field a value
<add> * is needed for.
<add> * @return mixed
<add> */
<add> public function val($field) {
<add> return $this->_request->data($field);
<add> }
<add>
<add>/**
<add> * Check if a given field is 'required'.
<add> *
<add> * In this context class, this is simply defined by the 'required' array.
<add> *
<add> * @param string $field A dot separated path to check required-ness for.
<add> * @return boolean
<add> */
<add> public function isRequired($field) {
<add> return false;
<add> }
<add>
<add>/**
<add> * Get the abstract field type for a given field name.
<add> *
<add> * @param string $field A dot separated path to get a schema type for.
<add> * @return null|string An abstract data type or null.
<add> * @see Cake\Database\Type
<add> */
<add> public function type($field) {
<add> return null;
<add> }
<add>
<add>/**
<add> * Get an associative array of other attributes for a field name.
<add> *
<add> * @param string $field A dot separated path to get additional data on.
<add> * @return array An array of data describing the additional attributes on a field.
<add> */
<add> public function attributes($field) {
<add> return [];
<add> }
<add>
<add>/**
<add> * Check whether or not a field has an error attached to it
<add> *
<add> * @param string $field A dot separated path to check errors on.
<add> * @return boolean Returns true if the errors for the field are not empty.
<add> */
<add> public function hasError($field) {
<add> return false;
<add> }
<add>
<add>/**
<add> * Get the errors for a given field
<add> *
<add> * @param string $field A dot separated path to check errors on.
<add> * @return array An array of errors, an empty array will be returned when the
<add> * context has no errors.
<add> */
<add> public function error($field) {
<add> return [];
<add> }
<add>
<add>} | 1 |
Javascript | Javascript | remove deprecated code strings | 234adb8748aa4adbb510e9e5e8e006388b3b7d0b | <ide><path>packages/one-dark-ui/lib/main.js
<ide> module.exports = {
<ide> atom.config.observe(`${themeName}.tabCloseButton`, setTabCloseButton);
<ide> atom.config.observe(`${themeName}.hideDockButtons`, setHideDockButtons);
<ide> atom.config.observe(`${themeName}.stickyHeaders`, setStickyHeaders);
<del>
<del> // DEPRECATED: This can be removed at some point (added in Atom 1.17/1.18ish)
<del> // It removes `layoutMode`
<del> if (atom.config.get(`${themeName}.layoutMode`)) {
<del> atom.config.unset(`${themeName}.layoutMode`);
<del> }
<ide> },
<ide>
<ide> deactivate() {
<ide><path>packages/one-light-ui/lib/main.js
<ide> module.exports = {
<ide> atom.config.observe(`${themeName}.tabCloseButton`, setTabCloseButton);
<ide> atom.config.observe(`${themeName}.hideDockButtons`, setHideDockButtons);
<ide> atom.config.observe(`${themeName}.stickyHeaders`, setStickyHeaders);
<del>
<del> // DEPRECATED: This can be removed at some point (added in Atom 1.17/1.18ish)
<del> // It removes `layoutMode`
<del> if (atom.config.get(`${themeName}.layoutMode`)) {
<del> atom.config.unset(`${themeName}.layoutMode`);
<del> }
<ide> },
<ide>
<ide> deactivate() {
<ide><path>src/main-process/atom-application.js
<ide> module.exports = class AtomApplication extends EventEmitter {
<ide>
<ide> global.atomApplication = this;
<ide>
<del> // DEPRECATED: This can be removed at some point (added in 1.13)
<del> // It converts `useCustomTitleBar: true` to `titleBar: "custom"`
<del> if (
<del> process.platform === 'darwin' &&
<del> this.config.get('core.useCustomTitleBar')
<del> ) {
<del> this.config.unset('core.useCustomTitleBar');
<del> this.config.set('core.titleBar', 'custom');
<del> }
<del>
<ide> this.applicationMenu = new ApplicationMenu(
<ide> this.version,
<ide> this.autoUpdateManager
<ide><path>vendor/jasmine.js
<ide> jasmine.Matchers = function(env, actual, spec, opt_isNot) {
<ide> this.reportWasCalled_ = false;
<ide> };
<ide>
<del>// todo: @deprecated as of Jasmine 0.11, remove soon [xw]
<del>jasmine.Matchers.pp = function(str) {
<del> throw new Error("jasmine.Matchers.pp() is no longer supported, please use jasmine.pp() instead!");
<del>};
<del>
<del>// todo: @deprecated Deprecated as of Jasmine 0.10. Rewrite your custom matchers to return true or false. [xw]
<del>jasmine.Matchers.prototype.report = function(result, failing_message, details) {
<del> throw new Error("As of jasmine 0.11, custom matchers must be implemented differently -- please see jasmine docs");
<del>};
<del>
<ide> jasmine.Matchers.wrapInto_ = function(prototype, matchersClass) {
<ide> for (var methodName in prototype) {
<ide> if (methodName == 'report') continue; | 4 |
Go | Go | improve warnings when image digest pinning fails | 44855dff42a4adbf73a4d286e27963da2112f563 | <ide><path>daemon/cluster/services.go
<ide> func (c *Cluster) CreateService(s types.ServiceSpec, encodedAuth string) (*apity
<ide> digestImage, err := c.imageWithDigestString(ctx, ctnr.Image, authConfig)
<ide> if err != nil {
<ide> logrus.Warnf("unable to pin image %s to digest: %s", ctnr.Image, err.Error())
<del> resp.Warnings = append(resp.Warnings, fmt.Sprintf("unable to pin image %s to digest: %s", ctnr.Image, err.Error()))
<add> // warning in the client response should be concise
<add> resp.Warnings = append(resp.Warnings, digestWarning(ctnr.Image))
<ide> } else if ctnr.Image != digestImage {
<ide> logrus.Debugf("pinning image %s by digest: %s", ctnr.Image, digestImage)
<ide> ctnr.Image = digestImage
<ide> func (c *Cluster) UpdateService(serviceIDOrName string, version uint64, spec typ
<ide> digestImage, err := c.imageWithDigestString(ctx, newCtnr.Image, authConfig)
<ide> if err != nil {
<ide> logrus.Warnf("unable to pin image %s to digest: %s", newCtnr.Image, err.Error())
<del> resp.Warnings = append(resp.Warnings, fmt.Sprintf("unable to pin image %s to digest: %s", newCtnr.Image, err.Error()))
<add> // warning in the client response should be concise
<add> resp.Warnings = append(resp.Warnings, digestWarning(newCtnr.Image))
<ide> } else if newCtnr.Image != digestImage {
<ide> logrus.Debugf("pinning image %s by digest: %s", newCtnr.Image, digestImage)
<ide> newCtnr.Image = digestImage
<ide> func (c *Cluster) imageWithDigestString(ctx context.Context, image string, authC
<ide> namedRef, ok := ref.(reference.Named)
<ide> if !ok {
<ide> if _, ok := ref.(reference.Digested); ok {
<del> return "", errors.New("image reference is an image ID")
<add> return image, nil
<ide> }
<ide> return "", errors.Errorf("unknown image reference format: %s", image)
<ide> }
<ide> func (c *Cluster) imageWithDigestString(ctx context.Context, image string, authC
<ide> // reference already contains a digest, so just return it
<ide> return reference.FamiliarString(ref), nil
<ide> }
<add>
<add>// digestWarning constructs a formatted warning string
<add>// using the image name that could not be pinned by digest. The
<add>// formatting is hardcoded, but could me made smarter in the future
<add>func digestWarning(image string) string {
<add> return fmt.Sprintf("image %s could not be accessed on a registry to record\nits digest. Each node will access %s independently,\npossibly leading to different nodes running different\nversions of the image.\n", image, image)
<add>} | 1 |
Javascript | Javascript | fix the openext call | d9b39323cf01273e240cccbf0dab024416856e55 | <ide><path>src/git-repository-async.js
<ide> export default class GitRepositoryAsync {
<ide> this.emitter = new Emitter()
<ide> this.subscriptions = new CompositeDisposable()
<ide> this.pathStatusCache = {}
<del> this.repoPromise = Git.Repository.openExt(_path)
<add> this.repoPromise = Git.Repository.openExt(_path, 0, '')
<ide> this.isCaseInsensitive = fs.isCaseInsensitive()
<ide> this.upstreamByPath = {}
<ide> | 1 |
PHP | PHP | add greeting option to simplemessage notification | cef70172b02f20b38281b3360069a951df2baedc | <ide><path>src/Illuminate/Notifications/Messages/SimpleMessage.php
<ide> class SimpleMessage
<ide> */
<ide> public $subject;
<ide>
<add> /**
<add> * Greeting at the beginning of the notification.
<add> * If null, a greeting depending on the level will be displayed.
<add> *
<add> * @var string|null
<add> */
<add> public $greeting = null;
<add>
<ide> /**
<ide> * The "intro" lines of the notification.
<ide> *
<ide> public function subject($subject)
<ide> return $this;
<ide> }
<ide>
<add> /**
<add> * Set the greeting of the notification.
<add> *
<add> * @param string $greeting
<add> * @return $this
<add> */
<add> public function greeting($greeting)
<add> {
<add> $this->greeting = $greeting;
<add>
<add> return $this;
<add> }
<add>
<ide> /**
<ide> * Add a line of text to the notification.
<ide> *
<ide> public function toArray()
<ide> return [
<ide> 'level' => $this->level,
<ide> 'subject' => $this->subject,
<add> 'greeting' => $this->greeting,
<ide> 'introLines' => $this->introLines,
<ide> 'outroLines' => $this->outroLines,
<ide> 'actionText' => $this->actionText,
<ide><path>src/Illuminate/Notifications/resources/views/email-plain.blade.php
<del>{{ $level == 'error' ? 'Whoops!' : 'Hello!' }}
<add>{{ ( $greeting !== null ) ? $greeting : ($level == 'error' ? 'Whoops!' : 'Hello!') }}
<ide>
<ide> <?php
<ide>
<ide><path>src/Illuminate/Notifications/resources/views/email.blade.php
<ide> <td style="{{ $fontFamily }} {{ $style['email-body_cell'] }}">
<ide> <!-- Greeting -->
<ide> <h1 style="{{ $style['header-1'] }}">
<del> @if ($level == 'error')
<del> Whoops!
<add> @if ($greeting !== null)
<add> {{ $greeting }}
<ide> @else
<del> Hello!
<add> @if ($level == 'error')
<add> Whoops!
<add> @else
<add> Hello!
<add> @endif
<ide> @endif
<ide> </h1>
<ide> | 3 |
Java | Java | increase sleep time in scheduledataitests | 9a6ec1b4b5a2e39841b44b466b1e9986700d4325 | <ide><path>src/test/java/org/springframework/scheduling/annotation/ScheduledAndTransactionalAnnotationIntegrationTests.java
<ide> public void succeedsWhenSubclassProxyAndScheduledMethodNotPresentOnInterface() t
<ide> ctx.register(Config.class, SubclassProxyTxConfig.class, RepoConfigA.class);
<ide> ctx.refresh();
<ide>
<del> Thread.sleep(10); // allow @Scheduled method to be called several times
<add> Thread.sleep(50); // allow @Scheduled method to be called several times
<ide>
<ide> MyRepository repository = ctx.getBean(MyRepository.class);
<ide> CallCountingTransactionManager txManager = ctx.getBean(CallCountingTransactionManager.class);
<ide> public void succeedsWhenJdkProxyAndScheduledMethodIsPresentOnInterface() throws
<ide> ctx.register(Config.class, JdkProxyTxConfig.class, RepoConfigB.class);
<ide> ctx.refresh();
<ide>
<del> Thread.sleep(30); // allow @Scheduled method to be called several times
<add> Thread.sleep(50); // allow @Scheduled method to be called several times
<ide>
<ide> MyRepositoryWithScheduledMethod repository = ctx.getBean(MyRepositoryWithScheduledMethod.class);
<ide> CallCountingTransactionManager txManager = ctx.getBean(CallCountingTransactionManager.class); | 1 |
Python | Python | add code for keras nli example | de32b6e5b8a090727c7238eedb1ac29c0a4bf521 | <ide><path>examples/nli/__main__.py
<add>from __future__ import division, unicode_literals, print_function
<add>import spacy
<add>
<add>import plac
<add>from pathlib import Path
<add>
<add>from spacy_hook import get_embeddings, get_word_ids
<add>from spacy_hook import create_similarity_pipeline
<add>
<add>
<add>def train(model_dir, train_loc, dev_loc, shape, settings):
<add> print("Loading spaCy")
<add> nlp = spacy.load('en', tagger=False, parser=False, entity=False, matcher=False)
<add> print("Compiling network")
<add> model = build_model(get_embeddings(nlp.vocab), shape, settings)
<add> print("Processing texts...")
<add> train_X = get_features(list(nlp.pipe(train_texts)))
<add> dev_X = get_features(list(nlp.pipe(dev_texts)))
<add>
<add> model.fit(
<add> train_X,
<add> train_labels,
<add> validation_data=(dev_X, dev_labels),
<add> nb_epoch=settings['nr_epoch'],
<add> batch_size=settings['batch_size'])
<add>
<add>
<add>def evaluate(model_dir, dev_loc):
<add> nlp = spacy.load('en', path=model_dir,
<add> tagger=False, parser=False, entity=False, matcher=False,
<add> create_pipeline=create_similarity_pipeline)
<add> n = 0
<add> correct = 0
<add> for (text1, text2), label in zip(dev_texts, dev_labels):
<add> doc1 = nlp(text1)
<add> doc2 = nlp(text2)
<add> sim = doc1.similarity(doc2)
<add> if bool(sim >= 0.5) == label:
<add> correct += 1
<add> n += 1
<add> return correct, total
<add>
<add>
<add>def demo(model_dir):
<add> nlp = spacy.load('en', path=model_dir,
<add> tagger=False, parser=False, entity=False, matcher=False,
<add> create_pipeline=create_similarity_pipeline)
<add> doc1 = nlp(u'Worst fries ever! Greasy and horrible...')
<add> doc2 = nlp(u'The milkshakes are good. The fries are bad.')
<add> print('doc1.similarity(doc2)', doc1.similarity(doc2))
<add> sent1a, sent1b = doc1.sents
<add> print('sent1a.similarity(sent1b)', sent1a.similarity(sent1b))
<add> print('sent1a.similarity(doc2)', sent1a.similarity(doc2))
<add> print('sent1b.similarity(doc2)', sent1b.similarity(doc2))
<add>
<add>
<add>LABELS = {'entailment': 0, 'contradiction': 1, 'neutral': 2}
<add>def read_snli(loc):
<add> with open(loc) as file_:
<add> for line in file_:
<add> eg = json.loads(line)
<add> label = eg['gold_label']
<add> if label == '-':
<add> continue
<add> text1 = eg['sentence1']
<add> text2 = eg['sentence2']
<add> yield text1, text2, LABELS[label]
<add>
<add>
<add>@plac.annotations(
<add> mode=("Mode to execute", "positional", None, str, ["train", "evaluate", "demo"]),
<add> model_dir=("Path to spaCy model directory", "positional", None, Path),
<add> train_loc=("Path to training data", "positional", None, Path),
<add> dev_loc=("Path to development data", "positional", None, Path),
<add> max_length=("Length to truncate sentences", "option", "L", int),
<add> nr_hidden=("Number of hidden units", "option", "H", int),
<add> dropout=("Dropout level", "option", "d", float),
<add> learn_rate=("Learning rate", "option", "e", float),
<add> batch_size=("Batch size for neural network training", "option", "b", float),
<add> nr_epoch=("Number of training epochs", "option", "i", float)
<add>)
<add>def main(mode, model_dir, train_loc, dev_loc,
<add> max_length=100,
<add> nr_hidden=100,
<add> dropout=0.2,
<add> learn_rate=0.001,
<add> batch_size=100,
<add> nr_epoch=5):
<add> shape = (max_length, nr_hidden, 3)
<add> settings = {
<add> 'lr': learn_rate,
<add> 'dropout': dropout,
<add> 'batch_size': batch_size,
<add> 'nr_epoch': nr_epoch
<add> }
<add> if mode == 'train':
<add> train(model_dir, train_loc, dev_loc, shape, settings)
<add> elif mode == 'evaluate':
<add> evaluate(model_dir, dev_loc)
<add> else:
<add> demo(model_dir)
<add>
<add>
<add>if __name__ == '__main__':
<add> plac.call(main)
<ide><path>examples/nli/keras_decomposable_attention.py
<add># Semantic similarity with decomposable attention (using spaCy and Keras)
<add># Practical state-of-the-art text similarity with spaCy and Keras
<add>import numpy
<add>
<add>from keras.layers import InputSpec, Layer, Input, Dense, merge
<add>from keras.layers import Activation, Dropout, Embedding, TimeDistributed
<add>import keras.backend as K
<add>import theano.tensor as T
<add>from keras.models import Sequential, Model, model_from_json
<add>from keras.regularizers import l2
<add>from keras.optimizers import Adam
<add>from keras.layers.normalization import BatchNormalization
<add>
<add>
<add>def build_model(vectors, shape, settings):
<add> '''Compile the model.'''
<add> max_length, nr_hidden, nr_class = shape
<add> # Declare inputs.
<add> ids1 = Input(shape=(max_length,), dtype='int32', name='words1')
<add> ids2 = Input(shape=(max_length,), dtype='int32', name='words2')
<add>
<add> # Construct operations, which we'll chain together.
<add> embed = _StaticEmbedding(vectors, max_length, nr_hidden)
<add> attend = _Attention(max_length, nr_hidden)
<add> align = _SoftAlignment(max_length, nr_hidden)
<add> compare = _Comparison(max_length, nr_hidden)
<add> entail = _Entailment(nr_hidden, nr_class)
<add>
<add> # Declare the model as a computational graph.
<add> sent1 = embed(ids1) # Shape: (i, n)
<add> sent2 = embed(ids2) # Shape: (j, n)
<add>
<add> attention = attend(sent1, sent2) # Shape: (i, j)
<add>
<add> align1 = align(sent2, attention)
<add> align2 = align(sent1, attention, transpose=True)
<add>
<add> feats1 = compare(sent1, align1)
<add> feats2 = compare(sent2, align2)
<add>
<add> scores = entail(feats1, feats2)
<add>
<add> # Now that we have the input/output, we can construct the Model object...
<add> model = Model(input=[ids1, ids2], output=[scores])
<add>
<add> # ...Compile it...
<add> model.compile(
<add> optimizer=Adam(lr=settings['lr']),
<add> loss='categorical_crossentropy',
<add> metrics=['accuracy'])
<add> # ...And return it for training.
<add> return model
<add>
<add>
<add>class _StaticEmbedding(object):
<add> def __init__(self, vectors, max_length, nr_out):
<add> self.embed = Embedding(
<add> vectors.shape[0],
<add> vectors.shape[1],
<add> input_length=max_length,
<add> weights=[vectors],
<add> name='embed',
<add> trainable=False,
<add> dropout=0.0)
<add>
<add> self.project = TimeDistributed(
<add> Dense(
<add> nr_out,
<add> activation=None,
<add> bias=False,
<add> name='project'))
<add>
<add> def __call__(self, sentence):
<add> return self.project(self.embed(sentence))
<add>
<add>
<add>class _Attention(object):
<add> def __init__(self, max_length, nr_hidden, dropout=0.0, L2=1e-4, activation='relu'):
<add> self.max_length = max_length
<add> self.model = Sequential()
<add> self.model.add(
<add> Dense(nr_hidden, name='attend1',
<add> init='he_normal', W_regularizer=l2(L2),
<add> input_shape=(nr_hidden,), activation='relu'))
<add> self.model.add(Dropout(dropout))
<add> self.model.add(Dense(nr_hidden, name='attend2',
<add> init='he_normal', W_regularizer=l2(L2), activation='relu'))
<add> self.model = TimeDistributed(self.model)
<add>
<add> def __call__(self, sent1, sent2):
<add> def _outer((A, B)):
<add> att_ji = T.batched_dot(B, A.dimshuffle((0, 2, 1)))
<add> return att_ji.dimshuffle((0, 2, 1))
<add>
<add> return merge(
<add> [self.model(sent1), self.model(sent2)],
<add> mode=_outer,
<add> output_shape=(self.max_length, self.max_length))
<add>
<add>
<add>class _SoftAlignment(object):
<add> def __init__(self, max_length, nr_hidden):
<add> self.max_length = max_length
<add> self.nr_hidden = nr_hidden
<add>
<add> def __call__(self, sentence, attention, transpose=False):
<add> def _normalize_attention((att, mat)):
<add> if transpose:
<add> att = att.dimshuffle((0, 2, 1))
<add> # 3d softmax
<add> e = K.exp(att - K.max(att, axis=-1, keepdims=True))
<add> s = K.sum(e, axis=-1, keepdims=True)
<add> sm_att = e / s
<add> return T.batched_dot(sm_att, mat)
<add> return merge([attention, sentence], mode=_normalize_attention,
<add> output_shape=(self.max_length, self.nr_hidden)) # Shape: (i, n)
<add>
<add>
<add>class _Comparison(object):
<add> def __init__(self, words, nr_hidden, L2=1e-6, dropout=0.2):
<add> self.words = words
<add> self.model = Sequential()
<add> self.model.add(Dense(nr_hidden, name='compare1',
<add> init='he_normal', W_regularizer=l2(L2),
<add> input_shape=(nr_hidden*2,)))
<add> self.model.add(Activation('relu'))
<add> self.model.add(Dropout(dropout))
<add> self.model.add(Dense(nr_hidden, name='compare2',
<add> W_regularizer=l2(L2), init='he_normal'))
<add> self.model.add(Activation('relu'))
<add> self.model.add(Dropout(dropout))
<add> self.model = TimeDistributed(self.model)
<add>
<add> def __call__(self, sent, align, **kwargs):
<add> result = self.model(merge([sent, align], mode='concat')) # Shape: (i, n)
<add> result = _GlobalSumPooling1D()(result, mask=self.words)
<add> return result
<add>
<add>
<add>class _Entailment(object):
<add> def __init__(self, nr_hidden, nr_out, dropout=0.2, L2=1e-4):
<add> self.model = Sequential()
<add> self.model.add(Dense(nr_hidden, name='entail1',
<add> init='he_normal', W_regularizer=l2(L2),
<add> input_shape=(nr_hidden*2,)))
<add> self.model.add(Activation('relu'))
<add> self.model.add(Dropout(dropout))
<add> self.model.add(Dense(nr_out, name='entail_out', activation='softmax',
<add> W_regularizer=l2(L2), init='zero'))
<add>
<add> def __call__(self, feats1, feats2):
<add> features = merge([feats1, feats2], mode='concat')
<add> return self.model(features)
<add>
<add>
<add>class _GlobalSumPooling1D(Layer):
<add> '''Global sum pooling operation for temporal data.
<add>
<add> # Input shape
<add> 3D tensor with shape: `(samples, steps, features)`.
<add>
<add> # Output shape
<add> 2D tensor with shape: `(samples, features)`.
<add> '''
<add> def __init__(self, **kwargs):
<add> super(_GlobalSumPooling1D, self).__init__(**kwargs)
<add> self.input_spec = [InputSpec(ndim=3)]
<add>
<add> def get_output_shape_for(self, input_shape):
<add> return (input_shape[0], input_shape[2])
<add>
<add> def call(self, x, mask=None):
<add> if mask is not None:
<add> return K.sum(x * T.clip(mask, 0, 1), axis=1)
<add> else:
<add> return K.sum(x, axis=1)
<add>
<add>
<add>def test_build_model():
<add> vectors = numpy.ndarray((100, 8), dtype='float32')
<add> shape = (10, 16, 3)
<add> settings = {'lr': 0.001, 'dropout': 0.2}
<add> model = build_model(vectors, shape, settings)
<add>
<add>
<add>def test_fit_model():
<add> def _generate_X(nr_example, length, nr_vector):
<add> X1 = numpy.ndarray((nr_example, length), dtype='int32')
<add> X1 *= X1 < nr_vector
<add> X1 *= 0 <= X1
<add> X2 = numpy.ndarray((nr_example, length), dtype='int32')
<add> X2 *= X2 < nr_vector
<add> X2 *= 0 <= X2
<add> return [X1, X2]
<add> def _generate_Y(nr_example, nr_class):
<add> ys = numpy.zeros((nr_example, nr_class), dtype='int32')
<add> for i in range(nr_example):
<add> ys[i, i % nr_class] = 1
<add> return ys
<add>
<add> vectors = numpy.ndarray((100, 8), dtype='float32')
<add> shape = (10, 16, 3)
<add> settings = {'lr': 0.001, 'dropout': 0.2}
<add> model = build_model(vectors, shape, settings)
<add>
<add> train_X = _generate_X(20, shape[0], vectors.shape[1])
<add> train_Y = _generate_Y(20, shape[2])
<add> dev_X = _generate_X(15, shape[0], vectors.shape[1])
<add> dev_Y = _generate_Y(15, shape[2])
<add>
<add> model.fit(train_X, train_Y, validation_data=(dev_X, dev_Y), nb_epoch=5,
<add> batch_size=4)
<add>
<add>
<add>
<add>
<add>__all__ = [build_model]
<ide><path>examples/nli/spacy_hook.py
<add>from keras.models import model_from_json
<add>
<add>
<add>class KerasSimilarityShim(object):
<add> @classmethod
<add> def load(cls, path, nlp, get_features=None):
<add> if get_features is None:
<add> get_features = doc2ids
<add> with (path / 'config.json').open() as file_:
<add> config = json.load(file_)
<add> model = model_from_json(config['model'])
<add> with (path / 'model').open('rb') as file_:
<add> weights = pickle.load(file_)
<add> embeddings = get_embeddings(nlp.vocab)
<add> model.set_weights([embeddings] + weights)
<add> return cls(model, get_features=get_features)
<add>
<add> def __init__(self, model, get_features=None):
<add> self.model = model
<add> self.get_features = get_features
<add>
<add> def __call__(self, doc):
<add> doc.user_hooks['similarity'] = self.predict
<add> doc.user_span_hooks['similarity'] = self.predict
<add>
<add> def predict(self, doc1, doc2):
<add> x1 = self.get_features(doc1)
<add> x2 = self.get_features(doc2)
<add> scores = self.model.predict([x1, x2])
<add> return scores[0]
<add>
<add>
<add>def get_embeddings(cls, vocab):
<add> max_rank = max(lex.rank+1 for lex in vocab if lex.has_vector)
<add> vectors = numpy.ndarray((max_rank+1, vocab.vectors_length), dtype='float32')
<add> for lex in vocab:
<add> if lex.has_vector:
<add> vectors[lex.rank + 1] = lex.vector
<add> return vectors
<add>
<add>
<add>def get_word_ids(docs, max_length=100):
<add> Xs = numpy.zeros((len(docs), max_length), dtype='int32')
<add> for i, doc in enumerate(docs):
<add> j = 0
<add> for token in doc:
<add> if token.has_vector and not token.is_punct and not token.is_space:
<add> Xs[i, j] = token.rank + 1
<add> j += 1
<add> if j >= max_length:
<add> break
<add> return Xs
<add>
<add>
<add>def create_similarity_pipeline(nlp):
<add> return [SimilarityModel.load(
<add> nlp.path / 'similarity',
<add> nlp,
<add> feature_extracter=get_features)]
<add>
<add>
<add> | 3 |
Javascript | Javascript | isolate cache leaks from subsequent tests | 04ae4e5b47fbc015b5de3dd660bce7b1904e2268 | <ide><path>test/helpers/testabilityPatch.js
<ide> afterEach(function() {
<ide> } else {
<ide> dump('LEAK', key, angular.toJson(value));
<ide> }
<add> delete expando.data[key];
<ide> });
<ide> });
<ide> if (count) { | 1 |
Text | Text | add version meta for ssl_cert_dir/file | d2de2ad846d80503c524e138c97e2f4078ab926e | <ide><path>doc/api/cli.md
<ide> If the [`--openssl-config`][] command line option is used, the environment
<ide> variable is ignored.
<ide>
<ide> ### `SSL_CERT_DIR=dir`
<add><!-- YAML
<add>added: REPLACEME
<add>-->
<ide>
<ide> If `--use-openssl-ca` is enabled, this overrides and sets OpenSSL's directory
<ide> containing trusted certificates.
<ide> evironment variable will be inherited by any child processes, and if they use
<ide> OpenSSL, it may cause them to trust the same CAs as node.
<ide>
<ide> ### `SSL_CERT_FILE=file`
<add><!-- YAML
<add>added: REPLACEME
<add>-->
<ide>
<ide> If `--use-openssl-ca` is enabled, this overrides and sets OpenSSL's file
<ide> containing trusted certificates. | 1 |
Javascript | Javascript | make camera optional | fbf6a820de0a9a6407d471b6634e336a7845b9a2 | <ide><path>threejs/lessons/resources/threejs-lesson-utils.js
<ide> window.threejsLessonUtils = {
<ide> const aspect = 1;
<ide> const zNear = 0.1;
<ide> const zFar = 50;
<del> const camera = new THREE.PerspectiveCamera(targetFOVDeg, aspect, zNear, zFar);
<add> let camera = new THREE.PerspectiveCamera(targetFOVDeg, aspect, zNear, zFar);
<ide> camera.position.z = 15;
<ide> scene.add(camera);
<ide>
<ide> window.threejsLessonUtils = {
<ide> if (info.resize) {
<ide> resizeFunctions.push(info.resize);
<ide> }
<add> if (info.camera) {
<add> camera = info.camera;
<add> renderInfo.camera = camera;
<add> }
<ide>
<ide> Object.assign(settings, info);
<ide> targetFOVDeg = camera.fov; | 1 |
Text | Text | add more information to head tag in 38 line | e279dbd9f4b42d1d6b667dd47ce43082f9d01454 | <ide><path>guide/english/html/index.md
<ide> In HTML tags come in pairs, as seen above. The first tag in a pair is called the
<ide>
<ide> html: The root element of an HTML page
<ide>
<del>head: This element contains meta information about the document
<add>head: The element contains meta information about the document and non-visual elements that help make the page work
<ide>
<ide> title: This element specifies a title for the document
<ide> | 1 |
PHP | PHP | remove empty foreign key test | 87d8dd706e727048157f9f708cd23c93b27e5aad | <ide><path>lib/Cake/Database/Schema/Table.php
<ide> public function column($name) {
<ide> * - `type` The type of index being added.
<ide> * - `columns` The columns in the index.
<ide> *
<add> * @TODO implement foreign keys.
<ide> * @param string $name The name of the index.
<ide> * @param array $attrs The attributes for the index.
<ide> * @return Table $this
<ide><path>lib/Cake/Test/TestCase/Database/Schema/TableTest.php
<ide> public function testAddIndexTypes() {
<ide> ]);
<ide> }
<ide>
<del>/**
<del> * Test adding foreign keys.
<del> *
<del> * @return void
<del> */
<del> public function testAddIndexForeign() {
<del> }
<del>
<ide> } | 2 |
Java | Java | add extra logging in the bridge exception handling | 4ad852c1376e268456cd6dcd0d240dd75d780df4 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/ReactContext.java
<ide> import android.os.Bundle;
<ide> import android.view.LayoutInflater;
<ide> import androidx.annotation.Nullable;
<add>import com.facebook.common.logging.FLog;
<ide> import com.facebook.infer.annotation.Assertions;
<ide> import com.facebook.infer.annotation.ThreadConfined;
<ide> import com.facebook.react.bridge.queue.MessageQueueThread;
<ide> import com.facebook.react.bridge.queue.ReactQueueConfiguration;
<ide> import com.facebook.react.common.LifecycleState;
<add>import com.facebook.react.common.ReactConstants;
<ide> import com.facebook.react.config.ReactFeatureFlags;
<ide> import java.lang.ref.WeakReference;
<ide> import java.util.concurrent.CopyOnWriteArraySet;
<ide> public void runOnJSQueueThread(Runnable runnable) {
<ide> * otherwise.
<ide> */
<ide> public void handleException(Exception e) {
<del> if (mCatalystInstance != null
<del> && !mCatalystInstance.isDestroyed()
<del> && mNativeModuleCallExceptionHandler != null) {
<add> boolean catalystInstanceVariableExists = mCatalystInstance != null;
<add> boolean isCatalystInstanceAlive =
<add> catalystInstanceVariableExists && !mCatalystInstance.isDestroyed();
<add> boolean hasExceptionHandler = mNativeModuleCallExceptionHandler != null;
<add>
<add> if (isCatalystInstanceAlive && hasExceptionHandler) {
<ide> mNativeModuleCallExceptionHandler.handleException(e);
<ide> } else {
<add> FLog.e(
<add> ReactConstants.TAG,
<add> "Unable to handle Exception - catalystInstanceVariableExists: "
<add> + catalystInstanceVariableExists
<add> + " - isCatalystInstanceAlive: "
<add> + !isCatalystInstanceAlive
<add> + " - hasExceptionHandler: "
<add> + hasExceptionHandler,
<add> e);
<ide> throw new RuntimeException(e);
<ide> }
<ide> } | 1 |
Python | Python | update tf backend | 1ccad186fd950b77dab771686200fc4a23bc0c2c | <ide><path>keras/backend/tensorflow_backend.py
<ide> def switch(condition, then_expression, else_expression):
<ide> then_expression: TensorFlow operation.
<ide> else_expression: TensorFlow operation.
<ide> """
<del> x_shape = copy.copy(then_expression.get_shape())
<ide> if condition.dtype != tf.bool:
<ide> condition = tf.cast(condition, 'bool')
<add> if not callable(then_expression):
<add> def then_expression_fn():
<add> return then_expression
<add> else:
<add> then_expression_fn = then_expression
<add> if not callable(else_expression):
<add> def else_expression_fn():
<add> return else_expression
<add> else:
<add> else_expression_fn = else_expression
<ide> x = _cond(condition,
<del> lambda: then_expression,
<del> lambda: else_expression)
<del> x.set_shape(x_shape)
<add> then_expression_fn,
<add> else_expression_fn)
<ide> return x
<ide>
<ide>
<ide> def categorical_crossentropy(output, target, from_logits=False):
<ide> return - tf.reduce_sum(target * tf.log(output),
<ide> reduction_indices=len(output.get_shape()) - 1)
<ide> else:
<del> return tf.nn.softmax_cross_entropy_with_logits(output, target)
<add> try:
<add> return tf.nn.softmax_cross_entropy_with_logits(labels=target,
<add> logits=output)
<add> except TypeError:
<add> return tf.nn.softmax_cross_entropy_with_logits(output, target)
<ide>
<ide>
<ide> def sparse_categorical_crossentropy(output, target, from_logits=False):
<ide> def sparse_categorical_crossentropy(output, target, from_logits=False):
<ide> output = tf.log(output)
<ide>
<ide> output_shape = output.get_shape()
<del> res = tf.nn.sparse_softmax_cross_entropy_with_logits(
<del> tf.reshape(output, [-1, int(output_shape[-1])]),
<del> cast(flatten(target), 'int64'))
<add> targets = cast(flatten(target), 'int64')
<add> logits = tf.reshape(output, [-1, int(output_shape[-1])])
<add> try:
<add> res = tf.nn.sparse_softmax_cross_entropy_with_logits(
<add> labels=targets,
<add> logits=logits)
<add> except TypeError:
<add> res = tf.nn.sparse_softmax_cross_entropy_with_logits(
<add> logits, targets)
<ide> if len(output_shape) == 3:
<ide> # if our output includes timesteps we need to reshape
<ide> return tf.reshape(res, tf.shape(output)[:-1])
<ide> def binary_crossentropy(output, target, from_logits=False):
<ide> epsilon = _to_tensor(_EPSILON, output.dtype.base_dtype)
<ide> output = tf.clip_by_value(output, epsilon, 1 - epsilon)
<ide> output = tf.log(output / (1 - output))
<del> return tf.nn.sigmoid_cross_entropy_with_logits(output, target)
<add> try:
<add> return tf.nn.sigmoid_cross_entropy_with_logits(labels=target,
<add> logits=output)
<add> except TypeError:
<add> return tf.nn.sigmoid_cross_entropy_with_logits(output, target)
<ide>
<ide>
<ide> def sigmoid(x): | 1 |
Javascript | Javascript | fix conflicting real imports and type imports | cbcd459d19865175b17bdf60b76d3da838f62a47 | <ide><path>lib/Compilation.js
<ide> const { getRuntimeKey } = require("./util/runtime");
<ide> /** @typedef {import("./Dependency").ReferencedExport} ReferencedExport */
<ide> /** @typedef {import("./DependencyTemplate")} DependencyTemplate */
<ide> /** @typedef {import("./Entrypoint").EntryOptions} EntryOptions */
<del>/** @typedef {import("./Module")} Module */
<ide> /** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */
<ide> /** @typedef {import("./ModuleFactory")} ModuleFactory */
<ide> /** @typedef {import("./RuntimeModule")} RuntimeModule */
<ide> /** @typedef {import("./Template").RenderManifestEntry} RenderManifestEntry */
<ide> /** @typedef {import("./Template").RenderManifestOptions} RenderManifestOptions */
<del>/** @typedef {import("./WebpackError")} WebpackError */
<del>/** @typedef {import("./stats/StatsFactory")} StatsFactory */
<del>/** @typedef {import("./stats/StatsPrinter")} StatsPrinter */
<ide> /** @typedef {import("./util/Hash")} Hash */
<ide> /** @template T @typedef {import("./util/deprecation").FakeHook<T>} FakeHook<T> */
<ide> /** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
<ide><path>lib/ExportsInfo.js
<ide> class ExportInfo {
<ide>
<ide> /**
<ide> * get used name
<del> * @param {string=} fallbackName fallback name for used exports with no name
<add> * @param {string | undefined} fallbackName fallback name for used exports with no name
<ide> * @param {RuntimeSpec} runtime check usage for this runtime only
<ide> * @returns {string | false} used name
<ide> */
<ide><path>lib/FlagDependencyUsagePlugin.js
<ide> const { getEntryRuntime, mergeRuntimeOwned } = require("./util/runtime");
<ide> /** @typedef {import("./ChunkGroup")} ChunkGroup */
<ide> /** @typedef {import("./Compiler")} Compiler */
<ide> /** @typedef {import("./DependenciesBlock")} DependenciesBlock */
<del>/** @typedef {import("./Dependency")} Dependency */
<ide> /** @typedef {import("./Dependency").ReferencedExport} ReferencedExport */
<ide> /** @typedef {import("./ExportsInfo")} ExportsInfo */
<ide> /** @typedef {import("./Module")} Module */
<ide><path>lib/NormalModule.js
<ide> const makeSerializable = require("./util/makeSerializable");
<ide> /** @typedef {import("webpack-sources").Source} Source */
<ide> /** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */
<ide> /** @typedef {import("./ChunkGraph")} ChunkGraph */
<del>/** @typedef {import("./Compilation")} Compilation */
<ide> /** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */
<ide> /** @typedef {import("./DependencyTemplates")} DependencyTemplates */
<ide> /** @typedef {import("./Generator")} Generator */
<ide><path>lib/RuntimeTemplate.js
<ide> const { forEachRuntime, subtractRuntime } = require("./util/runtime");
<ide> /** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */
<ide> /** @typedef {import("./ChunkGraph")} ChunkGraph */
<ide> /** @typedef {import("./Dependency")} Dependency */
<del>/** @typedef {import("./InitFragment")} InitFragment */
<ide> /** @typedef {import("./Module")} Module */
<ide> /** @typedef {import("./ModuleGraph")} ModuleGraph */
<ide> /** @typedef {import("./RequestShortener")} RequestShortener */
<ide><path>lib/Template.js
<ide>
<ide> const { ConcatSource, PrefixSource } = require("webpack-sources");
<ide>
<del>/** @typedef {import("webpack-sources").ConcatSource} ConcatSource */
<ide> /** @typedef {import("webpack-sources").Source} Source */
<ide> /** @typedef {import("../declarations/WebpackOptions").Output} OutputOptions */
<ide> /** @typedef {import("./Chunk")} Chunk */
<ide><path>lib/Watching.js
<ide> const Stats = require("./Stats");
<ide> /** @typedef {import("../declarations/WebpackOptions").WatchOptions} WatchOptions */
<ide> /** @typedef {import("./Compilation")} Compilation */
<ide> /** @typedef {import("./Compiler")} Compiler */
<del>/** @typedef {import("./Stats")} Stats */
<ide>
<ide> /**
<ide> * @template T
<ide><path>lib/cache/ResolverCachePlugin.js
<ide> const makeSerializable = require("../util/makeSerializable");
<ide> /** @typedef {import("../Compiler")} Compiler */
<ide> /** @typedef {import("../FileSystemInfo")} FileSystemInfo */
<ide> /** @typedef {import("../FileSystemInfo").Snapshot} Snapshot */
<del>/** @template T @typedef {import("../util/LazySet")<T>} LazySet<T> */
<ide>
<ide> class CacheEntry {
<ide> constructor(result, snapshot) {
<ide><path>lib/dependencies/CommonJsExportRequireDependency.js
<ide> const ModuleDependency = require("./ModuleDependency");
<ide> const processExportInfo = require("./processExportInfo");
<ide>
<ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
<del>/** @typedef {import("../Dependency")} Dependency */
<ide> /** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */
<ide> /** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */
<ide> /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
<ide><path>lib/dependencies/HarmonyExportImportedSpecifierDependency.js
<ide> const processExportInfo = require("./processExportInfo");
<ide>
<ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
<ide> /** @typedef {import("../ChunkGraph")} ChunkGraph */
<del>/** @typedef {import("../Dependency")} Dependency */
<ide> /** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */
<ide> /** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */
<ide> /** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */
<ide><path>lib/dependencies/HarmonyImportDependency.js
<ide> const ModuleDependency = require("./ModuleDependency");
<ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
<ide> /** @typedef {import("webpack-sources").Source} Source */
<ide> /** @typedef {import("../ChunkGraph")} ChunkGraph */
<del>/** @typedef {import("../Dependency")} Dependency */
<ide> /** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */
<ide> /** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */
<ide> /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
<ide><path>lib/dependencies/ImportDependency.js
<ide> const ModuleDependency = require("./ModuleDependency");
<ide>
<ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
<ide> /** @typedef {import("../AsyncDependenciesBlock")} AsyncDependenciesBlock */
<del>/** @typedef {import("../Dependency")} Dependency */
<ide> /** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */
<ide> /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
<ide> /** @typedef {import("../ModuleGraph")} ModuleGraph */
<ide><path>lib/dependencies/ModuleDecoratorDependency.js
<ide> const NullDependency = require("./NullDependency");
<ide>
<ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
<ide> /** @typedef {import("../ChunkGraph")} ChunkGraph */
<del>/** @typedef {import("../Dependency")} Dependency */
<ide> /** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */
<ide> /** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */
<ide> /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
<ide><path>lib/dependencies/NullDependency.js
<ide> const DependencyTemplate = require("../DependencyTemplate");
<ide>
<ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
<ide> /** @typedef {import("../ChunkGraph")} ChunkGraph */
<del>/** @typedef {import("../Dependency")} Dependency */
<ide> /** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */
<ide> /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
<ide> /** @typedef {import("../ModuleGraph")} ModuleGraph */
<ide><path>lib/dependencies/RequireIncludeDependency.js
<ide> const makeSerializable = require("../util/makeSerializable");
<ide> const ModuleDependency = require("./ModuleDependency");
<ide>
<ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
<del>/** @typedef {import("../Dependency")} Dependency */
<ide> /** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */
<ide> /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
<ide> /** @typedef {import("../ModuleGraph")} ModuleGraph */
<ide><path>lib/dependencies/WorkerDependency.js
<ide> const ModuleDependency = require("./ModuleDependency");
<ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
<ide> /** @typedef {import("../AsyncDependenciesBlock")} AsyncDependenciesBlock */
<ide> /** @typedef {import("../ChunkGraph")} ChunkGraph */
<del>/** @typedef {import("../Dependency")} Dependency */
<ide> /** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */
<ide> /** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */
<ide> /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
<ide><path>lib/optimize/SplitChunksPlugin.js
<ide> const MinMaxSizeWarning = require("./MinMaxSizeWarning");
<ide> /** @typedef {import("../../declarations/WebpackOptions").OptimizationSplitChunksOptions} OptimizationSplitChunksOptions */
<ide> /** @typedef {import("../../declarations/WebpackOptions").OptimizationSplitChunksSizes} OptimizationSplitChunksSizes */
<ide> /** @typedef {import("../../declarations/WebpackOptions").Output} OutputOptions */
<del>/** @typedef {import("../Chunk")} Chunk */
<ide> /** @typedef {import("../ChunkGraph")} ChunkGraph */
<ide> /** @typedef {import("../ChunkGroup")} ChunkGroup */
<ide> /** @typedef {import("../Compilation").AssetInfo} AssetInfo */
<ide><path>lib/runtime/LoadScriptRuntimeModule.js
<ide> const Template = require("../Template");
<ide> const HelperRuntimeModule = require("./HelperRuntimeModule");
<ide>
<ide> /** @typedef {import("../Chunk")} Chunk */
<del>/** @typedef {import("../Compilation")} Compilation */
<ide> /** @typedef {import("../Compiler")} Compiler */
<ide>
<ide> /**
<ide><path>lib/wasm-async/AsyncWebAssemblyModulesPlugin.js
<ide> const memorize = require("../util/memorize");
<ide> /** @typedef {import("../Chunk")} Chunk */
<ide> /** @typedef {import("../ChunkGraph")} ChunkGraph */
<ide> /** @typedef {import("../CodeGenerationResults")} CodeGenerationResults */
<del>/** @typedef {import("../Compilation")} Compilation */
<ide> /** @typedef {import("../Compiler")} Compiler */
<ide> /** @typedef {import("../DependencyTemplates")} DependencyTemplates */
<ide> /** @typedef {import("../Module")} Module */
<ide><path>lib/webpack.js
<ide> const NodeEnvironmentPlugin = require("./node/NodeEnvironmentPlugin");
<ide> const validateSchema = require("./validateSchema");
<ide>
<ide> /** @typedef {import("../declarations/WebpackOptions").WebpackOptions} WebpackOptions */
<del>/** @typedef {import("./Compiler")} Compiler */
<ide> /** @typedef {import("./Compiler").WatchOptions} WatchOptions */
<del>/** @typedef {import("./MultiCompiler")} MultiCompiler */
<ide> /** @typedef {import("./MultiStats")} MultiStats */
<ide> /** @typedef {import("./Stats")} Stats */
<ide> | 20 |
Text | Text | update package.json field definitions | e6b1d74b8dd17698c5a7a000bfe6b20e02820907 | <ide><path>doc/api/packages.md
<ide> The following fields in `package.json` files are used in Node.js:
<ide>
<ide> * [`"name"`][] - Relevant when using named imports within a package. Also used
<ide> by package managers as the name of the package.
<add>* [`"main"`][] - The default module when loading the package, if exports is not
<add> specified, and in versions of Node.js prior to the introduction of exports.
<ide> * [`"type"`][] - The package type determining whether to load `.js` files as
<ide> CommonJS or ES modules.
<ide> * [`"exports"`][] - Package exports and conditional exports. When present,
<ide> limits which submodules can be loaded from within the package.
<del>* [`"main"`][] - The default module when loading the package, if exports is not
<del> specified, and in versions of Node.js prior to the introduction of exports.
<ide> * [`"imports"`][] - Package imports, for use by modules within the package
<ide> itself.
<ide>
<ide> _npm_ registry requires a name that satisfies
<ide> The `"name"` field can be used in addition to the [`"exports"`][] field to
<ide> [self-reference][] a package using its name.
<ide>
<add>### `"main"`
<add><!-- YAML
<add>added: v0.4.0
<add>-->
<add>
<add>* Type: {string}
<add>
<add>```json
<add>{
<add> "main": "./main.js"
<add>}
<add>```
<add>
<add>The `"main"` field defines the script that is used when the [package directory
<add>is loaded via `require()`](modules.md#modules_folders_as_modules). Its value
<add>is a path.
<add>
<add>```js
<add>require('./path/to/directory'); // This resolves to ./path/to/directory/main.js.
<add>```
<add>
<add>When a package has an [`"exports"`][] field, this will take precedence over the
<add>`"main"` field when importing the package by name.
<add>
<ide> ### `"type"`
<ide> <!-- YAML
<ide> added: v12.0.0
<ide> changes:
<ide> description: Unflag `--experimental-modules`.
<ide> -->
<ide>
<add>> Stability: 1 - Experimental
<add>
<ide> * Type: {string}
<ide>
<ide> The `"type"` field defines the module format that Node.js uses for all
<ide> changes:
<ide> description: Implement conditional exports.
<ide> -->
<ide>
<add>> Stability: 1 - Experimental
<add>
<ide> * Type: {Object} | {string} | {string[]}
<ide>
<ide> ```json
<ide> referenced via `require` or via `import`.
<ide> All paths defined in the `"exports"` must be relative file URLs starting with
<ide> `./`.
<ide>
<del>### `"main"`
<del><!-- YAML
<del>added: v0.4.0
<del>-->
<del>
<del>* Type: {string}
<del>
<del>```json
<del>{
<del> "main": "./main.js"
<del>}
<del>```
<del>
<del>The `"main"` field defines the script that is used when the [package directory
<del>is loaded via `require()`](modules.md#modules_folders_as_modules). Its value
<del>is interpreted as a path.
<del>
<del>```js
<del>require('./path/to/directory'); // This resolves to ./path/to/directory/main.js.
<del>```
<del>
<del>When a package has an [`"exports"`][] field, this will take precedence over the
<del>`"main"` field when importing the package by name.
<del>
<ide> ### `"imports"`
<ide> <!-- YAML
<ide> added: v14.6.0 | 1 |
Ruby | Ruby | fix typo in doco | 12686ad417c40274f1da439c5cb7484aefde8b8c | <ide><path>Library/Homebrew/cmd/fetch.rb
<ide> #: If `--HEAD` or `--devel` is passed, fetch that version instead of the
<ide> #: stable version.
<ide> #:
<del>#: If `-v` is passed, do a verbose VCS checkout, if the URL represents a CVS.
<add>#: If `-v` is passed, do a verbose VCS checkout, if the URL represents a VCS.
<ide> #: This is useful for seeing if an existing VCS cache has been updated.
<ide> #:
<ide> #: If `--force` is passed, remove a previously cached version and re-fetch. | 1 |
PHP | PHP | add assertion for number of results | 426937bc759686775bd5dafbbb40faa5ad5b491c | <ide><path>tests/TestCase/ORM/MarshallerTest.php
<ide> public function testMergeManyExistQueryFails()
<ide> $marshall = new Marshaller($comments);
<ide> $result = $marshall->mergeMany($entities, $data);
<ide>
<add> $this->assertCount(3, $result);
<ide> $this->assertEquals('Changed 1', $result[0]->comment);
<ide> $this->assertEquals(1, $result[0]->user_id);
<ide> $this->assertEquals('Changed 2', $result[1]->comment); | 1 |
Javascript | Javascript | fix global leaks | 92789b16e594f806dbdaee1a65c1d8440b96fc65 | <ide><path>lib/net.js
<ide> Server.prototype._rejectPending = function() {
<ide> // Accept and close the waiting clients one at a time.
<ide> // Single threaded programming ftw.
<ide> while (true) {
<del> peerInfo = accept(this.fd);
<add> var peerInfo = accept(this.fd);
<ide> if (!peerInfo) return;
<ide> close(peerInfo.fd);
<ide>
<ide><path>test/fixtures/print-chars-from-buffer.js
<ide> var common = require('../common');
<ide> var assert = require('assert');;
<del>Buffer = require('buffer').Buffer;
<ide>
<ide> var n = parseInt(process.argv[2]);
<ide>
<del>b = new Buffer(n);
<add>var b = new Buffer(n);
<ide> for (var i = 0; i < n; i++) {
<ide> b[i] = 100;
<ide> }
<ide><path>test/message/2100bytes.js
<del>common = require('../common');
<del>assert = common.assert;
<add>var common = require('../common');
<add>var assert = require('assert');
<add>var util = require('util');
<ide>
<del>util = require('util');
<ide> console.log([
<ide> '_______________________________________________50',
<ide> '______________________________________________100',
<ide><path>test/message/hello_world.js
<del>common = require('../common');
<del>assert = common.assert;
<add>var common = require('../common');
<add>var assert = require('assert');
<ide>
<ide> console.log('hello world');
<ide><path>test/pummel/test-keep-alive.js
<ide> // This test requires the program 'ab'
<ide> var common = require('../common');
<ide> var assert = require('assert');;
<del>http = require('http');
<del>exec = require('child_process').exec;
<add>var http = require('http');
<add>var exec = require('child_process').exec;
<ide>
<del>body = 'hello world\n';
<del>server = http.createServer(function(req, res) {
<add>var body = 'hello world\n';
<add>var server = http.createServer(function(req, res) {
<ide> res.writeHead(200, {
<ide> 'Content-Length': body.length,
<ide> 'Content-Type': 'text/plain'
<ide><path>test/pummel/test-net-many-clients.js
<ide> var common = require('../common');
<ide> var assert = require('assert');;
<del>net = require('net');
<add>var net = require('net');
<add>
<ide> // settings
<ide> var bytes = 1024 * 40;
<ide> var concurrency = 100;
<ide><path>test/pummel/test-net-pause.js
<ide> var common = require('../common');
<ide> var assert = common.assert;
<ide> var net = require('net');
<add>
<ide> var N = 200;
<ide> var recv = '', chars_recved = 0;
<ide>
<del>server = net.createServer(function(connection) {
<add>var server = net.createServer(function(connection) {
<ide> function write(j) {
<ide> if (j >= N) {
<ide> connection.end();
<ide> server = net.createServer(function(connection) {
<ide> }
<ide> write(0);
<ide> });
<add>
<ide> server.on('listening', function() {
<del> client = net.createConnection(common.PORT);
<add> var client = net.createConnection(common.PORT);
<ide> client.setEncoding('ascii');
<ide> client.addListener('data', function(d) {
<ide> common.print(d);
<ide><path>test/pummel/test-net-pingpong-delay.js
<ide> var common = require('../common');
<ide> var assert = require('assert');;
<del>net = require('net');
<add>var net = require('net');
<ide>
<ide>
<ide> var tests_run = 0;
<ide><path>test/pummel/test-net-pingpong.js
<ide> var common = require('../common');
<ide> var assert = require('assert');;
<del>net = require('net');
<add>var net = require('net');
<ide>
<ide> var tests_run = 0;
<ide>
<ide><path>test/pummel/test-net-throttle.js
<ide> var common = require('../common');
<ide> var assert = require('assert');;
<del>net = require('net');
<del>N = 160 * 1024; // 30kb
<add>var net = require('net');
<ide>
<del>
<del>chars_recved = 0;
<del>npauses = 0;
<add>var N = 160 * 1024; // 30kb
<add>var chars_recved = 0;
<add>var npauses = 0;
<ide>
<ide> console.log('build big string');
<ide> var body = '';
<ide> for (var i = 0; i < N; i++) {
<ide>
<ide> console.log('start server on port ' + common.PORT);
<ide>
<del>server = net.createServer(function(connection) {
<add>var server = net.createServer(function(connection) {
<ide> connection.addListener('connect', function() {
<ide> assert.equal(false, connection.write(body));
<ide> connection.end();
<ide> });
<ide> });
<add>
<ide> server.listen(common.PORT, function() {
<ide> var paused = false;
<del> client = net.createConnection(common.PORT);
<add> var client = net.createConnection(common.PORT);
<ide> client.setEncoding('ascii');
<ide> client.addListener('data', function(d) {
<ide> chars_recved += d.length;
<ide> server.listen(common.PORT, function() {
<ide> npauses += 1;
<ide> paused = true;
<ide> console.log('pause');
<del> x = chars_recved;
<add> var x = chars_recved;
<ide> setTimeout(function() {
<ide> assert.equal(chars_recved, x);
<ide> client.resume();
<ide><path>test/pummel/test-net-timeout.js
<ide> var common = require('../common');
<ide> var assert = require('assert');;
<del>net = require('net');
<del>exchanges = 0;
<del>starttime = null;
<del>timeouttime = null;
<del>timeout = 1000;
<add>var net = require('net');
<add>
<add>var exchanges = 0;
<add>var starttime = null;
<add>var timeouttime = null;
<add>var timeout = 1000;
<ide>
<ide> var echo_server = net.createServer(function(socket) {
<ide> socket.setTimeout(timeout);
<ide><path>test/pummel/test-timers.js
<ide> var common = require('../common');
<ide> var assert = require('assert');
<ide>
<del>assert = require('assert');
<del>
<ide> var WINDOW = 200; // why is does this need to be so big?
<ide>
<ide> var interval_count = 0;
<ide> setInterval(function(param1, param2){
<ide> }, 1000, 'param1', 'param2');
<ide>
<ide> // setInterval(cb, 0) should be called multiple times.
<del>count4 = 0;
<del>interval4 = setInterval(function() {
<add>var count4 = 0;
<add>var interval4 = setInterval(function() {
<ide> if (++count4 > 10) clearInterval(interval4);
<ide> }, 0);
<ide>
<ide> function t () {
<ide> expectedTimeouts--;
<ide> }
<ide>
<del>w = setTimeout(t, 200),
<del>x = setTimeout(t, 200),
<del>y = setTimeout(t, 200);
<add>var w = setTimeout(t, 200);
<add>var x = setTimeout(t, 200);
<add>var y = setTimeout(t, 200);
<ide>
<del>clearTimeout(y),
<del>z = setTimeout(t, 200);
<add>clearTimeout(y);
<add>var z = setTimeout(t, 200);
<ide> clearTimeout(y);
<ide>
<ide>
<ide><path>test/simple/test-http-exceptions.js
<ide> var common = require('../common');
<ide> var assert = require('assert');;
<ide> var http = require('http');
<ide>
<del>server = http.createServer(function (req, res) {
<add>var server = http.createServer(function (req, res) {
<ide> intentionally_not_defined();
<ide> res.writeHead(200, {"Content-Type": "text/plain"});
<ide> res.write("Thank you, come again.");
<ide> server.listen(common.PORT, function () {
<ide> }
<ide> });
<ide>
<del>exception_count = 0;
<add>var exception_count = 0;
<ide>
<ide> process.addListener("uncaughtException", function (err) {
<ide> console.log("Caught an exception: " + err);
<ide><path>test/simple/test-http-expect-continue.js
<ide> var common = require("../common");
<del>var assert = common.assert;
<add>var assert = require('assert');
<ide> var http = require("http");
<ide>
<ide> var outstanding_reqs = 0;
<ide> server.listen(common.PORT);
<ide>
<ide> server.addListener("listening", function() {
<ide> var client = http.createClient(common.PORT);
<del> req = client.request("POST", "/world", {
<add> var req = client.request("POST", "/world", {
<ide> "Expect": "100-continue",
<ide> });
<ide> common.debug("Client sending request...");
<ide> outstanding_reqs++;
<del> body = "";
<add> var body = "";
<ide> req.addListener('continue', function () {
<ide> common.debug("Client got 100 Continue...");
<ide> got_continue = true;
<ide><path>test/simple/test-http-keep-alive-close-on-header.js
<ide> var common = require('../common');
<ide> var assert = require('assert');
<del>
<del>assert = require("assert");
<ide> var http = require('http');
<ide> var util = require('util');
<ide>
<del>body = "hello world\n";
<del>headers = {'connection':'keep-alive'}
<add>var body = "hello world\n";
<add>var headers = {'connection':'keep-alive'}
<ide>
<del>server = http.createServer(function (req, res) {
<add>var server = http.createServer(function (req, res) {
<ide> res.writeHead(200, {"Content-Length": body.length, "Connection":"close"});
<ide> res.write(body);
<ide> res.end();
<ide> });
<ide>
<del>connectCount = 0;
<add>var connectCount = 0;
<ide>
<ide> server.listen(common.PORT, function () {
<ide> var client = http.createClient(common.PORT);
<ide><path>test/simple/test-http-keep-alive.js
<ide> var common = require('../common');
<ide> var assert = require('assert');
<del>
<del>assert = require("assert");
<ide> var http = require('http');
<ide> var util = require('util');
<ide>
<del>body = "hello world\n";
<del>headers = {'connection':'keep-alive'}
<add>var body = "hello world\n";
<add>var headers = {'connection':'keep-alive'}
<ide>
<del>server = http.createServer(function (req, res) {
<add>var server = http.createServer(function (req, res) {
<ide> res.writeHead(200, {"Content-Length": body.length});
<ide> res.write(body);
<ide> res.end();
<ide> });
<ide>
<del>connectCount = 0;
<add>var connectCount = 0;
<ide>
<ide> server.listen(common.PORT, function () {
<ide> var client = http.createClient(common.PORT);
<ide><path>test/simple/test-http-server.js
<ide> var common = require('../common');
<ide> var assert = require('assert');
<ide> var net = require('net');
<ide> var http = require('http');
<del>url = require("url");
<del>qs = require("querystring");
<add>var url = require("url");
<add>var qs = require("querystring");
<ide>
<ide> var request_number = 0;
<ide> var requests_sent = 0;
<ide><path>test/simple/test-http-upgrade-server2.js
<ide> var common = require('../common');
<ide> var assert = require('assert');
<del>
<ide> var http = require('http');
<ide> var net = require('net');
<ide>
<del>server = http.createServer(function (req, res) {
<add>var server = http.createServer(function (req, res) {
<ide> common.error('got req');
<ide> throw new Error("This shouldn't happen.");
<ide> });
<ide> server.addListener('upgrade', function (req, socket, upgradeHead) {
<ide> throw new Error('upgrade error');
<ide> });
<ide>
<del>gotError = false;
<add>var gotError = false;
<ide>
<ide> process.addListener('uncaughtException', function (e) {
<ide> common.error('got "clientError" event');
<ide><path>test/simple/test-http-write-empty-string.js
<ide> var common = require('../common');
<ide> var assert = require('assert');
<ide>
<ide> var http = require('http');
<del>assert = require('assert');
<ide>
<del>server = http.createServer(function (request, response) {
<add>var server = http.createServer(function (request, response) {
<ide> console.log('responding to ' + request.url);
<ide>
<ide> response.writeHead(200, {'Content-Type': 'text/plain'});
<ide><path>test/simple/test-http.js
<ide> var common = require('../common');
<ide> var assert = require('assert');
<ide> var http = require('http');
<del>url = require("url");
<add>var url = require("url");
<ide>
<ide> function p (x) {
<ide> common.error(common.inspect(x));
<ide><path>test/simple/test-listen-fd.js
<ide> var common = require('../common');
<ide> var assert = require('assert');
<ide> var http = require('http');
<del>netBinding = process.binding('net');
<add>var netBinding = process.binding('net');
<ide>
<ide> // Create an server and set it listening on a socket bound to common.PORT
<ide> var gotRequest = false;
<ide><path>test/simple/test-net-binary.js
<ide> var common = require('../common');
<ide> var assert = require('assert');
<ide> var net = require('net');
<ide>
<del>binaryString = "";
<add>var binaryString = "";
<ide> for (var i = 255; i >= 0; i--) {
<ide> var s = "'\\" + i.toString(8) + "'";
<del> S = eval(s);
<add> var S = eval(s);
<ide> common.error( s
<ide> + " "
<ide> + JSON.stringify(S)
<ide><path>test/simple/test-net-server-max-connections.js
<ide> var net = require('net');
<ide> // TODO: test that the server can accept more connections after it reaches
<ide> // its maximum and some are closed.
<ide>
<del>N = 200;
<del>count = 0;
<del>closes = 0;
<del>waits = [];
<add>var N = 200;
<add>var count = 0;
<add>var closes = 0;
<add>var waits = [];
<ide>
<del>server = net.createServer(function (connection) {
<add>var server = net.createServer(function (connection) {
<ide> console.error("connect %d", count++);
<ide> connection.write("hello");
<ide> waits.push(function () { connection.end(); });
<ide><path>test/simple/test-pipe-head.js
<ide> var common = require('../common');
<ide> var assert = require('assert');
<add>var exec = require('child_process').exec;
<add>var join = require('path').join;
<ide>
<del>exec = require('child_process').exec;
<del>join = require('path').join;
<add>var nodePath = process.argv[0];
<add>var script = join(common.fixturesDir, 'print-10-lines.js');
<ide>
<del>nodePath = process.argv[0];
<del>script = join(common.fixturesDir, 'print-10-lines.js');
<add>var cmd = nodePath + ' ' + script + ' | head -2';
<ide>
<del>cmd = nodePath + ' ' + script + ' | head -2';
<del>
<del>finished = false;
<add>var finished = false;
<ide>
<ide> exec(cmd, function (err, stdout, stderr) {
<ide> if (err) throw err;
<del> lines = stdout.split('\n');
<add> var lines = stdout.split('\n');
<ide> assert.equal(3, lines.length);
<ide> finished = true;
<ide> });
<ide><path>test/simple/test-pump-file2tcp-noexist.js
<ide> var net = require('net');
<ide> var fs = require('fs');
<ide> var util = require('util');
<ide> var path = require('path');
<del>fn = path.join(common.fixturesDir, 'does_not_exist.txt');
<add>var fn = path.join(common.fixturesDir, 'does_not_exist.txt');
<ide>
<ide> var got_error = false;
<ide> var conn_closed = false;
<ide>
<del>server = net.createServer(function (stream) {
<add>var server = net.createServer(function (stream) {
<ide> common.error('pump!');
<ide> util.pump(fs.createReadStream(fn), stream, function (err) {
<ide> common.error("util.pump's callback fired");
<ide> server = net.createServer(function (stream) {
<ide> });
<ide>
<ide> server.listen(common.PORT, function () {
<del> conn = net.createConnection(common.PORT);
<add> var conn = net.createConnection(common.PORT);
<ide> conn.setEncoding('utf8');
<ide> conn.addListener("data", function (chunk) {
<ide> common.error('recv data! nchars = ' + chunk.length);
<ide> server.listen(common.PORT, function () {
<ide> });
<ide>
<ide> var buffer = '';
<del>count = 0;
<ide>
<ide> process.addListener('exit', function () {
<ide> assert.equal(true, got_error);
<ide><path>test/simple/test-pump-file2tcp.js
<ide> var net = require('net');
<ide> var fs = require('fs');
<ide> var util = require('util');
<ide> var path = require('path');
<del>fn = path.join(common.fixturesDir, 'elipses.txt');
<add>var fn = path.join(common.fixturesDir, 'elipses.txt');
<ide>
<del>expected = fs.readFileSync(fn, 'utf8');
<add>var expected = fs.readFileSync(fn, 'utf8');
<ide>
<del>server = net.createServer(function (stream) {
<add>var server = net.createServer(function (stream) {
<ide> common.error('pump!');
<ide> util.pump(fs.createReadStream(fn), stream, function () {
<ide> common.error('server stream close');
<ide> server = net.createServer(function (stream) {
<ide> });
<ide>
<ide> server.listen(common.PORT, function () {
<del> conn = net.createConnection(common.PORT);
<add> var conn = net.createConnection(common.PORT);
<ide> conn.setEncoding('utf8');
<ide> conn.addListener("data", function (chunk) {
<ide> common.error('recv data! nchars = ' + chunk.length);
<ide> server.listen(common.PORT, function () {
<ide> });
<ide>
<ide> var buffer = '';
<del>count = 0;
<add>var count = 0;
<ide>
<ide> server.addListener('listening', function () {
<ide> });
<ide><path>test/simple/test-signal-handler.js
<ide> process.addListener('SIGUSR1', function () {
<ide> }, 5);
<ide> });
<ide>
<del>i = 0;
<add>var i = 0;
<ide> setInterval(function () {
<ide> console.log("running process..." + ++i);
<ide>
<ide><path>test/simple/test-stdin-from-file.js
<ide> var common = require('../common');
<ide> var assert = require('assert');
<del>
<del>join = require('path').join;
<del>childProccess = require('child_process');
<add>var join = require('path').join;
<add>var childProccess = require('child_process');
<ide> var fs = require('fs');
<ide>
<del>stdoutScript = join(common.fixturesDir, 'echo.js');
<del>tmpFile = join(common.fixturesDir, 'stdin.txt');
<add>var stdoutScript = join(common.fixturesDir, 'echo.js');
<add>var tmpFile = join(common.fixturesDir, 'stdin.txt');
<ide>
<del>cmd = process.argv[0] + ' ' + stdoutScript + ' < ' + tmpFile;
<add>var cmd = process.argv[0] + ' ' + stdoutScript + ' < ' + tmpFile;
<ide>
<del>string = "abc\nümlaut.\nsomething else\n"
<del> + "南越国是前203年至前111年存在于岭南地区的一个国家,国都位于番禺,疆域包括今天中国的广东、广西两省区的大部份地区,福建省、湖南、贵州、云南的一小部份地区和越南的北部。南越国是秦朝灭亡后,由南海郡尉赵佗于前203年起兵兼并桂林郡和象郡后建立。前196年和前179年,南越国曾先后两次名义上臣属于西汉,成为西汉的“外臣”。前112年,南越国末代君主赵建德与西汉发生战争,被汉武帝于前111年所灭。南越国共存在93年,历经五代君主。南越国是岭南地区的第一个有记载的政权国家,采用封建制和郡县制并存的制度,它的建立保证了秦末乱世岭南地区社会秩序的稳定,有效的改善了岭南地区落后的政治、##济现状。\n";
<add>var string = "abc\nümlaut.\nsomething else\n" +
<add> "南越国是前203年至前111年存在于岭南地区的一个国家,国都位于番禺,疆域包括今天中国的广东、广西两省区的大部份地区,福建省、湖南、贵州、云南的一小部份地区和越南的北部。南越国是秦朝灭亡后,由南海郡尉赵佗于前203年起兵兼并桂林郡和象郡后建立。前196年和前179年,南越国曾先后两次名义上臣属于西汉,成为西汉的“外臣”。前112年,南越国末代君主赵建德与西汉发生战争,被汉武帝于前111年所灭。南越国共存在93年,历经五代君主。南越国是岭南地区的第一个有记载的政权国家,采用封建制和郡县制并存的制度,它的建立保证了秦末乱世岭南地区社会秩序的稳定,有效的改善了岭南地区落后的政治、##济现状。\n";
<ide>
<ide>
<ide> console.log(cmd + "\n\n");
<ide><path>test/simple/test-stdout-to-file.js
<ide> var common = require('../common');
<ide> var assert = require('assert');
<ide> var path = require('path');
<del>childProccess = require('child_process');
<add>var childProccess = require('child_process');
<ide> var fs = require('fs');
<del>scriptString = path.join(common.fixturesDir, 'print-chars.js');
<del>scriptBuffer = path.join(common.fixturesDir, 'print-chars-from-buffer.js');
<del>tmpFile = path.join(common.fixturesDir, 'stdout.txt');
<add>
<add>var scriptString = path.join(common.fixturesDir, 'print-chars.js');
<add>var scriptBuffer = path.join(common.fixturesDir, 'print-chars-from-buffer.js');
<add>var tmpFile = path.join(common.fixturesDir, 'stdout.txt');
<ide>
<ide> function test (size, useBuffer, cb) {
<ide> var cmd = process.argv[0]
<ide> function test (size, useBuffer, cb) {
<ide> });
<ide> }
<ide>
<del>finished = false;
<add>var finished = false;
<ide> test(1024*1024, false, function () {
<ide> console.log("Done printing with string");
<ide> test(1024*1024, true, function () {
<ide><path>test/simple/test-string-decoder.js
<ide> var common = require('../common');
<del>var assert = require('assert');;
<add>var assert = require('assert');
<add>var StringDecoder = require('string_decoder').StringDecoder;
<add>var decoder = new StringDecoder('utf8');
<ide>
<del>Buffer = require('buffer').Buffer;
<del>StringDecoder = require('string_decoder').StringDecoder;
<del>decoder = new StringDecoder('utf8');
<ide>
<ide>
<del>
<del>buffer = new Buffer('$');
<add>var buffer = new Buffer('$');
<ide> assert.deepEqual('$', decoder.write(buffer));
<ide>
<ide> buffer = new Buffer('¢');
<ide> assert.deepEqual('', decoder.write(buffer.slice(1, 2)));
<ide> assert.deepEqual('€', decoder.write(buffer.slice(2, 3)));
<ide>
<ide> buffer = new Buffer([0xF0, 0xA4, 0xAD, 0xA2]);
<del>s = '';
<add>var s = '';
<ide> s += decoder.write(buffer.slice(0, 1));
<ide> s += decoder.write(buffer.slice(1, 2));
<ide> s += decoder.write(buffer.slice(2, 3));
<ide> assert.ok(s.length > 0);
<ide> // U+12E4 -> E1 8B A4
<ide> // U+0030 -> 30
<ide> // U+3045 -> E3 81 85
<del>expected = '\u02e4\u0064\u12e4\u0030\u3045';
<del>buffer = new Buffer([0xCB, 0xA4, 0x64, 0xE1, 0x8B, 0xA4,
<del> 0x30, 0xE3, 0x81, 0x85]);
<del>charLengths = [0, 0, 1, 2, 2, 2, 3, 4, 4, 4, 5, 5];
<add>var expected = '\u02e4\u0064\u12e4\u0030\u3045';
<add>var buffer = new Buffer([0xCB, 0xA4, 0x64, 0xE1, 0x8B, 0xA4,
<add> 0x30, 0xE3, 0x81, 0x85]);
<add>var charLengths = [0, 0, 1, 2, 2, 2, 3, 4, 4, 4, 5, 5];
<ide>
<ide> // Split the buffer into 3 segments
<ide> // |----|------|-------| | 30 |
PHP | PHP | fix errors when validateunique is used with scope | 28462cab25c13ece7bf82bf65caa1a98d30e1c1f | <ide><path>src/ORM/Table.php
<ide> public function patchEntities($entities, array $data, array $options = [])
<ide> * the data to be validated.
<ide> *
<ide> * @param mixed $value The value of column to be checked for uniqueness
<del> * @param array $options The options array, optionally containing the 'scope' key
<add> * @param array $context Either the options or validation context.
<add> * @param array|null $options The options array, optionally containing the 'scope' key
<ide> * @return bool true if the value is unique
<ide> */
<del> public function validateUnique($value, array $options)
<add> public function validateUnique($value, array $context, array $options = null)
<ide> {
<add> if ($options === null) {
<add> $options = $context;
<add> }
<ide> $entity = new Entity(
<ide> $options['data'],
<ide> ['useSetters' => false, 'markNew' => $options['newRecord']]
<ide><path>tests/TestCase/ORM/TableTest.php
<ide> public function testValidateUnique()
<ide> $data = ['username' => 'larry'];
<ide> $this->assertNotEmpty($validator->errors($data, false));
<ide> }
<add>
<add> /**
<add> * Tests the validateUnique method with scope
<add> *
<add> * @return void
<add> */
<add> public function testValidateUniqueScope()
<add> {
<add> $table = TableRegistry::get('Users');
<add> $validator = new Validator;
<add> $validator->add('username', 'unique', [
<add> 'rule' => ['validateUnique', ['scope' => 'id']],
<add> 'provider' => 'table'
<add> ]);
<add> $validator->provider('table', $table);
<add> $data = ['username' => 'larry'];
<add> $this->assertNotEmpty($validator->errors($data));
<add>
<add> $data = ['username' => 'jose'];
<add> $this->assertEmpty($validator->errors($data));
<add> }
<ide> } | 2 |
Javascript | Javascript | use ports proxied by saucelabs | df17a2c7495cea22f803d1e2e22329712a7fd25a | <ide><path>lib/grunt/utils.js
<ide> module.exports = {
<ide> stream: options && options.stream
<ide> };
<ide>
<del> args.push('--port=' + this.lastParallelTaskPort);
<add> args.push('--port=' + this.sauceLabsAvailablePorts.pop());
<ide>
<ide> if (args.indexOf('test:e2e') !== -1 && grunt.option('e2e-browsers')) {
<ide> args.push('--browsers=' + grunt.option('e2e-browsers'));
<ide> module.exports = {
<ide> args.push('--reporters=' + grunt.option('reporters'));
<ide> }
<ide>
<del> this.lastParallelTaskPort++;
<del>
<ide> return task;
<ide> },
<ide>
<del> lastParallelTaskPort: 9876
<add> // see http://saucelabs.com/docs/connect#localhost
<add> sauceLabsAvailablePorts: [9000, 9001, 9080, 9090, 9876]
<ide> }; | 1 |
Javascript | Javascript | add common.platformtimeout() to dgram test | d3195615c0d11301b48f56413a26ca4d5d05f109 | <ide><path>test/parallel/test-dgram-send-empty-buffer.js
<ide> 'use strict';
<del>var common = require('../common');
<del>
<del>var dgram = require('dgram');
<del>var client, timer, buf;
<add>const common = require('../common');
<add>const dgram = require('dgram');
<ide>
<ide> if (process.platform === 'darwin') {
<ide> console.log('1..0 # Skipped: because of 17894467 Apple bug');
<ide> return;
<ide> }
<ide>
<del>
<del>client = dgram.createSocket('udp4');
<add>const client = dgram.createSocket('udp4');
<ide>
<ide> client.bind(common.PORT);
<ide>
<ide> client.on('message', function(buffer, bytes) {
<ide> client.close();
<ide> });
<ide>
<del>buf = new Buffer(0);
<add>const buf = new Buffer(0);
<ide> client.send(buf, 0, 0, common.PORT, '127.0.0.1', function(err, len) { });
<ide>
<del>timer = setTimeout(function() {
<add>const timer = setTimeout(function() {
<ide> throw new Error('Timeout');
<del>}, 200);
<add>}, common.platformTimeout(200)); | 1 |
PHP | PHP | update integrationtestcase tests to use httpserver | b1adcab2cae3669c24256a7c55303d028bdb9329 | <ide><path>src/TestSuite/IntegrationTestCase.php
<ide> public function controllerSpy($event, $controller = null)
<ide> $this->_viewName = $viewFile;
<ide> }
<ide> if ($this->_retainFlashMessages) {
<del> $this->_flashMessages = $controller->request->session()->read('Flash');
<add> $this->_flashMessages = $controller->request->getSession()->read('Flash');
<ide> }
<ide> });
<ide> $events->on('View.beforeLayout', function ($event, $viewFile) {
<ide> protected function _buildRequest($url, $method, $data)
<ide> list ($url, $query) = $this->_url($url);
<ide> $tokenUrl = $url;
<ide>
<del> parse_str($query, $queryData);
<del>
<ide> if ($query) {
<del> $tokenUrl .= '?' . http_build_query($queryData);
<add> $tokenUrl .= '?' . $query;
<ide> }
<ide>
<add> parse_str($query, $queryData);
<ide> $props = [
<ide> 'url' => $url,
<ide> 'session' => $session,
<ide> public function assertContentType($type, $message = '')
<ide> if ($alias !== false) {
<ide> $type = $alias;
<ide> }
<del> $result = $this->_response->type();
<add> $result = $this->_response->getType();
<ide> $this->assertEquals($type, $result, $message);
<ide> }
<ide>
<ide> public function assertCookie($expected, $name, $message = '')
<ide> if (!$this->_response) {
<ide> $this->fail('Not response set, cannot assert cookies.');
<ide> }
<del> $result = $this->_response->cookie($name);
<add> $result = $this->_response->getCookie($name);
<ide> $this->assertEquals(
<ide> $expected,
<ide> $result['value'],
<ide> public function assertCookieEncrypted($expected, $name, $encrypt = 'aes', $key =
<ide> if (!$this->_response) {
<ide> $this->fail('No response set, cannot assert cookies.');
<ide> }
<del> $result = $this->_response->cookie($name);
<add> $result = $this->_response->getCookie($name);
<ide> $this->_cookieEncryptionKey = $key;
<ide> $result['value'] = $this->_decrypt($result['value'], $encrypt);
<ide> $this->assertEquals($expected, $result['value'], 'Cookie data differs. ' . $message);
<ide><path>tests/TestCase/TestSuite/IntegrationTestCaseTest.php
<ide> use Cake\Http\Response;
<ide> use Cake\Routing\DispatcherFactory;
<ide> use Cake\Routing\Router;
<add>use Cake\Routing\Route\InflectedRoute;
<ide> use Cake\TestSuite\IntegrationTestCase;
<ide> use Cake\Test\Fixture\AssertIntegrationTestCase;
<ide> use Cake\Utility\Security;
<ide> public function setUp()
<ide> parent::setUp();
<ide> static::setAppNamespace();
<ide>
<del> Router::connect('/get/:controller/:action', ['_method' => 'GET'], ['routeClass' => 'InflectedRoute']);
<del> Router::connect('/head/:controller/:action', ['_method' => 'HEAD'], ['routeClass' => 'InflectedRoute']);
<del> Router::connect('/options/:controller/:action', ['_method' => 'OPTIONS'], ['routeClass' => 'InflectedRoute']);
<del> Router::connect('/:controller/:action/*', [], ['routeClass' => 'InflectedRoute']);
<add> Router::reload();
<add> Router::scope('/', function ($routes) {
<add> $routes->setRouteClass(InflectedRoute::class);
<add> $routes->get('/get/:controller/:action', []);
<add> $routes->head('/head/:controller/:action', []);
<add> $routes->options('/options/:controller/:action', []);
<add> $routes->connect('/:controller/:action/*', []);
<add> });
<add> Router::$initialized = true;
<add>
<add> $this->useHttpServer(true);
<ide> DispatcherFactory::clear();
<add> }
<add>
<add> /**
<add> * Helper for enabling the legacy stack for backwards compatibility testing.
<add> *
<add> * @return void
<add> */
<add> protected function useLegacyDispatcher()
<add> {
<ide> DispatcherFactory::add('Routing');
<ide> DispatcherFactory::add('ControllerFactory');
<add>
<ide> $this->useHttpServer(false);
<ide> }
<ide>
<ide> public function testCookieEncrypted()
<ide> /**
<ide> * Test sending get requests.
<ide> *
<add> * @group deprecated
<ide> * @return void
<ide> */
<del> public function testGet()
<add> public function testGetLegacy()
<ide> {
<del> $this->assertNull($this->_response);
<add> $this->useLegacyDispatcher();
<add> $this->deprecated(function () {
<add> $this->assertNull($this->_response);
<ide>
<del> $this->get('/request_action/test_request_action');
<del> $this->assertNotEmpty($this->_response);
<del> $this->assertInstanceOf('Cake\Http\Response', $this->_response);
<del> $this->assertEquals('This is a test', $this->_response->getBody());
<add> $this->get('/request_action/test_request_action');
<add> $this->assertNotEmpty($this->_response);
<add> $this->assertInstanceOf('Cake\Http\Response', $this->_response);
<add> $this->assertEquals('This is a test', $this->_response->getBody());
<ide>
<del> $this->_response = null;
<del> $this->get('/get/request_action/test_request_action');
<del> $this->assertEquals('This is a test', $this->_response->getBody());
<add> $this->_response = null;
<add> $this->get('/get/request_action/test_request_action');
<add> $this->assertEquals('This is a test', $this->_response->getBody());
<add> });
<ide> }
<ide>
<ide> /**
<ide> public function testGetUsingApplicationWithDefaultRoutes()
<ide> // first clean routes to have Router::$initailized === false
<ide> Router::reload();
<ide>
<del> $this->useHttpServer(true);
<ide> $this->configApplication(Configure::read('App.namespace') . '\ApplicationWithDefaultRoutes', null);
<ide>
<ide> $this->get('/some_alias');
<ide> public function testOptions()
<ide> $this->assertResponseSuccess();
<ide> }
<ide>
<add> /**
<add> * Test sending get requests sets the request method
<add> *
<add> * @return void
<add> */
<add> public function testGetSpecificRouteLegacy()
<add> {
<add> $this->useLegacyDispatcher();
<add> $this->deprecated(function () {
<add> $this->get('/get/request_action/test_request_action');
<add> $this->assertResponseOk();
<add> $this->assertEquals('This is a test', $this->_response->getBody());
<add> });
<add> }
<add>
<ide> /**
<ide> * Test sending get requests sets the request method
<ide> *
<ide> * @return void
<ide> */
<ide> public function testGetSpecificRouteHttpServer()
<ide> {
<del> $this->useHttpServer(true);
<ide> $this->get('/get/request_action/test_request_action');
<ide> $this->assertResponseOk();
<ide> $this->assertEquals('This is a test', $this->_response->getBody());
<ide> public function testConfigApplication()
<ide> {
<ide> $this->expectException(\LogicException::class);
<ide> $this->expectExceptionMessage('Cannot load "TestApp\MissingApp" for use in integration');
<del> DispatcherFactory::clear();
<del> $this->useHttpServer(true);
<ide> $this->configApplication('TestApp\MissingApp', []);
<ide> $this->get('/request_action/test_request_action');
<ide> }
<ide> public function testConfigApplication()
<ide> */
<ide> public function testGetHttpServer()
<ide> {
<del> DispatcherFactory::clear();
<del> $this->useHttpServer(true);
<ide> $this->assertNull($this->_response);
<ide>
<ide> $this->get('/request_action/test_request_action');
<ide> public function testGetHttpServer()
<ide> */
<ide> public function testGetQueryStringHttpServer()
<ide> {
<del> $this->useHttpServer(true);
<del>
<ide> $this->configRequest(['headers' => ['Content-Type' => 'text/plain']]);
<ide> $this->get('/request_action/params_pass?q=query');
<ide> $this->assertResponseOk();
<ide> public function testGetQueryStringHttpServer()
<ide> $this->assertHeader('X-Middleware', 'true');
<ide>
<ide> $request = $this->_controller->request;
<del> $this->assertContains('/request_action/params_pass?q=query', $request->here());
<ide> $this->assertContains('/request_action/params_pass?q=query', $request->getRequestTarget());
<ide> }
<ide>
<add> /**
<add> * Test that the PSR7 requests get query string data
<add> *
<add> * @group deprecated
<add> * @return void
<add> */
<add> public function testGetQueryStringSetsHere()
<add> {
<add> $this->deprecated(function () {
<add> $this->configRequest(['headers' => ['Content-Type' => 'text/plain']]);
<add> $this->get('/request_action/params_pass?q=query');
<add> $this->assertResponseOk();
<add> $this->assertResponseContains('"q":"query"');
<add> $this->assertResponseContains('"contentType":"text\/plain"');
<add> $this->assertHeader('X-Middleware', 'true');
<add>
<add> $request = $this->_controller->request;
<add> $this->assertContains('/request_action/params_pass?q=query', $request->here());
<add> $this->assertContains('/request_action/params_pass?q=query', $request->getRequestTarget());
<add> });
<add> }
<add>
<ide> /**
<ide> * Test that the PSR7 requests get cookies
<ide> *
<ide> * @return void
<ide> */
<ide> public function testGetCookiesHttpServer()
<ide> {
<del> $this->useHttpServer(true);
<del>
<ide> $this->configRequest(['cookies' => ['split_test' => 'abc']]);
<ide> $this->get('/request_action/cookie_pass');
<ide> $this->assertResponseOk();
<ide> public function testGetCookiesHttpServer()
<ide> *
<ide> * @return void
<ide> */
<del> public function testPostDataHttpServer()
<add> public function testPostDataLegacyDispatcher()
<ide> {
<del> $this->useHttpServer(true);
<add> $this->useLegacyDispatcher();
<add>
<add> $this->deprecated(function () {
<add> $this->post('/request_action/post_pass', ['title' => 'value']);
<add> $data = json_decode($this->_response->getBody());
<add> $this->assertEquals('value', $data->title);
<add> });
<add> }
<ide>
<add> /**
<add> * Test that the PSR7 requests receive post data
<add> *
<add> * @return void
<add> */
<add> public function testPostDataHttpServer()
<add> {
<ide> $this->post('/request_action/post_pass', ['title' => 'value']);
<ide> $data = json_decode($this->_response->getBody());
<ide> $this->assertEquals('value', $data->title);
<ide> public function testPostDataHttpServer()
<ide> */
<ide> public function testInputDataHttpServer()
<ide> {
<del> $this->useHttpServer(true);
<del>
<ide> $this->post('/request_action/input_test', '{"hello":"world"}');
<ide> if ($this->_response->getBody()->isSeekable()) {
<ide> $this->_response->getBody()->rewind();
<ide> public function testInputDataHttpServer()
<ide> */
<ide> public function testInputDataSecurityToken()
<ide> {
<del> $this->useHttpServer(true);
<ide> $this->enableSecurityToken();
<ide>
<ide> $this->post('/request_action/input_test', '{"hello":"world"}');
<ide> public function testInputDataSecurityToken()
<ide> */
<ide> public function testSessionHttpServer()
<ide> {
<del> $this->useHttpServer(true);
<del>
<ide> $this->session(['foo' => 'session data']);
<ide> $this->get('/request_action/session_test');
<ide> $this->assertResponseOk();
<ide> public function testRequestSetsProperties()
<ide> */
<ide> public function testRequestSetsPropertiesHttpServer()
<ide> {
<del> $this->useHttpServer(true);
<del> DispatcherFactory::clear();
<del>
<ide> $this->post('/posts/index');
<ide> $this->assertInstanceOf('Cake\Controller\Controller', $this->_controller);
<ide> $this->assertNotEmpty($this->_viewName, 'View name not set');
<ide> public function testFlashSessionAndCookieAsserts()
<ide> */
<ide> public function testFlashSessionAndCookieAssertsHttpServer()
<ide> {
<del> $this->useHttpServer(true);
<ide> $this->post('/posts/index');
<ide>
<ide> $this->assertSession('An error message', 'Flash.flash.0.message');
<ide> public function testWithExpectedException()
<ide> public function testWithExpectedExceptionHttpServer()
<ide> {
<ide> DispatcherFactory::clear();
<del> $this->useHttpServer(true);
<ide>
<ide> $this->get('/tests_apps/throw_exception');
<ide> $this->assertResponseCode(500);
<ide> public function testRedirect()
<ide> public function testRedirectHttpServer()
<ide> {
<ide> DispatcherFactory::clear();
<del> $this->useHttpServer(true);
<ide>
<ide> $this->post('/tests_apps/redirect_to');
<ide> $this->assertResponseCode(302);
<ide> public function testAssertHeaderContains()
<ide> public function testAssertContentType()
<ide> {
<ide> $this->_response = new Response();
<del> $this->_response->type('json');
<add> $this->_response = $this->_response->withType('json');
<ide>
<ide> $this->assertContentType('json');
<ide> $this->assertContentType('application/json');
<ide> public function testSendFile()
<ide> */
<ide> public function testSendFileHttpServer()
<ide> {
<del> DispatcherFactory::clear();
<del> $this->useHttpServer(true);
<del>
<ide> $this->get('/posts/file');
<ide> $this->assertFileResponse(TEST_APP . 'TestApp' . DS . 'Controller' . DS . 'PostsController.php');
<ide> }
<ide><path>tests/test_app/TestApp/Controller/RequestActionController.php
<ide> public function param_check()
<ide> if ($this->request->getParam('0')) {
<ide> $content = 'return found';
<ide> }
<add>
<ide> return $this->response->withStringBody($content);
<ide> }
<ide> | 3 |
Javascript | Javascript | remove polyfill for helio | 6f91e54fcd8b9413643cd9fe064cb492f6a14a26 | <ide><path>examples/js/vr/HelioWebXRPolyfill.js
<ide>
<ide> if ( /(Helio)/g.test( navigator.userAgent ) && "xr" in navigator ) {
<ide>
<add> if ('isSessionSupported' in navigator.xr) {
<add> return;
<add> }
<add>
<ide> console.log( "Helio WebXR Polyfill (Lumin 0.97.0)" );
<ide>
<ide> const isHelio96 = navigator.userAgent.includes( "Chrome/73" ); | 1 |
Javascript | Javascript | close dumb terminals on control+c | a5edceea0416ad911ffdbc9b6a93eb3630d1a550 | <ide><path>lib/readline.js
<ide> function _ttyWriteDumb(s, key) {
<ide> // This readline instance is finished
<ide> this.close();
<ide> }
<add>
<add> return;
<ide> }
<ide>
<ide> switch (key.name) { | 1 |
Text | Text | fix typo for 'fundations' | 0c4b2728c8c399c3bbcd210149b044f360bb9439 | <ide><path>docs/_posts/2014-07-28-community-roundup-20.md
<ide> At the last [JSConf.us](http://2014.jsconf.us/), Vjeux talked about the design d
<ide>
<ide> ## Live Editing
<ide>
<del>The best feature of React is that it provides fundations to implement concepts that were otherwise extremely hard to like server-side rendering, undo-redo, rendering to non-DOM environments like canvas... [Dan Abramov](https://twitter.com/dan_abramov) got hot code reloading working with webpack in order to [live edit a React project](http://gaearon.github.io/react-hot-loader/)!
<add>The best feature of React is that it provides foundations to implement concepts that were otherwise extremely hard to like server-side rendering, undo-redo, rendering to non-DOM environments like canvas... [Dan Abramov](https://twitter.com/dan_abramov) got hot code reloading working with webpack in order to [live edit a React project](http://gaearon.github.io/react-hot-loader/)!
<ide>
<ide> <iframe src="//player.vimeo.com/video/100010922" width="650" height="315" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
<ide> | 1 |
Ruby | Ruby | add big sur | 8d29e79f7eb4c6169fd6b0ec2149a7bcf51be45b | <ide><path>Library/Homebrew/os/mac/version.rb
<ide> module OS
<ide> module Mac
<ide> class Version < ::Version
<ide> SYMBOLS = {
<add> big_sur: "10.16",
<ide> catalina: "10.15",
<ide> mojave: "10.14",
<ide> high_sierra: "10.13", | 1 |
Python | Python | fix the test so it works with 2.5 | 6f764a1d3ea038f037129f8eba19e7fff8abf56c | <ide><path>libcloud/test/compute/test_ec2.py
<ide> def test_instantiate_driver_valid_datacenters(self):
<ide> datacenters.remove('nimbus')
<ide>
<ide> for datacenter in datacenters:
<del> EC2NodeDriver(*EC2_PARAMS, datacenter=datacenter)
<add> EC2NodeDriver(*EC2_PARAMS, **{'datacenter': datacenter})
<ide>
<ide> def test_instantiate_driver_invalid_datacenters(self):
<ide> for datacenter in ['invalid', 'nimbus']:
<ide> try:
<del> EC2NodeDriver(*EC2_PARAMS, datacenter=datacenter)
<add> EC2NodeDriver(*EC2_PARAMS, **{'datacenter': datacenter})
<ide> except ValueError:
<ide> pass
<ide> else:
<ide> def setUp(self):
<ide> EC2MockHttp.use_param = 'Action'
<ide> EC2MockHttp.type = None
<ide>
<del> self.driver = EC2NodeDriver(*EC2_PARAMS, datacenter=self.datacenter)
<add> self.driver = EC2NodeDriver(*EC2_PARAMS,
<add> **{'datacenter': self.datacenter})
<ide>
<ide> def test_create_node(self):
<ide> image = NodeImage(id='ami-be3adfd7', | 1 |
Ruby | Ruby | fix wrong `force` keyword | 1bfd2ac0e2613b0f5ceb0d5da16c9ff512b5dd4d | <ide><path>Library/Homebrew/cmd/fetch.rb
<ide> def fetch
<ide> else
<ide> cask = formula_or_cask
<ide>
<del> options = {
<del> force: args.force?,
<del> quarantine: args.quarantine?,
<del> }.compact
<add> quarantine = args.quarantine?
<add> quarantine = true if quarantine.nil?
<ide>
<del> options[:quarantine] = true if options[:quarantine].nil?
<del>
<del> download = Cask::Download.new(cask, **options)
<add> download = Cask::Download.new(cask, quarantine: quarantine)
<ide> fetch_cask(download, args: args)
<ide> end
<ide> end | 1 |
Javascript | Javascript | improve test stability | 32a9b205aad6d6ab8e47b7fbbee946e8bb75a88d | <ide><path>test/ProgressPlugin.test.js
<ide> "use strict";
<ide>
<add>require("./helpers/warmup-webpack");
<add>
<ide> const _ = require("lodash");
<ide> const path = require("path");
<ide> const { createFsFromVolume, Volume } = require("memfs");
<ide><path>test/configCases/externals/concatenated-module/test.filter.js
<ide> module.exports = () => {
<del> return !process.version.startsWith("v10.");
<add> return (
<add> !process.version.startsWith("v10.") && !process.version.startsWith("v12.")
<add> );
<ide> }; | 2 |
Text | Text | add additional reference links | b1a89d7aaac7b4eb4e93c973cd263040cf41c5f6 | <ide><path>docs/FAQ.md
<ide> It’s generally suggested that selectors are defined alongside reducers and exp
<ide> - [Stack Overflow: How to structure Redux components/containers](http://stackoverflow.com/questions/32634320/how-to-structure-redux-components-containers/32921576)
<ide> - [Redux Best Practices](https://medium.com/lexical-labs-engineering/redux-best-practices-64d59775802e)
<ide> - [Rules For Structuring (Redux) Applications ](http://jaysoo.ca/2016/02/28/organizing-redux-application/)
<add>- [A Better File Structure for React/Redux Applications](http://marmelab.com/blog/2015/12/17/react-directory-structure.html)
<add>- [Organizing Large React Applications](http://engineering.kapost.com/2016/01/organizing-large-react-applications/)
<add>- [Four Strategies for Organizing Code](https://medium.com/@msandin/strategies-for-organizing-code-2c9d690b6f33)
<ide>
<ide> ### How should I split my logic between reducers and action creators? Where should my “business logic” go?
<ide>
<ide> As for architecture, anecdotal evidence is that Redux works well for varying pro
<ide> - [Reddit: What's the best place to keep the initial state?](https://www.reddit.com/r/reactjs/comments/47m9h5/whats_the_best_place_to_keep_the_initial_state/)
<ide> - [Reddit: Help designing Redux state for a single page app](https://www.reddit.com/r/reactjs/comments/48k852/help_designing_redux_state_for_a_single_page/)
<ide> - [Reddit: Redux performance issues with a large state object?](https://www.reddit.com/r/reactjs/comments/41wdqn/redux_performance_issues_with_a_large_state_object/)
<add>- [Reddit: React/Redux for Ultra Large Scale apps](https://www.reddit.com/r/javascript/comments/49box8/reactredux_for_ultra_large_scale_apps/)
<ide> - [Twitter: Redux scaling](https://twitter.com/NickPresta/status/684058236828266496)
<ide>
<ide> ### Won’t calling “all my reducers” for each action be slow? | 1 |
Go | Go | add isprivate method for networkmode | 080ca8619172b020c7da29b46f2fe4c939bb47ca | <ide><path>daemon/container.go
<ide> func (container *Container) buildHostnameAndHostsFiles(IP string) error {
<ide>
<ide> func (container *Container) allocateNetwork() error {
<ide> mode := container.hostConfig.NetworkMode
<del> if container.Config.NetworkDisabled || mode.IsContainer() || mode.IsHost() || mode.IsNone() {
<add> if container.Config.NetworkDisabled || !mode.IsPrivate() {
<ide> return nil
<ide> }
<ide>
<ide> func (container *Container) updateParentsHosts() error {
<ide> }
<ide>
<ide> c := container.daemon.Get(cid)
<del> if c != nil && !container.daemon.config.DisableNetwork && !container.hostConfig.NetworkMode.IsContainer() && !container.hostConfig.NetworkMode.IsHost() {
<add> if c != nil && !container.daemon.config.DisableNetwork && container.hostConfig.NetworkMode.IsPrivate() {
<ide> if err := etchosts.Update(c.HostsPath, container.NetworkSettings.IPAddress, container.Name[1:]); err != nil {
<ide> return fmt.Errorf("Failed to update /etc/hosts in parent container: %v", err)
<ide> }
<ide><path>runconfig/hostconfig.go
<ide> import (
<ide>
<ide> type NetworkMode string
<ide>
<add>// IsPrivate indicates whether container use it's private network stack
<add>func (n NetworkMode) IsPrivate() bool {
<add> return !(n.IsHost() || n.IsContainer() || n.IsNone())
<add>}
<add>
<ide> func (n NetworkMode) IsHost() bool {
<ide> return n == "host"
<ide> } | 2 |
Ruby | Ruby | remove unnecessary string evals from doctor | d9c586e201b6d5ebfd7ccfe466808a2214494c0f | <ide><path>Library/Homebrew/cmd/doctor.rb
<ide> def check_access_usr_local
<ide> end
<ide>
<ide> %w{include etc lib lib/pkgconfig share}.each do |d|
<del> class_eval <<-EOS, __FILE__, __LINE__ + 1
<del> def check_access_#{d.sub("/", "_")}
<del> if (dir = HOMEBREW_PREFIX+'#{d}').exist? && !dir.writable_real?
<del> <<-EOF.undent
<del> \#{dir} isn't writable.
<del> This can happen if you "sudo make install" software that isn't managed by
<del> by Homebrew. If a brew tries to write a file to this directory, the
<del> install will fail during the link step.
<del>
<del> You should probably `chown` \#{dir}
<del> EOF
<del> end
<add> define_method("check_access_#{d.sub("/", "_")}") do
<add> dir = HOMEBREW_PREFIX.join(d)
<add> if dir.exist? && !dir.writable_real? then <<-EOS.undent
<add> #{dir} isn't writable.
<add>
<add> This can happen if you "sudo make install" software that isn't managed by
<add> by Homebrew. If a formula tries to write a file to this directory, the
<add> install will fail during the link step.
<add>
<add> You should probably `chown` #{dir}
<add> EOS
<ide> end
<del> EOS
<add> end
<ide> end
<ide>
<ide> def check_access_logs | 1 |
PHP | PHP | remove unneeded method call | 7fc5c93f454148bae6b1e8c2b731fd3f6b01aa03 | <ide><path>src/Core/PluginCollection.php
<ide> protected function loadConfig(): void
<ide> */
<ide> public function findPath(string $name): string
<ide> {
<del> $this->loadConfig();
<del>
<ide> $path = Configure::read('plugins.' . $name);
<ide> if ($path) {
<ide> return $path; | 1 |
Python | Python | add a deprecated flag to a size | 5f2925d4739ab43906f8a1c4f8105e5f96f50347 | <ide><path>libcloud/compute/drivers/gce.py
<ide> def _to_node(self, node):
<ide> extra['tags_fingerprint'] = node['tags']['fingerprint']
<ide> extra['scheduling'] = node.get('scheduling', {})
<ide>
<add> if (machine_type.get('deprecated')):
<add> extra['deprecated'] = True
<add>
<ide> extra['boot_disk'] = None
<ide> for disk in extra['disks']:
<ide> if disk.get('boot') and disk.get('type') == 'PERSISTENT': | 1 |
Javascript | Javascript | remove other copy functions | ea7d602a0619ba2b12d81f09e2472d455f004e36 | <ide><path>examples/js/lines/LineSegmentsGeometry.js
<ide> THREE.LineSegmentsGeometry.prototype = Object.assign( Object.create( THREE.Insta
<ide>
<ide> // todo
<ide>
<del> },
<del>
<del> clone: function () {
<del>
<del> // todo
<del>
<del> },
<del>
<del> copy: function ( /* source */ ) {
<del>
<del> // todo
<del>
<del> return this;
<del>
<ide> }
<ide>
<ide> } );
<ide><path>examples/js/lines/Wireframe.js
<ide> THREE.Wireframe.prototype = Object.assign( Object.create( THREE.Mesh.prototype )
<ide>
<ide> };
<ide>
<del> }() ),
<del>
<del> copy: function ( /* source */ ) {
<del>
<del> // todo
<del>
<del> return this;
<del>
<del> }
<add> }() )
<ide>
<ide> } );
<ide><path>examples/js/lines/WireframeGeometry2.js
<ide> THREE.WireframeGeometry2.prototype = Object.assign( Object.create( THREE.LineSeg
<ide>
<ide> constructor: THREE.WireframeGeometry2,
<ide>
<del> isWireframeGeometry2: true,
<del>
<del> copy: function ( /* source */ ) {
<del>
<del> // todo
<del>
<del> return this;
<del>
<del> }
<add> isWireframeGeometry2: true
<ide>
<ide> } ); | 3 |
Ruby | Ruby | handle renames on update | 6b0927944aca1b11eec90659b11390a1575c7ff1 | <ide><path>Library/Homebrew/cmd/update.rb
<ide> require "cmd/tap"
<ide> require "formula_versions"
<add>require "migrator"
<add>require "formulary"
<ide>
<ide> module Homebrew
<ide> def update
<ide> def update
<ide>
<ide> # automatically tap any migrated formulae's new tap
<ide> report.select_formula(:D).each do |f|
<del> next unless (HOMEBREW_CELLAR/f).exist?
<add> next unless (dir = HOMEBREW_CELLAR/f).exist?
<ide> migration = TAP_MIGRATIONS[f]
<ide> next unless migration
<ide> tap_user, tap_repo = migration.split "/"
<ide> install_tap tap_user, tap_repo
<add> # update tap for each Tab
<add> tabs = dir.subdirs.each.map { |d| Tab.for_keg(Keg.new(d)) }
<add> tabs.each { |tab| tab.source["tap"] = "#{tap_user}/homebrew-#{tap_repo}" }
<add> tabs.each(&:write)
<ide> end if load_tap_migrations
<ide>
<add> # Migrate installed renamed formulae from main Homebrew repository.
<add> if load_formula_renames
<add> report.select_formula(:D).each do |oldname|
<add> newname = FORMULA_RENAMES[oldname]
<add> next unless newname
<add> next unless (dir = HOMEBREW_CELLAR/oldname).directory? && !dir.subdirs.empty?
<add>
<add> begin
<add> migrator = Migrator.new(Formulary.factory("homebrew/homebrew/#{newname}"))
<add> migrator.migrate
<add> rescue Migrator::MigratorDifferentTapsError
<add> end
<add> end
<add> end
<add>
<add> # Migrate installed renamed formulae from taps
<add> report.select_formula(:D).each do |oldname|
<add> user, repo, oldname = oldname.split("/", 3)
<add> next unless user && repo && oldname
<add> tap = Tap.new(user, repo)
<add> next unless newname = tap.formula_renames[oldname]
<add> next unless (dir = HOMEBREW_CELLAR/oldname).directory? && !dir.subdirs.empty?
<add>
<add> begin
<add> migrator = Migrator.new(Formulary.factory("#{user}/#{repo}/#{newname}"))
<add> migrator.migrate
<add> rescue Migrator::MigratorDifferentTapsError
<add> end
<add> end
<add>
<ide> if report.empty?
<ide> puts "Already up-to-date."
<ide> else
<ide> def rename_taps_dir_if_necessary
<ide> end
<ide>
<ide> def load_tap_migrations
<del> require "tap_migrations"
<add> load "tap_migrations"
<add> rescue LoadError
<add> false
<add> end
<add>
<add> def load_formula_renames
<add> load "formula_renames.rb"
<ide> rescue LoadError
<ide> false
<ide> end | 1 |
Ruby | Ruby | allow range#=== and range#cover? on range | 0fcb921a65e615c301450d7820b03473acd53898 | <ide><path>activesupport/lib/active_support/core_ext/range.rb
<ide> # frozen_string_literal: true
<ide>
<ide> require "active_support/core_ext/range/conversions"
<del>require "active_support/core_ext/range/include_range"
<add>require "active_support/core_ext/range/compare_range"
<ide> require "active_support/core_ext/range/include_time_with_zone"
<ide> require "active_support/core_ext/range/overlaps"
<ide> require "active_support/core_ext/range/each"
<ide><path>activesupport/lib/active_support/core_ext/range/compare_range.rb
<add># frozen_string_literal: true
<add>
<add>module ActiveSupport
<add> module CompareWithRange #:nodoc:
<add> # Extends the default Range#=== to support range comparisons.
<add> # (1..5) === (1..5) # => true
<add> # (1..5) === (2..3) # => true
<add> # (1..5) === (2..6) # => false
<add> #
<add> # The native Range#=== behavior is untouched.
<add> # ('a'..'f') === ('c') # => true
<add> # (5..9) === (11) # => false
<add> def ===(value)
<add> if value.is_a?(::Range)
<add> # 1...10 includes 1..9 but it does not include 1..10.
<add> operator = exclude_end? && !value.exclude_end? ? :< : :<=
<add> super(value.first) && value.last.send(operator, last)
<add> else
<add> super
<add> end
<add> end
<add>
<add> # Extends the default Range#include? to support range comparisons.
<add> # (1..5).include?(1..5) # => true
<add> # (1..5).include?(2..3) # => true
<add> # (1..5).include?(2..6) # => false
<add> #
<add> # The native Range#include? behavior is untouched.
<add> # ('a'..'f').include?('c') # => true
<add> # (5..9).include?(11) # => false
<add> def include?(value)
<add> if value.is_a?(::Range)
<add> # 1...10 includes 1..9 but it does not include 1..10.
<add> operator = exclude_end? && !value.exclude_end? ? :< : :<=
<add> super(value.first) && value.last.send(operator, last)
<add> else
<add> super
<add> end
<add> end
<add>
<add> # Extends the default Range#cover? to support range comparisons.
<add> # (1..5).cover?(1..5) # => true
<add> # (1..5).cover?(2..3) # => true
<add> # (1..5).cover?(2..6) # => false
<add> #
<add> # The native Range#cover? behavior is untouched.
<add> # ('a'..'f').cover?('c') # => true
<add> # (5..9).cover?(11) # => false
<add> def cover?(value)
<add> if value.is_a?(::Range)
<add> # 1...10 covers 1..9 but it does not cover 1..10.
<add> operator = exclude_end? && !value.exclude_end? ? :< : :<=
<add> super(value.first) && value.last.send(operator, last)
<add> else
<add> super
<add> end
<add> end
<add> end
<add>end
<add>
<add>Range.prepend(ActiveSupport::CompareWithRange)
<ide><path>activesupport/lib/active_support/core_ext/range/include_range.rb
<ide> # frozen_string_literal: true
<ide>
<del>module ActiveSupport
<del> module IncludeWithRange #:nodoc:
<del> # Extends the default Range#include? to support range comparisons.
<del> # (1..5).include?(1..5) # => true
<del> # (1..5).include?(2..3) # => true
<del> # (1..5).include?(2..6) # => false
<del> #
<del> # The native Range#include? behavior is untouched.
<del> # ('a'..'f').include?('c') # => true
<del> # (5..9).include?(11) # => false
<del> def include?(value)
<del> if value.is_a?(::Range)
<del> # 1...10 includes 1..9 but it does not include 1..10.
<del> operator = exclude_end? && !value.exclude_end? ? :< : :<=
<del> super(value.first) && value.last.send(operator, last)
<del> else
<del> super
<del> end
<del> end
<del> end
<del>end
<add>require "active_support/deprecation"
<ide>
<del>Range.prepend(ActiveSupport::IncludeWithRange)
<add>ActiveSupport::Deprecation.warn "You have required `active_support/core_ext/range/include_range`. " \
<add>"This file will be removed in Rails 6.1. You should require `active_support/core_ext/range/compare_range` " \
<add> "instead."
<add>
<add>require "active_support/core_ext/range/compare_range" | 3 |
Text | Text | add missing space in test/readme.md | aa76ce943b618c3b6d5b86c89f69aa4817ca783d | <ide><path>test/README.md
<ide> On how to run tests in this directory, see
<ide> |addons |Yes |Tests for [addon](https://nodejs.org/api/addons.html) functionality along with some tests that require an addon to function properly.|
<ide> |cctest |Yes |C++ test that is run as part of the build process.|
<ide> |common | |Common modules shared among many tests. [Documentation](./common/README.md)|
<del>|debugger |No |Tests for [debugger](https://nodejs.org/api/debugger.html)functionality along with some tests that require an addon to function properly.|
<add>|debugger |No |Tests for [debugger](https://nodejs.org/api/debugger.html) functionality along with some tests that require an addon to function properly.|
<ide> |fixtures | |Test fixtures used in various tests throughout the test suite.|
<ide> |gc |No |Tests for garbage collection related functionality.|
<ide> |inspector |Yes |Tests for the V8 inspector integration.| | 1 |
Text | Text | replace instance of var with let | 7d90b9a1796dc758b61402740975e9f5d2992ea3 | <ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/basic-javascript/global-scope-and-functions.md
<ide> function fun1() {
<ide> // Only change code above this line
<ide>
<ide> function fun2() {
<del> var output = "";
<add> let output = "";
<ide> if (typeof myGlobal != "undefined") {
<ide> output += "myGlobal: " + myGlobal;
<ide> }
<ide> function fun1() {
<ide> }
<ide>
<ide> function fun2() {
<del> var output = "";
<add> let output = "";
<ide> if(typeof myGlobal != "undefined") {
<ide> output += "myGlobal: " + myGlobal;
<ide> } | 1 |
PHP | PHP | restore error handlers | 111db16ca6bce5cd0089c760d14e161c6230a2ee | <ide><path>lib/Cake/Core/Configure.php
<ide> public static function bootstrap($boot = true) {
<ide> if (!include APP . 'Config' . DS . 'bootstrap.php') {
<ide> trigger_error(__d('cake_dev', "Can't find application bootstrap file. Please create %sbootstrap.php, and make sure it is readable by PHP.", APP . 'Config' . DS), E_USER_ERROR);
<ide> }
<add> restore_error_handler();
<add> restore_exception_handler();
<ide>
<ide> self::$_values['Error'] = $error;
<ide> self::$_values['Exception'] = $exception; | 1 |
PHP | PHP | add support for predis client options | a83dcabd2ec37359bd728faa36b9282be478c8f1 | <ide><path>src/Illuminate/Redis/Database.php
<ide> protected function createAggregateClient(array $servers)
<ide> {
<ide> $servers = array_except($servers, array('cluster'));
<ide>
<del> return array('default' => new Client(array_values($servers)));
<add> $options = $this->getClientOptions($servers);
<add>
<add> return array('default' => new Client(array_values($servers), $options));
<ide> }
<ide>
<ide> /**
<ide> protected function createSingleClients(array $servers)
<ide> {
<ide> $clients = array();
<ide>
<add> $options = $this->getClientOptions($servers);
<add>
<ide> foreach ($servers as $key => $server)
<ide> {
<del> $clients[$key] = new Client($server);
<add> $clients[$key] = new Client($server, $options);
<ide> }
<ide>
<ide> return $clients;
<ide> }
<ide>
<add> /**
<add> * Get any client options from the config array
<add> *
<add> * @param array $servers
<add> * @return array
<add> */
<add> protected function getClientOptions($servers)
<add> {
<add> $options = array();
<add>
<add> if (isset($servers['options']) && $servers['options'])
<add> {
<add> $options = $servers['options'];
<add> }
<add>
<add> return $options;
<add> }
<add>
<ide> /**
<ide> * Get a specific Redis connection instance.
<ide> * | 1 |
Java | Java | remove assertion on number of resource locations | 4df05d1f98ade553c085ebd811f806c77f090a7d | <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/ResourceHandlerRegistration.java
<ide> protected String[] getPathPatterns() {
<ide> * Returns a {@link ResourceHttpRequestHandler} instance.
<ide> */
<ide> protected ResourceHttpRequestHandler getRequestHandler() {
<del> Assert.isTrue(!CollectionUtils.isEmpty(locations), "At least one location is required for resource handling.");
<ide> ResourceHttpRequestHandler handler = new ResourceHttpRequestHandler();
<ide> if (this.resourceChainRegistration != null) {
<ide> handler.setResourceResolvers(this.resourceChainRegistration.getResourceResolvers());
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandler.java
<ide> public class ResourceHttpRequestHandler extends WebContentGenerator implements H
<ide>
<ide> private static final String CONTENT_ENCODING = "Content-Encoding";
<ide>
<del> private List<Resource> locations;
<add> private final List<Resource> locations = new ArrayList<Resource>(4);
<ide>
<del> private final List<ResourceResolver> resourceResolvers = new ArrayList<ResourceResolver>();
<add> private final List<ResourceResolver> resourceResolvers = new ArrayList<ResourceResolver>(4);
<ide>
<del> private final List<ResourceTransformer> resourceTransformers = new ArrayList<ResourceTransformer>();
<add> private final List<ResourceTransformer> resourceTransformers = new ArrayList<ResourceTransformer>(4);
<ide>
<ide>
<ide> public ResourceHttpRequestHandler() {
<ide> public ResourceHttpRequestHandler() {
<ide> */
<ide> public void setLocations(List<Resource> locations) {
<ide> Assert.notEmpty(locations, "Locations list must not be empty");
<del> this.locations = locations;
<add> this.locations.clear();
<add> this.locations.addAll(locations);
<ide> }
<ide>
<ide> public List<Resource> getLocations() {
<ide> public List<ResourceTransformer> getResourceTransformers() {
<ide> @Override
<ide> public void afterPropertiesSet() throws Exception {
<ide> if (logger.isWarnEnabled() && CollectionUtils.isEmpty(this.locations)) {
<del> logger.warn("Locations list is empty. No resources will be served");
<add> logger.warn("Locations list is empty. No resources will be served unless a " +
<add> "custom ResourceResolver is configured as an alternative to PathResourceResolver.");
<ide> }
<ide> }
<ide> | 2 |
Javascript | Javascript | remove extra slash when redirecting to client | 92d7ae172596317da64cb93c32cc3c8641e54668 | <ide><path>api-server/src/server/boot/challenge.js
<ide> import { fixCompletedChallengeItem } from '../../common/utils';
<ide> import { getChallenges } from '../utils/get-curriculum';
<ide> import {
<ide> getRedirectParams,
<del> getRedirectBase,
<del> normalizeParams
<add> normalizeParams,
<add> getPrefixedLandingPath
<ide> } from '../utils/redirection';
<ide>
<ide> const log = debug('fcc:boot:challenges');
<ide> export function createRedirectToCurrentChallenge(
<ide> const { user } = req;
<ide> const { origin, pathPrefix } = getRedirectParams(req, normalizeParams);
<ide>
<del> const redirectBase = getRedirectBase(origin, pathPrefix);
<add> const redirectBase = getPrefixedLandingPath(origin, pathPrefix);
<ide> if (!user) {
<ide> return res.redirect(redirectBase + '/learn');
<ide> }
<ide><path>api-server/src/server/component-passport.js
<ide> import passportProviders from './passport-providers';
<ide> import { setAccessTokenToResponse } from './utils/getSetAccessToken';
<ide> import {
<ide> getReturnTo,
<del> getRedirectBase,
<add> getPrefixedLandingPath,
<ide> getRedirectParams,
<del> isRootPath
<add> haveSamePath
<ide> } from './utils/redirection';
<ide> import { jwtSecret } from '../../../config/secrets';
<ide> import { availableLangs } from '../../../config/i18n/all-langs';
<ide> export const devLoginRedirect = () => {
<ide> };
<ide> }
<ide> );
<del> returnTo += isRootPath(getRedirectBase(origin, pathPrefix), returnTo)
<del> ? '/learn'
<del> : '';
<add>
<add> // if returnTo has a trailing slash, we need to remove it before comparing
<add> // it to the prefixed landing path
<add> if (returnTo.slice(-1) === '/') {
<add> returnTo = returnTo.slice(0, -1);
<add> }
<add> const redirectBase = getPrefixedLandingPath(origin, pathPrefix);
<add> returnTo += haveSamePath(redirectBase, returnTo) ? '/learn' : '';
<ide> return res.redirect(returnTo);
<ide> };
<ide> };
<ide> we recommend using your email address: ${user.email} to sign in instead.
<ide> const state = req && req.query && req.query.state;
<ide> // returnTo, origin and pathPrefix are audited by getReturnTo
<ide> let { returnTo, origin, pathPrefix } = getReturnTo(state, jwtSecret);
<del> const redirectBase = getRedirectBase(origin, pathPrefix);
<add> const redirectBase = getPrefixedLandingPath(origin, pathPrefix);
<ide>
<ide> // TODO: getReturnTo could return a success flag to show a flash message,
<ide> // but currently it immediately gets overwritten by a second message. We
<ide> // should either change the message if the flag is present or allow
<ide> // multiple messages to appear at once.
<ide>
<ide> if (user.acceptedPrivacyTerms) {
<del> returnTo += isRootPath(redirectBase, returnTo) ? '/learn' : '';
<add> // if returnTo has a trailing slash, we need to remove it before comparing
<add> // it to the prefixed landing path
<add> if (returnTo.slice(-1) === '/') {
<add> returnTo = returnTo.slice(0, -1);
<add> }
<add> returnTo += haveSamePath(redirectBase, returnTo) ? '/learn' : '';
<ide> return res.redirectWithFlash(returnTo);
<ide> } else {
<ide> return res.redirectWithFlash(`${redirectBase}/email-sign-up`);
<ide><path>api-server/src/server/utils/redirection.js
<ide> function normalizeParams(
<ide> return { returnTo, origin, pathPrefix };
<ide> }
<ide>
<del>// TODO: tests!
<del>// TODO: ensure origin and pathPrefix validation happens first
<del>// (it needs a dedicated function that can be called from here and getReturnTo)
<del>function getRedirectBase(origin, pathPrefix) {
<add>function getPrefixedLandingPath(origin, pathPrefix) {
<ide> const redirectPathSegment = pathPrefix ? `/${pathPrefix}` : '';
<ide> return `${origin}${redirectPathSegment}`;
<ide> }
<ide> function getRedirectParams(req, _normalizeParams = normalizeParams) {
<ide> return _normalizeParams({ returnTo: returnUrl.href, origin, pathPrefix });
<ide> }
<ide>
<del>function isRootPath(redirectBase, returnUrl) {
<add>function haveSamePath(redirectBase, returnUrl) {
<ide> const base = new URL(redirectBase);
<ide> const url = new URL(returnUrl);
<ide> return base.pathname === url.pathname;
<ide> }
<ide>
<ide> module.exports.getReturnTo = getReturnTo;
<del>module.exports.getRedirectBase = getRedirectBase;
<add>module.exports.getPrefixedLandingPath = getPrefixedLandingPath;
<ide> module.exports.normalizeParams = normalizeParams;
<ide> module.exports.getRedirectParams = getRedirectParams;
<del>module.exports.isRootPath = isRootPath;
<add>module.exports.haveSamePath = haveSamePath;
<ide><path>cypress/support/commands.js
<ide> Cypress.Commands.add('login', () => {
<ide> cy.visit('/');
<ide> cy.contains("Get started (it's free)").click();
<add> cy.url().should('eq', Cypress.config().baseUrl + '/learn/');
<ide> cy.contains('Welcome back');
<ide> });
<ide> | 4 |
Javascript | Javascript | fix deprecation message for limitchunkcountplugin | d88605dcbd7a67d2e7737d10e31714a11a48ca76 | <ide><path>lib/optimize/LimitChunkCountPlugin.js
<ide> class LimitChunkCountPlugin {
<ide> }
<ide>
<ide> // merge the chunks
<del> if (a.integrate(b, "limit")) {
<add> if (chunkGraph.canChunksBeIntegrated(a, b)) {
<add> chunkGraph.integrateChunks(a, b);
<ide> compilation.chunks.delete(b);
<ide>
<ide> // flag chunk a as modified as further optimization are possible for all children here
<ide> class LimitChunkCountPlugin {
<ide> continue;
<ide> }
<ide> // Update size
<del> const newIntegratedSize = a.integratedSize(
<add> const newIntegratedSize = chunkGraph.getIntegratedChunksSize(
<add> a,
<ide> combination.b,
<ide> options
<ide> );
<ide> class LimitChunkCountPlugin {
<ide> continue;
<ide> }
<ide> // Update size
<del> const newIntegratedSize = combination.a.integratedSize(
<add> const newIntegratedSize = chunkGraph.getIntegratedChunksSize(
<add> combination.a,
<ide> a,
<ide> options
<ide> );
<add>
<ide> const finishUpdate = combinations.startUpdate(combination);
<ide> combination.b = a;
<ide> combination.integratedSize = newIntegratedSize; | 1 |
Python | Python | add percpu to export module | 2f2b84b6bd75a53095ab3cd22ceaf70e34367a5c | <ide><path>glances/exports/glances_export.py
<ide> def exit(self):
<ide>
<ide> def plugins_to_export(self):
<ide> """Return the list of plugins to export"""
<del> return ['cpu', 'load', 'mem', 'memswap', 'network', 'diskio', 'fs', 'processcount']
<add> return ['cpu', 'percpu', 'load', 'mem', 'memswap', 'network', 'diskio', 'fs', 'processcount']
<ide>
<ide> def update(self, stats):
<ide> """Update stats to a server.
<ide><path>glances/plugins/glances_percpu.py
<ide> def __init__(self, args=None):
<ide> # Init stats
<ide> self.reset()
<ide>
<add> def get_key(self):
<add> """Return the key of the list"""
<add> return 'cpu_number'
<add>
<ide> def reset(self):
<ide> """Reset/init the stats."""
<ide> self.stats = []
<ide> def update(self):
<ide> if self.input_method == 'local':
<ide> percpu_percent = psutil.cpu_percent(interval=0.0, percpu=True)
<ide> percpu_times_percent = psutil.cpu_times_percent(interval=0.0, percpu=True)
<add> cpu_number = 0
<ide> for cputimes in percpu_times_percent:
<ide> for cpupercent in percpu_percent:
<del> cpu = {'total': cpupercent,
<add> cpu = {'key': self.get_key(),
<add> 'cpu_number': str(cpu_number),
<add> 'total': cpupercent,
<ide> 'user': cputimes.user,
<ide> 'system': cputimes.system,
<ide> 'idle': cputimes.idle}
<ide> def update(self):
<ide> if hasattr(cputimes, 'guest_nice'):
<ide> cpu['guest_nice'] = cputimes.guest_nice
<ide> self.stats.append(cpu)
<add> cpu_number += 1
<ide> else:
<ide> # Update stats using SNMP
<ide> pass | 2 |
Javascript | Javascript | add umd module test with marked | a63af1fd642c7f2e700dcf80320f6297e6f9c7a5 | <ide><path>test/fixtures/snapshot/check-marked.js
<add>'use strict';
<add>
<add>let marked;
<add>if (process.env.NODE_TEST_USE_SNAPSHOT === 'true') {
<add> console.error('NODE_TEST_USE_SNAPSHOT true');
<add> marked = globalThis.marked;
<add>} else {
<add> console.error('NODE_TEST_USE_SNAPSHOT false');
<add> marked = require('./marked');
<add>}
<add>
<add>const md = `
<add># heading
<add>
<add>[link][1]
<add>
<add>[1]: #heading "heading"
<add>`;
<add>
<add>const html = marked(md)
<add>console.log(html);
<ide><path>test/fixtures/snapshot/marked.js
<add>/**
<add> * marked - a markdown parser
<add> * Copyright (c) 2011-2021, Christopher Jeffrey. (MIT Licensed)
<add> * https://github.com/markedjs/marked
<add> */
<add>
<add>/**
<add> * DO NOT EDIT THIS FILE
<add> * The code in this file is generated from files in ./src/
<add> */
<add>
<add>(function (global, factory) {
<add> typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
<add> typeof define === 'function' && define.amd ? define(factory) :
<add> (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.marked = factory());
<add>}(this, (function () { 'use strict';
<add>
<add> function _defineProperties(target, props) {
<add> for (var i = 0; i < props.length; i++) {
<add> var descriptor = props[i];
<add> descriptor.enumerable = descriptor.enumerable || false;
<add> descriptor.configurable = true;
<add> if ("value" in descriptor) descriptor.writable = true;
<add> Object.defineProperty(target, descriptor.key, descriptor);
<add> }
<add> }
<add>
<add> function _createClass(Constructor, protoProps, staticProps) {
<add> if (protoProps) _defineProperties(Constructor.prototype, protoProps);
<add> if (staticProps) _defineProperties(Constructor, staticProps);
<add> return Constructor;
<add> }
<add>
<add> function _unsupportedIterableToArray(o, minLen) {
<add> if (!o) return;
<add> if (typeof o === "string") return _arrayLikeToArray(o, minLen);
<add> var n = Object.prototype.toString.call(o).slice(8, -1);
<add> if (n === "Object" && o.constructor) n = o.constructor.name;
<add> if (n === "Map" || n === "Set") return Array.from(o);
<add> if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
<add> }
<add>
<add> function _arrayLikeToArray(arr, len) {
<add> if (len == null || len > arr.length) len = arr.length;
<add>
<add> for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
<add>
<add> return arr2;
<add> }
<add>
<add> function _createForOfIteratorHelperLoose(o, allowArrayLike) {
<add> var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
<add> if (it) return (it = it.call(o)).next.bind(it);
<add>
<add> if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
<add> if (it) o = it;
<add> var i = 0;
<add> return function () {
<add> if (i >= o.length) return {
<add> done: true
<add> };
<add> return {
<add> done: false,
<add> value: o[i++]
<add> };
<add> };
<add> }
<add>
<add> throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
<add> }
<add>
<add> var defaults$5 = {exports: {}};
<add>
<add> function getDefaults$1() {
<add> return {
<add> baseUrl: null,
<add> breaks: false,
<add> extensions: null,
<add> gfm: true,
<add> headerIds: true,
<add> headerPrefix: '',
<add> highlight: null,
<add> langPrefix: 'language-',
<add> mangle: true,
<add> pedantic: false,
<add> renderer: null,
<add> sanitize: false,
<add> sanitizer: null,
<add> silent: false,
<add> smartLists: false,
<add> smartypants: false,
<add> tokenizer: null,
<add> walkTokens: null,
<add> xhtml: false
<add> };
<add> }
<add>
<add> function changeDefaults$1(newDefaults) {
<add> defaults$5.exports.defaults = newDefaults;
<add> }
<add>
<add> defaults$5.exports = {
<add> defaults: getDefaults$1(),
<add> getDefaults: getDefaults$1,
<add> changeDefaults: changeDefaults$1
<add> };
<add>
<add> /**
<add> * Helpers
<add> */
<add> var escapeTest = /[&<>"']/;
<add> var escapeReplace = /[&<>"']/g;
<add> var escapeTestNoEncode = /[<>"']|&(?!#?\w+;)/;
<add> var escapeReplaceNoEncode = /[<>"']|&(?!#?\w+;)/g;
<add> var escapeReplacements = {
<add> '&': '&',
<add> '<': '<',
<add> '>': '>',
<add> '"': '"',
<add> "'": '''
<add> };
<add>
<add> var getEscapeReplacement = function getEscapeReplacement(ch) {
<add> return escapeReplacements[ch];
<add> };
<add>
<add> function escape$2(html, encode) {
<add> if (encode) {
<add> if (escapeTest.test(html)) {
<add> return html.replace(escapeReplace, getEscapeReplacement);
<add> }
<add> } else {
<add> if (escapeTestNoEncode.test(html)) {
<add> return html.replace(escapeReplaceNoEncode, getEscapeReplacement);
<add> }
<add> }
<add>
<add> return html;
<add> }
<add>
<add> var unescapeTest = /&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig;
<add>
<add> function unescape$1(html) {
<add> // explicitly match decimal, hex, and named HTML entities
<add> return html.replace(unescapeTest, function (_, n) {
<add> n = n.toLowerCase();
<add> if (n === 'colon') return ':';
<add>
<add> if (n.charAt(0) === '#') {
<add> return n.charAt(1) === 'x' ? String.fromCharCode(parseInt(n.substring(2), 16)) : String.fromCharCode(+n.substring(1));
<add> }
<add>
<add> return '';
<add> });
<add> }
<add>
<add> var caret = /(^|[^\[])\^/g;
<add>
<add> function edit$1(regex, opt) {
<add> regex = regex.source || regex;
<add> opt = opt || '';
<add> var obj = {
<add> replace: function replace(name, val) {
<add> val = val.source || val;
<add> val = val.replace(caret, '$1');
<add> regex = regex.replace(name, val);
<add> return obj;
<add> },
<add> getRegex: function getRegex() {
<add> return new RegExp(regex, opt);
<add> }
<add> };
<add> return obj;
<add> }
<add>
<add> var nonWordAndColonTest = /[^\w:]/g;
<add> var originIndependentUrl = /^$|^[a-z][a-z0-9+.-]*:|^[?#]/i;
<add>
<add> function cleanUrl$1(sanitize, base, href) {
<add> if (sanitize) {
<add> var prot;
<add>
<add> try {
<add> prot = decodeURIComponent(unescape$1(href)).replace(nonWordAndColonTest, '').toLowerCase();
<add> } catch (e) {
<add> return null;
<add> }
<add>
<add> if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0 || prot.indexOf('data:') === 0) {
<add> return null;
<add> }
<add> }
<add>
<add> if (base && !originIndependentUrl.test(href)) {
<add> href = resolveUrl(base, href);
<add> }
<add>
<add> try {
<add> href = encodeURI(href).replace(/%25/g, '%');
<add> } catch (e) {
<add> return null;
<add> }
<add>
<add> return href;
<add> }
<add>
<add> var baseUrls = {};
<add> var justDomain = /^[^:]+:\/*[^/]*$/;
<add> var protocol = /^([^:]+:)[\s\S]*$/;
<add> var domain = /^([^:]+:\/*[^/]*)[\s\S]*$/;
<add>
<add> function resolveUrl(base, href) {
<add> if (!baseUrls[' ' + base]) {
<add> // we can ignore everything in base after the last slash of its path component,
<add> // but we might need to add _that_
<add> // https://tools.ietf.org/html/rfc3986#section-3
<add> if (justDomain.test(base)) {
<add> baseUrls[' ' + base] = base + '/';
<add> } else {
<add> baseUrls[' ' + base] = rtrim$1(base, '/', true);
<add> }
<add> }
<add>
<add> base = baseUrls[' ' + base];
<add> var relativeBase = base.indexOf(':') === -1;
<add>
<add> if (href.substring(0, 2) === '//') {
<add> if (relativeBase) {
<add> return href;
<add> }
<add>
<add> return base.replace(protocol, '$1') + href;
<add> } else if (href.charAt(0) === '/') {
<add> if (relativeBase) {
<add> return href;
<add> }
<add>
<add> return base.replace(domain, '$1') + href;
<add> } else {
<add> return base + href;
<add> }
<add> }
<add>
<add> var noopTest$1 = {
<add> exec: function noopTest() {}
<add> };
<add>
<add> function merge$2(obj) {
<add> var i = 1,
<add> target,
<add> key;
<add>
<add> for (; i < arguments.length; i++) {
<add> target = arguments[i];
<add>
<add> for (key in target) {
<add> if (Object.prototype.hasOwnProperty.call(target, key)) {
<add> obj[key] = target[key];
<add> }
<add> }
<add> }
<add>
<add> return obj;
<add> }
<add>
<add> function splitCells$1(tableRow, count) {
<add> // ensure that every cell-delimiting pipe has a space
<add> // before it to distinguish it from an escaped pipe
<add> var row = tableRow.replace(/\|/g, function (match, offset, str) {
<add> var escaped = false,
<add> curr = offset;
<add>
<add> while (--curr >= 0 && str[curr] === '\\') {
<add> escaped = !escaped;
<add> }
<add>
<add> if (escaped) {
<add> // odd number of slashes means | is escaped
<add> // so we leave it alone
<add> return '|';
<add> } else {
<add> // add space before unescaped |
<add> return ' |';
<add> }
<add> }),
<add> cells = row.split(/ \|/);
<add> var i = 0; // First/last cell in a row cannot be empty if it has no leading/trailing pipe
<add>
<add> if (!cells[0].trim()) {
<add> cells.shift();
<add> }
<add>
<add> if (!cells[cells.length - 1].trim()) {
<add> cells.pop();
<add> }
<add>
<add> if (cells.length > count) {
<add> cells.splice(count);
<add> } else {
<add> while (cells.length < count) {
<add> cells.push('');
<add> }
<add> }
<add>
<add> for (; i < cells.length; i++) {
<add> // leading or trailing whitespace is ignored per the gfm spec
<add> cells[i] = cells[i].trim().replace(/\\\|/g, '|');
<add> }
<add>
<add> return cells;
<add> } // Remove trailing 'c's. Equivalent to str.replace(/c*$/, '').
<add> // /c*$/ is vulnerable to REDOS.
<add> // invert: Remove suffix of non-c chars instead. Default falsey.
<add>
<add>
<add> function rtrim$1(str, c, invert) {
<add> var l = str.length;
<add>
<add> if (l === 0) {
<add> return '';
<add> } // Length of suffix matching the invert condition.
<add>
<add>
<add> var suffLen = 0; // Step left until we fail to match the invert condition.
<add>
<add> while (suffLen < l) {
<add> var currChar = str.charAt(l - suffLen - 1);
<add>
<add> if (currChar === c && !invert) {
<add> suffLen++;
<add> } else if (currChar !== c && invert) {
<add> suffLen++;
<add> } else {
<add> break;
<add> }
<add> }
<add>
<add> return str.substr(0, l - suffLen);
<add> }
<add>
<add> function findClosingBracket$1(str, b) {
<add> if (str.indexOf(b[1]) === -1) {
<add> return -1;
<add> }
<add>
<add> var l = str.length;
<add> var level = 0,
<add> i = 0;
<add>
<add> for (; i < l; i++) {
<add> if (str[i] === '\\') {
<add> i++;
<add> } else if (str[i] === b[0]) {
<add> level++;
<add> } else if (str[i] === b[1]) {
<add> level--;
<add>
<add> if (level < 0) {
<add> return i;
<add> }
<add> }
<add> }
<add>
<add> return -1;
<add> }
<add>
<add> function checkSanitizeDeprecation$1(opt) {
<add> if (opt && opt.sanitize && !opt.silent) {
<add> console.warn('marked(): sanitize and sanitizer parameters are deprecated since version 0.7.0, should not be used and will be removed in the future. Read more here: https://marked.js.org/#/USING_ADVANCED.md#options');
<add> }
<add> } // copied from https://stackoverflow.com/a/5450113/806777
<add>
<add>
<add> function repeatString$1(pattern, count) {
<add> if (count < 1) {
<add> return '';
<add> }
<add>
<add> var result = '';
<add>
<add> while (count > 1) {
<add> if (count & 1) {
<add> result += pattern;
<add> }
<add>
<add> count >>= 1;
<add> pattern += pattern;
<add> }
<add>
<add> return result + pattern;
<add> }
<add>
<add> var helpers = {
<add> escape: escape$2,
<add> unescape: unescape$1,
<add> edit: edit$1,
<add> cleanUrl: cleanUrl$1,
<add> resolveUrl: resolveUrl,
<add> noopTest: noopTest$1,
<add> merge: merge$2,
<add> splitCells: splitCells$1,
<add> rtrim: rtrim$1,
<add> findClosingBracket: findClosingBracket$1,
<add> checkSanitizeDeprecation: checkSanitizeDeprecation$1,
<add> repeatString: repeatString$1
<add> };
<add>
<add> var defaults$4 = defaults$5.exports.defaults;
<add> var rtrim = helpers.rtrim,
<add> splitCells = helpers.splitCells,
<add> _escape = helpers.escape,
<add> findClosingBracket = helpers.findClosingBracket;
<add>
<add> function outputLink(cap, link, raw, lexer) {
<add> var href = link.href;
<add> var title = link.title ? _escape(link.title) : null;
<add> var text = cap[1].replace(/\\([\[\]])/g, '$1');
<add>
<add> if (cap[0].charAt(0) !== '!') {
<add> lexer.state.inLink = true;
<add> var token = {
<add> type: 'link',
<add> raw: raw,
<add> href: href,
<add> title: title,
<add> text: text,
<add> tokens: lexer.inlineTokens(text, [])
<add> };
<add> lexer.state.inLink = false;
<add> return token;
<add> } else {
<add> return {
<add> type: 'image',
<add> raw: raw,
<add> href: href,
<add> title: title,
<add> text: _escape(text)
<add> };
<add> }
<add> }
<add>
<add> function indentCodeCompensation(raw, text) {
<add> var matchIndentToCode = raw.match(/^(\s+)(?:```)/);
<add>
<add> if (matchIndentToCode === null) {
<add> return text;
<add> }
<add>
<add> var indentToCode = matchIndentToCode[1];
<add> return text.split('\n').map(function (node) {
<add> var matchIndentInNode = node.match(/^\s+/);
<add>
<add> if (matchIndentInNode === null) {
<add> return node;
<add> }
<add>
<add> var indentInNode = matchIndentInNode[0];
<add>
<add> if (indentInNode.length >= indentToCode.length) {
<add> return node.slice(indentToCode.length);
<add> }
<add>
<add> return node;
<add> }).join('\n');
<add> }
<add> /**
<add> * Tokenizer
<add> */
<add>
<add>
<add> var Tokenizer_1 = /*#__PURE__*/function () {
<add> function Tokenizer(options) {
<add> this.options = options || defaults$4;
<add> }
<add>
<add> var _proto = Tokenizer.prototype;
<add>
<add> _proto.space = function space(src) {
<add> var cap = this.rules.block.newline.exec(src);
<add>
<add> if (cap) {
<add> if (cap[0].length > 1) {
<add> return {
<add> type: 'space',
<add> raw: cap[0]
<add> };
<add> }
<add>
<add> return {
<add> raw: '\n'
<add> };
<add> }
<add> };
<add>
<add> _proto.code = function code(src) {
<add> var cap = this.rules.block.code.exec(src);
<add>
<add> if (cap) {
<add> var text = cap[0].replace(/^ {1,4}/gm, '');
<add> return {
<add> type: 'code',
<add> raw: cap[0],
<add> codeBlockStyle: 'indented',
<add> text: !this.options.pedantic ? rtrim(text, '\n') : text
<add> };
<add> }
<add> };
<add>
<add> _proto.fences = function fences(src) {
<add> var cap = this.rules.block.fences.exec(src);
<add>
<add> if (cap) {
<add> var raw = cap[0];
<add> var text = indentCodeCompensation(raw, cap[3] || '');
<add> return {
<add> type: 'code',
<add> raw: raw,
<add> lang: cap[2] ? cap[2].trim() : cap[2],
<add> text: text
<add> };
<add> }
<add> };
<add>
<add> _proto.heading = function heading(src) {
<add> var cap = this.rules.block.heading.exec(src);
<add>
<add> if (cap) {
<add> var text = cap[2].trim(); // remove trailing #s
<add>
<add> if (/#$/.test(text)) {
<add> var trimmed = rtrim(text, '#');
<add>
<add> if (this.options.pedantic) {
<add> text = trimmed.trim();
<add> } else if (!trimmed || / $/.test(trimmed)) {
<add> // CommonMark requires space before trailing #s
<add> text = trimmed.trim();
<add> }
<add> }
<add>
<add> var token = {
<add> type: 'heading',
<add> raw: cap[0],
<add> depth: cap[1].length,
<add> text: text,
<add> tokens: []
<add> };
<add> this.lexer.inline(token.text, token.tokens);
<add> return token;
<add> }
<add> };
<add>
<add> _proto.hr = function hr(src) {
<add> var cap = this.rules.block.hr.exec(src);
<add>
<add> if (cap) {
<add> return {
<add> type: 'hr',
<add> raw: cap[0]
<add> };
<add> }
<add> };
<add>
<add> _proto.blockquote = function blockquote(src) {
<add> var cap = this.rules.block.blockquote.exec(src);
<add>
<add> if (cap) {
<add> var text = cap[0].replace(/^ *> ?/gm, '');
<add> return {
<add> type: 'blockquote',
<add> raw: cap[0],
<add> tokens: this.lexer.blockTokens(text, []),
<add> text: text
<add> };
<add> }
<add> };
<add>
<add> _proto.list = function list(src) {
<add> var cap = this.rules.block.list.exec(src);
<add>
<add> if (cap) {
<add> var raw, istask, ischecked, indent, i, blankLine, endsWithBlankLine, line, lines, itemContents;
<add> var bull = cap[1].trim();
<add> var isordered = bull.length > 1;
<add> var list = {
<add> type: 'list',
<add> raw: '',
<add> ordered: isordered,
<add> start: isordered ? +bull.slice(0, -1) : '',
<add> loose: false,
<add> items: []
<add> };
<add> bull = isordered ? "\\d{1,9}\\" + bull.slice(-1) : "\\" + bull;
<add>
<add> if (this.options.pedantic) {
<add> bull = isordered ? bull : '[*+-]';
<add> } // Get next list item
<add>
<add>
<add> var itemRegex = new RegExp("^( {0,3}" + bull + ")((?: [^\\n]*| *)(?:\\n[^\\n]*)*(?:\\n|$))"); // Get each top-level item
<add>
<add> while (src) {
<add> if (this.rules.block.hr.test(src)) {
<add> // End list if we encounter an HR (possibly move into itemRegex?)
<add> break;
<add> }
<add>
<add> if (!(cap = itemRegex.exec(src))) {
<add> break;
<add> }
<add>
<add> lines = cap[2].split('\n');
<add>
<add> if (this.options.pedantic) {
<add> indent = 2;
<add> itemContents = lines[0].trimLeft();
<add> } else {
<add> indent = cap[2].search(/[^ ]/); // Find first non-space char
<add>
<add> indent = cap[1].length + (indent > 4 ? 1 : indent); // intented code blocks after 4 spaces; indent is always 1
<add>
<add> itemContents = lines[0].slice(indent - cap[1].length);
<add> }
<add>
<add> blankLine = false;
<add> raw = cap[0];
<add>
<add> if (!lines[0] && /^ *$/.test(lines[1])) {
<add> // items begin with at most one blank line
<add> raw = cap[1] + lines.slice(0, 2).join('\n') + '\n';
<add> list.loose = true;
<add> lines = [];
<add> }
<add>
<add> var nextBulletRegex = new RegExp("^ {0," + Math.min(3, indent - 1) + "}(?:[*+-]|\\d{1,9}[.)])");
<add>
<add> for (i = 1; i < lines.length; i++) {
<add> line = lines[i];
<add>
<add> if (this.options.pedantic) {
<add> // Re-align to follow commonmark nesting rules
<add> line = line.replace(/^ {1,4}(?=( {4})*[^ ])/g, ' ');
<add> } // End list item if found start of new bullet
<add>
<add>
<add> if (nextBulletRegex.test(line)) {
<add> raw = cap[1] + lines.slice(0, i).join('\n') + '\n';
<add> break;
<add> } // Until we encounter a blank line, item contents do not need indentation
<add>
<add>
<add> if (!blankLine) {
<add> if (!line.trim()) {
<add> // Check if current line is empty
<add> blankLine = true;
<add> } // Dedent if possible
<add>
<add>
<add> if (line.search(/[^ ]/) >= indent) {
<add> itemContents += '\n' + line.slice(indent);
<add> } else {
<add> itemContents += '\n' + line;
<add> }
<add>
<add> continue;
<add> } // Dedent this line
<add>
<add>
<add> if (line.search(/[^ ]/) >= indent || !line.trim()) {
<add> itemContents += '\n' + line.slice(indent);
<add> continue;
<add> } else {
<add> // Line was not properly indented; end of this item
<add> raw = cap[1] + lines.slice(0, i).join('\n') + '\n';
<add> break;
<add> }
<add> }
<add>
<add> if (!list.loose) {
<add> // If the previous item ended with a blank line, the list is loose
<add> if (endsWithBlankLine) {
<add> list.loose = true;
<add> } else if (/\n *\n *$/.test(raw)) {
<add> endsWithBlankLine = true;
<add> }
<add> } // Check for task list items
<add>
<add>
<add> if (this.options.gfm) {
<add> istask = /^\[[ xX]\] /.exec(itemContents);
<add>
<add> if (istask) {
<add> ischecked = istask[0] !== '[ ] ';
<add> itemContents = itemContents.replace(/^\[[ xX]\] +/, '');
<add> }
<add> }
<add>
<add> list.items.push({
<add> type: 'list_item',
<add> raw: raw,
<add> task: !!istask,
<add> checked: ischecked,
<add> loose: false,
<add> text: itemContents
<add> });
<add> list.raw += raw;
<add> src = src.slice(raw.length);
<add> } // Do not consume newlines at end of final item. Alternatively, make itemRegex *start* with any newlines to simplify/speed up endsWithBlankLine logic
<add>
<add>
<add> list.items[list.items.length - 1].raw = raw.trimRight();
<add> list.items[list.items.length - 1].text = itemContents.trimRight();
<add> list.raw = list.raw.trimRight();
<add> var l = list.items.length; // Item child tokens handled here at end because we needed to have the final item to trim it first
<add>
<add> for (i = 0; i < l; i++) {
<add> this.lexer.state.top = false;
<add> list.items[i].tokens = this.lexer.blockTokens(list.items[i].text, []);
<add>
<add> if (list.items[i].tokens.some(function (t) {
<add> return t.type === 'space';
<add> })) {
<add> list.loose = true;
<add> list.items[i].loose = true;
<add> }
<add> }
<add>
<add> return list;
<add> }
<add> };
<add>
<add> _proto.html = function html(src) {
<add> var cap = this.rules.block.html.exec(src);
<add>
<add> if (cap) {
<add> var token = {
<add> type: 'html',
<add> raw: cap[0],
<add> pre: !this.options.sanitizer && (cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style'),
<add> text: cap[0]
<add> };
<add>
<add> if (this.options.sanitize) {
<add> token.type = 'paragraph';
<add> token.text = this.options.sanitizer ? this.options.sanitizer(cap[0]) : _escape(cap[0]);
<add> token.tokens = [];
<add> this.lexer.inline(token.text, token.tokens);
<add> }
<add>
<add> return token;
<add> }
<add> };
<add>
<add> _proto.def = function def(src) {
<add> var cap = this.rules.block.def.exec(src);
<add>
<add> if (cap) {
<add> if (cap[3]) cap[3] = cap[3].substring(1, cap[3].length - 1);
<add> var tag = cap[1].toLowerCase().replace(/\s+/g, ' ');
<add> return {
<add> type: 'def',
<add> tag: tag,
<add> raw: cap[0],
<add> href: cap[2],
<add> title: cap[3]
<add> };
<add> }
<add> };
<add>
<add> _proto.table = function table(src) {
<add> var cap = this.rules.block.table.exec(src);
<add>
<add> if (cap) {
<add> var item = {
<add> type: 'table',
<add> header: splitCells(cap[1]).map(function (c) {
<add> return {
<add> text: c
<add> };
<add> }),
<add> align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
<add> rows: cap[3] ? cap[3].replace(/\n$/, '').split('\n') : []
<add> };
<add>
<add> if (item.header.length === item.align.length) {
<add> item.raw = cap[0];
<add> var l = item.align.length;
<add> var i, j, k, row;
<add>
<add> for (i = 0; i < l; i++) {
<add> if (/^ *-+: *$/.test(item.align[i])) {
<add> item.align[i] = 'right';
<add> } else if (/^ *:-+: *$/.test(item.align[i])) {
<add> item.align[i] = 'center';
<add> } else if (/^ *:-+ *$/.test(item.align[i])) {
<add> item.align[i] = 'left';
<add> } else {
<add> item.align[i] = null;
<add> }
<add> }
<add>
<add> l = item.rows.length;
<add>
<add> for (i = 0; i < l; i++) {
<add> item.rows[i] = splitCells(item.rows[i], item.header.length).map(function (c) {
<add> return {
<add> text: c
<add> };
<add> });
<add> } // parse child tokens inside headers and cells
<add> // header child tokens
<add>
<add>
<add> l = item.header.length;
<add>
<add> for (j = 0; j < l; j++) {
<add> item.header[j].tokens = [];
<add> this.lexer.inlineTokens(item.header[j].text, item.header[j].tokens);
<add> } // cell child tokens
<add>
<add>
<add> l = item.rows.length;
<add>
<add> for (j = 0; j < l; j++) {
<add> row = item.rows[j];
<add>
<add> for (k = 0; k < row.length; k++) {
<add> row[k].tokens = [];
<add> this.lexer.inlineTokens(row[k].text, row[k].tokens);
<add> }
<add> }
<add>
<add> return item;
<add> }
<add> }
<add> };
<add>
<add> _proto.lheading = function lheading(src) {
<add> var cap = this.rules.block.lheading.exec(src);
<add>
<add> if (cap) {
<add> var token = {
<add> type: 'heading',
<add> raw: cap[0],
<add> depth: cap[2].charAt(0) === '=' ? 1 : 2,
<add> text: cap[1],
<add> tokens: []
<add> };
<add> this.lexer.inline(token.text, token.tokens);
<add> return token;
<add> }
<add> };
<add>
<add> _proto.paragraph = function paragraph(src) {
<add> var cap = this.rules.block.paragraph.exec(src);
<add>
<add> if (cap) {
<add> var token = {
<add> type: 'paragraph',
<add> raw: cap[0],
<add> text: cap[1].charAt(cap[1].length - 1) === '\n' ? cap[1].slice(0, -1) : cap[1],
<add> tokens: []
<add> };
<add> this.lexer.inline(token.text, token.tokens);
<add> return token;
<add> }
<add> };
<add>
<add> _proto.text = function text(src) {
<add> var cap = this.rules.block.text.exec(src);
<add>
<add> if (cap) {
<add> var token = {
<add> type: 'text',
<add> raw: cap[0],
<add> text: cap[0],
<add> tokens: []
<add> };
<add> this.lexer.inline(token.text, token.tokens);
<add> return token;
<add> }
<add> };
<add>
<add> _proto.escape = function escape(src) {
<add> var cap = this.rules.inline.escape.exec(src);
<add>
<add> if (cap) {
<add> return {
<add> type: 'escape',
<add> raw: cap[0],
<add> text: _escape(cap[1])
<add> };
<add> }
<add> };
<add>
<add> _proto.tag = function tag(src) {
<add> var cap = this.rules.inline.tag.exec(src);
<add>
<add> if (cap) {
<add> if (!this.lexer.state.inLink && /^<a /i.test(cap[0])) {
<add> this.lexer.state.inLink = true;
<add> } else if (this.lexer.state.inLink && /^<\/a>/i.test(cap[0])) {
<add> this.lexer.state.inLink = false;
<add> }
<add>
<add> if (!this.lexer.state.inRawBlock && /^<(pre|code|kbd|script)(\s|>)/i.test(cap[0])) {
<add> this.lexer.state.inRawBlock = true;
<add> } else if (this.lexer.state.inRawBlock && /^<\/(pre|code|kbd|script)(\s|>)/i.test(cap[0])) {
<add> this.lexer.state.inRawBlock = false;
<add> }
<add>
<add> return {
<add> type: this.options.sanitize ? 'text' : 'html',
<add> raw: cap[0],
<add> inLink: this.lexer.state.inLink,
<add> inRawBlock: this.lexer.state.inRawBlock,
<add> text: this.options.sanitize ? this.options.sanitizer ? this.options.sanitizer(cap[0]) : _escape(cap[0]) : cap[0]
<add> };
<add> }
<add> };
<add>
<add> _proto.link = function link(src) {
<add> var cap = this.rules.inline.link.exec(src);
<add>
<add> if (cap) {
<add> var trimmedUrl = cap[2].trim();
<add>
<add> if (!this.options.pedantic && /^</.test(trimmedUrl)) {
<add> // commonmark requires matching angle brackets
<add> if (!/>$/.test(trimmedUrl)) {
<add> return;
<add> } // ending angle bracket cannot be escaped
<add>
<add>
<add> var rtrimSlash = rtrim(trimmedUrl.slice(0, -1), '\\');
<add>
<add> if ((trimmedUrl.length - rtrimSlash.length) % 2 === 0) {
<add> return;
<add> }
<add> } else {
<add> // find closing parenthesis
<add> var lastParenIndex = findClosingBracket(cap[2], '()');
<add>
<add> if (lastParenIndex > -1) {
<add> var start = cap[0].indexOf('!') === 0 ? 5 : 4;
<add> var linkLen = start + cap[1].length + lastParenIndex;
<add> cap[2] = cap[2].substring(0, lastParenIndex);
<add> cap[0] = cap[0].substring(0, linkLen).trim();
<add> cap[3] = '';
<add> }
<add> }
<add>
<add> var href = cap[2];
<add> var title = '';
<add>
<add> if (this.options.pedantic) {
<add> // split pedantic href and title
<add> var link = /^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(href);
<add>
<add> if (link) {
<add> href = link[1];
<add> title = link[3];
<add> }
<add> } else {
<add> title = cap[3] ? cap[3].slice(1, -1) : '';
<add> }
<add>
<add> href = href.trim();
<add>
<add> if (/^</.test(href)) {
<add> if (this.options.pedantic && !/>$/.test(trimmedUrl)) {
<add> // pedantic allows starting angle bracket without ending angle bracket
<add> href = href.slice(1);
<add> } else {
<add> href = href.slice(1, -1);
<add> }
<add> }
<add>
<add> return outputLink(cap, {
<add> href: href ? href.replace(this.rules.inline._escapes, '$1') : href,
<add> title: title ? title.replace(this.rules.inline._escapes, '$1') : title
<add> }, cap[0], this.lexer);
<add> }
<add> };
<add>
<add> _proto.reflink = function reflink(src, links) {
<add> var cap;
<add>
<add> if ((cap = this.rules.inline.reflink.exec(src)) || (cap = this.rules.inline.nolink.exec(src))) {
<add> var link = (cap[2] || cap[1]).replace(/\s+/g, ' ');
<add> link = links[link.toLowerCase()];
<add>
<add> if (!link || !link.href) {
<add> var text = cap[0].charAt(0);
<add> return {
<add> type: 'text',
<add> raw: text,
<add> text: text
<add> };
<add> }
<add>
<add> return outputLink(cap, link, cap[0], this.lexer);
<add> }
<add> };
<add>
<add> _proto.emStrong = function emStrong(src, maskedSrc, prevChar) {
<add> if (prevChar === void 0) {
<add> prevChar = '';
<add> }
<add>
<add> var match = this.rules.inline.emStrong.lDelim.exec(src);
<add> if (!match) return; // _ can't be between two alphanumerics. \p{L}\p{N} includes non-english alphabet/numbers as well
<add>
<add> if (match[3] && prevChar.match(/(?:[0-9A-Za-z\xAA\xB2\xB3\xB5\xB9\xBA\xBC-\xBE\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u0660-\u0669\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07C0-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08C7\u0904-\u0939\u093D\u0950\u0958-\u0961\u0966-\u096F\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09E6-\u09F1\u09F4-\u09F9\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A66-\u0A6F\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AE6-\u0AEF\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B66-\u0B6F\u0B71-\u0B77\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0BE6-\u0BF2\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C66-\u0C6F\u0C78-\u0C7E\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CE6-\u0CEF\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D58-\u0D61\u0D66-\u0D78\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DE6-\u0DEF\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F20-\u0F33\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F-\u1049\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u1090-\u1099\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1369-\u137C\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u17E0-\u17E9\u17F0-\u17F9\u1810-\u1819\u1820-\u1878\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A16\u1A20-\u1A54\u1A80-\u1A89\u1A90-\u1A99\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B50-\u1B59\u1B83-\u1BA0\u1BAE-\u1BE5\u1C00-\u1C23\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2070\u2071\u2074-\u2079\u207F-\u2089\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2150-\u2189\u2460-\u249B\u24EA-\u24FF\u2776-\u2793\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2CFD\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u3192-\u3195\u31A0-\u31BF\u31F0-\u31FF\u3220-\u3229\u3248-\u324F\u3251-\u325F\u3280-\u3289\u32B1-\u32BF\u3400-\u4DBF\u4E00-\u9FFC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7BF\uA7C2-\uA7CA\uA7F5-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA830-\uA835\uA840-\uA873\uA882-\uA8B3\uA8D0-\uA8D9\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA900-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF-\uA9D9\uA9E0-\uA9E4\uA9E6-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA50-\uAA59\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD07-\uDD33\uDD40-\uDD78\uDD8A\uDD8B\uDE80-\uDE9C\uDEA0-\uDED0\uDEE1-\uDEFB\uDF00-\uDF23\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC58-\uDC76\uDC79-\uDC9E\uDCA7-\uDCAF\uDCE0-\uDCF2\uDCF4\uDCF5\uDCFB-\uDD1B\uDD20-\uDD39\uDD80-\uDDB7\uDDBC-\uDDCF\uDDD2-\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE35\uDE40-\uDE48\uDE60-\uDE7E\uDE80-\uDE9F\uDEC0-\uDEC7\uDEC9-\uDEE4\uDEEB-\uDEEF\uDF00-\uDF35\uDF40-\uDF55\uDF58-\uDF72\uDF78-\uDF91\uDFA9-\uDFAF]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2\uDCFA-\uDD23\uDD30-\uDD39\uDE60-\uDE7E\uDE80-\uDEA9\uDEB0\uDEB1\uDF00-\uDF27\uDF30-\uDF45\uDF51-\uDF54\uDFB0-\uDFCB\uDFE0-\uDFF6]|\uD804[\uDC03-\uDC37\uDC52-\uDC6F\uDC83-\uDCAF\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD03-\uDD26\uDD36-\uDD3F\uDD44\uDD47\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDD0-\uDDDA\uDDDC\uDDE1-\uDDF4\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDEF0-\uDEF9\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC50-\uDC59\uDC5F-\uDC61\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE50-\uDE59\uDE80-\uDEAA\uDEB8\uDEC0-\uDEC9\uDF00-\uDF1A\uDF30-\uDF3B]|\uD806[\uDC00-\uDC2B\uDCA0-\uDCF2\uDCFF-\uDD06\uDD09\uDD0C-\uDD13\uDD15\uDD16\uDD18-\uDD2F\uDD3F\uDD41\uDD50-\uDD59\uDDA0-\uDDA7\uDDAA-\uDDD0\uDDE1\uDDE3\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE89\uDE9D\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC50-\uDC6C\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46\uDD50-\uDD59\uDD60-\uDD65\uDD67\uDD68\uDD6A-\uDD89\uDD98\uDDA0-\uDDA9\uDEE0-\uDEF2\uDFB0\uDFC0-\uDFD4]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD822\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879\uD880-\uD883][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF50-\uDF59\uDF5B-\uDF61\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDE40-\uDE96\uDF00-\uDF4A\uDF50\uDF93-\uDF9F\uDFE0\uDFE1\uDFE3]|\uD821[\uDC00-\uDFF7]|\uD823[\uDC00-\uDCD5\uDD00-\uDD08]|\uD82C[\uDC00-\uDD1E\uDD50-\uDD52\uDD64-\uDD67\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD834[\uDEE0-\uDEF3\uDF60-\uDF78]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD838[\uDD00-\uDD2C\uDD37-\uDD3D\uDD40-\uDD49\uDD4E\uDEC0-\uDEEB\uDEF0-\uDEF9]|\uD83A[\uDC00-\uDCC4\uDCC7-\uDCCF\uDD00-\uDD43\uDD4B\uDD50-\uDD59]|\uD83B[\uDC71-\uDCAB\uDCAD-\uDCAF\uDCB1-\uDCB4\uDD01-\uDD2D\uDD2F-\uDD3D\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD83C[\uDD00-\uDD0C]|\uD83E[\uDFF0-\uDFF9]|\uD869[\uDC00-\uDEDD\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uD884[\uDC00-\uDF4A])/)) return;
<add> var nextChar = match[1] || match[2] || '';
<add>
<add> if (!nextChar || nextChar && (prevChar === '' || this.rules.inline.punctuation.exec(prevChar))) {
<add> var lLength = match[0].length - 1;
<add> var rDelim,
<add> rLength,
<add> delimTotal = lLength,
<add> midDelimTotal = 0;
<add> var endReg = match[0][0] === '*' ? this.rules.inline.emStrong.rDelimAst : this.rules.inline.emStrong.rDelimUnd;
<add> endReg.lastIndex = 0; // Clip maskedSrc to same section of string as src (move to lexer?)
<add>
<add> maskedSrc = maskedSrc.slice(-1 * src.length + lLength);
<add>
<add> while ((match = endReg.exec(maskedSrc)) != null) {
<add> rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6];
<add> if (!rDelim) continue; // skip single * in __abc*abc__
<add>
<add> rLength = rDelim.length;
<add>
<add> if (match[3] || match[4]) {
<add> // found another Left Delim
<add> delimTotal += rLength;
<add> continue;
<add> } else if (match[5] || match[6]) {
<add> // either Left or Right Delim
<add> if (lLength % 3 && !((lLength + rLength) % 3)) {
<add> midDelimTotal += rLength;
<add> continue; // CommonMark Emphasis Rules 9-10
<add> }
<add> }
<add>
<add> delimTotal -= rLength;
<add> if (delimTotal > 0) continue; // Haven't found enough closing delimiters
<add> // Remove extra characters. *a*** -> *a*
<add>
<add> rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal); // Create `em` if smallest delimiter has odd char count. *a***
<add>
<add> if (Math.min(lLength, rLength) % 2) {
<add> var _text = src.slice(1, lLength + match.index + rLength);
<add>
<add> return {
<add> type: 'em',
<add> raw: src.slice(0, lLength + match.index + rLength + 1),
<add> text: _text,
<add> tokens: this.lexer.inlineTokens(_text, [])
<add> };
<add> } // Create 'strong' if smallest delimiter has even char count. **a***
<add>
<add>
<add> var text = src.slice(2, lLength + match.index + rLength - 1);
<add> return {
<add> type: 'strong',
<add> raw: src.slice(0, lLength + match.index + rLength + 1),
<add> text: text,
<add> tokens: this.lexer.inlineTokens(text, [])
<add> };
<add> }
<add> }
<add> };
<add>
<add> _proto.codespan = function codespan(src) {
<add> var cap = this.rules.inline.code.exec(src);
<add>
<add> if (cap) {
<add> var text = cap[2].replace(/\n/g, ' ');
<add> var hasNonSpaceChars = /[^ ]/.test(text);
<add> var hasSpaceCharsOnBothEnds = /^ /.test(text) && / $/.test(text);
<add>
<add> if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) {
<add> text = text.substring(1, text.length - 1);
<add> }
<add>
<add> text = _escape(text, true);
<add> return {
<add> type: 'codespan',
<add> raw: cap[0],
<add> text: text
<add> };
<add> }
<add> };
<add>
<add> _proto.br = function br(src) {
<add> var cap = this.rules.inline.br.exec(src);
<add>
<add> if (cap) {
<add> return {
<add> type: 'br',
<add> raw: cap[0]
<add> };
<add> }
<add> };
<add>
<add> _proto.del = function del(src) {
<add> var cap = this.rules.inline.del.exec(src);
<add>
<add> if (cap) {
<add> return {
<add> type: 'del',
<add> raw: cap[0],
<add> text: cap[2],
<add> tokens: this.lexer.inlineTokens(cap[2], [])
<add> };
<add> }
<add> };
<add>
<add> _proto.autolink = function autolink(src, mangle) {
<add> var cap = this.rules.inline.autolink.exec(src);
<add>
<add> if (cap) {
<add> var text, href;
<add>
<add> if (cap[2] === '@') {
<add> text = _escape(this.options.mangle ? mangle(cap[1]) : cap[1]);
<add> href = 'mailto:' + text;
<add> } else {
<add> text = _escape(cap[1]);
<add> href = text;
<add> }
<add>
<add> return {
<add> type: 'link',
<add> raw: cap[0],
<add> text: text,
<add> href: href,
<add> tokens: [{
<add> type: 'text',
<add> raw: text,
<add> text: text
<add> }]
<add> };
<add> }
<add> };
<add>
<add> _proto.url = function url(src, mangle) {
<add> var cap;
<add>
<add> if (cap = this.rules.inline.url.exec(src)) {
<add> var text, href;
<add>
<add> if (cap[2] === '@') {
<add> text = _escape(this.options.mangle ? mangle(cap[0]) : cap[0]);
<add> href = 'mailto:' + text;
<add> } else {
<add> // do extended autolink path validation
<add> var prevCapZero;
<add>
<add> do {
<add> prevCapZero = cap[0];
<add> cap[0] = this.rules.inline._backpedal.exec(cap[0])[0];
<add> } while (prevCapZero !== cap[0]);
<add>
<add> text = _escape(cap[0]);
<add>
<add> if (cap[1] === 'www.') {
<add> href = 'http://' + text;
<add> } else {
<add> href = text;
<add> }
<add> }
<add>
<add> return {
<add> type: 'link',
<add> raw: cap[0],
<add> text: text,
<add> href: href,
<add> tokens: [{
<add> type: 'text',
<add> raw: text,
<add> text: text
<add> }]
<add> };
<add> }
<add> };
<add>
<add> _proto.inlineText = function inlineText(src, smartypants) {
<add> var cap = this.rules.inline.text.exec(src);
<add>
<add> if (cap) {
<add> var text;
<add>
<add> if (this.lexer.state.inRawBlock) {
<add> text = this.options.sanitize ? this.options.sanitizer ? this.options.sanitizer(cap[0]) : _escape(cap[0]) : cap[0];
<add> } else {
<add> text = _escape(this.options.smartypants ? smartypants(cap[0]) : cap[0]);
<add> }
<add>
<add> return {
<add> type: 'text',
<add> raw: cap[0],
<add> text: text
<add> };
<add> }
<add> };
<add>
<add> return Tokenizer;
<add> }();
<add>
<add> var noopTest = helpers.noopTest,
<add> edit = helpers.edit,
<add> merge$1 = helpers.merge;
<add> /**
<add> * Block-Level Grammar
<add> */
<add>
<add> var block$1 = {
<add> newline: /^(?: *(?:\n|$))+/,
<add> code: /^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,
<add> fences: /^ {0,3}(`{3,}(?=[^`\n]*\n)|~{3,})([^\n]*)\n(?:|([\s\S]*?)\n)(?: {0,3}\1[~`]* *(?=\n|$)|$)/,
<add> hr: /^ {0,3}((?:- *){3,}|(?:_ *){3,}|(?:\* *){3,})(?:\n+|$)/,
<add> heading: /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,
<add> blockquote: /^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/,
<add> list: /^( {0,3}bull)( [^\n]+?)?(?:\n|$)/,
<add> html: '^ {0,3}(?:' // optional indentation
<add> + '<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)' // (1)
<add> + '|comment[^\\n]*(\\n+|$)' // (2)
<add> + '|<\\?[\\s\\S]*?(?:\\?>\\n*|$)' // (3)
<add> + '|<![A-Z][\\s\\S]*?(?:>\\n*|$)' // (4)
<add> + '|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)' // (5)
<add> + '|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n *)+\\n|$)' // (6)
<add> + '|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)' // (7) open tag
<add> + '|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)' // (7) closing tag
<add> + ')',
<add> def: /^ {0,3}\[(label)\]: *\n? *<?([^\s>]+)>?(?:(?: +\n? *| *\n *)(title))? *(?:\n+|$)/,
<add> table: noopTest,
<add> lheading: /^([^\n]+)\n {0,3}(=+|-+) *(?:\n+|$)/,
<add> // regex template, placeholders will be replaced according to different paragraph
<add> // interruption rules of commonmark and the original markdown spec:
<add> _paragraph: /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html| +\n)[^\n]+)*)/,
<add> text: /^[^\n]+/
<add> };
<add> block$1._label = /(?!\s*\])(?:\\[\[\]]|[^\[\]])+/;
<add> block$1._title = /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/;
<add> block$1.def = edit(block$1.def).replace('label', block$1._label).replace('title', block$1._title).getRegex();
<add> block$1.bullet = /(?:[*+-]|\d{1,9}[.)])/;
<add> block$1.listItemStart = edit(/^( *)(bull) */).replace('bull', block$1.bullet).getRegex();
<add> block$1.list = edit(block$1.list).replace(/bull/g, block$1.bullet).replace('hr', '\\n+(?=\\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$))').replace('def', '\\n+(?=' + block$1.def.source + ')').getRegex();
<add> block$1._tag = 'address|article|aside|base|basefont|blockquote|body|caption' + '|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption' + '|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe' + '|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option' + '|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr' + '|track|ul';
<add> block$1._comment = /<!--(?!-?>)[\s\S]*?(?:-->|$)/;
<add> block$1.html = edit(block$1.html, 'i').replace('comment', block$1._comment).replace('tag', block$1._tag).replace('attribute', / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex();
<add> block$1.paragraph = edit(block$1._paragraph).replace('hr', block$1.hr).replace('heading', ' {0,3}#{1,6} ').replace('|lheading', '') // setex headings don't interrupt commonmark paragraphs
<add> .replace('blockquote', ' {0,3}>').replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n').replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt
<add> .replace('html', '</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)').replace('tag', block$1._tag) // pars can be interrupted by type (6) html blocks
<add> .getRegex();
<add> block$1.blockquote = edit(block$1.blockquote).replace('paragraph', block$1.paragraph).getRegex();
<add> /**
<add> * Normal Block Grammar
<add> */
<add>
<add> block$1.normal = merge$1({}, block$1);
<add> /**
<add> * GFM Block Grammar
<add> */
<add>
<add> block$1.gfm = merge$1({}, block$1.normal, {
<add> table: '^ *([^\\n ].*\\|.*)\\n' // Header
<add> + ' {0,3}(?:\\| *)?(:?-+:? *(?:\\| *:?-+:? *)*)(?:\\| *)?' // Align
<add> + '(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)' // Cells
<add>
<add> });
<add> block$1.gfm.table = edit(block$1.gfm.table).replace('hr', block$1.hr).replace('heading', ' {0,3}#{1,6} ').replace('blockquote', ' {0,3}>').replace('code', ' {4}[^\\n]').replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n').replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt
<add> .replace('html', '</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)').replace('tag', block$1._tag) // tables can be interrupted by type (6) html blocks
<add> .getRegex();
<add> /**
<add> * Pedantic grammar (original John Gruber's loose markdown specification)
<add> */
<add>
<add> block$1.pedantic = merge$1({}, block$1.normal, {
<add> html: edit('^ *(?:comment *(?:\\n|\\s*$)' + '|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)' // closed tag
<add> + '|<tag(?:"[^"]*"|\'[^\']*\'|\\s[^\'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))').replace('comment', block$1._comment).replace(/tag/g, '(?!(?:' + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub' + '|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)' + '\\b)\\w+(?!:|[^\\w\\s@]*@)\\b').getRegex(),
<add> def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,
<add> heading: /^(#{1,6})(.*)(?:\n+|$)/,
<add> fences: noopTest,
<add> // fences not supported
<add> paragraph: edit(block$1.normal._paragraph).replace('hr', block$1.hr).replace('heading', ' *#{1,6} *[^\n]').replace('lheading', block$1.lheading).replace('blockquote', ' {0,3}>').replace('|fences', '').replace('|list', '').replace('|html', '').getRegex()
<add> });
<add> /**
<add> * Inline-Level Grammar
<add> */
<add>
<add> var inline$1 = {
<add> escape: /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,
<add> autolink: /^<(scheme:[^\s\x00-\x1f<>]*|email)>/,
<add> url: noopTest,
<add> tag: '^comment' + '|^</[a-zA-Z][\\w:-]*\\s*>' // self-closing tag
<add> + '|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>' // open tag
<add> + '|^<\\?[\\s\\S]*?\\?>' // processing instruction, e.g. <?php ?>
<add> + '|^<![a-zA-Z]+\\s[\\s\\S]*?>' // declaration, e.g. <!DOCTYPE html>
<add> + '|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>',
<add> // CDATA section
<add> link: /^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/,
<add> reflink: /^!?\[(label)\]\[(?!\s*\])((?:\\[\[\]]?|[^\[\]\\])+)\]/,
<add> nolink: /^!?\[(?!\s*\])((?:\[[^\[\]]*\]|\\[\[\]]|[^\[\]])*)\](?:\[\])?/,
<add> reflinkSearch: 'reflink|nolink(?!\\()',
<add> emStrong: {
<add> lDelim: /^(?:\*+(?:([punct_])|[^\s*]))|^_+(?:([punct*])|([^\s_]))/,
<add> // (1) and (2) can only be a Right Delimiter. (3) and (4) can only be Left. (5) and (6) can be either Left or Right.
<add> // () Skip other delimiter (1) #*** (2) a***#, a*** (3) #***a, ***a (4) ***# (5) #***# (6) a***a
<add> rDelimAst: /\_\_[^_*]*?\*[^_*]*?\_\_|[punct_](\*+)(?=[\s]|$)|[^punct*_\s](\*+)(?=[punct_\s]|$)|[punct_\s](\*+)(?=[^punct*_\s])|[\s](\*+)(?=[punct_])|[punct_](\*+)(?=[punct_])|[^punct*_\s](\*+)(?=[^punct*_\s])/,
<add> rDelimUnd: /\*\*[^_*]*?\_[^_*]*?\*\*|[punct*](\_+)(?=[\s]|$)|[^punct*_\s](\_+)(?=[punct*\s]|$)|[punct*\s](\_+)(?=[^punct*_\s])|[\s](\_+)(?=[punct*])|[punct*](\_+)(?=[punct*])/ // ^- Not allowed for _
<add>
<add> },
<add> code: /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,
<add> br: /^( {2,}|\\)\n(?!\s*$)/,
<add> del: noopTest,
<add> text: /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,
<add> punctuation: /^([\spunctuation])/
<add> }; // list of punctuation marks from CommonMark spec
<add> // without * and _ to handle the different emphasis markers * and _
<add>
<add> inline$1._punctuation = '!"#$%&\'()+\\-.,/:;<=>?@\\[\\]`^{|}~';
<add> inline$1.punctuation = edit(inline$1.punctuation).replace(/punctuation/g, inline$1._punctuation).getRegex(); // sequences em should skip over [title](link), `code`, <html>
<add>
<add> inline$1.blockSkip = /\[[^\]]*?\]\([^\)]*?\)|`[^`]*?`|<[^>]*?>/g;
<add> inline$1.escapedEmSt = /\\\*|\\_/g;
<add> inline$1._comment = edit(block$1._comment).replace('(?:-->|$)', '-->').getRegex();
<add> inline$1.emStrong.lDelim = edit(inline$1.emStrong.lDelim).replace(/punct/g, inline$1._punctuation).getRegex();
<add> inline$1.emStrong.rDelimAst = edit(inline$1.emStrong.rDelimAst, 'g').replace(/punct/g, inline$1._punctuation).getRegex();
<add> inline$1.emStrong.rDelimUnd = edit(inline$1.emStrong.rDelimUnd, 'g').replace(/punct/g, inline$1._punctuation).getRegex();
<add> inline$1._escapes = /\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/g;
<add> inline$1._scheme = /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/;
<add> inline$1._email = /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/;
<add> inline$1.autolink = edit(inline$1.autolink).replace('scheme', inline$1._scheme).replace('email', inline$1._email).getRegex();
<add> inline$1._attribute = /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/;
<add> inline$1.tag = edit(inline$1.tag).replace('comment', inline$1._comment).replace('attribute', inline$1._attribute).getRegex();
<add> inline$1._label = /(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/;
<add> inline$1._href = /<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/;
<add> inline$1._title = /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/;
<add> inline$1.link = edit(inline$1.link).replace('label', inline$1._label).replace('href', inline$1._href).replace('title', inline$1._title).getRegex();
<add> inline$1.reflink = edit(inline$1.reflink).replace('label', inline$1._label).getRegex();
<add> inline$1.reflinkSearch = edit(inline$1.reflinkSearch, 'g').replace('reflink', inline$1.reflink).replace('nolink', inline$1.nolink).getRegex();
<add> /**
<add> * Normal Inline Grammar
<add> */
<add>
<add> inline$1.normal = merge$1({}, inline$1);
<add> /**
<add> * Pedantic Inline Grammar
<add> */
<add>
<add> inline$1.pedantic = merge$1({}, inline$1.normal, {
<add> strong: {
<add> start: /^__|\*\*/,
<add> middle: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,
<add> endAst: /\*\*(?!\*)/g,
<add> endUnd: /__(?!_)/g
<add> },
<add> em: {
<add> start: /^_|\*/,
<add> middle: /^()\*(?=\S)([\s\S]*?\S)\*(?!\*)|^_(?=\S)([\s\S]*?\S)_(?!_)/,
<add> endAst: /\*(?!\*)/g,
<add> endUnd: /_(?!_)/g
<add> },
<add> link: edit(/^!?\[(label)\]\((.*?)\)/).replace('label', inline$1._label).getRegex(),
<add> reflink: edit(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace('label', inline$1._label).getRegex()
<add> });
<add> /**
<add> * GFM Inline Grammar
<add> */
<add>
<add> inline$1.gfm = merge$1({}, inline$1.normal, {
<add> escape: edit(inline$1.escape).replace('])', '~|])').getRegex(),
<add> _extended_email: /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/,
<add> url: /^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,
<add> _backpedal: /(?:[^?!.,:;*_~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_~)]+(?!$))+/,
<add> del: /^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,
<add> text: /^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/
<add> });
<add> inline$1.gfm.url = edit(inline$1.gfm.url, 'i').replace('email', inline$1.gfm._extended_email).getRegex();
<add> /**
<add> * GFM + Line Breaks Inline Grammar
<add> */
<add>
<add> inline$1.breaks = merge$1({}, inline$1.gfm, {
<add> br: edit(inline$1.br).replace('{2,}', '*').getRegex(),
<add> text: edit(inline$1.gfm.text).replace('\\b_', '\\b_| {2,}\\n').replace(/\{2,\}/g, '*').getRegex()
<add> });
<add> var rules = {
<add> block: block$1,
<add> inline: inline$1
<add> };
<add>
<add> var Tokenizer$1 = Tokenizer_1;
<add> var defaults$3 = defaults$5.exports.defaults;
<add> var block = rules.block,
<add> inline = rules.inline;
<add> var repeatString = helpers.repeatString;
<add> /**
<add> * smartypants text replacement
<add> */
<add>
<add> function smartypants(text) {
<add> return text // em-dashes
<add> .replace(/---/g, "\u2014") // en-dashes
<add> .replace(/--/g, "\u2013") // opening singles
<add> .replace(/(^|[-\u2014/(\[{"\s])'/g, "$1\u2018") // closing singles & apostrophes
<add> .replace(/'/g, "\u2019") // opening doubles
<add> .replace(/(^|[-\u2014/(\[{\u2018\s])"/g, "$1\u201C") // closing doubles
<add> .replace(/"/g, "\u201D") // ellipses
<add> .replace(/\.{3}/g, "\u2026");
<add> }
<add> /**
<add> * mangle email addresses
<add> */
<add>
<add>
<add> function mangle(text) {
<add> var out = '',
<add> i,
<add> ch;
<add> var l = text.length;
<add>
<add> for (i = 0; i < l; i++) {
<add> ch = text.charCodeAt(i);
<add>
<add> if (Math.random() > 0.5) {
<add> ch = 'x' + ch.toString(16);
<add> }
<add>
<add> out += '&#' + ch + ';';
<add> }
<add>
<add> return out;
<add> }
<add> /**
<add> * Block Lexer
<add> */
<add>
<add>
<add> var Lexer_1 = /*#__PURE__*/function () {
<add> function Lexer(options) {
<add> this.tokens = [];
<add> this.tokens.links = Object.create(null);
<add> this.options = options || defaults$3;
<add> this.options.tokenizer = this.options.tokenizer || new Tokenizer$1();
<add> this.tokenizer = this.options.tokenizer;
<add> this.tokenizer.options = this.options;
<add> this.tokenizer.lexer = this;
<add> this.inlineQueue = [];
<add> this.state = {
<add> inLink: false,
<add> inRawBlock: false,
<add> top: true
<add> };
<add> var rules = {
<add> block: block.normal,
<add> inline: inline.normal
<add> };
<add>
<add> if (this.options.pedantic) {
<add> rules.block = block.pedantic;
<add> rules.inline = inline.pedantic;
<add> } else if (this.options.gfm) {
<add> rules.block = block.gfm;
<add>
<add> if (this.options.breaks) {
<add> rules.inline = inline.breaks;
<add> } else {
<add> rules.inline = inline.gfm;
<add> }
<add> }
<add>
<add> this.tokenizer.rules = rules;
<add> }
<add> /**
<add> * Expose Rules
<add> */
<add>
<add>
<add> /**
<add> * Static Lex Method
<add> */
<add> Lexer.lex = function lex(src, options) {
<add> var lexer = new Lexer(options);
<add> return lexer.lex(src);
<add> }
<add> /**
<add> * Static Lex Inline Method
<add> */
<add> ;
<add>
<add> Lexer.lexInline = function lexInline(src, options) {
<add> var lexer = new Lexer(options);
<add> return lexer.inlineTokens(src);
<add> }
<add> /**
<add> * Preprocessing
<add> */
<add> ;
<add>
<add> var _proto = Lexer.prototype;
<add>
<add> _proto.lex = function lex(src) {
<add> src = src.replace(/\r\n|\r/g, '\n').replace(/\t/g, ' ');
<add> this.blockTokens(src, this.tokens);
<add> var next;
<add>
<add> while (next = this.inlineQueue.shift()) {
<add> this.inlineTokens(next.src, next.tokens);
<add> }
<add>
<add> return this.tokens;
<add> }
<add> /**
<add> * Lexing
<add> */
<add> ;
<add>
<add> _proto.blockTokens = function blockTokens(src, tokens) {
<add> var _this = this;
<add>
<add> if (tokens === void 0) {
<add> tokens = [];
<add> }
<add>
<add> if (this.options.pedantic) {
<add> src = src.replace(/^ +$/gm, '');
<add> }
<add>
<add> var token, lastToken, cutSrc, lastParagraphClipped;
<add>
<add> while (src) {
<add> if (this.options.extensions && this.options.extensions.block && this.options.extensions.block.some(function (extTokenizer) {
<add> if (token = extTokenizer.call({
<add> lexer: _this
<add> }, src, tokens)) {
<add> src = src.substring(token.raw.length);
<add> tokens.push(token);
<add> return true;
<add> }
<add>
<add> return false;
<add> })) {
<add> continue;
<add> } // newline
<add>
<add>
<add> if (token = this.tokenizer.space(src)) {
<add> src = src.substring(token.raw.length);
<add>
<add> if (token.type) {
<add> tokens.push(token);
<add> }
<add>
<add> continue;
<add> } // code
<add>
<add>
<add> if (token = this.tokenizer.code(src)) {
<add> src = src.substring(token.raw.length);
<add> lastToken = tokens[tokens.length - 1]; // An indented code block cannot interrupt a paragraph.
<add>
<add> if (lastToken && (lastToken.type === 'paragraph' || lastToken.type === 'text')) {
<add> lastToken.raw += '\n' + token.raw;
<add> lastToken.text += '\n' + token.text;
<add> this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;
<add> } else {
<add> tokens.push(token);
<add> }
<add>
<add> continue;
<add> } // fences
<add>
<add>
<add> if (token = this.tokenizer.fences(src)) {
<add> src = src.substring(token.raw.length);
<add> tokens.push(token);
<add> continue;
<add> } // heading
<add>
<add>
<add> if (token = this.tokenizer.heading(src)) {
<add> src = src.substring(token.raw.length);
<add> tokens.push(token);
<add> continue;
<add> } // hr
<add>
<add>
<add> if (token = this.tokenizer.hr(src)) {
<add> src = src.substring(token.raw.length);
<add> tokens.push(token);
<add> continue;
<add> } // blockquote
<add>
<add>
<add> if (token = this.tokenizer.blockquote(src)) {
<add> src = src.substring(token.raw.length);
<add> tokens.push(token);
<add> continue;
<add> } // list
<add>
<add>
<add> if (token = this.tokenizer.list(src)) {
<add> src = src.substring(token.raw.length);
<add> tokens.push(token);
<add> continue;
<add> } // html
<add>
<add>
<add> if (token = this.tokenizer.html(src)) {
<add> src = src.substring(token.raw.length);
<add> tokens.push(token);
<add> continue;
<add> } // def
<add>
<add>
<add> if (token = this.tokenizer.def(src)) {
<add> src = src.substring(token.raw.length);
<add> lastToken = tokens[tokens.length - 1];
<add>
<add> if (lastToken && (lastToken.type === 'paragraph' || lastToken.type === 'text')) {
<add> lastToken.raw += '\n' + token.raw;
<add> lastToken.text += '\n' + token.raw;
<add> this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;
<add> } else if (!this.tokens.links[token.tag]) {
<add> this.tokens.links[token.tag] = {
<add> href: token.href,
<add> title: token.title
<add> };
<add> }
<add>
<add> continue;
<add> } // table (gfm)
<add>
<add>
<add> if (token = this.tokenizer.table(src)) {
<add> src = src.substring(token.raw.length);
<add> tokens.push(token);
<add> continue;
<add> } // lheading
<add>
<add>
<add> if (token = this.tokenizer.lheading(src)) {
<add> src = src.substring(token.raw.length);
<add> tokens.push(token);
<add> continue;
<add> } // top-level paragraph
<add> // prevent paragraph consuming extensions by clipping 'src' to extension start
<add>
<add>
<add> cutSrc = src;
<add>
<add> if (this.options.extensions && this.options.extensions.startBlock) {
<add> (function () {
<add> var startIndex = Infinity;
<add> var tempSrc = src.slice(1);
<add> var tempStart = void 0;
<add>
<add> _this.options.extensions.startBlock.forEach(function (getStartIndex) {
<add> tempStart = getStartIndex.call({
<add> lexer: this
<add> }, tempSrc);
<add>
<add> if (typeof tempStart === 'number' && tempStart >= 0) {
<add> startIndex = Math.min(startIndex, tempStart);
<add> }
<add> });
<add>
<add> if (startIndex < Infinity && startIndex >= 0) {
<add> cutSrc = src.substring(0, startIndex + 1);
<add> }
<add> })();
<add> }
<add>
<add> if (this.state.top && (token = this.tokenizer.paragraph(cutSrc))) {
<add> lastToken = tokens[tokens.length - 1];
<add>
<add> if (lastParagraphClipped && lastToken.type === 'paragraph') {
<add> lastToken.raw += '\n' + token.raw;
<add> lastToken.text += '\n' + token.text;
<add> this.inlineQueue.pop();
<add> this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;
<add> } else {
<add> tokens.push(token);
<add> }
<add>
<add> lastParagraphClipped = cutSrc.length !== src.length;
<add> src = src.substring(token.raw.length);
<add> continue;
<add> } // text
<add>
<add>
<add> if (token = this.tokenizer.text(src)) {
<add> src = src.substring(token.raw.length);
<add> lastToken = tokens[tokens.length - 1];
<add>
<add> if (lastToken && lastToken.type === 'text') {
<add> lastToken.raw += '\n' + token.raw;
<add> lastToken.text += '\n' + token.text;
<add> this.inlineQueue.pop();
<add> this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;
<add> } else {
<add> tokens.push(token);
<add> }
<add>
<add> continue;
<add> }
<add>
<add> if (src) {
<add> var errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0);
<add>
<add> if (this.options.silent) {
<add> console.error(errMsg);
<add> break;
<add> } else {
<add> throw new Error(errMsg);
<add> }
<add> }
<add> }
<add>
<add> this.state.top = true;
<add> return tokens;
<add> };
<add>
<add> _proto.inline = function inline(src, tokens) {
<add> this.inlineQueue.push({
<add> src: src,
<add> tokens: tokens
<add> });
<add> }
<add> /**
<add> * Lexing/Compiling
<add> */
<add> ;
<add>
<add> _proto.inlineTokens = function inlineTokens(src, tokens) {
<add> var _this2 = this;
<add>
<add> if (tokens === void 0) {
<add> tokens = [];
<add> }
<add>
<add> var token, lastToken, cutSrc; // String with links masked to avoid interference with em and strong
<add>
<add> var maskedSrc = src;
<add> var match;
<add> var keepPrevChar, prevChar; // Mask out reflinks
<add>
<add> if (this.tokens.links) {
<add> var links = Object.keys(this.tokens.links);
<add>
<add> if (links.length > 0) {
<add> while ((match = this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc)) != null) {
<add> if (links.includes(match[0].slice(match[0].lastIndexOf('[') + 1, -1))) {
<add> maskedSrc = maskedSrc.slice(0, match.index) + '[' + repeatString('a', match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex);
<add> }
<add> }
<add> }
<add> } // Mask out other blocks
<add>
<add>
<add> while ((match = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) != null) {
<add> maskedSrc = maskedSrc.slice(0, match.index) + '[' + repeatString('a', match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);
<add> } // Mask out escaped em & strong delimiters
<add>
<add>
<add> while ((match = this.tokenizer.rules.inline.escapedEmSt.exec(maskedSrc)) != null) {
<add> maskedSrc = maskedSrc.slice(0, match.index) + '++' + maskedSrc.slice(this.tokenizer.rules.inline.escapedEmSt.lastIndex);
<add> }
<add>
<add> while (src) {
<add> if (!keepPrevChar) {
<add> prevChar = '';
<add> }
<add>
<add> keepPrevChar = false; // extensions
<add>
<add> if (this.options.extensions && this.options.extensions.inline && this.options.extensions.inline.some(function (extTokenizer) {
<add> if (token = extTokenizer.call({
<add> lexer: _this2
<add> }, src, tokens)) {
<add> src = src.substring(token.raw.length);
<add> tokens.push(token);
<add> return true;
<add> }
<add>
<add> return false;
<add> })) {
<add> continue;
<add> } // escape
<add>
<add>
<add> if (token = this.tokenizer.escape(src)) {
<add> src = src.substring(token.raw.length);
<add> tokens.push(token);
<add> continue;
<add> } // tag
<add>
<add>
<add> if (token = this.tokenizer.tag(src)) {
<add> src = src.substring(token.raw.length);
<add> lastToken = tokens[tokens.length - 1];
<add>
<add> if (lastToken && token.type === 'text' && lastToken.type === 'text') {
<add> lastToken.raw += token.raw;
<add> lastToken.text += token.text;
<add> } else {
<add> tokens.push(token);
<add> }
<add>
<add> continue;
<add> } // link
<add>
<add>
<add> if (token = this.tokenizer.link(src)) {
<add> src = src.substring(token.raw.length);
<add> tokens.push(token);
<add> continue;
<add> } // reflink, nolink
<add>
<add>
<add> if (token = this.tokenizer.reflink(src, this.tokens.links)) {
<add> src = src.substring(token.raw.length);
<add> lastToken = tokens[tokens.length - 1];
<add>
<add> if (lastToken && token.type === 'text' && lastToken.type === 'text') {
<add> lastToken.raw += token.raw;
<add> lastToken.text += token.text;
<add> } else {
<add> tokens.push(token);
<add> }
<add>
<add> continue;
<add> } // em & strong
<add>
<add>
<add> if (token = this.tokenizer.emStrong(src, maskedSrc, prevChar)) {
<add> src = src.substring(token.raw.length);
<add> tokens.push(token);
<add> continue;
<add> } // code
<add>
<add>
<add> if (token = this.tokenizer.codespan(src)) {
<add> src = src.substring(token.raw.length);
<add> tokens.push(token);
<add> continue;
<add> } // br
<add>
<add>
<add> if (token = this.tokenizer.br(src)) {
<add> src = src.substring(token.raw.length);
<add> tokens.push(token);
<add> continue;
<add> } // del (gfm)
<add>
<add>
<add> if (token = this.tokenizer.del(src)) {
<add> src = src.substring(token.raw.length);
<add> tokens.push(token);
<add> continue;
<add> } // autolink
<add>
<add>
<add> if (token = this.tokenizer.autolink(src, mangle)) {
<add> src = src.substring(token.raw.length);
<add> tokens.push(token);
<add> continue;
<add> } // url (gfm)
<add>
<add>
<add> if (!this.state.inLink && (token = this.tokenizer.url(src, mangle))) {
<add> src = src.substring(token.raw.length);
<add> tokens.push(token);
<add> continue;
<add> } // text
<add> // prevent inlineText consuming extensions by clipping 'src' to extension start
<add>
<add>
<add> cutSrc = src;
<add>
<add> if (this.options.extensions && this.options.extensions.startInline) {
<add> (function () {
<add> var startIndex = Infinity;
<add> var tempSrc = src.slice(1);
<add> var tempStart = void 0;
<add>
<add> _this2.options.extensions.startInline.forEach(function (getStartIndex) {
<add> tempStart = getStartIndex.call({
<add> lexer: this
<add> }, tempSrc);
<add>
<add> if (typeof tempStart === 'number' && tempStart >= 0) {
<add> startIndex = Math.min(startIndex, tempStart);
<add> }
<add> });
<add>
<add> if (startIndex < Infinity && startIndex >= 0) {
<add> cutSrc = src.substring(0, startIndex + 1);
<add> }
<add> })();
<add> }
<add>
<add> if (token = this.tokenizer.inlineText(cutSrc, smartypants)) {
<add> src = src.substring(token.raw.length);
<add>
<add> if (token.raw.slice(-1) !== '_') {
<add> // Track prevChar before string of ____ started
<add> prevChar = token.raw.slice(-1);
<add> }
<add>
<add> keepPrevChar = true;
<add> lastToken = tokens[tokens.length - 1];
<add>
<add> if (lastToken && lastToken.type === 'text') {
<add> lastToken.raw += token.raw;
<add> lastToken.text += token.text;
<add> } else {
<add> tokens.push(token);
<add> }
<add>
<add> continue;
<add> }
<add>
<add> if (src) {
<add> var errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0);
<add>
<add> if (this.options.silent) {
<add> console.error(errMsg);
<add> break;
<add> } else {
<add> throw new Error(errMsg);
<add> }
<add> }
<add> }
<add>
<add> return tokens;
<add> };
<add>
<add> _createClass(Lexer, null, [{
<add> key: "rules",
<add> get: function get() {
<add> return {
<add> block: block,
<add> inline: inline
<add> };
<add> }
<add> }]);
<add>
<add> return Lexer;
<add> }();
<add>
<add> var defaults$2 = defaults$5.exports.defaults;
<add> var cleanUrl = helpers.cleanUrl,
<add> escape$1 = helpers.escape;
<add> /**
<add> * Renderer
<add> */
<add>
<add> var Renderer_1 = /*#__PURE__*/function () {
<add> function Renderer(options) {
<add> this.options = options || defaults$2;
<add> }
<add>
<add> var _proto = Renderer.prototype;
<add>
<add> _proto.code = function code(_code, infostring, escaped) {
<add> var lang = (infostring || '').match(/\S*/)[0];
<add>
<add> if (this.options.highlight) {
<add> var out = this.options.highlight(_code, lang);
<add>
<add> if (out != null && out !== _code) {
<add> escaped = true;
<add> _code = out;
<add> }
<add> }
<add>
<add> _code = _code.replace(/\n$/, '') + '\n';
<add>
<add> if (!lang) {
<add> return '<pre><code>' + (escaped ? _code : escape$1(_code, true)) + '</code></pre>\n';
<add> }
<add>
<add> return '<pre><code class="' + this.options.langPrefix + escape$1(lang, true) + '">' + (escaped ? _code : escape$1(_code, true)) + '</code></pre>\n';
<add> };
<add>
<add> _proto.blockquote = function blockquote(quote) {
<add> return '<blockquote>\n' + quote + '</blockquote>\n';
<add> };
<add>
<add> _proto.html = function html(_html) {
<add> return _html;
<add> };
<add>
<add> _proto.heading = function heading(text, level, raw, slugger) {
<add> if (this.options.headerIds) {
<add> return '<h' + level + ' id="' + this.options.headerPrefix + slugger.slug(raw) + '">' + text + '</h' + level + '>\n';
<add> } // ignore IDs
<add>
<add>
<add> return '<h' + level + '>' + text + '</h' + level + '>\n';
<add> };
<add>
<add> _proto.hr = function hr() {
<add> return this.options.xhtml ? '<hr/>\n' : '<hr>\n';
<add> };
<add>
<add> _proto.list = function list(body, ordered, start) {
<add> var type = ordered ? 'ol' : 'ul',
<add> startatt = ordered && start !== 1 ? ' start="' + start + '"' : '';
<add> return '<' + type + startatt + '>\n' + body + '</' + type + '>\n';
<add> };
<add>
<add> _proto.listitem = function listitem(text) {
<add> return '<li>' + text + '</li>\n';
<add> };
<add>
<add> _proto.checkbox = function checkbox(checked) {
<add> return '<input ' + (checked ? 'checked="" ' : '') + 'disabled="" type="checkbox"' + (this.options.xhtml ? ' /' : '') + '> ';
<add> };
<add>
<add> _proto.paragraph = function paragraph(text) {
<add> return '<p>' + text + '</p>\n';
<add> };
<add>
<add> _proto.table = function table(header, body) {
<add> if (body) body = '<tbody>' + body + '</tbody>';
<add> return '<table>\n' + '<thead>\n' + header + '</thead>\n' + body + '</table>\n';
<add> };
<add>
<add> _proto.tablerow = function tablerow(content) {
<add> return '<tr>\n' + content + '</tr>\n';
<add> };
<add>
<add> _proto.tablecell = function tablecell(content, flags) {
<add> var type = flags.header ? 'th' : 'td';
<add> var tag = flags.align ? '<' + type + ' align="' + flags.align + '">' : '<' + type + '>';
<add> return tag + content + '</' + type + '>\n';
<add> } // span level renderer
<add> ;
<add>
<add> _proto.strong = function strong(text) {
<add> return '<strong>' + text + '</strong>';
<add> };
<add>
<add> _proto.em = function em(text) {
<add> return '<em>' + text + '</em>';
<add> };
<add>
<add> _proto.codespan = function codespan(text) {
<add> return '<code>' + text + '</code>';
<add> };
<add>
<add> _proto.br = function br() {
<add> return this.options.xhtml ? '<br/>' : '<br>';
<add> };
<add>
<add> _proto.del = function del(text) {
<add> return '<del>' + text + '</del>';
<add> };
<add>
<add> _proto.link = function link(href, title, text) {
<add> href = cleanUrl(this.options.sanitize, this.options.baseUrl, href);
<add>
<add> if (href === null) {
<add> return text;
<add> }
<add>
<add> var out = '<a href="' + escape$1(href) + '"';
<add>
<add> if (title) {
<add> out += ' title="' + title + '"';
<add> }
<add>
<add> out += '>' + text + '</a>';
<add> return out;
<add> };
<add>
<add> _proto.image = function image(href, title, text) {
<add> href = cleanUrl(this.options.sanitize, this.options.baseUrl, href);
<add>
<add> if (href === null) {
<add> return text;
<add> }
<add>
<add> var out = '<img src="' + href + '" alt="' + text + '"';
<add>
<add> if (title) {
<add> out += ' title="' + title + '"';
<add> }
<add>
<add> out += this.options.xhtml ? '/>' : '>';
<add> return out;
<add> };
<add>
<add> _proto.text = function text(_text) {
<add> return _text;
<add> };
<add>
<add> return Renderer;
<add> }();
<add>
<add> /**
<add> * TextRenderer
<add> * returns only the textual part of the token
<add> */
<add>
<add> var TextRenderer_1 = /*#__PURE__*/function () {
<add> function TextRenderer() {}
<add>
<add> var _proto = TextRenderer.prototype;
<add>
<add> // no need for block level renderers
<add> _proto.strong = function strong(text) {
<add> return text;
<add> };
<add>
<add> _proto.em = function em(text) {
<add> return text;
<add> };
<add>
<add> _proto.codespan = function codespan(text) {
<add> return text;
<add> };
<add>
<add> _proto.del = function del(text) {
<add> return text;
<add> };
<add>
<add> _proto.html = function html(text) {
<add> return text;
<add> };
<add>
<add> _proto.text = function text(_text) {
<add> return _text;
<add> };
<add>
<add> _proto.link = function link(href, title, text) {
<add> return '' + text;
<add> };
<add>
<add> _proto.image = function image(href, title, text) {
<add> return '' + text;
<add> };
<add>
<add> _proto.br = function br() {
<add> return '';
<add> };
<add>
<add> return TextRenderer;
<add> }();
<add>
<add> /**
<add> * Slugger generates header id
<add> */
<add>
<add> var Slugger_1 = /*#__PURE__*/function () {
<add> function Slugger() {
<add> this.seen = {};
<add> }
<add>
<add> var _proto = Slugger.prototype;
<add>
<add> _proto.serialize = function serialize(value) {
<add> return value.toLowerCase().trim() // remove html tags
<add> .replace(/<[!\/a-z].*?>/ig, '') // remove unwanted chars
<add> .replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~]/g, '').replace(/\s/g, '-');
<add> }
<add> /**
<add> * Finds the next safe (unique) slug to use
<add> */
<add> ;
<add>
<add> _proto.getNextSafeSlug = function getNextSafeSlug(originalSlug, isDryRun) {
<add> var slug = originalSlug;
<add> var occurenceAccumulator = 0;
<add>
<add> if (this.seen.hasOwnProperty(slug)) {
<add> occurenceAccumulator = this.seen[originalSlug];
<add>
<add> do {
<add> occurenceAccumulator++;
<add> slug = originalSlug + '-' + occurenceAccumulator;
<add> } while (this.seen.hasOwnProperty(slug));
<add> }
<add>
<add> if (!isDryRun) {
<add> this.seen[originalSlug] = occurenceAccumulator;
<add> this.seen[slug] = 0;
<add> }
<add>
<add> return slug;
<add> }
<add> /**
<add> * Convert string to unique id
<add> * @param {object} options
<add> * @param {boolean} options.dryrun Generates the next unique slug without updating the internal accumulator.
<add> */
<add> ;
<add>
<add> _proto.slug = function slug(value, options) {
<add> if (options === void 0) {
<add> options = {};
<add> }
<add>
<add> var slug = this.serialize(value);
<add> return this.getNextSafeSlug(slug, options.dryrun);
<add> };
<add>
<add> return Slugger;
<add> }();
<add>
<add> var Renderer$1 = Renderer_1;
<add> var TextRenderer$1 = TextRenderer_1;
<add> var Slugger$1 = Slugger_1;
<add> var defaults$1 = defaults$5.exports.defaults;
<add> var unescape = helpers.unescape;
<add> /**
<add> * Parsing & Compiling
<add> */
<add>
<add> var Parser_1 = /*#__PURE__*/function () {
<add> function Parser(options) {
<add> this.options = options || defaults$1;
<add> this.options.renderer = this.options.renderer || new Renderer$1();
<add> this.renderer = this.options.renderer;
<add> this.renderer.options = this.options;
<add> this.textRenderer = new TextRenderer$1();
<add> this.slugger = new Slugger$1();
<add> }
<add> /**
<add> * Static Parse Method
<add> */
<add>
<add>
<add> Parser.parse = function parse(tokens, options) {
<add> var parser = new Parser(options);
<add> return parser.parse(tokens);
<add> }
<add> /**
<add> * Static Parse Inline Method
<add> */
<add> ;
<add>
<add> Parser.parseInline = function parseInline(tokens, options) {
<add> var parser = new Parser(options);
<add> return parser.parseInline(tokens);
<add> }
<add> /**
<add> * Parse Loop
<add> */
<add> ;
<add>
<add> var _proto = Parser.prototype;
<add>
<add> _proto.parse = function parse(tokens, top) {
<add> if (top === void 0) {
<add> top = true;
<add> }
<add>
<add> var out = '',
<add> i,
<add> j,
<add> k,
<add> l2,
<add> l3,
<add> row,
<add> cell,
<add> header,
<add> body,
<add> token,
<add> ordered,
<add> start,
<add> loose,
<add> itemBody,
<add> item,
<add> checked,
<add> task,
<add> checkbox,
<add> ret;
<add> var l = tokens.length;
<add>
<add> for (i = 0; i < l; i++) {
<add> token = tokens[i]; // Run any renderer extensions
<add>
<add> if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[token.type]) {
<add> ret = this.options.extensions.renderers[token.type].call({
<add> parser: this
<add> }, token);
<add>
<add> if (ret !== false || !['space', 'hr', 'heading', 'code', 'table', 'blockquote', 'list', 'html', 'paragraph', 'text'].includes(token.type)) {
<add> out += ret || '';
<add> continue;
<add> }
<add> }
<add>
<add> switch (token.type) {
<add> case 'space':
<add> {
<add> continue;
<add> }
<add>
<add> case 'hr':
<add> {
<add> out += this.renderer.hr();
<add> continue;
<add> }
<add>
<add> case 'heading':
<add> {
<add> out += this.renderer.heading(this.parseInline(token.tokens), token.depth, unescape(this.parseInline(token.tokens, this.textRenderer)), this.slugger);
<add> continue;
<add> }
<add>
<add> case 'code':
<add> {
<add> out += this.renderer.code(token.text, token.lang, token.escaped);
<add> continue;
<add> }
<add>
<add> case 'table':
<add> {
<add> header = ''; // header
<add>
<add> cell = '';
<add> l2 = token.header.length;
<add>
<add> for (j = 0; j < l2; j++) {
<add> cell += this.renderer.tablecell(this.parseInline(token.header[j].tokens), {
<add> header: true,
<add> align: token.align[j]
<add> });
<add> }
<add>
<add> header += this.renderer.tablerow(cell);
<add> body = '';
<add> l2 = token.rows.length;
<add>
<add> for (j = 0; j < l2; j++) {
<add> row = token.rows[j];
<add> cell = '';
<add> l3 = row.length;
<add>
<add> for (k = 0; k < l3; k++) {
<add> cell += this.renderer.tablecell(this.parseInline(row[k].tokens), {
<add> header: false,
<add> align: token.align[k]
<add> });
<add> }
<add>
<add> body += this.renderer.tablerow(cell);
<add> }
<add>
<add> out += this.renderer.table(header, body);
<add> continue;
<add> }
<add>
<add> case 'blockquote':
<add> {
<add> body = this.parse(token.tokens);
<add> out += this.renderer.blockquote(body);
<add> continue;
<add> }
<add>
<add> case 'list':
<add> {
<add> ordered = token.ordered;
<add> start = token.start;
<add> loose = token.loose;
<add> l2 = token.items.length;
<add> body = '';
<add>
<add> for (j = 0; j < l2; j++) {
<add> item = token.items[j];
<add> checked = item.checked;
<add> task = item.task;
<add> itemBody = '';
<add>
<add> if (item.task) {
<add> checkbox = this.renderer.checkbox(checked);
<add>
<add> if (loose) {
<add> if (item.tokens.length > 0 && item.tokens[0].type === 'paragraph') {
<add> item.tokens[0].text = checkbox + ' ' + item.tokens[0].text;
<add>
<add> if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === 'text') {
<add> item.tokens[0].tokens[0].text = checkbox + ' ' + item.tokens[0].tokens[0].text;
<add> }
<add> } else {
<add> item.tokens.unshift({
<add> type: 'text',
<add> text: checkbox
<add> });
<add> }
<add> } else {
<add> itemBody += checkbox;
<add> }
<add> }
<add>
<add> itemBody += this.parse(item.tokens, loose);
<add> body += this.renderer.listitem(itemBody, task, checked);
<add> }
<add>
<add> out += this.renderer.list(body, ordered, start);
<add> continue;
<add> }
<add>
<add> case 'html':
<add> {
<add> // TODO parse inline content if parameter markdown=1
<add> out += this.renderer.html(token.text);
<add> continue;
<add> }
<add>
<add> case 'paragraph':
<add> {
<add> out += this.renderer.paragraph(this.parseInline(token.tokens));
<add> continue;
<add> }
<add>
<add> case 'text':
<add> {
<add> body = token.tokens ? this.parseInline(token.tokens) : token.text;
<add>
<add> while (i + 1 < l && tokens[i + 1].type === 'text') {
<add> token = tokens[++i];
<add> body += '\n' + (token.tokens ? this.parseInline(token.tokens) : token.text);
<add> }
<add>
<add> out += top ? this.renderer.paragraph(body) : body;
<add> continue;
<add> }
<add>
<add> default:
<add> {
<add> var errMsg = 'Token with "' + token.type + '" type was not found.';
<add>
<add> if (this.options.silent) {
<add> console.error(errMsg);
<add> return;
<add> } else {
<add> throw new Error(errMsg);
<add> }
<add> }
<add> }
<add> }
<add>
<add> return out;
<add> }
<add> /**
<add> * Parse Inline Tokens
<add> */
<add> ;
<add>
<add> _proto.parseInline = function parseInline(tokens, renderer) {
<add> renderer = renderer || this.renderer;
<add> var out = '',
<add> i,
<add> token,
<add> ret;
<add> var l = tokens.length;
<add>
<add> for (i = 0; i < l; i++) {
<add> token = tokens[i]; // Run any renderer extensions
<add>
<add> if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[token.type]) {
<add> ret = this.options.extensions.renderers[token.type].call({
<add> parser: this
<add> }, token);
<add>
<add> if (ret !== false || !['escape', 'html', 'link', 'image', 'strong', 'em', 'codespan', 'br', 'del', 'text'].includes(token.type)) {
<add> out += ret || '';
<add> continue;
<add> }
<add> }
<add>
<add> switch (token.type) {
<add> case 'escape':
<add> {
<add> out += renderer.text(token.text);
<add> break;
<add> }
<add>
<add> case 'html':
<add> {
<add> out += renderer.html(token.text);
<add> break;
<add> }
<add>
<add> case 'link':
<add> {
<add> out += renderer.link(token.href, token.title, this.parseInline(token.tokens, renderer));
<add> break;
<add> }
<add>
<add> case 'image':
<add> {
<add> out += renderer.image(token.href, token.title, token.text);
<add> break;
<add> }
<add>
<add> case 'strong':
<add> {
<add> out += renderer.strong(this.parseInline(token.tokens, renderer));
<add> break;
<add> }
<add>
<add> case 'em':
<add> {
<add> out += renderer.em(this.parseInline(token.tokens, renderer));
<add> break;
<add> }
<add>
<add> case 'codespan':
<add> {
<add> out += renderer.codespan(token.text);
<add> break;
<add> }
<add>
<add> case 'br':
<add> {
<add> out += renderer.br();
<add> break;
<add> }
<add>
<add> case 'del':
<add> {
<add> out += renderer.del(this.parseInline(token.tokens, renderer));
<add> break;
<add> }
<add>
<add> case 'text':
<add> {
<add> out += renderer.text(token.text);
<add> break;
<add> }
<add>
<add> default:
<add> {
<add> var errMsg = 'Token with "' + token.type + '" type was not found.';
<add>
<add> if (this.options.silent) {
<add> console.error(errMsg);
<add> return;
<add> } else {
<add> throw new Error(errMsg);
<add> }
<add> }
<add> }
<add> }
<add>
<add> return out;
<add> };
<add>
<add> return Parser;
<add> }();
<add>
<add> var Lexer = Lexer_1;
<add> var Parser = Parser_1;
<add> var Tokenizer = Tokenizer_1;
<add> var Renderer = Renderer_1;
<add> var TextRenderer = TextRenderer_1;
<add> var Slugger = Slugger_1;
<add> var merge = helpers.merge,
<add> checkSanitizeDeprecation = helpers.checkSanitizeDeprecation,
<add> escape = helpers.escape;
<add> var getDefaults = defaults$5.exports.getDefaults,
<add> changeDefaults = defaults$5.exports.changeDefaults,
<add> defaults = defaults$5.exports.defaults;
<add> /**
<add> * Marked
<add> */
<add>
<add> function marked(src, opt, callback) {
<add> // throw error in case of non string input
<add> if (typeof src === 'undefined' || src === null) {
<add> throw new Error('marked(): input parameter is undefined or null');
<add> }
<add>
<add> if (typeof src !== 'string') {
<add> throw new Error('marked(): input parameter is of type ' + Object.prototype.toString.call(src) + ', string expected');
<add> }
<add>
<add> if (typeof opt === 'function') {
<add> callback = opt;
<add> opt = null;
<add> }
<add>
<add> opt = merge({}, marked.defaults, opt || {});
<add> checkSanitizeDeprecation(opt);
<add>
<add> if (callback) {
<add> var highlight = opt.highlight;
<add> var tokens;
<add>
<add> try {
<add> tokens = Lexer.lex(src, opt);
<add> } catch (e) {
<add> return callback(e);
<add> }
<add>
<add> var done = function done(err) {
<add> var out;
<add>
<add> if (!err) {
<add> try {
<add> if (opt.walkTokens) {
<add> marked.walkTokens(tokens, opt.walkTokens);
<add> }
<add>
<add> out = Parser.parse(tokens, opt);
<add> } catch (e) {
<add> err = e;
<add> }
<add> }
<add>
<add> opt.highlight = highlight;
<add> return err ? callback(err) : callback(null, out);
<add> };
<add>
<add> if (!highlight || highlight.length < 3) {
<add> return done();
<add> }
<add>
<add> delete opt.highlight;
<add> if (!tokens.length) return done();
<add> var pending = 0;
<add> marked.walkTokens(tokens, function (token) {
<add> if (token.type === 'code') {
<add> pending++;
<add> setTimeout(function () {
<add> highlight(token.text, token.lang, function (err, code) {
<add> if (err) {
<add> return done(err);
<add> }
<add>
<add> if (code != null && code !== token.text) {
<add> token.text = code;
<add> token.escaped = true;
<add> }
<add>
<add> pending--;
<add>
<add> if (pending === 0) {
<add> done();
<add> }
<add> });
<add> }, 0);
<add> }
<add> });
<add>
<add> if (pending === 0) {
<add> done();
<add> }
<add>
<add> return;
<add> }
<add>
<add> try {
<add> var _tokens = Lexer.lex(src, opt);
<add>
<add> if (opt.walkTokens) {
<add> marked.walkTokens(_tokens, opt.walkTokens);
<add> }
<add>
<add> return Parser.parse(_tokens, opt);
<add> } catch (e) {
<add> e.message += '\nPlease report this to https://github.com/markedjs/marked.';
<add>
<add> if (opt.silent) {
<add> return '<p>An error occurred:</p><pre>' + escape(e.message + '', true) + '</pre>';
<add> }
<add>
<add> throw e;
<add> }
<add> }
<add> /**
<add> * Options
<add> */
<add>
<add>
<add> marked.options = marked.setOptions = function (opt) {
<add> merge(marked.defaults, opt);
<add> changeDefaults(marked.defaults);
<add> return marked;
<add> };
<add>
<add> marked.getDefaults = getDefaults;
<add> marked.defaults = defaults;
<add> /**
<add> * Use Extension
<add> */
<add>
<add> marked.use = function () {
<add> var _this = this;
<add>
<add> for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
<add> args[_key] = arguments[_key];
<add> }
<add>
<add> var opts = merge.apply(void 0, [{}].concat(args));
<add> var extensions = marked.defaults.extensions || {
<add> renderers: {},
<add> childTokens: {}
<add> };
<add> var hasExtensions;
<add> args.forEach(function (pack) {
<add> // ==-- Parse "addon" extensions --== //
<add> if (pack.extensions) {
<add> hasExtensions = true;
<add> pack.extensions.forEach(function (ext) {
<add> if (!ext.name) {
<add> throw new Error('extension name required');
<add> }
<add>
<add> if (ext.renderer) {
<add> // Renderer extensions
<add> var prevRenderer = extensions.renderers ? extensions.renderers[ext.name] : null;
<add>
<add> if (prevRenderer) {
<add> // Replace extension with func to run new extension but fall back if false
<add> extensions.renderers[ext.name] = function () {
<add> for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
<add> args[_key2] = arguments[_key2];
<add> }
<add>
<add> var ret = ext.renderer.apply(this, args);
<add>
<add> if (ret === false) {
<add> ret = prevRenderer.apply(this, args);
<add> }
<add>
<add> return ret;
<add> };
<add> } else {
<add> extensions.renderers[ext.name] = ext.renderer;
<add> }
<add> }
<add>
<add> if (ext.tokenizer) {
<add> // Tokenizer Extensions
<add> if (!ext.level || ext.level !== 'block' && ext.level !== 'inline') {
<add> throw new Error("extension level must be 'block' or 'inline'");
<add> }
<add>
<add> if (extensions[ext.level]) {
<add> extensions[ext.level].unshift(ext.tokenizer);
<add> } else {
<add> extensions[ext.level] = [ext.tokenizer];
<add> }
<add>
<add> if (ext.start) {
<add> // Function to check for start of token
<add> if (ext.level === 'block') {
<add> if (extensions.startBlock) {
<add> extensions.startBlock.push(ext.start);
<add> } else {
<add> extensions.startBlock = [ext.start];
<add> }
<add> } else if (ext.level === 'inline') {
<add> if (extensions.startInline) {
<add> extensions.startInline.push(ext.start);
<add> } else {
<add> extensions.startInline = [ext.start];
<add> }
<add> }
<add> }
<add> }
<add>
<add> if (ext.childTokens) {
<add> // Child tokens to be visited by walkTokens
<add> extensions.childTokens[ext.name] = ext.childTokens;
<add> }
<add> });
<add> } // ==-- Parse "overwrite" extensions --== //
<add>
<add>
<add> if (pack.renderer) {
<add> (function () {
<add> var renderer = marked.defaults.renderer || new Renderer();
<add>
<add> var _loop = function _loop(prop) {
<add> var prevRenderer = renderer[prop]; // Replace renderer with func to run extension, but fall back if false
<add>
<add> renderer[prop] = function () {
<add> for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
<add> args[_key3] = arguments[_key3];
<add> }
<add>
<add> var ret = pack.renderer[prop].apply(renderer, args);
<add>
<add> if (ret === false) {
<add> ret = prevRenderer.apply(renderer, args);
<add> }
<add>
<add> return ret;
<add> };
<add> };
<add>
<add> for (var prop in pack.renderer) {
<add> _loop(prop);
<add> }
<add>
<add> opts.renderer = renderer;
<add> })();
<add> }
<add>
<add> if (pack.tokenizer) {
<add> (function () {
<add> var tokenizer = marked.defaults.tokenizer || new Tokenizer();
<add>
<add> var _loop2 = function _loop2(prop) {
<add> var prevTokenizer = tokenizer[prop]; // Replace tokenizer with func to run extension, but fall back if false
<add>
<add> tokenizer[prop] = function () {
<add> for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
<add> args[_key4] = arguments[_key4];
<add> }
<add>
<add> var ret = pack.tokenizer[prop].apply(tokenizer, args);
<add>
<add> if (ret === false) {
<add> ret = prevTokenizer.apply(tokenizer, args);
<add> }
<add>
<add> return ret;
<add> };
<add> };
<add>
<add> for (var prop in pack.tokenizer) {
<add> _loop2(prop);
<add> }
<add>
<add> opts.tokenizer = tokenizer;
<add> })();
<add> } // ==-- Parse WalkTokens extensions --== //
<add>
<add>
<add> if (pack.walkTokens) {
<add> var walkTokens = marked.defaults.walkTokens;
<add>
<add> opts.walkTokens = function (token) {
<add> pack.walkTokens.call(_this, token);
<add>
<add> if (walkTokens) {
<add> walkTokens(token);
<add> }
<add> };
<add> }
<add>
<add> if (hasExtensions) {
<add> opts.extensions = extensions;
<add> }
<add>
<add> marked.setOptions(opts);
<add> });
<add> };
<add> /**
<add> * Run callback for every token
<add> */
<add>
<add>
<add> marked.walkTokens = function (tokens, callback) {
<add> var _loop3 = function _loop3() {
<add> var token = _step.value;
<add> callback(token);
<add>
<add> switch (token.type) {
<add> case 'table':
<add> {
<add> for (var _iterator2 = _createForOfIteratorHelperLoose(token.header), _step2; !(_step2 = _iterator2()).done;) {
<add> var cell = _step2.value;
<add> marked.walkTokens(cell.tokens, callback);
<add> }
<add>
<add> for (var _iterator3 = _createForOfIteratorHelperLoose(token.rows), _step3; !(_step3 = _iterator3()).done;) {
<add> var row = _step3.value;
<add>
<add> for (var _iterator4 = _createForOfIteratorHelperLoose(row), _step4; !(_step4 = _iterator4()).done;) {
<add> var _cell = _step4.value;
<add> marked.walkTokens(_cell.tokens, callback);
<add> }
<add> }
<add>
<add> break;
<add> }
<add>
<add> case 'list':
<add> {
<add> marked.walkTokens(token.items, callback);
<add> break;
<add> }
<add>
<add> default:
<add> {
<add> if (marked.defaults.extensions && marked.defaults.extensions.childTokens && marked.defaults.extensions.childTokens[token.type]) {
<add> // Walk any extensions
<add> marked.defaults.extensions.childTokens[token.type].forEach(function (childTokens) {
<add> marked.walkTokens(token[childTokens], callback);
<add> });
<add> } else if (token.tokens) {
<add> marked.walkTokens(token.tokens, callback);
<add> }
<add> }
<add> }
<add> };
<add>
<add> for (var _iterator = _createForOfIteratorHelperLoose(tokens), _step; !(_step = _iterator()).done;) {
<add> _loop3();
<add> }
<add> };
<add> /**
<add> * Parse Inline
<add> */
<add>
<add>
<add> marked.parseInline = function (src, opt) {
<add> // throw error in case of non string input
<add> if (typeof src === 'undefined' || src === null) {
<add> throw new Error('marked.parseInline(): input parameter is undefined or null');
<add> }
<add>
<add> if (typeof src !== 'string') {
<add> throw new Error('marked.parseInline(): input parameter is of type ' + Object.prototype.toString.call(src) + ', string expected');
<add> }
<add>
<add> opt = merge({}, marked.defaults, opt || {});
<add> checkSanitizeDeprecation(opt);
<add>
<add> try {
<add> var tokens = Lexer.lexInline(src, opt);
<add>
<add> if (opt.walkTokens) {
<add> marked.walkTokens(tokens, opt.walkTokens);
<add> }
<add>
<add> return Parser.parseInline(tokens, opt);
<add> } catch (e) {
<add> e.message += '\nPlease report this to https://github.com/markedjs/marked.';
<add>
<add> if (opt.silent) {
<add> return '<p>An error occurred:</p><pre>' + escape(e.message + '', true) + '</pre>';
<add> }
<add>
<add> throw e;
<add> }
<add> };
<add> /**
<add> * Expose
<add> */
<add>
<add>
<add> marked.Parser = Parser;
<add> marked.parser = Parser.parse;
<add> marked.Renderer = Renderer;
<add> marked.TextRenderer = TextRenderer;
<add> marked.Lexer = Lexer;
<add> marked.lexer = Lexer.lex;
<add> marked.Tokenizer = Tokenizer;
<add> marked.Slugger = Slugger;
<add> marked.parse = marked;
<add> var marked_1 = marked;
<add>
<add> return marked_1;
<add>
<add>})));
<ide><path>test/parallel/test-snapshot-umd.js
<add>'use strict';
<add>
<add>// This tests the behavior of loading a UMD module with --build-snapshot
<add>
<add>require('../common');
<add>const assert = require('assert');
<add>const { spawnSync } = require('child_process');
<add>const tmpdir = require('../common/tmpdir');
<add>const fixtures = require('../common/fixtures');
<add>const path = require('path');
<add>const fs = require('fs');
<add>
<add>tmpdir.refresh();
<add>const blobPath = path.join(tmpdir.path, 'snapshot.blob');
<add>const file = fixtures.path('snapshot', 'marked.js');
<add>
<add>{
<add> // By default, the snapshot blob path is snapshot.blob at cwd
<add> const child = spawnSync(process.execPath, [
<add> '--snapshot-blob',
<add> blobPath,
<add> '--build-snapshot',
<add> file,
<add> ], {
<add> cwd: tmpdir.path
<add> });
<add> const stderr = child.stderr.toString();
<add> const stdout = child.stdout.toString();
<add> console.log(stderr);
<add> console.log(stdout);
<add> assert.strictEqual(child.status, 0);
<add>
<add> const stats = fs.statSync(path.join(tmpdir.path, 'snapshot.blob'));
<add> assert(stats.isFile());
<add>}
<add>
<add>{
<add> let child = spawnSync(process.execPath, [
<add> '--snapshot-blob',
<add> path.join(tmpdir.path, 'snapshot.blob'),
<add> fixtures.path('snapshot', 'check-marked.js'),
<add> ], {
<add> cwd: tmpdir.path,
<add> env: {
<add> ...process.env,
<add> NODE_TEST_USE_SNAPSHOT: 'true'
<add> }
<add> });
<add> let stderr = child.stderr.toString();
<add> const snapshotOutput = child.stdout.toString();
<add> console.log(stderr);
<add> console.log(snapshotOutput);
<add>
<add> assert.strictEqual(child.status, 0);
<add> assert(stderr.includes('NODE_TEST_USE_SNAPSHOT true'));
<add>
<add> child = spawnSync(process.execPath, [
<add> '--snapshot-blob',
<add> blobPath,
<add> fixtures.path('snapshot', 'check-marked.js'),
<add> ], {
<add> cwd: tmpdir.path,
<add> env: {
<add> ...process.env,
<add> NODE_TEST_USE_SNAPSHOT: 'false'
<add> }
<add> });
<add> stderr = child.stderr.toString();
<add> const verifyOutput = child.stdout.toString();
<add> console.log(stderr);
<add> console.log(verifyOutput);
<add>
<add> assert.strictEqual(child.status, 0);
<add> assert(stderr.includes('NODE_TEST_USE_SNAPSHOT false'));
<add>
<add> assert(snapshotOutput.includes(verifyOutput));
<add>} | 3 |
Python | Python | remove useless strings from translation | d3a36c58b845259233f30737b900826412624a81 | <ide><path>glances/plugins/glances_now.py
<ide> def msg_curse(self, args=None):
<ide>
<ide> # Build the string message
<ide> # 23 is the padding for the process list
<del> msg = _("{0:23}").format(self.stats)
<add> msg = '{0:23}'.format(self.stats)
<ide> ret.append(self.curse_add_line(msg))
<ide>
<ide> return ret
<ide><path>glances/plugins/glances_system.py
<ide> def msg_curse(self, args=None):
<ide> ret.append(self.curse_add_line(msg, 'CRITICAL'))
<ide>
<ide> # Hostname is mandatory
<del> msg = _("{0}").format(self.stats['hostname'])
<add> msg = self.stats['hostname']
<ide> ret.append(self.curse_add_line(msg, "TITLE"))
<ide> # System info
<ide> if self.stats['os_name'] == "Linux":
<del> msg = _(" ({0} {1} / {2} {3})").format(self.stats['linux_distro'],
<del> self.stats['platform'],
<del> self.stats['os_name'],
<del> self.stats['os_version'])
<add> msg = " ({0} {1} / {2} {3})".format(self.stats['linux_distro'],
<add> self.stats['platform'],
<add> self.stats['os_name'],
<add> self.stats['os_version'])
<ide> else:
<ide> try:
<del> msg = _(" ({0} {1} {2})").format(self.stats['os_name'],
<del> self.stats['os_version'],
<del> self.stats['platform'])
<add> msg = " ({0} {1} {2})".format(self.stats['os_name'],
<add> self.stats['os_version'],
<add> self.stats['platform'])
<ide> except:
<del> msg = _(" ({0})").format(self.stats['os_name'])
<add> msg = " ({0})".format(self.stats['os_name'])
<ide> ret.append(self.curse_add_line(msg, optional=True))
<ide>
<ide> # Return the message with decoration | 2 |
Python | Python | use consistent docstring format | 4d83eba0b9cfa6beecd4dddeaba5040aa5a7b4f0 | <ide><path>libcloud/compute/drivers/cloudstack.py
<ide>
<ide>
<ide> class CloudStackNode(Node):
<del> "Subclass of Node so we can expose our extension methods."
<add> """
<add> Subclass of Node so we can expose our extension methods.
<add> """
<ide>
<ide> def ex_allocate_public_ip(self):
<del> "Allocate a public IP and bind it to this node."
<add> """
<add> Allocate a public IP and bind it to this node.
<add> """
<ide> return self.driver.ex_allocate_public_ip(self)
<ide>
<ide> def ex_release_public_ip(self, address):
<del> "Release a public IP that this node holds."
<add> """
<add> Release a public IP that this node holds.
<add> """
<ide> return self.driver.ex_release_public_ip(self, address)
<ide>
<ide> def ex_create_ip_forwarding_rule(self, address, protocol,
<ide> start_port, end_port=None):
<del> "Add a NAT/firewall forwarding rule for a port or ports."
<add> """
<add> Add a NAT/firewall forwarding rule for a port or ports.
<add> """
<ide> return self.driver.ex_create_ip_forwarding_rule(node=self,
<ide> address=address,
<ide> protocol=protocol,
<ide> def ex_create_port_forwarding_rule(self, address,
<ide> public_end_port=None,
<ide> private_end_port=None,
<ide> openfirewall=True):
<del> "Add a port forwarding rule for port or ports."
<add> """
<add> Add a port forwarding rule for port or ports.
<add> """
<ide> return self.driver.ex_create_port_forwarding_rule(node=self,
<ide> address=
<ide> address,
<ide> def ex_create_port_forwarding_rule(self, address,
<ide> openfirewall)
<ide>
<ide> def ex_delete_ip_forwarding_rule(self, rule):
<del> "Delete a port forwarding rule."
<add> """
<add> Delete a port forwarding rule.
<add> """
<ide> return self.driver.ex_delete_ip_forwarding_rule(node=self, rule=rule)
<ide>
<ide> def ex_delete_port_forwarding_rule(self, rule):
<del> "Delete a NAT/firewall rule."
<add> """
<add> Delete a NAT/firewall rule.
<add> """
<ide> return self.driver.ex_delete_port_forwarding_rule(node=self, rule=rule)
<ide>
<ide> def ex_start(self):
<del> "Starts a stopped virtual machine"
<add> """
<add> Starts a stopped virtual machine.
<add> """
<ide> return self.driver.ex_start(node=self)
<ide>
<ide> def ex_stop(self):
<del> "Stops a running virtual machine"
<add> """
<add> Stops a running virtual machine.
<add> """
<ide> return self.driver.ex_stop(node=self)
<ide>
<ide>
<ide> class CloudStackAddress(object):
<del> "A public IP address."
<add> """
<add> A public IP address.
<add> """
<ide>
<ide> def __init__(self, id, address, driver):
<ide> self.id = id
<ide> def __eq__(self, other):
<ide>
<ide>
<ide> class CloudStackIPForwardingRule(object):
<del> "A NAT/firewall forwarding rule."
<add> """
<add> A NAT/firewall forwarding rule.
<add> """
<ide>
<ide> def __init__(self, node, id, address, protocol, start_port, end_port=None):
<ide> self.node = node
<ide> def __eq__(self, other):
<ide>
<ide>
<ide> class CloudStackPortForwardingRule(object):
<del> "A Port forwarding rule for Source NAT."
<add> """
<add> A Port forwarding rule for Source NAT.
<add> """
<ide>
<ide> def __init__(self, node, rule_id, address, protocol, public_port,
<ide> private_port, public_end_port=None, private_end_port=None):
<ide> def __eq__(self, other):
<ide>
<ide>
<ide> class CloudStackDiskOffering(object):
<del> """A disk offering within CloudStack."""
<add> """
<add> A disk offering within CloudStack.
<add> """
<ide>
<ide> def __init__(self, id, name, size, customizable):
<ide> self.id = id
<ide> def __eq__(self, other):
<ide>
<ide>
<ide> class CloudStackNetwork(object):
<del> """Class representing a CloudStack Network"""
<add> """
<add> Class representing a CloudStack Network.
<add> """
<ide>
<ide> def __init__(self, displaytext, name, networkofferingid, id, zoneid,
<ide> driver):
<ide> def __repr__(self):
<ide>
<ide>
<ide> class CloudStackNodeDriver(CloudStackDriverMixIn, NodeDriver):
<del> """Driver for the CloudStack API.
<add> """
<add> Driver for the CloudStack API.
<ide>
<ide> :cvar host: The host where the API can be reached.
<ide> :cvar path: The path where the API can be reached. | 1 |
Text | Text | remove erroneous entrypoint note | f44d78b47838204b85204711d014b7f4cf7826ec | <ide><path>docs/reference/builder.md
<ide> sys 0m 0.03s
<ide> > `ENTRYPOINT [ "echo", "$HOME" ]` will not do variable substitution on `$HOME`.
<ide> > If you want shell processing then either use the *shell* form or execute
<ide> > a shell directly, for example: `ENTRYPOINT [ "sh", "-c", "echo $HOME" ]`.
<del>> Variables that are defined in the `Dockerfile`using `ENV`, will be substituted by
<del>> the `Dockerfile` parser.
<ide>
<ide> ### Shell form ENTRYPOINT example
<ide> | 1 |
Text | Text | react devtools 4.10.0 -> 4.10.1 | 3a8c04e3b234d8f54b35fa07796f4db8311bcbbd | <ide><path>packages/react-devtools/CHANGELOG.md
<ide>
<ide> ## 4.10.1 (November 12, 2020)
<ide> #### Bugfix
<del>* Fixed invalid internal work tag mappings ([bvaughn](https://github.com/bvaughn) in [#20380](https://github.com/facebook/react/pull/20380))
<add>* Fixed invalid internal work tag mappings ([bvaughn](https://github.com/bvaughn) in [#20362](https://github.com/facebook/react/pull/20362))
<ide>
<ide> ## 4.10.0 (November 12, 2020)
<ide> #### Features | 1 |
Python | Python | implement like_num getter for french (via ) | bb5c6314029cc598b667542579fad347044422e9 | <ide><path>spacy/lang/fr/__init__.py
<ide> from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS, TOKEN_MATCH
<ide> from .punctuation import TOKENIZER_SUFFIXES, TOKENIZER_INFIXES
<ide> from .stop_words import STOP_WORDS
<add>from .lex_attrs import LEX_ATTRS
<ide> from .lemmatizer import LOOKUP
<ide> from .syntax_iterators import SYNTAX_ITERATORS
<ide>
<ide>
<ide> class FrenchDefaults(Language.Defaults):
<ide> lex_attr_getters = dict(Language.Defaults.lex_attr_getters)
<add> lex_attr_getters.update(LEX_ATTRS)
<ide> lex_attr_getters[LANG] = lambda text: 'fr'
<ide> lex_attr_getters[NORM] = add_lookups(Language.Defaults.lex_attr_getters[NORM], BASE_NORMS)
<ide>
<ide><path>spacy/lang/fr/lex_attrs.py
<add># coding: utf8
<add>from __future__ import unicode_literals
<add>
<add>from ...attrs import LIKE_NUM
<add>
<add>
<add>_num_words = set("""
<add>zero un deux trois quatre cinq six sept huit neuf dix
<add>onze douze treize quatorze quinze seize dix-sept dix-huit dix-neuf
<add>vingt trente quanrante cinquante soixante septante quatre-vingt huitante nonante
<add>cent mille mil million milliard billion quadrillion quintillion
<add>sextillion septillion octillion nonillion decillion
<add>""".split())
<add>
<add>_ordinal_words = set("""
<add>premier deuxième second troisième quatrième cinquième sixième septième huitième neuvième dixième
<add>onzième douzième treizième quatorzième quinzième seizième dix-septième dix-huitième dix-neufième
<add>vingtième trentième quanrantième cinquantième soixantième septantième quatre-vingtième huitantième nonantième
<add>centième millième millionnième milliardième billionnième quadrillionnième quintillionnième
<add>sextillionnième septillionnième octillionnième nonillionnième decillionnième
<add>""".split())
<add>
<add>
<add>def like_num(text):
<add> # Might require more work?
<add> # See this discussion: https://github.com/explosion/spaCy/pull/1161
<add> text = text.replace(',', '').replace('.', '')
<add> if text.isdigit():
<add> return True
<add> if text.count('/') == 1:
<add> num, denom = text.split('/')
<add> if num.isdigit() and denom.isdigit():
<add> return True
<add> if text in _num_words:
<add> return True
<add> return False
<add>
<add>
<add>LEX_ATTRS = {
<add> LIKE_NUM: like_num
<add>} | 2 |
Javascript | Javascript | replace __definegetter__ with defineproperty | 8636af10129e822d8ae928ef3470a4dff9c4192a | <ide><path>lib/net.js
<ide> Socket.prototype._getpeername = function() {
<ide> return this._peername;
<ide> };
<ide>
<del>Socket.prototype.__defineGetter__('bytesRead', function() {
<add>function protoGetter(name, callback) {
<add> Object.defineProperty(Socket.prototype, name, {
<add> configurable: false,
<add> enumerable: true,
<add> get: callback
<add> });
<add>}
<add>
<add>protoGetter('bytesRead', function bytesRead() {
<ide> return this._handle ? this._handle.bytesRead : this[BYTES_READ];
<ide> });
<ide>
<del>Socket.prototype.__defineGetter__('remoteAddress', function() {
<add>protoGetter('remoteAddress', function remoteAddress() {
<ide> return this._getpeername().address;
<ide> });
<ide>
<del>Socket.prototype.__defineGetter__('remoteFamily', function() {
<add>protoGetter('remoteFamily', function remoteFamily() {
<ide> return this._getpeername().family;
<ide> });
<ide>
<del>Socket.prototype.__defineGetter__('remotePort', function() {
<add>protoGetter('remotePort', function remotePort() {
<ide> return this._getpeername().port;
<ide> });
<ide>
<ide> Socket.prototype._getsockname = function() {
<ide> };
<ide>
<ide>
<del>Socket.prototype.__defineGetter__('localAddress', function() {
<add>protoGetter('localAddress', function localAddress() {
<ide> return this._getsockname().address;
<ide> });
<ide>
<ide>
<del>Socket.prototype.__defineGetter__('localPort', function() {
<add>protoGetter('localPort', function localPort() {
<ide> return this._getsockname().port;
<ide> });
<ide>
<ide> function createWriteReq(req, handle, data, encoding) {
<ide> }
<ide>
<ide>
<del>Socket.prototype.__defineGetter__('bytesWritten', function() {
<add>protoGetter('bytesWritten', function bytesWritten() {
<ide> var bytes = this._bytesDispatched;
<ide> const state = this._writableState;
<ide> const data = this._pendingData; | 1 |
Java | Java | improve limit handling in stringdecoder | a741ae422b75e330dac655718ad91e0067a2caeb | <ide><path>spring-core/src/main/java/org/springframework/core/codec/StringDecoder.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2020 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public Flux<String> decode(Publisher<DataBuffer> input, ResolvableType elementTy
<ide>
<ide> byte[][] delimiterBytes = getDelimiterBytes(mimeType);
<ide>
<del> // TODO: Drop Consumer and use bufferUntil with Supplier<LimistedDataBufferList> (reactor-core#1925)
<del> // TODO: Drop doOnDiscard(LimitedDataBufferList.class, ...) (reactor-core#1924)
<del> LimitedDataBufferConsumer limiter = new LimitedDataBufferConsumer(getMaxInMemorySize());
<del>
<ide> Flux<DataBuffer> inputFlux = Flux.defer(() -> {
<ide> DataBufferUtils.Matcher matcher = DataBufferUtils.matcher(delimiterBytes);
<del> return Flux.from(input)
<del> .concatMapIterable(buffer -> endFrameAfterDelimiter(buffer, matcher))
<del> .doOnNext(limiter)
<del> .bufferUntil(buffer -> buffer instanceof EndFrameBuffer)
<del> .map(buffers -> joinAndStrip(buffers, this.stripDelimiter))
<del> .doOnDiscard(LimitedDataBufferList.class, LimitedDataBufferList::releaseAndClear)
<del> .doOnDiscard(PooledDataBuffer.class, DataBufferUtils::release);
<add> if (getMaxInMemorySize() != -1) {
<add>
<add> // Passing limiter into endFrameAfterDelimiter helps to ensure that in case of one DataBuffer
<add> // containing multiple lines, the limit is checked and raised immediately without accumulating
<add> // subsequent lines. This is necessary because concatMapIterable doesn't respect doOnDiscard.
<add> // When reactor-core#1925 is resolved, we could replace bufferUntil with:
<add>
<add> // .windowUntil(buffer -> buffer instanceof EndFrameBuffer)
<add> // .concatMap(fluxes -> fluxes.collect(() -> new LimitedDataBufferList(getMaxInMemorySize()), LimitedDataBufferList::add))
<add>
<add> LimitedDataBufferList limiter = new LimitedDataBufferList(getMaxInMemorySize());
<add>
<add> return Flux.from(input)
<add> .concatMapIterable(buffer -> endFrameAfterDelimiter(buffer, matcher, limiter))
<add> .bufferUntil(buffer -> buffer instanceof EndFrameBuffer)
<add> .map(buffers -> joinAndStrip(buffers, this.stripDelimiter))
<add> .doOnDiscard(PooledDataBuffer.class, DataBufferUtils::release);
<add> }
<add> else {
<ide>
<add> // When the decoder is unlimited (-1), concatMapIterable will cache buffers that may not
<add> // be released if cancel is signalled before they are turned into String lines
<add> // (see test maxInMemoryLimitReleasesUnprocessedLinesWhenUnlimited).
<add> // When reactor-core#1925 is resolved, the workaround can be removed and the entire
<add> // else clause possibly dropped.
<add>
<add> ConcatMapIterableDiscardWorkaroundCache cache = new ConcatMapIterableDiscardWorkaroundCache();
<add>
<add> return Flux.from(input)
<add> .concatMapIterable(buffer -> cache.addAll(endFrameAfterDelimiter(buffer, matcher, null)))
<add> .doOnNext(cache)
<add> .doOnCancel(cache)
<add> .bufferUntil(buffer -> buffer instanceof EndFrameBuffer)
<add> .map(buffers -> joinAndStrip(buffers, this.stripDelimiter))
<add> .doOnDiscard(PooledDataBuffer.class, DataBufferUtils::release);
<add> }
<ide> });
<ide>
<ide> return super.decode(inputFlux, elementType, mimeType, hints);
<ide> private static Charset getCharset(@Nullable MimeType mimeType) {
<ide> *
<ide> * @param dataBuffer the buffer to find delimiters in
<ide> * @param matcher used to find the first delimiters
<add> * @param limiter to enforce maxInMemorySize with
<ide> * @return a flux of buffers, containing {@link EndFrameBuffer} after each delimiter that was
<ide> * found in {@code dataBuffer}. Returns Flux, because returning List (w/ flatMapIterable)
<ide> * results in memory leaks due to pre-fetching.
<ide> */
<del> private static List<DataBuffer> endFrameAfterDelimiter(DataBuffer dataBuffer, DataBufferUtils.Matcher matcher) {
<add> private static List<DataBuffer> endFrameAfterDelimiter(
<add> DataBuffer dataBuffer, DataBufferUtils.Matcher matcher, @Nullable LimitedDataBufferList limiter) {
<add>
<ide> List<DataBuffer> result = new ArrayList<>();
<del> do {
<del> int endIdx = matcher.match(dataBuffer);
<del> if (endIdx != -1) {
<del> int readPosition = dataBuffer.readPosition();
<del> int length = endIdx - readPosition + 1;
<del> result.add(dataBuffer.retainedSlice(readPosition, length));
<del> result.add(new EndFrameBuffer(matcher.delimiter()));
<del> dataBuffer.readPosition(endIdx + 1);
<add> try {
<add> do {
<add> int endIdx = matcher.match(dataBuffer);
<add> if (endIdx != -1) {
<add> int readPosition = dataBuffer.readPosition();
<add> int length = (endIdx - readPosition + 1);
<add> DataBuffer slice = dataBuffer.retainedSlice(readPosition, length);
<add> result.add(slice);
<add> result.add(new EndFrameBuffer(matcher.delimiter()));
<add> dataBuffer.readPosition(endIdx + 1);
<add> if (limiter != null) {
<add> limiter.add(slice); // enforce the limit
<add> limiter.clear();
<add> }
<add> }
<add> else {
<add> result.add(DataBufferUtils.retain(dataBuffer));
<add> if (limiter != null) {
<add> limiter.add(dataBuffer);
<add> }
<add> break;
<add> }
<ide> }
<del> else {
<del> result.add(DataBufferUtils.retain(dataBuffer));
<del> break;
<add> while (dataBuffer.readableByteCount() > 0);
<add> }
<add> catch (DataBufferLimitException ex) {
<add> if (limiter != null) {
<add> limiter.releaseAndClear();
<ide> }
<add> throw ex;
<add> }
<add> finally {
<add> DataBufferUtils.release(dataBuffer);
<ide> }
<del> while (dataBuffer.readableByteCount() > 0);
<del>
<del> DataBufferUtils.release(dataBuffer);
<ide> return result;
<ide> }
<ide>
<ide> public byte[] delimiter() {
<ide> }
<ide>
<ide>
<del> /**
<del> * Temporary measure for reactor-core#1925.
<del> * Consumer that adds to a {@link LimitedDataBufferList} to enforce limits.
<del> */
<del> private static class LimitedDataBufferConsumer implements Consumer<DataBuffer> {
<add> private class ConcatMapIterableDiscardWorkaroundCache implements Consumer<DataBuffer>, Runnable {
<ide>
<del> private final LimitedDataBufferList bufferList;
<add> private final List<DataBuffer> buffers = new ArrayList<>();
<ide>
<ide>
<del> public LimitedDataBufferConsumer(int maxInMemorySize) {
<del> this.bufferList = new LimitedDataBufferList(maxInMemorySize);
<add> public List<DataBuffer> addAll(List<DataBuffer> buffersToAdd) {
<add> this.buffers.addAll(buffersToAdd);
<add> return buffersToAdd;
<ide> }
<ide>
<add> @Override
<add> public void accept(DataBuffer dataBuffer) {
<add> this.buffers.remove(dataBuffer);
<add> }
<ide>
<ide> @Override
<del> public void accept(DataBuffer buffer) {
<del> if (buffer instanceof EndFrameBuffer) {
<del> this.bufferList.clear();
<del> }
<del> else {
<add> public void run() {
<add> this.buffers.forEach(buffer -> {
<ide> try {
<del> this.bufferList.add(buffer);
<del> }
<del> catch (DataBufferLimitException ex) {
<ide> DataBufferUtils.release(buffer);
<del> throw ex;
<ide> }
<del> }
<add> catch (Throwable ex) {
<add> // Keep going..
<add> }
<add> });
<ide> }
<ide> }
<add>
<ide> }
<ide><path>spring-core/src/test/java/org/springframework/core/codec/StringDecoderTests.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2020 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> void decodeNewLine() {
<ide> }
<ide>
<ide> @Test
<del> void decodeNewLineWithLimit() {
<add> void maxInMemoryLimit() {
<ide> Flux<DataBuffer> input = Flux.just(
<del> stringBuffer("abc\n"),
<del> stringBuffer("defg\n"),
<del> stringBuffer("hijkl\n")
<del> );
<del> this.decoder.setMaxInMemorySize(5);
<add> stringBuffer("abc\n"), stringBuffer("defg\n"), stringBuffer("hijkl\n"));
<ide>
<add> this.decoder.setMaxInMemorySize(5);
<ide> testDecode(input, String.class, step ->
<del> step.expectNext("abc", "defg")
<del> .verifyError(DataBufferLimitException.class));
<add> step.expectNext("abc", "defg").verifyError(DataBufferLimitException.class));
<add> }
<add>
<add> @Test // gh-24312
<add> void maxInMemoryLimitReleaseUnprocessedLinesFromCurrentBuffer() {
<add> Flux<DataBuffer> input = Flux.just(
<add> stringBuffer("TOO MUCH DATA\nanother line\n\nand another\n"));
<add>
<add> this.decoder.setMaxInMemorySize(5);
<add> testDecode(input, String.class, step -> step.verifyError(DataBufferLimitException.class));
<add> }
<add>
<add> @Test // gh-24339
<add> void maxInMemoryLimitReleaseUnprocessedLinesWhenUnlimited() {
<add> Flux<DataBuffer> input = Flux.just(stringBuffer("Line 1\nLine 2\nLine 3\n"));
<add>
<add> this.decoder.setMaxInMemorySize(-1);
<add> testDecodeCancel(input, ResolvableType.forClass(String.class), null, Collections.emptyMap());
<ide> }
<ide>
<ide> @Test | 2 |
Java | Java | resolve remaining nullability warnings | 47a7475898fc918e2f945206e3364bdaab2bb39f | <ide><path>spring-aop/src/main/java/org/springframework/aop/target/CommonsPool2TargetSource.java
<ide> /*
<del> * Copyright 2002-2016 the original author or authors.
<add> * Copyright 2002-2017 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
<ide>
<ide> import org.springframework.lang.Nullable;
<add>import org.springframework.util.Assert;
<ide>
<ide> /**
<ide> * {@link org.springframework.aop.TargetSource} implementation that holds
<ide> protected ObjectPool createObjectPool() {
<ide> */
<ide> @Override
<ide> public Object getTarget() throws Exception {
<add> Assert.state(this.pool != null, "No Commons ObjectPool available");
<ide> return this.pool.borrowObject();
<ide> }
<ide>
<ide> public Object getTarget() throws Exception {
<ide> */
<ide> @Override
<ide> public void releaseTarget(Object target) throws Exception {
<del> this.pool.returnObject(target);
<add> if (this.pool != null) {
<add> this.pool.returnObject(target);
<add> }
<ide> }
<ide>
<ide> @Override
<ide> public int getActiveCount() throws UnsupportedOperationException {
<del> return this.pool.getNumActive();
<add> return (this.pool != null ? this.pool.getNumActive() : 0);
<ide> }
<ide>
<ide> @Override
<ide> public int getIdleCount() throws UnsupportedOperationException {
<del> return this.pool.getNumIdle();
<add> return (this.pool != null ? this.pool.getNumIdle() : 0);
<ide> }
<ide>
<ide>
<ide> public int getIdleCount() throws UnsupportedOperationException {
<ide> */
<ide> @Override
<ide> public void destroy() throws Exception {
<del> logger.debug("Closing Commons ObjectPool");
<del> this.pool.close();
<add> if (this.pool != null) {
<add> logger.debug("Closing Commons ObjectPool");
<add> this.pool.close();
<add> }
<ide> }
<ide>
<ide>
<ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/JdbcTemplate.java
<ide> public void query(String sql, RowCallbackHandler rch) throws DataAccessException
<ide>
<ide> @Override
<ide> public <T> List<T> query(String sql, RowMapper<T> rowMapper) throws DataAccessException {
<del> List<T> result = query(sql, new RowMapperResultSetExtractor<>(rowMapper));
<del> Assert.state(result != null, "No result list");
<del> return result;
<add> return nonNull(query(sql, new RowMapperResultSetExtractor<>(rowMapper)));
<ide> }
<ide>
<ide> @Override
<ide> public Map<String, Object> queryForMap(String sql) throws DataAccessException {
<del> return queryForObject(sql, getColumnMapRowMapper());
<add> return nonNull(queryForObject(sql, getColumnMapRowMapper()));
<ide> }
<ide>
<ide> @Override
<ide> public List<Map<String, Object>> queryForList(String sql) throws DataAccessExcep
<ide>
<ide> @Override
<ide> public SqlRowSet queryForRowSet(String sql) throws DataAccessException {
<del> SqlRowSet result = query(sql, new SqlRowSetResultSetExtractor());
<del> Assert.state(result != null, "No SqlRowSet");
<del> return result;
<add> return nonNull(query(sql, new SqlRowSetResultSetExtractor()));
<ide> }
<ide>
<ide> @Override
<ide> public <T> T queryForObject(String sql, Class<T> requiredType, @Nullable Object.
<ide>
<ide> @Override
<ide> public Map<String, Object> queryForMap(String sql, Object[] args, int[] argTypes) throws DataAccessException {
<del> return queryForObject(sql, args, argTypes, getColumnMapRowMapper());
<add> return nonNull(queryForObject(sql, args, argTypes, getColumnMapRowMapper()));
<ide> }
<ide>
<ide> @Override
<ide> public Map<String, Object> queryForMap(String sql, @Nullable Object... args) throws DataAccessException {
<del> return queryForObject(sql, args, getColumnMapRowMapper());
<add> return nonNull(queryForObject(sql, args, getColumnMapRowMapper()));
<ide> }
<ide>
<ide> @Override
<ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/namedparam/NamedParameterJdbcTemplate.java
<ide> public <T> T queryForObject(String sql, Map<String, ?> paramMap, Class<T> requir
<ide>
<ide> @Override
<ide> public Map<String, Object> queryForMap(String sql, SqlParameterSource paramSource) throws DataAccessException {
<del> return queryForObject(sql, paramSource, new ColumnMapRowMapper());
<add> Map<String, Object> result = queryForObject(sql, paramSource, new ColumnMapRowMapper());
<add> Assert.state(result != null, "No result map");
<add> return result;
<ide> }
<ide>
<ide> @Override
<ide> public Map<String, Object> queryForMap(String sql, Map<String, ?> paramMap) throws DataAccessException {
<del> return queryForObject(sql, paramMap, new ColumnMapRowMapper());
<add> Map<String, Object> result = queryForObject(sql, paramMap, new ColumnMapRowMapper());
<add> Assert.state(result != null, "No result map");
<add> return result;
<ide> }
<ide>
<ide> @Override
<ide><path>spring-jms/src/main/java/org/springframework/jms/listener/adapter/MessageListenerAdapter.java
<ide> public void onMessage(Message message, @Nullable Session session) throws JMSExce
<ide> // Regular case: find a handler method reflectively.
<ide> Object convertedMessage = extractMessage(message);
<ide> String methodName = getListenerMethodName(message, convertedMessage);
<del> if (methodName == null) {
<del> throw new javax.jms.IllegalStateException("No default listener method specified: " +
<del> "Either specify a non-null value for the 'defaultListenerMethod' property or " +
<del> "override the 'getListenerMethodName' method.");
<del> }
<ide>
<ide> // Invoke the handler method with appropriate arguments.
<ide> Object[] listenerArguments = buildListenerArguments(convertedMessage);
<ide><path>spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessageListenerAdapterTests.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2017 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import java.io.ByteArrayInputStream;
<ide> import java.io.Serializable;
<ide> import javax.jms.BytesMessage;
<del>import javax.jms.IllegalStateException;
<ide> import javax.jms.InvalidDestinationException;
<ide> import javax.jms.JMSException;
<ide> import javax.jms.Message;
<ide> protected Object extractMessage(Message message) {
<ide> catch (ListenerExecutionFailedException ex) { /* expected */ }
<ide> }
<ide>
<del> @Test
<del> public void testFailsIfNoDefaultListenerMethodNameIsSupplied() throws Exception {
<del> final TextMessage message = mock(TextMessage.class);
<del> given(message.getText()).willReturn(TEXT);
<del>
<del> final MessageListenerAdapter adapter = new MessageListenerAdapter() {
<del> @Override
<del> protected void handleListenerException(Throwable ex) {
<del> assertTrue(ex instanceof IllegalStateException);
<del> }
<del> };
<del> adapter.setDefaultListenerMethod(null);
<del> adapter.onMessage(message);
<del> }
<del>
<del> @Test
<del> public void testFailsWhenOverriddenGetListenerMethodNameReturnsNull() throws Exception {
<del> final TextMessage message = mock(TextMessage.class);
<del> given(message.getText()).willReturn(TEXT);
<del>
<del> final MessageListenerAdapter adapter = new MessageListenerAdapter() {
<del> @Override
<del> protected void handleListenerException(Throwable ex) {
<del> assertTrue(ex instanceof javax.jms.IllegalStateException);
<del> }
<del> @Override
<del> protected String getListenerMethodName(Message originalMessage, Object extractedMessage) {
<del> return null;
<del> }
<del> };
<del> adapter.setDefaultListenerMethod(null);
<del> adapter.onMessage(message);
<del> }
<del>
<ide> @Test
<ide> public void testWithResponsiveMessageDelegateWhenReturnTypeIsNotAJMSMessageAndNoMessageConverterIsSupplied() throws Exception {
<ide> final TextMessage sentTextMessage = mock(TextMessage.class);
<ide><path>spring-web/src/main/java/org/springframework/http/MediaType.java
<ide> public static MediaType parseMediaType(String mediaType) {
<ide> * @return the list of media types
<ide> * @throws InvalidMediaTypeException if the media type value cannot be parsed
<ide> */
<del> public static List<MediaType> parseMediaTypes(String mediaTypes) {
<add> public static List<MediaType> parseMediaTypes(@Nullable String mediaTypes) {
<ide> if (!StringUtils.hasLength(mediaTypes)) {
<ide> return Collections.emptyList();
<ide> }
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/condition/AbstractNameValueExpression.java
<ide> /*
<del> * Copyright 2002-2016 the original author or authors.
<add> * Copyright 2002-2017 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> package org.springframework.web.reactive.result.condition;
<ide>
<ide> import org.springframework.lang.Nullable;
<add>import org.springframework.util.ObjectUtils;
<ide> import org.springframework.web.server.ServerWebExchange;
<ide>
<ide> /**
<ide>
<ide> protected final boolean isNegated;
<ide>
<add>
<ide> AbstractNameValueExpression(String expression) {
<ide> int separator = expression.indexOf('=');
<ide> if (separator == -1) {
<ide> this.isNegated = expression.startsWith("!");
<del> this.name = isNegated ? expression.substring(1) : expression;
<add> this.name = (this.isNegated ? expression.substring(1) : expression);
<ide> this.value = null;
<ide> }
<ide> else {
<ide> this.isNegated = (separator > 0) && (expression.charAt(separator - 1) == '!');
<del> this.name = isNegated ? expression.substring(0, separator - 1) : expression.substring(0, separator);
<add> this.name = (this.isNegated ? expression.substring(0, separator - 1) : expression.substring(0, separator));
<ide> this.value = parseValue(expression.substring(separator + 1));
<ide> }
<ide> }
<ide>
<add>
<ide> @Override
<ide> public String getName() {
<ide> return this.name;
<ide> public boolean isNegated() {
<ide> return this.isNegated;
<ide> }
<ide>
<del> protected abstract boolean isCaseSensitiveName();
<del>
<del> protected abstract T parseValue(String valueExpression);
<del>
<ide> public final boolean match(ServerWebExchange exchange) {
<ide> boolean isMatch;
<ide> if (this.value != null) {
<ide> public final boolean match(ServerWebExchange exchange) {
<ide> return this.isNegated != isMatch;
<ide> }
<ide>
<add>
<add> protected abstract boolean isCaseSensitiveName();
<add>
<add> protected abstract T parseValue(String valueExpression);
<add>
<ide> protected abstract boolean matchName(ServerWebExchange exchange);
<ide>
<ide> protected abstract boolean matchValue(ServerWebExchange exchange);
<ide>
<add>
<ide> @Override
<ide> public boolean equals(Object obj) {
<ide> if (this == obj) {
<ide> public boolean equals(Object obj) {
<ide>
<ide> @Override
<ide> public int hashCode() {
<del> int result = isCaseSensitiveName() ? name.hashCode() : name.toLowerCase().hashCode();
<del> result = 31 * result + (value != null ? value.hashCode() : 0);
<del> result = 31 * result + (isNegated ? 1 : 0);
<add> int result = (isCaseSensitiveName() ? this.name : this.name.toLowerCase()).hashCode();
<add> result = 31 * result + ObjectUtils.nullSafeHashCode(this.value);
<add> result = 31 * result + (this.isNegated ? 1 : 0);
<ide> return result;
<ide> }
<ide>
<ide> @Override
<ide> public String toString() {
<ide> StringBuilder builder = new StringBuilder();
<del> if (value != null) {
<del> builder.append(name);
<del> if (isNegated) {
<add> if (this.value != null) {
<add> builder.append(this.name);
<add> if (this.isNegated) {
<ide> builder.append('!');
<ide> }
<ide> builder.append('=');
<del> builder.append(value);
<add> builder.append(this.value);
<ide> }
<ide> else {
<del> if (isNegated) {
<add> if (this.isNegated) {
<ide> builder.append('!');
<ide> }
<del> builder.append(name);
<add> builder.append(this.name);
<ide> }
<ide> return builder.toString();
<ide> }
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/condition/HeadersRequestCondition.java
<ide> /*
<del> * Copyright 2002-2016 the original author or authors.
<add> * Copyright 2002-2017 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> protected String parseValue(String valueExpression) {
<ide>
<ide> @Override
<ide> protected boolean matchName(ServerWebExchange exchange) {
<del> return exchange.getRequest().getHeaders().get(name) != null;
<add> return (exchange.getRequest().getHeaders().get(this.name) != null);
<ide> }
<ide>
<ide> @Override
<ide> protected boolean matchValue(ServerWebExchange exchange) {
<del> return value.equals(exchange.getRequest().getHeaders().getFirst(name));
<add> return (this.value != null && this.value.equals(exchange.getRequest().getHeaders().getFirst(this.name)));
<ide> }
<ide> }
<ide>
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/condition/ParamsRequestCondition.java
<ide> /*
<del> * Copyright 2002-2016 the original author or authors.
<add> * Copyright 2002-2017 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> protected boolean matchName(ServerWebExchange exchange) {
<ide>
<ide> @Override
<ide> protected boolean matchValue(ServerWebExchange exchange) {
<del> return this.value.equals(exchange.getRequest().getQueryParams().getFirst(this.name));
<add> return (this.value != null &&
<add> this.value.equals(exchange.getRequest().getQueryParams().getFirst(this.name)));
<ide> }
<ide> }
<ide>
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/view/DefaultRendering.java
<ide> class DefaultRendering implements Rendering {
<ide>
<ide>
<ide> @Override
<add> @Nullable
<ide> public Object view() {
<ide> return this.view;
<ide> }
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/view/Rendering.java
<ide> public interface Rendering {
<ide> /**
<ide> * Return the selected {@link String} view name or {@link View} object.
<ide> */
<add> @Nullable
<ide> Object view();
<ide>
<ide> /** | 11 |
Python | Python | fix typo in the 'issubclass' docstring | 6114f1c963ad011d276701967864f339e8e45ae0 | <ide><path>numpy/core/numerictypes.py
<ide> def issubclass_(arg1, arg2):
<ide> Determine if a class is a subclass of a second class.
<ide>
<ide> `issubclass_` is equivalent to the Python built-in ``issubclass``,
<del> except that it returns False instead of raising a TypeError is one
<add> except that it returns False instead of raising a TypeError if one
<ide> of the arguments is not a class.
<ide>
<ide> Parameters | 1 |
Javascript | Javascript | add jsdoc comments to pdfoutlineview | f4dbc994836467dfe9725d733b60baeaa3c13e81 | <ide><path>web/pdf_outline_view.js
<ide>
<ide> 'use strict';
<ide>
<add>/**
<add> * @typedef {Object} PDFOutlineViewOptions
<add> * @property {HTMLDivElement} container - The viewer element.
<add> * @property {Array} outline - An array of outline objects.
<add> * @property {IPDFLinkService} linkService - The navigation/linking service.
<add> */
<add>
<add>/**
<add> * @class
<add> */
<ide> var PDFOutlineView = (function PDFOutlineViewClosure() {
<add> /**
<add> * @constructs PDFOutlineView
<add> * @param {PDFOutlineViewOptions} options
<add> */
<ide> function PDFOutlineView(options) {
<ide> this.container = options.container;
<ide> this.outline = options.outline;
<ide> var PDFOutlineView = (function PDFOutlineViewClosure() {
<ide> }
<ide> },
<ide>
<add> /**
<add> * @private
<add> */
<ide> _bindLink: function PDFOutlineView_bindLink(element, item) {
<ide> var linkService = this.linkService;
<ide> element.href = linkService.getDestinationHash(item.dest); | 1 |
Java | Java | fix typo on mergedannotations | 860ec44c5096d16bedeef45a4e29b1156f44b4b9 | <ide><path>spring-core/src/main/java/org/springframework/core/annotation/MergedAnnotations.java
<ide> import org.springframework.lang.Nullable;
<ide>
<ide> /**
<del> * Provides access to a collection of merged annotations, usually obtained from
<del> * a from a source such as a {@link Class} or {@link Method}. Each merged
<add> * Provides access to a collection of merged annotations, usually obtained
<add> * from a source such as a {@link Class} or {@link Method}. Each merged
<ide> * annotation represent a view where the attribute values may be "merged" from
<ide> * different source values, typically:
<ide> * | 1 |
PHP | PHP | fix issue with duplicate prefixes | c3f17c24f39e683d0032429e50ad193a878f88b4 | <ide><path>lib/Cake/Model/Datasource/Database/Postgres.php
<ide> public function getSequence($table, $field = 'id') {
<ide> *
<ide> * @param mixed $table A string or model class representing the table to be truncated
<ide> * @param boolean $reset true for resetting the sequence, false to leave it as is.
<del> * and if 1, sequences are not modified
<add> * and if 1, sequences are not modified
<ide> * @return boolean SQL TRUNCATE TABLE statement, false if not applicable.
<ide> */
<del> public function truncate($table, $reset = 0) {
<del> $table = $this->fullTableName($table, false);
<del> if (!isset($this->_sequenceMap[$table])) {
<add> public function truncate($table, $reset = false) {
<add> $fullTable = $this->fullTableName($table, false);
<add> if (!isset($this->_sequenceMap[$fullTable])) {
<ide> $cache = $this->cacheSources;
<ide> $this->cacheSources = false;
<ide> $this->describe($table);
<ide> $this->cacheSources = $cache;
<ide> }
<ide> if ($this->execute('DELETE FROM ' . $this->fullTableName($table))) {
<del> $table = $this->fullTableName($table, false);
<del> if (isset($this->_sequenceMap[$table]) && $reset !== 1) {
<del> foreach ($this->_sequenceMap[$table] as $field => $sequence) {
<add> if (isset($this->_sequenceMap[$fullTable]) && $reset != true) {
<add> foreach ($this->_sequenceMap[$fullTable] as $field => $sequence) {
<ide> $this->_execute("ALTER SEQUENCE \"{$sequence}\" RESTART WITH 1");
<ide> }
<ide> } | 1 |
Javascript | Javascript | add needs to controllers | 8f6000057475dc0011bebc61d0539146986bc9b2 | <ide><path>packages/ember-routing/lib/ext/controller.js
<ide> var get = Ember.get;
<ide>
<ide> Ember.ControllerMixin.reopen({
<add> concatenatedProperties: ['needs'],
<add> needs: [],
<add>
<add> init: function() {
<add> this._super.apply(this, arguments);
<add>
<add> // Structure asserts to still do verification but not string concat in production
<add> if(!verifyDependencies(this)) {
<add> Ember.assert("Missing dependencies", false);
<add> }
<add> },
<add>
<ide> transitionTo: function() {
<ide> var router = get(this, 'target');
<ide>
<ide> Ember.ControllerMixin.reopen({
<ide> return container.lookup('controller:' + controllerName);
<ide> }
<ide> });
<add>
<add>function verifyDependencies(controller) {
<add> var needs = get(controller, 'needs'),
<add> container = get(controller, 'container'),
<add> dependency, satisfied = true;
<add>
<add> for (var i=0, l=needs.length; i<l; i++) {
<add> dependency = needs[i];
<add> if (dependency.indexOf(':') === -1) {
<add> dependency = "controller:" + dependency;
<add> }
<add>
<add> if (!container.has(dependency)) {
<add> satisfied = false;
<add> Ember.assert(this + " needs " + dependency + " but it does not exist", false);
<add> }
<add> }
<add>
<add> return satisfied;
<add>}
<ide><path>packages/ember-routing/tests/system/controller.js
<add>module("Controller dependencies");
<add>
<add>test("If a controller specifies a dependency, it is available to `controllerFor`", function() {
<add> var container = new Ember.Container();
<add>
<add> container.register('controller', 'post', Ember.Controller.extend({
<add> needs: 'posts',
<add>
<add> postsController: Ember.computed(function() {
<add> return this.controllerFor('posts');
<add> })
<add> }));
<add>
<add> container.register('controller', 'posts', Ember.Controller.extend());
<add>
<add> var postController = container.lookup('controller:post'),
<add> postsController = container.lookup('controller:posts');
<add>
<add> equal(postsController, postController.get('postsController'), "Getting dependency controllers work");
<add>});
<add>
<add>test("If a controller specifies an unavailable dependency, it raises", function() {
<add> var container = new Ember.Container();
<add>
<add> container.register('controller', 'post', Ember.Controller.extend({
<add> needs: 'posts'
<add> }));
<add>
<add> raises(function() {
<add> container.lookup('controller:post');
<add> }, /controller:posts/);
<add>});
<add> | 2 |
Javascript | Javascript | add $exceptionhandler service | 8ddee9bb25ade2bbe7d57db6353b29867606c184 | <ide><path>src/services.js
<ide> angularService("$log", function($window){
<ide> };
<ide> }, {inject:['$window']});
<ide>
<add>angularService('$exceptionHandler', function($log){
<add> return function(e) {
<add> $log.error(e);
<add> };
<add>}, {inject:['$log']});
<add>
<ide> angularService("$hover", function(browser, document) {
<ide> var tooltip, self = this, error, width = 300, arrowWidth = 10, body = jqLite(document[0].body);;
<ide> browser.hover(function(element, show){
<ide><path>test/servicesSpec.js
<ide> describe("service", function(){
<ide> });
<ide> });
<ide>
<add> describe("$exceptionHandler", function(){
<add> it('should log errors', function(){
<add> var error = '';
<add> $log.error = function(m) { error += m; };
<add> scope.$exceptionHandler('myError');
<add> expect(error).toEqual('myError');
<add> });
<add> });
<add>
<ide> describe("$location", function(){
<ide> it("should inject $location", function(){
<ide> scope.$location.parse('http://host:123/p/a/t/h.html?query=value#path?key=value'); | 2 |
Python | Python | fix typo in np.fill_diagonal docstring example | 34449614e34065e4599787095b90928dc22afb14 | <ide><path>numpy/lib/index_tricks.py
<ide> def fill_diagonal(a, val, wrap=False):
<ide> [0, 0, 0],
<ide> [0, 0, 4]])
<ide>
<del> # tall matrices no wrap
<add> The wrap option affects only tall matrices:
<add>
<add> >>> # tall matrices no wrap
<ide> >>> a = np.zeros((5, 3),int)
<ide> >>> fill_diagonal(a, 4)
<ide> >>> a
<ide> def fill_diagonal(a, val, wrap=False):
<ide> [0, 0, 0],
<ide> [0, 0, 0]])
<ide>
<del> # tall matrices wrap
<add> >>> # tall matrices wrap
<ide> >>> a = np.zeros((5, 3),int)
<ide> >>> fill_diagonal(a, 4, wrap=True)
<ide> >>> a
<ide> def fill_diagonal(a, val, wrap=False):
<ide> [0, 0, 0],
<ide> [4, 0, 0]])
<ide>
<del> # wide matrices
<add> >>> # wide matrices
<ide> >>> a = np.zeros((3, 5),int)
<ide> >>> fill_diagonal(a, 4, wrap=True)
<ide> >>> a | 1 |
Ruby | Ruby | define paths as expecting pathname or string | e29b2caee03a2749c976e08ab99bfc137747e535 | <ide><path>Library/Homebrew/service.rb
<ide> def root_dir(path = nil)
<ide> when String, Pathname
<ide> @root_dir = path.to_s
<ide> else
<del> raise TypeError, "Service#root_dir expects a String"
<add> raise TypeError, "Service#root_dir expects a String or Pathname"
<ide> end
<ide> end
<ide>
<ide> def input_path(path = nil)
<ide> when String, Pathname
<ide> @input_path = path.to_s
<ide> else
<del> raise TypeError, "Service#input_path expects a String"
<add> raise TypeError, "Service#input_path expects a String or Pathname"
<ide> end
<ide> end
<ide> | 1 |
Javascript | Javascript | remove old warning | 7a0674cd1a646a95e2f2139d420539051aa85a7c | <ide><path>src/renderers/webgl/WebGLTextures.js
<ide> function WebGLTextures( _gl, extensions, state, properties, capabilities, utils,
<ide>
<ide> extensions.get( 'EXT_color_buffer_float' );
<ide>
<del> } else if ( internalFormat === _gl.RGB16F || internalFormat === _gl.RGB32F ) {
<del>
<del> console.warn( 'THREE.WebGLRenderer: Floating point textures with RGB format not supported. Please use RGBA instead.' );
<del>
<ide> }
<ide>
<ide> return internalFormat; | 1 |
Text | Text | add guides for system testing | 62c7d983848726bb9a512d687d2765c1dd78fe8d | <ide><path>guides/source/testing.md
<ide> This guide covers built-in mechanisms in Rails for testing your application.
<ide> After reading this guide, you will know:
<ide>
<ide> * Rails testing terminology.
<del>* How to write unit, functional, and integration tests for your application.
<add>* How to write unit, functional, integration, and system tests for your application.
<ide> * Other popular testing approaches and plugins.
<ide>
<ide> --------------------------------------------------------------------------------
<ide> Rails creates a `test` directory for you as soon as you create a Rails project u
<ide>
<ide> ```bash
<ide> $ ls -F test
<del>controllers/ helpers/ mailers/ test_helper.rb
<del>fixtures/ integration/ models/
<add>controllers/ helpers/ mailers/ system/ test_helper.rb
<add>fixtures/ integration/ models/ system_test_helper.rb
<ide> ```
<ide>
<ide> The `helpers`, `mailers`, and `models` directories are meant to hold tests for view helpers, mailers, and models, respectively. The `controllers` directory is meant to hold tests for controllers, routes, and views. The `integration` directory is meant to hold tests for interactions between controllers.
<ide>
<add>The system test directory holds system tests, also known as acceptance tests.
<add>System tests inherit from Capybara and perform in browser tests for your
<add>application.
<add>
<ide> Fixtures are a way of organizing test data; they reside in the `fixtures` directory.
<ide>
<ide> A `jobs` directory will also be created when an associated test is first generated.
<ide>
<ide> The `test_helper.rb` file holds the default configuration for your tests.
<ide>
<add>The `system_test_helper.rb` holds the default configuration for your system
<add>tests.
<add>
<ide>
<ide> ### The Test Environment
<ide>
<ide> All the basic assertions such as `assert_equal` defined in `Minitest::Assertions
<ide> * [`ActionView::TestCase`](http://api.rubyonrails.org/classes/ActionView/TestCase.html)
<ide> * [`ActionDispatch::IntegrationTest`](http://api.rubyonrails.org/classes/ActionDispatch/IntegrationTest.html)
<ide> * [`ActiveJob::TestCase`](http://api.rubyonrails.org/classes/ActiveJob/TestCase.html)
<add>* [`ActionSystemTestCase`](http://api.rubyonrails.org/classes/ActionSystemTest.html)
<ide>
<ide> Each of these classes include `Minitest::Assertions`, allowing us to use all of the basic assertions in our tests.
<ide>
<ide> create test/fixtures/articles.yml
<ide>
<ide> Model tests don't have their own superclass like `ActionMailer::TestCase` instead they inherit from [`ActiveSupport::TestCase`](http://api.rubyonrails.org/classes/ActiveSupport/TestCase.html).
<ide>
<add>System Testing
<add>--------------
<add>
<add>System tests are full-browser acceptance tests that inherit from Capybara.
<add>System tests allow for running tests in either a real browser or a headless
<add>browser for testing full user interactions with your application.
<add>
<add>For creating Rails system tests, you use the `test/system` directory in your
<add>application. Rails provides a generator to create a system test skeleton for us.
<add>
<add>```bash
<add>$ bin/rails generate system_test users_create_test.rb
<add> invoke test_unit
<add> create test/system/users_create_test.rb
<add>```
<add>
<add>Here's what a freshly-generated system test looks like:
<add>
<add>```ruby
<add>require 'test_helper'
<add>
<add>class UsersCreateTest < ActionSystemTestCase
<add> # test "the truth" do
<add> # assert true
<add> # end
<add>end
<add>```
<add>
<add>Here the test is inheriting from `ActionSystemTestCase`. This allows for no-setup
<add>Capybara integration with Selenium Webdriver.
<add>
<add>### Changing the default settings
<add>
<add>Capybara requires that a driver be selected. Rails defaults to the Selenium
<add>Driver and provides default settings to Capyara and Selenium so that system
<add>tests work out of the box with no required configuration on your part.
<add>
<add>Some may prefer to use a headless driver so Rails provides a shim to set other
<add>drivers for Capybara with minimal configuration.
<add>
<add>In the `system_test_helper.rb` that is generated with the application or test
<add>you can set the driver:
<add>
<add>```ruby
<add>require 'test_helper'
<add>
<add>class ActionSystemTestCase < ActionSystemTest::Base
<add> ActionSystemTest.driver = :poltergeist
<add>end
<add>```
<add>
<add>The drivers that Rails and Capybara support are `:rack_test`, `:poltergeist`,
<add>`:capybara_webkit`, and of course `:selenium`.
<add>
<add>For selenium you can choose either the Rails configured driver `:rails_selenium`
<add>or `:selenium`. The `:selenium` driver inherits from `CabybaraDriver` and is
<add>the vanilla setup of selenium with Capybara if you don't want to use the
<add>Rails defaults.
<add>
<add>The default settings for `:rails_selenium` driver uses the Chrome browser,
<add>sets the server to Puma on port 28100 and the screen size to 1400 x 1400.
<add>
<add>You can change the default settings by initializing a new driver object.
<add>
<add>```ruby
<add>require 'test_helper'
<add>
<add>class ActionSystemTestCase < ActionSystemTest::Base
<add> ActionSystemTest.driver = ActionSystemTest::DriverAdapters::RailsSeleniumDriver.new(
<add> browser: :firefox,
<add> server: :webkit
<add> )
<add>end
<add>```
<add>
<add>The shim for other Capybara drivers provide some defaults such as driver name
<add>server, and port. To change any of those settings, you can initialize a new
<add>`CapybaraDriver` object.
<add>
<add>```ruby
<add>require 'test_helper'
<add>
<add>class ActionSystemTestCase < ActionSystemTest::Base
<add> ActionSystemTest.driver = ActionSystemTest::DriverAdapters::CapybaraDriver.new(
<add> driver: :poltergeist,
<add> server: :webrick
<add> )
<add>end
<add>```
<add>
<add>If your Capybara configuration requires more setup than provided by Rails, all
<add>of that configuration can be put into the `system_test_helper.rb` file provided
<add>by Rails.
<add>
<add>Please see Capybara's documentation for additional settings.
<add>
<add>### Helpers Available for System Tests
<add>
<add>`ActionSystemTest` provides a few helpers in addition to those provided previously
<add>by Rails or by Capybara.
<add>
<add>The `ScreenshotHelper` is a helper designed to capture screenshots of your test.
<add>This can be helpful for viewing the browser at the point a test failed, or
<add>to view screenshots later for debugging.
<add>
<add>Two methods are provided: `take_screenshot` and `take_failed_screenshot`.
<add>`take_failed_screenshot` is automatically included in the `system_test_helper.rb`
<add>file and will take a screenshot only if the test fails.
<add>
<add>The `take_screenshot` helper method can be included anywhere in your tests to
<add>take a screenshot of the browser.
<add>
<add>A method is provided by the drivers to determine whether the driver is capable
<add>of taking screenshots. The `RackTest` driver for example does not support
<add>screenshots. `supports_screenshots?` checks whether the driver supports
<add>screenshots:
<add>
<add>```ruby
<add>ActionSystemTest.driver.supports_screenshots?
<add>=> true
<add>```
<add>
<add>The `ActiveJobSetup` helper configures your system tests for handling Active Job.
<add>
<add>Two helper methods are included in the setup and teardown blocks in the
<add>`system_test_helper.rb` file. `set_queue_adapter_to_async` sets your Active Job
<add>queue adapter to the async adapter and remembers the original adapter.
<add>
<add>In teardown the `reset_queue_adapter_to_original` method resets the Active Job
<add>queue adapter back to the adapter your application has set for other environments.
<add>
<add>This is helpful for ensuring that jobs run async so that the test's that rely
<add>on job code are correctly tested at the time they run.
<add>
<add>If you don't want these helper methods you can remove them from the setup and
<add>teardown code in your `system_test_helper.rb`.
<add>
<add>The `AssertionsHelper` provides two helper methods for assertions. In Capybara
<add>you can assert that a selector does or does not exist, but often you have cases
<add>where you need to assert the same selector exsits multiple times with different
<add>values. For example, if you have 6 avatars on the page and you want to assert
<add>that each of them has the respective title for each person you can use
<add>`assert_all_of_selectors` and pass the selector, items you are asserting exist,
<add>and options.
<add>
<add>```ruby
<add>assert_all_of_selectors(:avatar, 'Eileen', 'Jeremy')
<add>assert_all_of_selectors(:avatar, 'Eileen', 'Jeremy', visible: all)
<add>```
<add>
<add>You can also assert that none of the selectors match with
<add>`assert_none_of_selectors`:
<add>
<add>```ruby
<add>assert_none_of_selectors(:avatar, 'Tom', 'Dan')
<add>assert_none_of_selectors(:avatar, 'Tom', 'Dan')
<add>```
<add>
<add>### Implementing a system test
<add>
<add>Now we're going to add a system test to our blog application. We'll demonstrate
<add>writing a system test by visiting the index page and creating a new blog article.
<add>
<add>If you used the scaffold generator, a system test skeleton is automatically
<add>created for you. If you did not use the generator start by creating a system
<add>test skeleton.
<add>
<add>```bash
<add>$ bin/rails generate system_test articles
<add>```
<add>
<add>It should have created a test file placeholder for us. With the output of the
<add>previous command we should see:
<add>
<add>```bash
<add> invoke test_unit
<add> create test/system/articles_test.rb
<add>```
<add>
<add>Now let's open that file and write our first assertion:
<add>
<add>```ruby
<add>require 'system_test_helper'
<add>
<add>class UsersTest < ActionSystemTestCase
<add> test "viewing the index" do
<add> visit articles_path
<add> assert_text "h1", "Articles"
<add> end
<add>end
<add>```
<add>
<add>The test should see that there is an h1 on the articles index and pass.
<add>
<add>Run the system tests.
<add>
<add>```bash
<add>bin/rails test:system
<add>```
<add>
<add>#### Creating articles system test
<add>
<add>Now let's test the flow for creating a new article in our blog.
<add>
<add>```ruby
<add>test "creating an article" do
<add> visit articles_path
<add>
<add> click_on "New Article"
<add>
<add> fill_in "Title", with: "Creating an Article"
<add> fill_in "Body", with: "Created this article successfully!"
<add>
<add> click_on "Create Article"
<add>
<add> assert_text "Creating an Article"
<add>end
<add>```
<add>
<add>The first step is to call `visit articles_path`. This will take the test to the
<add>articles index page.
<add>
<add>Then the `click_on "New Article"` will find the "New Article" button on the
<add>index page. This will redirect the browser to `/articles/new`.
<add>
<add>Then the test will fill in the title and body of the article with the specified
<add>text. Once the fields are filled in "Create Article" is clicked on which will
<add>send a POST request to create the new article in the database.
<add>
<add>We will be redirected back to the the articles index page and there we assert
<add>that the text from the article title is on the articles index page.
<add>
<add>#### Taking it further
<add>
<add>The beauty of system testing is that it is similar to integration testing in
<add>that it tests the user's interaction with your controller, model, and view, but
<add>system testing is much more robust and actually tests your application as if
<add>a real user were using it. Going forward you can test anything that the user
<add>themselves would do in your application such as commenting, deleting articles,
<add>publishing draft articles, etc.
<ide>
<ide> Integration Testing
<ide> ------------------- | 1 |
Python | Python | add list_nodes and create_node tests | 8bc7efab5d9646a9190ca6190639dc0b92a11001 | <ide><path>libcloud/compute/drivers/maxihost.py
<ide> def create_node(self, name, size, image, location,
<ide> error_message = exc.message.get('error_messages', '')
<ide> raise ValueError('Failed to create node: %s' % (error_message))
<ide>
<del> return res.object
<add> return self._to_node(res.object['devices'][0])
<ide>
<ide> def ex_start_node(self, node):
<ide> """
<ide><path>libcloud/test/compute/test_maxihost.py
<ide> def test_list_images(self):
<ide> image = images[0]
<ide> self.assertEqual(image.id, 'ubuntu_18_04_x64_lts')
<ide>
<del> def test_list_nodes(self):
<del> nodes = self.driver.list_nodes()
<del> self.assertEqual(len(nodes), 1)
<del> node = nodes[0]
<del> self.assertEqual(node.name, 'tester')
<del>
<ide> def test_list_key_pairs(self):
<ide> keys = self.driver.list_key_pairs()
<ide> self.assertEqual(len(keys), 1)
<ide> key = keys[0]
<ide> self.assertEqual(key.name, 'test_key')
<ide> self.assertEqual(key.fingerprint, '77:08:a7:a5:f9:8c:e1:ab:7b:c3:d8:0c:cd:ac:8b:dd')
<ide>
<add> def test_list_nodes(self):
<add> nodes = self.driver.list_nodes()
<add> self.assertEqual(len(nodes), 1)
<add> node = nodes[0]
<add> self.assertEqual(node.name, 'tester')
<add>
<add> def test_create_node_response(self):
<add> # should return a node object
<add> size = self.driver.list_sizes()[0]
<add> image = self.driver.list_images()[0]
<add> location = self.driver.list_locations()[0]
<add> node = self.driver.create_node(name='node-name',
<add> image=image,
<add> size=size,
<add> location=location)
<add> self.assertTrue(isinstance(node, Node))
<add>
<ide>
<ide> class MaxihostMockHttp(MockHttp):
<ide> fixtures = ComputeFileFixtures('maxihost') | 2 |
PHP | PHP | simplify a regex a bit | 37e3b579a97dd6fdcefa27cf92374315c6438f53 | <ide><path>src/Database/SqlDialectTrait.php
<ide> public function quoteIdentifier($identifier) {
<ide> return $this->_startQuote . $identifier . $this->_endQuote;
<ide> }
<ide>
<del> if (preg_match('/^[\w-]+(?:\.[^ \*]*)*$/', $identifier)) { // string.string
<add> if (preg_match('/^[\w-]+\.[^ \*]*$/', $identifier)) { // string.string
<ide> $items = explode('.', $identifier);
<ide> return $this->_startQuote . implode($this->_endQuote . '.' . $this->_startQuote, $items) . $this->_endQuote;
<ide> } | 1 |
Java | Java | fix testaotprocessortests on ms windows | 3f288eea1761590671c4c8dc8fadcc4c09e50fb5 | <ide><path>spring-test/src/test/java/org/springframework/test/context/aot/TestAotProcessorTests.java
<ide> private static List<String> findFiles(Path outputPath) throws IOException {
<ide> .map(Path::toAbsolutePath)
<ide> .map(Path::toString)
<ide> .map(path -> path.substring(prefixLength))
<add> .map(path -> path.replace('\\', '/')) // convert Windows path
<ide> .toList();
<ide> }
<ide> | 1 |
Ruby | Ruby | avoid a hash lookup | 27be777888cfefc6667c1d3b4c284cf1d0b67208 | <ide><path>activerecord/lib/active_record/associations.rb
<ide> def construct(parent, associations, joins, row)
<ide> construct(parent, association, joins, row)
<ide> end
<ide> when Hash
<del> associations.keys.sort{|a,b|a.to_s<=>b.to_s}.each do |name|
<add> associations.sort_by { |k,_| k.to_s }.each do |name, assoc|
<ide> join = joins.detect{|j| j.reflection.name.to_s == name.to_s && j.parent_table_name == parent.class.table_name }
<ide> raise(ConfigurationError, "No such association") if join.nil?
<ide>
<ide> association = construct_association(parent, join, row)
<ide> joins.delete(join)
<del> construct(association, associations[name], joins, row) if association
<add> construct(association, assoc, joins, row) if association
<ide> end
<ide> else
<ide> raise ConfigurationError, associations.inspect | 1 |
Javascript | Javascript | fix remaining linter issues | 6c46cf924355d0735123c6c932552271930b69b8 | <ide><path>spec/atom-environment-spec.js
<ide> describe('AtomEnvironment', () => {
<ide> a + 1 // eslint-disable-line no-undef
<ide> } catch (e) {
<ide> error = e
<del> window.onerror.call(window, e.toString(), 'abc', 2, 3, e)
<add> window.onerror(e.toString(), 'abc', 2, 3, e)
<ide> }
<ide>
<ide> delete willThrowSpy.mostRecentCall.args[0].preventDefault
<ide> describe('AtomEnvironment', () => {
<ide> try {
<ide> a + 1 // eslint-disable-line no-undef
<ide> } catch (e) {
<del> window.onerror.call(window, e.toString(), 'abc', 2, 3, e)
<add> window.onerror(e.toString(), 'abc', 2, 3, e)
<ide> }
<ide>
<ide> expect(willThrowSpy).toHaveBeenCalled()
<ide> describe('AtomEnvironment', () => {
<ide> a + 1 // eslint-disable-line no-undef
<ide> } catch (e) {
<ide> error = e
<del> window.onerror.call(window, e.toString(), 'abc', 2, 3, e)
<add> window.onerror(e.toString(), 'abc', 2, 3, e)
<ide> }
<ide> expect(didThrowSpy).toHaveBeenCalledWith({
<ide> message: error.toString(),
<ide> describe('AtomEnvironment', () => {
<ide> let atomEnvironment, envLoaded, spy
<ide>
<ide> beforeEach(() => {
<del> let resolve = null
<del> const promise = new Promise(r => {
<del> resolve = r
<add> let resolvePromise = null
<add> const promise = new Promise(resolve => {
<add> resolvePromise = resolve
<ide> })
<ide> envLoaded = () => {
<del> resolve()
<add> resolvePromise()
<ide> return promise
<ide> }
<ide> atomEnvironment = new AtomEnvironment({
<ide><path>spec/atom-paths-spec.js
<ide> describe('AtomPaths', () => {
<ide> describe('when a portable .atom folder exists', () => {
<ide> beforeEach(() => {
<ide> delete process.env.ATOM_HOME
<del> if (!fs.existsSync(portableAtomHomePath))
<add> if (!fs.existsSync(portableAtomHomePath)) {
<ide> fs.mkdirSync(portableAtomHomePath)
<add> }
<ide> })
<ide>
<ide> afterEach(() => {
<ide><path>spec/text-editor-component-spec.js
<ide> describe('TextEditorComponent', () => {
<ide> expect(actualWidth).toBe(expectedWidth + 'px')
<ide> }
<ide>
<del> {
<del> // Make sure we do not throw an error if a synchronous update is
<del> // triggered before measuring the longest line from a
<del> // previously-scheduled update.
<del> editor.getBuffer().insert(Point(12, Infinity), 'x'.repeat(100))
<del> expect(editor.getLongestScreenRow()).toBe(12)
<del>
<del> TextEditorComponent.getScheduler().readDocument(() => {
<del> // This will happen before the measurement phase of the update
<del> // triggered above.
<del> component.pixelPositionForScreenPosition(Point(11, Infinity))
<del> })
<add> // Make sure we do not throw an error if a synchronous update is
<add> // triggered before measuring the longest line from a
<add> // previously-scheduled update.
<add> editor.getBuffer().insert(Point(12, Infinity), 'x'.repeat(100))
<add> expect(editor.getLongestScreenRow()).toBe(12)
<ide>
<del> await component.getNextUpdatePromise()
<del> }
<add> TextEditorComponent.getScheduler().readDocument(() => {
<add> // This will happen before the measurement phase of the update
<add> // triggered above.
<add> component.pixelPositionForScreenPosition(Point(11, Infinity))
<add> })
<add>
<add> await component.getNextUpdatePromise()
<ide> })
<ide>
<ide> it('re-renders lines when their height changes', async () => {
<ide> describe('TextEditorComponent', () => {
<ide> } else if (k < 95) {
<ide> editor.setSelectedBufferRange(range)
<ide> } else {
<del> if (random(2))
<add> if (random(2)) {
<ide> component.setScrollTop(random(component.getScrollHeight()))
<del> if (random(2))
<add> }
<add> if (random(2)) {
<ide> component.setScrollLeft(random(component.getScrollWidth()))
<add> }
<ide> }
<ide>
<ide> component.scheduleUpdate()
<ide><path>spec/text-editor-registry-spec.js
<ide> describe('TextEditorRegistry', function () {
<ide> let disposable = registry.maintainConfig(editor)
<ide> expect(editor.getSoftTabs()).toBe(true)
<ide>
<add> /* eslint-disable no-tabs */
<ide> editor.setText(dedent`
<ide> {
<ide> hello;
<ide> }
<ide> `)
<add> /* eslint-enable no-tabs */
<ide> disposable.dispose()
<ide> disposable = registry.maintainConfig(editor)
<ide> expect(editor.getSoftTabs()).toBe(false)
<ide> describe('TextEditorRegistry', function () {
<ide> disposable = registry.maintainConfig(editor)
<ide> expect(editor.getSoftTabs()).toBe(false)
<ide>
<add> /* eslint-disable no-tabs */
<ide> editor.setText(dedent`
<ide> /*
<ide> * Comment with a leading space.
<ide> describe('TextEditorRegistry', function () {
<ide> hello;
<ide> }
<ide> `)
<add> /* eslint-enable no-tabs */
<ide> disposable.dispose()
<ide> disposable = registry.maintainConfig(editor)
<ide> expect(editor.getSoftTabs()).toBe(false)
<ide><path>spec/text-editor-spec.js
<ide> describe('TextEditor', () => {
<ide> await atom.packages.activatePackage('language-go')
<ide> editor.update({ autoIndent: true })
<ide> atom.grammars.assignLanguageMode(editor, 'source.go')
<del> editor.setText('fmt.Printf("some%s",\n "thing")')
<add> editor.setText('fmt.Printf("some%s",\n "thing")') // eslint-disable-line no-tabs
<ide> editor.setCursorBufferPosition([1, 10])
<ide> editor.insertNewline()
<ide> expect(editor.indentationForBufferRow(1)).toBe(1)
<ide><path>spec/text-mate-language-mode-spec.js
<ide> describe('TextMateLanguageMode', () => {
<ide> languageMode = new TextMateLanguageMode({
<ide> buffer,
<ide> config,
<del> config,
<ide> grammar: atom.grammars.grammarForScopeName('source.js')
<ide> })
<ide> languageMode.startTokenizing()
<ide><path>spec/theme-manager-spec.js
<ide> h2 {
<ide> expect(note.getType()).toBe('error')
<ide> expect(note.getMessage()).toContain('Error loading')
<ide> expect(
<del> atom.styles.styleElementsBySourcePath[
<del> atom.styles.getUserStyleSheetPath()
<del> ]
<add> atom.styles.styleElementsBySourcePath[atom.styles.getUserStyleSheetPath()]
<ide> ).toBeUndefined()
<ide> })
<ide> })
<ide><path>spec/tree-sitter-language-mode-spec.js
<add>/* eslint-disable no-template-curly-in-string */
<add>
<ide> const { it, beforeEach, afterEach } = require('./async-spec-helpers')
<ide>
<ide> const fs = require('fs')
<ide> describe('TreeSitterLanguageMode', () => {
<ide> buffer.getLanguageMode().syncOperationLimit = 0
<ide>
<ide> const initialSeed = Date.now()
<del> for (let i = 0, trial_count = 10; i < trial_count; i++) {
<add> for (let i = 0, trialCount = 10; i < trialCount; i++) {
<ide> let seed = initialSeed + i
<ide> // seed = 1541201470759
<ide> const random = Random(seed)
<ide> describe('TreeSitterLanguageMode', () => {
<ide> editor.displayLayer.getScreenLines()
<ide>
<ide> // Make several random edits.
<del> for (let j = 0, edit_count = 1 + random(4); j < edit_count; j++) {
<add> for (let j = 0, editCount = 1 + random(4); j < editCount; j++) {
<ide> const editRoll = random(10)
<ide> const range = getRandomBufferRange(random, buffer)
<ide>
<ide> describe('TreeSitterLanguageMode', () => {
<ide> if (jasmine.getEnv().currentSpec.results().failedCount > 0) {
<ide> console.log(tokens1)
<ide> console.log(tokens2)
<del> debugger
<add> debugger // eslint-disable-line no-debugger
<ide> break
<ide> }
<ide> } | 8 |
Java | Java | accept predicate instead of handlertypepredicate | 86c861516d55c69bae0150271c1a10d40afa726e | <ide><path>spring-web/src/main/java/org/springframework/web/method/HandlerTypePredicate.java
<ide> import org.springframework.util.StringUtils;
<ide>
<ide> /**
<del> * A {@code Predicate} to match request handling component types based on the
<del> * following selectors:
<add> * A {@code Predicate} to match request handling component types if
<add> * <strong>any</strong> of the following selectors match:
<ide> * <ul>
<ide> * <li>Base packages -- for selecting handlers by their package.
<ide> * <li>Assignable types -- for selecting handlers by super type.
<ide> * <li>Annotations -- for selecting handlers annotated in a specific way.
<ide> * </ul>
<del> * <p>Use static factory methods in this class to create a Predicate.
<add> * <p>Composability methods on {@link Predicate} can be used :
<add> * <pre class="code">
<add> * Predicate<Class<?>> predicate =
<add> * HandlerTypePredicate.forAnnotation(RestController)
<add> * .and(HandlerTypePredicate.forBasePackage("org.example"));
<add> * </pre>
<ide> *
<ide> * @author Rossen Stoyanchev
<ide> * @since 5.1
<ide> */
<del>public class HandlerTypePredicate implements Predicate<Class<?>> {
<add>public class HandlerTypePredicate implements Predicate<Class<?>> {
<ide>
<ide> private final Set<String> basePackages;
<ide>
<ide><path>spring-web/src/test/java/org/springframework/web/method/HandlerTypePredicateTests.java
<add>/*
<add> * Copyright 2002-2018 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>package org.springframework.web.method;
<add>
<add>import java.util.function.Predicate;
<add>
<add>import org.junit.Test;
<add>
<add>import org.springframework.stereotype.Controller;
<add>import org.springframework.web.bind.annotation.RestController;
<add>
<add>import static org.junit.Assert.*;
<add>
<add>/**
<add> * Unit tests for {@link HandlerTypePredicate}.
<add> * @author Rossen Stoyanchev
<add> */
<add>public class HandlerTypePredicateTests {
<add>
<add> @Test
<add> public void forAnnotation() {
<add>
<add> Predicate<Class<?>> predicate = HandlerTypePredicate.forAnnotation(Controller.class);
<add>
<add> assertTrue(predicate.test(HtmlController.class));
<add> assertTrue(predicate.test(ApiController.class));
<add> assertTrue(predicate.test(AnotherApiController.class));
<add> }
<add>
<add> @Test
<add> public void forAnnotationWithException() {
<add>
<add> Predicate<Class<?>> predicate = HandlerTypePredicate.forAnnotation(Controller.class)
<add> .and(HandlerTypePredicate.forAssignableType(Special.class));
<add>
<add> assertFalse(predicate.test(HtmlController.class));
<add> assertFalse(predicate.test(ApiController.class));
<add> assertTrue(predicate.test(AnotherApiController.class));
<add> }
<add>
<add>
<add> @Controller
<add> private static class HtmlController {}
<add>
<add> @RestController
<add> private static class ApiController {}
<add>
<add> @RestController
<add> private static class AnotherApiController implements Special {}
<add>
<add> interface Special {}
<add>
<add>}
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/config/PathMatchConfigurer.java
<ide>
<ide> import java.util.LinkedHashMap;
<ide> import java.util.Map;
<add>import java.util.function.Predicate;
<ide>
<ide> import org.springframework.lang.Nullable;
<del>import org.springframework.web.method.HandlerTypePredicate;
<ide>
<ide> /**
<ide> * Assist with configuring {@code HandlerMapping}'s with path matching options.
<ide> public class PathMatchConfigurer {
<ide> private Boolean caseSensitiveMatch;
<ide>
<ide> @Nullable
<del> private Map<String, HandlerTypePredicate> pathPrefixes;
<add> private Map<String, Predicate<Class<?>>> pathPrefixes;
<ide>
<ide>
<ide> /**
<ide> public PathMatchConfigurer setUseTrailingSlashMatch(Boolean trailingSlashMatch)
<ide> * Configure a path prefix to apply to matching controller methods.
<ide> * <p>Prefixes are used to enrich the mappings of every {@code @RequestMapping}
<ide> * method whose controller type is matched by the corresponding
<del> * {@link HandlerTypePredicate}. The prefix for the first matching predicate
<del> * is used.
<add> * {@code Predicate}. The prefix for the first matching predicate is used.
<add> * <p>Consider using {@link org.springframework.web.method.HandlerTypePredicate
<add> * HandlerTypePredicate} to group controllers.
<ide> * @param prefix the path prefix to apply
<ide> * @param predicate a predicate for matching controller types
<ide> * @since 5.1
<ide> */
<del> public PathMatchConfigurer addPathPrefix(String prefix, HandlerTypePredicate predicate) {
<add> public PathMatchConfigurer addPathPrefix(String prefix, Predicate<Class<?>> predicate) {
<ide> this.pathPrefixes = this.pathPrefixes == null ? new LinkedHashMap<>() : this.pathPrefixes;
<ide> this.pathPrefixes.put(prefix, predicate);
<ide> return this;
<ide> protected Boolean isUseCaseSensitiveMatch() {
<ide> }
<ide>
<ide> @Nullable
<del> protected Map<String, HandlerTypePredicate> getPathPrefixes() {
<add> protected Map<String, Predicate<Class<?>>> getPathPrefixes() {
<ide> return this.pathPrefixes;
<ide> }
<ide> }
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/config/WebFluxConfigurationSupport.java
<ide>
<ide> import java.util.List;
<ide> import java.util.Map;
<add>import java.util.function.Predicate;
<ide>
<ide> import reactor.core.publisher.Mono;
<ide>
<ide> import org.springframework.web.bind.WebDataBinder;
<ide> import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
<ide> import org.springframework.web.cors.CorsConfiguration;
<del>import org.springframework.web.method.HandlerTypePredicate;
<ide> import org.springframework.web.reactive.DispatcherHandler;
<ide> import org.springframework.web.reactive.HandlerMapping;
<ide> import org.springframework.web.reactive.accept.RequestedContentTypeResolver;
<ide> public RequestMappingHandlerMapping requestMappingHandlerMapping() {
<ide> mapping.setUseCaseSensitiveMatch(useCaseSensitiveMatch);
<ide> }
<ide>
<del> Map<String, HandlerTypePredicate> pathPrefixes = configurer.getPathPrefixes();
<add> Map<String, Predicate<Class<?>>> pathPrefixes = configurer.getPathPrefixes();
<ide> if (pathPrefixes != null) {
<ide> mapping.setPathPrefixes(pathPrefixes);
<ide> }
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/method/annotation/RequestMappingHandlerMapping.java
<ide> import java.util.Collections;
<ide> import java.util.LinkedHashMap;
<ide> import java.util.Map;
<add>import java.util.function.Predicate;
<ide>
<ide> import org.springframework.context.EmbeddedValueResolverAware;
<ide> import org.springframework.core.annotation.AnnotatedElementUtils;
<ide> import org.springframework.web.bind.annotation.RequestMapping;
<ide> import org.springframework.web.bind.annotation.RequestMethod;
<ide> import org.springframework.web.cors.CorsConfiguration;
<del>import org.springframework.web.method.HandlerTypePredicate;
<ide> import org.springframework.web.method.HandlerMethod;
<ide> import org.springframework.web.reactive.accept.RequestedContentTypeResolver;
<ide> import org.springframework.web.reactive.accept.RequestedContentTypeResolverBuilder;
<ide> public class RequestMappingHandlerMapping extends RequestMappingInfoHandlerMapping
<ide> implements EmbeddedValueResolverAware {
<ide>
<del> private final Map<String, HandlerTypePredicate> pathPrefixes = new LinkedHashMap<>();
<add> private final Map<String, Predicate<Class<?>>> pathPrefixes = new LinkedHashMap<>();
<ide>
<ide> private RequestedContentTypeResolver contentTypeResolver = new RequestedContentTypeResolverBuilder().build();
<ide>
<ide> public class RequestMappingHandlerMapping extends RequestMappingInfoHandlerMappi
<ide> /**
<ide> * Configure path prefixes to apply to controller methods.
<ide> * <p>Prefixes are used to enrich the mappings of every {@code @RequestMapping}
<del> * method whose controller type is matched by the corresponding
<del> * {@link HandlerTypePredicate} in the map. The prefix for the first matching
<del> * predicate is used, assuming the input map has predictable order.
<add> * method whose controller type is matched by a corresponding
<add> * {@code Predicate} in the map. The prefix for the first matching predicate
<add> * is used, assuming the input map has predictable order.
<add> * <p>Consider using {@link org.springframework.web.method.HandlerTypePredicate
<add> * HandlerTypePredicate} to group controllers.
<ide> * @param prefixes a map with path prefixes as key
<ide> * @since 5.1
<add> * @see org.springframework.web.method.HandlerTypePredicate
<ide> */
<del> public void setPathPrefixes(Map<String, HandlerTypePredicate> prefixes) {
<add> public void setPathPrefixes(Map<String, Predicate<Class<?>>> prefixes) {
<ide> this.pathPrefixes.clear();
<ide> prefixes.entrySet().stream()
<ide> .filter(entry -> StringUtils.hasText(entry.getKey()))
<ide> .forEach(entry -> this.pathPrefixes.put(entry.getKey(), entry.getValue()));
<ide> }
<ide>
<ide> /**
<del> * Set the {@link RequestedContentTypeResolver} to use to determine requested media types.
<del> * If not set, the default constructor is used.
<add> * Set the {@link RequestedContentTypeResolver} to use to determine requested
<add> * media types. If not set, the default constructor is used.
<ide> */
<ide> public void setContentTypeResolver(RequestedContentTypeResolver contentTypeResolver) {
<ide> Assert.notNull(contentTypeResolver, "'contentTypeResolver' must not be null");
<ide> public void afterPropertiesSet() {
<ide> * The configured path prefixes as a read-only, possibly empty map.
<ide> * @since 5.1
<ide> */
<del> public Map<String, HandlerTypePredicate> getPathPrefixes() {
<add> public Map<String, Predicate<Class<?>>> getPathPrefixes() {
<ide> return Collections.unmodifiableMap(this.pathPrefixes);
<ide> }
<ide>
<ide> protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handler
<ide> if (typeInfo != null) {
<ide> info = typeInfo.combine(info);
<ide> }
<del> for (Map.Entry<String, HandlerTypePredicate> entry : this.pathPrefixes.entrySet()) {
<add> for (Map.Entry<String, Predicate<Class<?>>> entry : this.pathPrefixes.entrySet()) {
<ide> if (entry.getValue().test(handlerType)) {
<ide> String prefix = entry.getKey();
<ide> if (this.embeddedValueResolver != null) {
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/PathMatchConfigurer.java
<ide>
<ide> import java.util.LinkedHashMap;
<ide> import java.util.Map;
<add>import java.util.function.Predicate;
<ide>
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.PathMatcher;
<del>import org.springframework.web.method.HandlerTypePredicate;
<ide> import org.springframework.web.util.UrlPathHelper;
<ide>
<ide> /**
<ide> public class PathMatchConfigurer {
<ide> private PathMatcher pathMatcher;
<ide>
<ide> @Nullable
<del> private Map<String, HandlerTypePredicate> pathPrefixes;
<add> private Map<String, Predicate<Class<?>>> pathPrefixes;
<ide>
<ide>
<ide> /**
<ide> public PathMatchConfigurer setPathMatcher(PathMatcher pathMatcher) {
<ide> * Configure a path prefix to apply to matching controller methods.
<ide> * <p>Prefixes are used to enrich the mappings of every {@code @RequestMapping}
<ide> * method whose controller type is matched by the corresponding
<del> * {@link HandlerTypePredicate}. The prefix for the first matching predicate
<del> * is used.
<add> * {@code Predicate}. The prefix for the first matching predicate is used.
<add> * <p>Consider using {@link org.springframework.web.method.HandlerTypePredicate
<add> * HandlerTypePredicate} to group controllers.
<ide> * @param prefix the prefix to apply
<ide> * @param predicate a predicate for matching controller types
<ide> * @since 5.1
<ide> */
<del> public PathMatchConfigurer addPathPrefix(String prefix, HandlerTypePredicate predicate) {
<add> public PathMatchConfigurer addPathPrefix(String prefix, Predicate<Class<?>> predicate) {
<ide> this.pathPrefixes = this.pathPrefixes == null ? new LinkedHashMap<>() : this.pathPrefixes;
<ide> this.pathPrefixes.put(prefix, predicate);
<ide> return this;
<ide> public PathMatcher getPathMatcher() {
<ide> }
<ide>
<ide> @Nullable
<del> protected Map<String, HandlerTypePredicate> getPathPrefixes() {
<add> protected Map<String, Predicate<Class<?>>> getPathPrefixes() {
<ide> return this.pathPrefixes;
<ide> }
<ide> }
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupport.java
<ide> import java.util.List;
<ide> import java.util.Locale;
<ide> import java.util.Map;
<add>import java.util.function.Predicate;
<ide> import javax.servlet.ServletContext;
<ide> import javax.servlet.http.HttpServletRequest;
<ide>
<ide> import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
<ide> import org.springframework.web.context.ServletContextAware;
<ide> import org.springframework.web.cors.CorsConfiguration;
<del>import org.springframework.web.method.HandlerTypePredicate;
<ide> import org.springframework.web.method.support.CompositeUriComponentsContributor;
<ide> import org.springframework.web.method.support.HandlerMethodArgumentResolver;
<ide> import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
<ide> public RequestMappingHandlerMapping requestMappingHandlerMapping() {
<ide> mapping.setPathMatcher(pathMatcher);
<ide> }
<ide>
<del> Map<String, HandlerTypePredicate> pathPrefixes = configurer.getPathPrefixes();
<add> Map<String, Predicate<Class<?>>> pathPrefixes = configurer.getPathPrefixes();
<ide> if (pathPrefixes != null) {
<ide> mapping.setPathPrefixes(pathPrefixes);
<ide> }
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMapping.java
<ide> import java.util.List;
<ide> import java.util.Map;
<ide> import java.util.Set;
<add>import java.util.function.Predicate;
<ide> import javax.servlet.http.HttpServletRequest;
<ide>
<ide> import org.springframework.context.EmbeddedValueResolverAware;
<ide> import org.springframework.web.bind.annotation.RequestMapping;
<ide> import org.springframework.web.bind.annotation.RequestMethod;
<ide> import org.springframework.web.cors.CorsConfiguration;
<del>import org.springframework.web.method.HandlerTypePredicate;
<ide> import org.springframework.web.method.HandlerMethod;
<ide> import org.springframework.web.servlet.handler.MatchableHandlerMapping;
<ide> import org.springframework.web.servlet.handler.RequestMatchResult;
<ide> public class RequestMappingHandlerMapping extends RequestMappingInfoHandlerMappi
<ide>
<ide> private boolean useTrailingSlashMatch = true;
<ide>
<del> private final Map<String, HandlerTypePredicate> pathPrefixes = new LinkedHashMap<>();
<add> private final Map<String, Predicate<Class<?>>> pathPrefixes = new LinkedHashMap<>();
<ide>
<ide> private ContentNegotiationManager contentNegotiationManager = new ContentNegotiationManager();
<ide>
<ide> public void setUseTrailingSlashMatch(boolean useTrailingSlashMatch) {
<ide> * Configure path prefixes to apply to controller methods.
<ide> * <p>Prefixes are used to enrich the mappings of every {@code @RequestMapping}
<ide> * method whose controller type is matched by the corresponding
<del> * {@link HandlerTypePredicate} in the map. The prefix for the first matching
<del> * predicate is used, assuming the input map has predictable order.
<add> * {@code Predicate}. The prefix for the first matching predicate is used.
<add> * <p>Consider using {@link org.springframework.web.method.HandlerTypePredicate
<add> * HandlerTypePredicate} to group controllers.
<ide> * @param prefixes a map with path prefixes as key
<ide> * @since 5.1
<ide> */
<del> public void setPathPrefixes(Map<String, HandlerTypePredicate> prefixes) {
<add> public void setPathPrefixes(Map<String, Predicate<Class<?>>> prefixes) {
<ide> this.pathPrefixes.clear();
<ide> prefixes.entrySet().stream()
<ide> .filter(entry -> StringUtils.hasText(entry.getKey()))
<ide> public boolean useTrailingSlashMatch() {
<ide> * The configured path prefixes as a read-only, possibly empty map.
<ide> * @since 5.1
<ide> */
<del> public Map<String, HandlerTypePredicate> getPathPrefixes() {
<add> public Map<String, Predicate<Class<?>>> getPathPrefixes() {
<ide> return Collections.unmodifiableMap(this.pathPrefixes);
<ide> }
<ide>
<ide> protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handler
<ide> if (typeInfo != null) {
<ide> info = typeInfo.combine(info);
<ide> }
<del> for (Map.Entry<String, HandlerTypePredicate> entry : this.pathPrefixes.entrySet()) {
<add> for (Map.Entry<String, Predicate<Class<?>>> entry : this.pathPrefixes.entrySet()) {
<ide> if (entry.getValue().test(handlerType)) {
<ide> String prefix = entry.getKey();
<ide> if (this.embeddedValueResolver != null) { | 8 |
Ruby | Ruby | add test for skip_before_filter with condition | 8da819eef5f11cc016ffa9ad747421ee50be32fa | <ide><path>actionpack/test/controller/filters_test.rb
<ide> class ConditionalOptionsFilter < ConditionalFilterController
<ide> before_filter :clean_up_tmp, :if => Proc.new { |c| false }
<ide> end
<ide>
<add> class ConditionalOptionsSkipFilter < ConditionalFilterController
<add> before_filter :ensure_login
<add> before_filter :clean_up_tmp
<add>
<add> skip_before_filter :ensure_login, if: -> { false }
<add> skip_before_filter :clean_up_tmp, if: -> { true }
<add> end
<add>
<ide> class PrependingController < TestController
<ide> prepend_before_filter :wonderful_life
<ide> # skip_before_filter :fire_flash
<ide> def test_running_conditional_options
<ide> assert_equal %w( ensure_login ), assigns["ran_filter"]
<ide> end
<ide>
<add> def test_running_conditional_skip_options
<add> test_process(ConditionalOptionsSkipFilter)
<add> assert_equal %w( ensure_login ), assigns["ran_filter"]
<add> end
<add>
<ide> def test_running_collection_condition_filters
<ide> test_process(ConditionalCollectionFilterController)
<ide> assert_equal %w( ensure_login ), assigns["ran_filter"] | 1 |
PHP | PHP | remove "experimental" tag from dic related classes | 7951860e65300daf7787754c9a3857031c6ba725 | <ide><path>src/Core/Container.php
<ide> * Dependency Injection container
<ide> *
<ide> * Based on the container out of League\Container
<del> *
<del> * @experimental This class' interface is not stable and may change
<del> * in future minor releases.
<ide> */
<ide> class Container extends LeagueContainer implements ContainerInterface
<ide> {
<ide><path>src/Core/ContainerApplicationInterface.php
<ide>
<ide> /**
<ide> * Interface for applications that configure and use a dependency injection container.
<del> *
<del> * @experimental This interface is not final and can have additional
<del> * methods and parameters added in future minor releases.
<ide> */
<ide> interface ContainerApplicationInterface
<ide> {
<ide><path>src/Core/ContainerInterface.php
<ide> *
<ide> * The methods defined in this interface use the conventions provided
<ide> * by league/container as that is the library that CakePHP uses.
<del> *
<del> * @experimental This interface is not final and can have additional
<del> * methods and parameters added in future minor releases.
<ide> */
<ide> interface ContainerInterface extends DefinitionContainerInterface
<ide> {
<ide><path>src/Core/ServiceProvider.php
<ide> * to organize your application's dependencies. They also help
<ide> * improve performance of applications with many services by
<ide> * allowing service registration to be deferred until services are needed.
<del> *
<del> * @experimental This class' interface is not stable and may change
<del> * in future minor releases.
<ide> */
<ide> abstract class ServiceProvider extends AbstractServiceProvider implements BootableServiceProviderInterface
<ide> { | 4 |
Javascript | Javascript | show component stack in proptypes warnings | 378c879a6a65afe18acacb8e2a6fe6ea323974df | <ide><path>src/isomorphic/ReactDebugTool.js
<ide> var ReactDebugTool = {
<ide> checkDebugID(debugID);
<ide> emitEvent('onSetOwner', debugID, ownerDebugID);
<ide> },
<add> onSetParent(debugID, parentDebugID) {
<add> checkDebugID(debugID);
<add> emitEvent('onSetParent', debugID, parentDebugID);
<add> },
<ide> onSetText(debugID, text) {
<ide> checkDebugID(debugID);
<ide> emitEvent('onSetText', debugID, text);
<ide><path>src/isomorphic/classic/element/ReactElementValidator.js
<ide>
<ide> 'use strict';
<ide>
<add>var ReactCurrentOwner = require('ReactCurrentOwner');
<add>var ReactComponentTreeDevtool = require('ReactComponentTreeDevtool');
<ide> var ReactElement = require('ReactElement');
<del>var ReactPropTypeLocations = require('ReactPropTypeLocations');
<ide> var ReactPropTypeLocationNames = require('ReactPropTypeLocationNames');
<del>var ReactCurrentOwner = require('ReactCurrentOwner');
<add>var ReactPropTypeLocations = require('ReactPropTypeLocations');
<ide>
<ide> var canDefineProperty = require('canDefineProperty');
<ide> var getIteratorFn = require('getIteratorFn');
<ide> function validateChildKeys(node, parentType) {
<ide> /**
<ide> * Assert that the props are valid
<ide> *
<add> * @param {object} element
<ide> * @param {string} componentName Name of the component for error messages.
<ide> * @param {object} propTypes Map of prop name to a ReactPropType
<del> * @param {object} props
<ide> * @param {string} location e.g. "prop", "context", "child context"
<ide> * @private
<ide> */
<del>function checkPropTypes(componentName, propTypes, props, location) {
<add>function checkPropTypes(element, componentName, propTypes, location) {
<add> var props = element.props;
<ide> for (var propName in propTypes) {
<ide> if (propTypes.hasOwnProperty(propName)) {
<ide> var error;
<ide> function checkPropTypes(componentName, propTypes, props, location) {
<ide> // same error.
<ide> loggedTypeFailures[error.message] = true;
<ide>
<del> var addendum = getDeclarationErrorAddendum();
<del> warning(false, 'Failed propType: %s%s', error.message, addendum);
<add> warning(
<add> false,
<add> 'Failed propType: %s%s',
<add> error.message,
<add> ReactComponentTreeDevtool.getCurrentStackAddendum(element)
<add> );
<ide> }
<ide> }
<ide> }
<ide> function validatePropTypes(element) {
<ide> var name = componentClass.displayName || componentClass.name;
<ide> if (componentClass.propTypes) {
<ide> checkPropTypes(
<add> element,
<ide> name,
<ide> componentClass.propTypes,
<del> element.props,
<ide> ReactPropTypeLocations.prop
<ide> );
<ide> }
<ide><path>src/isomorphic/classic/element/__tests__/ReactElementClone-test.js
<ide> describe('ReactElementClone', function() {
<ide> expect(console.error.argsForCall[0][0]).toBe(
<ide> 'Warning: Failed propType: ' +
<ide> 'Invalid prop `color` of type `number` supplied to `Component`, ' +
<del> 'expected `string`. Check the render method of `Parent`.'
<add> 'expected `string`.\n' +
<add> ' in Component (created by GrandParent)\n' +
<add> ' in Parent (created by GrandParent)\n' +
<add> ' in GrandParent'
<ide> );
<ide> });
<ide>
<ide><path>src/isomorphic/classic/element/__tests__/ReactElementValidator-test.js
<ide> describe('ReactElementValidator', function() {
<ide> expect(console.error.argsForCall[0][0]).toBe(
<ide> 'Warning: Failed propType: ' +
<ide> 'Invalid prop `color` of type `number` supplied to `MyComp`, ' +
<del> 'expected `string`. Check the render method of `ParentComp`.'
<add> 'expected `string`.\n' +
<add> ' in MyComp (created by ParentComp)\n' +
<add> ' in ParentComp'
<ide> );
<ide> });
<ide>
<ide> describe('ReactElementValidator', function() {
<ide> expect(console.error.calls.length).toBe(1);
<ide> expect(console.error.argsForCall[0][0]).toBe(
<ide> 'Warning: Failed propType: ' +
<del> 'Required prop `prop` was not specified in `Component`.'
<add> 'Required prop `prop` was not specified in `Component`.\n' +
<add> ' in Component'
<ide> );
<ide> });
<ide>
<ide> describe('ReactElementValidator', function() {
<ide> expect(console.error.calls.length).toBe(1);
<ide> expect(console.error.argsForCall[0][0]).toBe(
<ide> 'Warning: Failed propType: ' +
<del> 'Required prop `prop` was not specified in `Component`.'
<add> 'Required prop `prop` was not specified in `Component`.\n' +
<add> ' in Component'
<ide> );
<ide> });
<ide>
<ide> describe('ReactElementValidator', function() {
<ide> expect(console.error.calls.length).toBe(2);
<ide> expect(console.error.argsForCall[0][0]).toBe(
<ide> 'Warning: Failed propType: ' +
<del> 'Required prop `prop` was not specified in `Component`.'
<add> 'Required prop `prop` was not specified in `Component`.\n' +
<add> ' in Component'
<ide> );
<ide>
<ide> expect(console.error.argsForCall[1][0]).toBe(
<ide> 'Warning: Failed propType: ' +
<ide> 'Invalid prop `prop` of type `number` supplied to ' +
<del> '`Component`, expected `string`.'
<add> '`Component`, expected `string`.\n' +
<add> ' in Component'
<ide> );
<ide>
<ide> ReactTestUtils.renderIntoDocument(
<ide><path>src/isomorphic/classic/types/__tests__/ReactPropTypes-test.js
<ide> describe('ReactPropTypes', function() {
<ide> var instance = <Component num={6} />;
<ide> instance = ReactTestUtils.renderIntoDocument(instance);
<ide> expect(console.error.argsForCall.length).toBe(1);
<del> expect(console.error.argsForCall[0][0]).toBe(
<del> 'Warning: Failed propType: num must be 5!'
<add> expect(
<add> console.error.argsForCall[0][0].replace(/\(at .+?:\d+\)/g, '(at **)')
<add> ).toBe(
<add> 'Warning: Failed propType: num must be 5!\n' +
<add> ' in Component (at **)'
<ide> );
<ide> });
<ide>
<ide><path>src/isomorphic/devtools/ReactComponentTreeDevtool.js
<ide>
<ide> 'use strict';
<ide>
<add>var ReactCurrentOwner = require('ReactCurrentOwner');
<add>
<ide> var invariant = require('invariant');
<ide>
<ide> var tree = {};
<ide> var ReactComponentTreeDevtool = {
<ide>
<ide> onSetChildren(id, nextChildIDs) {
<ide> updateTree(id, item => {
<del> var prevChildIDs = item.childIDs;
<ide> item.childIDs = nextChildIDs;
<ide>
<ide> nextChildIDs.forEach(nextChildID => {
<ide> var ReactComponentTreeDevtool = {
<ide> 'Expected onMountComponent() to fire for the child ' +
<ide> 'before its parent includes it in onSetChildren().'
<ide> );
<del>
<del> if (prevChildIDs.indexOf(nextChildID) === -1) {
<add> if (nextChild.parentID == null) {
<ide> nextChild.parentID = id;
<add> // TODO: This shouldn't be necessary but mounting a new root during in
<add> // componentWillMount currently causes not-yet-mounted components to
<add> // be purged from our tree data so their parent ID is missing.
<ide> }
<add> invariant(
<add> nextChild.parentID === id,
<add> 'Expected onSetParent() and onSetChildren() to be consistent (%s ' +
<add> 'has parents %s and %s).',
<add> nextChildID,
<add> nextChild.parentID,
<add> id
<add> );
<ide> });
<ide> });
<ide> },
<ide> var ReactComponentTreeDevtool = {
<ide> updateTree(id, item => item.ownerID = ownerID);
<ide> },
<ide>
<add> onSetParent(id, parentID) {
<add> updateTree(id, item => item.parentID = parentID);
<add> },
<add>
<ide> onSetText(id, text) {
<ide> updateTree(id, item => item.text = text);
<ide> },
<ide> var ReactComponentTreeDevtool = {
<ide> return item ? item.isMounted : false;
<ide> },
<ide>
<add> getCurrentStackAddendum(topElement) {
<add> function describeComponentFrame(name, source, ownerName) {
<add> return '\n in ' + name + (
<add> source ?
<add> ' (at ' + source.fileName.replace(/^.*[\\\/]/, '') + ':' +
<add> source.lineNumber + ')' :
<add> ownerName ?
<add> ' (created by ' + ownerName + ')' :
<add> ''
<add> );
<add> }
<add>
<add> function describeID(id) {
<add> var name = ReactComponentTreeDevtool.getDisplayName(id);
<add> var element = ReactComponentTreeDevtool.getElement(id);
<add> var ownerID = ReactComponentTreeDevtool.getOwnerID(id);
<add> var ownerName;
<add> if (ownerID) {
<add> ownerName = ReactComponentTreeDevtool.getDisplayName(ownerID);
<add> }
<add> return describeComponentFrame(name, element._source, ownerName);
<add> }
<add>
<add> var info = '';
<add> if (topElement) {
<add> var type = topElement.type;
<add> var name = typeof type === 'function' ?
<add> type.displayName || type.name :
<add> type;
<add> var owner = topElement._owner;
<add> info += describeComponentFrame(
<add> name || 'Unknown',
<add> topElement._source,
<add> owner && owner.getName()
<add> );
<add> }
<add>
<add> var currentOwner = ReactCurrentOwner.current;
<add> var id = currentOwner && currentOwner._debugID;
<add> while (id) {
<add> info += describeID(id);
<add> id = ReactComponentTreeDevtool.getParentID(id);
<add> }
<add>
<add> return info;
<add> },
<add>
<ide> getChildIDs(id) {
<ide> var item = tree[id];
<ide> return item ? item.childIDs : [];
<ide> var ReactComponentTreeDevtool = {
<ide> return item ? item.displayName : 'Unknown';
<ide> },
<ide>
<add> getElement(id) {
<add> var item = tree[id];
<add> return item ? item.element : null;
<add> },
<add>
<ide> getOwnerID(id) {
<ide> var item = tree[id];
<ide> return item ? item.ownerID : null;
<ide><path>src/isomorphic/devtools/__tests__/ReactComponentTreeDevtool-test.js
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> expect(getRootDisplayNames()).toEqual([]);
<ide> expect(getRegisteredDisplayNames()).toEqual([]);
<ide> });
<add>
<add> it('creates stack addenda', () => {
<add> function getAddendum(element) {
<add> var addendum = ReactComponentTreeDevtool.getCurrentStackAddendum(element);
<add> return addendum.replace(/\(at .+?:\d+\)/g, '(at **)');
<add> }
<add>
<add> var Anon = React.createClass({displayName: null, render: () => null});
<add> var Orange = React.createClass({render: () => null});
<add>
<add> expect(getAddendum()).toBe(
<add> ''
<add> );
<add> expect(getAddendum(<div />)).toBe(
<add> '\n in div (at **)'
<add> );
<add> expect(getAddendum(<Anon />)).toBe(
<add> '\n in Unknown (at **)'
<add> );
<add> expect(getAddendum(<Orange />)).toBe(
<add> '\n in Orange (at **)'
<add> );
<add> expect(getAddendum(React.createElement(Orange))).toBe(
<add> '\n in Orange'
<add> );
<add>
<add> var renders = 0;
<add> var rOwnedByQ;
<add>
<add> function Q() {
<add> return (rOwnedByQ = React.createElement(R));
<add> }
<add> function R() {
<add> return <div><S /></div>;
<add> }
<add> class S extends React.Component {
<add> componentDidMount() {
<add> // Check that the parent path is still fetched when only S itself is on
<add> // the stack.
<add> this.forceUpdate();
<add> }
<add> render() {
<add> expect(getAddendum()).toBe(
<add> '\n in S (at **)' +
<add> '\n in div (at **)' +
<add> '\n in R (created by Q)' +
<add> '\n in Q (at **)'
<add> );
<add> expect(getAddendum(<span />)).toBe(
<add> '\n in span (at **)' +
<add> '\n in S (at **)' +
<add> '\n in div (at **)' +
<add> '\n in R (created by Q)' +
<add> '\n in Q (at **)'
<add> );
<add> expect(getAddendum(React.createElement('span'))).toBe(
<add> '\n in span (created by S)' +
<add> '\n in S (at **)' +
<add> '\n in div (at **)' +
<add> '\n in R (created by Q)' +
<add> '\n in Q (at **)'
<add> );
<add> renders++;
<add> return null;
<add> }
<add> }
<add> ReactDOM.render(<Q />, document.createElement('div'));
<add> expect(renders).toBe(2);
<add>
<add> // Make sure owner is fetched for the top element too.
<add> expect(getAddendum(rOwnedByQ)).toBe(
<add> '\n in R (created by Q)'
<add> );
<add> });
<ide> });
<ide><path>src/isomorphic/modern/element/__tests__/ReactJSXElementValidator-test.js
<ide> describe('ReactJSXElementValidator', function() {
<ide> }
<ide> }
<ide> ReactTestUtils.renderIntoDocument(<ParentComp />);
<del> expect(console.error.argsForCall[0][0]).toBe(
<add> expect(
<add> console.error.argsForCall[0][0].replace(/\(at .+?:\d+\)/g, '(at **)')
<add> ).toBe(
<ide> 'Warning: Failed propType: ' +
<ide> 'Invalid prop `color` of type `number` supplied to `MyComp`, ' +
<del> 'expected `string`. Check the render method of `ParentComp`.'
<add> 'expected `string`.\n' +
<add> ' in MyComp (at **)\n' +
<add> ' in ParentComp (at **)'
<ide> );
<ide> });
<ide>
<ide> describe('ReactJSXElementValidator', function() {
<ide> ReactTestUtils.renderIntoDocument(<RequiredPropComponent />);
<ide>
<ide> expect(console.error.calls.length).toBe(1);
<del> expect(console.error.argsForCall[0][0]).toBe(
<add> expect(
<add> console.error.argsForCall[0][0].replace(/\(at .+?:\d+\)/g, '(at **)')
<add> ).toBe(
<ide> 'Warning: Failed propType: ' +
<del> 'Required prop `prop` was not specified in `RequiredPropComponent`.'
<add> 'Required prop `prop` was not specified in `RequiredPropComponent`.\n' +
<add> ' in RequiredPropComponent (at **)'
<ide> );
<ide> });
<ide>
<ide> describe('ReactJSXElementValidator', function() {
<ide> ReactTestUtils.renderIntoDocument(<RequiredPropComponent prop={null} />);
<ide>
<ide> expect(console.error.calls.length).toBe(1);
<del> expect(console.error.argsForCall[0][0]).toBe(
<add> expect(
<add> console.error.argsForCall[0][0].replace(/\(at .+?:\d+\)/g, '(at **)')
<add> ).toBe(
<ide> 'Warning: Failed propType: ' +
<del> 'Required prop `prop` was not specified in `RequiredPropComponent`.'
<add> 'Required prop `prop` was not specified in `RequiredPropComponent`.\n' +
<add> ' in RequiredPropComponent (at **)'
<ide> );
<ide> });
<ide>
<ide> describe('ReactJSXElementValidator', function() {
<ide> ReactTestUtils.renderIntoDocument(<RequiredPropComponent prop={42} />);
<ide>
<ide> expect(console.error.calls.length).toBe(2);
<del> expect(console.error.argsForCall[0][0]).toBe(
<add> expect(
<add> console.error.argsForCall[0][0].replace(/\(at .+?:\d+\)/g, '(at **)')
<add> ).toBe(
<ide> 'Warning: Failed propType: ' +
<del> 'Required prop `prop` was not specified in `RequiredPropComponent`.'
<add> 'Required prop `prop` was not specified in `RequiredPropComponent`.\n' +
<add> ' in RequiredPropComponent (at **)'
<ide> );
<ide>
<del> expect(console.error.argsForCall[1][0]).toBe(
<add> expect(
<add> console.error.argsForCall[1][0].replace(/\(at .+?:\d+\)/g, '(at **)')
<add> ).toBe(
<ide> 'Warning: Failed propType: ' +
<ide> 'Invalid prop `prop` of type `number` supplied to ' +
<del> '`RequiredPropComponent`, expected `string`.'
<add> '`RequiredPropComponent`, expected `string`.\n' +
<add> ' in RequiredPropComponent (at **)'
<ide> );
<ide>
<ide> ReactTestUtils.renderIntoDocument(<RequiredPropComponent prop="string" />);
<ide><path>src/renderers/dom/shared/ReactDOMComponent.js
<ide> if (__DEV__) {
<ide> var contentDebugID = debugID + '#text';
<ide> this._contentDebugID = contentDebugID;
<ide> ReactInstrumentation.debugTool.onSetDisplayName(contentDebugID, '#text');
<add> ReactInstrumentation.debugTool.onSetParent(contentDebugID, debugID);
<add> ReactInstrumentation.debugTool.onBeforeMountComponent(contentDebugID);
<ide> ReactInstrumentation.debugTool.onSetText(contentDebugID, '' + contentToUse);
<ide> ReactInstrumentation.debugTool.onMountComponent(contentDebugID);
<ide> ReactInstrumentation.debugTool.onSetChildren(debugID, [contentDebugID]);
<ide><path>src/renderers/shared/stack/reconciler/ReactCompositeComponent.js
<ide> var ReactCompositeComponentMixin = {
<ide> }
<ide>
<ide> this._renderedNodeType = ReactNodeTypes.getType(renderedElement);
<del> this._renderedComponent = this._instantiateReactComponent(
<add> var child = this._instantiateReactComponent(
<ide> renderedElement
<ide> );
<add> this._renderedComponent = child;
<add> if (__DEV__) {
<add> if (child._debugID !== 0 && this._debugID !== 0) {
<add> ReactInstrumentation.debugTool.onSetParent(
<add> child._debugID,
<add> this._debugID
<add> );
<add> }
<add> }
<ide>
<ide> var markup = ReactReconciler.mountComponent(
<del> this._renderedComponent,
<add> child,
<ide> transaction,
<ide> hostParent,
<ide> hostContainerInfo,
<ide> var ReactCompositeComponentMixin = {
<ide> if (this._debugID !== 0) {
<ide> ReactInstrumentation.debugTool.onSetChildren(
<ide> this._debugID,
<del> this._renderedComponent._debugID !== 0 ?
<del> [this._renderedComponent._debugID] :
<del> []
<add> child._debugID !== 0 ? [child._debugID] : []
<ide> );
<ide> }
<ide> }
<ide> var ReactCompositeComponentMixin = {
<ide> ReactReconciler.unmountComponent(prevComponentInstance, false);
<ide>
<ide> this._renderedNodeType = ReactNodeTypes.getType(nextRenderedElement);
<del> this._renderedComponent = this._instantiateReactComponent(
<add> var child = this._instantiateReactComponent(
<ide> nextRenderedElement
<ide> );
<add> this._renderedComponent = child;
<add> if (__DEV__) {
<add> if (child._debugID !== 0 && this._debugID !== 0) {
<add> ReactInstrumentation.debugTool.onSetParent(
<add> child._debugID,
<add> this._debugID
<add> );
<add> }
<add> }
<ide>
<ide> var nextMarkup = ReactReconciler.mountComponent(
<del> this._renderedComponent,
<add> child,
<ide> transaction,
<ide> this._hostParent,
<ide> this._hostContainerInfo,
<ide> var ReactCompositeComponentMixin = {
<ide> if (this._debugID !== 0) {
<ide> ReactInstrumentation.debugTool.onSetChildren(
<ide> this._debugID,
<del> this._renderedComponent._debugID !== 0 ?
<del> [this._renderedComponent._debugID] :
<del> []
<add> child._debugID !== 0 ? [child._debugID] : []
<ide> );
<ide> }
<ide> }
<ide><path>src/renderers/shared/stack/reconciler/ReactMultiChild.js
<ide> function processQueue(inst, updateQueue) {
<ide> );
<ide> }
<ide>
<add>var setParentForInstrumentation = emptyFunction;
<ide> var setChildrenForInstrumentation = emptyFunction;
<ide> if (__DEV__) {
<add> setParentForInstrumentation = function(child) {
<add> if (child._debugID !== 0) {
<add> ReactInstrumentation.debugTool.onSetParent(child._debugID, this._debugID);
<add> }
<add> };
<ide> setChildrenForInstrumentation = function(children) {
<ide> ReactInstrumentation.debugTool.onSetChildren(
<ide> this._debugID,
<ide> var ReactMultiChild = {
<ide> for (var name in children) {
<ide> if (children.hasOwnProperty(name)) {
<ide> var child = children[name];
<add> if (__DEV__) {
<add> setParentForInstrumentation.call(this, child);
<add> }
<ide> var mountImage = ReactReconciler.mountComponent(
<ide> child,
<ide> transaction,
<ide><path>src/renderers/shared/stack/reconciler/ReactReconciler.js
<ide> var ReactReconciler = {
<ide> internalInstance._debugID,
<ide> 'performUpdateIfNecessary'
<ide> );
<add> ReactInstrumentation.debugTool.onBeforeUpdateComponent(
<add> internalInstance._debugID,
<add> internalInstance._currentElement
<add> );
<ide> }
<ide> }
<ide> internalInstance.performUpdateIfNecessary(transaction);
<ide><path>src/renderers/shared/stack/reconciler/__tests__/ReactStatelessComponent-test.js
<ide> describe('ReactStatelessComponent', function() {
<ide> spyOn(console, 'error');
<ide> ReactTestUtils.renderIntoDocument(<Child />);
<ide> expect(console.error.argsForCall.length).toBe(1);
<del> expect(console.error.argsForCall[0][0]).toBe(
<add> expect(
<add> console.error.argsForCall[0][0].replace(/\(at .+?:\d+\)/g, '(at **)')
<add> ).toBe(
<ide> 'Warning: Failed propType: Invalid prop `test` of type `number` ' +
<del> 'supplied to `Child`, expected `string`.'
<add> 'supplied to `Child`, expected `string`.\n' +
<add> ' in Child (at **)'
<ide> );
<ide> });
<ide> | 13 |
Ruby | Ruby | preserve link status on reinstall/upgrade | 7ec05052003ecf6142d94aeaa62f4b4bd84a569d | <ide><path>Library/Homebrew/cmd/reinstall.rb
<ide> def reinstall
<ide> def reinstall_formula(f)
<ide> if f.opt_prefix.directory?
<ide> keg = Keg.new(f.opt_prefix.resolved_path)
<add> keg_was_linked = keg.linked?
<ide> backup keg
<ide> end
<ide>
<ide> def reinstall_formula(f)
<ide> fi.build_bottle = ARGV.build_bottle? || (!f.bottled? && f.build.bottle?)
<ide> fi.interactive = ARGV.interactive?
<ide> fi.git = ARGV.git?
<add> fi.keg_was_linked = keg_was_linked
<ide> fi.prelude
<ide>
<ide> oh1 "Reinstalling #{f.full_name} #{options.to_a.join " "}"
<ide> def reinstall_formula(f)
<ide> rescue FormulaInstallationAlreadyAttemptedError
<ide> # next
<ide> rescue Exception
<del> ignore_interrupts { restore_backup(keg, f) }
<add> ignore_interrupts { restore_backup(keg, keg_was_linked) }
<ide> raise
<ide> else
<ide> backup_path(keg).rmtree if backup_path(keg).exist?
<ide> def backup(keg)
<ide> keg.rename backup_path(keg)
<ide> end
<ide>
<del> def restore_backup(keg, formula)
<add> def restore_backup(keg, keg_was_linked)
<ide> path = backup_path(keg)
<ide>
<ide> return unless path.directory?
<ide>
<ide> Pathname.new(keg).rmtree if keg.exist?
<ide>
<ide> path.rename keg
<del> keg.link unless formula.keg_only?
<add> keg.link if keg_was_linked
<ide> end
<ide>
<ide> def backup_path(path)
<ide><path>Library/Homebrew/cmd/upgrade.rb
<ide> def upgrade_formula(f)
<ide> .map(&:linked_keg)
<ide> .select(&:directory?)
<ide> .map { |k| Keg.new(k.resolved_path) }
<add> linked_kegs = outdated_kegs.select(&:linked?)
<ide>
<ide> if f.opt_prefix.directory?
<ide> keg = Keg.new(f.opt_prefix.resolved_path)
<ide> def upgrade_formula(f)
<ide> ensure
<ide> # restore previous installation state if build failed
<ide> begin
<del> outdated_kegs.each(&:link) unless f.installed?
<add> linked_kegs.each(&:link) unless f.installed?
<ide> rescue
<ide> nil
<ide> end
<ide><path>Library/Homebrew/formula_installer.rb
<ide> def self.mode_attr_accessor(*names)
<ide> mode_attr_accessor :show_summary_heading, :show_header
<ide> mode_attr_accessor :build_from_source, :force_bottle
<ide> mode_attr_accessor :ignore_deps, :only_deps, :interactive, :git
<del> mode_attr_accessor :verbose, :debug, :quieter
<add> mode_attr_accessor :verbose, :debug, :quieter, :keg_was_linked
<ide>
<ide> def initialize(formula)
<ide> @formula = formula
<add> @rack_was_present = formula.rack.directory?
<add> @keg_was_linked = if formula.linked_keg.directory?
<add> keg = Keg.new(formula.linked_keg.resolved_path)
<add> keg.linked?
<add> else
<add> false
<add> end
<ide> @show_header = false
<ide> @ignore_deps = false
<ide> @only_deps = false
<ide> def install_dependency(dep, inherited_options)
<ide>
<ide> if df.linked_keg.directory?
<ide> linked_keg = Keg.new(df.linked_keg.resolved_path)
<add> keg_was_linked = keg.linked?
<ide> linked_keg.unlink
<ide> end
<ide>
<ide> def install_dependency(dep, inherited_options)
<ide> fi.verbose = verbose?
<ide> fi.quieter = quieter?
<ide> fi.debug = debug?
<add> fi.keg_was_linked = keg_was_linked
<ide> fi.installed_as_dependency = true
<ide> fi.installed_on_request = false
<ide> fi.prelude
<ide> def install_dependency(dep, inherited_options)
<ide> rescue Exception
<ide> ignore_interrupts do
<ide> tmp_keg.rename(installed_keg) if tmp_keg && !installed_keg.directory?
<del> linked_keg.link if linked_keg
<add> linked_keg.link if keg_was_linked
<ide> end
<ide> raise
<ide> else
<ide> def build
<ide> end
<ide>
<ide> def link(keg)
<del> if formula.keg_only?
<add> link_formula = if @rack_was_present
<add> keg_was_linked?
<add> else
<add> !formula.keg_only?
<add> end
<add>
<add> unless link_formula
<ide> begin
<ide> keg.optlink
<ide> rescue Keg::LinkError => e
<ide><path>Library/Homebrew/test/bottle_hooks_spec.rb
<ide> local_bottle_path: nil,
<ide> bottle_disabled?: false,
<ide> some_random_method: true,
<add> linked_keg: Pathname("foo"),
<add> rack: Pathname("bar"),
<ide> )
<ide> end
<ide> | 4 |
Python | Python | convert stored tracebacks to strings | 5f09ce1469721a8ca38bfdffad8ffd42b2494025 | <ide><path>celery/execute.py
<ide> from functools import partial as curry
<ide> from datetime import datetime, timedelta
<ide> from multiprocessing import get_logger
<add>import sys
<ide> import traceback
<ide> import inspect
<ide>
<ide> def apply(task, args, kwargs, **options):
<ide> try:
<ide> ret_value = task(*args, **kwargs)
<ide> status = "DONE"
<del> tb = None
<add> strtb = None
<ide> except Exception, exc:
<add> type_, value_, tb = sys.exc_info()
<add> strtb = "\n".join(traceback.format_exception(type_, value_, tb))
<ide> ret_value = exc
<del> tb = traceback.format_stack()
<ide> status = "FAILURE"
<ide>
<del> return EagerResult(task_id, ret_value, status, traceback=tb)
<add> return EagerResult(task_id, ret_value, status, traceback=strtb)
<ide><path>celery/worker/job.py
<ide> def jail(task_id, task_name, func, args, kwargs):
<ide> If the call was successful, it saves the result to the task result
<ide> backend, and sets the task status to ``"DONE"``.
<ide>
<add> If the call raises :exc:`celery.task.base.RetryTaskError`, it extracts
<add> the original exception, uses that as the result and sets the task status
<add> to ``"RETRY"``.
<add>
<ide> If the call results in an exception, it saves the exception as the task
<ide> result, and sets the task status to ``"FAILURE"``.
<ide>
<ide> def jail(task_id, task_name, func, args, kwargs):
<ide> raise
<ide> except RetryTaskError, exc:
<ide> ### Task is to be retried.
<del> type_, _, tb = sys.exc_info()
<add> type_, value_, tb = sys.exc_info()
<add> strtb = "\n".join(traceback.format_exception(type_, value_, tb))
<ide>
<ide> # RetryTaskError stores both a small message describing the retry
<ide> # and the original exception.
<ide> message, orig_exc = exc.args
<del> default_backend.mark_as_retry(task_id, orig_exc, tb)
<add> default_backend.mark_as_retry(task_id, orig_exc, strtb)
<ide>
<ide> # Create a simpler version of the RetryTaskError that stringifies
<ide> # the original exception instead of including the exception instance.
<ide> def jail(task_id, task_name, func, args, kwargs):
<ide> tb))
<ide> except Exception, exc:
<ide> ### Task ended in failure.
<del> type_, _, tb = sys.exc_info()
<add> type_, value_, tb = sys.exc_info()
<add> strtb = "\n".join(traceback.format_exception(type_, value_, tb))
<ide>
<ide> # mark_as_failure returns an exception that is guaranteed to
<ide> # be pickleable.
<del> stored_exc = default_backend.mark_as_failure(task_id, exc, tb)
<add> stored_exc = default_backend.mark_as_failure(task_id, exc, strtb)
<ide>
<ide> # wrap exception info + traceback and return it to caller.
<ide> retval = ExceptionInfo((type_, stored_exc, tb)) | 2 |
PHP | PHP | add phar to list | f647a24b918648c2b8a17c122b855bc0b2bf5b86 | <ide><path>src/Illuminate/Validation/Concerns/ValidatesAttributes.php
<ide> protected function shouldBlockPhpUpload($value, $parameters)
<ide> }
<ide>
<ide> $phpExtensions = [
<del> 'php', 'php3', 'php4', 'php5', 'phtml',
<add> 'php', 'php3', 'php4', 'php5', 'phtml', 'phar'
<ide> ];
<ide>
<ide> return ($value instanceof UploadedFile) | 1 |
Go | Go | provide more information when testtop tests fail | 3ac90aeed5a6bdfe22af48eca1519fb186dc66cb | <ide><path>integration-cli/docker_cli_top_test.go
<ide> func TestTopNonPrivileged(t *testing.T) {
<ide> out, _, err = runCommandWithOutput(topCmd)
<ide> errorOut(err, t, fmt.Sprintf("failed to run top: %v %v", out, err))
<ide>
<add> topCmd = exec.Command(dockerBinary, "top", cleanedContainerID)
<add> out2, _, err2 := runCommandWithOutput(topCmd)
<add> errorOut(err, t, fmt.Sprintf("failed to run top: %v %v", out2, err2))
<add>
<ide> killCmd := exec.Command(dockerBinary, "kill", cleanedContainerID)
<ide> _, err = runCommand(killCmd)
<ide> errorOut(err, t, fmt.Sprintf("failed to kill container: %v", err))
<ide>
<ide> deleteContainer(cleanedContainerID)
<ide>
<del> if !strings.Contains(out, "sleep 20") {
<del> t.Fatal("top should've listed sleep 20 in the process list")
<add> if !strings.Contains(out, "sleep 20") && !strings.Contains(out2, "sleep 20") {
<add> t.Fatal("top should've listed `sleep 20` in the process list, but failed twice")
<add> } else if !strings.Contains(out, "sleep 20") {
<add> t.Fatal("top should've listed `sleep 20` in the process list, but failed the first time")
<add> } else if !strings.Contains(out2, "sleep 20") {
<add> t.Fatal("top should've listed `sleep 20` in the process list, but failed the second itime")
<ide> }
<ide>
<ide> logDone("top - sleep process should be listed in non privileged mode")
<ide> func TestTopPrivileged(t *testing.T) {
<ide> out, _, err = runCommandWithOutput(topCmd)
<ide> errorOut(err, t, fmt.Sprintf("failed to run top: %v %v", out, err))
<ide>
<add> topCmd = exec.Command(dockerBinary, "top", cleanedContainerID)
<add> out2, _, err2 := runCommandWithOutput(topCmd)
<add> errorOut(err, t, fmt.Sprintf("failed to run top: %v %v", out2, err2))
<add>
<ide> killCmd := exec.Command(dockerBinary, "kill", cleanedContainerID)
<ide> _, err = runCommand(killCmd)
<ide> errorOut(err, t, fmt.Sprintf("failed to kill container: %v", err))
<ide>
<ide> deleteContainer(cleanedContainerID)
<ide>
<del> if !strings.Contains(out, "sleep 20") {
<del> t.Fatal("top should've listed sleep 20 in the process list")
<add> if !strings.Contains(out, "sleep 20") && !strings.Contains(out2, "sleep 20") {
<add> t.Fatal("top should've listed `sleep 20` in the process list, but failed twice")
<add> } else if !strings.Contains(out, "sleep 20") {
<add> t.Fatal("top should've listed `sleep 20` in the process list, but failed the first time")
<add> } else if !strings.Contains(out2, "sleep 20") {
<add> t.Fatal("top should've listed `sleep 20` in the process list, but failed the second itime")
<ide> }
<ide>
<ide> logDone("top - sleep process should be listed in privileged mode") | 1 |
Go | Go | return better errors from exec | f078f75bf25353720f28f9f1ea180374fe205302 | <ide><path>api/server/exec.go
<ide> func (s *Server) postContainerExecStart(version version.Version, w http.Response
<ide> return err
<ide> }
<ide> var (
<del> execName = vars["name"]
<del> stdin io.ReadCloser
<del> stdout io.Writer
<del> stderr io.Writer
<add> execName = vars["name"]
<add> stdin, inStream io.ReadCloser
<add> stdout, stderr, outStream io.Writer
<ide> )
<ide>
<ide> execStartCheck := &types.ExecStartCheck{}
<ide> func (s *Server) postContainerExecStart(version version.Version, w http.Response
<ide> }
<ide>
<ide> if !execStartCheck.Detach {
<add> var err error
<ide> // Setting up the streaming http interface.
<del> inStream, outStream, err := hijackServer(w)
<add> inStream, outStream, err = hijackServer(w)
<ide> if err != nil {
<ide> return err
<ide> }
<ide> defer closeStreams(inStream, outStream)
<ide>
<del> var errStream io.Writer
<del>
<ide> if _, ok := r.Header["Upgrade"]; ok {
<ide> fmt.Fprintf(outStream, "HTTP/1.1 101 UPGRADED\r\nContent-Type: application/vnd.docker.raw-stream\r\nConnection: Upgrade\r\nUpgrade: tcp\r\n\r\n")
<ide> } else {
<ide> fmt.Fprintf(outStream, "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n")
<ide> }
<ide>
<ide> if !execStartCheck.Tty {
<del> errStream = stdcopy.NewStdWriter(outStream, stdcopy.Stderr)
<del> outStream = stdcopy.NewStdWriter(outStream, stdcopy.Stdout)
<add> stderr = stdcopy.NewStdWriter(outStream, stdcopy.Stderr)
<add> stdout = stdcopy.NewStdWriter(outStream, stdcopy.Stdout)
<ide> }
<del>
<ide> stdin = inStream
<del> stdout = outStream
<del> stderr = errStream
<ide> }
<del> // Now run the user process in container.
<ide>
<add> // Now run the user process in container.
<ide> if err := s.daemon.ContainerExecStart(execName, stdin, stdout, stderr); err != nil {
<del> logrus.Errorf("Error starting exec command in container %s: %s", execName, err)
<del> return err
<add> fmt.Fprintf(outStream, "Error running exec in container: %v\n", err)
<ide> }
<del> w.WriteHeader(http.StatusNoContent)
<del>
<ide> return nil
<ide> }
<ide>
<ide><path>daemon/exec.go
<ide> func (d *Daemon) ContainerExecCreate(config *runconfig.ExecConfig) (string, erro
<ide> }
<ide>
<ide> func (d *Daemon) ContainerExecStart(execName string, stdin io.ReadCloser, stdout io.Writer, stderr io.Writer) error {
<del>
<ide> var (
<ide> cStdin io.ReadCloser
<ide> cStdout, cStderr io.Writer
<ide> func (d *Daemon) ContainerExecStart(execName string, stdin io.ReadCloser, stdout
<ide> if err != nil {
<ide> return fmt.Errorf("attach failed with error: %s", err)
<ide> }
<del> break
<add> return nil
<ide> case err := <-execErr:
<add> if err == nil {
<add> return nil
<add> }
<add>
<add> // Maybe the container stopped while we were trying to exec
<add> if !container.IsRunning() {
<add> return fmt.Errorf("container stopped while running exec")
<add> }
<ide> return err
<ide> }
<del>
<del> return nil
<ide> }
<ide>
<ide> func (d *Daemon) Exec(c *Container, execConfig *execConfig, pipes *execdriver.Pipes, startCallback execdriver.StartCallback) (int, error) { | 2 |
Text | Text | redirect docs.brew.sh/linux to homebrew on linux | deffe8d403ff092c04b92094635eb8006c8f3bdf | <ide><path>docs/Homebrew-on-Linux.md
<ide> title: Homebrew on Linux
<ide> logo: https://brew.sh/assets/img/linuxbrew.png
<ide> image: https://brew.sh/assets/img/linuxbrew.png
<ide> redirect_from:
<add> - /linux
<ide> - /Linux
<ide> - /Linuxbrew
<ide> --- | 1 |
Python | Python | fix 2/3 problems for training | d108534dc289f4f1342194be8cc0151bad769153 | <ide><path>spacy/en/__init__.py
<ide> from __future__ import unicode_literals, print_function
<ide>
<ide> from os import path
<add>from pathlib import Path
<ide>
<ide> from ..util import match_best_version
<ide> from ..util import get_data_path
<ide>
<ide> from .language_data import *
<ide>
<add>try:
<add> basestring
<add>except NameError:
<add> basestring = str
<add>
<ide>
<ide> class English(Language):
<ide> lang = 'en'
<ide> def _fix_deprecated_glove_vectors_loading(overrides):
<ide> data_path = get_data_path()
<ide> else:
<ide> path = overrides['path']
<add> if isinstance(path, basestring):
<add> path = Path(path)
<ide> data_path = path.parent
<ide> vec_path = None
<ide> if 'add_vectors' not in overrides:
<ide> if 'vectors' in overrides:
<ide> vec_path = match_best_version(overrides['vectors'], None, data_path)
<ide> if vec_path is None:
<del> raise IOError(
<del> 'Could not load data pack %s from %s' % (overrides['vectors'], data_path))
<add> return overrides
<ide> else:
<ide> vec_path = match_best_version('en_glove_cc_300_1m_vectors', None, data_path)
<ide> if vec_path is not None: | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.