content_type stringclasses 8 values | main_lang stringclasses 7 values | message stringlengths 1 50 | sha stringlengths 40 40 | patch stringlengths 52 962k | file_count int64 1 300 |
|---|---|---|---|---|---|
PHP | PHP | avoid unexpected removal of items with null key | 528e4381af27a16eb59082b53c0e21a30e42dc1a | <ide><path>src/Illuminate/Support/Arr.php
<ide> public static function forget(&$array, $keys)
<ide> foreach ($keys as $key) {
<ide> $parts = explode('.', $key);
<ide>
<add> // clean up before each pass
<add> $array = &$original;
<add>
<ide> while (count($parts) > 1) {
<ide> $part = array_shift($parts);
<ide>
<ide> if (isset($array[$part]) && is_array($array[$part])) {
<ide> $array = &$array[$part];
<ide> } else {
<del> $parts = [];
<add> break(2);
<ide> }
<ide> }
<ide>
<ide> unset($array[array_shift($parts)]);
<del>
<del> // clean up after each pass
<del> $array = &$original;
<ide> }
<ide> }
<ide>
<ide><path>tests/Support/SupportArrTest.php
<ide> public function testForget()
<ide> $array = ['products' => ['desk' => ['price' => ['original' => 50, 'taxes' => 60]]]];
<ide> Arr::forget($array, 'products.desk.final.taxes');
<ide> $this->assertEquals(['products' => ['desk' => ['price' => ['original' => 50, 'taxes' => 60]]]], $array);
<add>
<add> $array = ['products' => ['desk' => ['price' => 50], null => 'something']];
<add> Arr::forget($array, 'products.amount.all');
<add> $this->assertEquals(['products' => ['desk' => ['price' => 50], null => 'something']], $array);
<ide> }
<ide> } | 2 |
Go | Go | unify host-options, and use consts | 6a5393636e358173e17275d3bd64218f6157f01d | <ide><path>opts/hosts_unix.go
<ide>
<ide> package opts // import "github.com/docker/docker/opts"
<ide>
<del>import "fmt"
<add>const (
<add> // DefaultHTTPHost Default HTTP Host used if only port is provided to -H flag e.g. dockerd -H tcp://:8080
<add> DefaultHTTPHost = "localhost"
<ide>
<del>// DefaultHost constant defines the default host string used by docker on other hosts than Windows
<del>var DefaultHost = fmt.Sprintf("unix://%s", DefaultUnixSocket)
<add> // DefaultHost constant defines the default host string used by docker on other hosts than Windows
<add> DefaultHost = "unix://" + DefaultUnixSocket
<add>)
<ide><path>opts/hosts_windows.go
<ide> package opts // import "github.com/docker/docker/opts"
<ide>
<del>// DefaultHost constant defines the default host string used by docker on Windows
<del>var DefaultHost = "npipe://" + DefaultNamedPipe
<add>const (
<add> // TODO Windows. Identify bug in GOLang 1.5.1+ and/or Windows Server 2016 TP5.
<add> //
<add> // On Windows, this mitigates a problem with the default options of running
<add> // a docker client against a local docker daemon on TP5.
<add> //
<add> // What was found that if the default host is "localhost", even if the client
<add> // (and daemon as this is local) is not physically on a network, and the DNS
<add> // cache is flushed (ipconfig /flushdns), then the client will pause for
<add> // exactly one second when connecting to the daemon for calls. For example
<add> // using docker run windowsservercore cmd, the CLI will send a create followed
<add> // by an attach. You see the delay between the attach finishing and the attach
<add> // being seen by the daemon.
<add> //
<add> // Here's some daemon debug logs with additional debug spew put in. The
<add> // AfterWriteJSON log is the very last thing the daemon does as part of the
<add> // create call. The POST /attach is the second CLI call. Notice the second
<add> // time gap.
<add> //
<add> // time="2015-11-06T13:38:37.259627400-08:00" level=debug msg="After createRootfs"
<add> // time="2015-11-06T13:38:37.263626300-08:00" level=debug msg="After setHostConfig"
<add> // time="2015-11-06T13:38:37.267631200-08:00" level=debug msg="before createContainerPl...."
<add> // time="2015-11-06T13:38:37.271629500-08:00" level=debug msg=ToDiskLocking....
<add> // time="2015-11-06T13:38:37.275643200-08:00" level=debug msg="loggin event...."
<add> // time="2015-11-06T13:38:37.277627600-08:00" level=debug msg="logged event...."
<add> // time="2015-11-06T13:38:37.279631800-08:00" level=debug msg="In defer func"
<add> // time="2015-11-06T13:38:37.282628100-08:00" level=debug msg="After daemon.create"
<add> // time="2015-11-06T13:38:37.286651700-08:00" level=debug msg="return 2"
<add> // time="2015-11-06T13:38:37.289629500-08:00" level=debug msg="Returned from daemon.ContainerCreate"
<add> // time="2015-11-06T13:38:37.311629100-08:00" level=debug msg="After WriteJSON"
<add> // ... 1 second gap here....
<add> // time="2015-11-06T13:38:38.317866200-08:00" level=debug msg="Calling POST /v1.22/containers/984758282b842f779e805664b2c95d563adc9a979c8a3973e68c807843ee4757/attach"
<add> // time="2015-11-06T13:38:38.326882500-08:00" level=info msg="POST /v1.22/containers/984758282b842f779e805664b2c95d563adc9a979c8a3973e68c807843ee4757/attach?stderr=1&stdin=1&stdout=1&stream=1"
<add> //
<add> // We suspect this is either a bug introduced in GOLang 1.5.1, or that a change
<add> // in GOLang 1.5.1 (from 1.4.3) is exposing a bug in Windows. In theory,
<add> // the Windows networking stack is supposed to resolve "localhost" internally,
<add> // without hitting DNS, or even reading the hosts file (which is why localhost
<add> // is commented out in the hosts file on Windows).
<add> //
<add> // We have validated that working around this using the actual IPv4 localhost
<add> // address does not cause the delay.
<add> //
<add> // This does not occur with the docker client built with 1.4.3 on the same
<add> // Windows build, regardless of whether the daemon is built using 1.5.1
<add> // or 1.4.3. It does not occur on Linux. We also verified we see the same thing
<add> // on a cross-compiled Windows binary (from Linux).
<add> //
<add> // Final note: This is a mitigation, not a 'real' fix. It is still susceptible
<add> // to the delay if a user were to do 'docker run -H=tcp://localhost:2375...'
<add> // explicitly.
<add>
<add> // DefaultHTTPHost Default HTTP Host used if only port is provided to -H flag e.g. dockerd -H tcp://:8080
<add> DefaultHTTPHost = "127.0.0.1"
<add>
<add> // DefaultHost constant defines the default host string used by docker on Windows
<add> DefaultHost = "npipe://" + DefaultNamedPipe
<add>)
<ide><path>opts/opts_unix.go
<del>// +build !windows
<del>
<del>package opts // import "github.com/docker/docker/opts"
<del>
<del>// DefaultHTTPHost Default HTTP Host used if only port is provided to -H flag e.g. dockerd -H tcp://:8080
<del>const DefaultHTTPHost = "localhost"
<ide><path>opts/opts_windows.go
<del>package opts // import "github.com/docker/docker/opts"
<del>
<del>// TODO Windows. Identify bug in GOLang 1.5.1+ and/or Windows Server 2016 TP5.
<del>//
<del>// On Windows, this mitigates a problem with the default options of running
<del>// a docker client against a local docker daemon on TP5.
<del>//
<del>// What was found that if the default host is "localhost", even if the client
<del>// (and daemon as this is local) is not physically on a network, and the DNS
<del>// cache is flushed (ipconfig /flushdns), then the client will pause for
<del>// exactly one second when connecting to the daemon for calls. For example
<del>// using docker run windowsservercore cmd, the CLI will send a create followed
<del>// by an attach. You see the delay between the attach finishing and the attach
<del>// being seen by the daemon.
<del>//
<del>// Here's some daemon debug logs with additional debug spew put in. The
<del>// AfterWriteJSON log is the very last thing the daemon does as part of the
<del>// create call. The POST /attach is the second CLI call. Notice the second
<del>// time gap.
<del>//
<del>// time="2015-11-06T13:38:37.259627400-08:00" level=debug msg="After createRootfs"
<del>// time="2015-11-06T13:38:37.263626300-08:00" level=debug msg="After setHostConfig"
<del>// time="2015-11-06T13:38:37.267631200-08:00" level=debug msg="before createContainerPl...."
<del>// time="2015-11-06T13:38:37.271629500-08:00" level=debug msg=ToDiskLocking....
<del>// time="2015-11-06T13:38:37.275643200-08:00" level=debug msg="loggin event...."
<del>// time="2015-11-06T13:38:37.277627600-08:00" level=debug msg="logged event...."
<del>// time="2015-11-06T13:38:37.279631800-08:00" level=debug msg="In defer func"
<del>// time="2015-11-06T13:38:37.282628100-08:00" level=debug msg="After daemon.create"
<del>// time="2015-11-06T13:38:37.286651700-08:00" level=debug msg="return 2"
<del>// time="2015-11-06T13:38:37.289629500-08:00" level=debug msg="Returned from daemon.ContainerCreate"
<del>// time="2015-11-06T13:38:37.311629100-08:00" level=debug msg="After WriteJSON"
<del>// ... 1 second gap here....
<del>// time="2015-11-06T13:38:38.317866200-08:00" level=debug msg="Calling POST /v1.22/containers/984758282b842f779e805664b2c95d563adc9a979c8a3973e68c807843ee4757/attach"
<del>// time="2015-11-06T13:38:38.326882500-08:00" level=info msg="POST /v1.22/containers/984758282b842f779e805664b2c95d563adc9a979c8a3973e68c807843ee4757/attach?stderr=1&stdin=1&stdout=1&stream=1"
<del>//
<del>// We suspect this is either a bug introduced in GOLang 1.5.1, or that a change
<del>// in GOLang 1.5.1 (from 1.4.3) is exposing a bug in Windows. In theory,
<del>// the Windows networking stack is supposed to resolve "localhost" internally,
<del>// without hitting DNS, or even reading the hosts file (which is why localhost
<del>// is commented out in the hosts file on Windows).
<del>//
<del>// We have validated that working around this using the actual IPv4 localhost
<del>// address does not cause the delay.
<del>//
<del>// This does not occur with the docker client built with 1.4.3 on the same
<del>// Windows build, regardless of whether the daemon is built using 1.5.1
<del>// or 1.4.3. It does not occur on Linux. We also verified we see the same thing
<del>// on a cross-compiled Windows binary (from Linux).
<del>//
<del>// Final note: This is a mitigation, not a 'real' fix. It is still susceptible
<del>// to the delay if a user were to do 'docker run -H=tcp://localhost:2375...'
<del>// explicitly.
<del>
<del>// DefaultHTTPHost Default HTTP Host used if only port is provided to -H flag e.g. dockerd -H tcp://:8080
<del>const DefaultHTTPHost = "127.0.0.1" | 4 |
PHP | PHP | fix syntax error in error class | 95528adab5e4f409d20f81c935e8ffdfee263f8d | <ide><path>application/routes.php
<ide>
<ide> 'GET /' => function()
<ide> {
<add> $this->
<ide> return View::make('home/index');
<ide> },
<ide>
<ide><path>system/error.php
<ide> public static function handle($e)
<ide> ->bind('message', $message)
<ide> ->bind('file', $file)
<ide> ->bind('line', $e->getLine())
<del> ->bind('trace', $e->getTraceAsString())
<add> ->bind('trace', $e->getTraceAsString());
<ide>
<ide> Response::make($view, 500)->send();
<ide> } | 2 |
Python | Python | use textwrap.dedent in f2py tests | 1f3a43d9450189088ba8224b18d60b0efa8cbd81 | <ide><path>numpy/f2py/tests/test_callback.py
<ide> def test_all(self, name):
<ide>
<ide> @pytest.mark.slow
<ide> def test_docstring(self):
<del> expected = """
<add> expected = textwrap.dedent("""\
<ide> a = t(fun,[fun_extra_args])
<ide>
<ide> Wrapper for ``t``.
<ide> def test_docstring(self):
<ide> def fun(): return a
<ide> Return objects:
<ide> a : int
<del> """
<del> assert_equal(self.module.t.__doc__, textwrap.dedent(expected).lstrip())
<add> """)
<add> assert_equal(self.module.t.__doc__, expected)
<ide>
<ide> def check_function(self, name):
<ide> t = getattr(self.module, name)
<ide><path>numpy/f2py/tests/test_mixed.py
<ide> def test_all(self):
<ide>
<ide> @pytest.mark.slow
<ide> def test_docstring(self):
<del> expected = """
<add> expected = textwrap.dedent("""\
<ide> a = bar11()
<ide>
<ide> Wrapper for ``bar11``.
<ide>
<ide> Returns
<ide> -------
<ide> a : int
<del> """
<del> assert_equal(self.module.bar11.__doc__,
<del> textwrap.dedent(expected).lstrip())
<add> """)
<add> assert_equal(self.module.bar11.__doc__, expected)
<ide><path>numpy/f2py/tests/util.py
<ide> def _get_compiler_status():
<ide>
<ide> # XXX: this is really ugly. But I don't know how to invoke Distutils
<ide> # in a safer way...
<del> code = """
<del>import os
<del>import sys
<del>sys.path = %(syspath)s
<del>
<del>def configuration(parent_name='',top_path=None):
<del> global config
<del> from numpy.distutils.misc_util import Configuration
<del> config = Configuration('', parent_name, top_path)
<del> return config
<del>
<del>from numpy.distutils.core import setup
<del>setup(configuration=configuration)
<del>
<del>config_cmd = config.get_config_cmd()
<del>have_c = config_cmd.try_compile('void foo() {}')
<del>print('COMPILERS:%%d,%%d,%%d' %% (have_c,
<del> config.have_f77c(),
<del> config.have_f90c()))
<del>sys.exit(99)
<del>"""
<add> code = textwrap.dedent("""\
<add> import os
<add> import sys
<add> sys.path = %(syspath)s
<add>
<add> def configuration(parent_name='',top_path=None):
<add> global config
<add> from numpy.distutils.misc_util import Configuration
<add> config = Configuration('', parent_name, top_path)
<add> return config
<add>
<add> from numpy.distutils.core import setup
<add> setup(configuration=configuration)
<add>
<add> config_cmd = config.get_config_cmd()
<add> have_c = config_cmd.try_compile('void foo() {}')
<add> print('COMPILERS:%%d,%%d,%%d' %% (have_c,
<add> config.have_f77c(),
<add> config.have_f90c()))
<add> sys.exit(99)
<add> """)
<ide> code = code % dict(syspath=repr(sys.path))
<ide>
<ide> with temppath(suffix='.py') as script:
<ide> def build_module_distutils(source_files, config_code, module_name, **kw):
<ide> # Build script
<ide> config_code = textwrap.dedent(config_code).replace("\n", "\n ")
<ide>
<del> code = """\
<del>import os
<del>import sys
<del>sys.path = %(syspath)s
<del>
<del>def configuration(parent_name='',top_path=None):
<del> from numpy.distutils.misc_util import Configuration
<del> config = Configuration('', parent_name, top_path)
<del> %(config_code)s
<del> return config
<del>
<del>if __name__ == "__main__":
<del> from numpy.distutils.core import setup
<del> setup(configuration=configuration)
<del>""" % dict(config_code=config_code, syspath=repr(sys.path))
<add> code = textwrap.dedent("""\
<add> import os
<add> import sys
<add> sys.path = %(syspath)s
<add>
<add> def configuration(parent_name='',top_path=None):
<add> from numpy.distutils.misc_util import Configuration
<add> config = Configuration('', parent_name, top_path)
<add> %(config_code)s
<add> return config
<add>
<add> if __name__ == "__main__":
<add> from numpy.distutils.core import setup
<add> setup(configuration=configuration)
<add> """) % dict(config_code=config_code, syspath=repr(sys.path))
<ide>
<ide> script = os.path.join(d, get_temp_module_name() + '.py')
<ide> dst_sources.append(script) | 3 |
Python | Python | break long lines in numpy/distutils/log.py | 79106925b1377c6b781fabb61daf505a35564c21 | <ide><path>numpy/distutils/log.py
<ide> from distutils.log import _global_log
<ide>
<ide> if sys.version_info[0] < 3:
<del> from .misc_util import red_text, default_text, cyan_text, green_text, is_sequence, is_string
<add> from .misc_util import (red_text, default_text, cyan_text, green_text,
<add> is_sequence, is_string)
<ide> else:
<del> from numpy.distutils.misc_util import red_text, default_text, cyan_text, green_text, is_sequence, is_string
<add> from numpy.distutils.misc_util import (red_text, default_text, cyan_text,
<add> green_text, is_sequence, is_string)
<ide>
<ide>
<ide> def _fix_args(args,flag=1):
<ide> def _fix_args(args,flag=1):
<ide> return tuple([_fix_args(a,flag=0) for a in args])
<ide> return args
<ide>
<add>
<ide> class Log(old_Log):
<ide> def _log(self, level, msg, args):
<ide> if level >= self.threshold:
<ide> def _log(self, level, msg, args):
<ide> sys.stdout.flush()
<ide>
<ide> def good(self, msg, *args):
<del> """If we'd log WARN messages, log this message as a 'nice' anti-warn
<add> """
<add> If we log WARN messages, log this message as a 'nice' anti-warn
<ide> message.
<add>
<ide> """
<ide> if WARN >= self.threshold:
<ide> if args:
<ide> print(green_text(msg % _fix_args(args)))
<ide> else:
<ide> print(green_text(msg))
<ide> sys.stdout.flush()
<add>
<add>
<ide> _global_log.__class__ = Log
<ide>
<ide> good = _global_log.good
<ide> def set_threshold(level, force=False):
<ide> # likely a good reason why we're running at this level.
<ide> _global_log.threshold = level
<ide> if level <= DEBUG:
<del> info('set_threshold: setting threshold to DEBUG level, it can be changed only with force argument')
<add> info('set_threshold: setting threshold to DEBUG level,'
<add> ' it can be changed only with force argument')
<ide> else:
<del> info('set_threshold: not changing threshold from DEBUG level %s to %s' % (prev_level,level))
<add> info('set_threshold: not changing threshold from DEBUG level'
<add> ' %s to %s' % (prev_level, level))
<ide> return prev_level
<ide>
<add>
<ide> def set_verbosity(v, force=False):
<ide> prev_level = _global_log.threshold
<ide> if v < 0:
<ide> def set_verbosity(v, force=False):
<ide> set_threshold(DEBUG, force)
<ide> return {FATAL:-2,ERROR:-1,WARN:0,INFO:1,DEBUG:2}.get(prev_level,1)
<ide>
<add>
<ide> _global_color_map = {
<ide> DEBUG:cyan_text,
<ide> INFO:default_text, | 1 |
PHP | PHP | apply fixes from styleci | f99752151ec05f3eb572f5bc00b2fdcbed45a51a | <ide><path>src/Illuminate/Validation/Concerns/ValidatesAttributes.php
<ide> public function validateAccepted($attribute, $value)
<ide> */
<ide> public function validateAcceptedIf($attribute, $value, $parameters)
<ide> {
<del>
<ide> $acceptable = ['yes', 'on', '1', 1, true, 'true'];
<ide>
<ide> $this->requireParameterCount(2, $parameters, 'accepted_if');
<ide><path>tests/Validation/ValidationValidatorTest.php
<ide> public function testValidateAccepted()
<ide>
<ide> public function testValidateAcceptedIf()
<ide> {
<del>
<ide> $trans = $this->getIlluminateArrayTranslator();
<ide> $v = new Validator($trans, ['foo' => 'no', 'bar' => 'aaa'], ['foo' => 'accepted_if:bar,aaa']);
<ide> $this->assertFalse($v->passes());
<ide> public function testValidateAcceptedIf()
<ide> $this->assertTrue($v->passes());
<ide>
<ide> $v = new Validator($trans, ['foo' => 'true', 'bar' => 'aaa'], ['foo' => 'accepted_if:bar,aaa']);
<del> $this->assertTrue($v->passes());
<add> $this->assertTrue($v->passes());
<ide> }
<ide>
<ide> public function testValidateEndsWith() | 2 |
Javascript | Javascript | use nonnumericonlyhash function for contenthash | f1d329cc0e5241327575d3b3d6f491ff95773c8b | <ide><path>lib/asset/AssetGenerator.js
<ide> const Generator = require("../Generator");
<ide> const RuntimeGlobals = require("../RuntimeGlobals");
<ide> const createHash = require("../util/createHash");
<ide> const { makePathsRelative } = require("../util/identifier");
<add>const nonNumericOnlyHash = require("../util/nonNumericOnlyHash");
<ide>
<ide> /** @typedef {import("webpack-sources").Source} Source */
<ide> /** @typedef {import("../../declarations/WebpackOptions").AssetGeneratorOptions} AssetGeneratorOptions */
<ide> class AssetGenerator extends Generator {
<ide> const fullHash = /** @type {string} */ (
<ide> hash.digest(runtimeTemplate.outputOptions.hashDigest)
<ide> );
<del> const contentHash = fullHash.slice(
<del> 0,
<add> const contentHash = nonNumericOnlyHash(
<add> fullHash,
<ide> runtimeTemplate.outputOptions.hashDigestLength
<ide> );
<ide> module.buildInfo.fullContentHash = fullHash;
<ide><path>lib/css/CssModulesPlugin.js
<ide> const { compareModulesByIdentifier } = require("../util/comparators");
<ide> const createSchemaValidation = require("../util/create-schema-validation");
<ide> const createHash = require("../util/createHash");
<ide> const memoize = require("../util/memoize");
<add>const nonNumericOnlyHash = require("../util/nonNumericOnlyHash");
<ide> const CssExportsGenerator = require("./CssExportsGenerator");
<ide> const CssGenerator = require("./CssGenerator");
<ide> const CssParser = require("./CssParser");
<ide> class CssModulesPlugin {
<ide> hash.update(chunkGraph.getModuleHash(module, chunk.runtime));
<ide> }
<ide> const digest = /** @type {string} */ (hash.digest(hashDigest));
<del> chunk.contentHash.css = digest.substr(0, hashDigestLength);
<add> chunk.contentHash.css = nonNumericOnlyHash(digest, hashDigestLength);
<ide> });
<ide> compilation.hooks.renderManifest.tap(plugin, (result, options) => {
<ide> const { chunkGraph } = compilation;
<ide><path>lib/javascript/JavascriptModulesPlugin.js
<ide> const { last, someInIterable } = require("../util/IterableHelpers");
<ide> const StringXor = require("../util/StringXor");
<ide> const { compareModulesByIdentifier } = require("../util/comparators");
<ide> const createHash = require("../util/createHash");
<add>const nonNumericOnlyHash = require("../util/nonNumericOnlyHash");
<ide> const { intersectRuntime } = require("../util/runtime");
<ide> const JavascriptGenerator = require("./JavascriptGenerator");
<ide> const JavascriptParser = require("./JavascriptParser");
<ide> class JavascriptModulesPlugin {
<ide> xor.updateHash(hash);
<ide> }
<ide> const digest = /** @type {string} */ (hash.digest(hashDigest));
<del> chunk.contentHash.javascript = digest.substr(0, hashDigestLength);
<add> chunk.contentHash.javascript = nonNumericOnlyHash(
<add> digest,
<add> hashDigestLength
<add> );
<ide> });
<ide> compilation.hooks.additionalTreeRuntimeRequirements.tap(
<ide> "JavascriptModulesPlugin",
<ide><path>lib/util/nonNumericOnlyHash.js
<add>/*
<add> MIT License http://www.opensource.org/licenses/mit-license.php
<add> Author Ivan Kopeykin @vankop
<add>*/
<add>
<add>"use strict";
<add>
<add>const A_CODE = "a".charCodeAt(0);
<add>
<add>/**
<add> * @param {string} hash hash
<add> * @param {number} hashLength hash length
<add> * @returns {string} returns hash that has at least one non numeric char
<add> */
<add>module.exports = (hash, hashLength) => {
<add> if (hashLength < 1) return "";
<add> const slice = hash.slice(0, hashLength);
<add> if (slice.match(/[^\d]/)) return slice;
<add> return `${String.fromCharCode(A_CODE + parseInt(hash[0], 10))}${slice.slice(
<add> 1
<add> )}`;
<add>};
<ide><path>test/nonNumericOnlyHash.unittest.js
<add>"use strict";
<add>
<add>const nonNumericOnlyHash = require("../lib/util/nonNumericOnlyHash");
<add>
<add>it("hashLength=0", () => {
<add> expect(nonNumericOnlyHash("111", 0)).toBe("");
<add>});
<add>
<add>it("abc", () => {
<add> expect(nonNumericOnlyHash("abc", 10)).toBe("abc");
<add>});
<add>
<add>it("abc1", () => {
<add> expect(nonNumericOnlyHash("abc1", 3)).toBe("abc");
<add>});
<add>
<add>it("ab11", () => {
<add> expect(nonNumericOnlyHash("ab11", 3)).toBe("ab1");
<add>});
<add>
<add>it("0111", () => {
<add> expect(nonNumericOnlyHash("0111", 3)).toBe("a11");
<add>});
<add>
<add>it("911a", () => {
<add> expect(nonNumericOnlyHash("911a", 3)).toBe("j11");
<add>}); | 5 |
Ruby | Ruby | fix some accidental nils | 03e9a6417d52e2783a8a82e733f6e9ef000ece52 | <ide><path>actionpack/lib/action_view/lookup_context.rb
<ide> def self.register_detail(name, options = {}, &block)
<ide> Accessors.send :define_method, :"default_#{name}", &block
<ide> Accessors.module_eval <<-METHOD, __FILE__, __LINE__ + 1
<ide> def #{name}
<del> @details[:#{name}]
<add> @details.fetch(:#{name}, [])
<ide> end
<ide>
<ide> def #{name}=(value)
<ide><path>actionpack/lib/action_view/renderer/template_renderer.rb
<ide> def render(context, options)
<ide>
<ide> # Determine the template to be rendered using the given options.
<ide> def determine_template(options) #:nodoc:
<del> keys = options[:locals].try(:keys) || []
<add> keys = options.fetch(:locals, {}).keys
<ide>
<ide> if options.key?(:text)
<del> Template::Text.new(options[:text], formats.try(:first))
<add> Template::Text.new(options[:text], formats.first)
<ide> elsif options.key?(:file)
<ide> with_fallbacks { find_template(options[:file], nil, false, keys, @details) }
<ide> elsif options.key?(:inline) | 2 |
Ruby | Ruby | add more test cases | eb933f0154f5e10a794552086cf18d1b29b90081 | <ide><path>activerecord/test/cases/relation_scoping_test.rb
<ide> def test_reverse_order_with_arel_node
<ide> assert_equal Developer.order("id DESC").to_a.reverse, Developer.order(Developer.arel_table[:id].desc).reverse_order
<ide> end
<ide>
<add> def test_reverse_order_with_multiple_arel_nodes
<add> assert_equal Developer.order("id DESC").order("name DESC").to_a.reverse, Developer.order(Developer.arel_table[:id].desc).order(Developer.arel_table[:name].desc).reverse_order
<add> end
<add>
<add> def test_reverse_order_with_arel_nodes_and_strings
<add> assert_equal Developer.order("id DESC").order("name DESC").to_a.reverse, Developer.order("id DESC").order(Developer.arel_table[:name].desc).reverse_order
<add> end
<add>
<ide> def test_double_reverse_order_produces_original_order
<ide> assert_equal Developer.order("name DESC"), Developer.order("name DESC").reverse_order.reverse_order
<ide> end | 1 |
Mixed | Python | rewrite parts of vector and matrix | fe5c711ce68cb1d410d13d8c8a02ee7bfd49b1d3 | <ide><path>knapsack/README.md
<ide> The knapsack problem has been studied for more than a century, with early works
<ide> ## Documentation
<ide>
<ide> This module uses docstrings to enable the use of Python's in-built `help(...)` function.
<del>For instance, try `help(Vector)`, `help(unitBasisVector)`, and `help(CLASSNAME.METHODNAME)`.
<add>For instance, try `help(Vector)`, `help(unit_basis_vector)`, and `help(CLASSNAME.METHODNAME)`.
<ide>
<ide> ---
<ide>
<ide><path>linear_algebra/README.md
<ide> This module contains classes and functions for doing linear algebra.
<ide> -
<ide> - This class represents a vector of arbitrary size and related operations.
<ide>
<del> **Overview about the methods:**
<add> **Overview of the methods:**
<ide>
<del> - constructor(components : list) : init the vector
<del> - set(components : list) : changes the vector components.
<add> - constructor(components) : init the vector
<add> - set(components) : changes the vector components.
<ide> - \_\_str\_\_() : toString method
<del> - component(i : int): gets the i-th component (start by 0)
<add> - component(i): gets the i-th component (0-indexed)
<ide> - \_\_len\_\_() : gets the size / length of the vector (number of components)
<del> - euclidLength() : returns the eulidean length of the vector.
<add> - euclidean_length() : returns the eulidean length of the vector
<ide> - operator + : vector addition
<ide> - operator - : vector subtraction
<ide> - operator * : scalar multiplication and dot product
<del> - copy() : copies this vector and returns it.
<del> - changeComponent(pos,value) : changes the specified component.
<add> - copy() : copies this vector and returns it
<add> - change_component(pos,value) : changes the specified component
<ide>
<del>- function zeroVector(dimension)
<add>- function zero_vector(dimension)
<ide> - returns a zero vector of 'dimension'
<del>- function unitBasisVector(dimension,pos)
<del> - returns a unit basis vector with a One at index 'pos' (indexing at 0)
<del>- function axpy(scalar,vector1,vector2)
<add>- function unit_basis_vector(dimension, pos)
<add> - returns a unit basis vector with a one at index 'pos' (0-indexed)
<add>- function axpy(scalar, vector1, vector2)
<ide> - computes the axpy operation
<del>- function randomVector(N,a,b)
<del> - returns a random vector of size N, with random integer components between 'a' and 'b'.
<add>- function random_vector(N, a, b)
<add> - returns a random vector of size N, with random integer components between 'a' and 'b' inclusive
<ide>
<ide> ### class Matrix
<ide> -
<ide> - This class represents a matrix of arbitrary size and operations on it.
<ide>
<del> **Overview about the methods:**
<add> **Overview of the methods:**
<ide>
<ide> - \_\_str\_\_() : returns a string representation
<ide> - operator * : implements the matrix vector multiplication
<ide> implements the matrix-scalar multiplication.
<del> - changeComponent(x,y,value) : changes the specified component.
<del> - component(x,y) : returns the specified component.
<add> - change_component(x, y, value) : changes the specified component.
<add> - component(x, y) : returns the specified component.
<ide> - width() : returns the width of the matrix
<ide> - height() : returns the height of the matrix
<del> - determinate() : returns the determinate of the matrix if it is square
<add> - determinant() : returns the determinant of the matrix if it is square
<ide> - operator + : implements the matrix-addition.
<del> - operator - _ implements the matrix-subtraction
<add> - operator - : implements the matrix-subtraction
<ide>
<del>- function squareZeroMatrix(N)
<add>- function square_zero_matrix(N)
<ide> - returns a square zero-matrix of dimension NxN
<del>- function randomMatrix(W,H,a,b)
<del> - returns a random matrix WxH with integer components between 'a' and 'b'
<add>- function random_matrix(W, H, a, b)
<add> - returns a random matrix WxH with integer components between 'a' and 'b' inclusive
<ide> ---
<ide>
<ide> ## Documentation
<ide>
<ide> This module uses docstrings to enable the use of Python's in-built `help(...)` function.
<del>For instance, try `help(Vector)`, `help(unitBasisVector)`, and `help(CLASSNAME.METHODNAME)`.
<add>For instance, try `help(Vector)`, `help(unit_basis_vector)`, and `help(CLASSNAME.METHODNAME)`.
<ide>
<ide> ---
<ide>
<ide><path>linear_algebra/src/lib.py
<ide> Overview:
<ide>
<ide> - class Vector
<del>- function zeroVector(dimension)
<del>- function unitBasisVector(dimension,pos)
<del>- function axpy(scalar,vector1,vector2)
<del>- function randomVector(N,a,b)
<add>- function zero_vector(dimension)
<add>- function unit_basis_vector(dimension, pos)
<add>- function axpy(scalar, vector1, vector2)
<add>- function random_vector(N, a, b)
<ide> - class Matrix
<del>- function squareZeroMatrix(N)
<del>- function randomMatrix(W,H,a,b)
<add>- function square_zero_matrix(N)
<add>- function random_matrix(W, H, a, b)
<ide> """
<ide> from __future__ import annotations
<ide>
<ide> class Vector:
<ide> This class represents a vector of arbitrary size.
<ide> You need to give the vector components.
<ide>
<del> Overview about the methods:
<del>
<del> constructor(components : list) : init the vector
<del> set(components : list) : changes the vector components.
<del> __str__() : toString method
<del> component(i : int): gets the i-th component (start by 0)
<del> __len__() : gets the size of the vector (number of components)
<del> euclidLength() : returns the euclidean length of the vector.
<del> operator + : vector addition
<del> operator - : vector subtraction
<del> operator * : scalar multiplication and dot product
<del> copy() : copies this vector and returns it.
<del> changeComponent(pos,value) : changes the specified component.
<del> TODO: compare-operator
<add> Overview of the methods:
<add>
<add> __init__(components: Collection[float] | None): init the vector
<add> __len__(): gets the size of the vector (number of components)
<add> __str__(): returns a string representation
<add> __add__(other: Vector): vector addition
<add> __sub__(other: Vector): vector subtraction
<add> __mul__(other: float): scalar multiplication
<add> __mul__(other: Vector): dot product
<add> set(components: Collection[float]): changes the vector components
<add> copy(): copies this vector and returns it
<add> component(i): gets the i-th component (0-indexed)
<add> change_component(pos: int, value: float): changes specified component
<add> euclidean_length(): returns the euclidean length of the vector
<add> magnitude(): returns the magnitude of the vector
<add> angle(other: Vector, deg: bool): returns the angle between two vectors
<add> TODO: compare-operator
<ide> """
<ide>
<ide> def __init__(self, components: Collection[float] | None = None) -> None:
<ide> def __init__(self, components: Collection[float] | None = None) -> None:
<ide> components = []
<ide> self.__components = list(components)
<ide>
<del> def set(self, components: Collection[float]) -> None:
<del> """
<del> input: new components
<del> changes the components of the vector.
<del> replace the components with newer one.
<del> """
<del> if len(components) > 0:
<del> self.__components = list(components)
<del> else:
<del> raise Exception("please give any vector")
<del>
<del> def __str__(self) -> str:
<del> """
<del> returns a string representation of the vector
<del> """
<del> return "(" + ",".join(map(str, self.__components)) + ")"
<del>
<del> def component(self, i: int) -> float:
<del> """
<del> input: index (start at 0)
<del> output: the i-th component of the vector.
<del> """
<del> if type(i) is int and -len(self.__components) <= i < len(self.__components):
<del> return self.__components[i]
<del> else:
<del> raise Exception("index out of range")
<del>
<ide> def __len__(self) -> int:
<ide> """
<ide> returns the size of the vector
<ide> """
<ide> return len(self.__components)
<ide>
<del> def euclidLength(self) -> float:
<add> def __str__(self) -> str:
<ide> """
<del> returns the euclidean length of the vector
<add> returns a string representation of the vector
<ide> """
<del> summe: float = 0
<del> for c in self.__components:
<del> summe += c ** 2
<del> return math.sqrt(summe)
<add> return "(" + ",".join(map(str, self.__components)) + ")"
<ide>
<ide> def __add__(self, other: Vector) -> Vector:
<ide> """
<ide> def __mul__(self, other: float | Vector) -> float | Vector:
<ide> if isinstance(other, float) or isinstance(other, int):
<ide> ans = [c * other for c in self.__components]
<ide> return Vector(ans)
<del> elif isinstance(other, Vector) and (len(self) == len(other)):
<add> elif isinstance(other, Vector) and len(self) == len(other):
<ide> size = len(self)
<del> summe: float = 0
<del> for i in range(size):
<del> summe += self.__components[i] * other.component(i)
<del> return summe
<add> prods = [self.__components[i] * other.component(i) for i in range(size)]
<add> return sum(prods)
<ide> else: # error case
<ide> raise Exception("invalid operand!")
<ide>
<add> def set(self, components: Collection[float]) -> None:
<add> """
<add> input: new components
<add> changes the components of the vector.
<add> replaces the components with newer one.
<add> """
<add> if len(components) > 0:
<add> self.__components = list(components)
<add> else:
<add> raise Exception("please give any vector")
<add>
<add> def copy(self) -> Vector:
<add> """
<add> copies this vector and returns it.
<add> """
<add> return Vector(self.__components)
<add>
<add> def component(self, i: int) -> float:
<add> """
<add> input: index (0-indexed)
<add> output: the i-th component of the vector.
<add> """
<add> if type(i) is int and -len(self.__components) <= i < len(self.__components):
<add> return self.__components[i]
<add> else:
<add> raise Exception("index out of range")
<add>
<add> def change_component(self, pos: int, value: float) -> None:
<add> """
<add> input: an index (pos) and a value
<add> changes the specified component (pos) with the
<add> 'value'
<add> """
<add> # precondition
<add> assert -len(self.__components) <= pos < len(self.__components)
<add> self.__components[pos] = value
<add>
<add> def euclidean_length(self) -> float:
<add> """
<add> returns the euclidean length of the vector
<add> """
<add> squares = [c ** 2 for c in self.__components]
<add> return math.sqrt(sum(squares))
<add>
<ide> def magnitude(self) -> float:
<ide> """
<ide> Magnitude of a Vector
<ide> def magnitude(self) -> float:
<ide> 5.385164807134504
<ide>
<ide> """
<del> return sum([i ** 2 for i in self.__components]) ** (1 / 2)
<add> squares = [c ** 2 for c in self.__components]
<add> return math.sqrt(sum(squares))
<ide>
<ide> def angle(self, other: Vector, deg: bool = False) -> float:
<ide> """
<ide> def angle(self, other: Vector, deg: bool = False) -> float:
<ide> else:
<ide> return math.acos(num / den)
<ide>
<del> def copy(self) -> Vector:
<del> """
<del> copies this vector and returns it.
<del> """
<del> return Vector(self.__components)
<del>
<del> def changeComponent(self, pos: int, value: float) -> None:
<del> """
<del> input: an index (pos) and a value
<del> changes the specified component (pos) with the
<del> 'value'
<del> """
<del> # precondition
<del> assert -len(self.__components) <= pos < len(self.__components)
<del> self.__components[pos] = value
<ide>
<del>
<del>def zeroVector(dimension: int) -> Vector:
<add>def zero_vector(dimension: int) -> Vector:
<ide> """
<ide> returns a zero-vector of size 'dimension'
<ide> """
<ide> def zeroVector(dimension: int) -> Vector:
<ide> return Vector([0] * dimension)
<ide>
<ide>
<del>def unitBasisVector(dimension: int, pos: int) -> Vector:
<add>def unit_basis_vector(dimension: int, pos: int) -> Vector:
<ide> """
<ide> returns a unit basis vector with a One
<ide> at index 'pos' (indexing at 0)
<ide> def axpy(scalar: float, x: Vector, y: Vector) -> Vector:
<ide> # precondition
<ide> assert (
<ide> isinstance(x, Vector)
<del> and (isinstance(y, Vector))
<add> and isinstance(y, Vector)
<ide> and (isinstance(scalar, int) or isinstance(scalar, float))
<ide> )
<ide> return x * scalar + y
<ide>
<ide>
<del>def randomVector(N: int, a: int, b: int) -> Vector:
<add>def random_vector(n: int, a: int, b: int) -> Vector:
<ide> """
<ide> input: size (N) of the vector.
<ide> random range (a,b)
<ide> output: returns a random vector of size N, with
<ide> random integer components between 'a' and 'b'.
<ide> """
<ide> random.seed(None)
<del> ans = [random.randint(a, b) for _ in range(N)]
<add> ans = [random.randint(a, b) for _ in range(n)]
<ide> return Vector(ans)
<ide>
<ide>
<ide> class Matrix:
<ide> """
<ide> class: Matrix
<del> This class represents a arbitrary matrix.
<del>
<del> Overview about the methods:
<del>
<del> __str__() : returns a string representation
<del> operator * : implements the matrix vector multiplication
<del> implements the matrix-scalar multiplication.
<del> changeComponent(x,y,value) : changes the specified component.
<del> component(x,y) : returns the specified component.
<del> width() : returns the width of the matrix
<del> height() : returns the height of the matrix
<del> operator + : implements the matrix-addition.
<del> operator - _ implements the matrix-subtraction
<add> This class represents an arbitrary matrix.
<add>
<add> Overview of the methods:
<add>
<add> __init__():
<add> __str__(): returns a string representation
<add> __add__(other: Matrix): matrix addition
<add> __sub__(other: Matrix): matrix subtraction
<add> __mul__(other: float): scalar multiplication
<add> __mul__(other: Vector): vector multiplication
<add> height() : returns height
<add> width() : returns width
<add> component(x: int, y: int): returns specified component
<add> change_component(x: int, y: int, value: float): changes specified component
<add> minor(x: int, y: int): returns minor along (x, y)
<add> cofactor(x: int, y: int): returns cofactor along (x, y)
<add> determinant() : returns determinant
<ide> """
<ide>
<ide> def __init__(self, matrix: list[list[float]], w: int, h: int) -> None:
<ide> def __str__(self) -> str:
<ide> ans += str(self.__matrix[i][j]) + "|\n"
<ide> return ans
<ide>
<del> def changeComponent(self, x: int, y: int, value: float) -> None:
<del> """
<del> changes the x-y component of this matrix
<del> """
<del> if 0 <= x < self.__height and 0 <= y < self.__width:
<del> self.__matrix[x][y] = value
<del> else:
<del> raise Exception("changeComponent: indices out of bounds")
<del>
<del> def component(self, x: int, y: int) -> float:
<add> def __add__(self, other: Matrix) -> Matrix:
<ide> """
<del> returns the specified (x,y) component
<add> implements the matrix-addition.
<ide> """
<del> if 0 <= x < self.__height and 0 <= y < self.__width:
<del> return self.__matrix[x][y]
<add> if self.__width == other.width() and self.__height == other.height():
<add> matrix = []
<add> for i in range(self.__height):
<add> row = [
<add> self.__matrix[i][j] + other.component(i, j)
<add> for j in range(self.__width)
<add> ]
<add> matrix.append(row)
<add> return Matrix(matrix, self.__width, self.__height)
<ide> else:
<del> raise Exception("changeComponent: indices out of bounds")
<del>
<del> def width(self) -> int:
<del> """
<del> getter for the width
<del> """
<del> return self.__width
<add> raise Exception("matrix must have the same dimension!")
<ide>
<del> def height(self) -> int:
<add> def __sub__(self, other: Matrix) -> Matrix:
<ide> """
<del> getter for the height
<add> implements the matrix-subtraction.
<ide> """
<del> return self.__height
<del>
<del> def determinate(self) -> float:
<del> """
<del> returns the determinate of an nxn matrix using Laplace expansion
<del> """
<del> if self.__height == self.__width and self.__width >= 2:
<del> total = 0
<del> if self.__width > 2:
<del> for x in range(0, self.__width):
<del> for y in range(0, self.__height):
<del> total += (
<del> self.__matrix[x][y]
<del> * (-1) ** (x + y)
<del> * Matrix(
<del> self.__matrix[0:x] + self.__matrix[x + 1 :],
<del> self.__width - 1,
<del> self.__height - 1,
<del> ).determinate()
<del> )
<del> else:
<del> return (
<del> self.__matrix[0][0] * self.__matrix[1][1]
<del> - self.__matrix[0][1] * self.__matrix[1][0]
<del> )
<del> return total
<add> if self.__width == other.width() and self.__height == other.height():
<add> matrix = []
<add> for i in range(self.__height):
<add> row = [
<add> self.__matrix[i][j] - other.component(i, j)
<add> for j in range(self.__width)
<add> ]
<add> matrix.append(row)
<add> return Matrix(matrix, self.__width, self.__height)
<ide> else:
<del> raise Exception("matrix is not square")
<add> raise Exception("matrices must have the same dimension!")
<ide>
<ide> @overload
<ide> def __mul__(self, other: float) -> Matrix:
<ide> def __mul__(self, other: float | Vector) -> Vector | Matrix:
<ide> implements the matrix-vector multiplication.
<ide> implements the matrix-scalar multiplication
<ide> """
<del> if isinstance(other, Vector): # vector-matrix
<add> if isinstance(other, Vector): # matrix-vector
<ide> if len(other) == self.__width:
<del> ans = zeroVector(self.__height)
<add> ans = zero_vector(self.__height)
<ide> for i in range(self.__height):
<del> summe: float = 0
<del> for j in range(self.__width):
<del> summe += other.component(j) * self.__matrix[i][j]
<del> ans.changeComponent(i, summe)
<del> summe = 0
<add> prods = [
<add> self.__matrix[i][j] * other.component(j)
<add> for j in range(self.__width)
<add> ]
<add> ans.change_component(i, sum(prods))
<ide> return ans
<ide> else:
<ide> raise Exception(
<ide> "vector must have the same size as the "
<del> + "number of columns of the matrix!"
<add> "number of columns of the matrix!"
<ide> )
<ide> elif isinstance(other, int) or isinstance(other, float): # matrix-scalar
<ide> matrix = [
<ide> def __mul__(self, other: float | Vector) -> Vector | Matrix:
<ide> ]
<ide> return Matrix(matrix, self.__width, self.__height)
<ide>
<del> def __add__(self, other: Matrix) -> Matrix:
<add> def height(self) -> int:
<ide> """
<del> implements the matrix-addition.
<add> getter for the height
<ide> """
<del> if self.__width == other.width() and self.__height == other.height():
<del> matrix = []
<del> for i in range(self.__height):
<del> row = []
<del> for j in range(self.__width):
<del> row.append(self.__matrix[i][j] + other.component(i, j))
<del> matrix.append(row)
<del> return Matrix(matrix, self.__width, self.__height)
<add> return self.__height
<add>
<add> def width(self) -> int:
<add> """
<add> getter for the width
<add> """
<add> return self.__width
<add>
<add> def component(self, x: int, y: int) -> float:
<add> """
<add> returns the specified (x,y) component
<add> """
<add> if 0 <= x < self.__height and 0 <= y < self.__width:
<add> return self.__matrix[x][y]
<ide> else:
<del> raise Exception("matrix must have the same dimension!")
<add> raise Exception("change_component: indices out of bounds")
<ide>
<del> def __sub__(self, other: Matrix) -> Matrix:
<add> def change_component(self, x: int, y: int, value: float) -> None:
<ide> """
<del> implements the matrix-subtraction.
<add> changes the x-y component of this matrix
<ide> """
<del> if self.__width == other.width() and self.__height == other.height():
<del> matrix = []
<del> for i in range(self.__height):
<del> row = []
<del> for j in range(self.__width):
<del> row.append(self.__matrix[i][j] - other.component(i, j))
<del> matrix.append(row)
<del> return Matrix(matrix, self.__width, self.__height)
<add> if 0 <= x < self.__height and 0 <= y < self.__width:
<add> self.__matrix[x][y] = value
<ide> else:
<del> raise Exception("matrix must have the same dimension!")
<add> raise Exception("change_component: indices out of bounds")
<add>
<add> def minor(self, x: int, y: int) -> float:
<add> """
<add> returns the minor along (x, y)
<add> """
<add> if self.__height != self.__width:
<add> raise Exception("Matrix is not square")
<add> minor = self.__matrix[:x] + self.__matrix[x + 1 :]
<add> for i in range(len(minor)):
<add> minor[i] = minor[i][:y] + minor[i][y + 1 :]
<add> return Matrix(minor, self.__width - 1, self.__height - 1).determinant()
<add>
<add> def cofactor(self, x: int, y: int) -> float:
<add> """
<add> returns the cofactor (signed minor) along (x, y)
<add> """
<add> if self.__height != self.__width:
<add> raise Exception("Matrix is not square")
<add> if 0 <= x < self.__height and 0 <= y < self.__width:
<add> return (-1) ** (x + y) * self.minor(x, y)
<add> else:
<add> raise Exception("Indices out of bounds")
<add>
<add> def determinant(self) -> float:
<add> """
<add> returns the determinant of an nxn matrix using Laplace expansion
<add> """
<add> if self.__height != self.__width:
<add> raise Exception("Matrix is not square")
<add> if self.__height < 1:
<add> raise Exception("Matrix has no element")
<add> elif self.__height == 1:
<add> return self.__matrix[0][0]
<add> elif self.__height == 2:
<add> return (
<add> self.__matrix[0][0] * self.__matrix[1][1]
<add> - self.__matrix[0][1] * self.__matrix[1][0]
<add> )
<add> else:
<add> cofactor_prods = [
<add> self.__matrix[0][y] * self.cofactor(0, y) for y in range(self.__width)
<add> ]
<add> return sum(cofactor_prods)
<ide>
<ide>
<del>def squareZeroMatrix(N: int) -> Matrix:
<add>def square_zero_matrix(n: int) -> Matrix:
<ide> """
<ide> returns a square zero-matrix of dimension NxN
<ide> """
<del> ans: list[list[float]] = [[0] * N for _ in range(N)]
<del> return Matrix(ans, N, N)
<add> ans: list[list[float]] = [[0] * n for _ in range(n)]
<add> return Matrix(ans, n, n)
<ide>
<ide>
<del>def randomMatrix(W: int, H: int, a: int, b: int) -> Matrix:
<add>def random_matrix(width: int, height: int, a: int, b: int) -> Matrix:
<ide> """
<ide> returns a random matrix WxH with integer components
<ide> between 'a' and 'b'
<ide> """
<ide> random.seed(None)
<ide> matrix: list[list[float]] = [
<del> [random.randint(a, b) for _ in range(W)] for _ in range(H)
<add> [random.randint(a, b) for _ in range(width)] for _ in range(height)
<ide> ]
<del> return Matrix(matrix, W, H)
<add> return Matrix(matrix, width, height)
<ide><path>linear_algebra/src/test_linear_algebra.py
<ide> """
<ide> import unittest
<ide>
<del>from .lib import Matrix, Vector, axpy, squareZeroMatrix, unitBasisVector, zeroVector
<add>from .lib import (
<add> Matrix,
<add> Vector,
<add> axpy,
<add> square_zero_matrix,
<add> unit_basis_vector,
<add> zero_vector,
<add>)
<ide>
<ide>
<ide> class Test(unittest.TestCase):
<ide> def test_component(self) -> None:
<ide> """
<del> test for method component
<add> test for method component()
<ide> """
<ide> x = Vector([1, 2, 3])
<ide> self.assertEqual(x.component(0), 1)
<ide> def test_component(self) -> None:
<ide>
<ide> def test_str(self) -> None:
<ide> """
<del> test for toString() method
<add> test for method toString()
<ide> """
<ide> x = Vector([0, 0, 0, 0, 0, 1])
<ide> self.assertEqual(str(x), "(0,0,0,0,0,1)")
<ide>
<ide> def test_size(self) -> None:
<ide> """
<del> test for size()-method
<add> test for method size()
<ide> """
<ide> x = Vector([1, 2, 3, 4])
<ide> self.assertEqual(len(x), 4)
<ide>
<ide> def test_euclidLength(self) -> None:
<ide> """
<del> test for the eulidean length
<add> test for method euclidean_length()
<ide> """
<ide> x = Vector([1, 2])
<del> self.assertAlmostEqual(x.euclidLength(), 2.236, 3)
<add> self.assertAlmostEqual(x.euclidean_length(), 2.236, 3)
<ide>
<ide> def test_add(self) -> None:
<ide> """
<ide> def test_mul(self) -> None:
<ide> test for * operator
<ide> """
<ide> x = Vector([1, 2, 3])
<del> a = Vector([2, -1, 4]) # for test of dot-product
<add> a = Vector([2, -1, 4]) # for test of dot product
<ide> b = Vector([1, -2, -1])
<ide> self.assertEqual(str(x * 3.0), "(3.0,6.0,9.0)")
<ide> self.assertEqual((a * b), 0)
<ide>
<ide> def test_zeroVector(self) -> None:
<ide> """
<del> test for the global function zeroVector(...)
<add> test for global function zero_vector()
<ide> """
<del> self.assertTrue(str(zeroVector(10)).count("0") == 10)
<add> self.assertTrue(str(zero_vector(10)).count("0") == 10)
<ide>
<ide> def test_unitBasisVector(self) -> None:
<ide> """
<del> test for the global function unitBasisVector(...)
<add> test for global function unit_basis_vector()
<ide> """
<del> self.assertEqual(str(unitBasisVector(3, 1)), "(0,1,0)")
<add> self.assertEqual(str(unit_basis_vector(3, 1)), "(0,1,0)")
<ide>
<ide> def test_axpy(self) -> None:
<ide> """
<del> test for the global function axpy(...) (operation)
<add> test for global function axpy() (operation)
<ide> """
<ide> x = Vector([1, 2, 3])
<ide> y = Vector([1, 0, 1])
<ide> self.assertEqual(str(axpy(2, x, y)), "(3,4,7)")
<ide>
<ide> def test_copy(self) -> None:
<ide> """
<del> test for the copy()-method
<add> test for method copy()
<ide> """
<ide> x = Vector([1, 0, 0, 0, 0, 0])
<ide> y = x.copy()
<ide> self.assertEqual(str(x), str(y))
<ide>
<ide> def test_changeComponent(self) -> None:
<ide> """
<del> test for the changeComponent(...)-method
<add> test for method change_component()
<ide> """
<ide> x = Vector([1, 0, 0])
<del> x.changeComponent(0, 0)
<del> x.changeComponent(1, 1)
<add> x.change_component(0, 0)
<add> x.change_component(1, 1)
<ide> self.assertEqual(str(x), "(0,1,0)")
<ide>
<ide> def test_str_matrix(self) -> None:
<add> """
<add> test for Matrix method str()
<add> """
<ide> A = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]], 3, 3)
<ide> self.assertEqual("|1,2,3|\n|2,4,5|\n|6,7,8|\n", str(A))
<ide>
<del> def test_determinate(self) -> None:
<add> def test_minor(self) -> None:
<add> """
<add> test for Matrix method minor()
<add> """
<add> A = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]], 3, 3)
<add> minors = [[-3, -14, -10], [-5, -10, -5], [-2, -1, 0]]
<add> for x in range(A.height()):
<add> for y in range(A.width()):
<add> self.assertEqual(minors[x][y], A.minor(x, y))
<add>
<add> def test_cofactor(self) -> None:
<ide> """
<del> test for determinate()
<add> test for Matrix method cofactor()
<ide> """
<del> A = Matrix([[1, 1, 4, 5], [3, 3, 3, 2], [5, 1, 9, 0], [9, 7, 7, 9]], 4, 4)
<del> self.assertEqual(-376, A.determinate())
<add> A = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]], 3, 3)
<add> cofactors = [[-3, 14, -10], [5, -10, 5], [-2, 1, 0]]
<add> for x in range(A.height()):
<add> for y in range(A.width()):
<add> self.assertEqual(cofactors[x][y], A.cofactor(x, y))
<add>
<add> def test_determinant(self) -> None:
<add> """
<add> test for Matrix method determinant()
<add> """
<add> A = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]], 3, 3)
<add> self.assertEqual(-5, A.determinant())
<ide>
<ide> def test__mul__matrix(self) -> None:
<add> """
<add> test for Matrix * operator
<add> """
<ide> A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 3, 3)
<ide> x = Vector([1, 2, 3])
<ide> self.assertEqual("(14,32,50)", str(A * x))
<ide> self.assertEqual("|2,4,6|\n|8,10,12|\n|14,16,18|\n", str(A * 2))
<ide>
<del> def test_changeComponent_matrix(self) -> None:
<add> def test_change_component_matrix(self) -> None:
<add> """
<add> test for Matrix method change_component()
<add> """
<ide> A = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]], 3, 3)
<del> A.changeComponent(0, 2, 5)
<add> A.change_component(0, 2, 5)
<ide> self.assertEqual("|1,2,5|\n|2,4,5|\n|6,7,8|\n", str(A))
<ide>
<ide> def test_component_matrix(self) -> None:
<add> """
<add> test for Matrix method component()
<add> """
<ide> A = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]], 3, 3)
<ide> self.assertEqual(7, A.component(2, 1), 0.01)
<ide>
<ide> def test__add__matrix(self) -> None:
<add> """
<add> test for Matrix + operator
<add> """
<ide> A = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]], 3, 3)
<ide> B = Matrix([[1, 2, 7], [2, 4, 5], [6, 7, 10]], 3, 3)
<ide> self.assertEqual("|2,4,10|\n|4,8,10|\n|12,14,18|\n", str(A + B))
<ide>
<ide> def test__sub__matrix(self) -> None:
<add> """
<add> test for Matrix - operator
<add> """
<ide> A = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]], 3, 3)
<ide> B = Matrix([[1, 2, 7], [2, 4, 5], [6, 7, 10]], 3, 3)
<ide> self.assertEqual("|0,0,-4|\n|0,0,0|\n|0,0,-2|\n", str(A - B))
<ide>
<ide> def test_squareZeroMatrix(self) -> None:
<add> """
<add> test for global function square_zero_matrix()
<add> """
<ide> self.assertEqual(
<del> "|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|" + "\n|0,0,0,0,0|\n",
<del> str(squareZeroMatrix(5)),
<add> "|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n",
<add> str(square_zero_matrix(5)),
<ide> )
<ide>
<ide> | 4 |
Go | Go | remove tests for canonicaltarnameforpath | 8b36298d7fa8d906c3528df4cbdee3a8bfa0493a | <ide><path>pkg/archive/archive_unix_test.go
<ide> import (
<ide> "gotest.tools/v3/skip"
<ide> )
<ide>
<del>func TestCanonicalTarNameForPath(t *testing.T) {
<del> cases := []struct{ in, expected string }{
<del> {"foo", "foo"},
<del> {"foo/bar", "foo/bar"},
<del> {"foo/dir/", "foo/dir/"},
<del> }
<del> for _, v := range cases {
<del> if CanonicalTarNameForPath(v.in) != v.expected {
<del> t.Fatalf("wrong canonical tar name. expected:%s got:%s", v.expected, CanonicalTarNameForPath(v.in))
<del> }
<del> }
<del>}
<del>
<ide> func TestCanonicalTarName(t *testing.T) {
<ide> cases := []struct {
<ide> in string
<ide><path>pkg/archive/archive_windows_test.go
<ide> func TestCopyFileWithInvalidDest(t *testing.T) {
<ide> }
<ide> }
<ide>
<del>func TestCanonicalTarNameForPath(t *testing.T) {
<del> cases := []struct {
<del> in, expected string
<del> }{
<del> {"foo", "foo"},
<del> {"foo/bar", "foo/bar"},
<del> {`foo\bar`, "foo/bar"},
<del> }
<del> for _, v := range cases {
<del> if CanonicalTarNameForPath(v.in) != v.expected {
<del> t.Fatalf("wrong canonical tar name. expected:%s got:%s", v.expected, CanonicalTarNameForPath(v.in))
<del> }
<del> }
<del>}
<del>
<ide> func TestCanonicalTarName(t *testing.T) {
<ide> cases := []struct {
<ide> in string | 2 |
Text | Text | update changelog for 0.19.0-beta.1 release | 56ac637d7d2f2f08e7b80e892d68cee7ae7ae830 | <ide><path>CHANGELOG.md
<ide> # Changelog
<ide>
<add>### 0.19.0-beta.1 (Aug 9, 2018)
<add>
<add>**NOTE:** This is a beta version of this release. There may be functionality that is broken in
<add>certain browsers, though we suspect that builds are hanging and not erroring. See
<add>https://saucelabs.com/u/axios for the most up-to-date information.
<add>
<add>New Functionality:
<add>
<add>- Add getUri method ([#1712](https://github.com/axios/axios/issues/1712))
<add>- Add support for no_proxy env variable ([#1693](https://github.com/axios/axios/issues/1693))
<add>- Add toJSON to decorated Axios errors to faciliate serialization ([#1625](https://github.com/axios/axios/issues/1625))
<add>- Add second then on axios call ([#1623](https://github.com/axios/axios/issues/1623))
<add>- Typings: allow custom return types
<add>- Add option to specify character set in responses (with http adapter)
<add>
<add>Fixes:
<add>
<add>- Fix Keep defaults local to instance ([#385](https://github.com/axios/axios/issues/385))
<add>- Correctly catch exception in http test ([#1475](https://github.com/axios/axios/issues/1475))
<add>- Fix accept header normalization ([#1698](https://github.com/axios/axios/issues/1698))
<add>- Fix http adapter to allow HTTPS connections via HTTP ([#959](https://github.com/axios/axios/issues/959))
<add>- Fix Removes usage of deprecated Buffer constructor. ([#1555](https://github.com/axios/axios/issues/1555), [#1622](https://github.com/axios/axios/issues/1622))
<add>- Fix defaults to use httpAdapter if available ([#1285](https://github.com/axios/axios/issues/1285))
<add> - Fixing defaults to use httpAdapter if available
<add> - Use a safer, cross-platform method to detect the Node environment
<add>- Fix Reject promise if request is cancelled by the browser ([#537](https://github.com/axios/axios/issues/537))
<add>- [Typescript] Fix missing type parameters on delete/head methods
<add>- [NS]: Send `false` flag isStandardBrowserEnv for Nativescript
<add>- Fix missing type parameters on delete/head
<add>- Fix Default method for an instance always overwritten by get
<add>- Fix type error when socketPath option in AxiosRequestConfig
<add>- Capture errors on request data streams
<add>- Decorate resolve and reject to clear timeout in all cases
<add>
<add>Huge thanks to everyone who contributed to this release via code (authors listed
<add>below) or via reviews and triaging on GitHub:
<add>
<add>- Andrew Scott <ascott18@gmail.com>
<add>- Anthony Gauthier <antho325@hotmail.com>
<add>- arpit <arpit2438735@gmail.com>
<add>- ascott18
<add>- Benedikt Rötsch <axe312ger@users.noreply.github.com>
<add>- Chance Dickson <me@chancedickson.com>
<add>- Dave Stewart <info@davestewart.co.uk>
<add>- Deric Cain <deric.cain@gmail.com>
<add>- Guillaume Briday <guillaumebriday@gmail.com>
<add>- Jacob Wejendorp <jacob@wejendorp.dk>
<add>- Jim Lynch <mrdotjim@gmail.com>
<add>- johntron
<add>- Justin Beckwith <beckwith@google.com>
<add>- Justin Beckwith <justin.beckwith@gmail.com>
<add>- Khaled Garbaya <khaledgarbaya@gmail.com>
<add>- Lim Jing Rong <jjingrong@users.noreply.github.com>
<add>- Mark van den Broek <mvdnbrk@gmail.com>
<add>- Martti Laine <martti@codeclown.net>
<add>- mattridley
<add>- mattridley <matt.r@joinblink.com>
<add>- Nicolas Del Valle <nicolas.delvalle@gmail.com>
<add>- Nilegfx
<add>- pbarbiero
<add>- Rikki Gibson <rikkigibson@gmail.com>
<add>- Sako Hartounian <sakohartounian@yahoo.com>
<add>- Shane Fitzpatrick <fitzpasd@gmail.com>
<add>- Stephan Schneider <stephanschndr@gmail.com>
<add>- Steven <steven@ceriously.com>
<add>- Tim Garthwaite <tim.garthwaite@jibo.com>
<add>- Tim Johns <timjohns@yahoo.com>
<add>- Yutaro Miyazaki <yutaro@studio-rubbish.com>
<add>
<ide> ### 0.18.0 (Feb 19, 2018)
<ide>
<ide> - Adding support for UNIX Sockets when running with Node.js ([#1070](https://github.com/axios/axios/pull/1070))
<ide> - Fixing typings ([#1177](https://github.com/axios/axios/pull/1177)):
<del> - AxiosRequestConfig.proxy: allows type false
<del> - AxiosProxyConfig: added auth field
<add> - AxiosRequestConfig.proxy: allows type false
<add> - AxiosProxyConfig: added auth field
<ide> - Adding function signature in AxiosInstance interface so AxiosInstance can be invoked ([#1192](https://github.com/axios/axios/pull/1192), [#1254](https://github.com/axios/axios/pull/1254))
<ide> - Allowing maxContentLength to pass through to redirected calls as maxBodyLength in follow-redirects config ([#1287](https://github.com/axios/axios/pull/1287))
<ide> - Fixing configuration when using an instance - method can now be set ([#1342](https://github.com/axios/axios/pull/1342))
<ide>
<del>
<ide> ### 0.17.1 (Nov 11, 2017)
<ide>
<ide> - Fixing issue with web workers ([#1160](https://github.com/axios/axios/pull/1160)) | 1 |
PHP | PHP | fix spacing issue in asset documentation | 0344d74c6e530a872fb2db189696ac4299bbe6eb | <ide><path>system/asset.php
<ide> private function get_group($group)
<ide> * Get the link to a single registered CSS asset.
<ide> *
<ide> * <code>
<del> * echo $container->get_style('common');
<add> * echo $container->get_style('common');
<ide> * </code>
<ide> *
<ide> * @param string $name | 1 |
PHP | PHP | add tests for trace logging change | 4a6c7e81fa5dd2eb27a87d80fb298ef90c068603 | <ide><path>tests/TestCase/Error/ErrorHandlerTest.php
<ide> public function testHandleExceptionLog()
<ide> {
<ide> $errorHandler = new TestErrorHandler([
<ide> 'log' => true,
<add> 'trace' => true,
<ide> ]);
<ide>
<ide> $error = new NotFoundException('Kaboom!');
<ide>
<del> $this->_logger->expects($this->once())
<add> $this->_logger->expects($this->at(0))
<ide> ->method('log')
<ide> ->with('error', $this->logicalAnd(
<ide> $this->stringContains('[Cake\Network\Exception\NotFoundException] Kaboom!'),
<ide> $this->stringContains('ErrorHandlerTest->testHandleExceptionLog')
<ide> ));
<ide>
<add> $this->_logger->expects($this->at(1))
<add> ->method('log')
<add> ->with('error', $this->logicalAnd(
<add> $this->stringContains('[Cake\Network\Exception\NotFoundException] Kaboom!'),
<add> $this->logicalNot($this->stringContains('ErrorHandlerTest->testHandleExceptionLog'))
<add> ));
<add>
<ide> $errorHandler->handleException($error);
<ide> $this->assertContains('Kaboom!', $errorHandler->response->body(), 'message missing.');
<add>
<add> $errorHandler = new TestErrorHandler([
<add> 'log' => true,
<add> 'trace' => false,
<add> ]);
<add> $errorHandler->handleException($error);
<ide> }
<ide>
<ide> /** | 1 |
Text | Text | note $home override | 90246be60a6ba46e07b5ab65ced53b1290b98ab9 | <ide><path>share/doc/homebrew/Formula-Cookbook.md
<ide> Check the top of the e.g. `./configure` output. Some configure scripts do not re
<ide>
<ide> Please add a [`test do`](http://www.rubydoc.info/github/Homebrew/homebrew/master/Formula#test-class_method) block to the formula. This will be run by `brew test foo` and the [Brew Test Bot](Brew-Test-Bot.md).
<ide>
<del>The [`test do`](http://www.rubydoc.info/github/Homebrew/homebrew/master/Formula#test-class_method) block automatically creates and changes to a temporary directory which is deleted after run. You can access this [`Pathname`](http://www.rubydoc.info/github/Homebrew/homebrew/master/Pathname) with the [`testpath`](http://www.rubydoc.info/github/Homebrew/homebrew/master/Formula#testpath-instance_method) function.
<add>The
<add>[`test do`](http://www.rubydoc.info/github/Homebrew/homebrew/master/Formula#test-class_method)
<add>block automatically creates and changes to a temporary directory which
<add>is deleted after run. You can access this
<add>[`Pathname`](http://www.rubydoc.info/github/Homebrew/homebrew/master/Pathname)
<add>with the
<add>[`testpath`](http://www.rubydoc.info/github/Homebrew/homebrew/master/Formula#testpath-instance_method)
<add>function. The environment variable `HOME` is set to `testpath` within
<add>the `test do` block.
<ide>
<ide> We want tests that don't require any user input and test the basic functionality of the application. For example `foo build-foo input.foo` is a good test and (despite their widespread use) `foo --version` and `foo --help` are bad tests. However, a bad test is better than no test at all.
<ide> | 1 |
Python | Python | add test for optional size argument for ndindex | ffb8c414875a1430814c1e9938d1a58defcf516d | <ide><path>numpy/lib/tests/test_index_tricks.py
<ide> def test_ndindex():
<ide> expected = [ix for ix, e in np.ndenumerate(np.zeros((1, 2, 3)))]
<ide> assert_array_equal(x, expected)
<ide>
<add> # Make sure size argument is optional
<add> x = list(np.ndindex())
<add> assert_equal(x, [(0,)])
<add>
<ide>
<ide> if __name__ == "__main__":
<ide> run_module_suite() | 1 |
PHP | PHP | assertcontent() | c703de37d6eee632a3eb661c2866566fda80388e | <ide><path>src/Illuminate/Testing/TestResponse.php
<ide> public function getCookie($cookieName, $decrypt = true, $unserialize = false)
<ide> }
<ide> }
<ide>
<add> /**
<add> * Assert that the given string matches the response content.
<add> *
<add> * @param string $value
<add> * @return $this
<add> */
<add> public function assertContent($value)
<add> {
<add> PHPUnit::assertSame($value, $this->content());
<add>
<add> return $this;
<add> }
<add>
<ide> /**
<ide> * Assert that the given string or array of strings are contained within the response.
<ide> *
<ide><path>tests/Testing/TestResponseTest.php
<ide> public function testAssertViewMissingNested()
<ide> $response->assertViewMissing('foo.baz');
<ide> }
<ide>
<add> public function testAssertContent()
<add> {
<add> $response = $this->makeMockResponse([
<add> 'render' => 'expected response data',
<add> ]);
<add>
<add> $response->assertContent('expected response data');
<add>
<add> try {
<add> $response->assertContent('expected');
<add> $this->fail('xxxx');
<add> } catch (AssertionFailedError $e) {
<add> $this->assertSame('Failed asserting that two strings are identical.', $e->getMessage());
<add> }
<add>
<add> try {
<add> $response->assertContent('expected response data with extra');
<add> $this->fail('xxxx');
<add> } catch (AssertionFailedError $e) {
<add> $this->assertSame('Failed asserting that two strings are identical.', $e->getMessage());
<add> }
<add> }
<add>
<ide> public function testAssertSee()
<ide> {
<ide> $response = $this->makeMockResponse([ | 2 |
Python | Python | use mattrgetter in apply_async() | ba969f807d341ede4e894e7bdfe0c0c8ccf52f82 | <ide><path>celery/conf.py
<ide> def _get(name, default=None):
<ide> "routing_key": AMQP_CONSUMER_ROUTING_KEY,
<ide> "exchange_type": AMQP_EXCHANGE_TYPE,
<ide> }
<add>}
<ide> AMQP_CONSUMER_QUEUES = _get("CELERY_AMQP_CONSUMER_QUEUES",
<ide> DEFAULT_AMQP_CONSUMER_QUEUES)
<ide> AMQP_CONNECTION_TIMEOUT = _get("CELERY_AMQP_CONNECTION_TIMEOUT")
<ide><path>celery/execute.py
<ide>
<ide> from celery import conf
<ide> from celery import signals
<del>from celery.utils import gen_unique_id, noop, fun_takes_kwargs
<add>from celery.utils import gen_unique_id, noop, fun_takes_kwargs, mattrgetter
<ide> from celery.result import AsyncResult, EagerResult
<ide> from celery.registry import tasks
<del>from celery.messaging import TaskPublisher, with_connection_inline
<add>from celery.messaging import TaskPublisher, with_connection
<ide> from celery.exceptions import RetryTaskError
<ide> from celery.datastructures import ExceptionInfo
<ide>
<del>TASK_EXEC_OPTIONS = ("routing_key", "exchange",
<del> "immediate", "mandatory",
<del> "priority", "serializer")
<add>extract_exec_options = mattrgetter("routing_key", "exchange",
<add> "immediate", "mandatory",
<add> "priority", "serializer")
<ide>
<ide>
<add>@with_connection
<ide> def apply_async(task, args=None, kwargs=None, countdown=None, eta=None,
<ide> task_id=None, publisher=None, connection=None, connect_timeout=None,
<ide> **options):
<ide> def apply_async(task, args=None, kwargs=None, countdown=None, eta=None,
<ide> if conf.ALWAYS_EAGER:
<ide> return apply(task, args, kwargs)
<ide>
<del> for option_name in TASK_EXEC_OPTIONS:
<del> if option_name not in options:
<del> options[option_name] = getattr(task, option_name, None)
<add> options = dict(extract_exec_options(task), **options)
<ide>
<ide> if countdown: # Convert countdown to ETA.
<ide> eta = datetime.now() + timedelta(seconds=countdown)
<ide>
<del> def _delay_task(connection):
<del> publish = publisher or TaskPublisher(connection)
<del> try:
<del> return publish.delay_task(task.name, args or [], kwargs or {},
<del> task_id=task_id,
<del> eta=eta,
<del> **options)
<del> finally:
<del> publisher or publish.close()
<del>
<del> task_id = with_connection_inline(_delay_task, connection=connection,
<del> connect_timeout=connect_timeout)
<add> publish = publisher or TaskPublisher(connection)
<add> try:
<add> task_id = publish.delay_task(task.name, args or [], kwargs or {},
<add> task_id=task_id,
<add> eta=eta,
<add> **options)
<add> finally:
<add> publisher or publish.close()
<add>
<ide> return AsyncResult(task_id)
<ide>
<ide>
<ide><path>celery/utils.py
<ide> def mitemgetter(*items):
<ide> return lambda container: map(container.get, items)
<ide>
<ide>
<add>def mattrgetter(*attrs):
<add> """Like :func:`operator.itemgetter` but returns ``None`` on missing
<add> attributes instead of raising :exc:`AttributeError`."""
<add> return lambda obj: dict((attr, getattr(obj, attr, None))
<add> for attr in attrs)
<add>
<add>
<ide> def get_full_cls_name(cls):
<ide> """With a class, get its full module and class name."""
<ide> return ".".join([cls.__module__, | 3 |
Text | Text | provide example of initial state ssr scrub | b3e43c85e4c1d2883000fad92db38bd37d243ad6 | <ide><path>docs/recipes/ServerRendering.md
<ide> In our example, we take a rudimentary approach to security. When we obtain the p
<ide>
<ide> For our simplistic example, coercing our input into a number is sufficiently secure. If you're handling more complex input, such as freeform text, then you should run that input through an appropriate sanitization function, such as [validator.js](https://www.npmjs.com/package/validator).
<ide>
<del>Furthermore, you can add additional layers of security by sanitizing your state output. `JSON.stringify` can be subject to script injections. To counter this, you can scrub the JSON string of HTML tags and other dangerous characters. This can be done with either a simple text replacement on the string or via more sophisticated libraries such as [serialize-javascript](https://github.com/yahoo/serialize-javascript).
<add>Furthermore, you can add additional layers of security by sanitizing your state output. `JSON.stringify` can be subject to script injections. To counter this, you can scrub the JSON string of HTML tags and other dangerous characters. This can be done with either a simple text replacement on the string, e.g. `JSON.stringify(state).replace(/</g, '\\u003c')`, or via more sophisticated libraries such as [serialize-javascript](https://github.com/yahoo/serialize-javascript).
<ide>
<ide> ## Next Steps
<ide> | 1 |
Go | Go | remove old testing stuff that slipped into master | b4988d8d75b4ee915ade6013de76bb1336917528 | <ide><path>integration-cli/docker_api_info_test.go
<ide> package main
<ide> import (
<ide> "net/http"
<ide> "strings"
<del> "testing"
<add>
<add> "github.com/go-check/check"
<ide> )
<ide>
<del>func TestInfoApi(t *testing.T) {
<add>func (s *DockerSuite) TestInfoApi(c *check.C) {
<ide> endpoint := "/info"
<ide>
<ide> statusCode, body, err := sockRequest("GET", endpoint, nil)
<ide> if err != nil || statusCode != http.StatusOK {
<del> t.Fatalf("Expected %d from info request, got %d", http.StatusOK, statusCode)
<add> c.Fatalf("Expected %d from info request, got %d", http.StatusOK, statusCode)
<ide> }
<ide>
<ide> // always shown fields
<ide> func TestInfoApi(t *testing.T) {
<ide> out := string(body)
<ide> for _, linePrefix := range stringsToCheck {
<ide> if !strings.Contains(out, linePrefix) {
<del> t.Errorf("couldn't find string %v in output", linePrefix)
<add> c.Errorf("couldn't find string %v in output", linePrefix)
<ide> }
<ide> }
<ide> } | 1 |
Javascript | Javascript | add test for non-standard extension transpilation | 227ef5e2deab0e711653a0a7dd949b6f9cea6e91 | <ide><path>spec/package-transpilation-registry-spec.js
<ide> describe("PackageTranspilationRegistry", () => {
<ide> let hitPathMissSubdir = '/path/to/file4.js'
<ide> let hitPathMissExt = '/path/to/file5.ts'
<ide> let nodeModulesFolder = '/path/to/lib/node_modules/file6.js'
<add> let hitNonStandardExt = '/path/to/file7.omgwhatisthis'
<ide>
<ide> let jsSpec = { glob: "lib/**/*.js", transpiler: './transpiler-js', options: { type: 'js' } }
<ide> let coffeeSpec = { glob: "*.coffee", transpiler: './transpiler-coffee', options: { type: 'coffee' } }
<add> let omgSpec = { glob: "*.omgwhatisthis", transpiler: './transpiler-omg', options: { type: 'omg' } }
<ide>
<ide> let jsTranspiler = {
<ide> transpile: (sourceCode, filePath, options) => {
<ide> describe("PackageTranspilationRegistry", () => {
<ide> }
<ide> }
<ide>
<add> let omgTranspiler = {
<add> transpile: (sourceCode, filePath, options) => {
<add> return {code: sourceCode + "-transpiler-omg"}
<add> },
<add>
<add> getCacheKeyData: (sourceCode, filePath, options) => {
<add> return 'omg-transpiler-cache-data'
<add> }
<add> }
<add>
<ide> beforeEach(() => {
<ide> jsSpec._transpilerSource = "js-transpiler-source"
<ide> coffeeSpec._transpilerSource = "coffee-transpiler-source"
<add> omgTranspiler._transpilerSource = "omg-transpiler-source"
<ide>
<ide> spyOn(registry, "getTranspiler").andCallFake(spec => {
<ide> if (spec.transpiler === './transpiler-js') return jsTranspiler
<ide> if (spec.transpiler === './transpiler-coffee') return coffeeTranspiler
<add> if (spec.transpiler === './transpiler-omg') return omgTranspiler
<ide> throw new Error('bad transpiler path ' + spec.transpiler)
<ide> })
<ide>
<ide> registry.addTranspilerConfigForPath('/path/to', [
<del> jsSpec, coffeeSpec
<add> jsSpec, coffeeSpec, omgSpec
<ide> ])
<ide> })
<ide>
<ide> it('always returns true from shouldCompile for a file in that dir that match a glob', () => {
<ide> spyOn(originalCompiler, 'shouldCompile').andReturn(false)
<ide> expect(wrappedCompiler.shouldCompile('source', hitPath)).toBe(true)
<ide> expect(wrappedCompiler.shouldCompile('source', hitPathCoffee)).toBe(true)
<add> expect(wrappedCompiler.shouldCompile('source', hitNonStandardExt)).toBe(true)
<ide> expect(wrappedCompiler.shouldCompile('source', hitPathMissExt)).toBe(false)
<ide> expect(wrappedCompiler.shouldCompile('source', hitPathMissSubdir)).toBe(false)
<ide> expect(wrappedCompiler.shouldCompile('source', missPath)).toBe(false)
<ide> describe("PackageTranspilationRegistry", () => {
<ide>
<ide> expect(wrappedCompiler.compile('source', hitPath)).toEqual('source-transpiler-js')
<ide> expect(wrappedCompiler.compile('source', hitPathCoffee)).toEqual('source-transpiler-coffee')
<add> expect(wrappedCompiler.compile('source', hitNonStandardExt)).toEqual('source-transpiler-omg')
<ide> expect(wrappedCompiler.compile('source', missPath)).toEqual('source-original-compiler')
<ide> expect(wrappedCompiler.compile('source', hitPathMissExt)).toEqual('source-original-compiler')
<ide> expect(wrappedCompiler.compile('source', hitPathMissSubdir)).toEqual('source-original-compiler') | 1 |
PHP | PHP | add a test fo cell options | 87568f2845923c2606f63bca69d21f1dae730aa8 | <ide><path>tests/TestCase/View/CellTest.php
<ide> public function testCellMissingMethod() {
<ide> $this->View->cell('Articles::nope');
<ide> }
<ide>
<add>/**
<add> * Test that cell options are passed on.
<add> *
<add> * @return void
<add> */
<add> public function testCellOptions() {
<add> $cell = $this->View->cell('Articles', [], ['limit' => 10, 'nope' => 'nope']);
<add> $this->assertEquals(10, $cell->limit);
<add> $this->assertFalse(property_exists('nope', $cell), 'Not a valid option');
<add> }
<add>
<ide> }
<ide><path>tests/test_app/TestApp/View/Cell/ArticlesCell.php
<ide> */
<ide> class ArticlesCell extends \Cake\View\Cell {
<ide>
<add>/**
<add> * valid cell options.
<add> *
<add> * @var array
<add> */
<add> protected $_validCellOptions = ['limit', 'page'];
<add>
<ide> /**
<ide> * Default cell action.
<ide> * | 2 |
Ruby | Ruby | add missing require to ap | da483d3f307a725d10fa3888df07d0bcbb14a0d2 | <ide><path>actionpack/lib/action_dispatch/middleware/cookies.rb
<ide> require 'active_support/core_ext/hash/keys'
<ide> require 'active_support/core_ext/module/attribute_accessors'
<add>require 'active_support/key_generator'
<ide> require 'active_support/message_verifier'
<ide>
<ide> module ActionDispatch | 1 |
Python | Python | fix typo in password | a2cf5a0e3fc2c463bcb44b665367db34fb7830b9 | <ide><path>airflow/models/connection.py
<ide> class Connection(Base, LoggingMixin):
<ide> :type host: str
<ide> :param login: The login.
<ide> :type login: str
<del> :param password: The pasword.
<add> :param password: The password.
<ide> :type password: str
<ide> :param schema: The schema.
<ide> :type schema: str | 1 |
Go | Go | remove superfluous panic | 14d3880daf9bdfe52248b5b0548a5522161baf2c | <ide><path>runtime_test.go
<ide> func newTestRuntime() (*Runtime, error) {
<ide> return nil, err
<ide> }
<ide> if err := CopyDirectory(unitTestStoreBase, root); err != nil {
<del> panic(err)
<ide> return nil, err
<ide> }
<ide> | 1 |
PHP | PHP | update hasmany to use proxy methods | 709189f7bfac23fb99d9a90a249b91a86dcb24f1 | <ide><path>src/ORM/Association/DependentDeleteHelper.php
<ide> public function cascadeDelete(Association $association, EntityInterface $entity,
<ide>
<ide> return true;
<ide> }
<del> $conditions = array_merge($conditions, $association->getConditions());
<ide>
<del> return (bool)$table->deleteAll($conditions);
<add> return (bool)$association->deleteAll($conditions);
<ide> }
<ide> }
<ide><path>src/ORM/Association/HasMany.php
<ide> protected function _unlink(array $foreignKey, Table $target, array $conditions =
<ide> $entry->setField($target->aliasField($entry->getField()));
<ide> }
<ide> });
<del> $query = $this->find('all')->where($conditions);
<add> $query = $this->find()->where($conditions);
<ide> $ok = true;
<ide> foreach ($query as $assoc) {
<ide> $ok = $ok && $target->delete($assoc, $options);
<ide> protected function _unlink(array $foreignKey, Table $target, array $conditions =
<ide> return $ok;
<ide> }
<ide>
<del> $conditions = array_merge($conditions, $this->getConditions());
<del> $target->deleteAll($conditions);
<add> $this->deleteAll($conditions);
<ide>
<ide> return true;
<ide> }
<ide>
<ide> $updateFields = array_fill_keys($foreignKey, null);
<del> $conditions = array_merge($conditions, $this->getConditions());
<del> $target->updateAll($updateFields, $conditions);
<add> $this->updateAll($updateFields, $conditions);
<ide>
<ide> return true;
<ide> }
<ide><path>tests/TestCase/ORM/Association/HasManyTest.php
<ide> class HasManyTest extends TestCase
<ide> 'core.Comments',
<ide> 'core.Articles',
<ide> 'core.Authors',
<add> 'core.ArticlesTags',
<ide> ];
<ide>
<ide> /**
<ide> class HasManyTest extends TestCase
<ide> public function setUp()
<ide> {
<ide> parent::setUp();
<add> $this->setAppNamespace('TestApp');
<add>
<ide> $this->author = $this->getTableLocator()->get('Authors', [
<ide> 'schema' => [
<ide> 'id' => ['type' => 'integer'],
<ide> public function testEagerLoaderMultipleKeys()
<ide> */
<ide> public function testCascadeDelete()
<ide> {
<add> $articles = $this->getTableLocator()->get('Articles');
<ide> $config = [
<ide> 'dependent' => true,
<ide> 'sourceTable' => $this->author,
<del> 'targetTable' => $this->article,
<del> 'conditions' => ['Articles.is_active' => true],
<add> 'targetTable' => $articles,
<add> 'conditions' => ['Articles.published' => 'Y'],
<ide> ];
<ide> $association = new HasMany('Articles', $config);
<ide>
<del> $this->article->expects($this->once())
<del> ->method('deleteAll')
<del> ->with([
<del> 'Articles.is_active' => true,
<del> 'Articles.author_id' => 1,
<add> $entity = new Entity(['id' => 1, 'name' => 'PHP']);
<add> $this->assertTrue($association->cascadeDelete($entity));
<add>
<add> $published = $articles
<add> ->find('published')
<add> ->where([
<add> 'published' => 'Y',
<add> 'author_id' => 1,
<ide> ]);
<add> $this->assertCount(0, $published->all());
<add> }
<add>
<add> /**
<add> * Test cascading deletes with a finder
<add> *
<add> * @return void
<add> */
<add> public function testCascadeDeleteFinder()
<add> {
<add> $articles = $this->getTableLocator()->get('Articles');
<add> $config = [
<add> 'dependent' => true,
<add> 'sourceTable' => $this->author,
<add> 'targetTable' => $articles,
<add> 'finder' => 'published',
<add> ];
<add> // Exclude one record from the association finder
<add> $articles->updateAll(
<add> ['published' => 'N'],
<add> ['author_id' => 1, 'title' => 'First Article']
<add> );
<add> $association = new HasMany('Articles', $config);
<ide>
<ide> $entity = new Entity(['id' => 1, 'name' => 'PHP']);
<del> $association->cascadeDelete($entity);
<add> $this->assertTrue($association->cascadeDelete($entity));
<add>
<add> $published = $articles->find('published')->where(['author_id' => 1]);
<add> $this->assertCount(0, $published->all(), 'Associated records should be removed');
<add>
<add> $all = $articles->find()->where(['author_id' => 1]);
<add> $this->assertCount(1, $all->all(), 'Record not in association finder should remain');
<ide> }
<ide>
<ide> /**
<ide> public function testSaveReplaceSaveStrategyDependentWithConditions()
<ide> 'dependent' => true,
<ide> ]);
<ide> $articles = $authors->Articles->getTarget();
<add>
<add> // Remove an article from the association finder scope
<ide> $articles->updateAll(['published' => 'N'], ['author_id' => 1, 'title' => 'Third Article']);
<ide>
<ide> $entity = $authors->get(1, ['contain' => ['Articles']]);
<ide> $data = [
<ide> 'name' => 'updated',
<ide> 'articles' => [
<del> ['title' => 'First Article', 'body' => 'New First', 'published' => 'N'],
<add> ['title' => 'New First', 'body' => 'New First', 'published' => 'Y'],
<ide> ],
<ide> ];
<ide> $entity = $authors->patchEntity($entity, $data, ['associated' => ['Articles']]);
<ide> $entity = $authors->save($entity, ['associated' => ['Articles']]);
<ide>
<ide> // Should only have one article left as we 'replaced' the others.
<ide> $this->assertCount(1, $entity->articles);
<del> $this->assertCount(1, $authors->Articles->find()->toArray());
<add>
<add> // No additional records in db.
<add> $this->assertCount(
<add> 1,
<add> $authors->Articles->find()->where(['author_id' => 1])->toArray()
<add> );
<ide>
<ide> $others = $articles->find('all')
<del> ->where(['Articles.author_id' => 1])
<add> ->where(['Articles.author_id' => 1, 'published' => 'N'])
<ide> ->orderAsc('title')
<ide> ->toArray();
<ide> $this->assertCount(
<ide> 1,
<ide> $others,
<del> 'Record not matching condition should stay. But does not'
<add> 'Record not matching association condition should stay'
<ide> );
<del> $this->assertSame('First Article', $others[0]->title);
<add> $this->assertSame('Third Article', $others[0]->title);
<ide> }
<ide>
<ide> /** | 3 |
Python | Python | ignore unused converters in `loadtxt` | f1855ef6c44ff037b606cbc0673a536ece31a945 | <ide><path>numpy/lib/io.py
<ide> def split_line(line):
<ide> # By preference, use the converters specified by the user
<ide> for i, conv in (user_converters or {}).iteritems():
<ide> if usecols:
<del> i = usecols.index(i)
<add> try:
<add> i = usecols.index(i)
<add> except ValueError:
<add> # Unused converter specified
<add> continue
<ide> converters[i] = conv
<ide>
<ide> # Parse each line, including the first
<ide><path>numpy/lib/tests/test_io.py
<ide> def test_empty_file(self):
<ide> c = StringIO.StringIO()
<ide> assert_raises(IOError, np.loadtxt, c)
<ide>
<add> def test_unused_converter(self):
<add> c = StringIO.StringIO()
<add> c.writelines(['1 21\n', '3 42\n'])
<add> c.seek(0)
<add> data = np.loadtxt(c, usecols=(1,), converters={0: lambda s: int(s, 16)})
<add> assert_array_equal(data, [21, 42])
<add>
<add> c.seek(0)
<add> data = np.loadtxt(c, usecols=(1,), converters={1: lambda s: int(s, 16)})
<add> assert_array_equal(data, [33, 66])
<add>
<ide> class Testfromregex(TestCase):
<ide> def test_record(self):
<ide> c = StringIO.StringIO() | 2 |
Text | Text | fix the ipaddress of an explanation | a94b48923e8ec7a5e9ebe6101f0ccac208fb4f25 | <ide><path>docs/userguide/networking/default_network/custom-docker0.md
<ide> Docker configures `docker0` with an IP address, netmask and IP allocation range.
<ide>
<ide> - `--bip=CIDR` -- supply a specific IP address and netmask for the `docker0` bridge, using standard CIDR notation like `192.168.1.5/24`.
<ide>
<del>- `--fixed-cidr=CIDR` -- restrict the IP range from the `docker0` subnet, using the standard CIDR notation like `172.167.1.0/28`. This range must be an IPv4 range for fixed IPs (ex: 10.20.0.0/16) and must be a subset of the bridge IP range (`docker0` or set using `--bridge`). For example with `--fixed-cidr=192.168.1.0/25`, IPs for your containers will be chosen from the first half of `192.168.1.0/24` subnet.
<add>- `--fixed-cidr=CIDR` -- restrict the IP range from the `docker0` subnet, using the standard CIDR notation like `172.16.1.0/28`. This range must be an IPv4 range for fixed IPs (ex: 10.20.0.0/16) and must be a subset of the bridge IP range (`docker0` or set using `--bridge`). For example with `--fixed-cidr=192.168.1.0/25`, IPs for your containers will be chosen from the first half of `192.168.1.0/24` subnet.
<ide>
<ide> - `--mtu=BYTES` -- override the maximum packet length on `docker0`.
<ide> | 1 |
Python | Python | make spacy.load kwargs keyword-only | fbf3a755d7af0afc32fb7f7d83d4b9933ed724e4 | <ide><path>spacy/__init__.py
<ide>
<ide> def load(
<ide> name: Union[str, Path],
<add> *,
<ide> disable: Iterable[str] = util.SimpleFrozenList(),
<ide> exclude: Iterable[str] = util.SimpleFrozenList(),
<ide> config: Union[Dict[str, Any], Config] = util.SimpleFrozenDict(), | 1 |
Text | Text | update a link in v8.md | 4bde70de5ab543333bc8c98091dc5ee2f2a2fe46 | <ide><path>doc/api/v8.md
<ide> A subclass of [`Deserializer`][] corresponding to the format written by
<ide> [V8]: https://developers.google.com/v8/
<ide> [`vm.Script`]: vm.html#vm_new_vm_script_code_options
<ide> [here]: https://github.com/thlorenz/v8-flags/blob/master/flags-0.11.md
<del>[`GetHeapSpaceStatistics`]: https://v8docs.nodesource.com/node-8.9/d5/dda/classv8_1_1_isolate.html#ac673576f24fdc7a33378f8f57e1d13a4
<add>[`GetHeapSpaceStatistics`]: https://v8docs.nodesource.com/node-10.6/d5/dda/classv8_1_1_isolate.html#ac673576f24fdc7a33378f8f57e1d13a4 | 1 |
Javascript | Javascript | add a support comment & fix a link @ tabindex hook | 9cb89bf91d034ec7166d9215e2f80fa765292975 | <ide><path>src/attributes/prop.js
<ide> jQuery.extend( {
<ide> tabIndex: {
<ide> get: function( elem ) {
<ide>
<add> // Support: IE 9-11 only
<ide> // elem.tabIndex doesn't always return the
<ide> // correct value when it hasn't been explicitly set
<del> // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
<add> // https://web.archive.org/web/20141116233347/http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
<ide> // Use proper attribute retrieval(#12072)
<ide> var tabindex = jQuery.find.attr( elem, "tabindex" );
<ide> | 1 |
Go | Go | add test for exposing large number of ports | 29be7b439ec4d0c8a54852ccbbe7b6bcf040e13f | <ide><path>integration-cli/docker_cli_build_test.go
<ide> package main
<ide>
<ide> import (
<ide> "archive/tar"
<add> "bytes"
<ide> "encoding/json"
<ide> "fmt"
<ide> "io/ioutil"
<ide> import (
<ide> "path"
<ide> "path/filepath"
<ide> "regexp"
<add> "strconv"
<ide> "strings"
<ide> "syscall"
<ide> "testing"
<add> "text/template"
<ide> "time"
<ide>
<ide> "github.com/docker/docker/pkg/archive"
<ide> func TestBuildExpose(t *testing.T) {
<ide> logDone("build - expose")
<ide> }
<ide>
<add>func TestBuildExposeMorePorts(t *testing.T) {
<add> // start building docker file with a large number of ports
<add> portList := make([]string, 50)
<add> line := make([]string, 100)
<add> expectedPorts := make([]int, len(portList)*len(line))
<add> for i := 0; i < len(portList); i++ {
<add> for j := 0; j < len(line); j++ {
<add> p := i*len(line) + j + 1
<add> line[j] = strconv.Itoa(p)
<add> expectedPorts[p-1] = p
<add> }
<add> if i == len(portList)-1 {
<add> portList[i] = strings.Join(line, " ")
<add> } else {
<add> portList[i] = strings.Join(line, " ") + ` \`
<add> }
<add> }
<add>
<add> dockerfile := `FROM scratch
<add> EXPOSE {{range .}} {{.}}
<add> {{end}}`
<add> tmpl := template.Must(template.New("dockerfile").Parse(dockerfile))
<add> buf := bytes.NewBuffer(nil)
<add> tmpl.Execute(buf, portList)
<add>
<add> name := "testbuildexpose"
<add> defer deleteImages(name)
<add> _, err := buildImage(name, buf.String(), true)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> // check if all the ports are saved inside Config.ExposedPorts
<add> res, err := inspectFieldJSON(name, "Config.ExposedPorts")
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> var exposedPorts map[string]interface{}
<add> if err := json.Unmarshal([]byte(res), &exposedPorts); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> for _, p := range expectedPorts {
<add> ep := fmt.Sprintf("%d/tcp", p)
<add> if _, ok := exposedPorts[ep]; !ok {
<add> t.Errorf("Port(%s) is not exposed", ep)
<add> } else {
<add> delete(exposedPorts, ep)
<add> }
<add> }
<add> if len(exposedPorts) != 0 {
<add> t.Errorf("Unexpected extra exposed ports %v", exposedPorts)
<add> }
<add> logDone("build - expose large number of ports")
<add>}
<add>
<ide> func TestBuildExposeOrder(t *testing.T) {
<ide> buildID := func(name, exposed string) string {
<ide> _, err := buildImage(name, fmt.Sprintf(`FROM scratch | 1 |
Text | Text | fix minor typo in reducing boilerplate | c90684f53ad6abbf8875030b6249392a637feb52 | <ide><path>docs/recipes/ReducingBoilerplate.md
<ide> function callAPIMiddleware({ dispatch, getState }) {
<ide> }
<ide>
<ide> if (typeof callAPI !== 'function') {
<del> throw new Error('Expected fetch to be a function.')
<add> throw new Error('Expected callAPI to be a function.')
<ide> }
<ide>
<ide> if (!shouldCallAPI(getState())) { | 1 |
Javascript | Javascript | fix scroll to zoom jump between 25% and 1000% | ed540a8d00e348f740dcfe6614c07b71573a800a | <ide><path>web/viewer.js
<ide> var PDFViewerApplication = {
<ide> newScale = (newScale * DEFAULT_SCALE_DELTA).toFixed(2);
<ide> newScale = Math.ceil(newScale * 10) / 10;
<ide> newScale = Math.min(MAX_SCALE, newScale);
<del> } while (--ticks && newScale < MAX_SCALE);
<add> } while (--ticks > 0 && newScale < MAX_SCALE);
<ide> this.setScale(newScale, true);
<ide> },
<ide>
<ide> var PDFViewerApplication = {
<ide> newScale = (newScale / DEFAULT_SCALE_DELTA).toFixed(2);
<ide> newScale = Math.floor(newScale * 10) / 10;
<ide> newScale = Math.max(MIN_SCALE, newScale);
<del> } while (--ticks && newScale > MIN_SCALE);
<add> } while (--ticks > 0 && newScale > MIN_SCALE);
<ide> this.setScale(newScale, true);
<ide> },
<ide> | 1 |
Java | Java | fix white spaces | b5e1198bd22b4d4d78cdd99dcc1b02793b98d9ed | <ide><path>spring-test/src/main/java/org/springframework/test/web/servlet/request/MockMvcRequestBuilders.java
<ide> public static MockHttpServletRequestBuilder delete(URI uri) {
<ide> }
<ide>
<ide> /**
<del> * Create a {@link MockHttpServletRequestBuilder} for an OPTIONS request.
<del> * @param urlTemplate a URL template; the resulting URL will be encoded
<del> * @param urlVariables zero or more URL variables
<del> */
<del> public static MockHttpServletRequestBuilder options(String urlTemplate, Object... urlVariables) {
<del> return new MockHttpServletRequestBuilder(HttpMethod.OPTIONS, urlTemplate, urlVariables);
<del> }
<add> * Create a {@link MockHttpServletRequestBuilder} for an OPTIONS request.
<add> * @param urlTemplate a URL template; the resulting URL will be encoded
<add> * @param urlVariables zero or more URL variables
<add> */
<add> public static MockHttpServletRequestBuilder options(String urlTemplate, Object... urlVariables) {
<add> return new MockHttpServletRequestBuilder(HttpMethod.OPTIONS, urlTemplate, urlVariables);
<add> }
<ide>
<ide> /**
<ide> * Create a {@link MockHttpServletRequestBuilder} for an OPTIONS request.
<ide> public static MockHttpServletRequestBuilder options(URI uri) {
<ide> return new MockHttpServletRequestBuilder(HttpMethod.OPTIONS, uri);
<ide> }
<ide>
<del> /**
<del> * Create a {@link MockHttpServletRequestBuilder} for a HEAD request.
<del> * @param urlTemplate a URL template; the resulting URL will be encoded
<del> * @param urlVariables zero or more URL variables
<del> * @since 4.1
<del> */
<del> public static MockHttpServletRequestBuilder head(String urlTemplate, Object... urlVariables) {
<del> return new MockHttpServletRequestBuilder(HttpMethod.HEAD, urlTemplate, urlVariables);
<del> }
<del>
<del> /**
<del> * Create a {@link MockHttpServletRequestBuilder} for a HEAD request.
<del> * @param uri the URL
<del> * @since 4.1
<del> */
<del> public static MockHttpServletRequestBuilder head(URI uri) {
<del> return new MockHttpServletRequestBuilder(HttpMethod.HEAD, uri);
<del> }
<add> /**
<add> * Create a {@link MockHttpServletRequestBuilder} for a HEAD request.
<add> * @param urlTemplate a URL template; the resulting URL will be encoded
<add> * @param urlVariables zero or more URL variables
<add> * @since 4.1
<add> */
<add> public static MockHttpServletRequestBuilder head(String urlTemplate, Object... urlVariables) {
<add> return new MockHttpServletRequestBuilder(HttpMethod.HEAD, urlTemplate, urlVariables);
<add> }
<add>
<add> /**
<add> * Create a {@link MockHttpServletRequestBuilder} for a HEAD request.
<add> * @param uri the URL
<add> * @since 4.1
<add> */
<add> public static MockHttpServletRequestBuilder head(URI uri) {
<add> return new MockHttpServletRequestBuilder(HttpMethod.HEAD, uri);
<add> }
<ide>
<ide> /**
<ide> * Create a {@link MockHttpServletRequestBuilder} for a request with the given HTTP method. | 1 |
Javascript | Javascript | fix first guard clause | 0d2646f9afea38bb4df01a658766ba6224e8f8cc | <ide><path>script/lib/verify-machine-requirements.js
<ide> module.exports = function () {
<ide> function verifyNode () {
<ide> const fullVersion = process.versions.node
<ide> const majorVersion = fullVersion.split('.')[0]
<del> if (majorVersion >= 4) {
<add> if (majorVersion >= 4 && majorVersion < 7) {
<ide> console.log(`Node:\tv${fullVersion}`)
<ide> } else if (majorVersion >= 7) {
<ide> throw new Error(`Atom does not build properly on node v7+. node v${fullVersion} is installed.`) | 1 |
Javascript | Javascript | relax y2k38 check in test-fs-utimes-y2k38 | 428c3fd31b86706bb6987f7ae1b1ac398eb343cb | <ide><path>test/parallel/test-fs-utimes-y2K38.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide>
<del>if (common.isIBMi) {
<del> common.skip('fs.utimesSync() currently fails on IBM i with Y2K38 values');
<del>}
<del>
<ide> const tmpdir = require('../common/tmpdir');
<ide> tmpdir.refresh();
<ide>
<ide> const assert = require('assert');
<ide> const fs = require('fs');
<ide>
<del>// Check for Y2K38 support. For Windows and AIX, assume it's there. Windows
<add>// Check for Y2K38 support. For Windows, assume it's there. Windows
<ide> // doesn't have `touch` and `date -r` which are used in the check for support.
<del>// AIX lacks `date -r`.
<del>if (!common.isWindows && !common.isAIX) {
<add>if (!common.isWindows) {
<ide> const testFilePath = `${tmpdir.path}/y2k38-test`;
<ide> const testFileDate = '204001020304';
<ide> const { spawnSync } = require('child_process');
<ide> if (!common.isWindows && !common.isAIX) {
<ide> common.skip('File system appears to lack Y2K38 support (touch failed)');
<ide> }
<ide>
<add> // On some file systems that lack Y2K38 support, `touch` will succeed but
<add> // the time will be incorrect.
<ide> const dateResult = spawnSync('date',
<ide> ['-r', testFilePath, '+%Y%m%d%H%M'],
<ide> { encoding: 'utf8' });
<del>
<del> assert.strictEqual(dateResult.status, 0);
<del> if (dateResult.stdout.trim() !== testFileDate) {
<del> common.skip('File system appears to lack Y2k38 support (date failed)');
<add> if (dateResult.status === 0) {
<add> if (dateResult.stdout.trim() !== testFileDate) {
<add> common.skip('File system appears to lack Y2k38 support (date failed)');
<add> }
<add> } else {
<add> // On some platforms `date` may not support the `-r` option. Usually
<add> // this will result in a non-zero status and usage information printed.
<add> // In this case optimistically proceed -- the earlier `touch` succeeded
<add> // but validation that the file has the correct time is not easily possible.
<add> assert.match(dateResult.stderr, /[Uu]sage:/);
<ide> }
<ide> }
<ide> | 1 |
Go | Go | ensure consistent status code | 3484e02590117d175d9c1ab24c583390b4e94a55 | <ide><path>api/server/httputils/errors.go
<ide> func GetHTTPErrorStatusCode(err error) int {
<ide> // If we need to differentiate between different possible error types,
<ide> // we should create appropriate error types that implement the httpStatusError interface.
<ide> errStr := strings.ToLower(errMsg)
<del> for keyword, status := range map[string]int{
<del> "not found": http.StatusNotFound,
<del> "no such": http.StatusNotFound,
<del> "bad parameter": http.StatusBadRequest,
<del> "no command": http.StatusBadRequest,
<del> "conflict": http.StatusConflict,
<del> "impossible": http.StatusNotAcceptable,
<del> "wrong login/password": http.StatusUnauthorized,
<del> "unauthorized": http.StatusUnauthorized,
<del> "hasn't been activated": http.StatusForbidden,
<del> "this node": http.StatusNotAcceptable,
<add> for _, status := range []struct {
<add> keyword string
<add> code int
<add> }{
<add> {"not found", http.StatusNotFound},
<add> {"no such", http.StatusNotFound},
<add> {"bad parameter", http.StatusBadRequest},
<add> {"no command", http.StatusBadRequest},
<add> {"conflict", http.StatusConflict},
<add> {"impossible", http.StatusNotAcceptable},
<add> {"wrong login/password", http.StatusUnauthorized},
<add> {"unauthorized", http.StatusUnauthorized},
<add> {"hasn't been activated", http.StatusForbidden},
<add> {"this node", http.StatusNotAcceptable},
<ide> } {
<del> if strings.Contains(errStr, keyword) {
<del> statusCode = status
<add> if strings.Contains(errStr, status.keyword) {
<add> statusCode = status.code
<ide> break
<ide> }
<ide> } | 1 |
Javascript | Javascript | fix tests so they work in worker threads | 82a256ac6740b7a6d29439af911b86a7a0b2e63f | <ide><path>test/parallel/test-cli-eval.js
<ide> const path = require('path');
<ide> const fixtures = require('../common/fixtures');
<ide> const nodejs = `"${process.execPath}"`;
<ide>
<del>if (!common.isMainThread)
<del> common.skip('process.chdir is not available in Workers');
<del>
<ide> if (process.argv.length > 2) {
<ide> console.log(process.argv.slice(2).join(' '));
<ide> process.exit(0);
<ide> child.exec(`${nodejs} --print "os.platform()"`,
<ide> }));
<ide>
<ide> // Module path resolve bug regression test.
<del>const cwd = process.cwd();
<del>process.chdir(path.resolve(__dirname, '../../'));
<ide> child.exec(`${nodejs} --eval "require('./test/parallel/test-cli-eval.js')"`,
<add> { cwd: path.resolve(__dirname, '../../') },
<ide> common.mustCall((err, stdout, stderr) => {
<ide> assert.strictEqual(err.code, 42);
<ide> assert.strictEqual(
<ide> stdout, 'Loaded as a module, exiting with status code 42.\n');
<ide> assert.strictEqual(stderr, '');
<ide> }));
<del>process.chdir(cwd);
<ide>
<ide> // Missing argument should not crash.
<ide> child.exec(`${nodejs} -e`, common.mustCall((err, stdout, stderr) => {
<ide><path>test/parallel/test-cli-node-options-disallowed.js
<ide> const common = require('../common');
<ide> if (process.config.variables.node_without_node_options)
<ide> common.skip('missing NODE_OPTIONS support');
<del>if (!common.isMainThread)
<del> common.skip('process.chdir is not available in Workers');
<ide>
<ide> // Test options specified by env variable.
<ide>
<ide> const exec = require('child_process').execFile;
<ide>
<ide> const tmpdir = require('../common/tmpdir');
<ide> tmpdir.refresh();
<del>process.chdir(tmpdir.path);
<ide>
<ide> disallow('--version');
<ide> disallow('-v');
<ide> disallow('--');
<ide>
<ide> function disallow(opt) {
<ide> const env = Object.assign({}, process.env, { NODE_OPTIONS: opt });
<del> exec(process.execPath, { env }, common.mustCall(function(err) {
<add> exec(process.execPath, { cwd: tmpdir.path, env }, common.mustCall((err) => {
<ide> const message = err.message.split(/\r?\n/)[1];
<ide> const expect = `${process.execPath}: ${opt} is not allowed in NODE_OPTIONS`;
<ide>
<ide><path>test/parallel/test-cli-node-options.js
<ide> const common = require('../common');
<ide> if (process.config.variables.node_without_node_options)
<ide> common.skip('missing NODE_OPTIONS support');
<del>if (!common.isMainThread)
<del> common.skip('process.chdir is not available in Workers');
<ide>
<ide> // Test options specified by env variable.
<ide>
<ide> const exec = require('child_process').execFile;
<ide>
<ide> const tmpdir = require('../common/tmpdir');
<ide> tmpdir.refresh();
<del>process.chdir(tmpdir.path);
<ide>
<ide> const printA = require.resolve('../fixtures/printA.js');
<ide> expect(`-r ${printA}`, 'A\nB\n');
<ide> expect('--stack-trace-limit=100',
<ide> function expect(opt, want, command = 'console.log("B")', wantsError = false) {
<ide> const argv = ['-e', command];
<ide> const opts = {
<add> cwd: tmpdir.path,
<ide> env: Object.assign({}, process.env, { NODE_OPTIONS: opt }),
<ide> maxBuffer: 1e6,
<ide> };
<ide><path>test/parallel/test-preload-print-process-argv.js
<ide> // This tests that process.argv is the same in the preloaded module
<ide> // and the user module.
<ide>
<del>const common = require('../common');
<add>require('../common');
<ide>
<ide> const tmpdir = require('../common/tmpdir');
<ide> const assert = require('assert');
<add>const { join } = require('path');
<ide> const { spawnSync } = require('child_process');
<ide> const fs = require('fs');
<ide>
<del>if (!common.isMainThread) {
<del> common.skip('Cannot chdir to the tmp directory in workers');
<del>}
<del>
<ide> tmpdir.refresh();
<ide>
<del>process.chdir(tmpdir.path);
<ide> fs.writeFileSync(
<del> 'preload.js',
<add> join(tmpdir.path, 'preload.js'),
<ide> 'console.log(JSON.stringify(process.argv));',
<ide> 'utf-8');
<ide>
<ide> fs.writeFileSync(
<del> 'main.js',
<add> join(tmpdir.path, 'main.js'),
<ide> 'console.log(JSON.stringify(process.argv));',
<ide> 'utf-8');
<ide>
<del>const child = spawnSync(process.execPath, ['-r', './preload.js', 'main.js']);
<add>const child = spawnSync(process.execPath, ['-r', './preload.js', 'main.js'],
<add> { cwd: tmpdir.path });
<ide>
<ide> if (child.status !== 0) {
<ide> console.log(child.stderr.toString());
<ide><path>test/parallel/test-preload.js
<ide> const fixtures = require('../common/fixtures');
<ide> // Refs: https://github.com/nodejs/node/pull/2253
<ide> if (common.isSunOS)
<ide> common.skip('unreliable on SunOS');
<del>if (!common.isMainThread)
<del> common.skip('process.chdir is not available in Workers');
<ide>
<ide> const assert = require('assert');
<ide> const childProcess = require('child_process');
<ide> childProcess.exec(
<ide> );
<ide>
<ide> // Test that preloading with a relative path works
<del>process.chdir(fixtures.fixturesDir);
<ide> childProcess.exec(
<ide> `"${nodeBinary}" ${preloadOption(['./printA.js'])} "${fixtureB}"`,
<add> { cwd: fixtures.fixturesDir },
<ide> common.mustCall(function(err, stdout, stderr) {
<ide> assert.ifError(err);
<ide> assert.strictEqual(stdout, 'A\nB\n');
<ide> if (common.isWindows) {
<ide> // https://github.com/nodejs/node/issues/21918
<ide> childProcess.exec(
<ide> `"${nodeBinary}" ${preloadOption(['.\\printA.js'])} "${fixtureB}"`,
<add> { cwd: fixtures.fixturesDir },
<ide> common.mustCall(function(err, stdout, stderr) {
<ide> assert.ifError(err);
<ide> assert.strictEqual(stdout, 'A\nB\n');
<ide> if (common.isWindows) {
<ide> }
<ide>
<ide> // https://github.com/nodejs/node/issues/1691
<del>process.chdir(fixtures.fixturesDir);
<ide> childProcess.exec(
<ide> `"${nodeBinary}" --require ` +
<ide> `"${fixtures.path('cluster-preload.js')}" cluster-preload-test.js`,
<add> { cwd: fixtures.fixturesDir },
<ide> function(err, stdout, stderr) {
<ide> assert.ifError(err);
<ide> assert.ok(/worker terminated with code 43/.test(stdout));
<ide><path>test/parallel/test-tick-processor-arguments.js
<ide> const fs = require('fs');
<ide> const assert = require('assert');
<ide> const { spawnSync } = require('child_process');
<ide>
<del>if (!common.isMainThread)
<del> common.skip('chdir not available in workers');
<ide> if (!common.enoughTestMem)
<ide> common.skip('skipped due to memory requirements');
<ide> if (common.isAIX)
<ide> common.skip('does not work on AIX');
<ide>
<ide> tmpdir.refresh();
<del>process.chdir(tmpdir.path);
<ide>
<ide> // Generate log file.
<del>spawnSync(process.execPath, [ '--prof', '-p', '42' ]);
<add>spawnSync(process.execPath, [ '--prof', '-p', '42' ], { cwd: tmpdir.path });
<ide>
<del>const logfile = fs.readdirSync('.').filter((name) => name.endsWith('.log'))[0];
<add>const files = fs.readdirSync(tmpdir.path);
<add>const logfile = files.filter((name) => /\.log$/.test(name))[0];
<ide> assert(logfile);
<ide>
<ide> // Make sure that the --preprocess argument is passed through correctly,
<ide> assert(logfile);
<ide> const { stdout } = spawnSync(
<ide> process.execPath,
<ide> [ '--prof-process', '--preprocess', logfile ],
<del> { encoding: 'utf8' });
<add> { cwd: tmpdir.path, encoding: 'utf8' });
<ide>
<ide> // Make sure that the result is valid JSON.
<ide> JSON.parse(stdout);
<ide><path>test/parallel/test-trace-events-environment.js
<ide> const tmpdir = require('../common/tmpdir');
<ide>
<ide> // This tests the emission of node.environment trace events
<ide>
<del>if (!common.isMainThread)
<del> common.skip('process.chdir is not available in Workers');
<del>
<ide> const names = new Set([
<ide> 'Environment',
<ide> 'RunAndClearNativeImmediates',
<ide> if (process.argv[2] === 'child') {
<ide> setTimeout(() => { 1 + 1; }, 1);
<ide> } else {
<ide> tmpdir.refresh();
<del> process.chdir(tmpdir.path);
<ide>
<ide> const proc = cp.fork(__filename,
<ide> [ 'child' ], {
<add> cwd: tmpdir.path,
<ide> execArgv: [
<ide> '--trace-event-categories',
<ide> 'node.environment'
<ide><path>test/parallel/test-worker-prof.js
<ide> 'use strict';
<del>const common = require('../common');
<add>require('../common');
<ide> const tmpdir = require('../common/tmpdir');
<ide> const fs = require('fs');
<ide> const assert = require('assert');
<add>const { join } = require('path');
<ide> const { spawnSync } = require('child_process');
<ide> const { Worker } = require('worker_threads');
<ide>
<del>if (!common.isMainThread)
<del> common.skip('process.chdir is not available in Workers');
<del>
<ide> // Test that --prof also tracks Worker threads.
<ide> // Refs: https://github.com/nodejs/node/issues/24016
<ide>
<ide> if (process.argv[2] === 'child') {
<ide> }
<ide>
<ide> tmpdir.refresh();
<del>process.chdir(tmpdir.path);
<del>spawnSync(process.execPath, ['--prof', __filename, 'child']);
<del>const logfiles = fs.readdirSync('.').filter((name) => /\.log$/.test(name));
<add>spawnSync(process.execPath, ['--prof', __filename, 'child'],
<add> { cwd: tmpdir.path });
<add>const files = fs.readdirSync(tmpdir.path);
<add>const logfiles = files.filter((name) => /\.log$/.test(name));
<ide> assert.strictEqual(logfiles.length, 2); // Parent thread + child thread.
<ide>
<ide> for (const logfile of logfiles) {
<del> const lines = fs.readFileSync(logfile, 'utf8').split('\n');
<add> const lines = fs.readFileSync(join(tmpdir.path, logfile), 'utf8').split('\n');
<ide> const ticks = lines.filter((line) => /^tick,/.test(line)).length;
<ide>
<ide> // Test that at least 15 ticks have been recorded for both parent and child | 8 |
Javascript | Javascript | remove unicode character from ellipsecurve.js | 57a483cfb8dbeb3e7a33af69f07bf10e6ec92e7d | <ide><path>src/extras/curves/EllipseCurve.js
<ide> function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockw
<ide> this.xRadius = xRadius || 1;
<ide> this.yRadius = yRadius || 1;
<ide>
<del> this.aStartAngle = aStartAngle || 0;
<add> this.aStartAngle = aStartAngle || 0;
<ide> this.aEndAngle = aEndAngle || 2 * Math.PI;
<ide>
<ide> this.aClockwise = aClockwise || false; | 1 |
Ruby | Ruby | terminate processing on bounce | b9e220aa41674c974f5a1e8c4fe1684596cab740 | <ide><path>lib/action_mailbox/callbacks.rb
<ide> module Callbacks
<ide> extend ActiveSupport::Concern
<ide> include ActiveSupport::Callbacks
<ide>
<add> TERMINATOR = ->(target, chain) do
<add> terminate = true
<add>
<add> catch(:abort) do
<add> chain.call
<add> terminate = target.inbound_email.bounced?
<add> end
<add>
<add> terminate
<add> end
<add>
<ide> included do
<del> define_callbacks :process
<add> define_callbacks :process, terminator: TERMINATOR
<ide> end
<ide>
<ide> module ClassMethods
<ide><path>test/unit/mailbox/callbacks_test.rb
<ide> def process
<ide> end
<ide> end
<ide>
<add>class BouncingCallbackMailbox < ActionMailbox::Base
<add> before_processing { $before_processing = [ "Pre-bounce" ] }
<add>
<add> before_processing do
<add> bounce_with BounceMailer.bounce(to: mail.from)
<add> $before_processing << "Bounce"
<add> end
<add>
<add> before_processing { $before_processing << "Post-bounce" }
<add>
<add> def process
<add> $processed = mail.subject
<add> end
<add>end
<add>
<ide> class ActionMailbox::Base::CallbacksTest < ActiveSupport::TestCase
<ide> setup do
<ide> $before_processing = $after_processing = $around_processing = $processed = false
<ide> class ActionMailbox::Base::CallbacksTest < ActiveSupport::TestCase
<ide> assert_equal "Ran that too!", $after_processing
<ide> assert_equal "Ran that as well!", $around_processing
<ide> end
<add>
<add> test "bouncing in a callback terminates processing" do
<add> BouncingCallbackMailbox.receive @inbound_email
<add> assert @inbound_email.bounced?
<add> assert_equal [ "Pre-bounce", "Bounce" ], $before_processing
<add> assert_not $processed
<add> end
<ide> end | 2 |
PHP | PHP | fix fulltext column generation | 0d9ef854ff6633e97adaaba41efcef30a6395274 | <ide><path>lib/Cake/Model/Datasource/Database/Mysql.php
<ide> public function buildIndex($indexes, $table = null) {
<ide> }
<ide> $name = $this->startQuote . $name . $this->endQuote;
<ide> }
<del> // length attribute only used for MySQL datasource, for TEXT/BLOB index columns
<add> if (isset($value['type']) && strtolower($value['type']) === 'fulltext') {
<add> $out .= 'FULLTEXT ';
<add> }
<ide> $out .= 'KEY ' . $name . ' (';
<add>
<ide> if (is_array($value['column'])) {
<ide> if (isset($value['length'])) {
<ide> $vals = array();
<ide><path>lib/Cake/Model/Datasource/DboSource.php
<ide> public function buildIndex($indexes, $table = null) {
<ide> } else {
<ide> if (!empty($value['unique'])) {
<ide> $out .= 'UNIQUE ';
<del> } elseif (!empty($value['type']) && strtoupper($value['type']) === 'FULLTEXT') {
<del> $out .= 'FULLTEXT ';
<ide> }
<ide> $name = $this->startQuote . $name . $this->endQuote;
<ide> }
<ide><path>lib/Cake/Test/Case/Model/Datasource/Database/MysqlTest.php
<ide> public function testBuildIndex() {
<ide> );
<ide> $result = $this->Dbo->buildIndex($data);
<ide> $expected = array('FULLTEXT KEY `MyFtIndex` (`name`, `description`)');
<add> $this->assertEquals($expected, $result);
<ide>
<ide> $data = array(
<ide> 'MyTextIndex' => array('column' => 'text_field', 'length' => array('text_field' => 20)) | 3 |
Javascript | Javascript | handle prettier error | 1d1f7038ec1c9e49408de7629bed53410c6b63a6 | <ide><path>scripts/prettier/index.js
<ide> var changedFiles = new Set(
<ide> );
<ide>
<ide> let didWarn = false;
<add>let didError = false;
<ide> Object.keys(config).forEach(key => {
<ide> const patterns = config[key].patterns;
<ide> const options = config[key].options;
<ide> Object.keys(config).forEach(key => {
<ide>
<ide> const args = Object.assign({}, defaultOptions, options);
<ide> files.forEach(file => {
<del> const input = fs.readFileSync(file, 'utf8');
<del> if (shouldWrite) {
<del> const output = prettier.format(input, args);
<del> if (output !== input) {
<del> fs.writeFileSync(file, output, 'utf8');
<del> }
<del> } else {
<del> if (!prettier.check(input, args)) {
<del> if (!didWarn) {
<del> console.log(
<del> '\n' +
<del> chalk.red(
<del> ` This project uses prettier to format all JavaScript code.\n`
<del> ) +
<del> chalk.dim(` Please run `) +
<del> chalk.reset('yarn prettier-all') +
<del> chalk.dim(
<del> ` and add changes to files listed below to your commit:`
<del> ) +
<del> `\n\n`
<del> );
<del> didWarn = true;
<add> try {
<add> const input = fs.readFileSync(file, 'utf8');
<add> if (shouldWrite) {
<add> const output = prettier.format(input, args);
<add> if (output !== input) {
<add> fs.writeFileSync(file, output, 'utf8');
<add> }
<add> } else {
<add> if (!prettier.check(input, args)) {
<add> if (!didWarn) {
<add> console.log(
<add> '\n' +
<add> chalk.red(
<add> ` This project uses prettier to format all JavaScript code.\n`
<add> ) +
<add> chalk.dim(` Please run `) +
<add> chalk.reset('yarn prettier-all') +
<add> chalk.dim(
<add> ` and add changes to files listed below to your commit:`
<add> ) +
<add> `\n\n`
<add> );
<add> didWarn = true;
<add> }
<add> console.log(file);
<ide> }
<del> console.log(file);
<ide> }
<add> } catch (error) {
<add> didError = true;
<add> console.log('\n\n' + error.message);
<add> console.log(file);
<ide> }
<ide> });
<ide> });
<ide>
<del>if (didWarn) {
<add>if (didWarn || didError) {
<ide> process.exit(1);
<ide> } | 1 |
Text | Text | add note about field level validation, fixes | 4704da9a1acf3cbf1b1b1396821fa6ee61e0ffce | <ide><path>docs/api-guide/serializers.md
<ide> Your `validate_<field_name>` methods should return the validated value or raise
<ide> raise serializers.ValidationError("Blog post is not about Django")
<ide> return value
<ide>
<add>---
<add>
<add>**Note:** If your `<field_name>` is declared on your serializer with the parameter `required=False` then this validation step will not take place if the field is not included.
<add>
<add>---
<add>
<ide> #### Object-level validation
<ide>
<ide> To do any other validation that requires access to multiple fields, add a method called `.validate()` to your `Serializer` subclass. This method takes a single argument, which is a dictionary of field values. It should raise a `ValidationError` if necessary, or just return the validated values. For example: | 1 |
Java | Java | fix broken test in annotationutilstests | 666d1cecc8e1e347e69bc9b58333893dbe63c0be | <ide><path>spring-core/src/test/java/org/springframework/core/annotation/AnnotationUtilsTests.java
<ide> public void findMethodAnnotationOnBridgeMethod() throws Exception {
<ide> assertNull(m.getAnnotation(Order.class));
<ide> assertNull(getAnnotation(m, Order.class));
<ide> assertNotNull(findAnnotation(m, Order.class));
<del> assertNull(m.getAnnotation(Transactional.class));
<add> // TODO: actually found on OpenJDK 8 b99 and higher!
<add> // assertNull(m.getAnnotation(Transactional.class));
<ide> assertNotNull(getAnnotation(m, Transactional.class));
<ide> assertNotNull(findAnnotation(m, Transactional.class));
<ide> } | 1 |
Text | Text | add explanation about comments | ab50b03c38ef1d6fbc498dc7f220e2e095507a59 | <ide><path>guide/english/c/hello-world/index.md
<ide> To write on console you can use the function `printf()` contained in the library
<ide>
<ide> int main(void)
<ide> {
<del> //lines starting with this are called comments, so use them to write notes to the reader about your code!
<del>
<add> printf("hello, world\n"); // lines starting with this (//) are called comments..
<add>
<ide> //this code prints "Hello World!"
<ide> printf("Hello World!\n"); //<-- the \n character prints a newline after the string
<ide>
<ide> return 0;
<ide> }
<ide> ```
<add>
<ide> ## Explanation
<add>
<ide> * The `#include <stdio.h>` is a preprocessor command. This command tells compiler to include the contents of `stdio.h` (standard input and output) file in the program.
<ide> * The `stdio.h` file contains functions such as `scanf()` and `printf()` to take input and display output respectively.
<ide> * If you use `printf()` function without writing `#include <stdio.h>`, the program will not be compiled.
<add> * Two backslash characters (//) are used to _comment_ the code, for better understandability. Anything after // on a line is ignored while compiling the program.
<ide> * The execution of a C program starts from the `main()` function.
<ide> * The `printf()` is a library function to send formatted output to the screen. In this program, the `printf()` displays `Hello World!` text on the screen.
<ide> * The `\n` in `printf` creates a new line for the forthcoming text.
<ide> * The `return 0;` statement is the "Exit status" of the program. In simple terms, program ends with this statement
<ide>
<add>
<ide> ## Output:
<ide> ```
<ide> >Hello World!
<ide> ```
<add>
<ide> #### More Information
<ide>
<ide> * Conventionally, the first ever program you write is the "hello world" program, be it in any language. | 1 |
Go | Go | update comparison log in container config | e5bed175741461edaa1de5dede0486d9f6afd328 | <ide><path>daemon/daemon_unix.go
<ide> func verifyContainerResources(resources *containertypes.Resources, sysInfo *sysi
<ide> return warnings, fmt.Errorf("You should always set the Memory limit when using Memoryswap limit, see usage")
<ide> }
<ide> if resources.MemorySwappiness != nil && *resources.MemorySwappiness != -1 && !sysInfo.MemorySwappiness {
<del> warnings = append(warnings, "Your kernel does not support memory swappiness capabilities, memory swappiness discarded.")
<del> logrus.Warn("Your kernel does not support memory swappiness capabilities, memory swappiness discarded.")
<add> warnings = append(warnings, "Your kernel does not support memory swappiness capabilities. Memory swappiness discarded.")
<add> logrus.Warn("Your kernel does not support memory swappiness capabilities. Memory swappiness discarded.")
<ide> resources.MemorySwappiness = nil
<ide> }
<ide> if resources.MemorySwappiness != nil {
<ide> func verifyContainerResources(resources *containertypes.Resources, sysInfo *sysi
<ide> return warnings, fmt.Errorf("Minimum memory reservation allowed is 4MB")
<ide> }
<ide> if resources.Memory > 0 && resources.MemoryReservation > 0 && resources.Memory < resources.MemoryReservation {
<del> return warnings, fmt.Errorf("Minimum memory limit should be larger than memory reservation limit, see usage")
<add> return warnings, fmt.Errorf("Minimum memory limit can not be less than memory reservation limit, see usage")
<ide> }
<ide> if resources.KernelMemory > 0 && !sysInfo.KernelMemory {
<ide> warnings = append(warnings, "Your kernel does not support kernel memory limit capabilities. Limitation discarded.")
<ide> func verifyContainerResources(resources *containertypes.Resources, sysInfo *sysi
<ide> // only produce warnings if the setting wasn't to *disable* the OOM Kill; no point
<ide> // warning the caller if they already wanted the feature to be off
<ide> if *resources.OomKillDisable {
<del> warnings = append(warnings, "Your kernel does not support OomKillDisable, OomKillDisable discarded.")
<del> logrus.Warn("Your kernel does not support OomKillDisable, OomKillDisable discarded.")
<add> warnings = append(warnings, "Your kernel does not support OomKillDisable. OomKillDisable discarded.")
<add> logrus.Warn("Your kernel does not support OomKillDisable. OomKillDisable discarded.")
<ide> }
<ide> resources.OomKillDisable = nil
<ide> }
<ide>
<ide> if resources.PidsLimit != 0 && !sysInfo.PidsLimit {
<del> warnings = append(warnings, "Your kernel does not support pids limit capabilities, pids limit discarded.")
<del> logrus.Warn("Your kernel does not support pids limit capabilities, pids limit discarded.")
<add> warnings = append(warnings, "Your kernel does not support pids limit capabilities. Pids limit discarded.")
<add> logrus.Warn("Your kernel does not support pids limit capabilities. Pids limit discarded.")
<ide> resources.PidsLimit = 0
<ide> }
<ide>
<ide> func verifyContainerResources(resources *containertypes.Resources, sysInfo *sysi
<ide> return warnings, fmt.Errorf("Invalid QoS settings: %s does not support Maximum IO Bandwidth or Maximum IO IOps", runtime.GOOS)
<ide> }
<ide> if len(resources.BlkioWeightDevice) > 0 && !sysInfo.BlkioWeightDevice {
<del> warnings = append(warnings, "Your kernel does not support Block I/O weight_device.")
<del> logrus.Warn("Your kernel does not support Block I/O weight_device. Weight-device discarded.")
<add> warnings = append(warnings, "Your kernel does not support Block I/O weight-device. Weight-device discarded.")
<add> logrus.Warn("Your kernel does not support Block I/O weight-device. Weight-device discarded.")
<ide> resources.BlkioWeightDevice = []*pblkiodev.WeightDevice{}
<ide> }
<ide> if len(resources.BlkioDeviceReadBps) > 0 && !sysInfo.BlkioReadBpsDevice {
<del> warnings = append(warnings, "Your kernel does not support Block read limit in bytes per second.")
<del> logrus.Warn("Your kernel does not support Block I/O read limit in bytes per second. --device-read-bps discarded.")
<add> warnings = append(warnings, "Your kernel does not support Block read limit in bytes per second. Device read bps discarded.")
<add> logrus.Warn("Your kernel does not support Block I/O read limit in bytes per second. Device read bps discarded.")
<ide> resources.BlkioDeviceReadBps = []*pblkiodev.ThrottleDevice{}
<ide> }
<ide> if len(resources.BlkioDeviceWriteBps) > 0 && !sysInfo.BlkioWriteBpsDevice {
<del> warnings = append(warnings, "Your kernel does not support Block write limit in bytes per second.")
<del> logrus.Warn("Your kernel does not support Block I/O write limit in bytes per second. --device-write-bps discarded.")
<add> warnings = append(warnings, "Your kernel does not support Block write limit in bytes per second. Device write bps discarded.")
<add> logrus.Warn("Your kernel does not support Block I/O write limit in bytes per second. Device write bps discarded.")
<ide> resources.BlkioDeviceWriteBps = []*pblkiodev.ThrottleDevice{}
<ide> }
<ide> if len(resources.BlkioDeviceReadIOps) > 0 && !sysInfo.BlkioReadIOpsDevice {
<del> warnings = append(warnings, "Your kernel does not support Block read limit in IO per second.")
<del> logrus.Warn("Your kernel does not support Block I/O read limit in IO per second. -device-read-iops discarded.")
<add> warnings = append(warnings, "Your kernel does not support Block read limit in IO per second. Device read iops discarded.")
<add> logrus.Warn("Your kernel does not support Block I/O read limit in IO per second. Device read iops discarded.")
<ide> resources.BlkioDeviceReadIOps = []*pblkiodev.ThrottleDevice{}
<ide> }
<ide> if len(resources.BlkioDeviceWriteIOps) > 0 && !sysInfo.BlkioWriteIOpsDevice {
<del> warnings = append(warnings, "Your kernel does not support Block write limit in IO per second.")
<del> logrus.Warn("Your kernel does not support Block I/O write limit in IO per second. --device-write-iops discarded.")
<add> warnings = append(warnings, "Your kernel does not support Block write limit in IO per second. Device write iops discarded.")
<add> logrus.Warn("Your kernel does not support Block I/O write limit in IO per second. Device write iops discarded.")
<ide> resources.BlkioDeviceWriteIOps = []*pblkiodev.ThrottleDevice{}
<ide> }
<ide>
<ide> func verifyPlatformContainerSettings(daemon *Daemon, hostConfig *containertypes.
<ide> warnings = append(warnings, w...)
<ide>
<ide> if hostConfig.ShmSize < 0 {
<del> return warnings, fmt.Errorf("SHM size must be greater than 0")
<add> return warnings, fmt.Errorf("SHM size can not be less than 0")
<ide> }
<ide>
<ide> if hostConfig.OomScoreAdj < -1000 || hostConfig.OomScoreAdj > 1000 {
<ide><path>daemon/daemon_windows.go
<ide> func verifyContainerResources(resources *containertypes.Resources, sysInfo *sysi
<ide> // TODO Windows: Add more validation of resource settings not supported on Windows
<ide>
<ide> if resources.BlkioWeight > 0 {
<del> warnings = append(warnings, "Windows does not support Block I/O weight. Weight discarded.")
<del> logrus.Warn("Windows does not support Block I/O weight. --blkio-weight discarded.")
<add> warnings = append(warnings, "Windows does not support Block I/O weight. Block I/O weight discarded.")
<add> logrus.Warn("Windows does not support Block I/O weight. Block I/O weight discarded.")
<ide> resources.BlkioWeight = 0
<ide> }
<ide> if len(resources.BlkioWeightDevice) > 0 {
<del> warnings = append(warnings, "Windows does not support Block I/O weight_device.")
<del> logrus.Warn("Windows does not support Block I/O weight_device. --blkio-weight-device discarded.")
<add> warnings = append(warnings, "Windows does not support Block I/O weight-device. Weight-device discarded.")
<add> logrus.Warn("Windows does not support Block I/O weight-device. Weight-device discarded.")
<ide> resources.BlkioWeightDevice = []*pblkiodev.WeightDevice{}
<ide> }
<ide> if len(resources.BlkioDeviceReadBps) > 0 {
<del> warnings = append(warnings, "Windows does not support Block read limit in bytes per second.")
<del> logrus.Warn("Windows does not support Block I/O read limit in bytes per second. --device-read-bps discarded.")
<add> warnings = append(warnings, "Windows does not support Block read limit in bytes per second. Device read bps discarded.")
<add> logrus.Warn("Windows does not support Block I/O read limit in bytes per second. Device read bps discarded.")
<ide> resources.BlkioDeviceReadBps = []*pblkiodev.ThrottleDevice{}
<ide> }
<ide> if len(resources.BlkioDeviceWriteBps) > 0 {
<del> warnings = append(warnings, "Windows does not support Block write limit in bytes per second.")
<del> logrus.Warn("Windows does not support Block I/O write limit in bytes per second. --device-write-bps discarded.")
<add> warnings = append(warnings, "Windows does not support Block write limit in bytes per second. Device write bps discarded.")
<add> logrus.Warn("Windows does not support Block I/O write limit in bytes per second. Device write bps discarded.")
<ide> resources.BlkioDeviceWriteBps = []*pblkiodev.ThrottleDevice{}
<ide> }
<ide> if len(resources.BlkioDeviceReadIOps) > 0 {
<del> warnings = append(warnings, "Windows does not support Block read limit in IO per second.")
<del> logrus.Warn("Windows does not support Block I/O read limit in IO per second. -device-read-iops discarded.")
<add> warnings = append(warnings, "Windows does not support Block read limit in IO per second. Device read iops discarded.")
<add> logrus.Warn("Windows does not support Block I/O read limit in IO per second. Device read iops discarded.")
<ide> resources.BlkioDeviceReadIOps = []*pblkiodev.ThrottleDevice{}
<ide> }
<ide> if len(resources.BlkioDeviceWriteIOps) > 0 {
<del> warnings = append(warnings, "Windows does not support Block write limit in IO per second.")
<del> logrus.Warn("Windows does not support Block I/O write limit in IO per second. --device-write-iops discarded.")
<add> warnings = append(warnings, "Windows does not support Block write limit in IO per second. Device write iops discarded.")
<add> logrus.Warn("Windows does not support Block I/O write limit in IO per second. Device write iops discarded.")
<ide> resources.BlkioDeviceWriteIOps = []*pblkiodev.ThrottleDevice{}
<ide> }
<ide> return warnings, nil
<ide><path>integration-cli/docker_api_containers_test.go
<ide> func (s *DockerSuite) TestPostContainersCreateShmSizeNegative(c *check.C) {
<ide> status, body, err := sockRequest("POST", "/containers/create", config)
<ide> c.Assert(err, check.IsNil)
<ide> c.Assert(status, check.Equals, http.StatusInternalServerError)
<del> c.Assert(getErrorMessage(c, body), checker.Contains, "SHM size must be greater than 0")
<add> c.Assert(getErrorMessage(c, body), checker.Contains, "SHM size can not be less than 0")
<ide> }
<ide>
<ide> func (s *DockerSuite) TestPostContainersCreateShmSizeHostConfigOmitted(c *check.C) {
<ide><path>integration-cli/docker_cli_run_unix_test.go
<ide> func (s *DockerSuite) TestRunWithMemoryReservationInvalid(c *check.C) {
<ide> testRequires(c, memoryReservationSupport)
<ide> out, _, err := dockerCmdWithError("run", "-m", "500M", "--memory-reservation", "800M", "busybox", "true")
<ide> c.Assert(err, check.NotNil)
<del> expected := "Minimum memory limit should be larger than memory reservation limit"
<add> expected := "Minimum memory limit can not be less than memory reservation limit"
<ide> c.Assert(strings.TrimSpace(out), checker.Contains, expected, check.Commentf("run container should fail with invalid memory reservation"))
<ide>
<ide> out, _, err = dockerCmdWithError("run", "--memory-reservation", "1k", "busybox", "true") | 4 |
Javascript | Javascript | tweak some comments | df913fe96b0bb0b190ddfab111136a7b868b8350 | <ide><path>src/geo/circle.js
<ide> function d3_geo_circleClip(degrees, rotate) {
<ide> });
<ide> // Create a circular linked list using the intersected segment start and
<ide> // end points, sorted by relative angles.
<add> // TODO sort by angle first, then set in/out flags to avoid
<add> // self-intersection/precision problems.
<ide> segments.forEach(function(segment) {
<ide> var p0 = segment[0],
<ide> p1 = segment[segment.length - 1];
<ide> function d3_geo_circleClip(degrees, rotate) {
<ide> }
<ide> };
<ide>
<del>// Convert spherical (degrees) to normalized Cartesian coordinates, relative to
<del>// a Cartesian origin.
<add>// Convert spherical to normalized Cartesian coordinates, relative to a
<add>// Cartesian origin.
<ide> function d3_geo_circleCartesian(point, origin) {
<ide> var p0 = point[0],
<ide> p1 = point[1],
<ide> function d3_geo_circleCartesian(point, origin) {
<ide> Math.sin(p1) - origin[2]];
<ide> }
<ide>
<del>// Convert from Cartesian to spherical coordinates (in degrees).
<add>// Convert from Cartesian to spherical coordinates.
<ide> function d3_geo_circleSpherical(point) {
<ide> return [
<ide> Math.atan2(point[1], point[0]), | 1 |
Java | Java | add sni support in netty4clienthttprequestfactory | 0c99346829b19a65fb435fb2557db3b2427de54b | <ide><path>spring-web/src/main/java/org/springframework/http/client/Netty4ClientHttpRequestFactory.java
<ide> * <p>Allows to use a pre-configured {@link EventLoopGroup} instance: useful for
<ide> * sharing across multiple clients.
<ide> *
<add> * <p>Note that this implementation consistently closes the HTTP connection on each
<add> * request.
<add> *
<ide> * @author Arjen Poutsma
<ide> * @author Rossen Stoyanchev
<ide> * @author Brian Clozel
<ide> public class Netty4ClientHttpRequestFactory implements ClientHttpRequestFactory,
<ide>
<ide> private volatile Bootstrap bootstrap;
<ide>
<del> private volatile Bootstrap sslBootstrap;
<del>
<ide>
<ide> /**
<ide> * Create a new {@code Netty4ClientHttpRequestFactory} with a default
<ide> private Netty4ClientHttpRequest createRequestInternal(URI uri, HttpMethod httpMe
<ide> private Bootstrap getBootstrap(URI uri) {
<ide> boolean isSecure = (uri.getPort() == 443 || "https".equalsIgnoreCase(uri.getScheme()));
<ide> if (isSecure) {
<del> if (this.sslBootstrap == null) {
<del> this.sslBootstrap = buildBootstrap(true);
<del> }
<del> return this.sslBootstrap;
<add> return buildBootstrap(uri, true);
<ide> }
<ide> else {
<ide> if (this.bootstrap == null) {
<del> this.bootstrap = buildBootstrap(false);
<add> this.bootstrap = buildBootstrap(uri, false);
<ide> }
<ide> return this.bootstrap;
<ide> }
<ide> }
<ide>
<del> private Bootstrap buildBootstrap(boolean isSecure) {
<add> private Bootstrap buildBootstrap(URI uri, boolean isSecure) {
<ide> Bootstrap bootstrap = new Bootstrap();
<ide> bootstrap.group(this.eventLoopGroup).channel(NioSocketChannel.class)
<ide> .handler(new ChannelInitializer<SocketChannel>() {
<ide> protected void initChannel(SocketChannel channel) throws Exception {
<ide> ChannelPipeline pipeline = channel.pipeline();
<ide> if (isSecure) {
<ide> Assert.notNull(sslContext, "sslContext should not be null");
<del> pipeline.addLast(sslContext.newHandler(channel.alloc()));
<add> pipeline.addLast(sslContext.newHandler(channel.alloc(), uri.getHost(), uri.getPort()));
<ide> }
<ide> pipeline.addLast(new HttpClientCodec());
<ide> pipeline.addLast(new HttpObjectAggregator(maxResponseSize)); | 1 |
Javascript | Javascript | apply review tasks | c06b0665d26f02fb3c9f37c48c228ca0cbafc99f | <ide><path>lib/NormalModule.js
<ide> class NormalModule extends Module {
<ide> // check if module should not be parsed
<ide> // returns "true" if the module should !not! be parsed
<ide> // returns "false" if the module !must! be parsed
<del> preventParsing(noParseRule, request) {
<add> shouldPreventParsing(noParseRule, request) {
<ide> // if no noParseRule exists, return false
<ide> // the module !must! be parsed.
<ide> if(!noParseRule) {
<ide> class NormalModule extends Module {
<ide> // check if this module should !not! be parsed.
<ide> // if so, exit here;
<ide> const noParseRule = options.module && options.module.noParse;
<del> if(this.preventParsing(noParseRule, this.request)) {
<add> if(this.shouldPreventParsing(noParseRule, this.request)) {
<ide> return callback();
<ide> }
<ide>
<ide> class NormalModule extends Module {
<ide> };
<ide> }
<ide>
<add> /*
<add> * creates the start part of a IIFE around the module to inject a variable name
<add> * (function(...){ <- this part
<add> * }.call(...))
<add> */
<ide> variableInjectionFunctionWrapperStartCode(varNames) {
<del> const openingIIFEParanthesis = "(";
<ide> const args = varNames.join(", ");
<del> return `/* WEBPACK VAR INJECTION */${openingIIFEParanthesis}function(${args}) {`;
<add> return `/* WEBPACK VAR INJECTION */(function(${args}) {`;
<ide> }
<ide>
<ide> contextArgument(block) {
<ide> class NormalModule extends Module {
<ide> }
<ide> return "this";
<ide> }
<add>
<add> /*
<add> * creates the end part of a IIFE around the module to inject a variable name
<add> * (function(...){
<add> * }.call(...)) <- this part
<add> */
<ide> variableInjectionFunctionWrapperEndCode(varExpressions, block) {
<ide> const firstParam = this.contextArgument(block);
<ide> const furtherParams = varExpressions.map(e => e.source()).join(", ");
<del> const closingIIFEParanthesis = ")";
<del> return `}.call(${firstParam}, ${furtherParams})${closingIIFEParanthesis}`;
<add> return `}.call(${firstParam}, ${furtherParams}))`;
<ide> }
<ide>
<ide> splitVariablesInUniqueNamedChunks(vars) {
<del> const chunkCollection = vars.reduce((chunkCol, variable) => {
<del> const nameStore = chunkCol.names;
<del> // if we dont know this variable name yet, add it to the tempChunk and names list
<del> if(nameStore.length === 0 || nameStore.indexOf(variable.name) === -1) {
<del> chunkCol.tempChunk.push(variable);
<del> chunkCol.names.push(variable.name);
<add> return vars.reduce((chunks, variable) => {
<add> const current = chunks[chunks.length - 1];
<add> // check if variable with same name exists already
<add> // if so create a new chunk of variables.
<add> const variableNameAlreadyExists = current.some(v => v.name === variable.name);
<add>
<add> if(variableNameAlreadyExists) {
<add> // start new chunk with current variable
<add> chunks.push([variable]);
<ide> } else {
<del> /**
<del> * We know this variable name already.
<del> * Add current tempChunk to chunks and start a new tempChunk/names list
<del> */
<del> chunkCol.chunks.push(chunkCol.tempChunk);
<del> chunkCol.tempChunk = [variable];
<del> chunkCol.names = [variable.name];
<add> // else add it to current chunk
<add> current.push(variable);
<ide> }
<del> return chunkCol;
<del> }, {
<del> chunks: [],
<del> names: [],
<del> tempChunk: []
<del> });
<del> const finalChunks = chunkCollection.chunks;
<del> if(chunkCollection.tempChunk.length !== 0) {
<del> finalChunks.push(chunkCollection.tempChunk);
<del> }
<del> return finalChunks;
<add> return chunks;
<add> }, [[]]);
<ide> }
<ide>
<ide> sourceBlock(block, availableVars, dependencyTemplates, source, outputOptions, requestShortener) {
<ide> class NormalModule extends Module {
<ide> /**
<ide> * Split all variables up into chunks of unique names.
<ide> * e.g. imagine you have the following variable names that need to be injected:
<del> * [foo, bar, baz, foo, wurst, suppe]
<add> * [foo, bar, baz, foo, some, more]
<ide> * we can not inject "foo" twice, therefore we just make two IIFEs like so:
<ide> * (function(foo, bar, baz){
<del> * (function(foo, wurst, suppe){
<add> * (function(foo, some, more){
<ide> * ...
<ide> * }(...));
<ide> * }(...));
<ide> *
<ide> * "splitVariablesInUniqueNamedChunks" splits the variables shown above up to this:
<del> * [[foo, bar, baz], [foo, wurst, suppe]]
<add> * [[foo, bar, baz], [foo, some, more]]
<ide> */
<ide> const injectionVariableChunks = this.splitVariablesInUniqueNamedChunks(vars);
<ide>
<ide> class NormalModule extends Module {
<ide> source: source,
<ide> hash: hashDigest
<ide> };
<del> const topLevelBlock = this;
<del> this.sourceBlock(this, [], dependencyTemplates, source, outputOptions, requestShortener, topLevelBlock);
<add>
<add> this.sourceBlock(this, [], dependencyTemplates, source, outputOptions, requestShortener);
<ide> return new CachedSource(source);
<ide> }
<ide>
<ide><path>test/NormalModule.test.js
<ide> describe("NormalModule", function() {
<ide> loaders = [];
<ide> resource = "some/resource";
<ide> parser = {
<del> parser() {}
<add> parse() {}
<ide> };
<ide> normalModule = new NormalModule(
<ide> request,
<ide> describe("NormalModule", function() {
<ide> });
<ide> });
<ide> describe("without the module having source", function() {
<del> let expectedSource = "wurst suppe";
<add> let expectedSource = "some source";
<ide> beforeEach(function() {
<ide> normalModule._source = new RawSource(expectedSource);
<ide> });
<ide> describe("NormalModule", function() {
<ide> name: "baz"
<ide> },
<ide> {
<del> name: "wurst"
<add> name: "some"
<ide> },
<ide> {
<del> name: "suppe"
<add> name: "more"
<ide> }
<ide> ];
<ide> });
<ide> describe("NormalModule", function() {
<ide> content = rule + "some-content";
<ide> });
<ide> it("returns true", function() {
<del> normalModule.preventParsing(rule, content).should.eql(true);
<add> normalModule.shouldPreventParsing(rule, content).should.eql(true);
<ide> });
<ide> });
<ide> describe("and the content does not start with the string specified in rule", function() {
<ide> beforeEach(function() {
<ide> content = "some-content";
<ide> });
<ide> it("returns false", function() {
<del> normalModule.preventParsing(rule, content).should.eql(false);
<add> normalModule.shouldPreventParsing(rule, content).should.eql(false);
<ide> });
<ide> });
<ide> });
<ide> describe("NormalModule", function() {
<ide> content = rule + "some-content";
<ide> });
<ide> it("returns true", function() {
<del> normalModule.preventParsing(rule, content).should.eql(true);
<add> normalModule.shouldPreventParsing(rule, content).should.eql(true);
<ide> });
<ide> });
<ide> describe("and the content does not match the rule", function() {
<ide> beforeEach(function() {
<ide> content = "some-content";
<ide> });
<ide> it("returns false", function() {
<del> normalModule.preventParsing(rule, content).should.eql(false);
<add> normalModule.shouldPreventParsing(rule, content).should.eql(false);
<ide> });
<ide> });
<ide> });
<ide> });
<ide>
<del> describe("#preventParsing", function() {
<add> describe("#shouldPreventParsing", function() {
<ide> let applyNoParseRuleSpy;
<ide> beforeEach(function() {
<ide> applyNoParseRuleSpy = sinon.stub();
<ide> normalModule.applyNoParseRule = applyNoParseRuleSpy;
<ide> });
<ide> describe("given no noParseRule", function() {
<ide> it("returns false", function() {
<del> normalModule.preventParsing().should.eql(false);
<add> normalModule.shouldPreventParsing().should.eql(false);
<ide> applyNoParseRuleSpy.callCount.should.eql(0);
<ide> });
<ide> });
<ide> describe("given a noParseRule", function() {
<ide> let returnValOfSpy;
<ide> beforeEach(function() {
<del> returnValOfSpy = Math.random() >= 0.5 ? true : false;
<add> returnValOfSpy = true;
<ide> applyNoParseRuleSpy.returns(returnValOfSpy);
<ide> });
<ide> describe("that is a string", function() {
<ide> it("calls and returns whatever applyNoParseRule returns", function() {
<del> normalModule.preventParsing("some rule").should.eql(returnValOfSpy);
<add> normalModule.shouldPreventParsing("some rule").should.eql(returnValOfSpy);
<ide> applyNoParseRuleSpy.callCount.should.eql(1);
<ide> });
<ide> });
<ide> describe("that is a regex", function() {
<ide> it("calls and returns whatever applyNoParseRule returns", function() {
<del> normalModule.preventParsing("some rule").should.eql(returnValOfSpy);
<add> normalModule.shouldPreventParsing("some rule").should.eql(returnValOfSpy);
<ide> applyNoParseRuleSpy.callCount.should.eql(1);
<ide> });
<ide> });
<ide> describe("NormalModule", function() {
<ide> let someRules;
<ide> beforeEach(function() {
<ide> someRules = [
<del> Math.random() >= 0.5 ? "some rule" : /some rule/,
<del> Math.random() >= 0.5 ? "some rule1" : /some rule1/,
<del> Math.random() >= 0.5 ? "some rule2" : /some rule2/,
<add> "some rule",
<add> /some rule1/,
<add> "some rule2",
<ide> ];
<ide> });
<ide> describe("and none of them match", function() {
<ide> describe("NormalModule", function() {
<ide> applyNoParseRuleSpy.returns(returnValOfSpy);
<ide> });
<ide> it("returns false", function() {
<del> normalModule.preventParsing(someRules).should.eql(returnValOfSpy);
<add> normalModule.shouldPreventParsing(someRules).should.eql(returnValOfSpy);
<ide> applyNoParseRuleSpy.callCount.should.eql(3);
<ide> });
<ide> });
<ide> describe("NormalModule", function() {
<ide> applyNoParseRuleSpy.returns(returnValOfSpy);
<ide> });
<ide> it("returns true", function() {
<del> normalModule.preventParsing(someRules).should.eql(returnValOfSpy);
<add> normalModule.shouldPreventParsing(someRules).should.eql(returnValOfSpy);
<ide> applyNoParseRuleSpy.callCount.should.eql(1);
<ide> });
<ide> });
<ide> describe("NormalModule", function() {
<ide> applyNoParseRuleSpy.onCall(2).returns(true);
<ide> });
<ide> it("returns true", function() {
<del> normalModule.preventParsing(someRules).should.eql(returnValOfSpy);
<add> normalModule.shouldPreventParsing(someRules).should.eql(returnValOfSpy);
<ide> applyNoParseRuleSpy.callCount.should.eql(3);
<ide> });
<ide> }); | 2 |
PHP | PHP | introduce a @prepend for stack | 7869f6b35f6c1dff7b59551682d27dbd30b2a536 | <ide><path>src/Illuminate/View/Compilers/Concerns/CompilesStacks.php
<ide> protected function compileEndpush()
<ide> {
<ide> return '<?php $__env->stopPush(); ?>';
<ide> }
<add>
<add> /**
<add> * Compile the prepend statements into valid PHP.
<add> *
<add> * @param string $expression
<add> * @return string
<add> */
<add> protected function compilePrepend($expression)
<add> {
<add> return "<?php \$__env->startPrepend{$expression}; ?>";
<add> }
<add>
<add> /**
<add> * Compile the end-prepend statements into valid PHP.
<add> *
<add> * @return string
<add> */
<add> protected function compileEndprepend()
<add> {
<add> return '<?php $__env->stopPrepend(); ?>';
<add> }
<ide> }
<ide><path>src/Illuminate/View/Concerns/ManagesStacks.php
<ide> trait ManagesStacks
<ide> */
<ide> protected $pushes = [];
<ide>
<add> /**
<add> * All of the finished, captured prepend sections.
<add> *
<add> * @var array
<add> */
<add> protected $prepends = [];
<add>
<ide> /**
<ide> * The stack of in-progress push sections.
<ide> *
<ide> public function stopPush()
<ide> });
<ide> }
<ide>
<add> /**
<add> * Start prepending content into a push section.
<add> *
<add> * @param string $section
<add> * @param string $content
<add> * @return void
<add> */
<add> public function startPrepend($section, $content = '')
<add> {
<add> if ($content === '') {
<add> if (ob_start()) {
<add> $this->pushStack[] = $section;
<add> }
<add> } else {
<add> $this->extendPrepend($section, $content);
<add> }
<add> }
<add>
<add> /**
<add> * Stop prepending content into a push section.
<add> *
<add> * @return string
<add> * @throws \InvalidArgumentException
<add> */
<add> public function stopPrepend()
<add> {
<add> if (empty($this->pushStack)) {
<add> throw new InvalidArgumentException('Cannot end a prepend stack without first starting one.');
<add> }
<add>
<add> return tap(array_pop($this->pushStack), function ($last) {
<add> $this->extendPrepend($last, ob_get_clean());
<add> });
<add> }
<add>
<ide> /**
<ide> * Append content to a given push section.
<ide> *
<ide> protected function extendPush($section, $content)
<ide> }
<ide> }
<ide>
<add> /**
<add> * Prepend content to a given stack.
<add> *
<add> * @param string $section
<add> * @param string $content
<add> * @return void
<add> */
<add> protected function extendPrepend($section, $content)
<add> {
<add> if (! isset($this->prepends[$section])) {
<add> $this->prepends[$section] = [];
<add> }
<add>
<add> if (! isset($this->prepends[$section][$this->renderCount])) {
<add> $this->prepends[$section][$this->renderCount] = $content;
<add> } else {
<add> $this->prepends[$section][$this->renderCount] = $content.$this->prepends[$section][$this->renderCount];
<add> }
<add> }
<add>
<ide> /**
<ide> * Get the string contents of a push section.
<ide> *
<ide> protected function extendPush($section, $content)
<ide> */
<ide> public function yieldPushContent($section, $default = '')
<ide> {
<add> if (! isset($this->pushes[$section]) && ! isset($this->prepends[$section])) {
<add> return $default;
<add> }
<add>
<add> $output = '';
<add>
<add> if (isset($this->prepends[$section])) {
<add> $output .= implode(array_reverse($this->prepends[$section]));
<add> }
<add>
<ide> if (isset($this->pushes[$section])) {
<del> return implode($this->pushes[$section]);
<add> $output .= implode($this->pushes[$section]);
<ide> }
<ide>
<del> return $default;
<add> return $output;
<ide> }
<ide>
<ide> /** | 2 |
Javascript | Javascript | remove duplicate export | 189d29f39e6de9ccf10682bfd1341819b4a2291f | <ide><path>lib/_http_outgoing.js
<ide> OutgoingMessage.prototype._renderHeaders = function _renderHeaders() {
<ide> };
<ide>
<ide>
<del>exports.OutgoingMessage = OutgoingMessage;
<del>
<del>
<ide> OutgoingMessage.prototype.setTimeout = function setTimeout(msecs, callback) {
<ide>
<ide> if (callback) { | 1 |
PHP | PHP | enable short option for --plugin and --connection | 211146fb7a87ae9e9da2d440aeccea54c6a0b9c5 | <ide><path>lib/Cake/Console/Command/SchemaShell.php
<ide> protected function _run($contents, $event, &$Schema) {
<ide> */
<ide> public function getOptionParser() {
<ide> $plugin = array(
<add> 'short' => 'p',
<ide> 'help' => __d('cake_console', 'The plugin to use.'),
<ide> );
<ide> $connection = array(
<add> 'short' => 'c',
<ide> 'help' => __d('cake_console', 'Set the db config to use.'),
<ide> 'default' => 'default'
<ide> ); | 1 |
PHP | PHP | deprecate unused properties | 18acea6bff82f69de459a8aaf9c657dff6caea4a | <ide><path>src/Database/Query.php
<ide> class Query implements ExpressionInterface, IteratorAggregate
<ide> * The list of query clauses to traverse for generating a SELECT statement
<ide> *
<ide> * @var array<string>
<add> * @deprecated 4.4.3 This property is unused.
<ide> */
<ide> protected $_selectParts = [
<ide> 'with', 'select', 'from', 'join', 'where', 'group', 'having', 'order', 'limit',
<ide> class Query implements ExpressionInterface, IteratorAggregate
<ide> * The list of query clauses to traverse for generating an UPDATE statement
<ide> *
<ide> * @var array<string>
<add> * @deprecated 4.4.3 This property is unused.
<ide> */
<ide> protected $_updateParts = ['with', 'update', 'set', 'where', 'epilog'];
<ide>
<ide> /**
<ide> * The list of query clauses to traverse for generating a DELETE statement
<ide> *
<ide> * @var array<string>
<add> * @deprecated 4.4.3 This property is unused.
<ide> */
<ide> protected $_deleteParts = ['with', 'delete', 'modifier', 'from', 'where', 'epilog'];
<ide>
<ide> /**
<ide> * The list of query clauses to traverse for generating an INSERT statement
<ide> *
<ide> * @var array<string>
<add> * @deprecated 4.4.3 This property is unused.
<ide> */
<ide> protected $_insertParts = ['with', 'insert', 'values', 'epilog'];
<ide> | 1 |
Javascript | Javascript | fix argument order for handlemandatorysetter | b3f0f6ce68833ffc53a72ebc6249908b6fff199d | <ide><path>packages/ember-metal/lib/watch_key.js
<ide> export function watchKey(obj, keyName, meta) {
<ide>
<ide>
<ide> if (Ember.FEATURES.isEnabled('mandatory-setter')) {
<del> var handleMandatorySetter = function handleMandatorySetter(m, keyName, obj) {
<add> var handleMandatorySetter = function handleMandatorySetter(m, obj, keyName) {
<ide> // this x in Y deopts, so keeping it in this function is better;
<ide> if (keyName in obj) {
<ide> m.values[keyName] = obj[keyName]; | 1 |
Go | Go | remove engine/job from graph | fa2c68a89e153cfc82c5af7cbb6d7f15b06e0a8c | <ide><path>api/server/server.go
<ide> func (s *Server) getImagesGet(eng *engine.Engine, version version.Version, w htt
<ide> }
<ide>
<ide> output := utils.NewWriteFlusher(w)
<del> imageExportConfig := &graph.ImageExportConfig{
<del> Engine: eng,
<del> Outstream: output,
<del> }
<add> imageExportConfig := &graph.ImageExportConfig{Outstream: output}
<ide> if name, ok := vars["name"]; ok {
<ide> imageExportConfig.Names = []string{name}
<ide> } else {
<ide> func (s *Server) getImagesGet(eng *engine.Engine, version version.Version, w htt
<ide> }
<ide>
<ide> func (s *Server) postImagesLoad(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<del>
<del> imageLoadConfig := &graph.ImageLoadConfig{
<del> InTar: r.Body,
<del> OutStream: w,
<del> Engine: eng,
<del> }
<del>
<del> return s.daemon.Repositories().Load(imageLoadConfig)
<add> return s.daemon.Repositories().Load(r.Body, w)
<ide> }
<ide>
<ide> func (s *Server) postContainersCreate(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> func (s *Server) getImagesByName(eng *engine.Engine, version version.Version, w
<ide> if vars == nil {
<ide> return fmt.Errorf("Missing parameter")
<ide> }
<del> var job = eng.Job("image_inspect", vars["name"])
<add>
<add> name := vars["name"]
<ide> if version.LessThan("1.12") {
<del> job.SetenvBool("raw", true)
<add> imageInspectRaw, err := s.daemon.Repositories().LookupRaw(name)
<add> if err != nil {
<add> return err
<add> }
<add>
<add> return writeJSON(w, http.StatusOK, imageInspectRaw)
<ide> }
<del> streamJSON(job.Stdout, w, false)
<del> return job.Run()
<add>
<add> imageInspect, err := s.daemon.Repositories().Lookup(name)
<add> if err != nil {
<add> return err
<add> }
<add>
<add> return writeJSON(w, http.StatusOK, imageInspect)
<ide> }
<ide>
<ide> func (s *Server) postBuild(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide><path>api/server/server_unit_test.go
<del>package server
<del>
<del>import (
<del> "encoding/json"
<del> "fmt"
<del> "io"
<del> "net/http"
<del> "net/http/httptest"
<del> "testing"
<del>
<del> "github.com/docker/docker/api"
<del> "github.com/docker/docker/engine"
<del> "github.com/docker/docker/pkg/version"
<del>)
<del>
<del>func TestHttpError(t *testing.T) {
<del> r := httptest.NewRecorder()
<del> httpError(r, fmt.Errorf("No such method"))
<del> if r.Code != http.StatusNotFound {
<del> t.Fatalf("Expected %d, got %d", http.StatusNotFound, r.Code)
<del> }
<del>
<del> r = httptest.NewRecorder()
<del> httpError(r, fmt.Errorf("This accound hasn't been activated"))
<del> if r.Code != http.StatusForbidden {
<del> t.Fatalf("Expected %d, got %d", http.StatusForbidden, r.Code)
<del> }
<del>
<del> r = httptest.NewRecorder()
<del> httpError(r, fmt.Errorf("Some error"))
<del> if r.Code != http.StatusInternalServerError {
<del> t.Fatalf("Expected %d, got %d", http.StatusInternalServerError, r.Code)
<del> }
<del>}
<del>
<del>func TestGetImagesByName(t *testing.T) {
<del> eng := engine.New()
<del> name := "image_name"
<del> var called bool
<del> eng.Register("image_inspect", func(job *engine.Job) error {
<del> called = true
<del> if job.Args[0] != name {
<del> t.Fatalf("name != '%s': %#v", name, job.Args[0])
<del> }
<del> if api.APIVERSION.LessThan("1.12") && !job.GetenvBool("dirty") {
<del> t.Fatal("dirty env variable not set")
<del> } else if api.APIVERSION.GreaterThanOrEqualTo("1.12") && job.GetenvBool("dirty") {
<del> t.Fatal("dirty env variable set when it shouldn't")
<del> }
<del> v := &engine.Env{}
<del> v.SetBool("dirty", true)
<del> if _, err := v.WriteTo(job.Stdout); err != nil {
<del> return err
<del> }
<del> return nil
<del> })
<del> r := serveRequest("GET", "/images/"+name+"/json", nil, eng, t)
<del> if !called {
<del> t.Fatal("handler was not called")
<del> }
<del> if r.HeaderMap.Get("Content-Type") != "application/json" {
<del> t.Fatalf("%#v\n", r)
<del> }
<del> var stdoutJson interface{}
<del> if err := json.Unmarshal(r.Body.Bytes(), &stdoutJson); err != nil {
<del> t.Fatalf("%#v", err)
<del> }
<del> if stdoutJson.(map[string]interface{})["dirty"].(float64) != 1 {
<del> t.Fatalf("%#v", stdoutJson)
<del> }
<del>}
<del>
<del>func serveRequest(method, target string, body io.Reader, eng *engine.Engine, t *testing.T) *httptest.ResponseRecorder {
<del> return serveRequestUsingVersion(method, target, api.APIVERSION, body, eng, t)
<del>}
<del>
<del>func serveRequestUsingVersion(method, target string, version version.Version, body io.Reader, eng *engine.Engine, t *testing.T) *httptest.ResponseRecorder {
<del> r := httptest.NewRecorder()
<del> req, err := http.NewRequest(method, target, body)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> ServeRequest(eng, version, r, req)
<del> return r
<del>}
<del>
<del>func readEnv(src io.Reader, t *testing.T) *engine.Env {
<del> out := engine.NewOutput()
<del> v, err := out.AddEnv()
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> if _, err := io.Copy(out, src); err != nil {
<del> t.Fatal(err)
<del> }
<del> out.Close()
<del> return v
<del>}
<del>
<del>func assertContentType(recorder *httptest.ResponseRecorder, contentType string, t *testing.T) {
<del> if recorder.HeaderMap.Get("Content-Type") != contentType {
<del> t.Fatalf("%#v\n", recorder)
<del> }
<del>}
<ide><path>daemon/daemon.go
<ide> type Daemon struct {
<ide>
<ide> // Install installs daemon capabilities to eng.
<ide> func (daemon *Daemon) Install(eng *engine.Engine) error {
<del> if err := daemon.Repositories().Install(eng); err != nil {
<del> return err
<del> }
<ide> // FIXME: this hack is necessary for legacy integration tests to access
<ide> // the daemon object.
<ide> eng.HackSetGlobalVar("httpapi.daemon", daemon)
<ide><path>graph/export.go
<ide> import (
<ide> "path"
<ide>
<ide> "github.com/Sirupsen/logrus"
<del> "github.com/docker/docker/engine"
<ide> "github.com/docker/docker/pkg/archive"
<ide> "github.com/docker/docker/pkg/parsers"
<ide> "github.com/docker/docker/registry"
<ide> import (
<ide> type ImageExportConfig struct {
<ide> Names []string
<ide> Outstream io.Writer
<del> Engine *engine.Engine
<ide> }
<ide>
<ide> func (s *TagStore) ImageExport(imageExportConfig *ImageExportConfig) error {
<ide> func (s *TagStore) ImageExport(imageExportConfig *ImageExportConfig) error {
<ide> // this is a base repo name, like 'busybox'
<ide> for tag, id := range rootRepo {
<ide> addKey(name, tag, id)
<del> if err := s.exportImage(imageExportConfig.Engine, id, tempdir); err != nil {
<add> if err := s.exportImage(id, tempdir); err != nil {
<ide> return err
<ide> }
<ide> }
<ide> func (s *TagStore) ImageExport(imageExportConfig *ImageExportConfig) error {
<ide> if len(repoTag) > 0 {
<ide> addKey(repoName, repoTag, img.ID)
<ide> }
<del> if err := s.exportImage(imageExportConfig.Engine, img.ID, tempdir); err != nil {
<add> if err := s.exportImage(img.ID, tempdir); err != nil {
<ide> return err
<ide> }
<ide>
<ide> } else {
<ide> // this must be an ID that didn't get looked up just right?
<del> if err := s.exportImage(imageExportConfig.Engine, name, tempdir); err != nil {
<add> if err := s.exportImage(name, tempdir); err != nil {
<ide> return err
<ide> }
<ide> }
<ide> func (s *TagStore) ImageExport(imageExportConfig *ImageExportConfig) error {
<ide> }
<ide>
<ide> // FIXME: this should be a top-level function, not a class method
<del>func (s *TagStore) exportImage(eng *engine.Engine, name, tempdir string) error {
<add>func (s *TagStore) exportImage(name, tempdir string) error {
<ide> for n := name; n != ""; {
<ide> // temporary directory
<ide> tmpImageDir := path.Join(tempdir, n)
<ide> func (s *TagStore) exportImage(eng *engine.Engine, name, tempdir string) error {
<ide> if err != nil {
<ide> return err
<ide> }
<del> job := eng.Job("image_inspect", n)
<del> job.SetenvBool("raw", true)
<del> job.Stdout.Add(json)
<del> if err := job.Run(); err != nil {
<add> imageInspectRaw, err := s.LookupRaw(n)
<add> if err != nil {
<ide> return err
<ide> }
<add> written, err := json.Write(imageInspectRaw)
<add> if err != nil {
<add> return err
<add> }
<add> if written != len(imageInspectRaw) {
<add> logrus.Warnf("%d byes should have been written instead %d have been written", written, len(imageInspectRaw))
<add> }
<ide>
<ide> // serialize filesystem
<ide> fsTar, err := os.Create(path.Join(tmpImageDir, "layer.tar"))
<ide><path>graph/load.go
<ide> import (
<ide> "path"
<ide>
<ide> "github.com/Sirupsen/logrus"
<del> "github.com/docker/docker/engine"
<ide> "github.com/docker/docker/image"
<ide> "github.com/docker/docker/pkg/archive"
<ide> "github.com/docker/docker/pkg/chrootarchive"
<ide> )
<ide>
<del>type ImageLoadConfig struct {
<del> InTar io.ReadCloser
<del> OutStream io.Writer
<del> Engine *engine.Engine
<del>}
<del>
<ide> // Loads a set of images into the repository. This is the complementary of ImageExport.
<ide> // The input stream is an uncompressed tar ball containing images and metadata.
<del>func (s *TagStore) Load(imageLoadConfig *ImageLoadConfig) error {
<add>func (s *TagStore) Load(inTar io.ReadCloser, outStream io.Writer) error {
<ide> tmpImageDir, err := ioutil.TempDir("", "docker-import-")
<ide> if err != nil {
<ide> return err
<ide> func (s *TagStore) Load(imageLoadConfig *ImageLoadConfig) error {
<ide> excludes[i] = k
<ide> i++
<ide> }
<del> if err := chrootarchive.Untar(imageLoadConfig.InTar, repoDir, &archive.TarOptions{ExcludePatterns: excludes}); err != nil {
<add> if err := chrootarchive.Untar(inTar, repoDir, &archive.TarOptions{ExcludePatterns: excludes}); err != nil {
<ide> return err
<ide> }
<ide>
<ide> func (s *TagStore) Load(imageLoadConfig *ImageLoadConfig) error {
<ide>
<ide> for _, d := range dirs {
<ide> if d.IsDir() {
<del> if err := s.recursiveLoad(imageLoadConfig.Engine, d.Name(), tmpImageDir); err != nil {
<add> if err := s.recursiveLoad(d.Name(), tmpImageDir); err != nil {
<ide> return err
<ide> }
<ide> }
<ide> func (s *TagStore) Load(imageLoadConfig *ImageLoadConfig) error {
<ide>
<ide> for imageName, tagMap := range repositories {
<ide> for tag, address := range tagMap {
<del> if err := s.SetLoad(imageName, tag, address, true, imageLoadConfig.OutStream); err != nil {
<add> if err := s.SetLoad(imageName, tag, address, true, outStream); err != nil {
<ide> return err
<ide> }
<ide> }
<ide> func (s *TagStore) Load(imageLoadConfig *ImageLoadConfig) error {
<ide> return nil
<ide> }
<ide>
<del>func (s *TagStore) recursiveLoad(eng *engine.Engine, address, tmpImageDir string) error {
<add>func (s *TagStore) recursiveLoad(address, tmpImageDir string) error {
<ide> if _, err := s.LookupImage(address); err != nil {
<ide> logrus.Debugf("Loading %s", address)
<ide>
<ide> func (s *TagStore) recursiveLoad(eng *engine.Engine, address, tmpImageDir string
<ide>
<ide> if img.Parent != "" {
<ide> if !s.graph.Exists(img.Parent) {
<del> if err := s.recursiveLoad(eng, img.Parent, tmpImageDir); err != nil {
<add> if err := s.recursiveLoad(img.Parent, tmpImageDir); err != nil {
<ide> return err
<ide> }
<ide> }
<ide><path>graph/load_unsupported.go
<ide> package graph
<ide>
<ide> import (
<ide> "fmt"
<del>
<del> "github.com/docker/docker/engine"
<add> "io"
<ide> )
<ide>
<del>func (s *TagStore) CmdLoad(job *engine.Job) error {
<del> return fmt.Errorf("CmdLoad is not supported on this platform")
<add>func (s *TagStore) Load(inTar io.ReadCloser, outStream io.Writer) error {
<add> return fmt.Errorf("Load is not supported on this platform")
<ide> }
<ide><path>graph/service.go
<ide> import (
<ide> "io"
<ide>
<ide> "github.com/Sirupsen/logrus"
<del> "github.com/docker/docker/engine"
<add> "github.com/docker/docker/api/types"
<ide> )
<ide>
<del>func (s *TagStore) Install(eng *engine.Engine) error {
<del> for name, handler := range map[string]engine.Handler{
<del> "image_inspect": s.CmdLookup,
<del> "viz": s.CmdViz,
<del> } {
<del> if err := eng.Register(name, handler); err != nil {
<del> return fmt.Errorf("Could not register %q: %v", name, err)
<del> }
<add>func (s *TagStore) LookupRaw(name string) ([]byte, error) {
<add> image, err := s.LookupImage(name)
<add> if err != nil || image == nil {
<add> return nil, fmt.Errorf("No such image %s", name)
<add> }
<add>
<add> imageInspectRaw, err := image.RawJson()
<add> if err != nil {
<add> return nil, err
<ide> }
<del> return nil
<add>
<add> return imageInspectRaw, nil
<ide> }
<ide>
<del>// CmdLookup return an image encoded in JSON
<del>func (s *TagStore) CmdLookup(job *engine.Job) error {
<del> if len(job.Args) != 1 {
<del> return fmt.Errorf("usage: %s NAME", job.Name)
<add>// Lookup return an image encoded in JSON
<add>func (s *TagStore) Lookup(name string) (*types.ImageInspect, error) {
<add> image, err := s.LookupImage(name)
<add> if err != nil || image == nil {
<add> return nil, fmt.Errorf("No such image: %s", name)
<ide> }
<del> name := job.Args[0]
<del> if image, err := s.LookupImage(name); err == nil && image != nil {
<del> if job.GetenvBool("raw") {
<del> b, err := image.RawJson()
<del> if err != nil {
<del> return err
<del> }
<del> job.Stdout.Write(b)
<del> return nil
<del> }
<ide>
<del> out := &engine.Env{}
<del> out.SetJson("Id", image.ID)
<del> out.SetJson("Parent", image.Parent)
<del> out.SetJson("Comment", image.Comment)
<del> out.SetAuto("Created", image.Created)
<del> out.SetJson("Container", image.Container)
<del> out.SetJson("ContainerConfig", image.ContainerConfig)
<del> out.Set("DockerVersion", image.DockerVersion)
<del> out.SetJson("Author", image.Author)
<del> out.SetJson("Config", image.Config)
<del> out.Set("Architecture", image.Architecture)
<del> out.Set("Os", image.OS)
<del> out.SetInt64("Size", image.Size)
<del> out.SetInt64("VirtualSize", image.GetParentsSize(0)+image.Size)
<del> if _, err = out.WriteTo(job.Stdout); err != nil {
<del> return err
<del> }
<del> return nil
<add> imageInspect := &types.ImageInspect{
<add> Id: image.ID,
<add> Parent: image.Parent,
<add> Comment: image.Comment,
<add> Created: image.Created,
<add> Container: image.Container,
<add> ContainerConfig: &image.ContainerConfig,
<add> DockerVersion: image.DockerVersion,
<add> Author: image.Author,
<add> Config: image.Config,
<add> Architecture: image.Architecture,
<add> Os: image.OS,
<add> Size: image.Size,
<add> VirtualSize: image.GetParentsSize(0) + image.Size,
<ide> }
<del> return fmt.Errorf("No such image: %s", name)
<add>
<add> return imageInspect, nil
<ide> }
<ide>
<ide> // ImageTarLayer return the tarLayer of the image
<ide><path>graph/viz.go
<del>package graph
<del>
<del>import (
<del> "fmt"
<del> "strings"
<del>
<del> "github.com/docker/docker/engine"
<del> "github.com/docker/docker/image"
<del>)
<del>
<del>func (s *TagStore) CmdViz(job *engine.Job) error {
<del> images, _ := s.graph.Map()
<del> if images == nil {
<del> return nil
<del> }
<del> job.Stdout.Write([]byte("digraph docker {\n"))
<del>
<del> var (
<del> parentImage *image.Image
<del> err error
<del> )
<del> for _, image := range images {
<del> parentImage, err = image.GetParent()
<del> if err != nil {
<del> return fmt.Errorf("Error while getting parent image: %v", err)
<del> }
<del> if parentImage != nil {
<del> job.Stdout.Write([]byte(" \"" + parentImage.ID + "\" -> \"" + image.ID + "\"\n"))
<del> } else {
<del> job.Stdout.Write([]byte(" base -> \"" + image.ID + "\" [style=invis]\n"))
<del> }
<del> }
<del>
<del> for id, repos := range s.GetRepoRefs() {
<del> job.Stdout.Write([]byte(" \"" + id + "\" [label=\"" + id + "\\n" + strings.Join(repos, "\\n") + "\",shape=box,fillcolor=\"paleturquoise\",style=\"filled,rounded\"];\n"))
<del> }
<del> job.Stdout.Write([]byte(" base [style=invisible]\n}\n"))
<del> return nil
<del>}
<ide><path>integration/runtime_test.go
<ide> func init() {
<ide>
<ide> func setupBaseImage() {
<ide> eng := newTestEngine(std_log.New(os.Stderr, "", 0), false, unitTestStoreBase)
<del> job := eng.Job("image_inspect", unitTestImageName)
<del> img, _ := job.Stdout.AddEnv()
<add> d := getDaemon(eng)
<add>
<add> _, err := d.Repositories().Lookup(unitTestImageName)
<ide> // If the unit test is not found, try to download it.
<del> if err := job.Run(); err != nil || img.Get("Id") != unitTestImageID {
<add> if err != nil {
<add> // seems like we can just ignore the error here...
<add> // there was a check of imgId from job stdout against unittestid but
<add> // if there was an error how could the imgid from the job
<add> // be compared?! it's obvious it's different, am I totally wrong?
<add>
<ide> // Retrieve the Image
<ide> imagePullConfig := &graph.ImagePullConfig{
<ide> Parallel: true,
<ide> OutStream: ioutils.NopWriteCloser(os.Stdout),
<ide> AuthConfig: &cliconfig.AuthConfig{},
<ide> }
<del> d := getDaemon(eng)
<ide> if err := d.Repositories().Pull(unitTestImageName, "", imagePullConfig); err != nil {
<ide> logrus.Fatalf("Unable to pull the test image: %s", err)
<ide> } | 9 |
Javascript | Javascript | fix dashes in api docs | 908f59a5dfd6e4378be1055918b04a8f40e9310d | <ide><path>src/filters.js
<ide> var NUMBER_STRING = /^\d+$/;
<ide> * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
<ide> * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
<ide> * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
<del> * * `'MMMM'`: Month in year (January‒December)
<del> * * `'MMM'`: Month in year (Jan - Dec)
<del> * * `'MM'`: Month in year, padded (01‒12)
<del> * * `'M'`: Month in year (1‒12)
<del> * * `'dd'`: Day in month, padded (01‒31)
<add> * * `'MMMM'`: Month in year (January-December)
<add> * * `'MMM'`: Month in year (Jan-Dec)
<add> * * `'MM'`: Month in year, padded (01-12)
<add> * * `'M'`: Month in year (1-12)
<add> * * `'dd'`: Day in month, padded (01-31)
<ide> * * `'d'`: Day in month (1-31)
<del> * * `'EEEE'`: Day in Week,(Sunday‒Saturday)
<add> * * `'EEEE'`: Day in Week,(Sunday-Saturday)
<ide> * * `'EEE'`: Day in Week, (Sun-Sat)
<del> * * `'HH'`: Hour in day, padded (00‒23)
<add> * * `'HH'`: Hour in day, padded (00-23)
<ide> * * `'H'`: Hour in day (0-23)
<del> * * `'hh'`: Hour in am/pm, padded (01‒12)
<add> * * `'hh'`: Hour in am/pm, padded (01-12)
<ide> * * `'h'`: Hour in am/pm, (1-12)
<del> * * `'mm'`: Minute in hour, padded (00‒59)
<add> * * `'mm'`: Minute in hour, padded (00-59)
<ide> * * `'m'`: Minute in hour (0-59)
<del> * * `'ss'`: Second in minute, padded (00‒59)
<del> * * `'s'`: Second in minute (0‒59)
<add> * * `'ss'`: Second in minute, padded (00-59)
<add> * * `'s'`: Second in minute (0-59)
<ide> * * `'a'`: am/pm marker
<del> * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200‒1200)
<add> * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-1200)
<ide> * * `'z'`: short form of current timezone name (e.g. PDT)
<ide> *
<ide> * `format` string can also be the following default formats for `en_US` locale (support for other | 1 |
Go | Go | simplify error handling | 300c51c3a4ca47b022eb2efb75d1e8cf7736b0ff | <ide><path>daemon/container.go
<ide> func (container *Container) buildHostnameAndHostsFiles(IP string) error {
<ide> return container.buildHostsFiles(IP)
<ide> }
<ide>
<del>func (container *Container) AllocateNetwork() (err error) {
<add>func (container *Container) AllocateNetwork() error {
<ide> mode := container.hostConfig.NetworkMode
<ide> if container.Config.NetworkDisabled || !mode.IsPrivate() {
<ide> return nil
<ide> }
<ide>
<ide> var (
<ide> env *engine.Env
<add> err error
<ide> eng = container.daemon.eng
<ide> )
<ide>
<ide> job := eng.Job("allocate_interface", container.ID)
<ide> if env, err = job.Stdout.AddEnv(); err != nil {
<ide> return err
<ide> }
<del> if err := job.Run(); err != nil {
<add> if err = job.Run(); err != nil {
<ide> return err
<ide> }
<ide>
<ide> // Error handling: At this point, the interface is allocated so we have to
<ide> // make sure that it is always released in case of error, otherwise we
<ide> // might leak resources.
<del> defer func() {
<del> if err != nil {
<del> eng.Job("release_interface", container.ID).Run()
<del> }
<del> }()
<ide>
<ide> if container.Config.PortSpecs != nil {
<del> if err := migratePortMappings(container.Config, container.hostConfig); err != nil {
<add> if err = migratePortMappings(container.Config, container.hostConfig); err != nil {
<add> eng.Job("release_interface", container.ID).Run()
<ide> return err
<ide> }
<ide> container.Config.PortSpecs = nil
<del> if err := container.WriteHostConfig(); err != nil {
<add> if err = container.WriteHostConfig(); err != nil {
<add> eng.Job("release_interface", container.ID).Run()
<ide> return err
<ide> }
<ide> }
<ide> func (container *Container) AllocateNetwork() (err error) {
<ide> container.NetworkSettings.PortMapping = nil
<ide>
<ide> for port := range portSpecs {
<del> if err := container.allocatePort(eng, port, bindings); err != nil {
<add> if err = container.allocatePort(eng, port, bindings); err != nil {
<add> eng.Job("release_interface", container.ID).Run()
<ide> return err
<ide> }
<ide> } | 1 |
Ruby | Ruby | use https for git remote test | a6d1ddf32611109b3284b045fdc5123c40e23b9e | <ide><path>Library/Homebrew/test/utils/git_spec.rb
<ide> context "when git is available" do
<ide> it "returns true when git remote exists", :needs_network do
<ide> git = HOMEBREW_SHIMS_PATH/"scm/git"
<del> url = "http://github.com/Homebrew/homebrew.github.io"
<add> url = "https://github.com/Homebrew/homebrew.github.io"
<ide> repo = HOMEBREW_CACHE/"hey"
<ide> repo.mkpath
<ide> | 1 |
Go | Go | fix a race condition in testinterruptedregister | 02cb7f45fa6f9a8899286431fa68bf1a9d0194d8 | <ide><path>graph.go
<ide> func (graph *Graph) Create(layerData archive.Archive, container *Container, comm
<ide>
<ide> // Register imports a pre-existing image into the graph.
<ide> // FIXME: pass img as first argument
<del>func (graph *Graph) Register(jsonData []byte, layerData archive.Archive, img *Image) error {
<add>func (graph *Graph) Register(jsonData []byte, layerData archive.Archive, img *Image) (err error) {
<add> defer func() {
<add> // If any error occurs, remove the new dir from the driver.
<add> // Don't check for errors since the dir might not have been created.
<add> // FIXME: this leaves a possible race condition.
<add> if err != nil {
<add> graph.driver.Remove(img.ID)
<add> }
<add> }()
<ide> if err := ValidateID(img.ID); err != nil {
<ide> return err
<ide> }
<ide> func (graph *Graph) Register(jsonData []byte, layerData archive.Archive, img *Im
<ide> return err
<ide> }
<ide>
<add> // If the driver has this ID but the graph doesn't, remove it from the driver to start fresh.
<add> // (the graph is the source of truth).
<add> // Ignore errors, since we don't know if the driver correctly returns ErrNotExist.
<add> // (FIXME: make that mandatory for drivers).
<add> graph.driver.Remove(img.ID)
<add>
<ide> tmp, err := graph.Mktemp("")
<ide> defer os.RemoveAll(tmp)
<ide> if err != nil { | 1 |
Javascript | Javascript | fix flowtype errors for pushnotificationios | 68bbccbaa25f6364254a19fa6ef88a4b04ac2cbb | <ide><path>Libraries/PushNotificationIOS/PushNotificationIOS.js
<ide> class PushNotificationIOS {
<ide> * - `userInfo` : An optional object containing additional notification data.
<ide> * - `thread-id` : The thread identifier of this notification, if has one.
<ide> */
<del> static getDeliveredNotifications(callback: (notifications: [Object]) => void): void {
<add> static getDeliveredNotifications(callback: (notifications: Array<Object>) => void): void {
<ide> RCTPushNotificationManager.getDeliveredNotifications(callback);
<ide> }
<ide>
<ide> class PushNotificationIOS {
<ide> *
<ide> * @param identifiers Array of notification identifiers
<ide> */
<del> static removeDeliveredNotifications(identifiers: [string]): void {
<add> static removeDeliveredNotifications(identifiers: Array<string>): void {
<ide> RCTPushNotificationManager.removeDeliveredNotifications(identifiers);
<ide> }
<ide> | 1 |
Javascript | Javascript | fix links of docs on the comment | c5a733e1e3ffa74bc6bbc769f1b13ecff9915763 | <ide><path>packages/react/src/ReactChildren.js
<ide> function forEachSingleChild(bookKeeping, child, name) {
<ide> /**
<ide> * Iterates through children that are typically specified as `props.children`.
<ide> *
<del> * See https://reactjs.org/docs/react-api.html#react.children.foreach
<add> * See https://reactjs.org/docs/react-api.html#reactchildrenforeach
<ide> *
<ide> * The provided forEachFunc(child, index) will be called for each
<ide> * leaf child.
<ide> function mapIntoWithKeyPrefixInternal(children, array, prefix, func, context) {
<ide> /**
<ide> * Maps children that are typically specified as `props.children`.
<ide> *
<del> * See https://reactjs.org/docs/react-api.html#react.children.map
<add> * See https://reactjs.org/docs/react-api.html#reactchildrenmap
<ide> *
<ide> * The provided mapFunction(child, key, index) will be called for each
<ide> * leaf child.
<ide> function mapChildren(children, func, context) {
<ide> * Count the number of children that are typically specified as
<ide> * `props.children`.
<ide> *
<del> * See https://reactjs.org/docs/react-api.html#react.children.count
<add> * See https://reactjs.org/docs/react-api.html#reactchildrencount
<ide> *
<ide> * @param {?*} children Children tree container.
<ide> * @return {number} The number of children.
<ide> function countChildren(children) {
<ide> * Flatten a children object (typically specified as `props.children`) and
<ide> * return an array with appropriately re-keyed children.
<ide> *
<del> * See https://reactjs.org/docs/react-api.html#react.children.toarray
<add> * See https://reactjs.org/docs/react-api.html#reactchildrentoarray
<ide> */
<ide> function toArray(children) {
<ide> const result = [];
<ide> function toArray(children) {
<ide> * Returns the first child in a collection of children and verifies that there
<ide> * is only one child in the collection.
<ide> *
<del> * See https://reactjs.org/docs/react-api.html#react.children.only
<add> * See https://reactjs.org/docs/react-api.html#reactchildrenonly
<ide> *
<ide> * The current implementation of this function assumes that a single child gets
<ide> * passed without a wrapper, but the purpose of this helper function is to | 1 |
Java | Java | pass rsocketstrategies to metadataextractor | 1e9ccdd8b8756162ed635b45c077e45b6ae33504 | <ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/DefaultMetadataExtractor.java
<ide> import org.springframework.core.io.buffer.DataBufferFactory;
<ide> import org.springframework.core.io.buffer.NettyDataBufferFactory;
<ide> import org.springframework.lang.Nullable;
<del>import org.springframework.util.Assert;
<ide> import org.springframework.util.MimeType;
<ide>
<ide> /**
<ide> */
<ide> public class DefaultMetadataExtractor implements MetadataExtractor {
<ide>
<del> private final RSocketStrategies rsocketStrategies;
<del>
<ide> private final Map<String, EntryProcessor<?>> entryProcessors = new HashMap<>();
<ide>
<ide>
<ide> /**
<ide> * Default constructor with {@link RSocketStrategies}.
<ide> */
<del> public DefaultMetadataExtractor(RSocketStrategies strategies) {
<del> Assert.notNull(strategies, "RSocketStrategies is required");
<del> this.rsocketStrategies = strategies;
<add> public DefaultMetadataExtractor() {
<ide> // TODO: remove when rsocket-core API available
<ide> metadataToExtract(MetadataExtractor.ROUTING, String.class, ROUTE_KEY);
<ide> }
<ide> public <T> void metadataToExtract(
<ide>
<ide>
<ide> @Override
<del> public Map<String, Object> extract(Payload payload, MimeType metadataMimeType) {
<add> public Map<String, Object> extract(Payload payload, MimeType metadataMimeType, RSocketStrategies strategies) {
<ide> Map<String, Object> result = new HashMap<>();
<ide> if (metadataMimeType.equals(COMPOSITE_METADATA)) {
<ide> for (CompositeMetadata.Entry entry : new CompositeMetadata(payload.metadata(), false)) {
<del> processEntry(entry.getContent(), entry.getMimeType(), result);
<add> processEntry(entry.getContent(), entry.getMimeType(), result, strategies);
<ide> }
<ide> }
<ide> else {
<del> processEntry(payload.metadata(), metadataMimeType.toString(), result);
<add> processEntry(payload.metadata(), metadataMimeType.toString(), result, strategies);
<ide> }
<ide> return result;
<ide> }
<ide>
<del> private void processEntry(ByteBuf content, @Nullable String mimeType, Map<String, Object> result) {
<add> private void processEntry(ByteBuf content,
<add> @Nullable String mimeType, Map<String, Object> result, RSocketStrategies strategies) {
<add>
<ide> EntryProcessor<?> entryProcessor = this.entryProcessors.get(mimeType);
<ide> if (entryProcessor != null) {
<ide> content.retain();
<del> entryProcessor.process(content, result);
<add> entryProcessor.process(content, result, strategies);
<ide> return;
<ide> }
<ide> if (MetadataExtractor.ROUTING.toString().equals(mimeType)) {
<ide> private void processEntry(ByteBuf content, @Nullable String mimeType, Map<String
<ide>
<ide> private final BiConsumer<T, Map<String, Object>> accumulator;
<ide>
<del> private final Decoder<T> decoder;
<del>
<ide>
<ide> public EntryProcessor(
<ide> MimeType mimeType, Class<T> targetType,
<ide> private EntryProcessor(
<ide> this.mimeType = mimeType;
<ide> this.targetType = targetType;
<ide> this.accumulator = accumulator;
<del> this.decoder = rsocketStrategies.decoder(targetType, mimeType);
<ide> }
<ide>
<ide>
<del> public void process(ByteBuf byteBuf, Map<String, Object> result) {
<del> DataBufferFactory factory = rsocketStrategies.dataBufferFactory();
<add> public void process(ByteBuf byteBuf, Map<String, Object> result, RSocketStrategies strategies) {
<add> DataBufferFactory factory = strategies.dataBufferFactory();
<ide> DataBuffer buffer = factory instanceof NettyDataBufferFactory ?
<ide> ((NettyDataBufferFactory) factory).wrap(byteBuf) :
<ide> factory.wrap(byteBuf.nioBuffer());
<ide>
<del> T value = this.decoder.decode(buffer, this.targetType, this.mimeType, Collections.emptyMap());
<add> Decoder<T> decoder = strategies.decoder(this.targetType, this.mimeType);
<add> T value = decoder.decode(buffer, this.targetType, this.mimeType, Collections.emptyMap());
<ide> this.accumulator.accept(value, result);
<ide> }
<ide> }
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/MetadataExtractor.java
<ide> public interface MetadataExtractor {
<ide> * @param payload the payload whose metadata should be read
<ide> * @param metadataMimeType the mime type of the metadata; this is what was
<ide> * specified by the client at the start of the RSocket connection.
<add> * @param strategies for access to codecs and a DataBufferFactory
<ide> * @return a map of 0 or more decoded metadata values with assigned names
<ide> */
<del> Map<String, Object> extract(Payload payload, MimeType metadataMimeType);
<add> Map<String, Object> extract(Payload payload, MimeType metadataMimeType, RSocketStrategies strategies);
<ide>
<ide> }
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/annotation/support/MessagingRSocket.java
<ide> import reactor.core.publisher.MonoProcessor;
<ide>
<ide> import org.springframework.core.io.buffer.DataBuffer;
<del>import org.springframework.core.io.buffer.DataBufferFactory;
<ide> import org.springframework.core.io.buffer.DataBufferUtils;
<ide> import org.springframework.core.io.buffer.NettyDataBuffer;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.messaging.rsocket.MetadataExtractor;
<ide> import org.springframework.messaging.rsocket.PayloadUtils;
<ide> import org.springframework.messaging.rsocket.RSocketRequester;
<add>import org.springframework.messaging.rsocket.RSocketStrategies;
<ide> import org.springframework.messaging.support.MessageBuilder;
<ide> import org.springframework.messaging.support.MessageHeaderAccessor;
<ide> import org.springframework.util.Assert;
<ide> class MessagingRSocket extends AbstractRSocket {
<ide>
<ide> private final RSocketRequester requester;
<ide>
<del> private final DataBufferFactory bufferFactory;
<add> private final RSocketStrategies strategies;
<ide>
<ide>
<ide> MessagingRSocket(MimeType dataMimeType, MimeType metadataMimeType, MetadataExtractor metadataExtractor,
<ide> RSocketRequester requester, ReactiveMessageHandler messageHandler,
<del> RouteMatcher routeMatcher, DataBufferFactory bufferFactory) {
<add> RouteMatcher routeMatcher, RSocketStrategies strategies) {
<ide>
<ide> Assert.notNull(dataMimeType, "'dataMimeType' is required");
<ide> Assert.notNull(metadataMimeType, "'metadataMimeType' is required");
<ide> Assert.notNull(metadataExtractor, "'metadataExtractor' is required");
<ide> Assert.notNull(requester, "'requester' is required");
<ide> Assert.notNull(messageHandler, "'messageHandler' is required");
<ide> Assert.notNull(routeMatcher, "'routeMatcher' is required");
<del> Assert.notNull(bufferFactory, "'bufferFactory' is required");
<add> Assert.notNull(strategies, "RSocketStrategies is required");
<ide>
<ide> this.dataMimeType = dataMimeType;
<ide> this.metadataMimeType = metadataMimeType;
<ide> this.metadataExtractor = metadataExtractor;
<ide> this.requester = requester;
<ide> this.messageHandler = messageHandler;
<ide> this.routeMatcher = routeMatcher;
<del> this.bufferFactory = bufferFactory;
<add> this.strategies = strategies;
<ide> }
<ide>
<ide>
<ide> private Flux<Payload> handleAndReply(Payload firstPayload, FrameType frameType,
<ide> }
<ide>
<ide> private DataBuffer retainDataAndReleasePayload(Payload payload) {
<del> return PayloadUtils.retainDataAndReleasePayload(payload, this.bufferFactory);
<add> return PayloadUtils.retainDataAndReleasePayload(payload, this.strategies.dataBufferFactory());
<ide> }
<ide>
<ide> private MessageHeaders createHeaders(Payload payload, FrameType frameType,
<ide> private MessageHeaders createHeaders(Payload payload, FrameType frameType,
<ide> MessageHeaderAccessor headers = new MessageHeaderAccessor();
<ide> headers.setLeaveMutable(true);
<ide>
<del> Map<String, Object> metadataValues = this.metadataExtractor.extract(payload, this.metadataMimeType);
<add> Map<String, Object> metadataValues =
<add> this.metadataExtractor.extract(payload, this.metadataMimeType, this.strategies);
<add>
<ide> metadataValues.putIfAbsent(MetadataExtractor.ROUTE_KEY, "");
<ide> for (Map.Entry<String, Object> entry : metadataValues.entrySet()) {
<ide> if (entry.getKey().equals(MetadataExtractor.ROUTE_KEY)) {
<ide> private MessageHeaders createHeaders(Payload payload, FrameType frameType,
<ide> if (replyMono != null) {
<ide> headers.setHeader(RSocketPayloadReturnValueHandler.RESPONSE_HEADER, replyMono);
<ide> }
<del> headers.setHeader(HandlerMethodReturnValueHandler.DATA_BUFFER_FACTORY_HEADER, this.bufferFactory);
<add> headers.setHeader(HandlerMethodReturnValueHandler.DATA_BUFFER_FACTORY_HEADER,
<add> this.strategies.dataBufferFactory());
<ide>
<ide> return headers.getMessageHeaders();
<ide> }
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/annotation/support/RSocketMessageHandler.java
<ide> public void afterPropertiesSet() {
<ide> .build();
<ide> }
<ide> if (this.metadataExtractor == null) {
<del> DefaultMetadataExtractor extractor = new DefaultMetadataExtractor(this.rsocketStrategies);
<add> DefaultMetadataExtractor extractor = new DefaultMetadataExtractor();
<ide> extractor.metadataToExtract(MimeTypeUtils.TEXT_PLAIN, String.class, MetadataExtractor.ROUTE_KEY);
<ide> this.metadataExtractor = extractor;
<ide> }
<ide> private MessagingRSocket createResponder(ConnectionSetupPayload setupPayload, RS
<ide> Assert.notNull(this.metadataExtractor, () -> "No MetadataExtractor. Was afterPropertiesSet not called?");
<ide>
<ide> return new MessagingRSocket(dataMimeType, metadataMimeType, this.metadataExtractor, requester,
<del> this, getRouteMatcher(), strategies.dataBufferFactory());
<add> this, getRouteMatcher(), strategies);
<ide> }
<ide>
<ide> }
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/rsocket/DefaultMetadataExtractorTests.java
<ide> public void setUp() {
<ide> this.captor = ArgumentCaptor.forClass(Payload.class);
<ide> BDDMockito.when(this.rsocket.fireAndForget(captor.capture())).thenReturn(Mono.empty());
<ide>
<del> this.extractor = new DefaultMetadataExtractor(this.strategies);
<add> this.extractor = new DefaultMetadataExtractor();
<ide> }
<ide>
<ide> @After
<ide> public void compositeMetadataWithDefaultSettings() {
<ide> .send().block();
<ide>
<ide> Payload payload = this.captor.getValue();
<del> Map<String, Object> result = this.extractor.extract(payload, COMPOSITE_METADATA);
<add> Map<String, Object> result = this.extractor.extract(payload, COMPOSITE_METADATA, this.strategies);
<ide> payload.release();
<ide>
<ide> assertThat(result).hasSize(1).containsEntry(ROUTE_KEY, "toA");
<ide> public void compositeMetadataWithMimeTypeRegistrations() {
<ide> .block();
<ide>
<ide> Payload payload = this.captor.getValue();
<del> Map<String, Object> result = this.extractor.extract(payload, COMPOSITE_METADATA);
<add> Map<String, Object> result = this.extractor.extract(payload, COMPOSITE_METADATA, this.strategies);
<ide> payload.release();
<ide>
<ide> assertThat(result).hasSize(4)
<ide> public void route() {
<ide>
<ide> requester(ROUTING).route("toA").data("data").send().block();
<ide> Payload payload = this.captor.getValue();
<del> Map<String, Object> result = this.extractor.extract(payload, ROUTING);
<add> Map<String, Object> result = this.extractor.extract(payload, ROUTING, this.strategies);
<ide> payload.release();
<ide>
<ide> assertThat(result).hasSize(1).containsEntry(ROUTE_KEY, "toA");
<ide> public void routeAsText() {
<ide>
<ide> requester(TEXT_PLAIN).route("toA").data("data").send().block();
<ide> Payload payload = this.captor.getValue();
<del> Map<String, Object> result = this.extractor.extract(payload, TEXT_PLAIN);
<add> Map<String, Object> result = this.extractor.extract(payload, TEXT_PLAIN, this.strategies);
<ide> payload.release();
<ide>
<ide> assertThat(result).hasSize(1).containsEntry(ROUTE_KEY, "toA");
<ide> public void routeWithCustomFormatting() {
<ide>
<ide> requester(TEXT_PLAIN).metadata("toA:text data", null).data("data").send().block();
<ide> Payload payload = this.captor.getValue();
<del> Map<String, Object> result = this.extractor.extract(payload, TEXT_PLAIN);
<add> Map<String, Object> result = this.extractor.extract(payload, TEXT_PLAIN, this.strategies);
<ide> payload.release();
<ide>
<ide> assertThat(result).hasSize(2) | 5 |
Ruby | Ruby | add parenthesis to avoid syntax warnings | 9027721b11436144e65bceb9e29ad8669b02582a | <ide><path>actionpack/test/template/prototype_helper_test.rb
<ide> def protect_against_forgery?
<ide> end
<ide>
<ide> def create_generator
<del> block = Proc.new { |*args| yield *args if block_given? }
<add> block = Proc.new { |*args| yield(*args) if block_given? }
<ide> JavaScriptGenerator.new self, &block
<ide> end
<ide> end
<ide><path>actionpack/test/template/tag_helper_test.rb
<ide> def test_tag_honors_html_safe_for_param_values
<ide>
<ide> def test_skip_invalid_escaped_attributes
<ide> ['&1;', 'dfa3;', '& #123;'].each do |escaped|
<del> assert_equal %(<a href="#{escaped.gsub /&/, '&'}" />), tag('a', :href => escaped)
<add> assert_equal %(<a href="#{escaped.gsub(/&/, '&')}" />), tag('a', :href => escaped)
<ide> end
<ide> end
<ide> | 2 |
Javascript | Javascript | revert this.async (avoid may breaking change) | 4bf2ba46af5f3f60eba6d6a23cea46c913100632 | <ide><path>lib/optimize/CommonsChunkPlugin.js
<ide> function CommonsChunkPlugin(options) {
<ide> this.minChunks = options.minChunks;
<ide> this.selectedChunks = options.chunks;
<ide> if(options.children) this.selectedChunks = false;
<del> this.asyncOption = options.async;
<add> this.async = options.async;
<ide> this.minSize = options.minSize;
<ide> this.ident = __filename + (nextIdent++);
<ide> }
<ide> CommonsChunkPlugin.prototype.apply = function(compiler) {
<ide> var filenameTemplate = this.filenameTemplate;
<ide> var minChunks = this.minChunks;
<ide> var selectedChunks = this.selectedChunks;
<del> var asyncOption = this.asyncOption;
<add> var asyncOption = this.async;
<ide> var minSize = this.minSize;
<ide> var ident = this.ident;
<ide> compiler.plugin("this-compilation", function(compilation) { | 1 |
Javascript | Javascript | define event handler as enumerable | 8e87efb8495c59cc829bc6971e89a7eddc104644 | <ide><path>lib/internal/event_target.js
<ide> function defineEventHandler(emitter, name) {
<ide> emitter.addEventListener(name, value);
<ide> }
<ide> eventHandlerValue = value;
<del> }
<add> },
<add> configurable: true,
<add> enumerable: true
<ide> });
<ide> }
<ide> module.exports = {
<ide><path>test/parallel/test-eventtarget.js
<ide> let asyncTest = Promise.resolve();
<ide> }));
<ide> target.dispatchEvent(new Event('foo'));
<ide> }
<add>{
<add> const target = new EventTarget();
<add> defineEventHandler(target, 'foo');
<add> const descriptor = Object.getOwnPropertyDescriptor(target, 'onfoo');
<add> strictEqual(descriptor.configurable, true);
<add> strictEqual(descriptor.enumerable, true);
<add>} | 2 |
PHP | PHP | add missing methods to request facade | a5c47f6872c2c7d1623a6fe5ffee1396de63aa4c | <ide><path>src/Illuminate/Support/Facades/Request.php
<ide> * @method static mixed offsetGet(string $offset)
<ide> * @method static void offsetSet(string $offset, mixed $value)
<ide> * @method static void offsetUnset(string $offset)
<add> * @method static array validate(array $rules, ...$params)
<add> * @method static array validateWithBag(string $errorBag, array $rules, ...$params)
<add> * @method static bool hasValidSignature(bool $absolute = true)
<ide> *
<ide> * @see \Illuminate\Http\Request
<ide> */ | 1 |
Ruby | Ruby | fix ambiguous use of * | 32836e7a538118d4ed831ded7fce0ae83fc3d860 | <ide><path>railties/lib/rails/generators/rails/app/templates/config/application.rb
<ide>
<ide> if defined?(Bundler)
<ide> # If you precompile assets before deploying to production, use this line
<del> Bundler.require *Rails.groups(:assets => %w(development test))
<add> Bundler.require(*Rails.groups(:assets => %w(development test)))
<ide> # If you want your assets lazily compiled in production, use this line
<ide> # Bundler.require(:default, :assets, Rails.env)
<ide> end | 1 |
Ruby | Ruby | inspect the filter when displaying error messages | 4c628e48a56920877948bd9d69d3e3caa41b5da8 | <ide><path>actionpack/lib/action_controller/log_subscriber.rb
<ide> def process_action(event)
<ide> end
<ide>
<ide> def halted_callback(event)
<del> info("Filter chain halted as #{event.payload[:filter]} rendered or redirected")
<add> info("Filter chain halted as #{event.payload[:filter].inspect} rendered or redirected")
<ide> end
<ide>
<ide> def send_file(event) | 1 |
Javascript | Javascript | draw tooltip with object borderwidth | 8ccff8cad70023f7e3d3dddc25e555cf098a6712 | <ide><path>src/plugins/plugin.tooltip.js
<ide> import Animations from '../core/core.animations';
<ide> import Element from '../core/core.element';
<ide> import {addRoundedRectPath} from '../helpers/helpers.canvas';
<del>import {each, noop, isNullOrUndef, isArray, _elementsEqual} from '../helpers/helpers.core';
<add>import {each, noop, isNullOrUndef, isArray, _elementsEqual, isObject} from '../helpers/helpers.core';
<ide> import {toFont, toPadding, toTRBLCorners} from '../helpers/helpers.options';
<ide> import {getRtlAdapter, overrideTextDirection, restoreTextDirection} from '../helpers/helpers.rtl';
<ide> import {distanceBetweenPoints, _limitValue} from '../helpers/helpers.math';
<ide> export class Tooltip extends Element {
<ide> drawPoint(ctx, drawOptions, centerX, centerY);
<ide> } else {
<ide> // Border
<del> ctx.lineWidth = labelColors.borderWidth || 1; // TODO, v4 remove fallback
<add> ctx.lineWidth = isObject(labelColors.borderWidth) ? Math.max(...Object.values(labelColors.borderWidth)) : (labelColors.borderWidth || 1); // TODO, v4 remove fallback
<ide> ctx.strokeStyle = labelColors.borderColor;
<ide> ctx.setLineDash(labelColors.borderDash || []);
<ide> ctx.lineDashOffset = labelColors.borderDashOffset || 0; | 1 |
Python | Python | remove unnecessary test | 42305bc519653c1f46bc0acb2ced8196ddc02025 | <ide><path>spacy/tests/test_misc.py
<ide> def test_util_ensure_path_succeeds(text):
<ide> path = ensure_path(text)
<ide> assert isinstance(path, Path)
<del>
<del>
<del>@pytest.mark.parametrize('text', [b'hello/world', True, False, None])
<del>def test_util_ensure_path_fails(text):
<del> path = ensure_path(text)
<del> assert not isinstance(path, Path) | 1 |
Javascript | Javascript | remove unused unmountidfromenvironment | 30aa84181d98dc9498f7e1eb3ded817d8faf65f6 | <ide><path>src/renderers/dom/shared/ReactComponentBrowserEnvironment.js
<ide> var ReactComponentBrowserEnvironment = {
<ide> replaceNodeWithMarkup:
<ide> DOMChildrenOperations.dangerouslyReplaceNodeWithMarkup,
<ide>
<del> /**
<del> * If a particular environment requires that some resources be cleaned up,
<del> * specify this in the injected Mixin. In the DOM, we would likely want to
<del> * purge any cached node ID lookups.
<del> *
<del> * @private
<del> */
<del> unmountIDFromEnvironment: function(rootNodeID) {
<del> },
<del>
<ide> };
<ide>
<ide> module.exports = ReactComponentBrowserEnvironment;
<ide><path>src/renderers/dom/shared/ReactDOMComponent.js
<ide> var EventConstants = require('EventConstants');
<ide> var EventPluginHub = require('EventPluginHub');
<ide> var EventPluginRegistry = require('EventPluginRegistry');
<ide> var ReactBrowserEventEmitter = require('ReactBrowserEventEmitter');
<del>var ReactComponentBrowserEnvironment =
<del> require('ReactComponentBrowserEnvironment');
<ide> var ReactDOMButton = require('ReactDOMButton');
<ide> var ReactDOMComponentFlags = require('ReactDOMComponentFlags');
<ide> var ReactDOMComponentTree = require('ReactDOMComponentTree');
<ide> ReactDOMComponent.Mixin = {
<ide> this.unmountChildren(safely);
<ide> ReactDOMComponentTree.uncacheNode(this);
<ide> EventPluginHub.deleteAllListeners(this);
<del> ReactComponentBrowserEnvironment.unmountIDFromEnvironment(this._rootNodeID);
<ide> this._rootNodeID = null;
<ide> this._domID = null;
<ide> this._wrapperState = null;
<ide><path>src/renderers/native/ReactNativeComponentEnvironment.js
<ide> var ReactNativeComponentEnvironment = {
<ide>
<ide> replaceNodeWithMarkup: ReactNativeDOMIDOperations.dangerouslyReplaceNodeWithMarkupByID,
<ide>
<del> /**
<del> * Nothing to do for UIKit bridge.
<del> *
<del> * @private
<del> */
<del> unmountIDFromEnvironment: function(/*rootNodeID*/) {
<del>
<del> },
<del>
<ide> /**
<ide> * @param {DOMElement} Element to clear.
<ide> */
<ide><path>src/renderers/shared/stack/reconciler/ReactComponentEnvironment.js
<ide> var injected = false;
<ide>
<ide> var ReactComponentEnvironment = {
<ide>
<del> /**
<del> * Optionally injectable environment dependent cleanup hook. (server vs.
<del> * browser etc). Example: A browser system caches DOM nodes based on component
<del> * ID and must remove that cache entry when this instance is unmounted.
<del> */
<del> unmountIDFromEnvironment: null,
<del>
<ide> /**
<ide> * Optionally injectable hook for swapping out mount images in the middle of
<ide> * the tree.
<ide> var ReactComponentEnvironment = {
<ide> !injected,
<ide> 'ReactCompositeComponent: injectEnvironment() can only be called once.'
<ide> );
<del> ReactComponentEnvironment.unmountIDFromEnvironment =
<del> environment.unmountIDFromEnvironment;
<ide> ReactComponentEnvironment.replaceNodeWithMarkup =
<ide> environment.replaceNodeWithMarkup;
<ide> ReactComponentEnvironment.processChildrenUpdates = | 4 |
Text | Text | fix syntax error and missing import in docs | 611a3b3fac3756b88ad05f1bc37d1b9fef252d90 | <ide><path>README.md
<ide> Any collection can be converted to a lazy Seq with `Seq()`.
<ide>
<ide> <!-- runkit:activate -->
<ide> ```js
<del>const { Map } = require('immutable')
<del>const map = Map({ a: 1, b: 2, c: 3 }
<add>const { Map, Seq } = require('immutable')
<add>const map = Map({ a: 1, b: 2, c: 3 })
<ide> const lazySeq = Seq(map)
<ide> ```
<ide> | 1 |
PHP | PHP | add application interface and baseplugin methods | 006ae853c221f6ff33d3269703a61b6b89d92e6b | <ide><path>src/Core/BasePlugin.php
<ide> namespace Cake\Core;
<ide>
<ide> use Cake\Console\CommandCollection;
<add>use Cake\Core\ContainerInterface;
<ide> use Cake\Http\MiddlewareQueue;
<ide> use Cake\Routing\RouteBuilder;
<ide> use InvalidArgumentException;
<ide> class BasePlugin implements PluginInterface
<ide> protected $bootstrapEnabled = true;
<ide>
<ide> /**
<del> * Load routes or not
<add> * Console middleware
<ide> *
<ide> * @var bool
<ide> */
<del> protected $routesEnabled = true;
<add> protected $consoleEnabled = true;
<ide>
<ide> /**
<ide> * Enable middleware
<ide> class BasePlugin implements PluginInterface
<ide> protected $middlewareEnabled = true;
<ide>
<ide> /**
<del> * Console middleware
<add> * Register container services
<ide> *
<ide> * @var bool
<ide> */
<del> protected $consoleEnabled = true;
<add> protected $registerEnabled = true;
<add>
<add> /**
<add> * Load routes or not
<add> *
<add> * @var bool
<add> */
<add> protected $routesEnabled = true;
<ide>
<ide> /**
<ide> * The path to this plugin.
<ide> public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue
<ide> {
<ide> return $middlewareQueue;
<ide> }
<add>
<add> /**
<add> * Register container services for this plugin.
<add> *
<add> * @param \Cake\Core\ContainerInterface $container The container to add services to.
<add> * @return \Cake\Core\ContainerInterface The updated container
<add> */
<add> public function register(ContainerInterface $container): ContainerInterface
<add> {
<add> return $container;
<add> }
<ide> }
<ide><path>src/Core/Container.php
<add><?php
<add>declare(strict_types=1);
<add>
<add>/**
<add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<add> * Copyright (c) Cake Software Foundation, Inc. (https://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. (https://cakefoundation.org)
<add> * @link https://cakephp.org CakePHP(tm) Project
<add> * @since 4.2.0
<add> * @license https://opensource.org/licenses/mit-license.php MIT License
<add> */
<add>namespace Cake\Core;
<add>
<add>use League\Container\Container as LeagueContainer;
<add>
<add>/**
<add> * Dependency Injection container
<add> *
<add> * Based on the container out of League\Container
<add> *
<add> * @experimental This class' interface is not stable and may change
<add> * in future minor releases.
<add> */
<add>class Container extends LeagueContainer implements ContainerInterface
<add>{
<add>}
<ide><path>src/Core/ContainerApplicationInterface.php
<add><?php
<add>declare(strict_types=1);
<add>
<add>/**
<add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<add> * Copyright (c) Cake Software Foundation, Inc. (https://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. (https://cakefoundation.org)
<add> * @link https://cakephp.org CakePHP(tm) Project
<add> * @since 4.2.0
<add> * @license https://opensource.org/licenses/mit-license.php MIT License
<add> */
<add>namespace Cake\Core;
<add>
<add>/**
<add> * Interface for applications that configure and use a dependency injection container.
<add> *
<add> * @experimental This interface is not final and can have additional
<add> * methods and parameters added in future minor releases.
<add> */
<add>interface ContainerApplicationInterface
<add>{
<add> /**
<add> * Register services to the container
<add> *
<add> * Registered services can have instances fetched out of the container
<add> * using `get()`. Dependencies and parameters will be resolved based
<add> * on service definitions.
<add> *
<add> * @param \Cake\Core\ContainerInterface $container The container to add services to
<add> * @return \Cake\Container\ContainerInterface The updated container.
<add> */
<add> public function register(ContainerInterface $container): ContainerInterface;
<add>
<add> /**
<add> * Create a new container and register services.
<add> *
<add> * This will `register()` services provided by both the application
<add> * and any plugins if the application has plugin support.
<add> *
<add> * @return \Cake\Container\ContainerInterface A populated container
<add> */
<add> public function getContainer(): ContainerInterface;
<add>}
<ide><path>src/Core/PluginInterface.php
<ide>
<ide> /**
<ide> * Plugin Interface
<add> *
<add> * @method register(\Cake\Core\ContainerInterface $container): \Cake\Core\ContainerInterface
<ide> */
<ide> interface PluginInterface
<ide> {
<ide> interface PluginInterface
<ide> *
<ide> * @var string[]
<ide> */
<del> public const VALID_HOOKS = ['routes', 'bootstrap', 'console', 'middleware'];
<add> public const VALID_HOOKS = ['bootstrap', 'console', 'middleware', 'register', 'routes'];
<ide>
<ide> /**
<ide> * Get the name of this plugin.
<ide><path>tests/TestCase/Core/BasePluginTest.php
<ide> use Cake\Console\CommandCollection;
<ide> use Cake\Core\BasePlugin;
<ide> use Cake\Core\Configure;
<add>use Cake\Core\Container;
<ide> use Cake\Core\Plugin;
<ide> use Cake\Core\PluginApplicationInterface;
<ide> use Cake\Http\MiddlewareQueue;
<ide> public function testConfigForRoutesAndBootstrap()
<ide> $this->assertFalse($plugin->isEnabled('bootstrap'));
<ide> $this->assertTrue($plugin->isEnabled('console'));
<ide> $this->assertTrue($plugin->isEnabled('middleware'));
<add> $this->assertTrue($plugin->isEnabled('register'));
<ide> }
<ide>
<ide> public function testGetName()
<ide> public function testMiddleware()
<ide> $this->assertSame($middleware, $plugin->middleware($middleware));
<ide> }
<ide>
<del> public function testConsoleNoop()
<add> public function testConsole()
<ide> {
<ide> $plugin = new BasePlugin();
<ide> $commands = new CommandCollection();
<ide> $this->assertSame($commands, $plugin->console($commands));
<ide> }
<ide>
<add> public function testRegister()
<add> {
<add> $plugin = new BasePlugin();
<add> $container = new Container();
<add> $this->assertSame($container, $plugin->register($container));
<add> }
<add>
<ide> public function testConsoleFind()
<ide> {
<ide> $plugin = new TestPlugin(); | 5 |
PHP | PHP | remove skip for fixtures | 678684136fdb4a5f1768dd622813bd9208144ea2 | <ide><path>lib/Cake/TestSuite/TestCase.php
<ide> public function skipIf($shouldSkip, $message = '') {
<ide> public function setUp() {
<ide> parent::setUp();
<ide>
<del> if (!empty($this->fixtures)) {
<del> $this->markTestIncomplete('Tests skipped because of fixture issues.');
<del> }
<del>
<ide> if (empty($this->_configure)) {
<ide> $this->_configure = Configure::read();
<ide> } | 1 |
Ruby | Ruby | add test to assert_recognizes with custom message | 67117f7c5d2ece5494191e937de91d353609e963 | <ide><path>actionpack/test/dispatch/routing_assertions_test.rb
<ide> def test_assert_recognizes_with_query_constraint
<ide> assert_recognizes({ :controller => 'query_articles', :action => 'index', :use_query => 'true' }, '/query/articles', { :use_query => 'true' })
<ide> end
<ide>
<add> def test_assert_recognizes_raises_message
<add> err = assert_raise(Assertion) do
<add> assert_recognizes({ :controller => 'secure_articles', :action => 'index' }, 'http://test.host/secure/articles', {}, "This is a really bad msg")
<add> end
<add>
<add> assert_match err.message, "This is a really bad msg"
<add> end
<add>
<ide> def test_assert_routing
<ide> assert_routing('/articles', :controller => 'articles', :action => 'index')
<ide> end
<ide>
<ide> def test_assert_routing_raises_message
<ide> err = assert_raise(Assertion) do
<del> assert_routing('/thisIsNotARoute', { :controller => 'articles', :action => 'edit', :id => '1' }, { :id => '1' }, {}, "This is a really bad msg")
<add> assert_routing('/thisIsNotARoute', { :controller => 'articles', :action => 'edit', :id => '1' }, { :id => '1' }, {}, "This is a really bad msg")
<ide> end
<ide>
<ide> assert_match err.message, "This is a really bad msg" | 1 |
Javascript | Javascript | keep consistency in the comment | 20c5d97bb6c6a4af76d66a7e5134952989f9a9b2 | <ide><path>packages/react-reconciler/src/ReactFiberCompleteWork.js
<ide> export default function<T, P, I, TI, HI, PI, C, CC, CX, PL>(
<ide>
<ide> function markUpdate(workInProgress: Fiber) {
<ide> // Tag the fiber with an update effect. This turns a Placement into
<del> // an UpdateAndPlacement.
<add> // an PlacementAndUpdate.
<ide> workInProgress.effectTag |= Update;
<ide> }
<ide> | 1 |
Javascript | Javascript | change decimalplaces to fractionsize | 26c36bb4d17ae90a6ad8717ae10e1a41c03417f3 | <ide><path>src/ng/filter/filters.js
<ide> function currencyFilter($locale) {
<ide> * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
<ide> * If this is not provided then the fraction size is computed from the current locale's number
<ide> * formatting pattern. In the case of the default locale, it will be 3.
<del> * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.
<add> * @returns {string} Number rounded to fractionSize and places a “,” after each third digit.
<ide> *
<ide> * @example
<ide> <example module="numberFilterExample"> | 1 |
Text | Text | change example text in create-a-form-element.md | fc976aba74446414d99ad8541e0389fbbbaf23b1 | <ide><path>curriculum/challenges/english/01-responsive-web-design/basic-html-and-html5/create-a-form-element.md
<ide> You can build web forms that actually submit data to a server using nothing more
<ide>
<ide> For example:
<ide>
<del>`<form action="/url-where-you-want-to-submit-form-data"></form>`
<add>```html
<add><form action="/url-where-you-want-to-submit-form-data">
<add> <input>
<add></form>
<add>```
<ide>
<ide> # --instructions--
<ide> | 1 |
Text | Text | update explanation to match example | ff47b0518b4d97f6115f9c71ded1f8402b8b57d5 | <ide><path>guides/source/routing.md
<ide> Sometimes, you have a resource that clients always look up without referencing a
<ide> get 'profile', to: 'users#show'
<ide> ```
<ide>
<del>Passing a `String` to `match` will expect a `controller#action` format, while passing a `Symbol` will map directly to an action:
<add>Passing a `String` to `get` will expect a `controller#action` format, while passing a `Symbol` will map directly to an action:
<ide>
<ide> ```ruby
<ide> get 'profile', to: :show | 1 |
Ruby | Ruby | try optimise `versioned_formulae_names` | f09be9a5f75b44bfd16033af8b9ec456c24081c4 | <ide><path>Library/Homebrew/formula.rb
<ide> def versioned_formula?
<ide> # Returns any `@`-versioned formulae names for any formula (including versioned formulae).
<ide> sig { returns(T::Array[String]) }
<ide> def versioned_formulae_names
<del> Pathname.glob(path.to_s.gsub(/(@[\d.]+)?\.rb$/, "@*.rb")).map do |versioned_path|
<add> versioned_paths = if tap
<add> # Faster path, due to `tap.versioned_formula_files` caching.
<add> name_prefix = "#{name.gsub(/(@[\d.]+)?$/, "")}@"
<add> tap.versioned_formula_files.select do |file|
<add> file.basename.to_s.start_with?(name_prefix)
<add> end
<add> else
<add> Pathname.glob(path.to_s.gsub(/(@[\d.]+)?\.rb$/, "@*.rb"))
<add> end
<add>
<add> versioned_paths.map do |versioned_path|
<ide> next if versioned_path == path
<ide>
<ide> versioned_path.basename(".rb").to_s | 1 |
PHP | PHP | add singular syntactic sugar | 913c2a1a6ef70a1574c69c0dbb178f2e0b8c6ea8 | <ide><path>src/Illuminate/Foundation/Testing/Wormhole.php
<ide> public function __construct($value)
<ide> $this->value = $value;
<ide> }
<ide>
<add> /**
<add> * Travel forward the given number of milliseconds.
<add> *
<add> * @param callable|null $callback
<add> * @return mixed
<add> */
<add> public function millisecond($callback = null)
<add> {
<add> return $this->milliseconds($callback);
<add> }
<add>
<ide> /**
<ide> * Travel forward the given number of milliseconds.
<ide> *
<ide> public function milliseconds($callback = null)
<ide> return $this->handleCallback($callback);
<ide> }
<ide>
<add> /**
<add> * Travel forward the given number of seconds.
<add> *
<add> * @param callable|null $callback
<add> * @return mixed
<add> */
<add> public function second($callback = null)
<add> {
<add> return $this->seconds($callback);
<add> }
<add>
<ide> /**
<ide> * Travel forward the given number of seconds.
<ide> *
<ide> public function minutes($callback = null)
<ide> return $this->handleCallback($callback);
<ide> }
<ide>
<add> /**
<add> * Travel forward the given number of hours.
<add> *
<add> * @param callable|null $callback
<add> * @return mixed
<add> */
<add> public function hour($callback = null)
<add> {
<add> return $this->hours($callback);
<add> }
<add>
<ide> /**
<ide> * Travel forward the given number of hours.
<ide> *
<ide> public function hours($callback = null)
<ide> return $this->handleCallback($callback);
<ide> }
<ide>
<add> /**
<add> * Travel forward the given number of days.
<add> *
<add> * @param callable|null $callback
<add> * @return mixed
<add> */
<add> public function day($callback = null)
<add> {
<add> return $this->days($callback);
<add> }
<add>
<ide> /**
<ide> * Travel forward the given number of days.
<ide> *
<ide> public function days($callback = null)
<ide> return $this->handleCallback($callback);
<ide> }
<ide>
<add> /**
<add> * Travel forward the given number of weeks.
<add> *
<add> * @param callable|null $callback
<add> * @return mixed
<add> */
<add> public function week($callback = null)
<add> {
<add> return $this->weeks($callback);
<add> }
<add>
<ide> /**
<ide> * Travel forward the given number of weeks.
<ide> *
<ide> public function weeks($callback = null)
<ide> return $this->handleCallback($callback);
<ide> }
<ide>
<add> /**
<add> * Travel forward the given number of months.
<add> *
<add> * @param callable|null $callback
<add> * @return mixed
<add> */
<add> public function month($callback = null)
<add> {
<add> return $this->months($callback);
<add> }
<add>
<ide> /**
<ide> * Travel forward the given number of months.
<ide> *
<ide> public function months($callback = null)
<ide> return $this->handleCallback($callback);
<ide> }
<ide>
<add> /**
<add> * Travel forward the given number of years.
<add> *
<add> * @param callable|null $callback
<add> * @return mixed
<add> */
<add> public function year($callback = null)
<add> {
<add> return $this->years($callback);
<add> }
<add>
<ide> /**
<ide> * Travel forward the given number of years.
<ide> * | 1 |
Text | Text | remove references to the makefile from the readme | 2decd0510d8bd70fe7bbae9ebbacc49717376cfd | <ide><path>README.md
<ide> As the source code is handled by the version control system Git, it's useful to
<ide>
<ide> ### Submodules ###
<ide>
<del>The repository uses submodules, which normally are handled directly by the Makefile, but sometimes you want to
<add>The repository uses submodules, which normally are handled directly by the `grunt update_submodules` command, but sometimes you want to
<ide> be able to work with them manually.
<ide>
<ide> Following are the steps to manually get the submodules: | 1 |
PHP | PHP | enable strict types and add missing docblocks | 669edca058b30c351df5eba901e8c7864f4bdab3 | <ide><path>src/View/Exception/MissingCellException.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> */
<ide> class MissingCellException extends Exception
<ide> {
<add> /**
<add> * {@inheritDoc}
<add> */
<ide> protected $_messageTemplate = 'Cell class %s is missing.';
<ide> }
<ide><path>src/View/Exception/MissingCellViewException.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> */
<ide> class MissingCellViewException extends Exception
<ide> {
<add> /**
<add> * {@inheritDoc}
<add> */
<ide> protected $_messageTemplate = 'Cell view file "%s" is missing.';
<ide> }
<ide><path>src/View/Exception/MissingElementException.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> class MissingElementException extends Exception
<ide> {
<ide> /**
<del> * Message template
<del> *
<del> * @var string
<add> * {@inheritDoc}
<ide> */
<ide> protected $_messageTemplate = 'Element file "%s" is missing.';
<ide> }
<ide><path>src/View/Exception/MissingHelperException.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> */
<ide> class MissingHelperException extends Exception
<ide> {
<add> /**
<add> * {@inheritDoc}
<add> */
<ide> protected $_messageTemplate = 'Helper class %s could not be found.';
<ide> }
<ide><path>src/View/Exception/MissingLayoutException.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> */
<ide> class MissingLayoutException extends Exception
<ide> {
<add> /**
<add> * {@inheritDoc}
<add> */
<ide> protected $_messageTemplate = 'Layout file "%s" is missing.';
<ide> }
<ide><path>src/View/Exception/MissingTemplateException.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> */
<ide> class MissingTemplateException extends Exception
<ide> {
<add> /**
<add> * {@inheritDoc}
<add> */
<ide> protected $_messageTemplate = 'Template file "%s" is missing.';
<ide> }
<ide><path>src/View/Exception/MissingViewException.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> */
<ide> class MissingViewException extends Exception
<ide> {
<add> /**
<add> * {@inheritDoc}
<add> */
<ide> protected $_messageTemplate = 'View class "%s" is missing.';
<ide> } | 7 |
PHP | PHP | adjust comment spacing | e569dc47a72fd2b4d322c5a96b2ca334ac18c89f | <ide><path>src/Illuminate/Database/Schema/Grammars/Grammar.php
<ide> protected function getTableWithColumnChanges(Blueprint $blueprint, Table $table)
<ide> $column = $this->getDoctrineColumnForChange($table, $fluent);
<ide>
<ide> // Here we will spin through each fluent column definition and map it to the proper
<del> // Doctrine column definitions, which is necessary because Laravel and Doctrine
<add> // Doctrine column definitions - which is necessary because Laravel and Doctrine
<ide> // use some different terminology for various column attributes on the tables.
<ide> foreach ($fluent->getAttributes() as $key => $value) {
<ide> if (! is_null($option = $this->mapFluentOptionToDoctrine($key))) { | 1 |
Javascript | Javascript | add modelview and normalview matrices | 4093be22f8061f7bcd6c9fd564f83d0ee0eb0846 | <ide><path>src/renderers/WebGLRenderer.js
<ide> function WebGLRenderer( parameters ) {
<ide> object.onBeforeRender( _this, scene, camera, geometry, material, group );
<ide> currentRenderState = renderStates.get( scene, _currentArrayCamera || camera );
<ide>
<del> object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
<del> object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
<add> if ( multiview.isEnabled() ) {
<add>
<add> multiview.computeObjectMatrices( object, camera );
<add>
<add> } else {
<add>
<add> object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
<add> object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
<add>
<add> }
<ide>
<ide> if ( object.isImmediateRenderObject ) {
<ide>
<ide> function WebGLRenderer( parameters ) {
<ide>
<ide> // common matrices
<ide>
<del> p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
<del> p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
<add> if ( material.supportsMultiview && multiview.isEnabled() ) {
<add>
<add> p_uniforms.setValue( _gl, 'modelViewMatrices', object.modelViewMatrices );
<add> p_uniforms.setValue( _gl, 'normalMatrices', object.normalMatrices );
<add>
<add> } else {
<add>
<add> p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
<add> p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
<add>
<add> }
<add>
<ide> p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
<ide>
<ide> return program;
<ide><path>src/renderers/webgl/WebGLMultiview.js
<ide> */
<ide>
<ide> import { WebGLRenderTarget } from '../WebGLRenderTarget.js';
<add>import { Matrix3 } from '../../math/Matrix3.js';
<add>import { Matrix4 } from '../../math/Matrix4.js';
<ide>
<ide> function WebGLMultiview( requested, gl, canvas, extensions, capabilities, properties ) {
<ide>
<ide> function WebGLMultiview( requested, gl, canvas, extensions, capabilities, proper
<ide>
<ide> };
<ide>
<del>
<ide> if ( requested && ! this.isAvailable() ) {
<ide>
<ide> console.warn( 'WebGLRenderer: Multiview requested but not supported by the browser' );
<ide> function WebGLMultiview( requested, gl, canvas, extensions, capabilities, proper
<ide> depthStencil: null
<ide> };
<ide>
<add> this.computeObjectMatrices = function ( object, camera ) {
<add>
<add> if ( ! object.modelViewMatrices ) {
<add>
<add> object.modelViewMatrices = new Array( numViews );
<add> object.normalMatrices = new Array( numViews );
<add>
<add> for ( var i = 0; i < numViews; i ++ ) {
<add>
<add> object.modelViewMatrices[ i ] = new Matrix4();
<add> object.normalMatrices[ i ] = new Matrix3();
<add>
<add> }
<add>
<add> }
<add>
<add> if ( camera.isArrayCamera ) {
<add>
<add> for ( var i = 0; i < numViews; i ++ ) {
<add>
<add> object.modelViewMatrices[ i ].multiplyMatrices( camera.cameras[ i ].matrixWorldInverse, object.matrixWorld );
<add> object.normalMatrices[ i ].getNormalMatrix( object.modelViewMatrices[ i ] );
<add>
<add> }
<add>
<add> } else {
<add>
<add> // In this case we still need to provide an array of matrices but just the first one will be used
<add> object.modelViewMatrices[ 0 ].multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
<add> object.normalMatrices[ 0 ].getNormalMatrix( object.modelViewMatrices[ 0 ] );
<add>
<add> for ( var i = 0; i < numViews; i ++ ) {
<add>
<add> object.modelViewMatrices[ i ].copy( object.modelViewMatrices[ 0 ] );
<add> object.normalMatrices[ i ].copy( object.normalMatrices[ 0 ] );
<add>
<add> }
<add>
<add> }
<add>
<add> };
<ide>
<ide> // @todo Get ArrayCamera
<ide> this.createMultiviewRenderTargetTexture = function () {
<ide><path>src/renderers/webgl/WebGLProgram.js
<ide> function WebGLProgram( renderer, extensions, code, material, shader, parameters,
<ide> 'uniform vec3 cameraPosition;',
<ide>
<ide> material.supportsMultiview && renderer.multiview.isEnabled() ? [
<del> 'uniform mat4 modelViewMatrix;',
<del> 'uniform mat3 normalMatrix;',
<add> 'uniform mat4 modelViewMatrices[2];',
<add> 'uniform mat3 normalMatrices[2];',
<ide> 'uniform mat4 viewMatrices[2];',
<ide> 'uniform mat4 projectionMatrices[2];',
<ide>
<add> '#define modelViewMatrix modelViewMatrices[VIEW_ID]',
<add> '#define normalMatrix normalMatrices[VIEW_ID]',
<ide> '#define viewMatrix viewMatrices[VIEW_ID]',
<ide> '#define projectionMatrix projectionMatrices[VIEW_ID]'
<ide> | 3 |
Text | Text | fix minor typo in readme | 8e7f9973b2b133f31f10aae0505ff14a2514734a | <ide><path>Readme.md
<ide> So far, we get:
<ide> - Server rendering and indexing of `./pages`
<ide> - Static file serving. `./static/` is mapped to `/static/`
<ide>
<del>To see how simple this is, check out the [sample app - nextagram](https://github.com/zeit/nextgram)
<add>To see how simple this is, check out the [sample app - nextgram](https://github.com/zeit/nextgram)
<ide>
<ide> ### Bundling (code splitting)
<ide> | 1 |
Python | Python | fix broken method call when config is none | 545a7ff20a4ff4f25cf97ee076eb60ca397b0e2f | <ide><path>glances/plugins/glances_processlist.py
<ide> def __init__(self, args=None, config=None):
<ide> self.pid_max = glances_processes.pid_max
<ide>
<ide> # Set the default sort key if it is defined in the configuration file
<del> if 'processlist' in config.as_dict() and 'sort_key' in config.as_dict()['processlist']:
<del> logger.debug('Configuration overwrites processes sort key by {}'.format(config.as_dict()['processlist']['sort_key']))
<del> glances_processes.set_sort_key(config.as_dict()['processlist']['sort_key'], False)
<add> if config is not None:
<add> if 'processlist' in config.as_dict() and 'sort_key' in config.as_dict()['processlist']:
<add> logger.debug('Configuration overwrites processes sort key by {}'.format(config.as_dict()['processlist']['sort_key']))
<add> glances_processes.set_sort_key(config.as_dict()['processlist']['sort_key'], False)
<ide>
<ide> # Note: 'glances_processes' is already init in the processes.py script
<ide> | 1 |
Javascript | Javascript | use strict mode | 4bb529d972afaa02d57a2ca29db33ac92f69b81d | <ide><path>benchmark/arrays/var-int.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var bench = common.createBenchmark(main, {
<ide> type: 'Array Buffer Int8Array Uint8Array Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array'.split(' '),
<ide><path>benchmark/arrays/zero-float.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var bench = common.createBenchmark(main, {
<ide> type: 'Array Buffer Int8Array Uint8Array Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array'.split(' '),
<ide><path>benchmark/arrays/zero-int.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var bench = common.createBenchmark(main, {
<ide> type: 'Array Buffer Int8Array Uint8Array Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array'.split(' '),
<ide><path>benchmark/buffers/buffer-base64-decode.js
<add>'use strict';
<ide> var assert = require('assert');
<ide> var common = require('../common.js');
<ide>
<ide><path>benchmark/buffers/buffer-base64-encode.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide>
<ide> var bench = common.createBenchmark(main, {});
<ide><path>benchmark/buffers/buffer-bytelength.js
<add>'use strict';
<ide> var common = require('../common');
<ide>
<ide> var bench = common.createBenchmark(main, {
<ide><path>benchmark/buffers/buffer-compare.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide>
<ide> var bench = common.createBenchmark(main, {
<ide><path>benchmark/buffers/buffer-creation.js
<del>SlowBuffer = require('buffer').SlowBuffer;
<add>'use strict';
<add>const SlowBuffer = require('buffer').SlowBuffer;
<ide>
<ide> var common = require('../common.js');
<ide> var bench = common.createBenchmark(main, {
<ide><path>benchmark/buffers/buffer-indexof.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var fs = require('fs');
<ide>
<ide><path>benchmark/buffers/buffer-iterate.js
<add>'use strict';
<ide> var SlowBuffer = require('buffer').SlowBuffer;
<ide> var common = require('../common.js');
<ide> var assert = require('assert');
<ide><path>benchmark/buffers/buffer-read.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide>
<ide> var bench = common.createBenchmark(main, {
<ide><path>benchmark/buffers/buffer-slice.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var SlowBuffer = require('buffer').SlowBuffer;
<ide>
<ide><path>benchmark/buffers/buffer-write.js
<del>
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var bench = common.createBenchmark(main, {
<ide> noAssert: [false, true],
<ide><path>benchmark/buffers/dataview-set.js
<del>
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var bench = common.createBenchmark(main, {
<ide> type: ['Uint8', 'Uint16LE', 'Uint16BE',
<ide><path>benchmark/common.js
<add>'use strict';
<ide> var assert = require('assert');
<ide> var fs = require('fs');
<ide> var path = require('path');
<ide><path>benchmark/compare.js
<add>'use strict';
<ide> var usage = 'node benchmark/compare.js ' +
<ide> '<node-binary1> <node-binary2> ' +
<ide> '[--html] [--red|-r] [--green|-g] ' +
<ide> for (var i = 2; i < process.argv.length; i++) {
<ide>
<ide> if (!html) {
<ide> var start = '';
<del> var green = '\033[1;32m';
<del> var red = '\033[1;31m';
<del> var reset = '\033[m';
<add> var green = '\u001b[1;32m';
<add> var red = '\u001b[1;31m';
<add> var reset = '\u001b[m';
<ide> var end = '';
<ide> } else {
<ide> var start = '<pre style="background-color:#333;color:#eee">';
<ide><path>benchmark/crypto/aes-gcm-throughput.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var crypto = require('crypto');
<ide> var keylen = {'aes-128-gcm': 16, 'aes-192-gcm': 24, 'aes-256-gcm': 32};
<ide><path>benchmark/crypto/cipher-stream.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide>
<ide> var bench = common.createBenchmark(main, {
<ide><path>benchmark/crypto/hash-stream-creation.js
<ide> // throughput benchmark
<ide> // creates a single hasher, then pushes a bunch of data through it
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var crypto = require('crypto');
<ide>
<ide><path>benchmark/crypto/hash-stream-throughput.js
<ide> // throughput benchmark
<ide> // creates a single hasher, then pushes a bunch of data through it
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var crypto = require('crypto');
<ide>
<ide><path>benchmark/crypto/rsa-encrypt-decrypt-throughput.js
<add>'use strict';
<ide> // throughput benchmark in signing and verifying
<ide> var common = require('../common.js');
<ide> var crypto = require('crypto');
<ide><path>benchmark/crypto/rsa-sign-verify-throughput.js
<add>'use strict';
<ide> // throughput benchmark in signing and verifying
<ide> var common = require('../common.js');
<ide> var crypto = require('crypto');
<ide><path>benchmark/events/ee-add-remove.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var events = require('events');
<ide>
<ide><path>benchmark/events/ee-emit-multi-args.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var EventEmitter = require('events').EventEmitter;
<ide>
<ide><path>benchmark/events/ee-emit.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var EventEmitter = require('events').EventEmitter;
<ide>
<ide><path>benchmark/events/ee-listener-count-on-prototype.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var EventEmitter = require('events').EventEmitter;
<ide>
<ide><path>benchmark/events/ee-listeners-many.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var EventEmitter = require('events').EventEmitter;
<ide>
<ide><path>benchmark/events/ee-listeners.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var EventEmitter = require('events').EventEmitter;
<ide>
<ide><path>benchmark/fs-write-stream-throughput.js
<del>
<ide> // If there are no args, then this is the root. Run all the benchmarks!
<add>'use strict';
<ide> if (!process.argv[2])
<ide> parent();
<ide> else
<ide><path>benchmark/fs/read-stream-throughput.js
<ide> // test the throughput of the fs.WriteStream class.
<add>'use strict';
<ide>
<ide> var path = require('path');
<ide> var common = require('../common.js');
<ide><path>benchmark/fs/readfile.js
<ide> // Call fs.readFile over and over again really fast.
<ide> // Then see how many times it got called.
<ide> // Yes, this is a silly benchmark. Most benchmarks are silly.
<add>'use strict';
<ide>
<ide> var path = require('path');
<ide> var common = require('../common.js');
<ide><path>benchmark/fs/write-stream-throughput.js
<ide> // test the throughput of the fs.WriteStream class.
<add>'use strict';
<ide>
<ide> var path = require('path');
<ide> var common = require('../common.js');
<ide><path>benchmark/http/chunked.js
<ide> // always as hot as it could be.
<ide> //
<ide> // Verify that our assumptions are valid.
<add>'use strict';
<ide>
<ide> var common = require('../common.js');
<ide> var PORT = common.PORT;
<ide> var bench = common.createBenchmark(main, {
<ide> });
<ide>
<ide> function main(conf) {
<del> http = require('http');
<add> const http = require('http');
<ide> var chunk = new Buffer(conf.size);
<ide> chunk.fill('8');
<ide>
<ide><path>benchmark/http/client-request-body.js
<ide> // Measure the time it takes for the HTTP client to send a request body.
<add>'use strict';
<ide>
<ide> var common = require('../common.js');
<ide> var http = require('http');
<ide><path>benchmark/http/cluster.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var PORT = common.PORT;
<ide>
<ide><path>benchmark/http/end-vs-write-end.js
<ide> // always as hot as it could be.
<ide> //
<ide> // Verify that our assumptions are valid.
<add>'use strict';
<ide>
<ide> var common = require('../common.js');
<ide> var PORT = common.PORT;
<ide> var bench = common.createBenchmark(main, {
<ide> });
<ide>
<ide> function main(conf) {
<del> http = require('http');
<add> const http = require('http');
<ide> var chunk;
<ide> var len = conf.kb * 1024;
<ide> switch (conf.type) {
<ide> function main(conf) {
<ide> chunk.fill('x');
<ide> break;
<ide> case 'utf':
<del> encoding = 'utf8';
<ide> chunk = new Array(len / 2 + 1).join('ü');
<ide> break;
<ide> case 'asc':
<ide><path>benchmark/http/simple.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var PORT = common.PORT;
<ide>
<ide><path>benchmark/http_bench.js
<add>'use strict';
<ide> var spawn = require('child_process').spawn;
<ide> var cluster = require('cluster');
<ide> var http = require('http');
<ide><path>benchmark/http_server_lag.js
<add>'use strict';
<add>
<ide> var http = require('http');
<ide> var port = parseInt(process.env.PORT, 10) || 8000;
<ide> var defaultLag = parseInt(process.argv[2], 10) || 100;
<ide><path>benchmark/http_simple.js
<add>'use strict';
<add>
<ide> var path = require('path'),
<ide> exec = require('child_process').exec,
<ide> http = require('http');
<ide><path>benchmark/http_simple_auto.js
<ide> // <args> Arguments to pass to `ab`.
<ide> // <target> Target to benchmark, e.g. `bytes/1024` or `buffer/8192`.
<ide> //
<add>'use strict';
<ide>
<ide> var path = require("path");
<ide> var http = require("http");
<ide><path>benchmark/http_simple_cluster.js
<add>'use strict';
<ide> var cluster = require('cluster');
<ide> var os = require('os');
<ide>
<ide><path>benchmark/idle_clients.js
<del>net = require('net');
<add>'use strict';
<add>const net = require('net');
<ide>
<ide> var errors = 0, connections = 0;
<ide>
<ide><path>benchmark/misc/child-process-read.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var bench = common.createBenchmark(main, {
<ide> len: [64, 256, 1024, 4096, 32768],
<ide><path>benchmark/misc/domain-fn-args.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var domain = require('domain');
<ide>
<ide> var gargs = [1, 2, 3];
<ide> function main(conf) {
<ide>
<ide> var args, ret, n = +conf.n;
<del> var arguments = gargs.slice(0, conf.arguments);
<add> var myArguments = gargs.slice(0, conf.arguments);
<ide> bench.start();
<ide>
<ide> bdomain.enter();
<ide> for (var i = 0; i < n; i++) {
<del> if (arguments.length >= 2) {
<del> args = Array.prototype.slice.call(arguments, 1);
<add> if (myArguments.length >= 2) {
<add> args = Array.prototype.slice.call(myArguments, 1);
<ide> ret = fn.apply(this, args);
<ide> } else {
<ide> ret = fn.call(this);
<ide><path>benchmark/misc/function_call/index.js
<ide> // relative to a comparable C++ function.
<ide> // Reports millions of calls per second.
<ide> // Note that JS speed goes up, while cxx speed stays about the same.
<add>'use strict';
<ide>
<ide> var assert = require('assert');
<ide> var common = require('../../common.js');
<ide><path>benchmark/misc/module-loader.js
<add>'use strict';
<ide> var fs = require('fs');
<ide> var path = require('path');
<ide> var common = require('../common.js');
<ide><path>benchmark/misc/next-tick-breadth.js
<add>'use strict';
<ide>
<ide> var common = require('../common.js');
<ide> var bench = common.createBenchmark(main, {
<ide><path>benchmark/misc/next-tick-depth.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var bench = common.createBenchmark(main, {
<ide> millions: [2]
<ide><path>benchmark/misc/spawn-echo.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var bench = common.createBenchmark(main, {
<ide> thousands: [1]
<ide><path>benchmark/misc/startup.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var spawn = require('child_process').spawn;
<ide> var path = require('path');
<ide><path>benchmark/misc/string-creation.js
<add>'use strict';
<ide>
<ide> var common = require('../common.js');
<ide> var bench = common.createBenchmark(main, {
<ide><path>benchmark/misc/string-decoder.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var StringDecoder = require('string_decoder').StringDecoder;
<ide>
<ide><path>benchmark/misc/timers.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide>
<ide> var bench = common.createBenchmark(main, {
<ide><path>benchmark/misc/url.js
<add>'use strict';
<ide> var url = require('url')
<ide> var n = 25 * 100;
<ide>
<ide><path>benchmark/misc/v8-bench.js
<ide> // compare with "google-chrome deps/v8/benchmarks/run.html"
<add>'use strict';
<ide> var fs = require('fs');
<ide> var path = require('path');
<ide> var vm = require('vm');
<ide><path>benchmark/net/net-c2s-cork.js
<ide> // test the speed of .pipe() with sockets
<add>'use strict';
<ide>
<ide> var common = require('../common.js');
<ide> var PORT = common.PORT;
<ide><path>benchmark/net/net-c2s.js
<ide> // test the speed of .pipe() with sockets
<add>'use strict';
<ide>
<ide> var common = require('../common.js');
<ide> var PORT = common.PORT;
<ide><path>benchmark/net/net-pipe.js
<ide> // test the speed of .pipe() with sockets
<add>'use strict';
<ide>
<ide> var common = require('../common.js');
<ide> var PORT = common.PORT;
<ide><path>benchmark/net/net-s2c.js
<ide> // test the speed of .pipe() with sockets
<add>'use strict';
<ide>
<ide> var common = require('../common.js');
<ide> var PORT = common.PORT;
<ide><path>benchmark/net/tcp-raw-c2s.js
<ide> // In this benchmark, we connect a client to the server, and write
<ide> // as many bytes as we can in the specified time (default = 10s)
<add>'use strict';
<ide>
<ide> var common = require('../common.js');
<ide> var util = require('util');
<ide><path>benchmark/net/tcp-raw-pipe.js
<ide> // In this benchmark, we connect a client to the server, and write
<ide> // as many bytes as we can in the specified time (default = 10s)
<add>'use strict';
<ide>
<ide> var common = require('../common.js');
<ide> var util = require('util');
<ide><path>benchmark/net/tcp-raw-s2c.js
<ide> // In this benchmark, we connect a client to the server, and write
<ide> // as many bytes as we can in the specified time (default = 10s)
<add>'use strict';
<ide>
<ide> var common = require('../common.js');
<ide> var util = require('util');
<ide><path>benchmark/path/basename-posix.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var path = require('path');
<ide> var v8 = require('v8');
<ide><path>benchmark/path/basename-win32.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var path = require('path');
<ide> var v8 = require('v8');
<ide><path>benchmark/path/dirname-posix.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var path = require('path');
<ide> var v8 = require('v8');
<ide><path>benchmark/path/dirname-win32.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var path = require('path');
<ide> var v8 = require('v8');
<ide><path>benchmark/path/extname-posix.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var path = require('path');
<ide> var v8 = require('v8');
<ide><path>benchmark/path/extname-win32.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var path = require('path');
<ide> var v8 = require('v8');
<ide><path>benchmark/path/format-posix.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var path = require('path');
<ide> var v8 = require('v8');
<ide><path>benchmark/path/format-win32.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var path = require('path');
<ide> var v8 = require('v8');
<ide><path>benchmark/path/isAbsolute-posix.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var path = require('path');
<ide> var v8 = require('v8');
<ide><path>benchmark/path/isAbsolute-win32.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var path = require('path');
<ide> var v8 = require('v8');
<ide><path>benchmark/path/join-posix.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var path = require('path');
<ide> var v8 = require('v8');
<ide><path>benchmark/path/join-win32.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var path = require('path');
<ide> var v8 = require('v8');
<ide><path>benchmark/path/makeLong-win32.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var path = require('path');
<ide> var v8 = require('v8');
<ide><path>benchmark/path/normalize-posix.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var path = require('path');
<ide> var v8 = require('v8');
<ide><path>benchmark/path/normalize-win32.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var path = require('path');
<ide> var v8 = require('v8');
<ide><path>benchmark/path/parse-posix.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var path = require('path');
<ide> var v8 = require('v8');
<ide><path>benchmark/path/parse-win32.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var path = require('path');
<ide> var v8 = require('v8');
<ide><path>benchmark/path/relative-posix.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var path = require('path');
<ide> var v8 = require('v8');
<ide><path>benchmark/path/relative-win32.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var path = require('path');
<ide> var v8 = require('v8');
<ide><path>benchmark/path/resolve-posix.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var path = require('path');
<ide> var v8 = require('v8');
<ide><path>benchmark/path/resolve-win32.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var path = require('path');
<ide> var v8 = require('v8');
<ide><path>benchmark/querystring/querystring-parse.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var querystring = require('querystring');
<ide> var v8 = require('v8');
<ide><path>benchmark/querystring/querystring-stringify.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var querystring = require('querystring');
<ide> var v8 = require('v8');
<ide><path>benchmark/report-startup-memory.js
<add>'use strict';
<ide> console.log(process.memoryUsage().rss);
<ide><path>benchmark/static_http_server.js
<add>'use strict';
<ide> var http = require('http');
<ide>
<ide> var concurrency = 30;
<ide><path>benchmark/tls/throughput.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var bench = common.createBenchmark(main, {
<ide> dur: [5],
<ide><path>benchmark/tls/tls-connect.js
<add>'use strict';
<ide> var assert = require('assert'),
<ide> fs = require('fs'),
<ide> path = require('path'),
<ide><path>benchmark/url/url-parse.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var url = require('url');
<ide> var v8 = require('v8');
<ide><path>benchmark/url/url-resolve.js
<add>'use strict';
<ide> var common = require('../common.js');
<ide> var url = require('url');
<ide> var v8 = require('v8');
<ide><path>benchmark/util/inspect.js
<add>'use strict';
<ide> var util = require('util');
<ide>
<ide> var common = require('../common.js'); | 93 |
Text | Text | fix a small typo in help files | 667577664051e07fceea25a73fef9e1119366435 | <ide><path>docs/templates/getting-started/faq.md
<ide> Code and pre-trained weights are available for the following image classificatio
<ide> They can be imported from the module `keras.applications`:
<ide>
<ide> ```python
<del>from keras.applications.vgg16 impoprt VGG16
<del>from keras.applications.vgg19 impoprt VGG19
<del>from keras.applications.resnet50 impoprt ResNet50
<del>from keras.applications.inception_v3 impoprt InceptionV3
<add>from keras.applications.vgg16 import VGG16
<add>from keras.applications.vgg19 import VGG19
<add>from keras.applications.resnet50 import ResNet50
<add>from keras.applications.inception_v3 import InceptionV3
<ide>
<ide> model = VGG16(weights='imagenet', include_top=True)
<ide> ``` | 1 |
Go | Go | fix resolv.conf and hosts handling in sandbox | ef659c904966d5a1419b795fe32d940940f71333 | <ide><path>libnetwork/resolvconf/resolvconf.go
<ide> var lastModified struct {
<ide> contents []byte
<ide> }
<ide>
<del>// Get returns the contents of /etc/resolv.conf
<del>func Get() ([]byte, error) {
<add>// File contains the resolv.conf content and its hash
<add>type File struct {
<add> Content []byte
<add> Hash string
<add>}
<add>
<add>// Get returns the contents of /etc/resolv.conf and its hash
<add>func Get() (*File, error) {
<ide> resolv, err := ioutil.ReadFile("/etc/resolv.conf")
<ide> if err != nil {
<ide> return nil, err
<ide> }
<del> return resolv, nil
<add> hash, err := ioutils.HashData(bytes.NewReader(resolv))
<add> if err != nil {
<add> return nil, err
<add> }
<add> return &File{Content: resolv, Hash: hash}, nil
<add>}
<add>
<add>// GetSpecific returns the contents of the user specified resolv.conf file and its hash
<add>func GetSpecific(path string) (*File, error) {
<add> resolv, err := ioutil.ReadFile(path)
<add> if err != nil {
<add> return nil, err
<add> }
<add> hash, err := ioutils.HashData(bytes.NewReader(resolv))
<add> if err != nil {
<add> return nil, err
<add> }
<add> return &File{Content: resolv, Hash: hash}, nil
<ide> }
<ide>
<ide> // GetIfChanged retrieves the host /etc/resolv.conf file, checks against the last hash
<ide> // and, if modified since last check, returns the bytes and new hash.
<ide> // This feature is used by the resolv.conf updater for containers
<del>func GetIfChanged() ([]byte, string, error) {
<add>func GetIfChanged() (*File, error) {
<ide> lastModified.Lock()
<ide> defer lastModified.Unlock()
<ide>
<ide> resolv, err := ioutil.ReadFile("/etc/resolv.conf")
<ide> if err != nil {
<del> return nil, "", err
<add> return nil, err
<ide> }
<ide> newHash, err := ioutils.HashData(bytes.NewReader(resolv))
<ide> if err != nil {
<del> return nil, "", err
<add> return nil, err
<ide> }
<ide> if lastModified.sha256 != newHash {
<ide> lastModified.sha256 = newHash
<ide> lastModified.contents = resolv
<del> return resolv, newHash, nil
<add> return &File{Content: resolv, Hash: newHash}, nil
<ide> }
<ide> // nothing changed, so return no data
<del> return nil, "", nil
<add> return nil, nil
<ide> }
<ide>
<ide> // GetLastModified retrieves the last used contents and hash of the host resolv.conf.
<ide> // Used by containers updating on restart
<del>func GetLastModified() ([]byte, string) {
<add>func GetLastModified() *File {
<ide> lastModified.Lock()
<ide> defer lastModified.Unlock()
<ide>
<del> return lastModified.contents, lastModified.sha256
<add> return &File{Content: lastModified.contents, Hash: lastModified.sha256}
<ide> }
<ide>
<ide> // FilterResolvDNS cleans up the config in resolvConf. It has two main jobs:
<ide> func GetLastModified() ([]byte, string) {
<ide> // 2. Given the caller provides the enable/disable state of IPv6, the filter
<ide> // code will remove all IPv6 nameservers if it is not enabled for containers
<ide> //
<del>// It returns a boolean to notify the caller if changes were made at all
<del>func FilterResolvDNS(resolvConf []byte, ipv6Enabled bool) ([]byte, bool) {
<del> changed := false
<add>func FilterResolvDNS(resolvConf []byte, ipv6Enabled bool) (*File, error) {
<ide> cleanedResolvConf := localhostNSRegexp.ReplaceAll(resolvConf, []byte{})
<ide> // if IPv6 is not enabled, also clean out any IPv6 address nameserver
<ide> if !ipv6Enabled {
<ide> func FilterResolvDNS(resolvConf []byte, ipv6Enabled bool) ([]byte, bool) {
<ide> }
<ide> cleanedResolvConf = append(cleanedResolvConf, []byte("\n"+strings.Join(dns, "\n"))...)
<ide> }
<del> if !bytes.Equal(resolvConf, cleanedResolvConf) {
<del> changed = true
<add> hash, err := ioutils.HashData(bytes.NewReader(cleanedResolvConf))
<add> if err != nil {
<add> return nil, err
<ide> }
<del> return cleanedResolvConf, changed
<add> return &File{Content: cleanedResolvConf, Hash: hash}, nil
<ide> }
<ide>
<ide> // getLines parses input into lines and strips away comments.
<ide> func GetOptions(resolvConf []byte) []string {
<ide> // Build writes a configuration file to path containing a "nameserver" entry
<ide> // for every element in dns, a "search" entry for every element in
<ide> // dnsSearch, and an "options" entry for every element in dnsOptions.
<del>func Build(path string, dns, dnsSearch, dnsOptions []string) (string, error) {
<add>func Build(path string, dns, dnsSearch, dnsOptions []string) (*File, error) {
<ide> content := bytes.NewBuffer(nil)
<ide> if len(dnsSearch) > 0 {
<ide> if searchString := strings.Join(dnsSearch, " "); strings.Trim(searchString, " ") != "." {
<ide> if _, err := content.WriteString("search " + searchString + "\n"); err != nil {
<del> return "", err
<add> return nil, err
<ide> }
<ide> }
<ide> }
<ide> for _, dns := range dns {
<ide> if _, err := content.WriteString("nameserver " + dns + "\n"); err != nil {
<del> return "", err
<add> return nil, err
<ide> }
<ide> }
<ide> if len(dnsOptions) > 0 {
<ide> if optsString := strings.Join(dnsOptions, " "); strings.Trim(optsString, " ") != "" {
<ide> if _, err := content.WriteString("options " + optsString + "\n"); err != nil {
<del> return "", err
<add> return nil, err
<ide> }
<ide> }
<ide> }
<ide>
<ide> hash, err := ioutils.HashData(bytes.NewReader(content.Bytes()))
<ide> if err != nil {
<del> return "", err
<add> return nil, err
<ide> }
<ide>
<del> return hash, ioutil.WriteFile(path, content.Bytes(), 0644)
<add> return &File{Content: content.Bytes(), Hash: hash}, ioutil.WriteFile(path, content.Bytes(), 0644)
<ide> }
<ide><path>libnetwork/resolvconf/resolvconf_test.go
<ide> import (
<ide> "os"
<ide> "testing"
<ide>
<add> "github.com/docker/docker/pkg/ioutils"
<ide> _ "github.com/docker/libnetwork/netutils"
<ide> )
<ide>
<ide> func TestGet(t *testing.T) {
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<del> if string(resolvConfUtils) != string(resolvConfSystem) {
<add> if string(resolvConfUtils.Content) != string(resolvConfSystem) {
<ide> t.Fatalf("/etc/resolv.conf and GetResolvConf have different content.")
<ide> }
<add> hashSystem, err := ioutils.HashData(bytes.NewReader(resolvConfSystem))
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> if resolvConfUtils.Hash != hashSystem {
<add> t.Fatalf("/etc/resolv.conf and GetResolvConf have different hashes.")
<add> }
<ide> }
<ide>
<ide> func TestGetNameservers(t *testing.T) {
<ide> func TestFilterResolvDns(t *testing.T) {
<ide> ns0 := "nameserver 10.16.60.14\nnameserver 10.16.60.21\n"
<ide>
<ide> if result, _ := FilterResolvDNS([]byte(ns0), false); result != nil {
<del> if ns0 != string(result) {
<del> t.Fatalf("Failed No Localhost: expected \n<%s> got \n<%s>", ns0, string(result))
<add> if ns0 != string(result.Content) {
<add> t.Fatalf("Failed No Localhost: expected \n<%s> got \n<%s>", ns0, string(result.Content))
<ide> }
<ide> }
<ide>
<ide> ns1 := "nameserver 10.16.60.14\nnameserver 10.16.60.21\nnameserver 127.0.0.1\n"
<ide> if result, _ := FilterResolvDNS([]byte(ns1), false); result != nil {
<del> if ns0 != string(result) {
<del> t.Fatalf("Failed Localhost: expected \n<%s> got \n<%s>", ns0, string(result))
<add> if ns0 != string(result.Content) {
<add> t.Fatalf("Failed Localhost: expected \n<%s> got \n<%s>", ns0, string(result.Content))
<ide> }
<ide> }
<ide>
<ide> ns1 = "nameserver 10.16.60.14\nnameserver 127.0.0.1\nnameserver 10.16.60.21\n"
<ide> if result, _ := FilterResolvDNS([]byte(ns1), false); result != nil {
<del> if ns0 != string(result) {
<del> t.Fatalf("Failed Localhost: expected \n<%s> got \n<%s>", ns0, string(result))
<add> if ns0 != string(result.Content) {
<add> t.Fatalf("Failed Localhost: expected \n<%s> got \n<%s>", ns0, string(result.Content))
<ide> }
<ide> }
<ide>
<ide> ns1 = "nameserver 127.0.1.1\nnameserver 10.16.60.14\nnameserver 10.16.60.21\n"
<ide> if result, _ := FilterResolvDNS([]byte(ns1), false); result != nil {
<del> if ns0 != string(result) {
<del> t.Fatalf("Failed Localhost: expected \n<%s> got \n<%s>", ns0, string(result))
<add> if ns0 != string(result.Content) {
<add> t.Fatalf("Failed Localhost: expected \n<%s> got \n<%s>", ns0, string(result.Content))
<ide> }
<ide> }
<ide>
<ide> ns1 = "nameserver ::1\nnameserver 10.16.60.14\nnameserver 127.0.2.1\nnameserver 10.16.60.21\n"
<ide> if result, _ := FilterResolvDNS([]byte(ns1), false); result != nil {
<del> if ns0 != string(result) {
<del> t.Fatalf("Failed Localhost: expected \n<%s> got \n<%s>", ns0, string(result))
<add> if ns0 != string(result.Content) {
<add> t.Fatalf("Failed Localhost: expected \n<%s> got \n<%s>", ns0, string(result.Content))
<ide> }
<ide> }
<ide>
<ide> ns1 = "nameserver 10.16.60.14\nnameserver ::1\nnameserver 10.16.60.21\nnameserver ::1"
<ide> if result, _ := FilterResolvDNS([]byte(ns1), false); result != nil {
<del> if ns0 != string(result) {
<del> t.Fatalf("Failed Localhost: expected \n<%s> got \n<%s>", ns0, string(result))
<add> if ns0 != string(result.Content) {
<add> t.Fatalf("Failed Localhost: expected \n<%s> got \n<%s>", ns0, string(result.Content))
<ide> }
<ide> }
<ide>
<ide> // with IPv6 disabled (false param), the IPv6 nameserver should be removed
<ide> ns1 = "nameserver 10.16.60.14\nnameserver 2002:dead:beef::1\nnameserver 10.16.60.21\nnameserver ::1"
<ide> if result, _ := FilterResolvDNS([]byte(ns1), false); result != nil {
<del> if ns0 != string(result) {
<del> t.Fatalf("Failed Localhost+IPv6 off: expected \n<%s> got \n<%s>", ns0, string(result))
<add> if ns0 != string(result.Content) {
<add> t.Fatalf("Failed Localhost+IPv6 off: expected \n<%s> got \n<%s>", ns0, string(result.Content))
<ide> }
<ide> }
<ide>
<ide> // with IPv6 enabled, the IPv6 nameserver should be preserved
<ide> ns0 = "nameserver 10.16.60.14\nnameserver 2002:dead:beef::1\nnameserver 10.16.60.21\n"
<ide> ns1 = "nameserver 10.16.60.14\nnameserver 2002:dead:beef::1\nnameserver 10.16.60.21\nnameserver ::1"
<ide> if result, _ := FilterResolvDNS([]byte(ns1), true); result != nil {
<del> if ns0 != string(result) {
<del> t.Fatalf("Failed Localhost+IPv6 on: expected \n<%s> got \n<%s>", ns0, string(result))
<add> if ns0 != string(result.Content) {
<add> t.Fatalf("Failed Localhost+IPv6 on: expected \n<%s> got \n<%s>", ns0, string(result.Content))
<ide> }
<ide> }
<ide>
<ide> // with IPv6 enabled, and no non-localhost servers, Google defaults (both IPv4+IPv6) should be added
<ide> ns0 = "\nnameserver 8.8.8.8\nnameserver 8.8.4.4\nnameserver 2001:4860:4860::8888\nnameserver 2001:4860:4860::8844"
<ide> ns1 = "nameserver 127.0.0.1\nnameserver ::1\nnameserver 127.0.2.1"
<ide> if result, _ := FilterResolvDNS([]byte(ns1), true); result != nil {
<del> if ns0 != string(result) {
<del> t.Fatalf("Failed no Localhost+IPv6 enabled: expected \n<%s> got \n<%s>", ns0, string(result))
<add> if ns0 != string(result.Content) {
<add> t.Fatalf("Failed no Localhost+IPv6 enabled: expected \n<%s> got \n<%s>", ns0, string(result.Content))
<ide> }
<ide> }
<ide>
<ide> // with IPv6 disabled, and no non-localhost servers, Google defaults (only IPv4) should be added
<ide> ns0 = "\nnameserver 8.8.8.8\nnameserver 8.8.4.4"
<ide> ns1 = "nameserver 127.0.0.1\nnameserver ::1\nnameserver 127.0.2.1"
<ide> if result, _ := FilterResolvDNS([]byte(ns1), false); result != nil {
<del> if ns0 != string(result) {
<del> t.Fatalf("Failed no Localhost+IPv6 enabled: expected \n<%s> got \n<%s>", ns0, string(result))
<add> if ns0 != string(result.Content) {
<add> t.Fatalf("Failed no Localhost+IPv6 enabled: expected \n<%s> got \n<%s>", ns0, string(result.Content))
<ide> }
<ide> }
<ide> }
<ide><path>libnetwork/sandbox.go
<ide> package libnetwork
<ide>
<ide> import (
<del> "bytes"
<ide> "container/heap"
<ide> "encoding/json"
<ide> "fmt"
<ide> import (
<ide> "sync"
<ide>
<ide> log "github.com/Sirupsen/logrus"
<del> "github.com/docker/docker/pkg/ioutils"
<ide> "github.com/docker/libnetwork/etchosts"
<ide> "github.com/docker/libnetwork/osl"
<ide> "github.com/docker/libnetwork/resolvconf"
<ide> func (sb *sandbox) buildHostsFile() error {
<ide> }
<ide>
<ide> func (sb *sandbox) updateHostsFile(ifaceIP string, svcRecords []etchosts.Record) error {
<add> if sb.config.originHostsPath != "" {
<add> return nil
<add> }
<add>
<ide> // Rebuild the hosts file accounting for the passed interface IP and service records
<ide> extraContent := make([]etchosts.Record, 0, len(sb.config.extraHosts)+len(svcRecords))
<ide>
<ide> func (sb *sandbox) updateParentHosts() error {
<ide> }
<ide>
<ide> func (sb *sandbox) setupDNS() error {
<add> var newRC *resolvconf.File
<add>
<ide> if sb.config.resolvConfPath == "" {
<ide> sb.config.resolvConfPath = defaultPrefix + "/" + sb.id + "/resolv.conf"
<ide> }
<ide> func (sb *sandbox) setupDNS() error {
<ide> return nil
<ide> }
<ide>
<del> resolvConf, err := resolvconf.Get()
<add> currRC, err := resolvconf.Get()
<ide> if err != nil {
<ide> return err
<ide> }
<del> dnsList := resolvconf.GetNameservers(resolvConf)
<del> dnsSearchList := resolvconf.GetSearchDomains(resolvConf)
<del> dnsOptionsList := resolvconf.GetOptions(resolvConf)
<ide>
<del> if len(sb.config.dnsList) > 0 || len(sb.config.dnsSearchList) > 0 || len(dnsOptionsList) > 0 {
<add> if len(sb.config.dnsList) > 0 || len(sb.config.dnsSearchList) > 0 || len(sb.config.dnsOptionsList) > 0 {
<add> var (
<add> err error
<add> dnsList = resolvconf.GetNameservers(currRC.Content)
<add> dnsSearchList = resolvconf.GetSearchDomains(currRC.Content)
<add> dnsOptionsList = resolvconf.GetOptions(currRC.Content)
<add> )
<ide> if len(sb.config.dnsList) > 0 {
<ide> dnsList = sb.config.dnsList
<ide> }
<ide> func (sb *sandbox) setupDNS() error {
<ide> if len(sb.config.dnsOptionsList) > 0 {
<ide> dnsOptionsList = sb.config.dnsOptionsList
<ide> }
<add> newRC, err = resolvconf.Build(sb.config.resolvConfPath, dnsList, dnsSearchList, dnsOptionsList)
<add> if err != nil {
<add> return err
<add> }
<add> } else {
<add> // Replace any localhost/127.* (at this point we have no info about ipv6, pass it as true)
<add> if newRC, err = resolvconf.FilterResolvDNS(currRC.Content, true); err != nil {
<add> return err
<add> }
<add> // No contention on container resolv.conf file at sandbox creation
<add> if err := ioutil.WriteFile(sb.config.resolvConfPath, newRC.Content, filePerm); err != nil {
<add> return types.InternalErrorf("failed to write unhaltered resolv.conf file content when setting up dns for sandbox %s: %v", sb.ID(), err)
<add> }
<ide> }
<ide>
<del> hash, err := resolvconf.Build(sb.config.resolvConfPath, dnsList, dnsSearchList, dnsOptionsList)
<del> if err != nil {
<del> return err
<del> }
<del>
<del> // write hash
<del> if err := ioutil.WriteFile(sb.config.resolvConfHashFile, []byte(hash), filePerm); err != nil {
<del> return types.InternalErrorf("failed to write resol.conf hash file when setting up dns for sandbox %s: %v", sb.ID(), err)
<add> // Write hash
<add> if err := ioutil.WriteFile(sb.config.resolvConfHashFile, []byte(newRC.Hash), filePerm); err != nil {
<add> return types.InternalErrorf("failed to write resolv.conf hash file when setting up dns for sandbox %s: %v", sb.ID(), err)
<ide> }
<ide>
<ide> return nil
<ide> }
<ide>
<ide> func (sb *sandbox) updateDNS(ipv6Enabled bool) error {
<del> var oldHash []byte
<del> hashFile := sb.config.resolvConfHashFile
<add> var (
<add> currHash string
<add> hashFile = sb.config.resolvConfHashFile
<add> )
<add>
<add> if len(sb.config.dnsList) > 0 || len(sb.config.dnsSearchList) > 0 || len(sb.config.dnsOptionsList) > 0 {
<add> return nil
<add> }
<ide>
<del> resolvConf, err := ioutil.ReadFile(sb.config.resolvConfPath)
<add> currRC, err := resolvconf.GetSpecific(sb.config.resolvConfPath)
<ide> if err != nil {
<ide> if !os.IsNotExist(err) {
<ide> return err
<ide> }
<ide> } else {
<del> oldHash, err = ioutil.ReadFile(hashFile)
<add> h, err := ioutil.ReadFile(hashFile)
<ide> if err != nil {
<ide> if !os.IsNotExist(err) {
<ide> return err
<ide> }
<del>
<del> oldHash = []byte{}
<add> } else {
<add> currHash = string(h)
<ide> }
<ide> }
<ide>
<del> curHash, err := ioutils.HashData(bytes.NewReader(resolvConf))
<del> if err != nil {
<del> return err
<del> }
<del>
<del> if string(oldHash) != "" && curHash != string(oldHash) {
<add> if currHash != "" && currHash != currRC.Hash {
<ide> // Seems the user has changed the container resolv.conf since the last time
<ide> // we checked so return without doing anything.
<ide> log.Infof("Skipping update of resolv.conf file with ipv6Enabled: %t because file was touched by user", ipv6Enabled)
<ide> return nil
<ide> }
<ide>
<ide> // replace any localhost/127.* and remove IPv6 nameservers if IPv6 disabled.
<del> resolvConf, _ = resolvconf.FilterResolvDNS(resolvConf, ipv6Enabled)
<del>
<del> newHash, err := ioutils.HashData(bytes.NewReader(resolvConf))
<add> newRC, err := resolvconf.FilterResolvDNS(currRC.Content, ipv6Enabled)
<ide> if err != nil {
<ide> return err
<ide> }
<ide> func (sb *sandbox) updateDNS(ipv6Enabled bool) error {
<ide> }
<ide>
<ide> // write the updates to the temp files
<del> if err = ioutil.WriteFile(tmpHashFile.Name(), []byte(newHash), filePerm); err != nil {
<add> if err = ioutil.WriteFile(tmpHashFile.Name(), []byte(newRC.Hash), filePerm); err != nil {
<ide> return err
<ide> }
<del> if err = ioutil.WriteFile(tmpResolvFile.Name(), resolvConf, filePerm); err != nil {
<add> if err = ioutil.WriteFile(tmpResolvFile.Name(), newRC.Content, filePerm); err != nil {
<ide> return err
<ide> }
<ide> | 3 |
Python | Python | add files for exporter | a3ae12584f55254e13e97344a51487a1e0a1cb94 | <ide><path>research/object_detection/exporter_lib_tf2_test.py
<ide> def __init__(self, conv_weight_scalar=1.0):
<ide> filters=1, kernel_size=1, strides=(1, 1), padding='valid',
<ide> kernel_initializer=tf.keras.initializers.Constant(
<ide> value=conv_weight_scalar))
<add> #self._conv(tf.ones([1, 10, 10, 3]))
<ide>
<ide> def preprocess(self, inputs):
<ide> true_image_shapes = [] # Doesn't matter for the fake model.
<ide> return tf.identity(inputs), true_image_shapes
<ide>
<del> def predict(self, preprocessed_inputs, true_image_shapes):
<del> return {'image': self._conv(preprocessed_inputs)}
<add> def predict(self, preprocessed_inputs, true_image_shapes, **side_inputs):
<add> return_dict = {'image': self._conv(preprocessed_inputs)}
<add> print("SIDE INPUTS: ", side_inputs)
<add> if 'side_inp' in side_inputs:
<add> return_dict['image'] += side_inputs['side_inp']
<add> return return_dict
<ide>
<ide> def postprocess(self, prediction_dict, true_image_shapes):
<ide> predict_tensor_sum = tf.reduce_sum(prediction_dict['image'])
<ide> def test_export_saved_model_and_run_inference(
<ide> saved_model_path = os.path.join(output_directory, 'saved_model')
<ide> detect_fn = tf.saved_model.load(saved_model_path)
<ide> image = self.get_dummy_input(input_type)
<del> detections = detect_fn(image)
<add> detections = detect_fn.signatures['serving_default'](tf.constant(image))
<ide>
<ide> detection_fields = fields.DetectionResultFields
<ide> self.assertAllClose(detections[detection_fields.detection_boxes],
<ide> def test_export_saved_model_and_run_inference(
<ide> [[1, 2], [2, 1]])
<ide> self.assertAllClose(detections[detection_fields.num_detections], [2, 1])
<ide>
<add> def test_export_saved_model_and_run_inference_with_side_inputs(
<add> self, input_type='image_tensor'):
<add> tmp_dir = self.get_temp_dir()
<add> self._save_checkpoint_from_mock_model(tmp_dir)
<add> with mock.patch.object(
<add> model_builder, 'build', autospec=True) as mock_builder:
<add> mock_builder.return_value = FakeModel()
<add> output_directory = os.path.join(tmp_dir, 'output')
<add> pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
<add> exporter_lib_v2.export_inference_graph(
<add> input_type=input_type,
<add> pipeline_config=pipeline_config,
<add> trained_checkpoint_dir=tmp_dir,
<add> output_directory=output_directory,
<add> use_side_inputs=True,
<add> side_input_shapes="1",
<add> side_input_names="side_inp",
<add> side_input_types="tf.float32")
<add>
<add> saved_model_path = os.path.join(output_directory, 'saved_model')
<add> detect_fn = tf.saved_model.load(saved_model_path)
<add> detect_fn_sig = detect_fn.signatures['serving_default']
<add> image = tf.constant(self.get_dummy_input(input_type))
<add> side_input = np.ones((1,), dtype=np.float32)
<add> #detections_one = tf.saved_model.load(saved_model_path)(image, side_input)
<add> detections = detect_fn_sig(input_tensor=image, side_inp=tf.constant(side_input))
<add>
<add> detection_fields = fields.DetectionResultFields
<add> self.assertAllClose(detections[detection_fields.detection_boxes],
<add> [[[0.0, 0.0, 0.5, 0.5],
<add> [0.5, 0.5, 0.8, 0.8]],
<add> [[0.5, 0.5, 1.0, 1.0],
<add> [0.0, 0.0, 0.0, 0.0]]])
<add> self.assertAllClose(detections[detection_fields.detection_scores],
<add> [[400.7, 400.6], [400.9, 400.0]])
<add> self.assertAllClose(detections[detection_fields.detection_classes],
<add> [[1, 2], [2, 1]])
<add> self.assertAllClose(detections[detection_fields.num_detections], [2, 1])
<add>
<ide> def test_export_checkpoint_and_run_inference_with_image(self):
<ide> tmp_dir = self.get_temp_dir()
<ide> self._save_checkpoint_from_mock_model(tmp_dir, conv_weight_scalar=2.0)
<ide><path>research/object_detection/exporter_lib_v2.py
<ide> def _decode_tf_example(tf_example_string_tensor):
<ide> class DetectionInferenceModule(tf.Module):
<ide> """Detection Inference Module."""
<ide>
<del> def __init__(self, detection_model):
<add> def __init__(self, detection_model,
<add> use_side_inputs=False,
<add> side_input_shapes=None,
<add> side_input_types=None,
<add> side_input_names=None):
<ide> """Initializes a module for detection.
<ide>
<ide> Args:
<ide> detection_model: The detection model to use for inference.
<ide> """
<ide> self._model = detection_model
<ide>
<del> def _run_inference_on_images(self, image):
<add> def _run_inference_on_images(self, image, **kwargs):
<ide> """Cast image to float and run inference.
<ide>
<ide> Args:
<ide> def _run_inference_on_images(self, image):
<ide>
<ide> image = tf.cast(image, tf.float32)
<ide> image, shapes = self._model.preprocess(image)
<del> prediction_dict = self._model.predict(image, shapes)
<add> prediction_dict = self._model.predict(image, shapes, **kwargs)
<ide> detections = self._model.postprocess(prediction_dict, shapes)
<ide> classes_field = fields.DetectionResultFields.detection_classes
<ide> detections[classes_field] = (
<ide> def _run_inference_on_images(self, image):
<ide>
<ide> return detections
<ide>
<del>
<ide> class DetectionFromImageModule(DetectionInferenceModule):
<ide> """Detection Inference Module for image inputs."""
<ide>
<del> @tf.function(
<del> input_signature=[
<del> tf.TensorSpec(shape=[1, None, None, 3], dtype=tf.uint8)])
<del> def __call__(self, input_tensor):
<del> return self._run_inference_on_images(input_tensor)
<add> def __init__(self, detection_model,
<add> use_side_inputs=False,
<add> side_input_shapes="",
<add> side_input_types="",
<add> side_input_names=""):
<add> """Initializes a module for detection.
<add>
<add> Args:
<add> detection_model: The detection model to use for inference.
<add> """
<add> self.side_input_names = side_input_names
<add> sig = [tf.TensorSpec(shape=[1, None, None, 3], dtype=tf.uint8)]
<add> if use_side_inputs:
<add> for info in zip(side_input_shapes.split("/"),
<add> side_input_types.split(","),
<add> side_input_names.split(",")):
<add> sig.append(tf.TensorSpec(shape=eval("[" + info[0] + "]"),
<add> dtype=eval(info[1]),
<add> name=info[2]))
<add>
<add> def __call__(input_tensor, *side_inputs):
<add> kwargs = dict(zip(self.side_input_names.split(","), side_inputs))
<add> return self._run_inference_on_images(input_tensor, **kwargs)
<add>
<add> self.__call__ = tf.function(__call__, input_signature=sig)
<add>
<add> super(DetectionFromImageModule, self).__init__(detection_model,
<add> side_input_shapes,
<add> side_input_types,
<add> side_input_names)
<ide>
<ide>
<ide> class DetectionFromFloatImageModule(DetectionInferenceModule):
<ide> def __call__(self, input_tensor):
<ide> def export_inference_graph(input_type,
<ide> pipeline_config,
<ide> trained_checkpoint_dir,
<del> output_directory):
<add> output_directory,
<add> use_side_inputs=False,
<add> side_input_shapes="",
<add> side_input_types="",
<add> side_input_names=""):
<ide> """Exports inference graph for the model specified in the pipeline config.
<ide>
<ide> This function creates `output_directory` if it does not already exist,
<ide> def export_inference_graph(input_type,
<ide>
<ide> if input_type not in DETECTION_MODULE_MAP:
<ide> raise ValueError('Unrecognized `input_type`')
<del> detection_module = DETECTION_MODULE_MAP[input_type](detection_model)
<add> if use_side_inputs and input_type != 'image_tensor':
<add> raise ValueError('Side inputs supported for image_tensor input type only.')
<add> detection_module = DETECTION_MODULE_MAP[input_type](detection_model,
<add> use_side_inputs,
<add> side_input_shapes,
<add> side_input_types,
<add> side_input_names)
<ide> # Getting the concrete function traces the graph and forces variables to
<ide> # be constructed --- only after this can we save the checkpoint and
<ide> # saved model.
<ide><path>research/object_detection/exporter_main_v2.py
<ide> flags.DEFINE_string('config_override', '',
<ide> 'pipeline_pb2.TrainEvalPipelineConfig '
<ide> 'text proto to override pipeline_config_path.')
<add>flags.DEFINE_boolean('use_side_inputs', False,
<add> 'If True, uses side inputs as well as image inputs.')
<add>flags.DEFINE_string('side_input_shapes', "",
<add> 'If use_side_inputs is True, this explicitly sets '
<add> 'the shape of the side input tensors to a fixed size. The '
<add> 'dimensions are to be provided as a comma-separated list '
<add> 'of integers. A value of -1 can be used for unknown '
<add> 'dimensions. A `/` denotes a break, starting the shape of '
<add> 'the next side input tensor. This flag is required if '
<add> 'using side inputs.')
<add>flags.DEFINE_string('side_input_types', "",
<add> 'If use_side_inputs is True, this explicitly sets '
<add> 'the type of the side input tensors. The '
<add> 'dimensions are to be provided as a comma-separated list '
<add> 'of types, each of `string`, `integer`, or `float`. '
<add> 'This flag is required if using side inputs.')
<add>flags.DEFINE_string('side_input_names', "",
<add> 'If use_side_inputs is True, this explicitly sets '
<add> 'the names of the side input tensors required by the model '
<add> 'assuming the names will be a comma-separated list of '
<add> 'strings. This flag is required if using side inputs.')
<ide>
<ide> flags.mark_flag_as_required('pipeline_config_path')
<ide> flags.mark_flag_as_required('trained_checkpoint_dir')
<ide> def main(_):
<ide> text_format.Merge(FLAGS.config_override, pipeline_config)
<ide> exporter_lib_v2.export_inference_graph(
<ide> FLAGS.input_type, pipeline_config, FLAGS.trained_checkpoint_dir,
<del> FLAGS.output_directory)
<add> FLAGS.output_directory, FLAGS.use_side_inputs, FLAGS.side_input_shapes,
<add> FLAGS.side_input_types, FLAGS.side_input_names)
<ide>
<ide>
<ide> if __name__ == '__main__': | 3 |
Javascript | Javascript | use buildid instead of entry path for reporting | b74b2d5193d29ac364852a02df752eb8dd5ec177 | <ide><path>packager/src/Server/index.js
<ide> class Server {
<ide> _reporter: Reporter;
<ide> _symbolicateInWorker: Symbolicate;
<ide> _platforms: Set<string>;
<add> _nextBundleBuildID: number;
<ide>
<ide> constructor(options: Options) {
<ide> this._opts = {
<ide> class Server {
<ide> }, 50);
<ide>
<ide> this._symbolicateInWorker = symbolicate.createWorker();
<add> this._nextBundleBuildID = 1;
<ide> }
<ide>
<ide> end(): mixed {
<ide> class Server {
<ide> * and for when we build for scratch.
<ide> */
<ide> _reportBundlePromise(
<add> buildID: string,
<ide> options: {entryFile: string},
<ide> bundlePromise: Promise<Bundle>,
<ide> ): Promise<Bundle> {
<ide> this._reporter.update({
<add> buildID,
<ide> entryFilePath: options.entryFile,
<ide> type: 'bundle_build_started',
<ide> });
<ide> return bundlePromise.then(bundle => {
<ide> this._reporter.update({
<del> entryFilePath: options.entryFile,
<add> buildID,
<ide> type: 'bundle_build_done',
<ide> });
<ide> return bundle;
<ide> }, error => {
<ide> this._reporter.update({
<del> entryFilePath: options.entryFile,
<add> buildID,
<ide> type: 'bundle_build_failed',
<ide> });
<ide> return Promise.reject(error);
<ide> });
<ide> }
<ide>
<del> useCachedOrUpdateOrCreateBundle(options: BundleOptions): Promise<Bundle> {
<add> useCachedOrUpdateOrCreateBundle(
<add> buildID: string,
<add> options: BundleOptions,
<add> ): Promise<Bundle> {
<ide> const optionsJson = this.optionsHash(options);
<ide> const bundleFromScratch = () => {
<ide> const building = this.buildBundle(options);
<ide> class Server {
<ide> debug('Failed to update existing bundle, rebuilding...', e.stack || e.message);
<ide> return bundleFromScratch();
<ide> });
<del> return this._reportBundlePromise(options, bundlePromise);
<add> return this._reportBundlePromise(buildID, options, bundlePromise);
<ide> } else {
<ide> debug('Using cached bundle');
<ide> return bundle;
<ide> }
<ide> });
<ide> }
<ide>
<del> return this._reportBundlePromise(options, bundleFromScratch());
<add> return this._reportBundlePromise(buildID, options, bundleFromScratch());
<ide> }
<ide>
<ide> processRequest(
<ide> class Server {
<ide> entry_point: options.entryFile,
<ide> }));
<ide>
<add> const buildID = this.getNewBuildID();
<ide> let reportProgress = emptyFunction;
<ide> if (!this._opts.silent) {
<ide> reportProgress = (transformedFileCount, totalFileCount) => {
<ide> this._reporter.update({
<add> buildID,
<ide> type: 'bundle_transform_progressed',
<del> entryFilePath: options.entryFile,
<ide> transformedFileCount,
<ide> totalFileCount,
<ide> });
<ide> class Server {
<ide> };
<ide>
<ide> debug('Getting bundle for request');
<del> const building = this.useCachedOrUpdateOrCreateBundle(options);
<add> const building = this.useCachedOrUpdateOrCreateBundle(buildID, options);
<ide> building.then(
<ide> p => {
<ide> if (requestType === 'bundle') {
<ide> class Server {
<ide>
<ide> _sourceMapForURL(reqUrl: string): Promise<SourceMap> {
<ide> const options = this._getOptionsFromUrl(reqUrl);
<del> const building = this.useCachedOrUpdateOrCreateBundle(options);
<add> // We're not properly reporting progress here. Reporting should be done
<add> // from within that function.
<add> const building = this.useCachedOrUpdateOrCreateBundle(
<add> this.getNewBuildID(),
<add> options,
<add> );
<ide> return building.then(p => p.getSourceMap({
<ide> minify: options.minify,
<ide> dev: options.dev,
<ide> class Server {
<ide> return query[opt] === 'true' || query[opt] === '1';
<ide> }
<ide>
<add> getNewBuildID(): string {
<add> return (this._nextBundleBuildID++).toString(36);
<add> }
<add>
<ide> static DEFAULT_BUNDLE_OPTIONS;
<ide>
<ide> }
<ide><path>packager/src/lib/TerminalReporter.js
<ide> const GLOBAL_CACHE_DISABLED_MESSAGE_FORMAT =
<ide> 'The global cache is now disabled because %s';
<ide>
<ide> type BundleProgress = {
<add> entryFilePath: string,
<ide> transformedFileCount: number,
<ide> totalFileCount: number,
<ide> ratio: number,
<ide> function getProgressBar(ratio: number, length: number) {
<ide> }
<ide>
<ide> export type TerminalReportableEvent = ReportableEvent | {
<add> buildID: string,
<ide> type: 'bundle_transform_progressed_throttled',
<del> entryFilePath: string,
<ide> transformedFileCount: number,
<ide> totalFileCount: number,
<ide> };
<ide> class TerminalReporter {
<ide>
<ide> _dependencyGraphHasLoaded: boolean;
<ide> _scheduleUpdateBundleProgress: (data: {
<del> entryFilePath: string,
<add> buildID: string,
<ide> transformedFileCount: number,
<ide> totalFileCount: number,
<ide> }) => void;
<ide> class TerminalReporter {
<ide> * Bunding `foo.js` |#### | 34.2% (324/945)
<ide> */
<ide> _getBundleStatusMessage(
<del> entryFilePath: string,
<del> {totalFileCount, transformedFileCount, ratio}: BundleProgress,
<add> {entryFilePath, totalFileCount, transformedFileCount, ratio}: BundleProgress,
<ide> phase: BuildPhase,
<ide> ): string {
<ide> const localPath = path.relative('.', entryFilePath);
<ide> class TerminalReporter {
<ide> }
<ide> }
<ide>
<del> _logBundleBuildDone(entryFilePath: string) {
<del> const progress = this._activeBundles.get(entryFilePath);
<add> _logBundleBuildDone(buildID: string) {
<add> const progress = this._activeBundles.get(buildID);
<ide> if (progress != null) {
<del> const msg = this._getBundleStatusMessage(entryFilePath, {
<add> const msg = this._getBundleStatusMessage({
<ide> ...progress,
<ide> ratio: 1,
<ide> transformedFileCount: progress.totalFileCount,
<ide> class TerminalReporter {
<ide> }
<ide> }
<ide>
<del> _logBundleBuildFailed(entryFilePath: string) {
<del> const progress = this._activeBundles.get(entryFilePath);
<add> _logBundleBuildFailed(buildID: string) {
<add> const progress = this._activeBundles.get(buildID);
<ide> if (progress != null) {
<del> const msg = this._getBundleStatusMessage(entryFilePath, progress, 'failed');
<add> const msg = this._getBundleStatusMessage(progress, 'failed');
<ide> terminal.log(msg);
<ide> }
<ide> }
<ide> class TerminalReporter {
<ide> this._logPackagerInitializingFailed(event.port, event.error);
<ide> break;
<ide> case 'bundle_build_done':
<del> this._logBundleBuildDone(event.entryFilePath);
<add> this._logBundleBuildDone(event.buildID);
<ide> break;
<ide> case 'bundle_build_failed':
<del> this._logBundleBuildFailed(event.entryFilePath);
<add> this._logBundleBuildFailed(event.buildID);
<ide> break;
<ide> case 'bundling_error':
<ide> this._logBundlingError(event.error);
<ide> class TerminalReporter {
<ide> * also prevent the ratio from going backwards.
<ide> */
<ide> _updateBundleProgress(
<del> {entryFilePath, transformedFileCount, totalFileCount}: {
<del> entryFilePath: string,
<add> {buildID, transformedFileCount, totalFileCount}: {
<add> buildID: string,
<ide> transformedFileCount: number,
<ide> totalFileCount: number,
<ide> },
<ide> ) {
<del> const currentProgress = this._activeBundles.get(entryFilePath);
<add> const currentProgress = this._activeBundles.get(buildID);
<ide> if (currentProgress == null) {
<ide> return;
<ide> }
<ide> class TerminalReporter {
<ide> switch (event.type) {
<ide> case 'bundle_build_done':
<ide> case 'bundle_build_failed':
<del> this._activeBundles.delete(event.entryFilePath);
<add> this._activeBundles.delete(event.buildID);
<ide> break;
<ide> case 'bundle_build_started':
<del> this._activeBundles.set(event.entryFilePath, {
<add> this._activeBundles.set(event.buildID, {
<add> entryFilePath: event.entryFilePath,
<ide> transformedFileCount: 0,
<ide> totalFileCount: 1,
<ide> ratio: 0,
<ide> class TerminalReporter {
<ide> return [
<ide> this._getDepGraphStatusMessage(),
<ide> ].concat(Array.from(this._activeBundles.entries()).map(
<del> ([entryFilePath, progress]) =>
<del> this._getBundleStatusMessage(entryFilePath, progress, 'in_progress'),
<add> ([_, progress]) =>
<add> this._getBundleStatusMessage(progress, 'in_progress'),
<ide> )).filter(str => str != null).join('\n');
<ide> }
<ide>
<ide><path>packager/src/lib/reporting.js
<ide> export type ReportableEvent = {
<ide> port: number,
<ide> error: Error,
<ide> } | {
<del> entryFilePath: string,
<add> buildID: string,
<ide> type: 'bundle_build_done',
<ide> } | {
<del> entryFilePath: string,
<add> buildID: string,
<ide> type: 'bundle_build_failed',
<ide> } | {
<add> buildID: string,
<ide> entryFilePath: string,
<ide> type: 'bundle_build_started',
<ide> } | {
<ide> export type ReportableEvent = {
<ide> } | {
<ide> type: 'dep_graph_loaded',
<ide> } | {
<add> buildID: string,
<ide> type: 'bundle_transform_progressed',
<del> entryFilePath: string,
<ide> transformedFileCount: number,
<ide> totalFileCount: number,
<ide> } | { | 3 |
Ruby | Ruby | add tmux warning for launchctl caveats | 5fd9c568031d42b93b1f7a3bfc2a91d4e266aac2 | <ide><path>Library/Homebrew/caveats.rb
<ide> def plist_caveats
<ide> s << " launchctl load #{plist_link}"
<ide> end
<ide> end
<add> s << '' << "WARNING: launchctl will fail when run under tmux."
<ide> end
<ide> s.join("\n") unless s.empty?
<ide> end | 1 |
PHP | PHP | remove some comment bloat | 16a21422fbc75316db4fcb674c92cea6ce5456e9 | <ide><path>laravel/view.php
<ide> protected function compile()
<ide> {
<ide> // For simplicity, compiled views are stored in a single directory by
<ide> // the MD5 hash of their name. This allows us to avoid recreating the
<del> // entire view directory structure within the compiled views directory.
<add> // entire view directory structure within the compiled directory.
<ide> $compiled = STORAGE_PATH.'views/'.md5($this->view);
<ide>
<ide> // The view will only be re-compiled if the view has been modified | 1 |
Go | Go | add test case for graph byparent() | 02b8d14bdd1837aad5b8fb667d1f4e7eace59687 | <ide><path>graph_test.go
<ide> func TestDelete(t *testing.T) {
<ide> assertNImages(graph, t, 1)
<ide> }
<ide>
<add>func TestByParent(t *testing.T) {
<add> archive1, _ := fakeTar()
<add> archive2, _ := fakeTar()
<add> archive3, _ := fakeTar()
<add>
<add> graph := tempGraph(t)
<add> defer os.RemoveAll(graph.Root)
<add> parentImage := &Image{
<add> ID: GenerateID(),
<add> Comment: "parent",
<add> Created: time.Now(),
<add> Parent: "",
<add> }
<add> childImage1 := &Image{
<add> ID: GenerateID(),
<add> Comment: "child1",
<add> Created: time.Now(),
<add> Parent: parentImage.ID,
<add> }
<add> childImage2 := &Image{
<add> ID: GenerateID(),
<add> Comment: "child2",
<add> Created: time.Now(),
<add> Parent: parentImage.ID,
<add> }
<add> _ = graph.Register(nil, archive1, parentImage)
<add> _ = graph.Register(nil, archive2, childImage1)
<add> _ = graph.Register(nil, archive3, childImage2)
<add>
<add> byParent, err := graph.ByParent()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> numChildren := len(byParent[parentImage.ID])
<add> if numChildren != 2 {
<add> t.Fatalf("Expected 2 children, found %d", numChildren)
<add> }
<add>}
<add>
<ide> func assertNImages(graph *Graph, t *testing.T, n int) {
<ide> if images, err := graph.All(); err != nil {
<ide> t.Fatal(err) | 1 |
Text | Text | add v3.28.11 to changelog | 38363419e2e673afa1ebec3e541fb9d8f399239f | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>## v3.28.11 (November 30, 2022)
<add>
<add>- [#20286](https://github.com/emberjs/ember.js/pull/20286) [BUGFIX LTS] Allow class-based helpers in strict-mode
<add>
<ide> ### v4.10.0-beta.1 (November 28, 2022)
<ide>
<ide> - [#20253](https://github.com/emberjs/ember.js/pull/20253) [FEATURE] Add the `Resolver` type to preview types | 1 |
Ruby | Ruby | simplify singleton_class? method | cdc4274931c2d6bafdf2b97f7e4ecedf89a8202e | <ide><path>activesupport/lib/active_support/core_ext/class/attribute.rb
<ide> def #{name}?
<ide>
<ide> private
<ide> def singleton_class?
<del> # in case somebody is crazy enough to overwrite allocate
<del> allocate = Class.instance_method(:allocate)
<del> # object.class always points to a real (non-singleton) class
<del> allocate.bind(self).call.class != self
<del> rescue TypeError
<del> # MRI/YARV/JRuby all disallow creating new instances of a singleton class
<del> true
<add> !name || '' == name
<ide> end
<ide> end | 1 |
Javascript | Javascript | add text node types | cafa7b284a7f1830a443525ec08ae26e14ba7cc6 | <ide><path>src/renderers/dom/fiber/ReactDOMFiber.js
<ide> type DOMContainerElement = Element & { _reactRootContainer: ?Object };
<ide> type Container = Element;
<ide> type Props = { };
<ide> type Instance = Element;
<add>type TextInstance = Text;
<ide>
<del>function recursivelyAppendChildren(parent : Element, child : HostChildren<Instance>) {
<add>function recursivelyAppendChildren(parent : Element, child : HostChildren<Instance | TextInstance>) {
<ide> if (!child) {
<ide> return;
<ide> }
<del> /* $FlowFixMe: Element should have this property. */
<del> if (child.nodeType === 1) {
<add> /* $FlowFixMe: Element and Text should have this property. */
<add> if (child.nodeType === 1 || child.nodeType === 3) {
<ide> /* $FlowFixMe: Refinement issue. I don't know how to express different. */
<ide> parent.appendChild(child);
<ide> } else {
<ide> function recursivelyAppendChildren(parent : Element, child : HostChildren<Instan
<ide>
<ide> var DOMRenderer = ReactFiberReconciler({
<ide>
<del> updateContainer(container : Container, children : HostChildren<Instance>) : void {
<add> updateContainer(container : Container, children : HostChildren<Instance | TextInstance>) : void {
<ide> container.innerHTML = '';
<ide> recursivelyAppendChildren(container, children);
<ide> },
<ide>
<del> createInstance(type : string, props : Props, children : HostChildren<Instance>) : Instance {
<add> createInstance(type : string, props : Props, children : HostChildren<Instance | TextInstance>) : Instance {
<ide> const domElement = document.createElement(type);
<ide> recursivelyAppendChildren(domElement, children);
<del> if (typeof props.children === 'string') {
<add> if (typeof props.children === 'string' ||
<add> typeof props.children === 'number') {
<ide> domElement.textContent = props.children;
<ide> }
<ide> return domElement;
<ide> var DOMRenderer = ReactFiberReconciler({
<ide> domElement : Instance,
<ide> oldProps : Props,
<ide> newProps : Props,
<del> children : HostChildren<Instance>
<add> children : HostChildren<Instance | TextInstance>
<ide> ) : boolean {
<ide> return true;
<ide> },
<ide>
<del> commitUpdate(domElement : Instance, oldProps : Props, newProps : Props, children : HostChildren<Instance>) : void {
<add> commitUpdate(domElement : Instance, oldProps : Props, newProps : Props, children : HostChildren<Instance | TextInstance>) : void {
<ide> domElement.innerHTML = '';
<ide> recursivelyAppendChildren(domElement, children);
<del> if (typeof newProps.children === 'string') {
<add> if (typeof newProps.children === 'string' ||
<add> typeof newProps.children === 'number') {
<ide> domElement.textContent = newProps.children;
<ide> }
<ide> },
<ide> var DOMRenderer = ReactFiberReconciler({
<ide> // Noop
<ide> },
<ide>
<add> createTextInstance(text : string) : TextInstance {
<add> return document.createTextNode(text);
<add> },
<add>
<add> commitTextUpdate(textInstance : TextInstance, oldText : string, newText : string) : void {
<add> textInstance.nodeValue = newText;
<add> },
<add>
<ide> scheduleAnimationCallback: window.requestAnimationFrame,
<ide>
<ide> scheduleDeferredCallback: window.requestIdleCallback,
<ide><path>src/renderers/noop/ReactNoop.js
<ide> var scheduledDeferredCallback = null;
<ide>
<ide> const TERMINAL_TAG = 99;
<ide>
<del>type Container = { rootID: number, children: Array<Instance> };
<add>type Container = { rootID: number, children: Array<Instance | TextInstance> };
<ide> type Props = { prop: any };
<del>type Instance = { tag: 99, type: string, id: number, children: Array<Instance>, prop: any };
<add>type Instance = { tag: 99, type: string, id: number, children: Array<Instance | TextInstance>, prop: any };
<add>type TextInstance = string;
<ide>
<ide> var instanceCounter = 0;
<ide>
<del>function recursivelyAppendChildren(flatArray : Array<Instance>, child : HostChildren<Instance>) {
<add>function recursivelyAppendChildren(flatArray : Array<Instance | TextInstance>, child : HostChildren<Instance | TextInstance>) {
<ide> if (!child) {
<ide> return;
<ide> }
<del> if (child.tag === TERMINAL_TAG) {
<add> if (typeof child === 'string' || child.tag === TERMINAL_TAG) {
<ide> flatArray.push(child);
<ide> } else {
<ide> let node = child;
<ide> function recursivelyAppendChildren(flatArray : Array<Instance>, child : HostChil
<ide> }
<ide> }
<ide>
<del>function flattenChildren(children : HostChildren<Instance>) {
<add>function flattenChildren(children : HostChildren<Instance | TextInstance>) {
<ide> const flatArray = [];
<ide> recursivelyAppendChildren(flatArray, children);
<ide> return flatArray;
<ide> }
<ide>
<ide> var NoopRenderer = ReactFiberReconciler({
<ide>
<del> updateContainer(containerInfo : Container, children : HostChildren<Instance>) : void {
<add> updateContainer(containerInfo : Container, children : HostChildren<Instance | TextInstance>) : void {
<ide> containerInfo.children = flattenChildren(children);
<ide> },
<ide>
<del> createInstance(type : string, props : Props, children : HostChildren<Instance>) : Instance {
<add> createInstance(type : string, props : Props, children : HostChildren<Instance | TextInstance>) : Instance {
<ide> const inst = {
<ide> tag: TERMINAL_TAG,
<ide> id: instanceCounter++,
<ide> var NoopRenderer = ReactFiberReconciler({
<ide> return inst;
<ide> },
<ide>
<del> prepareUpdate(instance : Instance, oldProps : Props, newProps : Props, children : HostChildren<Instance>) : boolean {
<add> prepareUpdate(instance : Instance, oldProps : Props, newProps : Props, children : HostChildren<Instance | TextInstance>) : boolean {
<ide> return true;
<ide> },
<ide>
<del> commitUpdate(instance : Instance, oldProps : Props, newProps : Props, children : HostChildren<Instance>) : void {
<add> commitUpdate(instance : Instance, oldProps : Props, newProps : Props, children : HostChildren<Instance | TextInstance>) : void {
<ide> instance.children = flattenChildren(children);
<ide> instance.prop = newProps.prop;
<ide> },
<ide>
<ide> deleteInstance(instance : Instance) : void {
<ide> },
<ide>
<add> createTextInstance(text : string) : TextInstance {
<add> return text;
<add> },
<add>
<add> commitTextUpdate(textInstance : TextInstance, oldText : string, newText : string) : void {
<add> // Not yet supported.
<add> },
<add>
<ide> scheduleAnimationCallback(callback) {
<ide> scheduledAnimationCallback = callback;
<ide> },
<ide> var ReactNoop = {
<ide> bufferedLog.push(...args, '\n');
<ide> }
<ide>
<del> function logHostInstances(children: Array<Instance>, depth) {
<add> function logHostInstances(children: Array<Instance | TextInstance>, depth) {
<ide> for (var i = 0; i < children.length; i++) {
<ide> var child = children[i];
<del> log(' '.repeat(depth) + '- ' + child.type + '#' + child.id);
<del> logHostInstances(child.children, depth + 1);
<add> if (typeof child === 'string') {
<add> log(' '.repeat(depth) + '- ' + child);
<add> } else {
<add> log(' '.repeat(depth) + '- ' + child.type + '#' + child.id);
<add> logHostInstances(child.children, depth + 1);
<add> }
<ide> }
<ide> }
<ide> function logContainer(container : Container, depth) {
<ide><path>src/renderers/shared/fiber/ReactChildFiber.js
<ide> const {
<ide> cloneFiber,
<ide> createFiberFromElement,
<ide> createFiberFromFragment,
<add> createFiberFromText,
<ide> createFiberFromCoroutine,
<ide> createFiberFromYield,
<ide> } = ReactFiber;
<ide> function ChildReconciler(shouldClone) {
<ide> newChildren : any,
<ide> priority : PriorityLevel
<ide> ) : Fiber {
<add> if (typeof newChildren === 'string') {
<add> const textNode = createFiberFromText(newChildren, priority);
<add> previousSibling.sibling = textNode;
<add> textNode.return = returnFiber;
<add> return textNode;
<add> }
<add>
<ide> if (typeof newChildren !== 'object' || newChildren === null) {
<ide> return previousSibling;
<ide> }
<ide> function ChildReconciler(shouldClone) {
<ide> }
<ide>
<ide> function createFirstChild(returnFiber, existingChild, newChildren : any, priority) {
<add> if (typeof newChildren === 'string') {
<add> const textNode = createFiberFromText(newChildren, priority);
<add> textNode.return = returnFiber;
<add> return textNode;
<add> }
<add>
<ide> if (typeof newChildren !== 'object' || newChildren === null) {
<ide> return null;
<ide> }
<ide><path>src/renderers/shared/fiber/ReactFiber.js
<ide> var {
<ide> ClassComponent,
<ide> HostContainer,
<ide> HostComponent,
<add> HostText,
<ide> CoroutineComponent,
<ide> YieldComponent,
<ide> Fragment,
<ide> exports.createFiberFromFragment = function(elements : ReactFragment, priorityLev
<ide> return fiber;
<ide> };
<ide>
<add>exports.createFiberFromText = function(content : string, priorityLevel : PriorityLevel) {
<add> const fiber = createFiber(HostText, null);
<add> fiber.pendingProps = content;
<add> fiber.pendingWorkPriority = priorityLevel;
<add> return fiber;
<add>};
<add>
<ide> function createFiberFromElementType(type : mixed, key : null | string) {
<ide> let fiber;
<ide> if (typeof type === 'function') {
<ide><path>src/renderers/shared/fiber/ReactFiberBeginWork.js
<ide> var {
<ide> ClassComponent,
<ide> HostContainer,
<ide> HostComponent,
<add> HostText,
<ide> CoroutineComponent,
<ide> CoroutineHandlerPhase,
<ide> YieldComponent,
<ide> var {
<ide> } = require('ReactFiberUpdateQueue');
<ide> var ReactInstanceMap = require('ReactInstanceMap');
<ide>
<del>module.exports = function<T, P, I, C>(config : HostConfig<T, P, I, C>, getScheduler : () => Scheduler) {
<add>module.exports = function<T, P, I, TI, C>(config : HostConfig<T, P, I, TI, C>, getScheduler : () => Scheduler) {
<ide>
<ide> function markChildAsProgressed(current, workInProgress, priorityLevel) {
<ide> // We now have clones. Let's store them as the currently progressed work.
<ide> module.exports = function<T, P, I, C>(config : HostConfig<T, P, I, C>, getSchedu
<ide> }
<ide>
<ide> function updateHostComponent(current, workInProgress) {
<del> const nextChildren = workInProgress.pendingProps.children;
<add> let nextChildren = workInProgress.pendingProps.children;
<add> if (typeof nextChildren === 'string' || typeof nextChildren === 'number') {
<add> // We special case a direct text child of a host node. This is a common
<add> // case. We won't handle it as a reified child. We will instead handle
<add> // this in the host environment that also have access to this prop. That
<add> // avoids allocating another HostText fiber and traversing it.
<add> nextChildren = null;
<add> }
<ide> if (workInProgress.pendingProps.hidden &&
<ide> workInProgress.pendingWorkPriority !== OffscreenPriority) {
<ide> // If this host component is hidden, we can bail out on the children.
<ide> module.exports = function<T, P, I, C>(config : HostConfig<T, P, I, C>, getSchedu
<ide> config.beginUpdate(workInProgress.stateNode);
<ide> }
<ide> return updateHostComponent(current, workInProgress);
<add> case HostText:
<add> // Nothing to do here. This is terminal. We'll do the completion step
<add> // immediately after.
<add> return null;
<ide> case CoroutineHandlerPhase:
<ide> // This is a restart. Reset the tag to the initial phase.
<ide> workInProgress.tag = CoroutineComponent;
<ide><path>src/renderers/shared/fiber/ReactFiberCommitWork.js
<ide> var {
<ide> ClassComponent,
<ide> HostContainer,
<ide> HostComponent,
<add> HostText,
<ide> } = ReactTypeOfWork;
<ide> var { callCallbacks } = require('ReactFiberUpdateQueue');
<ide>
<del>module.exports = function<T, P, I, C>(config : HostConfig<T, P, I, C>) {
<add>module.exports = function<T, P, I, TI, C>(config : HostConfig<T, P, I, TI, C>) {
<ide>
<ide> const updateContainer = config.updateContainer;
<ide> const commitUpdate = config.commitUpdate;
<add> const commitTextUpdate = config.commitTextUpdate;
<ide>
<ide> function commitWork(current : ?Fiber, finishedWork : Fiber) : void {
<ide> switch (finishedWork.tag) {
<ide> module.exports = function<T, P, I, C>(config : HostConfig<T, P, I, C>) {
<ide> commitUpdate(instance, oldProps, newProps, children);
<ide> return;
<ide> }
<add> case HostText: {
<add> if (finishedWork.stateNode == null || !current) {
<add> throw new Error('This should only be done during updates.');
<add> }
<add> // TODO: This never gets called yet because I don't have update support
<add> // for text nodes. This only gets updated through a host component or
<add> // container updating with this as one of its child nodes.
<add> const textInstance : TI = finishedWork.stateNode;
<add> const oldText : string = finishedWork.memoizedProps;
<add> const newText : string = current.memoizedProps;
<add> commitTextUpdate(textInstance, oldText, newText);
<add> }
<ide> default:
<ide> throw new Error('This unit of work tag should not have side-effects.');
<ide> }
<ide><path>src/renderers/shared/fiber/ReactFiberCompleteWork.js
<ide> var {
<ide> ClassComponent,
<ide> HostContainer,
<ide> HostComponent,
<add> HostText,
<ide> CoroutineComponent,
<ide> CoroutineHandlerPhase,
<ide> YieldComponent,
<ide> Fragment,
<ide> } = ReactTypeOfWork;
<ide>
<del>module.exports = function<T, P, I, C>(config : HostConfig<T, P, I, C>) {
<add>module.exports = function<T, P, I, TI, C>(config : HostConfig<T, P, I, TI, C>) {
<ide>
<ide> const createInstance = config.createInstance;
<add> const createTextInstance = config.createTextInstance;
<ide> const prepareUpdate = config.prepareUpdate;
<ide>
<ide> function markForPreEffect(workInProgress : Fiber) {
<ide> module.exports = function<T, P, I, C>(config : HostConfig<T, P, I, C>) {
<ide> }
<ide> workInProgress.memoizedProps = newProps;
<ide> return null;
<add> case HostText:
<add> let newText = workInProgress.pendingProps;
<add> if (current && workInProgress.stateNode != null) {
<add> // If we have an alternate, that means this is an update and we need to
<add> // schedule a side-effect to do the updates.
<add> markForPreEffect(workInProgress);
<add> } else {
<add> if (typeof newText !== 'string') {
<add> if (workInProgress.stateNode === null) {
<add> throw new Error('We must have new props for new mounts.');
<add> } else {
<add> // This can happen when we abort work.
<add> return null;
<add> }
<add> }
<add> const textInstance = createTextInstance(newText);
<add> // TODO: This seems like unnecessary duplication.
<add> workInProgress.stateNode = textInstance;
<add> workInProgress.output = textInstance;
<add> }
<add> workInProgress.memoizedProps = newText;
<add> return null;
<ide> case CoroutineComponent:
<ide> return moveCoroutineToHandlerPhase(current, workInProgress);
<ide> case CoroutineHandlerPhase:
<ide><path>src/renderers/shared/fiber/ReactFiberReconciler.js
<ide> type HostChildNode<I> = { tag: TypeOfWork, output: HostChildren<I>, sibling: any
<ide>
<ide> export type HostChildren<I> = null | void | I | HostChildNode<I>;
<ide>
<del>export type HostConfig<T, P, I, C> = {
<add>export type HostConfig<T, P, I, TI, C> = {
<ide>
<ide> // TODO: We don't currently have a quick way to detect that children didn't
<ide> // reorder so we host will always need to check the set. We should make a flag
<ide> // or something so that it can bailout easily.
<ide>
<del> updateContainer(containerInfo : C, children : HostChildren<I>) : void;
<add> updateContainer(containerInfo : C, children : HostChildren<I | TI>) : void;
<ide>
<del> createInstance(type : T, props : P, children : HostChildren<I>) : I,
<del> prepareUpdate(instance : I, oldProps : P, newProps : P, children : HostChildren<I>) : boolean,
<del> commitUpdate(instance : I, oldProps : P, newProps : P, children : HostChildren<I>) : void,
<add> createInstance(type : T, props : P, children : HostChildren<I | TI>) : I,
<add> prepareUpdate(instance : I, oldProps : P, newProps : P, children : HostChildren<I | TI>) : boolean,
<add> commitUpdate(instance : I, oldProps : P, newProps : P, children : HostChildren<I | TI>) : void,
<ide> deleteInstance(instance : I) : void,
<ide>
<add> createTextInstance(text : string) : TI,
<add> commitTextUpdate(textInstance : TI, oldText : string, newText : string) : void,
<add>
<ide> scheduleAnimationCallback(callback : () => void) : void,
<ide> scheduleDeferredCallback(callback : (deadline : Deadline) => void) : void
<ide>
<ide> export type Reconciler<C> = {
<ide> getPublicRootInstance(container : OpaqueNode) : (C | null),
<ide> };
<ide>
<del>module.exports = function<T, P, I, C>(config : HostConfig<T, P, I, C>) : Reconciler<C> {
<add>module.exports = function<T, P, I, TI, C>(config : HostConfig<T, P, I, TI, C>) : Reconciler<C> {
<ide>
<ide> var { scheduleWork, performWithPriority } = ReactFiberScheduler(config);
<ide>
<ide><path>src/renderers/shared/fiber/ReactFiberScheduler.js
<ide> export type Scheduler = {
<ide> scheduleDeferredWork: (root : FiberRoot, priority : PriorityLevel) => void
<ide> };
<ide>
<del>module.exports = function<T, P, I, C>(config : HostConfig<T, P, I, C>) {
<add>module.exports = function<T, P, I, TI, C>(config : HostConfig<T, P, I, TI, C>) {
<ide> // Use a closure to circumvent the circular dependency between the scheduler
<ide> // and ReactFiberBeginWork. Don't know if there's a better way to do this.
<ide> let scheduler;
<ide><path>src/renderers/shared/fiber/ReactTypeOfWork.js
<ide>
<ide> 'use strict';
<ide>
<del>export type TypeOfWork = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;
<add>export type TypeOfWork = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
<ide>
<ide> module.exports = {
<ide> IndeterminateComponent: 0, // Before we know whether it is functional or class
<ide> FunctionalComponent: 1,
<ide> ClassComponent: 2,
<ide> HostContainer: 3, // Root of a host tree. Could be nested inside another node.
<ide> HostComponent: 4,
<del> CoroutineComponent: 5,
<del> CoroutineHandlerPhase: 6,
<del> YieldComponent: 7,
<del> Fragment: 8,
<add> HostText: 5,
<add> CoroutineComponent: 6,
<add> CoroutineHandlerPhase: 7,
<add> YieldComponent: 8,
<add> Fragment: 9,
<ide> };
<ide><path>src/renderers/shared/fiber/__tests__/ReactIncrementalSideEffects-test.js
<ide> describe('ReactIncrementalSideEffects', () => {
<ide>
<ide> });
<ide>
<add> it('can update child nodes rendering into text nodes', function() {
<add>
<add> function Bar(props) {
<add> return props.text;
<add> }
<add>
<add> function Foo(props) {
<add> return (
<add> <div>
<add> <Bar text={props.text} />
<add> {props.text === 'World' ? [
<add> <Bar key="a" text={props.text} />,
<add> '!',
<add> ] : null}
<add> </div>
<add> );
<add> }
<add>
<add> ReactNoop.render(<Foo text="Hello" />);
<add> ReactNoop.flush();
<add> expect(ReactNoop.root.children).toEqual([
<add> div('Hello'),
<add> ]);
<add>
<add> ReactNoop.render(<Foo text="World" />);
<add> ReactNoop.flush();
<add> expect(ReactNoop.root.children).toEqual([
<add> div('World', 'World', '!'),
<add> ]);
<add>
<add> });
<add>
<ide> it('does not update child nodes if a flush is aborted', () => {
<ide>
<ide> function Bar(props) { | 11 |
Ruby | Ruby | add sensitive_environment function | 66697d429046550904adfa3ac8e689b37c964b6a | <ide><path>Library/Homebrew/extend/ENV.rb
<ide> def with_build_environment
<ide> replace(old_env)
<ide> end
<ide>
<del> def clear_sensitive_environment!
<del> each_key do |key|
<del> next unless /(cookie|key|token|password)/i =~ key
<add> def sensitive?(key)
<add> /(cookie|key|token|password)/i =~ key
<add> end
<ide>
<del> delete key
<del> end
<add> def sensitive_environment
<add> select { |key, _| sensitive?(key) }
<add> end
<add>
<add> def clear_sensitive_environment!
<add> each_key { |key| delete key if sensitive?(key) }
<ide> end
<ide> end
<ide>
<ide><path>Library/Homebrew/system_config.rb
<ide> require "software_spec"
<ide> require "rexml/document"
<ide> require "development_tools"
<add>require "extend/ENV"
<ide>
<ide> class SystemConfig
<ide> class << self
<ide> def dump_verbose_config(f = $stdout)
<ide> next if boring_keys.include?(key)
<ide> next if defaults_hash[key.to_sym]
<ide>
<del> value = "set" if key =~ /(cookie|key|token|password)/i
<add> value = "set" if ENV.sensitive?(key)
<ide> f.puts "#{key}: #{value}"
<ide> end
<ide> end
<ide><path>Library/Homebrew/test/ENV_spec.rb
<ide> expect(subject["MAKEFLAGS"]).to eq("-j4")
<ide> end
<ide>
<add> describe "#sensitive_environment" do
<add> it "list sensitive environment" do
<add> subject["SECRET_TOKEN"] = "password"
<add> expect(subject.sensitive_environment).to include("SECRET_TOKEN")
<add> end
<add> end
<add>
<ide> describe "#clear_sensitive_environment!" do
<ide> it "removes sensitive environment variables" do
<ide> subject["SECRET_TOKEN"] = "password" | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.